text
stringlengths
7
3.69M
var playlist = pls = { DEFAULT_VIDEO_ID: 'QcvjoWOwnn4', list: {}, videoIndexes: [], playedSoFar: [], continuousPlayback: true, playOrResumeCurrentVideo: function() { playr.player.loadVideoById(playr.videoId); playlist.highlightCurrentVideo(); //if (storedTime > 0.0) { // seekToSeconds(storedTime); //} }, highlightCurrentVideo: function() { if (playr.videoId != null) { for (videoId in pls.list) { pls.list[videoId].element.className = 'ListElement'; } if (pls.list[playr.videoId]) { pls.list[playr.videoId].element.className = 'ListElement Playing'; pls.list[playr.videoId].element.scrollIntoView(); } else { var titleElement = getElement('video_title_'+playr.videoId); titleElement.className = 'PreviewTitle Played'; } } }, playVideoId: function(id) { playr.videoId = id; playlist.playOrResumeCurrentVideo(); }, updateVideoOrder: function(videoId) { var startIndex = pls.videoIndexes.indexOf(videoId); startIndex = startIndex > 0 ? startIndex : 0; for (var i = startIndex; i < pls.videoIndexes.length; i++) { var videoId = pls.videoIndexes[i]; pls.list[videoId].index = i+1; pls.setTitleForPlaylistItem(videoId); } }, arrayGetRandom: function(a) { return a[Math.floor(Math.random() * a.length)]; }, arrayDiff: function(outside, inside) { return outside.filter(function(i) {return !(inside.indexOf(i) > -1);}); }, setPlayToRandom: function () { playlist.continuousPlayback = false; playlist.resetPlayOrder(); }, setPlayToContinuous: function() { playlist.continuousPlayback = true; }, playNextContinuous: function() { var currentVideoIndex = pls.videoIndexes.indexOf(playr.videoId); if (currentVideoIndex < (pls.videoIndexes.length - 1)) { pls.playVideoId(pls.videoIndexes[currentVideoIndex + 1]); } }, playNextRandom: function() { if (pls.playedSoFar.length == pls.videoIndexes.length) { pls.resetPlayOrder(); } var randomId = pls.arrayGetRandom(pls.arrayDiff(pls.videoIndexes, pls.playedSoFar)); pls.playedSoFar.push(randomId); pls.playVideoId(randomId); }, playNext: function() { pls = playlist; if (pls.continuousPlayback) { pls.playNextContinuous(); } else { pls.playNextRandom(); } }, removeFromPlaylist: function(videoId) { pls.list[videoId].element.parentNode.removeChild(pls.list[videoId].element); delete(pls.list[videoId]); pls.videoIndexes.splice(pls.videoIndexes.indexOf(videoId), 1); if (pls.videoIndexes.indexOf(videoId) != -1) { pls.playedSoFar.splice(pls.playedSoFar.indexOf(videoId), 1) }; pls.updateVideoOrder(); pls.updateAddressBar('remove'); }, dragSourceElement: null, handleDragStart: function(e) { this.style.opacity = '0.8'; // this / e.target is the source node. playlist.dragSourceElement = this; }, handleDragEnter: function(e) { this.classList.add('over'); }, handleDragOver: function(e) { if (e.preventDefault) { e.preventDefault(); // Necessary. Allows us to drop. } e.dataTransfer.dropEffect = 'move'; return false; }, handleDragLeave: function(e) { this.classList.remove('over'); }, handleDrop: function(e) { if (e.stopPropagation) { e.stopPropagation(); // Stops some browsers from redirecting. } // Don't do anything if dropping the same column we're dragging. if (pls.dragSourceElement != this) { var videoId = this.getElementsByClassName('VideoId')[0].value; var dragSourceVideoId = pls.dragSourceElement.getElementsByClassName('VideoId')[0].value; this.parentNode.insertBefore(pls.dragSourceElement, this); pls.videoIndexes.splice(pls.videoIndexes.indexOf(dragSourceVideoId), 1); pls.videoIndexes.splice(pls.videoIndexes.indexOf(videoId), 0, dragSourceVideoId); pls.updateVideoOrder(dragSourceVideoId); pls.updateAddressBar('remove'); } return false; }, handleDragEnd: function(e) { this.style.opacity = '1.0'; // this / e.target is the source node. this.classList.remove('over'); }, handleDoubleClick: function(e) { this.classList.remove('over'); var clickedVideoId = this.getElementsByClassName('VideoId')[0].value; playlist.playVideoId(clickedVideoId); scrollToTop(); }, handleClick: function(e) { this.classList.toggle('over'); }, getNewVideoNode: function(videoId) { var newItem = document.createElement('div'); newItem.className = 'ListElement'; newItem.draggable = true; newItem.innerHTML = '<span>'+videoId+'</span>\n' + '<input type="hidden" name="videoId" class="VideoId" value="'+videoId+'" />\n' + '<a href="javascript:void(0);" class="RemoveButton" title="Remove from Playlist"><img src="images/btnRemove.png" /></a>\n' + '<a href="javascript:void(0);" class="DragButton" title="Click And Drag to Rearrange the Playlist"><img src="images/btnDrag.png" /></a>'; return newItem; }, getTitleFromSource: function(videoId) { var url = 'https://gdata.youtube.com/feeds/api/videos/'+videoId+'?v=2&alt=json'; var xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", url, false ); xmlHttp.send( null ); var response = xmlHttp.responseText; var videoFunc = new Function('return '+response); return videoFunc().entry.title['$t']; }, setTitleForPlaylistItem: function(id) { var list = playlist.list; if (list[id].title === null) { list[id].title = playlist.getTitleFromSource(id); } list[id].element.getElementsByTagName('span')[0].innerHTML = list[id]['index'] +' - ' + list[id].title; }, setupPlaylistControlsForVideoId: function(videoId) { var item = playlist.list[videoId].element; var removeButton = item.getElementsByClassName('RemoveButton')[0]; var dragButton = item.getElementsByClassName('DragButton')[0]; item.addEventListener('dblclick', playlist.handleDoubleClick, false); item.addEventListener('click', playlist.handleClick, false); item.addEventListener('dragstart', playlist.handleDragStart, false); item.addEventListener('dragenter', playlist.handleDragEnter, false); item.addEventListener('dragover', playlist.handleDragOver, false); item.addEventListener('dragleave', playlist.handleDragLeave, false); item.addEventListener('drop', playlist.handleDrop, false); item.addEventListener('dragend', playlist.handleDragEnd, false); removeButton.setAttribute('onClick', "playlist.removeFromPlaylist('"+videoId+"')"); }, adjustPlaylistSize: function(offset) { getElement('list').style.marginRight = getElement('player').offsetWidth - progressBar.offsetLeft - progressBar.offsetWidth + offset + 'px'; }, getPlaylistQueryString: function(videoIndexes) { var playlistQueryString = '?v='; for (index in videoIndexes) { playlistQueryString += videoIndexes[index]+','; } return playlistQueryString.substr(0, playlistQueryString.length - 1); }, updateAddressBar: function(action) { var leDate = new Date; var playerState = { videoIndexes: playlist.videoIndexes, }; window.history.pushState(playerState, 'playr.me', playlist.getPlaylistQueryString(playlist.videoIndexes)); }, addVideoIds: function(ids) { var retval = false; for (var key in ids) { retval = playlist.addVideoId(ids[key]) || retval; } if (retval === true) { playlist.updateAddressBar('add'); } return retval; }, addVideoId: function(id) { var list = playlist.list; var videoIndexes = playlist.videoIndexes; var retval = false; if (list[id] === undefined) { var newItem = playlist.getNewVideoNode(id); getElement('list').appendChild(newItem); if (videoIndexes.indexOf(id) == -1) { list[id] = { 'id': id, 'element': newItem, 'title': null }; videoIndexes.push(id); list[id]['index'] = videoIndexes.length; playlist.setupPlaylistControlsForVideoId(id); playlist.setTitleForPlaylistItem(id); } if (videoIndexes.length == 1) { playlist.playVideoId(id); scrollToTop(); } playlist.updateAddressBar('add'); retval = true; } return retval; }, getVideoIdsFromAddress: function(address) { var match = address.match(/([?\&]v\=)([\w-,]+)/gi); var videoIds = null; if (match != null) { videoIds = match[0].substr(3).split(','); } return videoIds; }, getVideoIdsFromAddressBar: function() { return playlist.getVideoIdsFromAddress(window.location.toString()); }, resetPlayOrder: function() { playlist.playedSoFar = [playr.videoId]; }, initialize: function() { // Add first item to playlist // and play it. var videoIds = pls.getVideoIdsFromAddressBar(); if (videoIds) { pls.addVideoIds(videoIds); } else { // Default video ID pls.addVideoId(pls.DEFAULT_VIDEO_ID); } }, handleStatusChange: function(e) { switch (playr.status) { case 'YOUTUBE PLUGIN LOADED': pls.initialize(); break; case 'VIDEO HAS ENDED': pls.playNext(); break; case 'PLAYBACK SET TO RANDOM': pls.setPlayToRandom(); break; case 'PLAYBACK SET TO CONTINUOUS': pls.setPlayToContinuous(); break; } } }; document.addEventListener("playrStatusChanged", playlist.handleStatusChange);
import currency from '../currency' import { fetchBtcRequest, fetchEthRequest, fetchBtcSuccess, fetchBtcFailure, fetchEthFailure, fetchEthSuccess, selectOffset } from '../../actions/currency' describe('Сurrency reducer', () => { describe('action fetchBtcRequest', () => { it('изменяет isBtcLoading на true', () => { const next = currency({ isBtcLoading: false }, fetchBtcRequest()) expect(next.isBtcLoading).toBeTruthy() }) }) describe('action fetchEthRequest', () => { it('изменяет isEthLoading на true', () => { const next = currency({ isEthLoading: false }, fetchEthRequest()) expect(next.isEthLoading).toBeTruthy() }) }) describe('action fetchBtcSuccess', () => { const payload = [1, 2, 3] it('изменяет isBtcLoading на false', () => { const next = currency({ isBtcLoading: true }, fetchBtcSuccess(payload)) expect(next.isBtcLoading).toBeFalsy() }) it('заполняет данными поле btc', () => { const next = currency({ btc: [] }, fetchBtcSuccess(payload)) expect(next.btc).toEqual(payload) }) }) describe('action fetchEthSuccess', () => { const payload = [1, 2, 3] it('изменяет isEthLoading на false', () => { const next = currency({ isEthLoading: true }, fetchEthSuccess(payload)) expect(next.isEthLoading).toBeFalsy() }) it('заполняет данными поле eth', () => { const next = currency({ eth: [] }, fetchEthSuccess(payload)) expect(next.eth).toEqual(payload) }) }) describe('action fetchBtcFailure', () => { it('изменяет isBtcLoading на false', () => { const next = currency({ isBtcLoading: true }, fetchBtcFailure()) expect(next.isBtcLoading).toBeFalsy() }) }) describe('action fetchEthFailure', () => { it('изменяет isEthLoading на false', () => { const next = currency({ isEthLoading: true }, fetchEthFailure()) expect(next.isEthLoading).toBeFalsy() }) }) describe('action selectOffset', () => { const payload = '1d' it('изменяет offset переданным значением', () => { const next = currency({ offset: '4h' }, selectOffset(payload)) expect(next.offset).toEqual(payload) }) }) })
// Higher Order Functions //We call functions that accept functions as parameters "higher order functions." //This is actually something special about JavaScript. Not all languages //allow us to pass other functions as parameters to functions! // sendMessage is a higher order function as it accepts a parameter called fn. // How do we know fn is a function? We can see the fn parameter is being // invoked with () function sendMessage(message, fn){ return fn(message); } sendMessage("Hello World", console.log); // Hello World sendMessage("Hello World", alert); // Hello World is alerted sendMessage("What is your name?", prompt); // value from prompt is returned sendMessage("Do you like JavaScript?", confirm); // true or false is returned // It is important to remember the difference between referencing a function // here, and invoking a function. In the following line of code, // sendMessage("Hello World", console.log);, console.log is a function that // is being referenced but not invoked. //When you pass a function in to a higher order function, you must always // pass in the function name, not an invocation of the function. //Anonymous Functions As Parameters sendMessage("Hello World", function(message){ // message refers to the string "Hello World" console.log(message + " from a callback function!"); }); // Hello World from a callback function! //The previous example is equivalent to doing the following: var myFunction = function(message){ // message refers to the string "Hello World" console.log(message + " from a callback function!"); }; sendMessage("Hello World", myFunction); // In our previous examples we would have had to do a lot of work to get // the same code. Higher order functions allow us to avoid writing seperate functions like this function sendMessageWithConsoleLog(message){ return console.log(message); } function sendMessageWithAlert(message){ return alert(message); } function promptWithMessage(message){ return prompt(message); } function confirmWithMessage(message){ return confirm(message); } function sendMessageWithFromCallback(message){ return console.log(message + " from a callback function!"); } // /////////////////////////// /////////////////////////// ///////////////////////// //We call a function that is passed as an argument to a higher order function a callback // In our sendMessage example, sendMessage is the higher order function and fn is the callback function. function add(a,b){ return a+b; } function subtract(a,b){ return a-b; } function math(a,b,callback){ return callback(a,b); } math(1,4,add); // returns 5 math(5,5,subtract); // returns 0 //practice function each(arr, func){ for(let i = 0; i < arr.length; i++){ func(arr[i]); } } each([1,2,3,4], function(val){ console.log(val); }); // Here is what should be output if you wrote the function correctly // 1 // 2 // 3 // 4 each([1,2,3,4], function(val){ console.log(val*2); }); // Here is what should be output if you wrote the function correctly // 2 // 4 // 6 // 8 //Exercises function map(arr, fn){ let result = []; for(let i = 0; i < arr.length; i++){ result.push(fn(arr[i])); } return result; } map([1,2,3,4], function(val){ return val * 2; }); // [2,4,6,8] ///////////////////////////////////////////////////////////////////////////////// function reject(arr, fn){ let result = []; for(let i = 0; i < arr.length; i++){ if(!fn(arr[i])){ result.push(arr[i]); } } return result; } reject([1,2,3,4], function(val){ return val > 2; }); // [1,2] reject([2,3,4,5], function(val){ return val % 2 === 0; }); // [3,5] ///////////////////////////////////////////////////////////////////////////////// //
/** * png.js - The catch-all PNG optimizer task * * Copyright (c) 2012 DIY Co * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at: * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. * * @author Zachary Bruggeman <zbruggeman@me.com> */ var _ = require('underscore'), exec = require('child_process').exec, colorize = require('../colorize'), async = require('async'); module.exports = function(roto) { roto.defineTask('png', function(callback, options, target, globalOptions) { var files; var binary; var queue; var args = []; var finalArgs; _.defaults(options, { compressor : 'none', binaries : {'optipng' : './bin/optipng', 'pngquant' : './bin/pngquant', 'pngcrush' : './bin/pngcrush'}, customArgs : '', workers : 1 }); // find files var files = roto.findFiles(options.files, options.ignore); if (!files.length) { roto.error(colorize('Error: ', 'red') + 'No valid files were provided. \n'); return callback(false); }; // get compressor if (options.compressor === 'none') { roto.error(colorize('Error: ', 'red') + 'You need to specify a compressor! \n'); return callback(false); } var binary = options.binaries[options.compressor]; // push and format args args.push(options.customArgs); if (options.compressor === 'pngcrush') { finalArgs = ' -ow ' + args.join(' '); } else if (options.compressor === 'optipng' || options.compressor === 'pngquant') { finalArgs = args.join(' ') + ' -- '; }; // queue files (thanks Brian!) var queue = async.queue(function(filename, callback) { var proc = exec(binary + finalArgs + filename, function(err, stdout, stderr) { if (err) { roto.error(colorize('Error: ', 'red') + err + '\n'); callback(); } else { roto.notice(stderr + '\n'); callback(); }; }); }, options.workers); queue.drain = callback(); queue.push(files); }); };
const MatrixBase = [1, 0, 0, 1, 0, 0] // ctx.transform.apply(ctx,Matrix) export default class Matrix { constructor() { let x if (arguments.length > 0) { x = Array.prototype.slice.call(arguments) } else { x = MatrixBase } for (const p in x) { this[p] = x[p] } this.length = x.length } translate(x, y) { this[4] += this[0] * x + this[2] * y this[5] += this[1] * x + this[3] * y return this } rotate(r) { const cos = Math.cos(r), sin = Math.sin(r), mx = this, a = mx[0] * cos + mx[2] * sin, b = mx[1] * cos + mx[3] * sin, c = -mx[0] * sin + mx[2] * cos, d = -mx[1] * sin + mx[3] * cos this[0] = a this[1] = b this[2] = c this[3] = d return this } skew(x, y) { const tanX = Math.tan(x), tanY = Math.tan(y), mx0 = this[0], mx1 = this[1] this[0] += tanY * this[2] this[1] += tanY * this[3] this[2] += tanX * mx0 this[3] += tanX * mx1 return this } scale(x, y) { y = x this[0] *= x this[1] *= x this[2] *= y this[3] *= y return this } }
import FileSaver from 'file-saver' import XLSX from 'xlsx' export function downloadExcel(dataArr, nameArr, excelName) { // dataArr二维数组,存放导出数据,不可为空 // nameArr一维数组, 允许空数组(默认sheet) // excelName, 导出excel文件名,不允许为空 const defaultCellStyle = { font: { name: '', sz: 11, color: 'FF00FF88' }, fill: { fgColor: { rgb: 'FFFFAA00' } } } const wopts = { bookType: 'xlsx', bookSST: false, type: 'binary', defaultCellStyle: defaultCellStyle, showGridLines: false } const wb = { SheetNames: [], Sheets: {}, Props: {} } for (let i = 0; i < dataArr.length; i++) { wb.SheetNames[i] = nameArr[i] ? nameArr[i] : 'Sheet' + (i + 1) let data = dataArr[i] wb.Sheets[wb.SheetNames[i]] = XLSX.utils.json_to_sheet(data) } let tmpDown = new Blob([s2ab(XLSX.write(wb, wopts))], { type: 'application/octet-stream' }) FileSaver.saveAs(tmpDown, excelName + '.xlsx') } export function s2ab(s) { if (typeof ArrayBuffer !== 'undefined') { let buf = new ArrayBuffer(s.length) let view = new Uint8Array(buf) for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF return buf } else { let buf = new Array(s.length) for (let i = 0; i !== s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF return buf } }
import fetch from 'node-fetch'; /** * Gets the horoscope for a given sign * @method getHoroscope * @param {String} sign the sign of question * @param {String} time yesterday, today, tomorrow * @return {Promise} * date: body.date, * horoscope: body.horoscope, * sunsign: body.sunsign, */ export const getHoroscope = (sign, period = 'today') => ( fetch(`http://horoscope-api.herokuapp.com/horoscope/${period}/${sign}`) .then(res => res.json()) .then((res) => res.horoscope) );
import React from "react"; import { BrowserRouter as Router, Route, Link, IndexRoute, Redirect } from "react-router-dom"; import { HEADER_LINKS } from "./common.props"; import Utility from "../lib/util"; export default class PageBody extends React.Component { constructor(props) { super(props); this.state = {}; this.getRoutes = this.getRoutes.bind(this); } getRoutes() { let routeList = HEADER_LINKS.filter(headerLinkObj => headerLinkObj.isRouteLink).map(headerLinkObj => { let redirectObj = {}; if(headerLinkObj.redirect) { redirectObj.pathname = headerLinkObj.redirect } return ( headerLinkObj.redirect ? <Route exact path={headerLinkObj.address} render={props => <Redirect to={redirectObj}/>} key={Utility.generateRandomString(5)}/> : <Route exact path={headerLinkObj.address} component={headerLinkObj.handlerComponent} key={Utility.generateRandomString(5)}/> ); }); return routeList; } render() { return ( <div className=""> {this.getRoutes()} </div> ); } }
/// <reference path="jquery-3.3.1.js" /> $(document).ready(function () { compression.Init(); }); var compression = { before: 0, after:0, Init: function () { $('.comp').click(function () { compression.compressInput(); }); $('.decomp').click(function () { compression.decompressInput(); }); }, compressInput: function () { var $compressionTextArea = $('textarea.compress'); var $decompressionTextArea = $('textarea.decompress'); var textValue = $compressionTextArea.val(); if (textValue !=="") { compressionApi.compressText(textValue).then(function (response) { $compressionTextArea.val(''); $decompressionTextArea.val(response.compressedFile); compression.before = response.beforeCompression; compression.after = response.afterCompression; var compressedValuePercent = ((response.afterCompression / response.beforeCompression) * 100).toFixed(1); var compressionPercent = (100 - compressedValuePercent).toFixed(1); compressionPercent += "%"; var percent = compressedValuePercent.toString(); percent += "%"; $('div.bar1').text(response.beforeCompression); $('div.bar2').text(response.afterCompression); $('div.bar3').text(compressionPercent); $('.bar2').append('<style>.bar2::after{ max-width:' + percent +' }</style>'); $('.bar3').append('<style>.bar3::after{ max-width:' + compressionPercent + ' }</style>'); $('.graph-cont').removeClass('hidden'); }) .fail(function myfunction() { }); } }, decompressInput: function () { var $compressionTextArea = $('textarea.compress'); var $decompressionTextArea = $('textarea.decompress'); var compressedValue = $decompressionTextArea.val(); if (compressedValue !== "") { compressionApi.decompressText(compressedValue).then(function (response) { $decompressionTextArea.val(''); $compressionTextArea.val(response.decodedString); }) .fail(function myfunction() { }); } }, }; var compressionApi = { compressText: function (text) { return $.ajax({ type: "get", url: '../api/compression/compress', data: { 'text': text } }); }, decompressText: function (compressedValue) { return $.ajax({ type: "get", url: '../api/compression/decompress', data: { 'text': compressedValue } }); } };
var count_click_Funnel = 0; (function(){ var DEFAULT_HEIGHT = 400, DEFAULT_WIDTH = 600, DEFAULT_BOTTOM_PERCENT = 1/3; window.FunnelChart = function(options) { /* Parameters: data: Array containing arrays of categories and engagement in order from greatest expected funnel engagement to lowest. I.e. Button loads -> Short link hits Ex: [['Button Loads', 1500], ['Button Clicks', 300], ['Subscribers', 150], ['Shortlink Hits', 100]] width & height: Optional parameters for width & height of chart in pixels, otherwise default width/height are used bottomPct: Optional parameter that specifies the percent of the total width the bottom of the trapezoid is This is used to calculate the slope, so the chart's view can be changed by changing this value */ this.data = options.data; this.totalEngagement = 0; for(var i = 0; i < this.data.length; i++){ this.totalEngagement += this.data[i][1]; } this.width = typeof options.width !== 'undefined' ? options.width : DEFAULT_WIDTH; this.height = typeof options.height !== 'undefined' ? options.height : DEFAULT_HEIGHT; var bottomPct = typeof options.bottomPct !== 'undefined' ? options.bottomPct : DEFAULT_BOTTOM_PERCENT; this._slope = 2*this.height/(this.width - bottomPct*this.width); this._totalArea = (this.width+bottomPct*this.width)*this.height/2; }; //Lấy text hiển thị trên chart window.FunnelChart.prototype._getLabel = function(ind){ /* Get label of a category at index 'ind' in this.data */ return this.data[ind][0]; }; window.FunnelChart.prototype._getEngagementCount = function(ind){ /* Get engagement value of a category at index 'ind' in this.data */ return this.data[ind][1]; }; window.FunnelChart.prototype._getColor = function(ind){ /* Get engagement value of a category at index 'ind' in this.data */ return this.data[ind][2]; // return colorPie(ind); }; window.FunnelChart.prototype._createPaths = function(){ /* Returns an array of points that can be passed into d3.svg.line to create a path for the funnel */ trapezoids = []; var height = 30, slope = 13; function findNextPoints(chart, prevLeftX, prevRightX, prevHeight, dataInd){ // reached end of funnel if(dataInd >= chart.data.length) return; // math to calculate coordinates of the next base //area = chart.data[dataInd][1]*chart._totalArea/chart.totalEngagement; //prevBaseLength = prevRightX - prevLeftX; //nextBaseLength = Math.sqrt((chart._slope * prevBaseLength * prevBaseLength - 4 * area)/chart._slope); //nextLeftX = (prevBaseLength - nextBaseLength)/2 + prevLeftX; nextLeftX = slope + prevLeftX; //nextRightX = prevRightX - (prevBaseLength-nextBaseLength)/2; nextRightX = prevRightX - slope; //nextHeight = chart._slope * (prevBaseLength-nextBaseLength)/2 + prevHeight; nextHeight = height + prevHeight; //console.log("nextRightX:", nextRightX); points = [[nextRightX, nextHeight]]; points.push([prevRightX, prevHeight]); points.push([prevLeftX, prevHeight]); points.push([nextLeftX, nextHeight]); points.push([nextRightX, nextHeight]); trapezoids.push(points); findNextPoints(chart, nextLeftX, nextRightX, nextHeight, dataInd+1); } findNextPoints(this, 0, this.width, 0, 0); return trapezoids; }; window.FunnelChart.prototype.draw = function(elem, speed){ var DEFAULT_SPEED = 2.5; speed = typeof speed !== 'undefined' ? speed : DEFAULT_SPEED; var funnelSvg = d3.select(elem).append('svg') .attr('width', this.width) .attr('height', this.height) .append('g'); // filters go in defs element var defs = funnelSvg.append("defs"); var filter = defs.append("filter") .attr("id", "drop-shadow") .attr("width", "200%") .attr("height", "200%"); // SourceAlpha refers to opacity of graphic that this filter will be applied to // convolve that with a Gaussian with standard deviation 3 and store result // in blur filter.append("feGaussianBlur") .attr("in", "SourceAlpha") .attr("stdDeviation", 5) .attr("result", "blur"); // translate output of Gaussian blur to the right and downwards with 2px // store result in offsetBlur filter.append("feOffset") .attr("in", "blur") .attr("dx", 3) .attr("dy", 3) .attr("result", "offsetBlur"); // overlay original SourceGraphic over translated blurred opacity by using // feMerge filter. Order of specifying inputs is important! var feMerge = filter.append("feMerge"); feMerge.append("feMergeNode") .attr("in", "offsetBlur") feMerge.append("feMergeNode") .attr("in", "SourceGraphic"); // Creates the correct d3 line for the funnel var funnelPath = d3.svg.line() .x(function(d) { return d[0]; }) .y(function(d) { return d[1]; }); // Automatically generates colors for each trapezoid in funnel //var colorScale = d3.scale.category20(); var paths = this._createPaths(); function drawTrapezoids(funnel, i){ //console.log("ntt", funnel.totalEngagement); var g = funnelSvg.append("g") .attr("class", "funnel") .attr("cursor", "pointer") .on("mouseover", function(d){ d3.select(this).select("path") .transition() .duration(100) .style("filter", "url(#drop-shadow)") .attr("transform", "translate(-3,-3)") .attr("stroke-width", 3); //Lấy thông tin phân pie khi click vào tooktipFunnel.transition() .duration(100) .style("opacity", 0.9); tooktipFunnel.html("<strong>Trạng thái: </strong>" + d3.select(this).select("#label").attr("value") + "</br> <strong>Số lượng: </strong>" + d3.select(this).select("#value").attr("value")) .style("left", (d3.event.pageX)- 10 + "px") .style("top", (d3.event.pageY) - 40 + "px"); }) .on("mouseout", function(d) { d3.select(this).select("path") .transition() .duration(100) .style("filter", null) .attr("stroke-width", 1) .attr("transform", null); tooktipFunnel.transition() .duration(100) .style("opacity", 0); }); var trapezoid = g.append('path') .attr('d', function(d){ return funnelPath( [paths[i][0], paths[i][1], paths[i][2], paths[i][2], paths[i][1], paths[i][2]]); }) .attr('fill', '#fff') .attr('stroke', '#fff'); nextHeight = paths[i][[paths[i].length]-1]; //var totalLength = trapezoid.node().getTotalLength(); var transition = trapezoid.transition() //.duration(totalLength/speed) .ease("linear") .attr("d", function(d){return funnelPath(paths[i]);}) //.attr("fill", function(d){return colorScale(i);}); .attr("fill", function(d){return funnel._getColor(i) ;}); g.append('text') //.text(funnel._getLabel(i) + ': ' + funnel._getEngagementCount(i)) .text(Math.round(funnel._getEngagementCount(i)/funnel.totalEngagement*100*10)/10 + "%") .attr("x", function(d){ return funnel.width/2; }) .attr("y", function(d){ return (paths[i][0][1] + paths[i][1][1])/2;}) // Average height of bases .attr("text-anchor", "middle") .attr("dominant-baseline", "middle") .attr("font-size", "12px") .attr("fill", "#fff"); if(i < paths.length - 1){ transition.each('end', function(){ drawTrapezoids(funnel, i+1); }); } g.append("p").attr("id", "label").attr("value", funnel._getLabel(i)); g.append("p").attr("id", "value").attr("value", funnel._getEngagementCount(i)) } drawTrapezoids(this, 0); }; })();
const enter = () => { document.getElementById("tag-line").classList.add('hidden'); document.getElementById("enter-r").classList.add('hidden'); document.getElementById("enter-l").classList.add('hidden'); document.getElementById("app").classList.remove('centered'); document.getElementById("ledger").classList.remove('hidden'); document.getElementById("nav").classList.remove('hidden'); document.getElementById("sub-total").classList.remove('hidden'); }; const exit = () => { document.getElementById("tag-line").classList.remove('hidden'); document.getElementById("app").classList.add('centered'); document.getElementById("ledger").classList.add('hidden'); document.getElementById("nav").classList.add('hidden'); document.getElementById("sub-total").classList.add('hidden'); };
var session = require('express-session'); var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var compression = require('compression'); var routes = require('./routes/index'); var login = require('./routes/login'); var navbarData = require('./routes/navBarData'); var dashboard = require('./routes/dashboard'); var getData = require('./routes/getRedisData'); var getKeyValue = require('./routes/getKeyValue'); var saveKeyValue = require('./routes/saveKeyValue'); var exportData = require('./routes/exportData'); var exportDataFile = require('./routes/exportDataFile'); var deleteKey = require('./routes/deleteKey'); var executeCommand = require('./routes/executeCommands'); var commandExecute = require('./routes/commandExecute'); var logout = require('./routes/logout'); var importData = require('./routes/importData'); var fileUpload = require('express-fileupload'); var app = express(); app.use(fileUpload()); app.all('*', function(req, res, next) { res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate'); res.header('Expires', '-1'); res.header('Pragma', 'no-cache'); next(); }); app.use(session({secret: 'Shubham_123'})); app.use(compression()); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', routes); app.use('/login', login); app.use('/dashboard',dashboard); app.use('/getData',getData); app.use('/getKeyValue',getKeyValue); app.use('/saveKeyValue',saveKeyValue); app.use('/exportData',exportData); app.use('/deleteKey',deleteKey); app.use('/executeCommand',executeCommand); app.use('/executeCommand',commandExecute); app.use('/getNavBarData',navbarData); app.use('/exportDataFile',exportDataFile); app.use('/importData',importData); app.use('/logout',logout); // catch 404 and forward to error handler app.use(function(req, res, next) { console.log('here'); res.sendFile(path.join(__dirname,'public','404.html')); /*var err = new Error('Not Found'); err.status = 404; next(err);*/ }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
/*** * module dependencies */ const should = require('should'), sinon = require('sinon'), Package = require('./index'); let _create, _resolve, _access, _token = { id: "token-test-123", client_id: "client-test-123", owner_id: "owner-test-123", scopes: [ "scope-a", "scope-b" ], access_id: "access-test-123" }, _configCreate = { secret: "secret-test-1234", expiry: 10 }, _configResolve = { secret: "secret-test-1234", find: function (tokenId, done) { done(null, tokenId === _token.id ? _token : null); } }, _payload = { tokenId: "token-test-123", accessId: "access-test-123" }, _bearerTokenRegex = /^([A-Za-z0-9\-._~+\/]*)=?$/; describe("Package.Create", function () { it("should be a function", function () { should.exist(Package.Create); Package.Create.should.be.a.Function(); }); describe("init", function () { it("should throw an error if no secret was provided", function () { (function () { Package.Create({ secret: "" }); }).should.throw(); }); it("should throw an error if expiry <= 0", function () { (function () { Package.Create({ secret: "secret-test-123", expiry: 0 }); }).should.throw(); }); it("should initialize successfully", function () { _create = Package.Create(_configCreate); }); it("should return a function", function () { should.exist(_create); _create.should.be.a.Function(); }); }); describe("generator", function () { it("should be able to generate access object", function (done) { _create(_payload, function (err, access) { if (err) return done(err); should.exist(access); access.should.be.an.Object(); _access = access; done(); }); }); it("access object should have a token string", function () { _access.token.should.be.a.String(); }); it("access object should have token confronting to Bearer specs", function () { _access.token.should.match(_bearerTokenRegex); }); it("access object should have the expected expiry", function () { should.equal(_access.expiry, _configCreate.expiry); }); it("access object should have type field with Bearer value", function () { should.equal(_access.type, "Bearer"); }); }); }); describe("Package.Resolve", function () { it("should be a function", function () { should.exist(Package.Resolve); Package.Resolve.should.be.a.Function(); }); describe("init", function () { it("should throw an error if no secret was provided", function () { (function () { // noinspection JSCheckFunctionSignatures Package.Resolve(); }).should.throw(); }); it("should throw an error if no find was provided", function () { (function () { // noinspection JSCheckFunctionSignatures Package.Resolve({ secret: _configResolve.secret }); }).should.throw(); }); it("should throw an error if find is not a function", function () { (function () { // noinspection JSCheckFunctionSignatures Package.Resolve({ secret: _configResolve.secret, find: "find" }); }).should.throw(); }); it("should throw an error if realm is not a string value", function () { (function () { // noinspection JSCheckFunctionSignatures Package.Resolve({ secret: _configCreate.secret, find: function () { }, realm: 1234 }); }).should.throw(); }); it("should initialize successfully", function () { _resolve = Package.Resolve(_configResolve); }); it("should return a function", function () { should.exist(_resolve); _resolve.should.be.a.Function(); }); }); describe("resolver", function () { let req, res, callback; beforeEach(function () { req = { _headers: {}, get: function (header) { return this._headers[header]; } }; res = { _headers: {}, _status: 0, set: function (header, value) { this._headers[header] = value; }, status: function (status) { this._status = status; }, end: function () { } }; callback = sinon.fake(); }); it("should end request with status 401 if missing Authorization header", function () { _resolve(req, res, callback); should(callback.notCalled). be. true(); should.equal(res._status, 401); }); it("should end request with status 400 and error code invalid_request if Authorization header is malformed - Missing Bearer", function () { req._headers.Authorization = "token-12345"; _resolve(req, res, callback); should(callback.notCalled). be. true(); should.equal(res._status, 400); res._headers["WWW-Authenticate"].should.match(/error="invalid_request"/); }); it("should end request with status 400 and error code invalid_request if Authorization header is malformed - Missing token", function () { req._headers.Authorization = "Bearer"; _resolve(req, res, callback); should(callback.notCalled). be. true(); should.equal(res._status, 400); res._headers["WWW-Authenticate"].should.match(/error="invalid_request"/); }); it("should end request with status 401 and error code invalid_token if provided Authorization Bearer token is malformed", function () { req._headers.Authorization = "Bearer !$@32&%"; _resolve(req, res, callback); should(callback.notCalled). be. true(); should.equal(res._status, 401); res._headers["WWW-Authenticate"].should.match(/error="invalid_token"/); }); it("should call find with tokenId on valid Authorization Bearer token", function () { const spy = sinon.spy(_configResolve, "find"); req._headers.Authorization = "Bearer " + _access.token; _resolve(req, res, callback); should(spy.withArgs(_token.id).calledOnce). be. true(); }); it("should end request with status 401 and error code invalid_token if access token was expired", function () { // update the access time stamp on token _token.access_expires_on = Date.now() - 1; req._headers.Authorization = "Bearer " + _access.token; _resolve(req, res, callback); should(callback.notCalled). be. true(); should.equal(res._status, 401); res._headers["WWW-Authenticate"].should.match(/error="invalid_token"/); // reset expiry _token.access_expires_on = undefined; }); it("should conclude to next on valid access token", function (done) { req._headers.Authorization = "Bearer " + _access.token; _resolve(req, res, done); }); it("should append access information to req", function (done) { req._headers.Authorization = "Bearer " + _access.token; _resolve(req, res, function (err) { if (err) return done(err); const access = req.oauth_access; should.equal(access.clientId, _token.client_id); should.equal(access.ownerId, _token.owner_id); should.equal(access.scopes, _token.scopes); should.equal(access.token, _access.token); done(); }); }); describe("compatibility with gateway", function () { beforeEach(function () { req._headers.Authorization = "Bearer " + _access.token; }); it("should end request with status 403 if required scope was not found", function () { req.oauth_access_key = "scope-c"; _resolve(req, res, callback); should(callback.notCalled). be. true(); should.equal(res._status, 403); res._headers["WWW-Authenticate"].should.match(/error="insufficient_scope"/); }); it("should conclude to next on valid access token with required scopes", function (done) { req.oauth_access_key = "scope-a"; _resolve(req, res, done); }); }); }); });
'use strict'; const tableName = 'logs'; module.exports = { up: (queryInterface, dataTypes) => queryInterface.createTable(tableName, { id: { type: dataTypes.STRING, defaultValue: dataTypes.UUIDV4, allowNull: false, primaryKey: true }, session_id: { type: dataTypes.STRING(255), allowNull: false }, coordinate: { type: dataTypes.GEOMETRY('POINT'), allowNull: false }, status: { type: dataTypes.INTEGER, defaultValue: 20, allowNull: false }, created_at: { type: dataTypes.DATE, allowNull: true }, updated_at: { type: dataTypes.DATE, allowNull: true }, deleted_at: { type: dataTypes.DATE, allowNull: true } }), down: (queryInterface, Sequelize) => queryInterface.dropTable(tableName) };
/** * Created by Administrator on 2016/8/22. */ Ext.define('Overrides.Template', { override: 'Ext.Template', /** * @private * Do not create the substitution closure on every apply call */ evaluate: function(values) { var me = this, useFormat = !me.disableFormats, fm = Ext.util.Format, tpl = me; function fn(match, index, name, formatFn, args) { // Calculate the correct name extracted from the {} // Certain browser pass unmatched parameters as undefined, some as an empty string. if (name == null || name === '') { name = index; } if (formatFn && useFormat) { if (args) { args = [values[name]].concat(Ext.functionFactory('return ['+ args +'];')()); } else { args = [values[name]]; } // Caller used '{0:this.bold}'. Create a call to tpl member function if (formatFn.substr(0, 5) === "this.") { return tpl[formatFn.substr(5)].apply(tpl, args); } // Caller used '{0:number("0.00")}'. Create a call to Ext.util.Format function else if (fm[formatFn]) { return fm[formatFn].apply(fm, args); } // Caller used '{0:someRandomText}'. We must return it unchanged else { return match; } } else { // return values[name] !== undefined ? values[name] : ""; //start custom by jonnyLee return values[name] !== (undefined||null) ? values[name] : ""; //end custom by jonnyLee } } return me.html.replace(me.tokenRe, fn); } });
import React, { Component } from 'react'; import { fire, base } from './fire'; import firebase from 'firebase' import firestore from 'firebase'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; import Feed from './components/Feed'; import Settings from './components/Settings'; import PropsRoute from './components/PropsRoute'; const routes = [ { path: "/", exact: true, main: Feed, link_name: "Feed" }, { path: "/settings", main: Settings, link_name: "Settings" } ]; // const TwitterUserContext = React.createContext(null); class App extends Component { constructor(props) { super(props); this.state = { // firebase_user: null, twitterUser: null, loading: true }; // <- set up react state } componentWillMount(){ } componentDidMount(){ let component = this firebase.auth().onAuthStateChanged(user => { if (user) { let uid = user.providerData[0].uid; base.bindDoc(`twitter_users/${uid}`, { context: component, state: "twitterUser", then() { // component.formatUserStructure() component.setState({ // firebase_user: user, loading: false }) }, onFailure(err) { } }); } else { this.setState({loading: false}) } }); } login = () => { let provider = new firebase.auth.TwitterAuthProvider(); firebase.auth().signInWithPopup(provider).then(result => { let user = result.user let username = result.additionalUserInfo.username let twitterUid = user.providerData[0].uid let token = result.credential.accessToken let secret = result.credential.secret // possibly set display name to username and index twitter_users by handle // user.updateProfile({ displayName: username }) let update_attrs = { uid: twitterUid, username: username, accessToken: result.credential.accessToken, secret: result.credential.secret, } base.updateDoc(`twitter_users/${twitterUid}`, update_attrs).catch(e => { base.addToCollection( 'twitter_users', {...update_attrs, friendIds: [twitterUid], }, twitterUid ) }) }) } logout = async () => { this.setState({loading: true}) await firebase.auth().signOut() this.setState({loading: false}) } render() { if (!crypto.subtle) { return <h2>Unsupported Browser: needs <a href="https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/">crypto.subtle</a></h2> } if (this.state.loading) { return <h2>Loading...</h2> } let user = firebase.auth().currentUser if (!user || !this.state.twitterUser) { return ( <div> <h2>notloggedin</h2> <button onClick={this.login}>Login</button> </div> ) } return ( <Router> {/*<TwitterUserContext.Provider twitterUser={this.state.twitterUser}>*/} <div> <p>Signed in as {user.displayName}. <button onClick={this.logout}>Logout</button></p> <ul> {routes.map((route, index) => ( <li key={index}><Link to={route.path}>{route.link_name}</Link></li> ))} </ul> <hr /> <div> {routes.map((route, index) => ( <PropsRoute key={index} path={route.path} exact={route.exact} // render={React.createElement(route.main, {twitterUser: this.state.twitterUser})} component={route.main} twitterUser={this.state.twitterUser} /> ))} </div> </div> {/*</TwitterUserContext.Provider>*/} </Router> ); } } export default App;
// Configuración de Firebase const firebaseConfig = { apiKey: "AIzaSyC_yF5Y90-GsKfO7fZWmS6OQFv5Gj7B8a8", authDomain: "cmyk-orange.firebaseapp.com", projectId: "cmyk-orange", storageBucket: "cmyk-orange.appspot.com", messagingSenderId: "179241068454", appId: "1:179241068454:web:5e1763ec4bbee8ef5d5167", }; firebase.initializeApp(firebaseConfig); const db = firebase.firestore(); const auth = firebase.auth(); /************ Boton de atrás ************/ // const goBack = document.querySelector("#goBack"); // goBack.addEventListener("click", (e) => { // Location.assign(); // }); /***** boton de Contactar *****/ // const formBtn = document.querySelector("#formBtn"); // formBtn.addEventListener("submit", (e) => { // e.preventDefault(); // db.collection("project").doc("OPGE5WRuwZhNMiSGQoCw").set(); // }); // db.collection("projects").doc("OPGE5WRuwZhNMiSGQoCw").set({ // name: "Proyecto 45", // userId: "123", // });
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const SeasonSchema = new Schema({ userId: { type: Schema.Types.ObjectId, ref: 'users', required: true }, roleType: { type: Number, required: true }, startingSR: { type: Number, required: true }, SR: { type: Number, required: true }, mainHeroes: { type: Array, required: true }, games: [{ type: Schema.Types.ObjectId, ref: 'games' }], }); function removeGames(games) { if (games.length) { games.map(game => { game.remove(err => { if (err) { console.log(err); } else { console.log(`game ${game} removed`) } }) }) } } const Season = mongoose.model('seasons', SeasonSchema); SeasonSchema.pre('remove', function (next, docs) { Game.find({ seasonId: this._id }).then(games => { removeGames(games); }) next() }) module.exports = Season;
import React, { Component } from 'react'; import { AppRegistry, Platform, StyleSheet, Text, Dimensions, PermissionsAndroid, View, FlatList, TouchableHighlight, TouchableOpacity, Image, Alert, Button, AsyncStorage, NativeAppEventEmitter, NativeEventEmitter, NativeModules, ListView, ScrollView} from 'react-native'; import prompt from 'react-native-prompt-android'; import firebase from 'react-native-firebase'; import {connect} from "react-redux" import { NavigationActions } from "react-navigation"; import BleManager from 'react-native-ble-manager'; import '../../shim' import $ from 'buffer'; var headIcon = require('../resources/device_icons/headIcon.png') var bandIcon = require('../resources/device_icons/bandIcon.png') var wheelIcon = require('../resources/device_icons/wheelIcon.png') var armIcon = require('../resources/device_icons/armIcon.png') var deleteIcon = require('../resources/device_icons/deleteIcon.png') const deviceImages = [headIcon, bandIcon, wheelIcon, armIcon]; const BleManagerModule = NativeModules.BleManager; const bleManagerEmitter = new NativeEventEmitter(BleManagerModule); const window = Dimensions.get('window'); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); var accels = [0.0,0.0,0.0]; var gyros = [0.0,0.0,0.0]; var temp = 0.0; var name = "name"; var led = 0; var count = 0 var curItem; var savedAccels = []; var savedAccelsx = []; var savedGyros = []; var savedTemps = []; export default class AddDeviceScreen extends Component { constructor(){ super() this.state = { selectedColor: '#06a7e2', type: "", loading: false, user: null, accessCode: "", deviceData: null, scanning:false, peripherals: new Map(), connected_peripheral: "", } this.handleDiscoverPeripheral = this.handleDiscoverPeripheral.bind(this); this.handleStopScan = this.handleStopScan.bind(this); this.handleUpdateValueForCharacteristic = this.handleUpdateValueForCharacteristic.bind(this); this.handleDisconnectedPeripheral = this.handleDisconnectedPeripheral.bind(this); this.handleAppStateChange = this.handleAppStateChange.bind(this); } navigate = () => { const navigateToDevice = NavigationActions.navigate({ routeName: "screenDevice", params: {} }); this.props.navigation.dispatch(navigateToDevice); }; navigateToScanDevice = () => { const navigateToScanDevice = NavigationActions.navigate({ routeName: "screenScanDevice", params: {} }); this.props.navigation.dispatch(navigateToScanDevice); }; fetchDataLocal = async ()=> { try{ let userData = await AsyncStorage.getItem('userData'); userData = JSON.parse(userData) this.setState({ user: userData, loading: false}); } catch(error) { alert(error); } } fetchDatabase = async (code)=> { try{ await firebase.database().ref().child("users").child(this.state.user.uid).child("devices") .child("savedDevices").on("value", snapshot => { this.setState({deviceData: snapshot.val(), accessCode: code}) }) } catch(error) { alert(error); } } async confirmCode(code){ var codeLength = code.length.toString() if(codeLength != 5){ return alert("Invalid access code") } this.fetchDatabase(code).done() alert("Synced!") } async componentWillMount(){ this.fetchDataLocal().done() BleManager.enableBluetooth() .then(() => { console.log('Bluetooth is already enabled'); }) .catch((error) => { Alert.alert('You need to enable bluetooth to use this app.'); }); BleManager.start({showAlert: false}); } componentDidMount() { this.handlerDiscover = bleManagerEmitter.addListener('BleManagerDiscoverPeripheral', this.handleDiscoverPeripheral ); this.handlerStop = bleManagerEmitter.addListener('BleManagerStopScan', this.handleStopScan ); this.handlerDisconnect = bleManagerEmitter.addListener('BleManagerDisconnectPeripheral', this.handleDisconnectedPeripheral ); this.handlerUpdate = bleManagerEmitter.addListener('BleManagerDidUpdateValueForCharacteristic', this.handleUpdateValueForCharacteristic ); if (Platform.OS === 'android' && Platform.Version >= 23) { PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION).then((result) => { if (result) { console.log("Permission is OK"); } else { PermissionsAndroid.requestPermission(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION).then((result) => { if (result) { console.log("User accept"); } else { console.log("User refuse"); } }); } }); } } componentWillUnmount() { this.handlerDiscover.remove(); this.handlerStop.remove(); this.handlerDisconnect.remove(); this.handlerUpdate.remove(); } handleAppStateChange(nextAppState) { if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') { console.log('App has come to the foreground!') BleManager.getConnectedPeripherals([]).then((peripheralsArray) => { console.log('Connected peripherals: ' + peripheralsArray.length); }); } this.setState({appState: nextAppState}); } handleDisconnectedPeripheral(data) { let peripherals = this.state.peripherals; let peripheral = peripherals.get(data.peripheral); if (peripheral) { peripheral.connected = false; peripherals.set(peripheral.id, peripheral); this.setState({peripherals, connected: "no"}); } console.log('Disconnected from ' + data.peripheral); } confirmDevicePrompt(){ prompt( 'Enter Access code', 'Access codes are 5 digits long, only numbers are allowed', [ {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'}, {text: 'OK', onPress: code => this.confirmCode(code)}, ], { type: 'phone-pad', cancelable: true, defaultValue: this.state.accessCode, placeholder: '12345', } ) } async createDevice(){ if(this.state.accessCode == ""){ return alert("Please Sync Device!") } else{ var savedDevices = this.state.deviceData //var iconType = this.pickIconType() if(!savedDevices){ let addDevice = [{ key: this.state.connected_peripheral.id + "_" + this.state.connected_peripheral.name , id : this.state.connected_peripheral.id, name: this.state.connected_peripheral.name, code: this.state.accessCode, type: this.state.type, //set to arm when connecting to device emg: 0, thresholds: [0,0,0,0], iconPath: 3 //3 is arm }] savedDevices = addDevice firebase.database().ref().child("users").child(this.state.user.uid).child("devices").set({savedDevices}) AsyncStorage.setItem('accessCode', JSON.stringify(this.state.accessCode)) AsyncStorage.setItem('savedDevices', JSON.stringify(savedDevices)) this.navigate(); } else{ let addDevice = { key: this.state.connected_peripheral.id + "_" + this.state.connected_peripheral.name , id : this.state.connected_peripheral.id, name: this.state.connected_peripheral.name, code: this.state.accessCode, type: this.state.type, //set to arm when connecting to device emg: 0, thresholds: [0,0,0,0], iconPath: 3 //3 is arm } savedDevices.push(addDevice) var userID = this.state.user.uid firebase.database().ref().child("users").child(this.state.user.uid).child("devices").set({savedDevices}) AsyncStorage.setItem('accessCode', JSON.stringify(this.state.accessCode)) AsyncStorage.setItem('savedDevices', JSON.stringify(savedDevices)) this.navigate(); } } } checkLength(curItem, command, input){ var codeLength = input.length.toString() if(codeLength != 5){ return alert("Invalid access code") } else{ return this.handleWriteCharacteristic(curItem, command, input) } } handleWriteCharacteristic(peripheral, command, input) { if(peripheral == null){ return (alert("No device connected")) } BleManager.retrieveServices(peripheral.id).then((peripheralInfo) => { console.log(peripheralInfo); var service = 'fe84-0000-1000-8000-00805f9b34fb'; var readCharacteristic = '2d30c082-f39f-4ce6-923f-3484ea480596'; var writeCharacteristic = '2d30c083-f39f-4ce6-923f-3484ea480596'; if (command == 1) { if (led == 0) { BleManager.write(peripheral.id, service, writeCharacteristic, [1, 1]).then(() => { console.log('Turned LED on'); }); led = 1; } else if (led == 1) { BleManager.write(peripheral.id, service, writeCharacteristic, [1, 0]).then(() => { console.log('Turned LED off'); }); led = 0; } } else if (command == 0) { var arr = Array.from(input); var send = []; for (var i=0; i<input.length; i++) send[i] = Number(arr[i]); console.log('User input was: '+input); console.log('Access code sending: '+send); BleManager.write(peripheral.id, service, writeCharacteristic, [0, send[0], send[1], send[2], send[3], send[4]]).then(() => { console.log('Access code sent'); }); } }); } handleUpdateValueForCharacteristic(data) { console.log('Received data from ' + data.peripheral + ' characteristic ' + data.characteristic, data.value); var buf = Buffer.from(data.value); name = buf.toString('utf8', 0, 4); if (name == "acel") { // reads byte sets of 4 into appropriate variable in array accels[0] = buf.readFloatLE(4); accels[1] = buf.readFloatLE(8); accels[2] = buf.readFloatLE(12); } else if (name == "gyro") { gyros[0] = buf.readFloatLE(4); gyros[1] = buf.readFloatLE(8); gyros[2] = buf.readFloatLE(12); } else if (name == "temp") { temp = buf.readFloatLE(4); } else console.log("Unable to read sensor data"); console.log("Accel: "+accels[0]+" "+accels[1]+" "+accels[2]+ "\nGyro: "+gyros[0]+" "+gyros[1]+" "+gyros[2]+"\nTemp: "+temp); this.latestArrayData(accels, gyros, temp) } latestArrayData(accels, gyros, temp){ var tempaccels = []; tempaccels[0] = accels[0].toFixed(2) tempaccels[1] = accels[1].toFixed(2) tempaccels[2] = accels[2].toFixed(2) if(savedAccels.length > 20){ savedAccels.pop() savedAccelsx.pop() savedGyros.pop() savedTemps.pop() } else if(count == 25){ savedAccels.unshift(tempaccels) savedAccelsx.unshift(tempaccels[0]) savedGyros.unshift(gyros) savedTemps.unshift(temp) count = 0 this.setState({savedAccelsx: savedAccelsx}) } count = count + 1; } handleStopScan() { console.log('Scan is stopped'); this.setState({ scanning: false }); } startScan() { if (!this.state.scanning) { this.setState({peripherals: new Map()}); BleManager.scan([], 2, true).then((results) => { console.log('Scanning...'); this.setState({scanning:true}); }); } this.retrieveConnected() } retrieveConnected(){ if(this.state.peripherals == null){ return } BleManager.getConnectedPeripherals([]).then((results) => { console.log(results); var peripherals = this.state.peripherals; for (var i = 0; i < results.length; i++) { var peripheral = results[i]; peripheral.connected = true; peripherals.set(peripheral.id, peripheral); this.setState({ peripherals, connected: "yes" }); } }); } handleDiscoverPeripheral(peripheral){ var peripherals = this.state.peripherals; if(peripheral == null){ return } if (!peripherals.has(peripheral.id)){ console.log('Got ble peripheral', peripheral); peripherals.set(peripheral.id, peripheral); this.setState({ peripherals }) } } test(peripheral) { if (peripheral){ if (peripheral.connected){ BleManager.disconnect(peripheral.id); this.setState({connected_peripheral: ""}) }else{ BleManager.connect(peripheral.id).then(() => { let peripherals = this.state.peripherals; let p = peripherals.get(peripheral.id); if (p) { p.connected = true; peripherals.set(peripheral.id, p); this.setState({peripherals: peripherals, type: 'arm'}); } console.log('Connected to ' + peripheral.id); }).catch((error) => { console.log('Connection error', error); }); this.setState({connected_peripheral: peripheral}) } } } checkDeviceName(name){ thisname =(JSON.stringify(name)) thisname = thisname.toLowerCase() checkname = "simblee" if(thisname.indexOf(checkname) > -1){ return( <Image source = {armIcon} style= {{width: 100, height: 100, margin: 5, borderRadius:10, borderColor: '#06a7e2', borderWidth: 1}} />) } else return <Text> Not Simblee Device </Text> } render() { const list = Array.from(this.state.peripherals.values()); const dataSource = ds.cloneWithRows(list); return ( <View style={styles.container}> <View style ={{alignItems: 'center'}}> <Text style = {styles.titleText}> ADD DEVICE </Text> </View> <View style = {{flexDirection: 'row', justifyContent: 'center', margin:10}}> <TouchableHighlight style={{margin: 10, padding:10, backgroundColor:'#06a7e2'}} onPress={() => this.startScan() }> <Text style = {styles.buttonText}>Scan Bluetooth ({this.state.scanning ? 'on' : 'off'})</Text> </TouchableHighlight> </View> <View style = {{flexDirection: 'row', justifyContent: 'center'}}> <TouchableHighlight style={{margin: 10, padding:10, backgroundColor:'#06a7e2', justifyContent:'center'}} onPress={this.confirmDevicePrompt.bind(this)}> <Text style = {styles.buttonText}>Sync Device</Text> </TouchableHighlight> <TouchableHighlight style={{margin: 10, padding:10, backgroundColor:'#06a7e2', justifyContent:'center'}} onPress={()=> this.createDevice()}> <Text style = {styles.buttonText}>Add Device</Text> </TouchableHighlight> </View> <ScrollView style={styles.scroll}> {(list.length == 0) && <View style={{flex:1, margin: 20}}> <Text style={{textAlign: 'center'}}>No peripherals</Text> </View> } <ListView enableEmptySections={true} contentContainerStyle={{paddingBottom:100}} dataSource={dataSource} renderRow={(item) => { const color = item.connected ? '#06a7e2' : '#fff'; return ( <TouchableOpacity onPress={() => this.test(item) }> <View style={[styles.row, {backgroundColor: color}]}> <View style = {{flexDirection: 'row'}}> {this.checkDeviceName(item.name)} <Text style={{ fontFamily : "Klavika-Regular", fontSize: 14,textAlign: 'center', color: item.connected ? '#ffffff' : '#333333', padding: 10}}>{item.name}</Text> <Text style={{fontFamily : "Klavika-Regular", fontSize: 14, textAlign: 'center', color: item.connected ? '#ffffff' : '#333333', padding: 10}}>{item.id}</Text> </View> </View> </TouchableOpacity> ); }} /> </ScrollView> </View> ); } } const styles = StyleSheet.create({ MainContainer: { alignItems: 'center', justifyContent: 'center', }, row : { margin: 15, }, titleText: { marginTop: 40, alignItems: 'center', justifyContent: 'center', fontFamily : "Klavika Bold", fontSize: 40, color: '#1c3d72' }, buttonText: { fontFamily : "MuseoSans", color: '#ffffff', fontSize: 14, textAlign: 'center', }, touchableIcon: { margin: 10, borderRadius: 5, borderWidth: 5 }, textStyle: { fontFamily : "Klavika-Regular", fontSize: 20, margin: 5, color: 'black' } });
import { MaybeLink, } from "../toolbox"; import PropTypes from "prop-types"; import React from "react"; import styled from "styled-components"; const EntryWrapperLink = styled(MaybeLink)` display: flex; width: 100%; position: relative; overflow: hidden; `; const EntryWrapper = ( { children, externalUrl, internalUrl, GatsbyLink, } ) => { return ( externalUrl ? <EntryWrapperLink href = { externalUrl }> {children} </EntryWrapperLink> : <EntryWrapperLink GatsbyLink = { GatsbyLink } to = { internalUrl } > {children} </EntryWrapperLink> ); }; EntryWrapper.propTypes = { GatsbyLink: PropTypes.any, children: PropTypes.array, externalUrl: PropTypes.string, internalUrl: PropTypes.string, }; export default EntryWrapper;
const express = require("express"); const router = express.Router(); const post = require("../controller/postController"); router.get("/post", post.findAll); router.get("/post/:postId", post.findOneByPostId); router.post("/post", post.create); router.put("/post/:postId", post.updateByPostId); router.delete("/post", post.deleteAll); router.delete("/post/:postId", post.deleteByPostId); module.exports = router;
import React, { useState,useReducer, useEffect } from "react"; import { useForm } from "react-hook-form"; import { createStyles, makeStyles, Theme } from "@material-ui/core/styles"; import TextField from "@material-ui/core/TextField"; import Card from "@material-ui/core/Card"; import CardContent from "@material-ui/core/CardContent"; import CardHeader from "@material-ui/core/CardHeader"; import Button from "@material-ui/core/Button"; import { useAuth } from "../contexts/AuthContext" import { Link , useHistory} from "react-router-dom" import {TwitterSingUpLogin } from "./firebaseprovider/Twitter" import {GoogleSingUpLogin } from "./firebaseprovider/Google" const useStyles = makeStyles((theme: Theme) => createStyles({ container: { display: "flex", flexWrap: "wrap", width: 400, margin: `${theme.spacing(0)} auto` }, loginBtn: { marginTop: theme.spacing(2), flexGrow: 1 }, header: { textAlign: "center", background: "#212121", color: "#fff" }, card: { marginTop: theme.spacing(10) } }) ); //state type type State = { username: string, password: string, isButtonDisabled: boolean, helperText: string, isError: boolean }; const initialState: State = { username: "", password: "", isButtonDisabled: true, helperText: "", isError: false }; type Action = | { type: "setEmail", payload: string } | { type: "setPassword", payload: string } | { type: "setIsButtonDisabled", payload: boolean } | { type: "loginSuccess", payload: string } | { type: "loginFailed", payload: string } | { type: "setIsError", payload: boolean }; const reducer = (state: State, action: Action): State => { switch (action.type) { case "setEmail": return { ...state, username: action.payload }; case "setPassword": return { ...state, password: action.payload }; case "setIsButtonDisabled": return { ...state, isButtonDisabled: action.payload }; case "loginSuccess": return { ...state, helperText: action.payload, isError: false }; case "loginFailed": return { ...state, helperText: action.payload, isError: true }; case "setIsError": return { ...state, isError: action.payload }; default: return state; } }; const Login = () => { const classes = useStyles(); const [state, dispatch] = useReducer(reducer, initialState); const [error, setError] = useState("") const { login } = useAuth() const { register, handleSubmit, errors, trigger } = useForm(); const history = useHistory() useEffect(() => { if (state.username.trim() && state.password.trim()){ //trigger(); dispatch({ type: "setIsButtonDisabled", payload: false }); } else { //clearErrors() dispatch({ type: "setIsButtonDisabled", payload: true }); } }, [state.username, state.password]); async function handleLogin (data) { //react-hook-formを導入したためevent -> dataに変更 //event.preventDefault() //react-hook-formを導入したため削除 try { setError("") //sing up ボタンの無効化 dispatch({ type: "setIsButtonDisabled", payload: true }); await login(state.username, state.password) history.push("/dashboard") } catch (e){ //エラーのメッセージの表示 switch (e.code) { case "auth/network-request-failed": setError("通信がエラーになったのか、またはタイムアウトになりました。通信環境がいい所で再度やり直してください。"); break; case "auth/weak-password": setError("メールアドレスまたはパスワードが間違えています。"); break; case "auth/invalid-email": setError("メールアドレスまたはパスワードが間違えています。"); break; case "auth/user-not-found": setError("メールアドレスまたはパスワードが間違えています。"); break; case "auth/user-disabled": setError("入力されたメールアドレスは無効(BAN)になっています。"); break; case "auth/wrong-password": setError("メールアドレスまたはパスワードが間違えています。"); break; default: //想定外 setError("ログインに失敗しました。通信環境がいい所で再度やり直してください。"); console.log(e) } //dispatch({ // type: "loginFailed", // payload: "Incorrect username or password" //}); //sing up ボタンの有効化 dispatch({ type: "setIsButtonDisabled", payload: false }); } }; const handleKeyPress = (event: React.KeyboardEvent) => { if (event.keyCode === 13 || event.which === 13) { if (!state.isButtonDisabled){ handleKeyPresstrigger() if (errors) { //errorメッセージを表示する } else { handleLogin() } } } }; async function handleKeyPresstrigger () { const result = await trigger(); return result } const handleEmailChange: React.ChangeEventHandler<HTMLInputElement> = ( event ) => { dispatch({ type: "setEmail", payload: event.target.value }); }; const handlePasswordChange: React.ChangeEventHandler<HTMLInputElement> = ( event ) => { dispatch({ type: "setPassword", payload: event.target.value }); }; return ( <form className={classes.container} noValidate autoComplete="off"> <Card className={classes.card}> <CardHeader className={classes.header} title="Login" /> <CardContent> <div> {error && <div style={{ color: "red" }}>{error}</div>} <TextField error={state.isError} fullWidth id="username" name="username" type="email" label="Email" placeholder="Email" margin="normal" onChange={handleEmailChange} onKeyPress={handleKeyPress} inputRef={register({pattern: /^[A-Za-z0-9]{1}[A-Za-z0-9_.-]*@{1}[A-Za-z0-9_.-]{1,}\.[A-Za-z0-9]{1,}$/ })} /> {errors.username?.type === "pattern" && <div style={{ color: "red" }}>メールアドレスの形式で入力されていません</div>} <TextField error={state.isError} fullWidth id="password" name="password" type="password" label="Password" placeholder="Password" margin="normal" onChange={handlePasswordChange} onKeyPress={handleKeyPress} inputRef={register({ required: true, minLength: 6 })} /> {errors.password?.type === "minLength" && <div style={{ color: "red" }}>パスワードは6文字以上で入力してください</div>} </div> もしアカウントがないなら<Link to="/signup">こちら</Link>からアカウントを作成してください。パスワードを忘れた方は<Link to="/forgotPassword">こちら</Link>から初期化をおこなってください <Button fullWidth variant="contained" size="large" color="secondary" className={classes.loginBtn} onClick={handleSubmit(handleLogin)} disabled={state.isButtonDisabled} > Login </Button> もしくは <TwitterSingUpLogin title="TwitterでLoginする"/> <GoogleSingUpLogin title="GoogleでLoginする"/> </CardContent> </Card> </form> ); }; export default Login;
var Modeler = require("../Modeler.js"); var className = 'Typeukinvestorrecord'; var Typeukinvestorrecord = function(json, parentObj) { parentObj = parentObj || this; // Class property definitions here: Modeler.extend(className, { result: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "result", "s:annotation": { "s:documentation": "The match level achieved" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 1 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, title: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "title", "s:annotation": { "s:documentation": "Title" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 30 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, forename: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "forename", "s:annotation": { "s:documentation": "Forename" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 30 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, surname: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "surname", "s:annotation": { "s:documentation": "Surname" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 30 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, abode: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "abode", "s:annotation": { "s:documentation": "Abode name or number" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 30 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, housename: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "housename", "s:annotation": { "s:documentation": "House name" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 50 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, housenum: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "housenum", "s:annotation": { "s:documentation": "House number" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 10 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, street1: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "street1", "s:annotation": { "s:documentation": "Street 1" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 50 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, street2: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "street2", "s:annotation": { "s:documentation": "Street 2" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 50 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, sublocality: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "sublocality", "s:annotation": { "s:documentation": "Sub Locality" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 35 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, locality: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "locality", "s:annotation": { "s:documentation": "Locality" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 35 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, town: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "town", "s:annotation": { "s:documentation": "Town" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 25 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, postcode: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "postcode", "s:annotation": { "s:documentation": "Postcode" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 8 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, companies: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "companies", "s:annotation": { "s:documentation": "CSV list of company names in which shares are held" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 2000 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, currentaddress: { type: "boolean", wsdlDefinition: { minOccurs: 1, maxOccurs: 1, name: "currentaddress", type: "s:boolean", "s:annotation": { "s:documentation": "Indicates whether or not the address given is the applicants&apos; current address" } }, mask: Modeler.GET | Modeler.SET, required: true }, usedindecision: { type: "boolean", wsdlDefinition: { minOccurs: 1, maxOccurs: 1, name: "usedindecision", type: "s:boolean", "s:annotation": { "s:documentation": "Indicates if this record is used in the final decision" } }, mask: Modeler.GET | Modeler.SET, required: true } }, parentObj, json); }; module.exports = Typeukinvestorrecord; Modeler.register(Typeukinvestorrecord, "Typeukinvestorrecord");
export function CartReducer(state = { cartItems: [] }, action){ switch(action.type){ case "INITIALIZE_CART": { state = {...state} return state } case "CART_LOADED": { state = {...state} state['cartItems'] = action.payload return state } case "ADD_TO_CART": { state = {...state} return state } case "ADDED_IN_CART": { state = {...state} state['cartItems'].push(action.payload) return state } case "REMOVE_FROM_CART": { state = {...state} return state } case "CART_ITEM_REMOVED": { console.log('CART_ITEM_REMOVED'); state = {...state} state['cartItems'].splice(action.payload.index,1) state["cartItems"]= [...state["cartItems"]] return state } default: return state } }
import React from 'react' const ModDark = () => { const style = { oscuro: { backgroundColor: '#092D53', color: '#fff', } } const cambiarModo = () => { let cuerpoweb = document.body; cuerpoweb.classList.toggle('oscuro'); } return ( <div style={style.oscuro}> <img src="./Initial.png" alt="" onClick={cambiarModo()}></img> </div> ) } export default ModDark
import React from 'react'; import {View, Text, TouchableOpacity, StyleSheet, Image, Dimensions, Alert, FlatList} from 'react-native'; import PropTypes from "prop-types"; import Colors from "../constants/Colors"; import OrderArrayItem from './OrderArrayItem'; const {width: SCREEN_WIDTH, height: SCREEN_HEIGHT} = Dimensions.get("window"); const OrderListItem = (props) => { const { orders, containerStyle, detailStyle, addressType, addressTypeTextStyle, openAddressTextStyle, CountryTextStyle, CityTextStyle, } = props; const renderOrderArrays = ({item, index}) => { return <OrderArrayItem orderModel={item.orderModel} productModel={item.productModel} containerStyle={{width: (SCREEN_WIDTH - 20) / 2.2}} /> } return ( <FlatList horizontal={false} showsVerticalScrollIndicator={false} data={orders} renderItem={renderOrderArrays} keyExtractor={item => item.orderModel.orderId} /> ) } const styles = StyleSheet.create({ container : { height: SCREEN_HEIGHT / 6, elevation: 2, backgroundColor: '#FFF', marginTop: 20, borderRadius: 15, marginBottom: 10, width: (SCREEN_WIDTH - 20) / 2.6, paddingVertical: 10, marginHorizontal: 10 }, detail:{ flexDirection: 'column', paddingTop: 15, paddingHorizontal: 10, height: "40%" }, addressTypeTextStyle: { color: '#FF8303', fontWeight: 'bold', fontSize: 13, textAlign: 'center', }, openAddressTextStyle: { fontWeight: 'bold', fontSize: 10, textAlign: 'center', }, CountryTextStyle:{ fontWeight: 'bold', fontSize: 16, color: '#FF8303', textAlign: 'center', }, CityTextStyle: { fontWeight: 'bold', fontSize: 16, color: '#FF8303', } }) OrderListItem.propTypes = { containerStyle: PropTypes.object, detailStyle: PropTypes.object, orders: PropTypes.array.isRequired, addressTypeTextStyle: PropTypes.object, openAddressTextStyle: PropTypes.object, navigatePage: PropTypes.string, } OrderListItem.defaultProps = { containerStyle: {}, detailStyle: {}, addressTypeTextStyles: {}, openAddressTextStyle: {}, CityTextStyle: {}, CountryTextStyle: {}, } export default OrderListItem;
function showAlert(){ alert("注意:本站内容为学习使用,不作任何商业用途,所有数据均为测试数据。" +"\n" + "本站暂时只支持内核为webKit的谷歌浏览器,360浏览器极速模式。" + "\n" + "请点击确认继续加载本站内容。"); }; $(function(){ //顶部导航栏 var navlists=$(".nav_ul li"); for (var i = 0; i < navlists.length; i++) { navlists.eq(i).attr("class",i); if (i==0) { navlists.eq(i).attr("class", "active "+i); } } $(".nav_ul li").click(function(){ page=1; $(".nav_ul li").removeClass("active"); $("#js_article_list").empty(); type_id=$(this).attr("class"); $(this).addClass("active"); getPageData(type_id); console.log("type_id:"+type_id); }); // 鼠标滑动,控制左右两侧导航栏出现和隐藏 window.onscroll= function (){ var top=$("body").scrollTop(); console.log(top); if (top>=340) { $("#js_recomand").css("top","0px"); } else{ $("#js_recomand").css("top","700px"); } } }); //加载轮播内容 $.getJSON("/carousel/get_effect_list",function(jsondata){ console.log("jsondata.date.items"+ jsondata.data.items); console.log(jsondata); if (jsondata=="") { alert("网站出现一点小bug了,抢修中。。。"); return false; } if (jsondata.code!=0) { alert("系统繁忙,请稍后再试~~"); return false; } else{ carouselIndicators(jsondata.data.items); carouselInner(jsondata.data.items); } }); function carouselIndicators(jsondata){ var slideNum=jsondata.length; $(".carousel-indicators").empty(); for (var i = 0; i <slideNum; i++) { var li=document.createElement("li"); li.setAttribute("data-target","#myCarousel"); li.setAttribute("data-slide-to",i); if (i==0) { li.setAttribute("class","active"); } $(".carousel-indicators").append(li); } } function carouselInner(carousel){ var slideNum=carousel.length; // debugger; $(".carousel-inner").empty(); if (slideNum==0) { $(".glyphicon-chevron-left").hide(); $(".glyphicon-chevron-right").hide(); return false; } for (var i = 0; i < slideNum; i++) { var item=document.createElement("div"); if (i==0) { item.setAttribute("class","active item"); } else{ item.setAttribute("class","item"); } var link=document.createElement("a"); link.setAttribute("href",'/front.1/html/articleDetial.html?article_id=' + carousel[i].article_id ); var img=document.createElement("img"); img.setAttribute("src",carousel[i].img_url); console.log(carousel[i].img_url); var img_info=imgInfo(carousel[i]); item.appendChild(link); link.appendChild(img); link.appendChild(img_info); $(".carousel-inner").append(item); } } function imgInfo(carousel){ // $(".writer_name").text(carousel.author); // $(".writer_info").text(carousel.author_desp); // $("h1").text(carousel.title); // $(".detile").text(carousel.summary); console.log(carousel); var img_info=document.createElement("div"); img_info.setAttribute("class","img_info"); var writer_name=document.createElement("div"); writer_name.setAttribute("class","writer_name"); var writer_name_text=document.createTextNode(carousel.author); writer_name.appendChild(writer_name_text); var writer_info=document.createElement("div"); writer_info.setAttribute("class","writer_info"); var writer_info_text=document.createTextNode(carousel.author_desp); writer_info.appendChild(writer_info_text); var h1=document.createElement("h1"); title=document.createTextNode(carousel.title); h1.appendChild(title); var detial=document.createElement("div"); detial.setAttribute("class","detial"); var detial_text=document.createTextNode(carousel.summary.substring(0,60) + "~ ~ ~"); detial.appendChild(detial_text); img_info.appendChild(writer_name); img_info.appendChild(writer_info); img_info.appendChild(h1); img_info.appendChild(detial); return img_info; } //首次加载文章内容 $.getJSON("/article/get_list?type_id=0&page=1&num="+5,function(jsondata){ console.log("jsondata.date.items"+ jsondata.data.items); console.log(jsondata); if (jsondata=="") { alert("网站出现一点小bug了,抢修中。。。"); return false; } if (jsondata.code!=0) { alert("系统繁忙,请稍后再试~~"); return false; } else{ onePageItems(jsondata.data); } }); var type_id=0; //根据第几页和每页的页数加载 function getPageData(typeId){ $.getJSON("/article/get_list?type_id=" + type_id + "&page=" + page + "&num="+5,function(jsondata){ console.log("jsondata.date.items"+ jsondata.data.items); console.log(jsondata); if (jsondata.code!=0) { alert("系统繁忙,请稍后再试~~"); } else{ onePageItems(jsondata.data); } }); } //加载文章列表 function buildItem(article){ var tr=document.createElement("tr"); tr.setAttribute("class","js_tr"); var td=document.createElement("td"); td.setAttribute("class","js_td"); var link=document.createElement("a"); link.setAttribute("href",'/front.1/html/articleDetial.html?article_id=' + article.id); link.setAttribute("target","_blank") tr.appendChild(td); td.appendChild(link); var box_l= buildArticleCover(article,"col-xs-4"); var box_r=buildArticleBrief(article,"col-xs-8"); var read=buildRead(article); link.appendChild(box_l); link.appendChild(box_r); box_r.appendChild(read); return tr; }
import React from 'react' import {ListItem} from '@material-ui/core' import {getColor} from './getColor' class CommentContainer extends React.Component { showCommentID = (comment) => { console.log(comment.id) console.log(comment.room_id) } render() { const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step)) const row = 9 const col = 9 return( <ListItem onClick={(() => this.showCommentID(this.props.comment))}> <div className="campus-table"> {range(0, row-1, 1).map((j) => { return( <div className='campus-row' key={j}> {range(j * col, j * col + col -1, 1).map((i) => { return( <div key={i} className="dot" style={{background: `${getColor(this.props.comment.text.charAt(i))}`}} ></div> ) })} </div> ) })} </div> </ListItem> ) } } export default CommentContainer
// console.log uses standard output to log msg to the console, and also controls line spacing to give in new line // PROCCESS STANDARD OUTPUT will write Strings but will not give you a new line automatically process.stdout.write("Hello "); process.stdout.write("World \n\n\n\n"); // Array of questions var questions = ["What is your name? ", "What is your fav hobby?", "What is your preferred programming language?"]; // Answers will be stored in an array var answers = []; function ask(i){ process.stdout.write(`\n\n\n\n ${questions[i]}`); process.stdout.write(` > `); } ask(0); // Add listener to get answers to our question// this code is to echo the data we are getting from the terminal, not to save them // process.stdin.on('data', function(data){ // //At this point it is the first time we are using NODE.JS asynchronously // // we are wating for some input and when we add that input it will be handled with that asynchronous callback // process.stdout.write('\n' + data.toString().trim()+ '\n'); // }); // Add listener to get answers to our question// THIS CODE IS TO SAVE THE ANSWERS AND ASK THE NEXT QUESTION, INSTEAD OF ECHOING THE DATA process.stdin.on('data', function(data){ //Save answer to current array index answers.push(data.toString().trim()); //Ask next question, as long as theres questions to ask/(length of questions) if(answers.length < questions.length){ ask(answers.length); }else{ process.exit(); } }); // Before exit is invoked process.on('exit', function(){ process.stdout.write("\n\n\n\n"); process.stdout.write(`Go ${answers[1]} ${answers[0]} you can finish writing ${answers[2]} late`); process.stdout.write("\n\n\n\n"); });
// 别误会, 就是特意导出一个空函数 export default () => {}
(function() { function int(x) { return x | 0; } function svg_element(tag) { return document.createElementNS('http://www.w3.org/2000/svg', tag); } var rt = {}; rt.mkGlobalScope = function() { var o = Object.create(null); function def(name, x) { Object.defineProperty(o, name, { value: x }); } def('hasOwnProperty', function(o, x) { return Object.prototype.hasOwnProperty.call(o, x); }); // HACK(eddyb) trap writes. if(Object.freeze) return Object.freeze(o); return o; }; rt.mkLocalScope = function(_this) { var o = Object.create(_this); function def(name, x) { Object.defineProperty(o, name, { value: x }); } def('this', _this); // HACK(eddyb) trap writes. if(Object.freeze) return Object.freeze(o); return o; }; rt.mkMovieClip = function(timeline) { var o = Object.create(null); function def_get(name, f) { Object.defineProperty(o, name, { get: f }); } function def(name, x) { Object.defineProperty(o, name, { value: x }); } def('play', function() { timeline.paused = false; }); def('stop', function() { timeline.paused = true; }); // HACK(eddyb) support for Goto{Frame,Label}. def('goto', function(frame) { if(typeof frame === 'string') frame = timeline.labels[frame]; timeline.frame = frame; }); def('gotoAndPlay', function(frame) { this.goto(frame); timeline.paused = false; }); // HACK(eddyb) these are usually only used as the // `getBytesLoaded() / getBytesTotal()` ratio. def('getBytesLoaded', function() { return 1; }); def('getBytesTotal', function() { return 1; }); def('getURL', function(url, target) { window.open(url, target); }); def_get('_root', rt.mkMovieClip.bind(null, timeline.root)); if(timeline.parent) def_get('_parent', rt.mkMovieClip.bind(null, timeline.parent)); for(var name in timeline.named) { var layer = timeline.layers[timeline.named[name]]; if(layer && layer.sprite) def_get(name, rt.mkMovieClip.bind(null, layer.sprite)); } // HACK(eddyb) trap writes. if(Object.freeze) return Object.freeze(o); return api; }; function Timeline(data, container, id_prefix) { if(!(this instanceof Timeline)) return new Timeline(data); id_prefix = id_prefix || ''; this.frame_count = data.frame_count; this.named = Object.create(null); this.actions = data.actions; this.labels = data.labels; this.sounds = data.sounds; this.sound_stream = data.sound_stream; this.activeSounds = []; this.layers = data.layers.map(function(frames, depth) { var container = svg_element('g'); var use = svg_element('use'); container.appendChild(use); var filter = svg_element('filter'); filter.setAttribute('id', id_prefix + 'd_' + depth + '_filter'); filter.setAttribute('x', 0); filter.setAttribute('y', 0); filter.setAttribute('width', 1); filter.setAttribute('height', 1); var feColorMatrix = svg_element('feColorMatrix'); filter.appendChild(feColorMatrix); container.appendChild(filter); return { frames: frames, container: container, use: use, filter: filter, feColorMatrix: feColorMatrix, ratio: null, isHover: function() { // FIXME(eddyb) figure out how much this needs polyfill. return this.container.matches(':hover'); }, updateUseHref: function() { if(this.character > 0) { var href = '#c_' + this.character; if(this.button && this.button.state != 'up') href += '_' + this.button.state; if(href != this.useHref) this.use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', href); this.useHref = href; } else { this.use.removeAttributeNS('http://www.w3.org/1999/xlink', 'href'); this.useHref = null; } } }; }); this.root = this; this.container = container; this.id_prefix = id_prefix; this.attachLayers(); } Timeline.prototype.paused = false; Timeline.prototype.frame = 0; Timeline.prototype.renderedFrame = -1; Timeline.prototype.attachLayers = function() { var container = this.container; this.layers.forEach(function(layer) { container.appendChild(layer.container); }); }; Timeline.prototype.detachLayers = function() { this.layers.forEach(function(layer) { layer.container.remove(); }); }; Timeline.prototype.showFrame = function() { if(this.paused && this.renderedFrame == this.frame) { // Update sprites and buttons even when paused. this.layers.forEach(function(layer) { if(layer.sprite) layer.sprite.showFrame(); if(layer.button) layer.button.showFrame(); }); return; } var mkMovieClip = rt.mkMovieClip.bind(null, this); var frame = this.frame; var renderedFrame = this.renderedFrame; var named = this.named; var id_prefix = this.id_prefix; if(renderedFrame > frame) renderedFrame = -1; this.layers.forEach(function(layer, depth) { var obj, i; for(i = frame; i > renderedFrame && !obj && obj !== null; i--) obj = layer.frames[i]; // Fully remove anything not present yet. var removeOld = renderedFrame == -1 || obj === null; // TODO(eddyb) this might need to take SWF's `is_move` into account. // HACK(eddyb) there's the issue of what `ratio` does, see also // http://wahlers.com.br/claus/blog/hacking-swf-2-placeobject-and-ratio/. // Remove the old character if necessary. if(removeOld || (obj && (layer.character != obj.character || layer.ratio !== obj.ratio))) { layer.character = -1; layer.ratio = null; if(layer.sprite) { layer.sprite.detachLayers(); layer.sprite.parent = null; layer.sprite.root = null; layer.sprite = null; } if(layer.button) { layer.button = null; } } // Remove the old name if necessary. if(layer.name && (removeOld || (obj && layer.name != obj.name))) { named[layer.name] = null; layer.name = null; } if(obj) { if(layer.character != obj.character || layer.ratio !== obj.ratio) { layer.character = obj.character; layer.ratio = obj.ratio; var sprite_data = sprites[obj.character]; if(sprite_data) { layer.sprite = new Timeline( sprite_data, layer.container, id_prefix + 'd_' + depth + '_', ); layer.sprite.parent = this; layer.sprite.root = this.root; } var button_data = buttons[obj.character]; if(button_data) { var button = layer.button = { state: 'up', attachListeners: function() { layer.use.addEventListener('mouseover', this.mouse_over_out_up); layer.use.addEventListener('mouseout', this.mouse_over_out_up); layer.use.addEventListener('mouseup', this.mouse_over_out_up); layer.use.addEventListener('mousedown', this.mouse_down); }, detachListeners: function() { layer.use.removeEventListener('mouseover', this.mouse_over_out_up); layer.use.removeEventListener('mouseout', this.mouse_over_out_up); layer.use.removeEventListener('mouseup', this.mouse_over_out_up); layer.use.removeEventListener('mousedown', this.mouse_down); }, mouse_over_out_up: function(ev) { button.transition(layer.isHover() ? 'over' : 'up'); }, mouse_down: function() { button.transition('down'); }, showFrame: function() { if(layer.button !== this) return; if(!layer.isHover()) this.transition('up'); }, transition: function(to) { if(layer.button !== this) return; if(this.state == to) return; var event; if(this.state == 'up' && to == 'over') { event = 'hoverIn'; } else if(this.state == 'over' && to == 'up') { event = 'hoverOut'; } else if(this.state == 'over' && to == 'down') { event = 'down'; } else if(this.state == 'down' && to == 'over') { event = 'up'; } this.state = to; var handler = event && button_data.mouse[event]; if(handler) handler(rt.mkGlobalScope(), rt.mkLocalScope(mkMovieClip())); }, }; button.attachListeners(); } } if(obj.matrix) { layer.container.setAttribute('transform', 'matrix(' + obj.matrix.join(' ') + ')'); } else { layer.container.removeAttribute('transform'); } if(obj.color_transform) { layer.feColorMatrix.setAttribute('values', obj.color_transform.join(' ')); layer.container.setAttribute('filter', 'url(#' + layer.filter.id + ')'); } else { layer.container.removeAttribute('filter'); } if(layer.name != obj.name) { layer.name = obj.name; if(layer.name) named[layer.name] = depth; } } // Update the sprite or button if it exists. if(layer.sprite) layer.sprite.showFrame(); if(layer.button) layer.button.showFrame(); // Update the <use> element. layer.updateUseHref(); }); if(renderedFrame == -1) { var activeSounds = this.activeSounds; // Remove sounds that start right away from the // active set, to avoid them getting stopped. var play_sounds_at_start = this.sounds[0]; if(play_sounds_at_start) play_sounds_at_start.forEach(function(sound) { activeSounds[sound.character] = null; }); if(this.sound_stream && this.sound_stream.start == 0) activeSounds[0] = null; activeSounds.forEach(function(sound) { if(sound) { sound.userTimeline = null; sound.pause(); } }); this.activeSounds = []; } for(var i = renderedFrame + 1; i <= frame; i++) { var timeline = this; var play_sounds = this.sounds[i]; if(play_sounds) play_sounds.forEach(function(sound) { sounds[sound.character].userTimeline = timeline; }); if(this.sound_stream && this.sound_stream.start == i) this.sound_stream.sound.userTimeline = timeline; } for(var i = renderedFrame + 1; i <= frame; i++) { var timeline = this; function playSound(sound_data, sound) { if(sound.userTimeline && sound.userTimeline != timeline) return console.error('sound already in use by', sound.userTimeline); sound.loop = sound_data.loops !== null; if(!(sound_data.no_restart && sound.userTimeline == timeline)) { // FIXME(eddyb) couple this with `requestAnimationFrame` // (currently calling `showFrame` in a loop doesn't do the right thing). sound.currentTime = (frame - i) / frame_rate; } var promise = sound.play(); if(promise && promise.catch) promise.catch(function(e) { console.error('failed to play sound: ' + e.toString()); }); sound.userTimeline = timeline; timeline.activeSounds[sound_data.character] = sound; } var play_sounds = this.sounds[i]; if(play_sounds) play_sounds.forEach(function(sound) { playSound(sound, sounds[sound.character]); }); if(this.sound_stream && this.sound_stream.start == i) playSound({ character: 0 }, this.sound_stream.sound); } this.renderedFrame = frame; var action = this.actions[frame]; if(action) action(rt.mkGlobalScope(), rt.mkLocalScope(mkMovieClip())); // HACK(eddyb) no idea what the interaction here should be. if(!this.paused) this.frame = (frame + 1) % this.frame_count; }; timeline = new Timeline(timeline, document.getElementById('body')); var start; var last_frame = 0; function update(now) { window.requestAnimationFrame(update); if(!start) start = now; // TODO(eddyb) figure out how to avoid absolute values. var frame = int((now - start) * frame_rate / 1000); for(; last_frame < frame; last_frame++) timeline.showFrame(); } // HACK(eddyb) work around unreasonable autoplay policies in Chrome. // See https://goo.gl/xX8pDD for their one-sided description of it. var anySounds = false; function forEachSound(f) { timeline.sound_stream && f(timeline.sound_stream.sound); sprites.forEach(function(sprite) { sprite.sound_stream && f(sprite.sound_stream.sound); }); sounds.forEach(f); } forEachSound(function() { anySounds = true; }) if(anySounds) { var viewBox = timeline.container.parentNode.getAttribute('viewBox') .split(' ') .map(function(x) { return +x; }); var bgRect = document.getElementById('bg'); var bgOriginalFill = bgRect.getAttribute('fill'); bgRect.setAttribute('fill', 'white'); var playButton = svg_element('path'); var x = viewBox[0] + viewBox[2] / 2; var y = viewBox[1] + viewBox[3] / 2; var size = Math.min(viewBox[2], viewBox[3]) / 2; var x0 = x - size / 3; var x1 = x + size / 3 * 2; var y0 = y - size / 2; var y1 = y + size / 2; playButton.setAttribute('d', 'M' + x1 + ',' + y + ' L' + x0 + ',' + y0 + ' L' + x0 + ',' + y1 + ' Z'); playButton.setAttribute('fill', 'black'); playButton.style.cursor = 'pointer'; var clicked = false; playButton.addEventListener('click', function() { if(clicked) return; clicked = true; // HACK(eddyb) Safari is even worse, requires loading media // as a result of a user interaction to enable "autoplay" later. forEachSound(function(sound) { sound.load(); }); playButton.remove(); bgRect.setAttribute('fill', bgOriginalFill); window.requestAnimationFrame(update); }); timeline.container.appendChild(playButton); } else window.requestAnimationFrame(update); })()
// TODO: split routes into individual files // TODO: don't hardcode 'article_' and 'page_' id prefixes exports.register = (server, options, next) => { server.route([ { method: 'GET', path: '/collections', config: { handler: (request, reply) => { reply(options.collections); }, }, }, { method: 'GET', path: `/{page}`, config: { handler: (request, reply) => { server.methods .database() .get( 'page_' + request.params.page, (err, body) => err ? reply(err) : reply(body) ); }, }, }, ]); for (let collectionpath in options.collections) { const collectionname = options.collections[collectionpath]; server.route({ method: 'GET', path: `/${collectionpath}`, config: { handler: (request, reply) => { server.methods .database() .view( 'articles', 'category', { key: collectionname }, (err, body) => err ? reply(err) : reply(body) ); }, }, }); server.route({ method: 'GET', path: `/${collectionpath}/{article}`, config: { handler: (request, reply) => { server.methods .database() .get( 'article_' + request.params.article, (err, body) => err ? reply(err) : reply(body) ); }, }, }); } return next(); }; exports.register.attributes = { pkg: require('./package.json'), };
import React from 'react'; import PropTypes from 'prop-types'; import AudioVolumeVisualization from '../audioVolumeMeter/AudioVolumeVisualization.js'; import AudioPreview from '../components/AudioPreview.jsx'; import {AudioSpeakerDetector} from 'phenix-web-sdk'; import colors from '../../styles/colors.css'; import {select} from 'd3-selection'; class AudioContainer extends React.Component { constructor(props) { super(props); this.audioVolumeMeterInit = this.audioVolumeMeterInit.bind(this); } audioVolumeMeterInit() { if (!this.props.mediaStream) { return; } const stream = this.props.mediaStream; this.audioSpeakingDetector = new AudioSpeakerDetector([stream]); this.audioVolumeMeter = this.audioSpeakingDetector.getAudioVolumeMeter(stream); this.audioVolumeVisualization = new AudioVolumeVisualization(); this.audioVolumeVisualization.startRender(this.audioVolumeMeter, 'gain', { element: '#audioSelectPreview', title: 'Microphone Volume', textColors: colors, barColor: colors.bar }); } componentDidUpdate(prevProps) { if (prevProps.mediaStream !== this.props.mediaStream) { if (prevProps.mediaStream) { disposeOfAudioContext.call(this); const audioTrack = prevProps.mediaStream.getAudioTracks()[0]; if (audioTrack) { audioTrack.stop(); prevProps.mediaStream.removeTrack(audioTrack); } } if (this.props.mediaStream) { this.audioVolumeMeterInit(); } } else if (this.props.mediaStream === null) { this.audioVolumeMeterInit(); } } componentWillUnmount() { disposeOfAudioContext.call(this); } render() { const propsStyle = this.props.propsStyle || {}; return ( <AudioPreview propsStyle={propsStyle} /> ); } } AudioContainer.propTypes = { propsStyle: PropTypes.object, mediaStream: PropTypes.object }; function disposeOfAudioContext() { if (this.audioVolumeVisualization) { this.audioVolumeVisualization.stopRender(); } if (this.audioSpeakingDetector) { this.audioSpeakingDetector.stop(); this.audioSpeakingDetector.dispose(); } select('#audioSelectPreview').selectAll('*').remove(); } export default AudioContainer;
import actionTypes from "../actionTypes"; import makeActionCreator from "./makeActionCreator"; export const setScreenName = makeActionCreator( actionTypes.SET_CURRENTUSER_SCREEN_NAME, "name" ); export const setPhone = makeActionCreator( actionTypes.SET_CURRENTUSER_PHONE, "phone" ); export const setEmail = makeActionCreator( actionTypes.SET_CURRENTUSER_EMAIL, "email" );
'use strict' const { Trait } = require('@northscaler/mutrait') const property = require('@northscaler/property-decorator') const { IllegalArgumentError } = require('@northscaler/error-support') const { StreetAddress } = require('../entities/Location') /** * Imparts a `streetAddress` property with backing property `_streetAddress` supporting {@link StreetAddress}. */ const HasStreetAddress = Trait(superclass => class extends superclass { @property() _streetAddress _testSetStreetAddress (streetAddress) { if (streetAddress && !(streetAddress instanceof StreetAddress)) { throw new IllegalArgumentError({ message: 'StreetAddress required', info: { streetAddress } }) } return streetAddress.clone() } } ) module.exports = HasStreetAddress
class Left { static of(value) { return new Left(value) } constructor(value) { this._value = value } map(fn) { return this } } class Right { static of(value) { return new Right(value) } constructor(value) { this._value = value } map(fn) { return Right.of(fn(this._value)) } } function parseJson(str) { try { return Right.of(JSON.parse(str)) // str => object } catch (e) { return Left.of({ error: e.message }) } } let str = "{ name: zs }" // Left { _value: { error: 'Unexpected token n in JSON at position 2' } } 不合法得json串 // str = "123123zxcc" str = '{"name":"zs"}' let r = parseJson(str) .map(x => x.name.toUpperCase()) console.log(r); // Right { _value: 'ZS' } console.log(JSON.stringify({ name: 'zs' }));
import React from 'react'; const userInput = ( props ) => { const style = { backgroundColor: 'blue' } return( <input type="text" onChange={props.change} value={props.name}></input> ); } export default userInput;
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsFilterCenterFocus = { name: 'filter_center_focus', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M5 15H3v4c0 1.1.9 2 2 2h4v-2H5v-4zM5 5h4V3H5c-1.1 0-2 .9-2 2v4h2V5zm14-2h-4v2h4v4h2V5c0-1.1-.9-2-2-2zm0 16h-4v2h4c1.1 0 2-.9 2-2v-4h-2v4zM12 9c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/></svg>` };
// Provides dev-time type structures for `danger` - doesn't affect runtime. /* global danger, fail, warn */ import { CLIEngine } from 'eslint' /** * Eslint your code with */ export default async function eslint(config, extensions) { const allFiles = danger.git.created_files.concat(danger.git.modified_files) const options = { baseConfig: config } if (extensions) { options.extensions = extensions } const cli = new CLIEngine(options) // let eslint filter down to non-ignored, matching the extensions expected const filesToLint = allFiles.filter(f => { return ( !cli.isPathIgnored(f) && cli.options.extensions.some(ext => f.endsWith(ext)) ) }) return Promise.all(filesToLint.map(f => lintFile(cli, config, f))) } async function lintFile(linter, config, path) { const contents = await danger.github.utils.fileContents(path) const report = linter.executeOnText(contents, path) if (report.results.length !== 0) { report.results[0].messages.map(msg => { if (msg.fatal) { return fail(`Fatal error linting ${path} with eslint.`) } const fn = { 1: warn, 2: fail }[msg.severity] return fn( `${path} line ${msg.line} – ${msg.message} (${msg.ruleId})`, path, msg.line, ) }) } }
import createElement from '../../assets/lib/create-element.js'; function createCardTemplate({ image, price, name }) { return `<div class="card"> <div class="card__top"> <img src="/assets/images/products/${image}" class="card__image" alt="product"> <span class="card__price">€${price.toFixed(2)}</span> </div> <div class="card__body"> <div class="card__title">${name}</div> <button type="button" class="card__button"> <img src="/assets/images/icons/plus-icon.svg" alt="icon"> </button> </div> </div>`; } function createCard(product) { const div = document.createElement('div'); div.innerHTML = createCardTemplate(product); return div.firstElementChild; } export default class ProductCard { constructor(product) { this.product = product; this._container = null; this._render(); } get elem() { return this._container; } _productAdd =() => { const event = new CustomEvent( "product-add", { detail: this.product.id, bubbles: true } ); this._container.dispatchEvent(event); } _render() { this._container = createCard(this.product); this._container.querySelector('button').addEventListener('click', this._productAdd); } }
// result export const ADD_RESULT = 'ADD_RESULT';
(function (angular, appSuite) { "use strict"; function constructor($mdDialog,studentService) { var vm = this; vm.studentData = {}; debugger; } constructor.$inject = ["$mdDialog","studentService"]; angular.module("student").controller("addNewStudentController", constructor); })(window.angular, window.appSuite);
/** * Created by xiaojiu on 2017/5/6. */ /** * 4pl Grid thead配置 * check:true //使用checkbox 注(选中后对象中增加pl4GridCheckbox.checked:true) * checkAll:true //使用全选功能 * field:’id’ //字段名(用于绑定) * name:’序号’ //表头标题名 * link:{ * url:’/aaa/{id}’ //a标签跳转 {id}为参数 (与click只存在一个) * click:’test’ //点击事件方法 参数test(index(当前索引),item(当前对象)) * } * input:true //使用input 注(不设置默认普通文本) * type:text //与input一起使用 注(type:operate为操作项将不绑定field,与按钮配合使用) * buttons:[{ * text:’收货’, //显示文本 * call:’tackGoods’, //点击事件 参数tackGoods(index(当前索引),item(当前对象)) * type:’link button’ //类型 link:a标签 button:按钮 * state:'checkstorage', //跳转路由 注(只有当后台传回按钮数据op.butType=link 才会跳转) * style:’’ //设置样式 * }] //启用按钮 与type:operate配合使用 可多个按钮 * style:’width:10px’ //设置样式 * */ 'use strict'; define(['../../../app'], function(app) { app.factory('createOrder', ['$http', '$q', '$filter', 'HOST', function($http, $q, $filter, HOST) { return { getThead: function() { return [{ type: 'input', check:true, checkAll:true }, { field: 'taskId', name: '业务单号' }, { field: 'waybillId', name: '运单号' },{ field: 'createTime', name: '创建时间' }, // { // field: 'wlStatu', // name: '订单状态' //}, { field: 'chuHuoName', name: '发件方' }, { field: 'senderNumber', name: '发件方编号' }, { field: 'chuHTel', name: '发件人电话' }, { field: 'receiverName', name: '收件方' }, { field: 'receTel', name: '收件人电话' },{ field: 'acceGoodCount', name: '件数', },{ field: 'pay', name: '运费', },{ field: 'payType', name: '结算方式' },{ field: 'paySide', name: '运费付费方' },{ field: 'collectMoney', name: '代收货款' },{ field: 'fee', name: '代收款手续费' },{ field: 'offerMoney', name: '保价金额' },{ field: 'insuranceMoney', name: '保价费' }, { field: 'name11', name: '操作', type: 'operate', buttons: [{ text: '确认收货', call:'confirmInCk' },{ text: '修改', btnType: 'btn', call:'updateOperation', openModal:'#addCar' }, { text: '作废', openModal:'#deleteCar', call: 'obtainId', },{ text: '查看', btnType: 'btn', call: 'lookCar', openModal:'#lookCar' },{ text:'打印配送单', btnType: 'button',call: 'print' },{ text:'打印箱单', btnType: 'button',call: 'printBox' }] }] }, getTheadChange: function() { return [{ field: 'pl4GridCount', name: '序号', type: 'pl4GridCount' }, { field: 'taskId', name: '业务单号' }, { field: 'createTime', name: '创建时间' }, { field: 'wlStatu', name: '订单状态' }, { field: 'chuHuoName', name: '发件方' },{ field: 'senderNumber', name: '发件方编号' } ,{ field: 'chuHTel', name: '发件人电话' }, { field: 'receiverName', name: '收件方' }, { field: 'receTel', name: '收件人电话' }, { field: 'frequency', name: '班次' }, // { // field: 'shouhuoState', // name: '收货状态' //}, { field: 'acceGoodCount', name: '件数', },{ field: 'pay', name: '运费', },{ field: 'pay', name: '实收运费', },{ field: 'payType', name: '结算方式' },{ field: 'paySide', name: '运费付费方' },{ field: 'collectMoney', name: '代收货款' },{ field: 'collectMoney', name: '实收代收货款' },{ field: 'fee', name: '代收款手续费' },{ field: 'offerMoney', name: '保价金额' },{ field: 'insuranceMoney', name: '保价费' }, { field: 'distributionWay', name: '配送方式' },{ field: 'fBdistributionWay', name: '调拨方式' }, //{ // field: 'distributionType', // name: '配送类型' //}, { field: 'auditStatus', name: '审核状态' }, { field: 'name11', name: '操作', type: 'operate', buttons: [{ text: '查看', btnType: 'btn', call: 'lookCar', openModal:'#lookCar' },{ text: '外单修改', btnType: 'btn', call: 'modification' },{ text:'打印配送单', btnType: 'button',call: 'print' },{ text:'打印箱单', btnType: 'button',call: 'printBox' }] }] }, getSearch: function() { var deferred = $q.defer(); $http.post(HOST + '/personalOrder/getDicList',{}) .success(function(data) { deferred.resolve(data); }) .error(function(e) { deferred.reject('error:' + e); }); return deferred.promise; }, getDataTable: function(data) { //将parm转换成json字符串 data.param = $filter('json')(data.param); var deferred = $q.defer(); $http.post(HOST + '/personalOrder/queryPersonalOrder', data) .success(function(data) { // console.log(data) deferred.resolve(data); }) .error(function(e) { deferred.reject('error:' + e); }); return deferred.promise; }, confirmInCk: function(data,url) { //将parm转换成json字符串 data.param = $filter('json')(data.param); var deferred = $q.defer(); $http.post(HOST + url, data) .success(function(data) { deferred.resolve(data); }) .error(function(e) { deferred.reject('error:' + e); }); return deferred.promise; }, deletePersonOrder: function(data,url) { //将parm转换成json字符串 data.param = $filter('json')(data.param); var deferred = $q.defer(); $http.post(HOST + url, data) .success(function(data) { deferred.resolve(data); }) .error(function(e) { deferred.reject('error:' + e); }); return deferred.promise; } } }]); });
const selectors = { OVERWATCH_FOOTER: "#footer", COMPETITIVE_STATS: "#competitive", COMPETITIVE_DROPDOWN_MENU: "#competitive > section:nth-child(2) > div > div.flex-container\\@md-min.m-bottom-items > div.flex-item\\@md-min.m-grow.u-align-right > div > select", OPTIONS: "#competitive > section:nth-child(2) > div > div.flex-container\\@md-min.m-bottom-items > div.flex-item\\@md-min.m-grow.u-align-right > div > select" }; module.exports = selectors;
const gulp = require('gulp'); const fs = require('fs'); const rename = require('gulp-rename'); const environment = process.env.ENVIRONMENT || 'dev'; gulp.task('copy-default-json', function() { fs.stat('./config/default.json', function(err, stat) { if(err != null && environment === 'dev') { return gulp.src("./default.json.default") .pipe(rename("default.json")) .pipe(gulp.dest("./config")); } else { return; } }); });
(function() { var toString = Object.prototype.toString; function isArray(it){ return toString.call(it) === '[object Array]'; } function isObject(it){ return toString.call(it) === '[object Object]'; } function _merge(a, b){ for(var key in b){ if(isArray(b[key])){ a[key] = b[key].slice(); }else if(isObject(b[key])){ a[key] = a[key] || {}; _merge(a[key], b[key]); }else{ a[key] = b[key]; } } return a; } function merge(){ var res = {}; for(var i = 0; i < arguments.length; ++i){ _merge(res, arguments[i]); } return res; } var axisColor = "#AAAAAA"; var axisGridlineColor = "#333333"; var rangeSlider = { rangeSlider: { sliderStyle: { borderColor: "#4e4e4e", highlightBorderColor: "#ffffff" }, tooltipStyle: { fontColor: "#ffffff", borderColor: "#4e4e4e", highlightBorderColor: "#009de0", backgroundColor: "#333333" }, thumbStyle: { indicatorStartColor: "#555555", indicatorEndColor: "#0c0c0c", indicatorPressStartColor: "#555555", indicatorPressEndColor: "#0c0c0c", indicatorBorderStartColor: "#ffffff", indicatorBorderEndColor: "#ffffff", indicatorPressBorderStartColor: "#8b8b8b", indicatorPressBorderEndColor: "#8b8b8b", indicatorInternalLineColor: "#ffffff", subRectBorderColor: "#ffffff", subRectColor: "#ffffff", rectOpacity: 0.3, rectColor: '#009de0', rectPressOpacity: 0.3, rectPressColor: "#ffffff" } } }; var title = { title: { style: { color: '#D8D8D8' } } }; var background = { background: { color: "#1B1B1B", border: { top: { visible: false }, bottom: { visible: false }, left: { visible: false }, right: { visible: false } }, drawingEffect: "normal" } }; var scrollbar = { thumb: { fill: "#a6a6a6", hoverFill: "#888888" }, track: { fill: '#333333' } }; var legend = { legend: { drawingEffect: "normal", title: { visible: true, style: { color: "#D8D8D8" } }, label: { style: { color: "#D8D8D8" } }, hoverShadow: { color: "#606060" }, mouseDownShadow: { color: "#cccccc" }, scrollbar: scrollbar }, sizeLegend: { drawingEffect: "normal", title: { visible: true, style: { color: "#D8D8D8" } }, label: { style: { color: "#D8D8D8" } } } }; var tooltip = { tooltip: { background: { color: "#000000", borderColor: "#ffffff" }, drawingEffect: "normal", footerLabel: { color: "#ffffff" }, separationLine: { // borderBottomColor: "#ffffff" color: "#ffffff" }, bodyDimensionLabel: { color: "#c0c0c0" }, bodyDimensionValue: { color: "#c0c0c0" }, bodyMeasureLabel: { color: "#c0c0c0" }, bodyMeasureValue: { color: "#ffffff" }, closeButton: { backgroundColor: "#000000", borderColor: "#ffffff" } } }; var plotArea = { plotArea: { drawingEffect: "normal", referenceLine: { defaultStyle: { color: "#ffffff", label: { background: "#1B1B1B", color: "#ffffff" } } } } }; var dataLabel = { plotArea: { dataLabel: { style: { color: "#D8D8D8" } } } }; var zAxis = { zAxis: { title: { visible: true, style: { color: axisColor } }, label: { style: { color: axisColor } }, color: axisColor } }; // Axis---------------------------- var axis = { title: { visible: true, style: { color: axisColor } }, gridline: { color: axisGridlineColor }, hoverShadow: { color: "#606060" }, mouseDownShadow: { color: "#cccccc" }, label: { style: { color: axisColor } }, color: axisColor }; var showAxisLine = { axisline: { visible: true } }; var showInfoAxisLine = { axisLine: { visible: true } }; var hideAxisLine = { axisline: { visible: false } }; var hideInfoAxisLine = { axisLine: { visible: false } }; var gridline = { gridline: { type: "line", color: axisGridlineColor, showLastLine: true } }; var dual = { title: { applyAxislineColor: true } }; var base = merge(title, background, legend, tooltip); var horizontalEffect = { xAxis: merge(axis, hideAxisLine, gridline), yAxis: axis, xAxis2: merge(axis, hideAxisLine) }; var horizontalDualEffect = merge(horizontalEffect, { xAxis: dual, xAxis2: dual }); var verticalEffect = { yAxis: merge(axis, hideAxisLine, gridline), xAxis: axis, yAxis2: merge(axis, hideAxisLine) }; var verticalDualEffect = merge(verticalEffect, { yAxis: dual, yAxis2: dual }); //------------------------------------------------ var barEffect = merge(base, plotArea, dataLabel, horizontalEffect); var bar3dEffect = merge(base, plotArea, zAxis, horizontalEffect); var dualbarEffect = merge(base, plotArea, dataLabel, horizontalDualEffect); var verticalbarEffect = merge(base, plotArea, dataLabel, rangeSlider, verticalEffect); var vertical3dbarEffect = merge(base, plotArea, zAxis, verticalEffect); var dualverticalbarEffect = merge(base, plotArea, dataLabel, verticalDualEffect); var stackedbarEffect = merge(base, plotArea, horizontalEffect); var dualstackedbarEffect = merge(base, plotArea, horizontalDualEffect); var stackedverticalbarEffect = merge(base, plotArea, { yAxis: merge(axis, hideAxisLine, dual), xAxis: axis, yAxis2: merge(axis, hideAxisLine) }); var dualstackedverticalbarEffect = merge(base, plotArea, verticalDualEffect); var lineEffect = merge(base, plotArea, dataLabel, rangeSlider, verticalEffect); var duallineEffect = merge(base, plotArea, dataLabel, verticalDualEffect); var horizontallineEffect = merge(base, plotArea, dataLabel, horizontalEffect); var dualhorizontallineEffect = merge(base, plotArea, dataLabel, horizontalDualEffect); var combinationEffect = merge(base, plotArea, dataLabel, rangeSlider, verticalEffect); var dualcombinationEffect = merge(base, plotArea, dataLabel, verticalDualEffect); var horizontalcombinationEffect = merge(base, plotArea, dataLabel, horizontalEffect); var dualhorizontalcombinationEffect = merge(base, plotArea, dataLabel, horizontalDualEffect); var bubbleEffect = merge(base, plotArea, dataLabel, { yAxis: merge(axis, hideAxisLine, gridline), xAxis: axis }); var pieEffect = merge(title, legend, plotArea, dataLabel, tooltip); var pieWithDepthEffect = pieEffect; var radarEffect = merge(legend, tooltip, plotArea, { background: { visible: false }, plotArea: { valueAxis: { title: { visible: true }, gridline: { color: axisGridlineColor } }, dataline: { fill: { transparency: 0 } }, polarGrid: { color: axisGridlineColor } } }); var mekkoEffect = merge(base, plotArea, { yAxis: merge(axis, hideAxisLine, { gridline: { type: "line" } }), xAxis: merge(axis, showAxisLine), xAxis2: merge(axis, showAxisLine) }); var horizontalmekkoEffect = merge(base, plotArea, { xAxis: merge(axis, hideAxisLine, { gridline: { type: "line" } }), yAxis: merge(axis, showAxisLine), yAxis2: merge(axis, showAxisLine) }); var bulletEffect = merge(legend, background, tooltip, plotArea, { plotArea: { target:{ valueColor: "#FFFFFF", shadowColor: "#333333" } }, categoryAxis2: { label: { style: { color: "#FFFFFF" } } } }); var treemapEffect = merge(legend, tooltip); sap.viz.extapi.env.Template.register({ id: "hcb", name: "hcb", version: "4.0.0", properties: { 'viz/bar': barEffect, 'viz/3d_bar': bar3dEffect, 'viz/image_bar': barEffect, 'viz/multi_bar': barEffect, 'viz/dual_bar': dualbarEffect, 'viz/multi_dual_bar': dualbarEffect, 'viz/column': verticalbarEffect, 'viz/3d_column': vertical3dbarEffect, 'viz/multi_column': verticalbarEffect, 'viz/dual_column': dualverticalbarEffect, 'viz/multi_dual_column': dualverticalbarEffect, 'viz/stacked_bar': stackedbarEffect, 'viz/multi_stacked_bar': stackedbarEffect, 'viz/dual_stacked_bar': dualstackedbarEffect, 'viz/multi_dual_stacked_bar': dualstackedbarEffect, 'viz/100_stacked_bar': stackedbarEffect, 'viz/multi_100_stacked_bar': stackedbarEffect, 'viz/100_dual_stacked_bar': dualstackedbarEffect, 'viz/multi_100_dual_stacked_bar': dualstackedbarEffect, 'viz/stacked_column': stackedverticalbarEffect, 'viz/multi_stacked_column': stackedverticalbarEffect, 'viz/dual_stacked_column': dualstackedverticalbarEffect, 'viz/multi_dual_stacked_column': dualstackedverticalbarEffect, 'viz/100_stacked_column': stackedverticalbarEffect, 'viz/multi_100_stacked_column': stackedverticalbarEffect, 'viz/100_dual_stacked_column': dualstackedverticalbarEffect, 'viz/multi_100_dual_stacked_column': dualstackedverticalbarEffect, 'riv/cbar': merge(legend, tooltip, plotArea, { background: { drawingEffect: "normal" }, yAxis: axis }), 'viz/combination': combinationEffect, 'viz/horizontal_combination': horizontalcombinationEffect, 'viz/dual_combination': dualcombinationEffect, 'viz/dual_horizontal_combination': dualhorizontalcombinationEffect, 'viz/boxplot': merge(base, plotArea, { yAxis: merge(axis, hideAxisLine, gridline), xAxis: axis }), 'viz/horizontal_boxplot': merge(base, plotArea, { xAxis: merge(axis, hideAxisLine, gridline), yAxis: axis }), 'viz/waterfall': merge(base, plotArea, { yAxis: merge(axis, hideAxisLine, gridline), xAxis: axis }), 'viz/horizontal_waterfall': merge(base, plotArea, { xAxis: merge(axis, hideAxisLine, gridline), yAxis: axis }), 'viz/stacked_waterfall': stackedverticalbarEffect, 'viz/horizontal_stacked_waterfall': stackedbarEffect, 'viz/line': lineEffect, 'viz/multi_line': lineEffect, 'viz/dual_line': duallineEffect, 'viz/multi_dual_line': duallineEffect, 'viz/horizontal_line': horizontallineEffect, 'viz/multi_horizontal_line': horizontallineEffect, 'viz/dual_horizontal_line': dualhorizontallineEffect, 'viz/multi_dual_horizontal_line': dualhorizontallineEffect, 'viz/area': lineEffect, 'viz/multi_area': lineEffect, 'viz/100_area': lineEffect, 'viz/multi_100_area': lineEffect, 'viz/horizontal_area': horizontallineEffect, 'viz/multi_horizontal_area': horizontallineEffect, 'viz/100_horizontal_area': horizontallineEffect, 'viz/multi_100_horizontal_area': horizontallineEffect, 'viz/pie': pieEffect, 'viz/multi_pie': pieEffect, 'viz/donut': pieEffect, 'viz/multi_donut': pieEffect, 'viz/pie_with_depth': pieWithDepthEffect, 'viz/donut_with_depth': pieWithDepthEffect, 'viz/multi_pie_with_depth': pieWithDepthEffect, 'viz/multi_donut_with_depth': pieWithDepthEffect, 'viz/bubble': bubbleEffect, 'viz/multi_bubble': bubbleEffect, 'viz/scatter': bubbleEffect, 'viz/multi_scatter': bubbleEffect, 'viz/scatter_matrix': bubbleEffect, 'viz/radar': radarEffect, 'viz/multi_radar': radarEffect, 'viz/tagcloud': merge(legend, tooltip), 'viz/heatmap': merge(legend, tooltip, { xAxis: axis, yAxis: axis }), 'viz/treemap': treemapEffect, 'viz/mekko': mekkoEffect, 'viz/100_mekko': mekkoEffect, 'viz/horizontal_mekko': horizontalmekkoEffect, 'viz/100_horizontal_mekko': horizontalmekkoEffect, 'viz/number': merge(tooltip, { plotArea: { valuePoint: { label: { fontColor: '#D8D8D8' } } } }), 'info/column': info(verticalbarEffect), 'info/bar': info(barEffect), 'info/line': info(lineEffect), 'info/pie': info(pieEffect), 'info/donut': info(pieEffect), 'info/scatter': infoBubble(bubbleEffect), 'info/bubble': infoBubble(bubbleEffect), 'info/stacked_column': info(stackedverticalbarEffect), 'info/stacked_bar': info(stackedbarEffect), 'info/combination': info(combinationEffect), 'info/stacked_combination': info(combinationEffect), 'info/dual_stacked_combination': infoDual(dualcombinationEffect), 'info/dual_column': infoDual(dualverticalbarEffect), 'info/dual_bar': infoDual(dualbarEffect), 'info/dual_line': infoDual(duallineEffect), 'info/100_stacked_column': info(stackedverticalbarEffect), 'info/100_stacked_bar': info(stackedbarEffect), 'info/horizontal_line': info(horizontallineEffect), 'info/dual_horizontal_line': infoDual(dualhorizontallineEffect), 'info/horizontal_combination': info(horizontalcombinationEffect), 'info/horizontal_stacked_combination': info(horizontalcombinationEffect), 'info/dual_horizontal_stacked_combination': infoDual(dualhorizontalcombinationEffect), 'info/treemap': infoTreemap(treemapEffect), 'info/trellis_column': trellis(info(verticalbarEffect)), 'info/trellis_bar': trellis(info(barEffect)), 'info/trellis_line': trellis(info(lineEffect)), 'info/trellis_pie': trellis(info(pieEffect)), 'info/trellis_donut': trellis(info(pieEffect)), 'info/trellis_scatter': trellis(infoBubble(bubbleEffect)), 'info/trellis_bubble': trellis(infoBubble(bubbleEffect)), 'info/trellis_stacked_column': trellis(info(stackedverticalbarEffect)), 'info/trellis_stacked_bar': trellis(info(stackedbarEffect)), 'info/trellis_combination': trellis(info(combinationEffect)), 'info/trellis_dual_column': trellis(infoDual(dualverticalbarEffect)), 'info/trellis_dual_bar': trellis(infoDual(dualbarEffect)), 'info/trellis_dual_line': trellis(infoDual(duallineEffect)), 'info/trellis_100_stacked_column': trellis(info(stackedverticalbarEffect)), 'info/trellis_100_stacked_bar': trellis(info(stackedbarEffect)), 'info/trellis_horizontal_line': trellis(info(horizontallineEffect)), 'info/trellis_dual_horizontal_line': trellis(infoDual(dualhorizontallineEffect)), 'info/trellis_horizontal_combination': trellis(info(horizontalcombinationEffect)), 'info/dual_stacked_bar': infoDual(dualstackedbarEffect), 'info/100_dual_stacked_bar': infoDual(dualstackedbarEffect), 'info/dual_stacked_column': infoDual(dualstackedverticalbarEffect), 'info/100_dual_stacked_column': infoDual(dualstackedverticalbarEffect), 'info/time_bubble': infoBubble(bubbleEffect), 'info/bullet': infoBullet(bulletEffect), 'info/vertical_bullet': infoBullet(bulletEffect), 'info/trellis_bullet': infoBullet(bulletEffect), 'info/trellis_vertical_bullet': infoBullet(bulletEffect) }, //v-hidden-title must be set after v-title //v-longtick must be set after v-categoryaxisline css: "\ .v-m-title .v-title{fill:#D8D8D8;}\ .v-subtitle{fill:#D8D8D8;}\ .v-longtick{stroke:#5e5e5e;}\ .v-title{fill:#D8D8D8;}\ .v-hidden-title{fill:#737373;}\ .v-label{fill:#D8D8D8;}\ .v-background-body{fill:#1B1B1B;}\ .v-pie .v-donut-title{fill:#D8D8D8;}\ .v-polar-axis-label{fill:#D8D8D8;}\ .v-datalabel{fill:#D8D8D8;}\ .v-hoverline{stroke:#606060;}\ .v-hovershadow{fill:#606060;}\ .v-hovershadow-mousedown{fill:#cccccc;}\ .v-m-tooltip .v-background{background-color:#000000; border-color:#ffffff; fill:#1B1B1B;stroke:#FFFFFF;}\ .v-m-tooltip .v-footer-label{color:#ffffff; fill:#D8D8D8;}\ .v-m-tooltip .v-body-dimension-label{color:#c0c0c0;}\ .v-m-tooltip .v-body-dimension-value{color:#c0c0c0;}\ .v-m-tooltip .v-body-measure-label{color:#c0c0c0;}\ .v-m-tooltip .v-body-measure-value{color:#ffffff;}\ .v-m-tooltip .v-separationline{border-bottom-color:#ffffff;}\ .v-m-tooltip .v-closeButton{background-color:#000000;border-color:#ffffff;}\ .v-datapoint-default{stroke:#000000}\ .v-datapoint-hover{stroke:#999999}\ .v-datapoint-selected{stroke:#999999}\ .v-datapoint .v-boxplotmidline{stroke:#ffffff}\ .v-scrollbarThumb{fill:#c0c0c0}\ " }); function infoBullet(obj) { var ret = info(obj); ret.valueAxis.title.visible = false; ret.categoryAxis.title.visible = false; ret.plotArea.gridline.visible = true; ret.title = {}; ret.title.style = {}; ret.title.style.color = "#d8d8d8"; return ret; } function trellis(obj){ obj.rowAxis = { color : axisColor, label : { style : { color : axisColor } }, hoverShadow: { color: "#606060" }, mouseDownShadow: { color: "#cccccc" } }; obj.columnAxis = { color : axisColor, label : { style : { color : axisColor } }, hoverShadow: { color: "#606060" }, mouseDownShadow: { color: "#cccccc" } }; obj.plotArea = obj.plotArea || {}; obj.plotArea.gridline = merge(obj.plotArea.gridline || {}, { zeroLine: { color: "#303030" } }); obj.plotArea.cellGrid = { color: axisGridlineColor }; return obj; } function info(obj) { var ret = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) { ret[i] = obj[i]; } } ret.valueAxis = merge(axis, hideInfoAxisLine, gridline, { }); ret.categoryAxis = merge(axis, { hoverShadow: { color: "#606060" }, mouseDownShadow: { color: "#cccccc" } }); ret.plotArea.scrollbar = scrollbar; ret.plotArea.gridline = merge(ret.plotArea.gridline || {}, { zeroLine: { unhighlightAxis: false } }); general(ret); return ret; } function infoDual(obj) { var ret = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) { ret[i] = obj[i]; } } ret.valueAxis = merge(axis, hideInfoAxisLine, gridline, dual); delete ret.valueAxis.color; ret.categoryAxis = merge(axis, { hoverShadow: { color: "#606060" }, mouseDownShadow: { color: "#cccccc" } }); ret.valueAxis2 = merge(axis, hideInfoAxisLine, dual); delete ret.valueAxis2.color; ret.plotArea.scrollbar = scrollbar; general(ret); return ret; } function infoBubble(obj) { var ret = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) { ret[i] = obj[i]; } } ret.valueAxis = merge(axis, gridline, showInfoAxisLine); ret.valueAxis2 = merge(axis, hideInfoAxisLine); ret.plotArea.scrollbar = scrollbar; general(ret); return ret; } function infoTreemap(obj) { var ret = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) { ret[i] = obj[i]; } } ret.plotArea = {}; ret.plotArea.background = {}; ret = merge(background, ret, title); general(ret); return ret; } function general(obj) { obj.plotArea = obj.plotArea || {}; obj.plotArea.background = obj.background; delete obj.background; delete obj.xAxis; delete obj.xAxis2; delete obj.yAxis; delete obj.yAxis2; var gen = obj.general = obj.general || {}; gen.background = { color: "#1B1B1B" }; if (!obj.plotArea.gridline) { obj.plotArea.gridline = {}; } obj.plotArea.gridline.color = axisGridlineColor; obj.legend = obj.legend || {}; obj.legend.hoverShadow = { color: "#606060" }; obj.legend.mouseDownShadow = { color: "#cccccc" }; } })();
/** * title: Address.jsx * * date: 12/23/2019 * * author: javier olaya * * description: component to get users Address */ import React from 'react'; import PropTypes from 'prop-types'; import Picture from './Picture'; import SaveIcon from '../pictures/SaveIcon.svg'; import Search from '../pictures/Search.svg'; /** * * * @param {*} props * @returns jsx component */ const Address = props => { const { getText, searchText, saveLoc } = props; return ( <div className="row save"> <Picture picture={Search} /> <div className="column"> <input type="text" value={searchText} onChange={getText} placeholder={searchText} /> </div> <div className="column" onClick={saveLoc} role="button" tabIndex="0"> <Picture picture={SaveIcon} /> </div> </div> ); }; export default Address; Address.propTypes = { getText: PropTypes.func, searchText: PropTypes.string, saveLoc: PropTypes.func }; Address.defaultProps = { getText: null, searchText: null, saveLoc: null };
import { createStore, applyMiddleware, compose } from 'redux' import rootReducer from '../reducers/rootReducer' import initialState from './initialState'; import logger from 'redux-logger' // Without configuration import thunk from 'redux-thunk' const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; export default function() { return createStore( rootReducer, initialState, composeEnhancers(applyMiddleware(logger, thunk)) ) }
const formidable = require("formidable"); const fs = require("fs"); const Upload = require("../models/upload"); exports.getAllUpload = (req, res) => { Upload.find({}) .sort({ date: -1 }) .exec((err, data) => { if (err) throw err; res.render("home", { data: data }); }); }; // POST all upload exports.createUpload = (req, res) => { let form = new formidable.IncomingForm(); form.keepExtensions = true; form.parse(req, (err, fields, file) => { if (err) { return res.status(400).json({ error: "problem with image", }); } // destructure the fields const { name, email } = fields; // Restriction on product fields if (!name || !email) { return res.status(400).json({ error: "Please include all fields", }); } let upload = new Upload(fields); // handle file here if (file.photo) { if (file.photo.size > 3000000) { return res.status(400).json({ error: "File size is too large!", }); } upload.photo.data = fs.readFileSync(file.photo.path); upload.photo.contentType = file.photo.type; } // save to the DB upload.save((err, upload) => { if (err) { res.status(400).json({ error: "Saving Tshirt in db failed", }); } res.redirect("/"); console.log(upload); }); }); };
/** * The baseclass for queryengines * @abstract */ Freja.QueryEngine = function() {}; Freja.QueryEngine.prototype.getElementById = function(document, id) { // getElementById doesn't work on XML document without xml:id var allElements = document.getElementsByTagName("*"); for (var i= 0; i < allElements.length; i++) { if (allElements[i].getAttribute("id") == id) { return allElements[i]; } } }; Freja.QueryEngine.prototype.get = function(document, expression) { var node = this._find(document, expression); if(!node) throw new Error("Can't evaluate expression " + expression); switch(node.nodeType) { case 1: /* element */ // return content of text nodes // @TO-DO: return more than just firstchild? if(node.firstChild && (node.firstChild.nodeType == 3 || node.firstChild.nodeType == 4)) { return node.firstChild.nodeValue; } break; case 2: /* Attribute */ return node.nodeValue; break; case 3: /* text node */ // fall through case 4: /* CDATA section */ return node.nodeValue; break; } return null; }; Freja.QueryEngine.prototype.set = function(document, expression, value) { var node = this._find(document, expression); if(!node) { // Could not evaluate expression. // Check if we're trying to set a non-existent attribute var nodeName = expression.substr(expression.lastIndexOf('/')+1); if(nodeName.charAt(0)=='@') { // Let's try to create the attribute. var parentExpression = expression.substring(0, expression.lastIndexOf('/')); var pNode = this._find(document, parentExpression); if(pNode) { pNode.setAttribute(nodeName.substr(1),value); return; } // else parent node non existent either, give up. } // not an attribute, give up. throw new Error("Can't evaluate expression " + expression); } // Expression succesfully evaluated. Set content switch(node.nodeType) { case 1: /* element */ // @TO-DO: set more than just firstchild if(node.firstChild && (node.firstChild.nodeType == 3 || node.firstChild.nodeType == 4)) { node.firstChild.nodeValue = value; } else { if(value!="") // prevent a subsequent IE7/MSXML3 crash in view rendering. node.appendChild(document.createTextNode(value)); } break; case 2: /* Attribute */ node.nodeValue = value; break; case 3: /* text node */ // fall through case 4: /* CDATA section */ node.nodeValue = value; break; } return ; }; /** * XPath query engine. */ Freja.QueryEngine.XPath = function() {}; Freja.Class.extend(Freja.QueryEngine.XPath, Freja.QueryEngine); Freja.QueryEngine.XPath.prototype._find = function(document, expression) { var result = document.selectSingleNode(expression); return result; }; /** * SimplePath */ Freja.QueryEngine.SimplePath = function() {}; Freja.Class.extend(Freja.QueryEngine.SimplePath, Freja.QueryEngine); Freja.QueryEngine.SimplePath.prototype._find = function(document, expression) { if (!expression.match(/^[\d\w\/@\[\]=_\-']*$/)) { throw new Error("Can't evaluate expression " + expression); } var parts = expression.split("/"); var node = document; var regAttr = new RegExp("^@([\\d\\w]*)"); var regOffset = new RegExp("^([@\\d\\w]*)\\[([\\d]*)\\]$"); var regFilter = new RegExp("^([\\d\\w]+)\\[@([@\\d\\w]+)=['\"]{1}(.*)['\"]{1}\\]$"); var attr = null; var offset = 0; for (var i = 0; i < parts.length; ++i) { var part = parts[i]; var filter = regFilter.exec(part); if(filter) { // filter[1] element name, filter[2] attribute name, filter[3] attribute value if(i>0 && parts[i-1]=='') { // expression was of type //element[...] var cn = node.getElementsByTagName(filter[1]); } else { var cn = node.childNodes; } for(var j=0, l=cn.length; j<l ; j++) { if(cn[j].nodeType==1 && cn[j].tagName==filter[1] && cn[j].getAttribute(filter[2])== filter[3]) { node = cn[j]; break; } } if (j==l) throw new Error("Can't evaluate expression " + part); } else { offset = regOffset.exec(part); if (offset) { part = offset[1]; offset = offset[2] - 1; } else { offset = 0; } if (part != "") { attr = regAttr.exec(part); if (attr) { node = node.getAttributeNode(attr[1]); } else { node = node.getElementsByTagName(part).item(offset); } } } } if (node && node.firstChild && node.firstChild.nodeType == 3) { return node.firstChild; } if (node && node.firstChild && node.firstChild.nodeType == 4) { return node.firstChild; } if (!node) { throw new Error("Can't evaluate expression " + expression); } return node; };
const express = require('express'); const mongose = require('mongoose'); const config = require('./config'); const authController = require('./app/controllers/auth.controller'); const morgan = require('morgan'); const bodyParser = require('body-parser'); const app = express(); let port = process.env.PORT || 1337; mongose.connect(config.database); app.set('superSecret', config.secret); // secret variable app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(morgan('dev')); //logs in console app.use('/api', require('./app/routes/auth.routes')); // app.use('*', authController.checkToken); // seeds if db is empty // app.get('/projects', (req, res) => { // res.sendfile('./public/index.html'); // }); app.listen(port);
import React, { useState, useEffect } from 'react'; import sqlFormatter from 'sql-formatter'; import { Button, Row, Col, message, } from 'antd'; import brace from 'brace'; import 'brace/theme/sqlserver'; import 'brace/mode/mysql'; import AceEditor from 'react-ace'; const handleOnload = (e) => { // console.log('load', e); }; const IndexPage = () => { const [formatSql, setFormatSql] = useState(''); const [beforeSql, setBeforeSql] = useState(''); const handleFormatSql = () => { const newFormatSql = sqlFormatter.format(beforeSql); setFormatSql(newFormatSql); // message.success('format success', 0.5); }; const handleEditorChange = (value) => { setBeforeSql(value); }; return ( <div className="sql-formatter"> <Button type="primary" style={{ textAlign: 'center', margin: '0 auto 20px', display: 'block' }} onClick={handleFormatSql}>格式化SQL</Button> <Row type="flex" justify="space-around"> <Col className="editorContainer" span={11}> <AceEditor mode="mysql" theme="sqlserver" name="blah2" onLoad={handleOnload} onChange={handleEditorChange} fontSize={14} height="1000px" width="100%" showPrintMargin showGutter highlightActiveLine wrapEnabled value={beforeSql} setOptions={{ enableBasicAutocompletion: false, enableLiveAutocompletion: false, enableSnippets: false, showLineNumbers: true, tabSize: 2, }} /> </Col> <Col className="editorContainer" span={11}> <AceEditor mode="mysql" theme="sqlserver" name="blah3" height="1000px" width="100%" onLoad={handleOnload} onChange={handleEditorChange} fontSize={14} showPrintMargin showGutter highlightActiveLine wrapEnabled value={formatSql} setOptions={{ enableBasicAutocompletion: false, enableLiveAutocompletion: false, enableSnippets: false, showLineNumbers: true, tabSize: 2, }} /> </Col> </Row> <style jsx global>{` .sql-formatter { width:100%; padding:10px 20px; } .editorContainer { border: 1px dashed grey; } `} </style> </div> ); }; export default IndexPage;
var checksum = require('../../model/checksum'); var config = require('../../config/config'); module.exports = function (app) { app.post('/pgredirect', function(req,res){ console.log("in pgdirect"); res.render('pgredirect.ejs',{'config' : config}); }); }; //vidisha
// 搜索接口 // 请求相关函数 const { get } = require('../request') // utils const { getRandomVal, mergeSinger } = require('../utils') // 歌曲图片加载失败时使用的默认图片 const fallbackPicUrl = 'https://y.gtimg.cn/mediastyle/music_v11/extra/default_300x300.jpg?max_age=31536000' // 响应成功code const CODE_OK = 0 const token = 5381 // 注册热门搜索接口 function registerHotKeys (app) { app.get('/api/getHotKeys', (req, res) => { const url = 'https://c.y.qq.com/splcloud/fcgi-bin/gethotkey.fcg' get(url, { g_tk_new_20200303: token }).then((response) => { const data = response.data if (data.code === CODE_OK) { res.json({ code: CODE_OK, result: { hotKeys: data.data.hotkey.map((key) => { return { key: key.k, id: key.n } }).slice(0, 10) } }) } else { res.json(data) } }) }) } // 注册搜索查询接口 function registerSearch (app) { app.get('/api/search', (req, res) => { const url = 'https://c.y.qq.com/soso/fcgi-bin/search_for_qq_cp' const { query, page, showSinger } = req.query const data = { _: getRandomVal(), g_tk_new_20200303: token, w: query, p: page, perpage: 20, n: 20, zhidaqu: 1, catZhida: showSinger === 'true' ? 1 : 0, t: 0, flag: 1, ie: 'utf-8', sem: 1, aggr: 0, remoteplace: 'txt.mqq.all', uin: '0', needNewCode: 1, platform: 'h5', format: 'json' } get(url, data).then((response) => { const data = response.data if (data.code === CODE_OK) { const songList = [] const songData = data.data.song const list = songData.list list.forEach((item) => { const info = item if (info.pay.payplay !== 0 || !info.interval) { // 过滤付费歌曲 return } const song = { id: info.songid, mid: info.songmid, name: info.songname, singer: mergeSinger(info.singer), url: '', duration: info.interval, pic: info.albummid ? `https://y.gtimg.cn/music/photo_new/T002R800x800M000${info.albummid}.jpg?max_age=2592000` : fallbackPicUrl, album: info.albumname } songList.push(song) }) let singer const zhida = data.data.zhida if (zhida && zhida.type === 2) { singer = { id: zhida.singerid, mid: zhida.singermid, name: zhida.singername, pic: `https://y.gtimg.cn/music/photo_new/T001R800x800M000${zhida.singermid}.jpg?max_age=2592000` } } const { curnum, curpage, totalnum } = songData const hasMore = 20 * (curpage - 1) + curnum < totalnum res.json({ code: CODE_OK, result: { songs: songList, singer, hasMore } }) } else { res.json(data) } }) }) } module.exports = { registerHotKeys, registerSearch }
'use strict'; var React = require('react'); var UIKernel = require('uikernel'); var createClass = require('create-react-class'); var RecordForm = createClass({ mixins: [UIKernel.Mixins.Form], componentDidMount: function () { this.initForm({ fields: ['name', 'phone', 'age', 'gender'], changes: this.props.changes, model: this.props.model, submitAll: this.props.mode === 'create', partialErrorChecking: this.props.mode === 'create' }) }, save: function (e) { e.preventDefault(); this.submit(function (err, response) { if (!err) { this.props.onSubmit(response) } }.bind(this)) }, render: function () { if (!this.isLoaded()) { return <span>Loading...</span> } var data = this.getData(); var globalError = this.getGlobalError(); return ( <div className='modal-dialog modal-lg'> <div className='modal-content'> <div className='modal-header'> <button type='button' className='close' onClick={this.props.onClose}> <span>&times</span> <span className='sr-only'>Close</span> </button> <h4 className='modal-title'> {this.props.mode === 'edit' ? 'Edit ' + data.name : 'Create'} </h4> </div> <div className='modal-body'> <div className='form-horizontal'> <div className='form-group'> <div className='col-sm-9 col-sm-offset-3'> <b className='text-danger'>{globalError ? globalError.message : ''}</b> </div> </div> <div className={'form-group' + (this.hasChanges('name') ? ' bg-warning' : '') + (this.hasError('name') ? ' bg-danger' : '')} > <label className='col-sm-3 control-label'>First Name</label> <div className='col-sm-9'> <input type='text' className='form-control' onChange={this.updateField.bind(null, 'name')} onFocus={this.clearError.bind(null, 'name')} onBlur={this.validateForm} value={data.name} /> </div> </div> <div className={'form-group' + (this.hasChanges('phone') ? ' bg-warning' : '') + (this.hasError('phone') ? ' bg-danger' : '')} > <label className='col-sm-3 control-label'>Phone</label> <div className='col-sm-9'> <input type='text' className='form-control' onChange={this.updateField.bind(null, 'phone')} onFocus={this.clearError.bind(null, 'phone')} onBlur={this.validateForm} value={data.phone} /> </div> </div> <div className={'form-group' + (this.hasChanges('age') ? ' bg-warning' : '') + (this.hasError('age') ? ' bg-danger' : '')} > <label className='col-sm-3 control-label'>Age</label> <div className='col-sm-9'> <input type='number' className='form-control' onChange={this.updateField.bind(null, 'age')} onFocus={this.clearError.bind(null, 'age')} onBlur={this.validateForm} value={data.age} /> </div> </div> <div className={'form-group' + (this.hasChanges('gender') ? ' bg-warning' : '') + (this.hasError('email') ? ' bg-danger' : '')}> <label className='col-sm-3 control-label'>Gender</label> <div className='col-sm-9'> <UIKernel.Editors.Select className='form-control' onChange={this.updateField.bind(null, 'gender')} onFocus={this.clearError.bind(null, 'gender')} onBlur={this.validateForm} options={[ ['MALE', 'Male'], ['FEMALE', 'Female'] ]} value={data.gender} /> </div> </div> </div> </div> <div className='modal-footer'> <button type='button' className='btn btn-default' onClick={this.props.onClose}>Cancel</button> <button type='button' className='btn btn-default' onClick={this.clearChanges}>Discard</button> <button type='submit' className='btn btn-primary' onClick={this.save}>Save</button> </div> </div> </div> ) } }); module.exports = RecordForm;
(function (wijmo, $, data) { 'use strict'; var grid = new wijmo.grid.FlexGrid('#mdFlexGrid'), cv = new wijmo.collections.CollectionView(data.getData(100)); grid.initialize({ autoGenerateColumns: false, columns: [ { header: 'Country', binding: 'country', width: '*' }, { header: 'Date', binding: 'date' } ], itemsSource: cv }); // init details pane updateDetails(cv.currentItem); // handle CollectionView's currentChanged event to update details cv.currentChanged.addHandler(function (sender, args) { updateDetails(sender.currentItem); }); // update the details when the CollectionView's currentItem changes function updateDetails(item) { $('#mdCurId').text(item.id); $('#mdCurCountry').text(item.country); $('#mdCurDate').text(wijmo.Globalize.format(item.date, 'd')); $('#mdCurRevenue').text(wijmo.Globalize.format(item.amount, 'c')); $('#mdCurActive').text(item.active); } })(wijmo, jQuery, appData);
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Shape = function Shape(x, y, z, c) { _classCallCheck(this, Shape); this.color = c; this.mass = z; this.curPos = new Vector(x, y, z); this.originalPos = new Vector(x, y, z); this.targetPos = new Vector(x, y); this.velocity = new Vector(0.0, 0.0); }; var Circle = function (_Shape) { _inherits(Circle, _Shape); function Circle(x, y, z, c) { _classCallCheck(this, Circle); var _this = _possibleConstructorReturn(this, (Circle.__proto__ || Object.getPrototypeOf(Circle)).call(this, x, y, z, c)); _this.radius = z; _this.start = 0; _this.end = Math.PI * 2; _this.acw = false; return _this; } _createClass(Circle, [{ key: 'draw', value: function draw(ctx) { var s = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; ctx.beginPath(); ctx.arc(this.curPos.x, this.curPos.y, this.radius, this.start, this.end, this.acw); if (s != 0) { ctx.lineWidth = 1; ctx.strokeStyle = this.color; ctx.stroke(); } else { ctx.fillStyle = this.color; ctx.fill(); } ctx.closePath(); } }, { key: 'update', value: function update() { var strength = document.springStrength; var _ref = [document.friction, document.rotationForce]; var friction = _ref[0]; var rotationFroce = _ref[1]; var dx = this.targetPos.x - this.curPos.x; var dy = this.targetPos.y - this.curPos.y; var ax = dx / this.mass - rotationFroce * dy; var ay = dy / this.mass + rotationFroce * dx; //console.log(rotationFroce) this.velocity.x += ax; this.velocity.x -= this.velocity.x * friction; this.curPos.x += this.velocity.x; this.velocity.y += ay; this.velocity.y -= this.velocity.y * friction; this.curPos.y += this.velocity.y; } }]); return Circle; }(Shape); var Square = function (_Shape2) { _inherits(Square, _Shape2); function Square(x, y, z, c) { _classCallCheck(this, Square); var _this2 = _possibleConstructorReturn(this, (Square.__proto__ || Object.getPrototypeOf(Square)).call(this, x, y, z, c)); _this2.w = z; _this2.h = z; return _this2; } _createClass(Square, [{ key: 'draw', value: function draw(ctx) { ctx.fillStyle = this.color; ctx.fillRect(this.curPos.x, this.curPos.y, this.w, this.h); } }]); return Square; }(Shape); var Line = function () { function Line(x, y, ex, ey) { var c = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'cyan'; _classCallCheck(this, Line); this.x = x; this.y = y; this.ex = ex; this.ey = ey; this.color = c; } _createClass(Line, [{ key: 'draw', value: function draw(ctx) { ctx.beginPath(); ctx.moveTo(this.x, this.y); ctx.lineTo(this.ex, this.ey); ctx.lineWidth = 2; ctx.strokeStyle = this.color; ctx.stroke(); } }]); return Line; }(); var Curve = function Curve(x, y, cpx, cpy, ex, ey) { var c = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 'orange'; _classCallCheck(this, Curve); this.x = x; this.y = y; this.ex = ex; this.ey = ey; this.cpx = cpx; this.cpy = cpy; this.color = c; }; var Cubic = function (_Curve) { _inherits(Cubic, _Curve); function Cubic(x, y, cpx, cpy, cp1x, cp1y, ex, ey, c) { _classCallCheck(this, Cubic); var _this3 = _possibleConstructorReturn(this, (Cubic.__proto__ || Object.getPrototypeOf(Cubic)).call(this, x, y, cpx, cpy, ex, ey, c)); _this3.cp1x = cp1x; _this3.cp1y = cp1y; _this3.t = 0.2; _this3.speed = 0.1; return _this3; } _createClass(Cubic, [{ key: 'draw', value: function draw(ctx) { ctx.beginPath(); ctx.moveTo(this.x, this.y); ctx.bezierCurveTo(this.cpx, this.cpy, this.cp1x, this.cp1y, this.ex, this.ey); ctx.lineWidth = 4; ctx.strokeStyle = this.color; ctx.stroke(); } }, { key: 'update', value: function update(ctx) { if (this.t >= 1 || this.t < 0) this.speed *= -1; this.speed -= this.speed * 0.01; this.t += this.speed; // point on the line same as starting point var qx = (1 - this.t) * this.x + this.t * this.cpx; var qy = (1 - this.t) * this.y + this.t * this.cpy; // point on curve tangent line var rx = (1 - this.t) * this.cpx + this.t * this.cp1x; var ry = (1 - this.t) * this.cpy + this.t * this.cp1y; // point on the line same as ending point var sx = (1 - this.t) * this.cp1x + this.t * this.ex; var sy = (1 - this.t) * this.cp1y + this.t * this.ey; // line connect three points above new Line(qx, qy, rx, ry, 'rgb(44, 122, 185)').draw(ctx); new Line(rx, ry, sx, sy, 'rgb(44, 122, 185)').draw(ctx); // point on the first moving line var ax = (1 - this.t) * qx + this.t * rx; var ay = (1 - this.t) * qy + this.t * ry; // point on the second moving line var fx = (1 - this.t) * rx + this.t * sx; var fy = (1 - this.t) * ry + this.t * sy; // line for the tip lies on new Line(ax, ay, fx, fy, 'rgb(186, 57, 68)').draw(ctx); // point of the tip var Gx = (1 - this.t) * ax + this.t * fx; var Gy = (1 - this.t) * ay + this.t * fy; // tip of the pen new Circle(Gx, Gy, 7, 'rgb(183, 228, 33)').draw(ctx); } }]); return Cubic; }(Curve);
(function () { 'use strict'; angular .module('Mobilot') .factory('LanguageService', LanguageService); LanguageService.$inject = [ '$log', '$translate' ]; function LanguageService ( $log, $translate ) { /// LanguageService var service = { /// constants LANGUAGES: { GERMAN: 'de_DE', ENGLISH: 'en_US' }, /// vars // ... /// functions switchLanguage: switchLanguage, getCurrentLanguage: getCurrentLanguage }; /// private helpers // ... /// services function getCurrentLanguage () { return $translate.use(); } function switchLanguage ( newLanguage ) { for (var l in service.LANGUAGES) { if ( service.LANGUAGES[l] == newLanguage ) { $translate.use(newLanguage); return; } } $log.error(newLanguage, 'is not supported'); } return service; } })();
import React from "react" import PropTypes from "prop-types" import style from './Notification.module.css' export default function Notification({ message }) { return ( <> <h2 className={style.title}>{message}</h2> </> ) } Notification.propTypes = { message: PropTypes.string.isRequired, }
module.exports = function(deployer) { deployer.deploy(FundingHub); deployer.autolink(); deployer.deploy(Project); }; // module.exports = function (deployer) { // var fundingHub; // deployer.then(function () { // console.log('Deploying FundingHub...'); // return FundingHub.new("FugueWeb FH"); // }).then(function (result) { // deployer.autolink(); // console.log('FundingHub: ', result.address); // fundingHub = result; // console.log('Deploying Project...'); // return result.createProject("myDefaultName", "myDefaultDesc", result.address, 400, 200); // }).then(function (tx) { // console.log('createProject tx: ', tx); // }); // };
import {Box} from "src/geo/Box.js"; import {Vector} from "src/geo/Vector.js"; import {Point} from "src/geo/Point.js"; import {codeDistanceUnitCellSize} from "src/braid/CodeDistance.js"; import {DetailedError} from "src/base/DetailedError.js"; import {UnitCellSocket} from "src/braid/UnitCellSocket.js"; import {PlumbingPiece} from "src/braid/PlumbingPiece.js"; import {Rect} from "src/geo/Rect.js"; import {XY} from "src/sim/util/XY.js"; import {seq} from "src/base/Seq.js"; import {UnitCellSocketFootprint} from "src/braid/UnitCellSocketFootprint.js"; const EXTENSION_LENGTH = 0.2; class LocalizedPlumbingPiece { /** * @param {!Point} loc Which unit cell is it in? * @param {!UnitCellSocket} socket Which socket is it in? * @param {!PlumbingPiece} piece What's in the socket? */ constructor(loc, socket, piece) { if (!(loc instanceof Point)) { throw new DetailedError("Not a Point.", {loc}); } if (!(socket instanceof UnitCellSocket)) { throw new DetailedError("Not a UnitCellSocket.", {socket}); } if (!(piece instanceof PlumbingPiece)) { throw new DetailedError("Not a PlumbingPiece.", {piece}); } this.loc = loc; this.socket = socket; this.piece = piece; } /** * @returns {!Box} */ toBox() { return this.socket.boxAt(this.loc); } /** * @param {!Vector} dirFrom The direction from the other piece to this neighbor piece. * @returns {!Box} */ toNeighborExtensionBox(dirFrom) { return clampBox(this.socket.boxAt(this.loc), dirFrom.scaledBy(-1), EXTENSION_LENGTH); } /** * @param {!int} codeDistance * @returns {!UnitCellSocketFootprint} */ toFootprint(codeDistance) { let r = this.toSocketFootprintRect(codeDistance); return UnitCellSocketFootprint.grid(r.x, r.y, r.w, r.h); } /** * @param {!int} codeDistance * @returns {!XY} */ toCellOriginXy(codeDistance) { let {w, h} = codeDistanceUnitCellSize(codeDistance); return new XY(w * this.loc.x, h * this.loc.z); } /** * @param {!int} codeDistance * @returns {!Rect} */ toSocketFootprintRect(codeDistance) { let {x, y} = this.toCellOriginXy(codeDistance); return this.socket.footprintRect(codeDistance).offsetBy(x, y); } /** * @returns {!string} */ key() { return `${this.loc}:${this.socket.name}:${this.piece.name}`; } /** * @param {![!number, !number, !number, !number]} highlight * @returns {!RenderData} */ toRenderData(highlight = undefined) { let c = [...this.piece.color]; if (highlight !== undefined) { for (let i = 0; i < 4; i++) { c[i] = 0.7 * c[i] + highlight[i] * 0.3; } } return this.toBox().toRenderData(c, this.piece.textureRect); } /** * @returns {!string} */ toString() { return `${this.loc}, ${this.socket.name}, ${this.piece.name}`; } } /** * @param {!number} v * @param {!number} epsilon * @returns {!int} */ function approximate_sign(v, epsilon=0.001) { if (Math.abs(v) < epsilon) { return 0; } return Math.sign(v); } /** * @param {!Box} box The box to clamp. * @param {!Vector} shrinkAlong An axis-aligned unit vector indicating which axis to affect and which side to move. * @param {!number} maxDiameter * @returns {!Box} */ function clampBox(box, shrinkAlong, maxDiameter) { let delta = box.diagonal.zip(shrinkAlong, (e, s) => Math.abs(s) * (e - Math.min(maxDiameter, e))); return shrinkBox(box, shrinkAlong, delta.x + delta.y + delta.z); } /** * @param {!Box} box The box to clamp. * @param {!Vector} shrinkAlong An axis-aligned unit vector indicating which axis to affect and which side to move. * @param {!number} delta The amount to shrink the box by. * @returns {!Box} */ function shrinkBox(box, shrinkAlong, delta) { let shift = shrinkAlong.pointwise(e => Math.abs(e) * delta); let baseMask = shrinkAlong.pointwise(e => e === 1 ? 1 : 0); let baseShift = baseMask.pointwiseMultiply(shift); return new Box( box.baseCorner.plus(baseShift), box.diagonal.minus(shift)); } export {LocalizedPlumbingPiece, shrinkBox, clampBox}
import React, { useState, useEffect, useRef } from "react"; import Header from "../components/Header"; import { Link as RouterLink } from "react-router-dom"; import { Flex, Text, Center, Image, Tabs, TabList, TabPanels, Tab, TabPanel, Button, Avatar, LinkBox, useColorModeValue, Skeleton, SkeletonCircle, SkeletonText, Divider, Select, useToast, } from "@chakra-ui/react"; import AccessDenial from "../assets/images/noAccess.svg"; import Empty from "../assets/images/empty.svg"; import { BiChalkboard } from "react-icons/bi"; import { IoTimeOutline, IoVideocamOutline, IoPersonCircleSharp, } from "react-icons/io5"; import { useAuth } from "../contexts/Auth"; import { db, fb } from "../firebase/Config"; import { format, formatDistance } from "date-fns"; function Administrator() { const { userData } = useAuth(); // console.log(userData); return ( <Header> {userData.level === "Admin" ? ( <AdminHeader /> ) : ( <Center flexDir="column" mt={32}> <Image src={AccessDenial} width="640" height="320" /> <Text textAlign="center" color="#a5a5a5"> Sorry, you have no access to this page. </Text> </Center> )} </Header> ); } export default Administrator; const AdminHeader = () => { return ( <Flex mt={24}> <Tabs variant="soft-rounded" colorScheme="teal" isFitted w="100%"> <TabList> <Tab>Users</Tab> <Tab>Feeds</Tab> <Tab>Class</Tab> <Tab>Materials</Tab> </TabList> <TabPanels> <TabPanel> <Users /> </TabPanel> <TabPanel> <Feeds /> </TabPanel> <TabPanel> <Class /> </TabPanel> <TabPanel> <Materials /> </TabPanel> </TabPanels> </Tabs> </Flex> ); }; const Users = () => { const [loading, setLoading] = useState(false); const [userItems, setUserItems] = useState([]); const [unApprovedUser, setUnApprovedUser] = useState([]); const [lockedUser, setLockedUser] = useState([]); const isMounted = useRef(false); useEffect(() => { isMounted.current = true; db.collection("users") .orderBy("created", "desc") .onSnapshot(function (items) { const fetchUserItems = []; const fetchUnapprovedItems = []; const fetchLockedItems = []; items.forEach((item) => { const fetchItem = { UID: item.id, ...item.data(), }; if (fetchItem.approved === false) { fetchUnapprovedItems.push(fetchItem); } else if (fetchItem.locked === true) { fetchLockedItems.push(fetchItem); } else { fetchUserItems.push(fetchItem); } }); if (isMounted.current) { setUnApprovedUser(fetchUnapprovedItems); setLockedUser(fetchLockedItems); setUserItems(fetchUserItems); //set loading to false setLoading(false); } }); return () => { isMounted.current = false; setLoading(false); }; }, []); return ( <> {loading && <UserSkeleton />} {!loading && ( <> {/* Waiting List */} {unApprovedUser.length !== 0 && ( <Text fontSize="lg" color="teal" fontWeight="bold" textAlign="center" mb="2.5" > Waiting List </Text> )} {unApprovedUser.map((users) => ( <React.Fragment key={users.UID}> {users.approved === false && ( <Flex flexDir="column"> <UserCard users={users} /> </Flex> )} </React.Fragment> ))} <Divider my="3.5" /> {/* Locked out User */} {lockedUser.length !== 0 && ( <Text fontSize="lg" color="teal" fontWeight="bold" textAlign="center" mb="2.5" > Locked Users </Text> )} {lockedUser.map((users) => ( <React.Fragment key={users.UID}> {users.locked === true && ( <Flex flexDir="column"> <UserCard users={users} /> </Flex> )} </React.Fragment> ))} <Divider my="3.5" /> {/* Approved Users */} <Text fontSize="lg" color="teal" fontWeight="bold" textAlign="center" mb="2.5" > Approved Users </Text> {userItems.map((users) => ( <React.Fragment key={users.UID}> <UserCard users={users} /> </React.Fragment> ))} </> )} </> ); }; const UserCard = ({ users }) => { const toast = useToast(); const handleDelete = (e) => { e.preventDefault(); db.collection("users") .doc(users.UID) .delete() .then(() => { toast({ title: `${users.displayName} has been deleted.`, status: "success", duration: 2000, isClosable: true, }); }) .catch((error) => { toast({ title: `Error: Unable to delete ${users.displayName}.`, status: "error", duration: 2000, isClosable: true, }); }); }; const handleApprove = (e) => { e.preventDefault(); db.collection("users") .doc(users.UID) .update({ approved: true, }) .then(() => { toast({ title: `${users.displayName} has been approved.`, status: "success", duration: 2000, isClosable: true, }); }) .catch((error) => { toast({ title: `Error: Unable to approve ${users.displayName}.`, status: "error", duration: 2000, isClosable: true, }); }); }; const handleLocked = (e) => { e.preventDefault(); console.log(e.target.value); if (users.locked === true) { db.collection("users") .doc(users.UID) .update({ locked: false, }) .then(() => { toast({ title: `${users.displayName} has been unlocked successfully.`, status: "success", duration: 2000, isClosable: true, }); }) .catch((error) => { toast({ title: `Error: Unable to unlock ${users.displayName}.`, status: "error", duration: 2000, isClosable: true, }); }); } else { db.collection("users") .doc(users.UID) .update({ locked: true, }) .then(() => { toast({ title: `${users.displayName} has been locked successfully.`, status: "success", duration: 2000, isClosable: true, }); }) .catch((error) => { toast({ title: `Error: Unable to lock ${users.displayName}.`, status: "error", duration: 2000, isClosable: true, }); }); } }; const handleLevelChange = (e) => { e.preventDefault(); db.collection("users") .doc(users.UID) .update({ level: e.target.value, }) .then(() => { toast({ title: `User Level Changed to ${e.target.value} .`, status: "success", duration: 2000, isClosable: true, }); }) .catch((error) => { toast({ title: `Error: Unable to change User Level to ${e.target.value} .`, status: "error", duration: 2000, isClosable: true, }); }); }; return ( <Flex flexDir="column" borderWidth="1px" borderRadius="8px" p="2.5" mb="1.5" > <Flex> <Avatar size="xl" src={users.photoURL} /> <Flex ml={2.5} flexDir="column" justifyContent="space-between" py="1.5"> <Text fontWeight="bold">{users.displayName}</Text> <Select w="100px" my="1.5" value={users.level} onChange={handleLevelChange} > <option value="user">user</option> <option value="Admin">Admin</option> </Select> <Text> RegDate: {format(new Date(users.created.toDate()), "do, MMMM yyyy")} </Text> </Flex> </Flex> <Flex justifyContent="space-between" mt={4}> <Button colorScheme="red" onClick={handleDelete}> Delete </Button> <Button colorScheme="blue" onClick={handleLocked}> {users.locked === true ? "Unlock" : "Lock"} </Button> <Button colorScheme="green" onClick={handleApprove} disabled={users.approved === true ? true : false} > Approve </Button> </Flex> </Flex> ); }; const UserSkeleton = () => { return ( <Flex flexDir="column" borderWidth="1px" borderRadius="8px" p="2.5" mb="1.5" > <Flex> <SkeletonCircle size="24" /> <Flex ml={2.5} flexDir="column" justifyContent="space-between" py="1.5"> <SkeletonText noOfLines={1} w="200px" /> <SkeletonText noOfLines={1} w="100px" /> <SkeletonText noOfLines={1} w="200px" /> </Flex> </Flex> <Flex justifyContent="space-between" mt={4}> <Skeleton w="80px" borderRadius="8px" h="40px" /> <Skeleton w="80px" borderRadius="8px" h="40px" /> <Skeleton w="80px" borderRadius="8px" h="40px" /> </Flex> </Flex> ); }; const Feeds = () => { const [loading, setLoading] = useState(false); const [feedItems, setFeedItems] = useState([]); const [unApprovedFeed, setUnApprovedFeed] = useState([]); const isMounted = useRef(false); useEffect(() => { isMounted.current = true; db.collection("posts") .orderBy("createdAt", "desc") .onSnapshot(function (items) { const fetchFeedItems = []; const fetchUnapprovedItems = []; items.forEach((item) => { const fetchItem = { feedID: item.id, ...item.data(), }; if (fetchItem.approved === false) { fetchUnapprovedItems.push(fetchItem); // console.log(fetchItem); } else { fetchFeedItems.push(fetchItem); } }); if (isMounted.current) { setUnApprovedFeed(fetchUnapprovedItems); setFeedItems(fetchFeedItems); //set loading to false setLoading(false); } }); return () => { isMounted.current = false; setLoading(false); }; }, []); return ( <> {loading && <FeedSkeleton />} {!loading && ( <> {/* Waiting List */} {unApprovedFeed.length !== 0 && ( <Text fontSize="lg" color="teal" fontWeight="bold" textAlign="center" mb="2.5" > Waiting List </Text> )} {unApprovedFeed.map((feed) => ( <React.Fragment key={feed.feedID}> {feed.approved === false && ( <Flex flexDir="column"> <FeedCard feed={feed} /> </Flex> )} </React.Fragment> ))} <Divider my="3.5" /> {/* Approved Users */} <Text fontSize="lg" color="teal" fontWeight="bold" textAlign="center" mb="2.5" > Approved Feeds </Text> {feedItems.map((feed) => ( <React.Fragment key={feed.feedID}> <FeedCard feed={feed} /> </React.Fragment> ))} </> )} </> ); }; const FeedCard = ({ feed }) => { // console.log(feed); const toast = useToast(); const handleDelete = (e) => { e.preventDefault(); db.collection("posts") .doc(feed.feedID) .delete() .then(() => { toast({ title: `feed has been deleted.`, status: "success", duration: 2000, isClosable: true, }); }) .catch((error) => { toast({ title: `Error: Unable to delete feed.`, status: "error", duration: 2000, isClosable: true, }); }); }; const handleApprove = (e) => { e.preventDefault(); console.log(feed.feedID); db.collection("posts") .doc(feed.feedID) .update({ approved: true, }) .then(() => { toast({ title: `Feed has been approved.`, status: "success", duration: 2000, isClosable: true, }); }) .catch((error) => { toast({ title: `Error: Unable to approve feed.`, status: "error", duration: 2000, isClosable: true, }); }); }; const time = formatDistance(new Date(feed.createdAt.toDate()), new Date(), { includeSeconds: true, addSuffix: true, }); return ( <Flex borderRadius="8" flexDir="column" boxShadow="0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)" p="4" mb="4" > <Flex mb="1.5"> <Avatar size="md" src="item.posterImage" /> <Flex flexDir="column" ml="2.5"> <Text>{feed.posterName}</Text> <Text fontSize="sm" color="{grayColor}"> {time} </Text> </Flex> </Flex> <Text noOfLines={2}>{feed.title}</Text> <Divider my="1.5" /> {feed.imageUrl && ( <Image src={feed.imageUrl} height="180" w="100%" mb="2.5" objectFit="cover" borderRadius="8" /> )} <Flex justifyContent="space-between" mt={4}> <Button colorScheme="red" onClick={handleDelete}> Delete </Button> <Button colorScheme="green" onClick={handleApprove}> Approve </Button> </Flex> </Flex> ); }; const FeedSkeleton = () => { return ( <Flex borderRadius="8" flexDir="column" boxShadow="0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)" p="4" mb="4" > {/* <LinkBox to="#" onClick={onOpen}> */} <Flex mb="1.5"> <SkeletonCircle size="12" /> <Flex flexDir="column" ml="2.5" py="2.5"> <SkeletonText noOfLines={1} w="100px" /> <SkeletonText noOfLines={1} w="100px" mt="1.5" /> </Flex> </Flex> <SkeletonText noOfLines={2} my="1.5" /> <Skeleton height="180" w="100%" /> <Flex justifyContent="space-between" mt={4}> <Skeleton w="80px" borderRadius="8px" h="40px" /> <Skeleton w="80px" borderRadius="8px" h="40px" /> </Flex> </Flex> ); }; const Class = () => { const [loading, setLoading] = useState(false); const [lessonItems, setLessonItems] = useState([]); const [unApprovedLesson, setUnApprovedLesson] = useState([]); const isMounted = useRef(false); useEffect(() => { isMounted.current = true; db.collection("lessons") .orderBy("createdAt", "desc") .onSnapshot(function (items) { const fetchLessonItems = []; const fetchUnapprovedItems = []; items.forEach((item) => { const fetchItem = { lessonID: item.id, ...item.data(), }; if (fetchItem.approved === false) { fetchUnapprovedItems.push(fetchItem); // console.log(fetchItem); } else { fetchLessonItems.push(fetchItem); } }); if (isMounted.current) { setUnApprovedLesson(fetchUnapprovedItems); setLessonItems(fetchLessonItems); //set loading to false setLoading(false); } }); return () => { isMounted.current = false; setLoading(false); }; }, []); return ( <> {loading && <ClassSkeleton />} {!loading && ( <> {/* Waiting List */} {unApprovedLesson.length !== 0 && ( <Text fontSize="lg" color="teal" fontWeight="bold" textAlign="center" mb="2.5" > Waiting List </Text> )} {unApprovedLesson.map((lesson) => ( <React.Fragment key={lesson.lessonID}> {lesson.approved === false && ( <Flex flexDir="column"> <ClassCard lesson={lesson} /> </Flex> )} </React.Fragment> ))} {/* Approved Users */} {lessonItems.length !== 0 && ( <Text fontSize="lg" color="teal" fontWeight="bold" textAlign="center" mb="2.5" > Approved Feeds </Text> )} {lessonItems.map((lesson) => ( <React.Fragment key={lesson.lessonID}> <ClassCard lesson={lesson} /> </React.Fragment> ))} {(unApprovedLesson.length === 0) & (lessonItems.length === 0) && ( <Center flexDir="column" mt={16}> <Image src={Empty} width="640" height="320" /> <Text textAlign="center" color="#a5a5a5"> Such emptiness! </Text> </Center> )} </> )} </> ); }; const ClassCard = ({ lesson }) => { const grayColor = useColorModeValue("gray.600", "gray.400"); const toast = useToast(); let type = ""; if (lesson.classType === "Video") { type = <IoVideocamOutline fontSize="1.2em" color="black" />; } else { type = <BiChalkboard fontSize="1.2em" color="black" />; } //getting the first name from user let firstName = lesson.uploaderName.split(" "); firstName = firstName[firstName.length - 1]; //formatting time let to = tConvert(lesson.timeTo); let from = tConvert(lesson.timeFrom); function tConvert(time) { // Check correct time format and split into components time = time .toString() .match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time]; if (time.length > 1) { // If time format correct time = time.slice(1); // Remove full string match value time[5] = +time[0] < 12 ? "am" : "pm"; // Set AM/PM time[0] = +time[0] % 12 || 12; // Adjust hours } return time.join(""); // return adjusted time or original string } const handleDelete = (e) => { e.preventDefault(); db.collection("lessons") .doc(lesson.lessonID) .delete() .then(() => { toast({ title: `Lesson has been deleted.`, status: "success", duration: 2000, isClosable: true, }); }) .catch((error) => { toast({ title: `Error: Unable to Lesson feed.`, status: "error", duration: 2000, isClosable: true, }); }); }; const handleApprove = (e) => { e.preventDefault(); console.log(lesson.feedID); db.collection("lessons") .doc(lesson.lessonID) .update({ approved: true, }) .then(() => { toast({ title: `Feed has been approved.`, status: "success", duration: 2000, isClosable: true, }); }) .catch((error) => { toast({ title: `Error: Unable to approve feed.`, status: "error", duration: 2000, isClosable: true, }); }); }; return ( <Flex flexDir="column" borderRadius="4" borderColor={grayColor} p="2" mb="3.5" w="100%" boxShadow="0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)" > <Flex flexDir="column" p="2"> <Flex as="button"> <Flex className="lessonIcon" flexDir="column" bg="teal.100" borderRadius="4" alignItems="center" justifyContent="center" p="1.5" w="30%" h="3.0rem" > {type} <Text fontSize="0.5em" fontWeight="black" color="black"> {lesson.classType} Class </Text> </Flex> <Flex ml="1.5" flexDir="column" justifyContent="space-between" w="78%" h="3.0rem" > <Text textAlign="start" isTruncated> {lesson.title} </Text> <Flex flexDir="row" justifyContent="space-between"> <Flex alignItems="center"> <IoPersonCircleSharp color={grayColor} /> <Text color={grayColor} fontSize="xs" ml="0.5"> {firstName} </Text> </Flex> <Flex alignItems="center"> <IoTimeOutline color={grayColor} /> <Text color={grayColor} fontSize="xs" ml="0.5"> {from} - {to} </Text> </Flex> </Flex> </Flex> </Flex> </Flex> <Flex mt={4} justifyContent="flex-end"> <Button mr="2.5" colorScheme="red" onClick={handleDelete}> Delete </Button> <Button colorScheme="green" onClick={handleApprove}> Approve </Button> </Flex> </Flex> ); }; const ClassSkeleton = () => { const grayColor = useColorModeValue("gray.600", "gray.400"); return ( <Flex flexDir="column" borderRadius="4" borderColor={grayColor} p="2" mb="3.5" w="100%" boxShadow="0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)" > <LinkBox to="#" as={RouterLink}> <Flex flexDir="column" p="2"> <Flex as="button"> <Flex className="lessonIcon" flexDir="column" borderRadius="4" alignItems="center" justifyContent="center" p="1.5" w="20%" h="3.0rem" > <Skeleton w="60px" borderRadius="8px" height="80px" /> </Flex> <Flex ml="2.5" flexDir="column" justifyContent="space-between" w="78%" h="3.0rem" > <SkeletonText noOfLines={1} w="200px" /> <Flex flexDir="row" justifyContent="space-between"> <Flex alignItems="center"> <SkeletonCircle size="5" /> <SkeletonText noOfLines={1} w="100px" /> </Flex> <Flex alignItems="center"> <SkeletonCircle size="5" /> <SkeletonText noOfLines={1} w="50px" /> </Flex> </Flex> </Flex> </Flex> </Flex> </LinkBox> <Flex mt={4} justifyContent="flex-end"> <Skeleton w="80px" borderRadius="8px" h="40px" mr="2.5" /> <Skeleton w="80px" borderRadius="8px" h="40px" /> </Flex> </Flex> ); }; const Materials = () => { const [loading, setLoading] = useState(false); const [materialItems, setMaterialItems] = useState([]); const [unApprovedMaterial, setUnApprovedMaterial] = useState([]); const isMounted = useRef(false); useEffect(() => { isMounted.current = true; db.collection("materials") .orderBy("time", "desc") .onSnapshot(function (items) { const fetchMaterialItems = []; const fetchUnapprovedItems = []; items.forEach((item) => { const fetchItem = { materialID: item.id, ...item.data(), }; if (fetchItem.approved === false) { fetchUnapprovedItems.push(fetchItem); // console.log(fetchItem); } else { fetchMaterialItems.push(fetchItem); // console.log(fetchItem); } }); if (isMounted.current) { setUnApprovedMaterial(fetchUnapprovedItems); setMaterialItems(fetchMaterialItems); //set loading to false setLoading(false); } }); return () => { isMounted.current = false; setLoading(false); }; }, []); return ( <> {loading && <MaterialSkeleton />} {!loading && ( <> {/* Waiting List */} {unApprovedMaterial.length !== 0 && ( <Text fontSize="lg" color="teal" fontWeight="bold" textAlign="center" mb="2.5" > Waiting List </Text> )} {unApprovedMaterial.map((material) => ( <React.Fragment key={material.materialID}> {material.approved === false && ( <Flex flexDir="column"> <MaterialCard material={material} /> </Flex> )} </React.Fragment> ))} {/* Approved Users */} {materialItems.length !== 0 && ( <Text fontSize="lg" color="teal" fontWeight="bold" textAlign="center" my="2.5" > Approved Feeds </Text> )} {materialItems.map((material) => ( <React.Fragment key={material.materialID}> <MaterialCard material={material} /> </React.Fragment> ))} {(unApprovedMaterial.length === 0) & (materialItems.length === 0) && ( <Center flexDir="column" mt={16}> <Image src={Empty} width="640" height="320" /> <Text textAlign="center" color="#a5a5a5"> Such emptiness! </Text> </Center> )} </> )} </> ); }; const MaterialCard = ({ material }) => { const grayColor = useColorModeValue("gray.600", "gray.400"); const toast = useToast(); const handleDelete = (e) => { e.preventDefault(); const fileName = material.title.split(" ").join("_"); const file = `${fileName}.${material.fileType}`; // console.log(file); db.collection("materials") .doc(material.materialID) .delete() .then(() => { // Create a reference to the file to delete let storageRef = fb.storage().ref().child(`materials/${file}`); // Delete the file storageRef .delete() .then(() => { // File deleted successfully toast({ title: `Material has been deleted.`, status: "success", duration: 2000, isClosable: true, }); }) .catch((error) => { // Uh-oh, an error occurred! console.log(error); }) .catch((error) => { toast({ title: `Error: Unable to Lesson material.`, status: "error", duration: 2000, isClosable: true, }); }); }); }; const handleApprove = (e) => { e.preventDefault(); console.log(material.materialID); db.collection("materials") .doc(material.materialID) .update({ approved: true, }) .then(() => { toast({ title: `Material has been approved.`, status: "success", duration: 2000, isClosable: true, }); }) .catch((error) => { toast({ title: `Error: Unable to approve material.`, status: "error", duration: 2000, isClosable: true, }); }); }; return ( <Flex flexDir="column" borderY="1px" p="2"> <Flex flexDir="row" p="1" justifyContent="space-between" alignItems="center" mb="1.5" > <Flex flexDir="column" w="100%"> <Text fontSize="xl" fontWeight="bold" pb="2.5"> {material.title} </Text> <Text fontSize="lg" color={grayColor}> Category: {material.category} </Text> <Text fontSize="lg" color={grayColor}> Format: {material.fileType} </Text> </Flex> </Flex> <Flex mt={4} justifyContent="flex-end"> <Button mr="2.5" colorScheme="red" onClick={handleDelete}> Delete </Button> <Button colorScheme="green" onClick={handleApprove} disabled={material.approved === true ? true : false} > Approve </Button> </Flex> </Flex> ); }; const MaterialSkeleton = () => { return ( <Flex flexDir="column" borderY="1px" p="2"> <LinkBox to="#" as={RouterLink}> <Flex flexDir="row" p="1" justifyContent="space-between" alignItems="center" mb="1.5" > <Flex flexDir="row" alignItems="center"> <Flex bg="" p="2" m="2" borderRadius="4"> <Skeleton w="50px" borderRadius="8px" h="40px" /> </Flex> <Flex flexDir="column" justifyContent="space-between"> <SkeletonText noOfLines={2} w="200px" /> </Flex> </Flex> </Flex> </LinkBox> <Flex mt={4} justifyContent="flex-end"> <Skeleton w="80px" borderRadius="8px" h="40px" mr="2.5" /> <Skeleton w="80px" borderRadius="8px" h="40px" /> </Flex> </Flex> ); };
var Phaser = Phaser || {}; var CrazyBird = CrazyBird || {}; CrazyBird.Cat = function(gameState, position, texture, group, properties) { "use strict"; CrazyBird.Prefab.call(this, gameState, position, texture, group, properties); game.physics.p2.enable(this); this.body.setCollisionGroup(this.gameState.collideGroups['cat']); this.body.collides([this.gameState.collideGroups['bird']]); this.body.static = true; }; CrazyBird.Cat.prototype = Object.create(CrazyBird.Prefab.prototype); CrazyBird.Cat.prototype.constructor = CrazyBird.Cat; CrazyBird.Cat.prototype.update = function () { "use strict"; }
'use strict' import { Meteor } from 'meteor/meteor'; import { Counts } from 'meteor/tmeasday:publish-counts'; import { Feeds } from '../imports/api/feeds'; Meteor.publish('feeds', function(options, searchString) { var user = Meteor.users.findOne({ _id: this.userId }); if(options.sort) { var where = { 'title': { '$regex': '.*' + (searchString || '') + '.*', '$options': 'i' }, '_id': { '$in': user.subscriptions || [] } }; } else { //console.log("options is..", options); var where = { 'title': { '$regex': '.*' + (searchString || '') + '.*', '$options': 'i' } //,{ //'_id': { // '$nin': user.subscriptions || [] //} }; } Counts.publish(this, 'numberOfFeeds', Feeds.find(where), {noReady: true}); return Feeds.find(where, options); });
import React from 'react' import './category-item.styles.scss' import {withRouter} from 'react-router-dom' const CategoryItem = ({categoryId,imageUrl,history,match}) => ( <div className='collection-item'> <div className='image' onClick={()=>history.push(`${match.url}/${categoryId}`)} style={{backgroundImage:`url(${imageUrl})`}} /> <div className='collection-footer'> <div className='name'>{categoryId}</div> </div> </div> ) export default withRouter(CategoryItem);
module.exports = function(Item){ //Item.disableRemoteMethod("create", true); Item.disableRemoteMethod("upsert", true); Item.disableRemoteMethod("updateAll", true); Item.disableRemoteMethod("updateAttributes", true); Item.disableRemoteMethod("find", true); Item.disableRemoteMethod("findById", true); Item.disableRemoteMethod("findOne", true); Item.disableRemoteMethod("deleteById", true); Item.disableRemoteMethod("exists", true); Item.disableRemoteMethod("count", true); Item.disableRemoteMethod("createChangeStream", true); }
$(function() { var categories = []; var names = []; var tabs = []; // create tab names and categories from result-list items $("#source-list-results > li ").each(function() { categories.push($(this).attr("data-category")); names.push($(this).attr("data-name")); }); var dups = []; $.each(categories, function(i, val){ if (dups.indexOf(val) == -1) { tabs.push({ label: names[i], category: val }); } dups.push(val); }); tabs.sort(tabSort); // watch for new tabs and attach tabs click event $("#list-filter-tabs > ul") .on("click", "li > a", function() { var tab_category = $(this).attr("data-category"); // toggle active tab $("#list-filter-tabs > ul li").each(function() { var current_tab = $(this).find("a").attr("data-category"); if(current_tab == tab_category) { $(this).addClass("active"); } else { $(this).removeClass("active"); }; }); // filter list results $("#source-list-results > li").each(function(i, val){ var item_category = $(this).attr("data-category"); if (tab_category == "all") { $(this).show();} else { if (tab_category == item_category) { $(this).show(); } else { $(this).hide(); } } }) }); // create tabs $.each(tabs, function(i, val) { $("#list-filter-tabs > ul") .append('<li class="' + val.category + '">' + '<a href="#" data-category="' + val.category + '"><i class="icon-chevron-right"></i>' + val.label + '</a></li>'); }); function tabSort(a,b) { if (a.label < b.label) { return -1; } if (a.label > b.label) { return 1; } return 0; } });
const mongoose = require('mongoose'); const Tipo = mongoose.model('Tipo', { nombre: String, foto: String, descripcion: String, modoPreparacion: Array, beneficios: Array }); module.exports = Tipo;
import logo from "./logo.svg"; import "./App.css"; import { CourierProvider } from "@trycourier/react-provider"; import { Toast } from "@trycourier/react-toast"; import { Inbox } from "@trycourier/react-inbox"; function App() { return ( <div className="App"> <header className="App-header"> <CourierProvider clientKey={"YTk4MGVmNWUtMWMzMS00OTQxLWI4Y2MtZDA0ZDViNDM3ZmU2"} userId={"courier-333"} > <Toast /> </CourierProvider> </header> </div> ); } export default App;
import React, { Component } from "react"; import { Link } from "react-router-dom"; import isEmpty from "../../../validation/is-empty"; import { Redirect } from "react-router-dom"; import { addMovieToCollection, removeMovieFromCollection } from "../../../actions/movieActions"; import PropTypes from "prop-types"; // Redux import { connect } from "react-redux"; export class MovieDetails extends Component { back = () => { this.props.history.push(`/`); }; render() { if (isEmpty(this.props.movies.detailsMovie)) { return <Redirect to="/" />; } else { const { isAuthenticated } = this.props.auth; const { backdrop_path, id, original_title, overview, poster_path, release_date, title, vote_average } = this.props.movies.detailsMovie; const { myMovies } = this.props.movies; const year = release_date.slice(0, 4); let componentButtons; if (isAuthenticated) { if (myMovies.some(movie => parseInt(movie.movie_id) === id)) { componentButtons = ( <button onClick={() => this.props.removeMovieFromCollection(id)} className="button button-red" > Remove </button> ); } else { componentButtons = ( <button onClick={() => this.props.addMovieToCollection(this.props.movies.detailsMovie) } className="button button-green" > Add </button> ); } } else { componentButtons = ( <Link to="/login"> <button className="button button-green">Login</button> </Link> ); } return ( <section className="section-moviedetails"> <div className="back-button"> <button className="button button-red" onClick={this.back}> Back </button> </div> <div className="section-moviedetails-back" style={{ background: `url("http://image.tmdb.org/t/p/w1280/${backdrop_path}") no-repeat center center / cover` }} /> <div className="section-moviedetails-body"> <div className="section-moviedetails-body-image"> <img alt="Movie poster" src={`http://image.tmdb.org/t/p/w185/${poster_path}`} /> </div> <div className="section-moviedetails-body-text"> <div> <h2 className="section-moviedetails-title-primary">{title}</h2> <h3 className="section-moviedetails-title-secondary"> {original_title} </h3> </div> <h4>{year}</h4> <p>{overview}</p> </div> <div className="section-movie-details-vote"> <h1>{vote_average}</h1> {componentButtons} </div> </div> </section> ); } } } MovieDetails.propTypes = { auth: PropTypes.object.isRequired, movies: PropTypes.object.isRequired, addMovieToCollection: PropTypes.func.isRequired, removeMovieFromCollection: PropTypes.func.isRequired }; const mapStateToProps = state => ({ auth: state.auth, movies: state.movies }); export default connect( mapStateToProps, { addMovieToCollection, removeMovieFromCollection } )(MovieDetails);
import React from 'react' import './mineInfo.css' import { connect } from 'react-redux' import { withRouter } from 'react-router-dom' import ChangeStNo from './changeStNo/changeStNo' class MineInfo extends React.Component { goto_changeAavatar(){ this.props.history.push("/mine/ChangeAvatar") } render() { return ( <div className='mineInfo'> <div className="mineInfo-bg"></div> <div className="mineInfo-wrap"> <div className="mineInfo-info"> <div className="mineInfo-info-avatar"> <img onClick={()=>{this.goto_changeAavatar()}} width="80" height="80" src={this.props.userInfo.stAvatar} alt="" /> </div> <div className="mineInfo-info-desc"> <div className="mineInfo-info-desc-username">{this.props.userInfo.stName}</div> <div className="mineInfo-info-desc-className"> 班级:{this.props.userInfo.clName} <ChangeStNo/> </div> </div> </div> </div> </div> ) } } const mapStateToProps = state => { return { userInfo: state.userInfo } } export default withRouter(connect(mapStateToProps, null)(MineInfo))
// pages/order/order.js let app = getApp(); let baseUrl = app.globalData.baseUrl; const utils = require('../../utils/util.js') const regeneratorRuntime = require('../../lib/runtime') var page = 1; Page({ /** * 页面的初始数据 */ data: { showModel:false, cur:'', index:'', Tindex:'', statuindex:'', contarct:[ { id:'', typeTxt:'全部类型' }, { id:1, typeTxt:'新增' }, { id:2, typeTxt:'续签' }, { id:3, typeTxt:'赠送' }, ], status:[ { id: '', txt: '全部' }, { id:1, txt:'正常' }, { id:2, txt:'退款' } ], w_cur: '', stuType_cur: '', lesson_cur:'', noResult:'', hasMoreData: true, page_size:10, page:1, contentlist:[], satrtdate:'', enddate:'', name:'' }, addOrder:function(){ wx.navigateTo({ url: '../chooseClass/chooseClass?from_page=order' }); }, select:function(){ var model=this.data.showModel; var that=this; if(model){ that.setData({ showModel:false }) }else{ that.setData({ showModel:true }) } }, canceModel:function(){ this.setData({ showModel:false }) }, sendModel:function(){ var startDate = this.data.satrtdate; var enddate=this.data.enddate; var lesson_name =this.data.lesson_name; var lesson_id = this.data.lesson_cur; var contractId = this.data.stuType_cur;//订单类型 var status = this.data.w_cur;//是否退费 var name=this.data.name; this.setData({ showModel:false, showModalStatus: false }) this.shaiCon(startDate, enddate, lesson_id, contractId, name, status, 1, 10); }, getNowFormatDate: function() { var token = wx.getStorageSync('token'); var date = new Date(); var seperator1 = "-"; var year = date.getFullYear(); var month = date.getMonth() + 1; var strDate = date.getDate(); if (month >= 1 && month <= 9) { month = "0" + month; } if (strDate >= 0 && strDate <= 9) { strDate = "0" + strDate; } var currentdate = year + seperator1 + month + seperator1 + strDate; var d=new Date(date); d.setDate(d.getDate()-7); var m=d.getMonth()+1; var startY=d.getFullYear(); var startM=d.getMonth()+1; var startD=d.getDate(); if(startM >= 1 && startM <= 9){ startM = "0" + startM; } if (startD >= 0 && startD <= 9) { startD = "0" + startD; } var sb=startY+'-'+startM+'-'+startD; // this.setData({ // satrtdate: sb, // enddate:currentdate // }) this.getOrderList('','','','','','',1,10); return currentdate; }, startChange: function (e) { this.setData({ satrtdate: e.detail.value }) }, endChange: function (e) { this.setData({ enddate: e.detail.value }) }, lessonChange:function(e){ var list = this.data.lessonList; var index = e.detail.value; var lesson_name = list[index].name; var lesson_id = list[index].id; this.setData({ index: e.detail.value, lesson_name: lesson_name, lesson_id: lesson_id }) //this.getlesson(lessonId, teacherId,date); }, contractChange:function(e){ var list=this.data.contarct; var index = e.detail.value; var contractId=list[index].id; var typeTxt = list[index].typeTxt; this.setData({ Tindex:index, contractId:contractId, typeTxt: typeTxt }) }, typeChange: function (e) { var list = this.data.status; var index=e.detail.value; var status = list[index].id; var typeTxt = list[index].txt; this.setData({ statuindex: e.detail.value, orderstatus: status, ordertxt: typeTxt }) }, getlesson: function (){ var token = wx.getStorageSync('token'); var that=this; wx.request({ url: baseUrl +'/api/lesson/get_list', method:'get', header:{ token: token }, data:{ page:page, page_size:100, }, success:function(res){ var list =res.data.data; if(res.data.code==1){ that.setData({ lessonList:list }) wx.hideLoading(); } } }) }, searchName: function (e) { wx.showLoading({ title: '正在搜索中', }) var name = e.detail.value; this.setData({ keyword:e.detail.value, contentlist:[], name:name, page:1 }) this.getOrderList('', '', '', '', name, '', 1, 10); }, inpuName:function(e){ var name = e.detail.value; this.setData({ keyword: e.detail.value, contentlist: [], name: name, page: 1 }) this.getOrderList('', '', '', '', name, '', 1, 10); }, async getOrderList(startdate, enddate, lesson_id, contract, key, status,page,page_size) { var date = this.data.nowDate; var token=wx.getStorageSync('token'); var that=this; const data = await utils.get("/api/backend.lesson_order/get_order_list", { status: status, startdate: startdate, enddate: enddate, contract_type:contract, lesson_id: lesson_id, keyword:key, page:page, page_size:page_size },token); if(data.code==1){ wx.hideLoading(); } var contentlistTem = that.data.contentlist; if (that.data.page == 1) { contentlistTem = [] } var contentlist = data.data.data; if (contentlist.length==0){ this.setData({ noResult: true }) } if (contentlist.length < that.data.page_size) { that.setData({ contentlist: contentlistTem.concat(contentlist), hasMoreData: false }) console.log('haha') } else { that.setData({ contentlist: contentlistTem.concat(contentlist), hasMoreData: true, page: that.data.page + 1 }) } }, async shaiCon(startdate, enddate, lesson_id, contract, key, status, page, page_size){ var date = this.data.nowDate; var token = wx.getStorageSync('token'); var that = this; that.setData({ page:1 }) const data = await utils.get("/api/backend.lesson_order/get_order_list", { status: status, startdate: startdate, enddate: enddate, contract_type: contract, lesson_id: lesson_id, keyword: key, page: page, page_size: page_size }, token); if(data.code==1){ wx.showToast({ title: data.msg, icon:'none' }) } if (data.data.data.length==0){ this.setData({ noResult:true }) } if (that.data.page == 1) { var contentlistTem = []; this.setData({ contentlist:[] }) }else{ var contentlistTem = that.data.contentlist; } var contentlist = data.data.data; console.log(contentlist); if (contentlist.length < that.data.page_size) { that.setData({ contentlist: contentlistTem.concat(contentlist), hasMoreData: false }) } else { that.setData({ contentlist: contentlistTem.concat(contentlist), hasMoreData: true, page: that.data.page + 1 }) } }, toDetail: function (e) { var id = e.currentTarget.dataset.id; wx.navigateTo({ url: '../recordDetail/recordDetail?' + 'id=' + id, }) }, close:function(e){ var froms=e.currentTarget.dataset.close; var contract = this.data.contractId; var lesson_name = this.data.lesson_name; var lesson_id = this.data.lesson_id; var status = this.data.statuindex; var startdate=this.data.startdate; var enddate = this.data.enddate; var keyword=this.data.keyword; var index=e.currentTarget.dataset.index; var page=this.data.page; var page_size=this.data.page_size; this.setData({ cur:index }) if (froms =="lessonName"){ this.getOrderList(startdate, enddate, '', contract, keyword, status,page,page_size); this.setData({ lesson_name:'' }) } else if (froms == "contarct"){ this.getOrderList(startdate, enddate, lesson_id, '', keyword, status, page, page_size); this.setData({ contractId: '' }) } else if (froms == "order") { this.getOrderList(startdate, enddate, lesson_id, contract, keyword, '', page, page_size); this.setData({ statuindex: '' }) } else if (froms == "keyword") { this.getOrderList(startdate, enddate, lesson_id, contract, '', status, page, page_size); this.setData({ keyword: '' }) } }, setModalStatus: function (e) { console.log("设置显示状态,1显示0不显示", e.currentTarget.dataset.status); var animation = wx.createAnimation({ duration: 200, timingFunction: "linear", delay: 0 }) this.animation = animation animation.translateX(300).step() this.setData({ animationData: animation.export() }) if (e.currentTarget.dataset.status == 1) { this.setData( { showModalStatus: true } ); } setTimeout(function () { animation.translateX(0).step() this.setData({ animationData: animation }) if (e.currentTarget.dataset.status == 0) { this.setData( { showModalStatus: false } ); } }.bind(this), 200) }, reBack: function (e) { var w_index = e.currentTarget.dataset.w_index; var w_curs = this.data.w_cur; if (w_index != w_curs) { this.setData({ w_cur: w_index }) } else { this.setData({ w_cur: '' }) } }, stuType: function (e) { var stuType = e.currentTarget.dataset.learn_status; var stuCur = this.data.stuType_cur; if (stuType != stuCur) { this.setData({ stuType_cur: stuType }) } else { this.setData({ stuType_cur: '' }) } }, keshiNum: function (e) { var keshi = e.detail.value; this.setData({ keshiNum: keshi }) }, slectCourses:function(e){ var lesson_id=e.currentTarget.dataset.id; var lesson_curs=this.data.lesson_cur; if (lesson_curs != lesson_id){ this.setData({ lesson_cur: lesson_id }) }else{ this.setData({ lesson_cur: '' }) } }, reset: function () { this.setData({ w_cur: '', stuType_cur: '', keshiNum: '', lesson_cur:'' }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var startdate=this.data.startdate; var enddate=this.data.enddate; var myrule = wx.getStorageSync('myrule'); //console.log(myrule); for (var i = 0; i < myrule.length; i++) { if (myrule[i] == 88) { var hasrule = true; } } if (hasrule) { this.setData({ hasrule: hasrule }) } //this.getNowFormatDate(); this.getlesson(); }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { this.setData({ contentlist:[], page:1 }) this.getNowFormatDate(); }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { wx.removeStorageSync('courseval'); }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { var page=this.data.page; var page_sie=this.data.page_size; var name=this.data.name; var contract_type=this.data.stuType_cur; var start=this.data.startdate; var end=this.data.enddate; var lesson=this.data.lesson_cur; var status=this.data.w_cur; if (this.data.hasMoreData) { this.getOrderList(start, end, lesson, contract_type, name, status, page, page_sie); } else { // wx.showToast({ // title: '没有更多数据了', // icon:'none' // }) } }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
export default function get(req, res) { const title = `Dictionaries` res.render(`Dictionaries/Dictionaries`, { [title]: true, title, }) }
import React from 'react'; import Header from './Header'; const App = props => { return ( <> <Header count={12} /> <ul> <li>Item One</li> <li>Item Two</li> </ul> </> ) }; export default App;
(global.webpackJsonp = global.webpackJsonp || []).push([ [ "components/views/fc_icon" ], { "1e41": function(n, e, t) { t.r(e); var c = t("bbec"), o = t.n(c); for (var i in c) [ "default" ].indexOf(i) < 0 && function(n) { t.d(e, n, function() { return c[n]; }); }(i); e.default = o.a; }, "1e9e": function(n, e, t) { t.d(e, "b", function() { return c; }), t.d(e, "c", function() { return o; }), t.d(e, "a", function() {}); var c = function() { var n = this, e = (n.$createElement, n._self._c, n.__get_style([ n.style ])); n.$mp.data = Object.assign({}, { $root: { s0: e } }); }, o = []; }, "5a9c": function(n, e, t) { t.r(e); var c = t("1e9e"), o = t("1e41"); for (var i in o) [ "default" ].indexOf(i) < 0 && function(n) { t.d(e, n, function() { return o[n]; }); }(i); var a = t("f0c5"), r = Object(a.a)(o.default, c.b, c.c, !1, null, "dc2074f4", null, !1, c.a, void 0); e.default = r.exports; }, bbec: function(n, e, t) { Object.defineProperty(e, "__esModule", { value: !0 }), e.default = void 0; var c = { props: { type: { type: String } }, computed: { src: function() { return "https://cdn.vip-wifi.com/hzfangchan/version-img/1.14.25/icon/".concat(this.type, ".png"); }, style: function() { var n = this.type.match(/^\d+/g); if (n.length) { var e = n[0] + "rpx"; return { width: e, height: e }; } return {}; } } }; e.default = c; } } ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "components/views/fc_icon-create-component", { "components/views/fc_icon-create-component": function(n, e, t) { t("543d").createComponent(t("5a9c")); } }, [ [ "components/views/fc_icon-create-component" ] ] ]);
import React, { Component, PropTypes } from 'react'; import { reduxForm, Field, formValueSelector } from 'redux-form'; import inputField from './../../components/ModalWindows/inputField'; import { withGoogleMap, GoogleMap, Polygon, Marker } from 'react-google-maps'; import DrawingManager from 'react-google-maps/lib/drawing/DrawingManager'; import Select from 'react-select'; import isInPolygon from '../../helpers/isInPolygon'; import { change } from 'redux-form'; import { connect } from 'react-redux'; import { calculateInvestment } from 'redux/modules/requests'; let currentCenter = {}; let maxPrice = null; const GettingStartedGoogleMap = withGoogleMap(props => { return ( <GoogleMap defaultZoom={9} defaultCenter={{ lat: Number(props.region.center_lat), lng: Number(props.region.center_lon) }} onClick={() => { console.log('click', props); }} ref={(map) => { if (map) { if (currentCenter !== props.mapCenter) { map.panTo({ lat: Number(props.region.center_lat), lng: Number(props.region.center_lon) }); } currentCenter = props.mapCenter; } }} > {props && props.region && props.region.map_points.length !== 0 ? <Polygon paths={props.region.map_points.map( point => ({lat: Number(point.map_lat), lng: Number(point.map_lon)}) )} options={{ strokeWeight: '1', fillColor: 'gray' }} key={`item-polygon-`} /> : ''} <DrawingManager onMarkerComplete={(event) => { const point = { lat: event.position.lat(), lng: event.position.lng() }; const polygonPoints = props.region.map_points.map(element => ({ lat: Number(element.map_lat), lng: Number(element.map_lon) })); event.setVisible(false); if (isInPolygon(point, polygonPoints)) { props.onMarkerAdded(point); } }} drawingMode={Marker} /> {props && props.marker ? <div className="ds"> <Marker position={{ lat: Number(props.marker.lat), lng: Number(props.marker.lng) }} /> </div> : ''} </GoogleMap> ); }); const validate = (values) => { const requiredFields = ['first_name', 'last_name', 'email', 'login', 'password', 'submit_password']; const lengthFields = ['password', 'submit_password']; const mailFields = ['email']; const errors = {}; requiredFields.map((field) => { if (!values[field]) { errors[field] = 'Поле обов\'язкове!'; return errors[field]; } return true; }); lengthFields.map((field) => { if (values[field] && values[field].length <= 5) { errors[field] = 'Поле має містити щонайменше 6 символів!'; return errors[field]; } return true; }); mailFields.map((field) => { if (values[field] && !values[field].match(/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{1,})$/i)) { errors[field] = 'Це поле має бути поштою'; } }); if (values.submit_password !== values.password) { errors.submit_password = 'Паролі не співпадають!'; } return errors; }; const selector = formValueSelector('calculateInvestmentForm'); @reduxForm({ form: 'calculateInvestmentForm', validate }) @connect( state => ({ formMapLon: selector(state, 'map_lon'), formMapLat: selector(state, 'map_lat'), calculateInvestmentResult: state.requests.calculateInvestmentResult }), {}) export default class CalculateInvestmentForm extends Component { static propTypes = { handleSubmit: PropTypes.func.isRequired, display: PropTypes.bool, categoriesList: PropTypes.array, currentRegion: PropTypes.object, formMapLon: PropTypes.Number, formMapLat: PropTypes.Number, calculateInvestmentResult: PropTypes.Array, }; static contextTypes = { store: PropTypes.object.isRequired, }; static defaultProps = { display: false, categoriesList: [], currentRegion: {}, formMapLon: null, formMapLat: null, calculateInvestmentResult: [] }; constructor(props) { super(props); this.state = { markerObject: null, selectedItems: [] }; } handleSelectChange(selectedItems) { this.setState({ selectedItems }); } createArray(values) { const dispatch = this.context.store.dispatch; const postValues = values; const mapLon = values.map_lon; const mapLat = values.map_lat; maxPrice = values.max_price; delete postValues.map_lat; delete postValues.map_lon; delete postValues.max_price; dispatch(calculateInvestment(mapLon, mapLat, maxPrice, postValues)); } render() { const { handleSubmit, display, categoriesList, formMapLon, formMapLat, currentRegion, calculateInvestmentResult } = this.props; const dispatch = this.context.store.dispatch; const optionsData = categoriesList.map(item => ({ value: item.id, label: item.title })); const displayItems = this.state.selectedItems.map(item => item.value); return ( <div className={`calculate-investment-form ${display ? 'display' : ''}`}> <form onSubmit={handleSubmit((submitValues) => { this.createArray(submitValues); })}> <div className="form-elements"> <div className="left-row"> <div className="find-items"> <div className="title-row">Оберіть список необхідних категорій:</div> <Select placeholder="Список категорій" name="form-field-name" options={optionsData} onChange={(value) => { this.handleSelectChange(value); }} value={this.state.selectedItems} multi /> </div> <div className="title-row" style={{ display: `${displayItems.length !== 0 ? 'block' : 'none'}` }} > Виставте пріоритет інвестиційних об'єктів для капіталовкладення: </div> {categoriesList && categoriesList.length !== 0 ? categoriesList.map(category => <div className="input-field" key={`category-id-${category.id}`} style={{ display: `${displayItems.includes(category.id) ? 'block' : 'none'}` }} > <div className="label">{category.title}:</div> <div className="field"> <Field name={category.id} component={inputField} divClassName="input-text" /> </div> </div> ) : ''} <br /><br /> <div className="input-field" key={'category-id-'}> <div className="title-row">Вкажіть розмір фонду, який задовольнятиме вашим фінансовим можливостям: </div> <div className="label">Інвестиційний фонд:</div> <div className="field"> <Field name="max_price" component={inputField} divClassName="input-text" /> </div> </div> </div> <div className="right-row"> <div className="title-row">Вкажіть точку вашого об'кта: </div> <GettingStartedGoogleMap containerElement={ <div style={{ height: `300px` }} /> } mapElement={ <div style={{ height: `300px` }} /> } region={currentRegion} onMarkerAdded={(marker) => { this.setState({ markerObject: marker }); dispatch(change('calculateInvestmentForm', 'map_lon', marker.lng)); dispatch(change('calculateInvestmentForm', 'map_lat', marker.lat)); }} marker={{ lng: formMapLon, lat: formMapLat }} /> <div className="form-row map-points"> <div className="input-field" key={`map-lon`}> <div className="label">Довгота об'єкту:</div> <div className="field"> <Field name="map_lon" component={inputField} divClassName="input-text" /> </div> </div> <div className="input-field" key={`map-lat`}> <div className="label">Широта об'єкту:</div> <div className="field"> <Field name="map_lat" component={inputField} divClassName="input-text" /> </div> </div> </div> </div> </div> <div onClick={handleSubmit((submitValues) => { this.createArray(submitValues); })} className="default-dark-button" > Обрахувати </div> </form> <div className="result"> <div className="result-title">Результат: </div> <div className="text"> <div>Найкращий шлях розподілення фонду в "{maxPrice} грн" наступний:</div> {calculateInvestmentResult && calculateInvestmentResult.length !== 0 ? calculateInvestmentResult.map((item, key) => <div className="row"><span>{key + 1} - {item.key}: </span> - (об'єкт) <a>{item.value}</a> <div></div></div> ) : ''} </div> </div> </div> ); } }
/* @flow */ import React, { Component } from 'react'; import { View, Text, StyleSheet, } from 'react-native'; import LocalizedStrings from 'react-native-localization'; export default class global_data { // const backgroundColor = '#2c3e50'; // global.backgroundColor = backgroundColor; constructor(){ } } const styles = StyleSheet.create({ container: { flex: 1, }, });
import React from 'react' import {connect} from 'react-redux' import {fetchGists} from '../saga/gists' class About extends React.Component{ constructor(){ super(...arguments) this.getList = this.getList.bind(this) } componentWillMount(){ this.props.getList() } getList(){ this.props.getList() } render(){ return ( <div className="a"> about<br/> <button onClick={this.getList}>fetch</button> <ul> {this.props.list && this.props.list.latest && this.props.list.latest.map( gist => ( <li key={ gist.id }>{gist.title}</li> ) )} </ul> </div> ) } } const mapStateToProps = (state) => { return { list:state.store.gists } } const mapDispatchToProps = (dispatch) => { return { getList:()=>{dispatch({type:'REQUEST'})} } } About.loadData = store => { return store.dispatch({type:'REQUEST'}) } export default connect(mapStateToProps, mapDispatchToProps)(About)
Ext.define('Gvsu.modules.refs.view.CustomersForm', { extend: 'Core.form.DetailForm', titleIndex: 'name', layout: 'border', defaults: { margin: '0', }, width: 450, height: 100, buildItems: function() { var me = this; return [{ xtype: 'panel', region: 'center', layout: 'anchor', bodyStyle: 'overflow: auto;padding: 10px;', defaults: { xtype: 'textfield', labelWidth: 200 ,anchor: '90%' }, items: me.buildFields() }] }, buildFields: function() { return [ { name: 'name', fieldLabel: D.t('Наименование организации') }] } })
class Path { constructor(seed, canvasX, canvasY) { this.seed = seed; // maximum number of points on the svg path this.maxPoints = 10; // x and y coordinates of the desired svg canvas size this.maxX = canvasX; this.maxY = canvasY; // maximum stroke width on the svg path this.maxWidth = 10; } random() { let rand = Math.sin(this.seed++) * 100000; return (rand - Math.floor(rand)); } randInt(max) { // returns an integer between 0 and max return Math.floor(this.random() * max + 1); } randLineType() { let line_type = this.randInt(2); if (line_type == 0) { return 'L'; } else if (line_type == 1) { return 'Q'; } else if (line_type == 2) { return 'C'; } else { return 'L'; } } randLine() { let lineType = this.randLineType(); let line = lineType + ' '; line += this.randPoint() + ' '; if (lineType == 'Q') { line += this.randPoint() + ' '; } else if (lineType == 'C') { line += this.randPoint() + ' '; line += this.randPoint() + ' '; } return line; } randNumPoints() { return this.randInt(this.maxPoints); } randPoint() { let x = this.randInt(this.maxX); let y = this.randInt(this.maxY); return (x + ',' + y); } randColor() { let r = this.randInt(255); let g = this.randInt(255); let b = this.randInt(255); return ("rgb(" + r + ',' + g + ',' + b + ')'); } randWidth() { return this.randInt(this.maxWidth); } randPathType() { let choice = this.randInt(1); if (choice == 1) { return 'z'; } else { return ''; } } randOpacity() { let opacity = this.randInt(100); return opacity / 100; } buildPath() { this.d = "M " + this.randPoint() + ' '; this.numPoints = this.randNumPoints(); for (let line = 1; line <= this.numPoints; line++) { this.d += this.randLine(); } this.d += this.randPathType(); this.stroke = this.randColor(); this.strokeWidth = this.randWidth(); this.fill = this.randColor(); this.opacity = this.randOpacity(); } }
import DataType from 'sequelize'; import Model from '../sequelize'; // TODO: maybe it is better to just refer to Wallet with walletId const Reward = Model.define( 'Reward', { id: { type: DataType.INTEGER(11), allowNull: false, primaryKey: true, autoIncrement: true, }, amount: { type: DataType.DECIMAL(30, 18), allowNull: false, }, start_date: { type: DataType.DATE, allowNull: false, }, end_date: { type: DataType.DATE, allowNull: false, }, }, { charset: 'utf8mb4', createdAt: false, updatedAt: false, }, ); export default Reward;
import React from 'react'; import PropTypes from 'prop-types'; import FieldStyled from './FieldStyled'; const Field = ({ value, changeValue, placeholder, name, type, getErrorMessage, }) => { const handleChange = (evt) => { changeValue(evt.target.name, evt.target.value); }; const handleFocus = () => { getErrorMessage(false, []); }; return ( <FieldStyled> <input className="input" type={type} name={name} value={value} onChange={handleChange} onFocus={handleFocus} autoComplete="off" // required /> <label className="label" htmlFor={name} > {placeholder} </label> </FieldStyled> ); }; Field.propTypes = { value: PropTypes.string.isRequired, placeholder: PropTypes.string.isRequired, name: PropTypes.string.isRequired, type: PropTypes.string.isRequired, changeValue: PropTypes.func.isRequired, getErrorMessage: PropTypes.func.isRequired, }; export default Field;
export const ApiCalls = { get: { photos: "https://api.unsplash.com/photos/curated" } };
module.exports = function(app) { require('./controllers/cryptids_controller')(app); require('./directives/cryptid_form_directive')(app); };
export const GET_ERRORS = "GET_ERRORS"; export const CLEAR_ERRORS = "CLEAR_ERRORS"; export const SET_CURRENT_USER = "SET_CURRENT_USER"; export const GET_PROFILE = "GET_PROFILE"; export const GET_DOGS = "GET_DOGS"; export const GET_DOG = "GET_DOG"; export const DELETE_VACCINATION = "DELETE_VACCINATION";
ui.Checklist = function() { ui.Checklist.base.constructor.call(this); }; wr.inherit(ui.Checklist, wr.View); ui.Checklist.prototype.create = function() { this.node = wr.div_c("ui_checklist"); }; ui.Checklist.prototype.enter = function() { ui.Checklist.base.enter.call(this); }; ui.Checklist.prototype.exit = function() { ui.Checklist.base.exit.call(this); }; ui.Checklist.prototype.reset = function() { };
import React from 'react'; import styled from 'styled-components'; import { Route, Link, Redirect } from 'react-router-dom'; import'../App.css' const Splash = styled.div` display: flex; flex-direction: column; justify-content: center; align-items: center; height: 98vh; h4 { margin-top: 10%; background-color: rgba(0,0,0,.7); padding: 3%; color: white; } button { width: 8em; margin: 2em; } .buttons { display: flex; justify-content: space-evenly; border: 1px solid; margin: 4em 0em; background-color: white; .logins { display: flex; flex-direction: column; justify-content: center; align-items: center; border-right: 1px solid black; } .registers { display: flex; flex-direction: column; justify-content: center; align-items: center; } } ` const Home = () => { return ( <Splash className='splash'> <h4>You've come to the best place for stuff like Veggies!</h4> <div className="buttons"> <div className="logins"> <Link to='/login-user'><button>Log In</button></Link> </div> <div className="registers"> <Link to='/register-user'><button>Register</button></Link> </div> </div> </Splash> ); } export default Home;
import React, { PureComponent } from 'react'; import { connect } from 'dva'; import { routerRedux } from 'dva/router'; import { Form, Input, Button, Card, Radio } from 'antd'; import PageHeaderLayout from '../../layouts/PageHeaderLayout'; import styles from './Edit.less'; const FormItem = Form.Item; const { TextArea } = Input; const STATE_KEY = 'franchiser_edit'; @connect(state => ({ franchiserEdit: state[STATE_KEY], loading: state.loading, })) @Form.create() export default class FranchiserEdit extends PureComponent { componentDidMount() { const { dispatch, match } = this.props; const payload = match.params; dispatch({ type: `${STATE_KEY}/get`, payload, }); } handleSubmit = (e) => { e.preventDefault(); const { form, dispatch, match } = this.props; form.validateFieldsAndScroll((err, values) => { if (!err) { dispatch({ type: `${STATE_KEY}/save`, payload: { ...values, id: match.params.id, }, }); } }); } handleBack() { const { dispatch } = this.props; dispatch( routerRedux.push('/basic/franchiser/list') ); } render() { const { loading, form, franchiserEdit } = this.props; const submitting = loading.effects[STATE_KEY]; const { record } = franchiserEdit; const { getFieldDecorator } = form; const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 7 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 12 }, md: { span: 10 }, }, }; const submitFormLayout = { wrapperCol: { xs: { span: 24, offset: 0 }, sm: { span: 10, offset: 7 }, }, }; return ( <PageHeaderLayout> <Card bordered={false}> <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }} > <FormItem {...formItemLayout} label="标题" > {getFieldDecorator('title', { initialValue: record.title, rules: [{ required: true, message: '请输入标题', }], })( <Input placeholder="给目标起个名字" /> )} </FormItem> <FormItem {...formItemLayout} label="目标描述" > {getFieldDecorator('description', { initialValue: record.description, rules: [{ required: true, message: '请输入目标描述', }], })( <TextArea style={{ minHeight: 32 }} placeholder="请输入你的阶段性工作目标" rows={4} /> )} </FormItem> <FormItem {...formItemLayout} label="状态" help="数据的状态" > {getFieldDecorator('status', { initialValue: String(record.status || 1), })( <Radio.Group> <Radio value="0">关闭</Radio> <Radio value="1">运行中</Radio> <Radio value="2">已上线</Radio> <Radio value="3">异常</Radio> </Radio.Group> )} </FormItem> <FormItem {...submitFormLayout} style={{ marginTop: 32 }}> <Button type="primary" htmlType="submit" loading={submitting}> 提交 </Button> <Button style={{ marginLeft: 8 }} onClick={() => this.handleBack()}>返回</Button> </FormItem> </Form> </Card> </PageHeaderLayout> ); } }
module.exports.run = async (PREFIX, message, args, bot) => { message.channel.send("Pong!") }; module.exports.config = { name: "ping", d_name: "Ping", aliases: [] };
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import Panel from './Panel.jsx'; import FormGroup from './FormGroup.jsx'; import { submitForm } from '../actions/others'; class Others extends React.PureComponent { constructor (props) { super(props); this.onSubmit = this.onSubmit.bind(this); this.onChange = this.onChange.bind(this); this.state = { paid: '' }; } onChange (value) { this.setState({ paid: value }); } onSubmit (event) { event.preventDefault(); this.props.submitForm( this.props.active, this.state.paid ); } render () { const { active, title } = this.props; return ( <form action="#" onSubmit={ this.onSubmit }> <Panel title={ title } refresh={()=>{}}> <FormGroup addon="Сума оплати:" name="paid" title="грн" value={ this.state.paid } onChange={ this.onChange } /> </Panel> <Link to={`/tables/${active}`} className="btn btn-default btn-block"> Переглянути історію платежів </Link> </form> ); } } Others.propTypes = { active: PropTypes.string.isRequired, title: PropTypes.string.isRequired, submitForm: PropTypes.func.isRequired }; export default connect( null, { submitForm })(Others);
var express = require('express'); var router = express.Router(); var async = require('async'); var _ = require('underscore'); var api = require('local-cms-api'); var Pager = require('local-pager'); var tkd = require('../tkd.json'); var pageId = require('./pageId.json'); var request = require('request'); var Cache = require('local-cache'); var ad_pkg = require('./ad_pkg.json'); var pkg = require('../package.json'); //频道列表页 router.get('/',function(req,res){ var act = req.query.preview_act || ''; api.parallel( {lady:[ { "key":"indexData", params:{ preview_act:act } } ]}, function(err,data){ data.Title = tkd.index.t; data.Keywords = tkd.index.k; data.Description = tkd.index.d; //console.log(data); //MPS定义BODY类型 data.pkg_mps_by_define = 'home'; res.render('index', data); } ); }); router.post('/ajax', function(req, res) { var callback = req.query.jsonpCallback; api.parallel( {lady:[ { "key":"setComment", params:{ "comment_content": req.body.comment_content, "userid": req.body.userid, "email": req.body.email, "password": req.body.password, "starid": req.body.starid, "docid": req.body.docid } } ]}, function(err,data){ //console.log(data); res.send(callback+'('+ JSON.stringify(data.setComment) +')'); } ); }); router.get('/ajax_2', function(req, res) { var callback = req.query.jsonpCallback; api.parallel( {lady:[ { "key":"getComment", params:{ "starid": req.query.starid, "docid": req.query.docid, "page_size": req.query.page_size } } ]}, function(err,data){ console.log(data); res.send(callback+'('+ JSON.stringify(data.getComment) +')'); } ); }); //评论更多 router.get('/mx/comment-:id.html',function(req,res){ var starid = req.params.id || ''; var pageSize = 10; // 显示个数 var curPage = Number(req.query.page) || 1; // 当前页码 var act = req.query.preview_act || ''; api.parallel( {lady:[ { "key":"Review", params:{ starid:starid, } } ]}, function(err,data){ console.log(data.Review); if(data.Review != null){ data.Title = data.Review.T; data.Keywords = data.Review.K; data.Description = data.Review.D; res.render('review', data); }else{ res.redirect('/error.html'); } } ); }); //明星详情页docid router.get('/mx/article-:id.html',function(req,res){ var docid = req.params.id || ''; var pageSize = 10; // 显示个数 var curPage = Number(req.query.page) || 1; // 当前页码 var act = req.query.preview_act || ''; api.parallel( {lady:[ { "key":"seoDetail", params:{ docid:docid, preview_act:act, page:curPage, page_size:pageSize } } ]}, function(err,data){ console.log(data.seoDetail.bread); if(data.seoDetail != null){ data.Title = data.seoDetail.T; data.Keywords = data.seoDetail.K; data.Description = data.seoDetail.D; /*data.detPager = new Pager({ pageSize:pageSize, //显示的条数 totalCount:Math.ceil(data.detailContent.page.total / pageSize), //page总数 curPage:curPage, //当前页码, numCount:data.detailContent.pages, //显示1,2,3,4,5...的个数 pageUrl:'/'+ cateId[1] +'/' + id + '.html' });*/ res.render('newsdetail', data); }else{ res.redirect('/error.html'); } } ); /*res.render('newsdetail', {'title':'mingxing'});*/ }); //明星长尾词页keywords router.get('/mx/id-:id.html',function(req,res){ var keywords = encodeURIComponent(req.params.id); var pageSize = 10; // 显示个数 var curPage = Number(req.query.page) || 1; // 当前页码 var act = req.query.preview_act || ''; api.parallel( {lady:[ { "key":"keyWord", params:{ keyword:keywords } } ]}, function(err,data){ if(data.keyWord != null){ if(!data.keyWord.keyword_star_news||0===data.keyWord.keyword_star_news.length){ res.redirect(301,'http://www.b5m.com/404.html'); return false; } data.Title = data.keyWord.T; data.Keywords = data.keyWord.K; data.Description = data.keyWord.D; /*data.detPager = new Pager({ pageSize:pageSize, //显示的条数 totalCount:Math.ceil(data.detailContent.page.total / pageSize), //page总数 curPage:curPage, //当前页码, numCount:data.detailContent.pages, //显示1,2,3,4,5...的个数 pageUrl:'/'+ cateId[1] +'/' + id + '.html' });*/ res.render('keywords', data); }else{ res.redirect(301,'http://www.b5m.com/404.html'); } } ); /*res.render('newsdetail', {'title':'mingxing'});*/ }); //明星图集页starid router.get('/mx/pic-:id.html',function(req,res){ var starid = req.params.id || ''; var pageSize = 20; // 显示个数 var curPage = Number(req.query.page) || 1; // 当前页码 var act = req.query.preview_act || ''; api.parallel( {lady:[ { "key":"photos", params:{ starid:starid, page_size:pageSize, page:curPage } } ]}, function(err,data){ //console.log(data.seoDetail.bread); if(data.photos != null){ data.Title = data.photos.T; data.Keywords = data.photos.K; data.Description = data.photos.D; data.detPager = new Pager({ pageSize:pageSize, //显示的条数 totalCount:Math.ceil(data.photos.count / pageSize), //page总数 curPage:curPage, //当前页码, numCount:data.photos.pages, //显示1,2,3,4,5...的个数 pageUrl:'/mx/pic-'+ starid + '.html' }); res.render('photos', data); }else{ res.redirect('/error.html'); } } ); }); //关键词图集页starid router.get('/mx/key-:id.html',function(req,res){ var keyword = req.params.id || ''; var pageSize = 20; // 显示个数 var curPage = Number(req.query.page) || 1; // 当前页码 var act = req.query.preview_act || ''; api.parallel( {lady:[ { "key":"articleListKeyword", params:{ keyword:keyword, page_size:pageSize, page:curPage } } ]}, function(err,data){ //console.log(data.seoDetail.bread); if(data.articleListKeyword != null){ data.Title = data.articleListKeyword.T; data.Keywords = data.articleListKeyword.K; data.Description = data.articleListKeyword.D; data.detPager = new Pager({ pageSize:pageSize, //显示的条数 totalCount:Math.ceil(data.articleListKeyword.count / pageSize), //page总数 curPage:curPage, //当前页码, numCount:data.articleListKeyword.pages, //显示1,2,3,4,5...的个数 pageUrl:'/mx/key-'+ keyword + '.html' }); res.render('KeywordPhotos', data); }else{ res.redirect('/error.html'); } } ); }); //更多资讯 router.get('/mx/artlist-:id.html',function(req,res){ var starid = req.params.id || ''; var act = req.query.preview_act || ''; var pageSize = 10; // 显示个数 var curPage = Number(req.query.page) || 1; // 当前页码 api.parallel( {lady:[ { "key":"moreNews", params:{ starid:starid, page_size:pageSize, page:curPage } } ]}, function(err,data){ console.log(data.moreNews); if(data.moreNews != null){ /*data.Title = data.detailContent.content.seo_title || tkd[cateId[1]]['t'];*/ data.Title = data.moreNews.T; data.Keywords = data.moreNews.K; data.Description = data.moreNews.D; data.detPager = new Pager({ pageSize:pageSize, //显示的条数 totalCount:Math.ceil(data.moreNews.count / pageSize), curPage:curPage, //当前页码, numCount:data.moreNews.pages, //显示1,2,3,4,5...的个数 pageUrl:'/mx/artlist-'+ starid + '.html' }); res.render('moreNews', data); }else{ res.redirect('/error.html'); } } ); }); //seo Index router.get('/mx/:id.html',function(req,res){ var starid = req.params.id || ''; var act = req.query.preview_act || ''; api.parallel( {lady:[ { "key":"seoDataIndex", params:{ starid:starid } } ]}, function(err,data){ // console.log(data.seoDataIndex.star_info); if(data.seoDataIndex != null){ data.Title = data.seoDataIndex.T; data.Keywords = data.seoDataIndex.K; data.Description = data.seoDataIndex.D; //js_ad data.js_ad_lady_mx_right_bnr = ''; async.parallel([ function(callback){ var data3 = null; //判断缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.get('js_ad_lady_mx_right_bnr',function(err,js_ad_lady_mx_right_bnr){ if(err) { } if(js_ad_lady_mx_right_bnr){ try{ js_ad_lady_mx_right_bnr = JSON.parse(js_ad_lady_mx_right_bnr); data.js_ad_lady_mx_right_bnr = js_ad_lady_mx_right_bnr; } catch (e) {} callback(null, data3); }else{ request(pkg.use_urls.www_url+'/singleAd?identifier=lady_mx_right_bnr',function(error,response,data3){ if(!error && response.statusCode === 200) { var data2_str = data3; if(data3.substr(0,13)=='jsonpCallback'){ data2_str =data3.substring(14,data3.lastIndexOf(")")); } var info = JSON.parse(data2_str); data.js_ad_lady_mx_right_bnr = info; //存缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.set({ key : 'js_ad_lady_mx_right_bnr', value : data2_str, left : 60*5 },function(err){ if(err){ console.log(err); } }); } callback(null, data3); }); } }); } ], function(err, results){ res.render('seoindex', data); }); }else{ res.redirect('/error.html'); } } ); }); router.get('/*/:id.html',function(req,res){ var pathUrl = req.path; var cateId = pathUrl.split('/'); var id = pathUrl.match(/\d+(?=\.html)/)[0]; /* var id = req.params.id || '';*/ var pageSize = 1; // 显示个数 var curPage = Number(req.query.page) || 1; // 当前页码 var act = req.query.preview_act || ''; api.parallel( {lady:[ { "key":"detailContent", params:{ id:id, page:curPage, preview_act:act } } ]}, function(err,data){ if(data.detailContent != null){ data.Title = data.detailContent.content.seo_title || tkd[cateId[1]]['t']; data.Keywords = data.detailContent.content.seo_keywords || tkd[cateId[1]]['k']; data.Description = data.detailContent.content.seo_description || tkd[cateId[1]]['d']; data.rightData = data.detailContent.block; //整理详细内容,加入广告位置,大约在中间左右 data.detailContent.content.content_one = ''; data.detailContent.content.content_two = ''; if(data.detailContent.content.content){ var data_len = (data.detailContent.content.content).length; var one_content = (data.detailContent.content.content).substr(0, parseInt(data_len/2) ); var two_content = (data.detailContent.content.content).substr(parseInt(data_len/2) ); var one_pos = one_content.lastIndexOf("\r"); one_pos = (one_pos<0)?data_len:one_pos; one_content = (data.detailContent.content.content).substr(0, one_pos ); two_content = (data.detailContent.content.content).substr(one_pos ); data.detailContent.content.content_one = one_content; data.detailContent.content.content_two = two_content; } data.detPager = new Pager({ pageSize:pageSize, //显示的条数 totalCount:Math.ceil(data.detailContent.page.total / pageSize), //page总数 curPage:curPage, //当前页码, numCount:data.detailContent.pages, //显示1,2,3,4,5...的个数 pageUrl:'/'+ cateId[1] +'/' + id + '.html' }); data.ad_pkg = ad_pkg; data.is_detail = 1; //MPS定义BODY类型 data.pkg_mps_by_define = 'subcatlist'; res.render('detail', data); }else{ res.redirect('/error.html'); } } ); }); router.get('/*/*',function(req,res){ var pathUrl = req.path; var cateId = pathUrl.split('/'); var category_id = pageId[cateId[1]][cateId[2]]; var pageSize = 10; // 显示个数 var curPage = Number(req.query.page) || 1; // 当前页码 var act = req.query.preview_act || ''; /*console.log(category_id +'A33333'+ cateId[2]);*/ api.parallel( {lady:[ { "key":"listPage", params:{ category_id:category_id, page:curPage, preview_act:act } } ]}, function(err,data){ data.Title = tkd[cateId[1]][cateId[2]]['t']; data.Keywords = tkd[cateId[1]][cateId[2]]['k']; data.Description = tkd[cateId[1]][cateId[2]]['d']; data.rightData = data.listPage.block; data.pager = new Pager({ pageSize:pageSize, //显示的条数 totalCount:Math.ceil(data.listPage.count / pageSize), curPage:curPage, //当前页码, numCount:data.listPage.pages, //显示[1,2,3,4,5...]的个数 pageUrl:pathUrl }); data.ad_pkg = ad_pkg; data.is_detail = 0; res.render('list', data); } ); }); //beauty router.get('/*',function(req,res){ var category_id = req.path.split('/')[1] || ''; var act = req.query.preview_act || ''; /*console.log(category_id +'33333');*/ api.parallel( {lady:[ { "key":"channel", params:{ category_id:pageId[category_id]['/'], preview_act:act } } ]}, function(err,data){ data.Title = tkd[category_id][category_id]['t']; data.Keywords = tkd[category_id][category_id]['k']; data.Description = tkd[category_id][category_id]['d']; data.rightData = data.channel.block; //console.log(data); data.ad_pkg = ad_pkg; data.is_ad_channel = 1; res.render('channel', data); } ); }); module.exports= router;
// Write a function that returns the product of every value in an array of numbers function productOfArray(arr) { // DO stuff // if the array length is 0 return 1 if (arr.length === 0) { return 1; } // return array[0] multiplied by the value of productOfArray on the array with the first element taken off return arr[0] * productOfArray(arr.slice(1)); } console.log(productOfArray([1, 2, 3])); // 6 console.log(productOfArray([1, 2, 3, 10])); // 60
const raiseStatus = (response) => { if (response.status >= 200 && response.status < 300) { return response.json(); } const err = new Error(response.status); throw err; }; const getGameData = () => fetch("https://opentdb.com/api.php?amount=10&category=9&difficulty=easy&type=multiple") .then(raiseStatus); export default getGameData;
var chatModel = require('../../models/ChatModel'); var userlistModel = require('../../models/UserModel'); var fs = require('fs'); var path = require('path'); var stopWords = require('fs').readFileSync(path.join(__dirname, "../../stopWords.txt"), 'utf8').toString().split(","); var testCtrl = require('./testCtrl.js'); for (var i = 0; i < stopWords.length; i++) stopWords[i] = stopWords[i].toUpperCase(); function validateTime(time) { var isValidDateMsg = Date.parse(time); if (isNaN(isValidDateMsg)) { return 'Error: date and time must be in ISO format!'; } return ''; } function isAllStopWords(words){ var allUndefined = true; for (var j = 0; j < words.length; j++){ if (words[j]) allUndefined = false; } if (allUndefined) return true; return false; } function isMactch(msg, words){ for (var j = 0; j < words.length; j++){ if (words[j] && msg.indexOf(words[j].toUpperCase()) < 0) return false; } return true; } module.exports.saveMessage = function(msg, callback) { if (testCtrl.isTesting()){ callback({statusCode: 400, desc: 'system is under testing, try again later'}); return; } if (msg.postedAt) { var errorMsg = validateTime(msg.postedAt); if (errorMsg) return callback({ statusCode: 400, desc: errorMsg }); } chatModel.saveMessage(msg.content, msg.author, msg.messageType, msg.target, msg.postedAt, function(result) { if (!result.status) callback({ statusCode: 400, desc: result.desc }); else callback({ statusCode: 201, desc: "message has been saved" }); return; }); }; module.exports.getPublicMessages = function(callback) { if (testCtrl.isTesting()){ callback({statusCode: 400, desc: 'system is under testing, try again later'}); return; } var isActive = {}; chatModel.getPublicMessages(function(result) { if (!result.status) return callback({ statusCode: 400 }); var publicMsgs = result.msgs; userlistModel.allUser(function(result){ result.users.forEach(function(item){ isActive[item.username] = (item.accountStatus === "Active"); }); publicMsgs = publicMsgs.filter(function(item, idx, arr){ return isActive[item.author]; }); callback({ statusCode: 200, msglist: publicMsgs }); }); }); }; module.exports.getPrivateMessages = function(author, target, callback) { if (testCtrl.isTesting()){ callback({statusCode: 400, desc: 'system is under testing, try again later'}); return; } var isActive = {}; userlistModel.selectOneUser(author, function(result) { if (!result.status) { return callback({ statusCode: 404 }); } isActive[result.user.username] = (result.user.accountStatus === "Active"); userlistModel.selectOneUser(target, function(result) { if (!result.status) { return callback({ statusCode: 404 }); } isActive[result.user.username] = result.user.accountStatus === "Active"; chatModel.getPrivateMessages(author, target, function(result) { if (!result.status) { return callback({ statusCode: 500 }); } var activeMsgs = result.msgs.filter(function(item, idx, arr) { return (isActive[item.author] && isActive[item.target]); }); callback({ statusCode: 200, msglist: activeMsgs }); }); }); }); }; module.exports.getAnnouncements = function(callback) { if (testCtrl.isTesting()){ callback({statusCode: 400, desc: 'system is under testing, try again later'}); return; } var isActive = {}; chatModel.getAnnouncements(function(result) { if (!result.status) return callback({ statusCode: 500 }); var anns = result.msgs; userlistModel.allUser(function(result){ result.users.filter(function(item){ isActive[item.username] = (item.accountStatus === "Active"); }); anns = anns.filter(function(item, idx, arr){ return isActive[item.author]; }); callback({ statusCode: 200, msglist: anns }); }); }); }; module.exports.getAnnouncementsByStringMatch = function(searchStr, offset, callback){ if (testCtrl.isTesting()){ callback({statusCode: 400, desc: 'system is under testing, try again later'}); return; } var words = searchStr.split(' '); for (var i = 0; i < words.length; i++) words[i] = words[i].toUpperCase(); for (i = 0; i < words.length; i++){ if (stopWords.indexOf(words[i]) >= 0) delete words[i]; } if (isAllStopWords(words)){ callback({statusCode: 400}); return; } chatModel.getAnnouncements(function(result){ if (!result.status){ callback({statusCode: 500}); return; } else { var announcements = result.msgs; var count = 0; var msgs = []; for (var i = 0; i < announcements.length; i++) { var content = announcements[i].content.toUpperCase(); if (isMactch(content, words)) { count++; if (count > offset) msgs.push(announcements[i]); if (msgs.length >= 10) break; } } callback({statusCode: 200, msglist: msgs}); return; } }); }; module.exports.getPublicMessagesByStringMatch = function(searchStr, offset, callback){ if (testCtrl.isTesting()){ callback({statusCode: 400, desc: 'system is under testing, try again later'}); return; } var words = searchStr.split(' '); for (var i = 0; i < words.length; i++) words[i] = words[i].toUpperCase(); for (i = 0; i < words.length; i++){ if (stopWords.indexOf(words[i]) >= 0) delete words[i]; } if (isAllStopWords(words)){ callback({statusCode: 400}); return; } chatModel.getPublicMessages(function(result){ if (!result.status){ callback({statusCode: 500}); return; }else{ var publicMsgs = result.msgs; var count = 0; var msgs = []; for (var i = 0; i < publicMsgs.length; i++){ var content = publicMsgs[i].content.toUpperCase(); if (isMactch(content, words)){ count++; if (count > offset) msgs.push(publicMsgs[i]); if (msgs.length > 10) break; } } callback({statusCode: 200, msglist: msgs}); } }); }; module.exports.getPrivateMessagesByStringMatch = function(username, searchStr, offset, callback){ if (testCtrl.isTesting()){ callback({statusCode: 400, desc: 'system is under testing, try again later'}); return; } userlistModel.selectOneUser(username, function(result){ if (!result.status){ callback({statusCode: 400}); return; } var words = searchStr.split(' '); for (var i = 0; i < words.length; i++) words[i] = words[i].toUpperCase(); for (i = 0; i < words.length; i++){ if (stopWords.indexOf(words[i]) >= 0) delete words[i]; } if (isAllStopWords(words)){ callback({statusCode: 400}); return; } chatModel.searchPrivateMessageByAuthor(username, function(resultSearchAuthor){ if (!resultSearchAuthor.status){ callback({status: 500}); return; } chatModel.searchPrivateMessageByTarget(username, function(resultSearchTarget){ if (!resultSearchTarget.status){ callback({status: 500}); return; } var privateMsgs = resultSearchAuthor.msgs.concat(resultSearchTarget.msgs); privateMsgs.sort(function(a, b){ if (a.postedAt < b.postedAt) return -1; else if (a.postedAt == b.postedAt) return 0; return 1; }); var count = 0; var msgs = []; for (var i = 0; i < privateMsgs.length; i++){ var content = privateMsgs[i].content.toUpperCase(); if (isMactch(content, words)){ count++; if (count > offset) msgs.push(privateMsgs[i]); if (msgs.length > 10) break; } } callback({statusCode: 200, msglist: msgs}); }); }); }); };
// 1. functions as abstraction var work = function() { var name = "*** WORK FUNCTION ***"; console.log(name + "\nworking hard!"); } var play = function() { var name = "*** PLAY FUNCTION ***"; console.log(name + "\nPLAYING hard !"); } var doIt = function(f) { console.log("<<< BEGIN doIt(f) >>> " + Date() ); f(); // also can add try-catch block here for error-handling console.log("<<< END doIt(f) >>> " + Date() ); }; doIt(work); doIt(play);
import React, { useEffect, useState, Fragment } from "react"; // eslint-disable-line no-unused-vars import { Route, Link } from "react-router-dom"; // eslint-disable-line no-unused-vars import styled from "styled-components"; import { axiosWithAuth } from "../../../helpers/axiosWithAuth"; import axios from "axios"; // eslint-disable-line no-unused-vars const SurveyForm = () => { const [questions, setQuestions] = useState([ { question: "", questionType: "" } ]); const [form, setForm] = useState({ name: "", description: "" }); const [newQuestion, setNewQuestion] = useState(false); const [enabledBtn, setEnabledBtn] = useState(false); console.log("fresh q", questions); const questionHandleChange = (e, i) => { questions[i] = { ...questions[i], [e.target.name]: e.target.value }; questions[i].question && questions[i].question.length > 2 && questions[i].questionType && questions[i].questionType.length > 2 && setNewQuestion(true); }; const handleChange = e => { setForm({ ...form, [e.target.name]: e.target.value }); }; let errors = {}; useEffect(() => { errors.surveyName = !form.name && "Please enter a name for your survey"; errors.surveyDesc = !form.description && "Please enter a description for your survey"; //TODO -- figure out why this wasn't reading correctly // errors.surveyQType = // !form.questionType && // "Please select which type of answers this survey is looking for"; !errors.surveyName && !errors.surveyDesc && setEnabledBtn(true); }, [form]); const addQuestion = () => { setQuestions([...questions, { question: "", questionType: "" }]); setNewQuestion(false); }; const handleSubmit = e => { e.preventDefault(); if (!enabledBtn) { alert(errors.surveyName || errors.surveyDesc || errors.surveyQType); } else { const data = { ...form, question_ids: questions }; axiosWithAuth() .post("/questiongroups", data) .then(res => console.log(res)) .catch(err => console.log(err)); } }; console.log("questions state", questions); return ( <StyledWrapper> <StyledForm onSubmit={handleSubmit}> <> <h3>SURVEY NAME</h3> <input type="text" name="name" value={form.name} placeholder="Create a name for this mission" onChange={handleChange} /> <h3>SURVEY DESCRIPTION</h3> <input type="text" name="description" value={form.description} placeholder="Add a description for your mission..." onChange={handleChange} /> {questions.map((group, i) => { return ( <StyledQuestions> <h3>QUESTION {i + 1}</h3> <input type="text" name="question" placeholder="What question would you like to ask?" onChange={e => questionHandleChange(e, i)} /> <h3>QUESTION TYPE</h3> <select name="questionType" onChange={e => questionHandleChange(e, i)} > <option defaultValue="">Please Select One</option> <option value="multiple choice">Multiple Choice</option> <option value="slider">Slider</option> <option value="text reply">Text Reply</option> </select> </StyledQuestions> ); })} </> {newQuestion && ( <div onClick={() => { addQuestion(); }} > Add Question </div> )} <StyledButton type="submit">Submit your survey</StyledButton> </StyledForm> </StyledWrapper> //styled comp ); }; const StyledForm = styled.form` display: flex; margin: 0 auto; padding-top: 10rem; width: 100% flex-direction: column; input { font-family: Catamaran; font-size: 1.3rem; padding: 1.0rem; border: none; width: 100%; color: rgba(204, 201, 255, 0.4); background: #3D3B91; } select { font-size: 1.3rem; padding: 1.0rem; font-family: Catamaran; border: none; width: 100%; color: rgba(204, 201, 255, 0.4); background: #3D3B91; } h3 { font-family: Catamaran; font-size: 1.6rem; font-weight: bold; line-height: 2.6rem; letter-spacing: 0.035em; color: #B8B7E1; } `; const StyledWrapper = styled.div` font-family: Catamaran; margin: 0 auto; max-width: 80vw; `; const StyledButton = styled.button` padding: 1rem; width: 251px; text-align: center; margin: 0 auto; color: #e6e6e6; background-color: #e05cb3; border: none; border-radius: 5px; font-weight: bold; `; const StyledQuestions = styled.div` width: 100%; input { width: 100%; } `; export default SurveyForm;
import { createStore } from 'vuex' export default createStore({ state: { themeId: 0, language: 'cn', }, mutations: { CHANGE_THEME(state, i) { state.themeId = i }, CHANGE_LANGUAGE(state, i) { state.language = i }, }, })
document.addEventListener('DOMContentLoaded', () => { console.log('JavaScript loaded'); const newListButton = document.createElement("button"); newListButton.textContent= 'Delete'; const body = document.querySelector("body"); body.appendChild(newListButton); newListButton.addEventListener('click', handleClick); const form = document.querySelector("#new-item-form") form.addEventListener('submit', handleNewForm); }); const handleNewForm = function(event){ event.preventDefault(); const list = document.querySelector("#reading-list"); const listItem = document.createElement("li"); list.appendChild(listItem); const listContainer = document.createElement("div"); listContainer.classList.add("list-container") listItem.appendChild(listContainer); const newListTitle = document.createElement("h3"); const title = event.target.title.value; newListTitle.textContent = `${title}`; listContainer.appendChild(newListTitle); const newListAuthor = document.createElement("h5"); const author = event.target.author.value; newListAuthor.textContent = `${author}`; listContainer.appendChild(newListAuthor); const newListCategory = document.createElement("p"); const category = event.target.category.value; newListCategory.textContent = `${category}` listContainer.appendChild(newListCategory); document.getElementById("new-item-form").reset(); console.log(event.target); }; const handleClick = function (event){ document.getElementById("reading-list").innerHTML = ""; };
import _ from 'lodash'; import { isJsonString, jsonIsEqual, } from '@/helpers/utils'; export default { handleChangePage: function handleChangePage(page) { this.getItems(page); }, handleSizeChange: function handleSizeChange(size) { this.pageSize = size; this.getItems(1); }, handleSortChange: function handleSortChange({ prop, order }) { if (order === 'ascending') { this.sort = prop; } else { this.sort = `-${prop}`; } this.getItems(1); }, handleAdd: function handleAdd() { this.dataToAdd = {}; }, handleSearch: function handleSearch() { this.getItems(1); }, handleSave: async function handleSave() { const data = this.dataToAdd; this.dataToAdd = null; try { await this.save(data); } catch (err) { this.$alert(err); } }, handleEdit: function handleEdit(index) { const item = this.items[index]; const data = {}; _.forEach(this.keys, (v) => { const name = v.name; data[name] = item[name]; }); this.dataToUpdate = data; this.editIndex = index; }, handleUpdate: async function handleUpdate(index, key) { const item = this.items[index]; /* eslint no-underscore-dangle:0 */ const id = item._id; this.editIndex = -1; const { keys, dataToUpdate, } = this; const data = {}; _.forEach(keys, (v) => { const key = v.name; const updateItem = dataToUpdate[key]; if (isJsonString(updateItem)) { let tmp = null; try { tmp = JSON.parse(updateItem); } catch (err) { this.$alert(err); throw err; } if (!jsonIsEqual(item[key], tmp)) { data[key] = tmp; } } else if (item[key] !== dataToUpdate[key]) { data[key] = dataToUpdate[key]; } }); if (_.isEmpty(data)) { return; } try { await this.update({ id, data, }); this.$message({ showClose: true, message: `成功更新${item[key]}`, }); } catch (err) { this.$alert(err); } }, type: function type() { if (this.isValid) { return 3; } const userInfo = this.userInfo; if (!userInfo) { return 0; } if (userInfo.anonymous) { return 1; } const { roles, } = userInfo; const validRoles = this.validRoles || ['su', 'admin']; let found = false; _.forEach(roles, (role) => { if (found) { return; } if (_.includes(validRoles, role)) { found = true; } }); if (!found) { return 2; } this.isValid = true; this.getItems(1); return 3; }, };
const ChainUtil = require('../chain-util'); const { DIFFICULTY, MINE_RATE } = require('../config'); // Create the block class with a file called block.js. // Each black has a `lastHash`, `hash`, `data, `nonce`, `diffculty` and `timestamp` attribute. class Block { constructor(timestamp, lastHash, hash, data, nonce, difficulty) { this.timestamp = timestamp; this.lastHash = lastHash; this.hash = hash; this.data = data; this.nonce = nonce; this.difficulty = difficulty || DIFFICULTY; } // convert attributes to strings toString() { return `Block - Timestamp : ${this.timestamp} Last Hash : ${this.lastHash.substring(0, 10)} Hash : ${this.hash.substring(0, 10)} Nonce : ${this.nonce} Difficulty: ${this.difficulty} Data : ${this.data}`; } // Every blockchain starts with the "genesis block" - a default dummy block to originate the chain. static genesis() { return new this('Genesis time', '-----', 'f1r57-h45h', [], 0, DIFFICULTY); } // Add a function to add a generate a block based off of some provided `data` to store, and a given `lastBlock.` // Call the function `mineBlock`. // Generating a block is equated to an act of mining since it takes computational power to “mine” the block. static mineBlock(lastBlock, data) { let hash, timestamp; const lastHash = lastBlock.hash; let { difficulty } = lastBlock; let nonce = 0; do { nonce++; timestamp = Date.now(); difficulty = Block.adjustDifficulty(lastBlock, timestamp); hash = Block.hash(timestamp, lastHash, data, nonce, difficulty); } while (hash.substring(0, difficulty) !== '0'.repeat(difficulty)); return new this(timestamp, lastHash, hash, data, nonce, difficulty); } // convert hash to string static hash(timestamp, lastHash, data, nonce, difficulty) { return ChainUtil.hash(`${timestamp}${lastHash}${data}${nonce}${difficulty}`).toString(); } // return the blockHash static blockHash(block) { const { timestamp, lastHash, data, nonce, difficulty } = block; return Block.hash(timestamp, lastHash, data, nonce, difficulty); } // adjust difficutly of last block static adjustDifficulty(lastBlock, currentTime) { let { difficulty } = lastBlock; difficulty = lastBlock.timestamp + MINE_RATE > currentTime ? difficulty + 1 : difficulty - 1; return difficulty; } } module.exports = Block;