text
stringlengths
7
3.69M
import React from 'react'; import PropTypes from 'prop-types'; import css from './FeedbackOptions.module.css'; const FeedbackOptions = ({ options, onLeaveFeedback }) => ( <div className={css.section}> {Object.keys(options).map(key => ( <button key={key} type="button" name={key} onClick={onLeaveFeedback} className={css.button} > {key} </button> ))} </div> ); FeedbackOptions.propTypes = { onLeaveFeedback: PropTypes.func, options: PropTypes.shape({ good: PropTypes.number, neutral: PropTypes.number, bad: PropTypes.number, }), }; export default FeedbackOptions;
$(document).ready(function() { $('.menu-toggle').on('click', function(e) { e.preventDefault(); var $this = $(this), href = $this.attr('href'), $menu = $(href); if ( $menu.length > 0 ) { $menu.slideToggle(); } }); });
class Card{ constructor(name, cost){ this.name = name; this.cost = cost; } } class Unit extends Card{ constructor(name, cost, power, res){ super(name, cost); this.power = power; this.Resilience = res } attack(target){ target.Resilience -= this.power console.log(target.name + "'s resilience has reduced by " + this.power+ " and the current resilience : " + target.Resilience) } } class Effect extends Card{ constructor(name, cost ,stat ,magnitude){ super(name, cost) this.stat=stat this.magnitude=magnitude } play( target ) { if( target instanceof Unit ) { if (this.stat == "power") { if (this.magnitude > 0){ target.power += this.magnitude console.log(target.name+"'s "+this.stat+" has increased by "+this.magnitude+" and it has become "+target.power) } else{ target.power += this.magnitude console.log(target.name+"'s "+this.stat+" has decreased by "+Math.abs(this.magnitude)+" and it has become "+target.stat) } } else { if (this.magnitude > 0){ target.Resilience += this.magnitude console.log(target.name+"'s "+this.stat+" has increased by "+this.magnitude+" and it has become "+target.Resilience) } else{ target.Resilience += this.magnitude console.log(target.name+"'s "+this.stat+" has decreased by "+Math.abs(this.magnitude)+" and it has become "+target.Resilience) } } } else { throw new Error( "Target must be a unit!" ); } } } //units const unit1 = new Unit("Red Belt Ninja", 3, 3, 4); const unit2 = new Unit("Black Belt Ninja", 4, 5, 4); //effects const effect1 = new Effect("Hard Algorithm", 2, "Resilience" ,magnitude = 3); const effect2 = new Effect("Unhandled Promise Rejection", 1, "Resilience", magnitude = -2); const effect3 = new Effect("Pair Programming", 3, "power",magnitude = 2); //turn1 effect1.play(unit1);// use Hard Algorithm on Red Belt Ninja increase resilience by 3 //turn2 effect2.play(unit1);// use Unhandled Promise Rejection on Red Belt Ninja decrease resilience by 2 //turn3 effect3.play(unit1);// use Pair Programming on Red Belt Ninja increase power by 2 unit1.attack(unit2);// Red Belt Ninja attacks Black Belt Ninja
/** * @provides javelin-behavior-diff-preview-link * @requires javelin-behavior * javelin-stratcom * javelin-dom */ JX.behavior('diff-preview-link', function(config, statics) { if (statics.initialized) { return; } statics.initialized = true; var pht = JX.phtize(config.pht); // After inline comment previews are rendered, hook up the links to the // comments that are visible on the current page. function link_inline_preview(e) { var root = e.getData().rootNode; var links = JX.DOM.scry(root, 'a', 'differential-inline-preview-jump'); for (var ii = 0; ii < links.length; ii++) { var data = JX.Stratcom.getData(links[ii]); try { JX.$(data.anchor); links[ii].href = '#' + data.anchor; JX.DOM.setContent(links[ii], pht('view')); } catch (ignored) { // This inline comment isn't visible, e.g. on some other diff. } } } JX.Stratcom.listen('EditEngine.didCommentPreview', null, link_inline_preview); });
function concatArguments() { var result = “”; for (var i = 0; i < arguments.length; i ++) { result + = arguments[i] + “ “; } console.log result; }
import { Card } from 'antd'; import React, {Component} from 'react'; import PropTypes from 'prop-types'; import {Link} from "react-router-dom"; const { Meta } = Card; class Article extends React.Component { render(){ return( <Card hoverable style={{ width: this.props.width, height: this.props.height }} cover={<img src={this.props.gambar} />} > <Meta title={this.props.title} description={this.props.desc} /> </Card> ); } } export default Article;
'use strict'; const moment = require('moment'); const uuid = require('uuid/v1'); const service = {}; service.timestampFormat = 'YYYY-MM-DD HH:mm:ss:SS'; service.generateId = () => { return uuid().replace(/-/g, ''); }; service.info = (message, loggingId, timestamp) => { let id = loggingId || service.generateId(); let ts = timestamp || moment().format(service.timestampFormat); let logMessage = `${ts} ${id}: ${message}`; console.info(logMessage); }; service.error = (message, loggingId, timestamp) => { let id = loggingId || service.generateId(); let ts = timestamp || moment().format(service.timestampFormat); let logMessage = `${ts} ${id}: ${message}`; console.error(logMessage); }; module.exports = service;
const express = require("express"); const router = express.Router(); const ctrl = require("../../../controllers/contacts"); const guard = require("../../../helpers/guard"); const { validateCreateContact, validateUpdateContact, validateUpdateFavorite, } = require("./validation"); // Маршрути для app // GET router.get("/", guard, ctrl.getAll); // GET BY ID router.get("/:contactId", guard, ctrl.getById); // POST router.post("/", guard, validateCreateContact, ctrl.add); // DELETE router.delete("/:contactId", guard, ctrl.remove); // PUT router.put("/:contactId", guard, validateUpdateContact, ctrl.update); // PATCH router.patch( "/:contactId/favorite", guard, validateUpdateFavorite, ctrl.update ); module.exports = router;
config_ = [ { row_limit:100,//maximum no of rows to be displayed in a list records_per_page:5, path:'/media' } ]; var mediaApp = angular.module('mediaApp', ['mediaCtrl', 'mediaService']).value('config', config_[0]); var productApp = angular.module('productApp', ['productCtrl', 'productService']).value('config', config_[0]); var wizardApp = angular.module('wizardApp',['campaignCtrl', 'campaignService', 'adSetCtrl', 'adSetService', 'mediaCtrl', 'mediaService', 'adCreativeCtrl', 'adCreativeService', 'productGalleryCtrl', 'productService', 'adsCtrl', 'adsService', 'wizardNavCtrl' ]).value('config', config_[0]) .service('wizardService', function() { var serviceParams = {campaign_id:null, adset_id:null, media_id:null, creative_id:null, products:[], ad:null}; var getServiceParams = function(){ return serviceParams; }; var addCampaignId = function(v){ serviceParams.campaign_id = v; }; var addMediaId = function(v){ serviceParams.media_id = v; } var addAdsetId = function(v){ serviceParams.adset_id = v; } var addCreativeId = function(v){ serviceParams.creative_id = v; } var addProducts = function(v){ serviceParams.products = v; } var addAd = function(v){ serviceParams.ad = v; } return { getServiceParams:getServiceParams, addCampaignId:addCampaignId, addMediaId:addMediaId, addAdsetId:addAdsetId, addCreativeId:addCreativeId, addProducts:addProducts, addAd:addAd }; //stackoverflow.com/questions/20181323/passing-data-between-controllers-in-angulaar-js }); //var wzAdSetApp = angular.module('wzAdSetApp', ['adSetCtrl', 'adSetService']).value('config', config_[0]); //var app = angular.module('app', ['app.mediaApp']); //app.value('config', config_[0]);
import mongoose from 'mongoose' import uniqueValidator from 'mongoose-unique-validator'; const osSchema = new mongoose.Schema({ family: {type: String, required: false}, name: {type: String, required: false}, version: {type: String, required: false}, platform: {type: String, required: false} }) const clientSchema = new mongoose.Schema({ type: {type: String, required: false}, name: {type: String, required: false}, version: {type: String, required: false}, }) const deviceSchema = new mongoose.Schema({ type: {type: String, required: false}, brand: {type: String, required: false}, model: {type: String, required: false}, }) const geoSchema = new mongoose.Schema({ country: {type: String, required: false}, region: {type: String, required: false}, timezone: {type: String, required: false}, city: {type: String, required: false}, }) // Defining user Mongoose Schema const SessionSchema = new mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', unique: false, required: true }, username: {type: String, unique: false, required: false, dropDups: true}, since: {type: Date, required: true, default: Date.now}, until: {type: Date, required: true, default: Date.now}, duration: {type: Number, required: false, default: 0}, request: {type: Number, required: false, default: 1}, agent: {type: String, unique: false, required: true, dropDups: true}, ip: {type: String, unique: false, required: true, dropDups: true}, geo: geoSchema, device: deviceSchema, client: clientSchema, os: osSchema }); SessionSchema.set('toJSON', {getters: true}); SessionSchema.plugin(uniqueValidator, {message: '{VALUE} ya existe. {PATH} debe ser unico.'}); export default mongoose.model('Session', SessionSchema);
/* * @lc app=leetcode id=140 lang=javascript * * [140] Word Break II */ // @lc code=start /** * @param {string} s * @param {string[]} wordDict * @return {string[]} */ var wordBreak = function(s, wordDict) { function isWord(str) { return wordDict.includes(str); } const result = []; let cur = []; const map = new Map(); function backtrack(index = 0) { if (index >= s.length) { result.push(cur.join(' ')); return; } for (let i = index + 1; i <= s.length; i++) { const str = s.slice(index, i); if (isWord(str)) { cur.push(str); backtrack(i); cur.pop(); } } } backtrack(); return result; }; // @lc code=end wordBreak('catsanddog', ["cat", "cats", "and", "sand", "dog"])
// carsModel.js var mongoose = require('mongoose'); // Setup schema var carSchema = mongoose.Schema({ placa: { type: String, uppercase: true, validate: /[a-zA-Z]{3}[0-9]{3}|[a-zA-Z]{3}[0-9]{2}[a-zA-Z]/, required: true }, marca:{type: String, required: true}, modelo: {type: String, required: true}, empleado: {type: String,required: true}, fechaIngreso: {type: String,required: true}, fechaSalida: {type: String,required: true}, estado: {type: String,required: true}, descripcion: {type: String,required: true}, procedimiento: {type: String,required: true}, created_date: { type: Date, default: Date.now } }); // Export Contact model var Car = module.exports = mongoose.model('car', carSchema); module.exports.get = function (callback, limit) { Car.find(callback).limit(limit); }
const sqlite = require("sqlite3").verbose(), db = new sqlite.Database("comics.db"), fs = require("fs"), path = require("path"), iconv = require("iconv-lite"), jsonPath = "./json/", reencode = function(s) { return iconv.decode(iconv.encode(s, "ISO-8859-1"), "utf8") } db.serialize(() => { db.run("DELETE FROM comics") const insertStmt = db.prepare("INSERT INTO comics VALUES(?,?,?,?,?,?,?,?,?)") const jsonFiles = fs.readdirSync(jsonPath) jsonFiles.forEach((filename) => { if (filename.charAt(0) != "c") return fs.readFile(jsonPath + filename, "utf8", (err, data) => { const comic = JSON.parse(data) insertStmt.run( comic.num, reencode(comic.title), comic.img, reencode(comic.alt), reencode(comic.transcript), comic.year, comic.month, comic.day, false ) }) }); })
export const TOGGLE_THEME = "DARK_THEME";
function byId(id) { return typeof id === "string" ? document.getElementById(id):id } function byClass(sClass, oParent){ var aClass = []; var reClass = new RegExp("(^| )" + sClass + "( |$)"); var aElem = byTagName("*",oParent); for (var i = 0; i < aElem.length; i++) { reClass.test(aElem[i].className) && aClass.push(aElem[i]); } return aClass; } function byTagName(elem,obj){ return (obj || document).getElementsByTagName(elem); } function getStyle(element,attr){ return parseFloat(element.currentStyle ? element.currentStyle[attr]:getComputedStyle(element,null)[attr]) } function jdFocus(obj){ var oSlider = byClass("slider_main")[0]; var aItem = byClass("slider_item",oSlider); var oIndicator = byClass("slider_indicator",oSlider)[0]; var aBtn = byTagName("i",oIndicator); var oPrev = byClass("slider_control_prev",oSlider)[0]; var oNext = byClass("slider_control_next",oSlider)[0]; var playTimer = null; var index = 0; for (var i = 0; i < aBtn.length; i++) { aBtn[i].index = i; aBtn[i].onmouseover = function(){ show(this.index); } } playTimer = setInterval(function(){ index++; index == aItem.length && (index = 0) show(index) },3000) oSlider.onmouseover = function(){ clearInterval(playTimer) } oSlider.onmouseout = function(){ playTimer = setInterval(function(){ index++; index == aItem.length && (index = 0) show(index) },3000) } oPrev.onclick = function(){ index == 0 && (index = aItem.length); index--; show(index) } oNext.onclick = function(){ index++; index == aItem.length && (index = 0) show(index) } function show(a){ for (var i = 0; i < aBtn.length; i++) { aBtn[i].className = "slider_indicator_btn"; } aBtn[a].className = "slider_indicator_btn slider_indicator_btn_active"; for (var j = 0; j < aItem.length; j++) { doMove(aItem[j],0) aItem[j].style.zIndex = 0; } doMove(aItem[a], 100) aItem[a].style.zIndex = 1; } function doMove(obj, iTarget){ clearInterval(obj.timer); obj.timer = setInterval(function(){ var iCur = getStyle(obj,"opacity"); iCur = iCur * 100; var iSpeed = (iTarget - iCur)/5; iSpeed = iSpeed > 0 ? Math.ceil(iSpeed):Math.floor(iSpeed); if(iCur == iTarget) { clearInterval(obj.timer) }else{ obj.style.opacity = (iSpeed + iCur)/100; obj.style.filter = "alpha(opacity="+iSpeed+iCur+")"; } },30) } } window.onload = function() { jdFocus(); }
import React, { Component } from 'react'; import ViewMasterclassEduOrgItem from './ViewMasterclassEduOrgItem' import '../App.css' class ViewMasterclassesEduOrg extends Component{ render(){ return this.props.workshop.map((current)=> <ViewMasterclassEduOrgItem key={current._id} current={current} Choose={this.props.Choose} delWorkshops={this.props.delWorkshops} updateWorkshops={this.props.updateWorkshops} />) } } export default ViewMasterclassesEduOrg
import React from 'react'; import ChatPage from './chatPage'; class WelcomePage extends React.Component { constructor(props) { super(props); this.state = { selectedUser: "", userName: "", usersList: [{ key: "Select Contact", value: "Select Contact" }, { id: "harry", key: "Harry Potter", value: "Harry Potter", source: "/profiles/Harry.jpg" }, { id: "hermione", key: "Hermione Granger", value: "Hermione Granger", source: "/profiles/Hermione.jpg" }, { id: "ron", key: "Ron Weasley", value: "Ron Weasley", source: "/profiles/Ron.jpg" }, { id: "hagrid", key: "Rubeus Hagrid", value: "Rubeus Hagrid", source: "/profiles/Hagrid.jpg" }, { id: "dumble", key: "Aberforth Dumbledore", value: "Aberforth Dumbledore", source: "/profiles/Dumbledore.jpg" }, { id: "snape", key: "Severus Snape", value: "Severus Snape", source: "/profiles/Snape.jpg" }, { id: "dobby", key: "Dobby", value: "Dobby", source: "/profiles/Dobby.jpg" }], contactList: [], imgSource: "" }; } handleChange = (event) => { if (event.target.value !== "Select Contact") { const contactList = this.state.usersList.filter((user) => { return user.value !== event.target.value; }); let imgSource = ""; this.state.usersList.map((user) => { if (user.value === event.target.value) { imgSource = user.source; } return user; }); this.setState({ imgSource: imgSource, userName: event.target.value, selectedUser: event.target.value, contactList: contactList }); } else { this.setState({ userName: "", selectedUser: event.target.value }); } } onLogout = (event) => { this.setState({ userName: "", selectedUser: "Select Contact" }); } render() { const { userName, selectedUser, usersList, contactList, imgSource } = this.state; return ( <div className="App-header"> <div className="App-title">JusCHAT</div> {userName ? <div> <div onClick={this.onLogout}> <img className="user-image" alt="userimg" height="40px" width="40px" src={imgSource} onClick={this.onClick} /> <label className="logout-user">Logout</label> </div> <ChatPage contactList={contactList} userName={userName} /> </div> : <div> <div className="login-user">Login as..</div> <div className="user-list"> <select className="user-dropdown" value={selectedUser} placeholder="Select User" onChange={this.handleChange}> {usersList.map((user) => { return <option key={user.key} value={user.value}>{user.value}</option> })} </select> </div> </div>} </div> ); } } export default WelcomePage;
/** * Created by Administrator on 2015.12.09.. */ /** * Created by Administrator on 2015.12.08.. */ hospitalNet.config(function(entityDefinitions){ entityDefinitions.helyseg = { table: 'szobak', entity: 'szoba', dataFields: { szam: { desc: 'Szobaszám', type: 'text', reqired: true }, ferohely: { desc: 'Férőhely', type: 'text', reqired: true }, tipus: { desc: 'Típus', type: 'select', options: { staticData: [ {id: 'elfekvo', label: 'Elfekvő'}, {id: 'muto', label: 'Műtő'}, {id: 'raktar', label: 'Raktár'}, {id: 'vizsgalo', label: 'Vizsgáló'} ] }, reqired: true } } }; });
/* * Application : global test 2 * ClassName : sys_script_include * Created On : 2020-09-03 13:00:14 * Created By : admin * Updated On : 2020-09-03 13:00:29 * Updated By : admin * URL : /sys_script_include.do?sys_id=e67b459ddbcf9410fcf41780399619a6 */ var gu = Class.create(); gu.prototype = { initialize: function() { }, type: 'gu' };
import React, { Component } from 'react'; import {DrawerNavigator} from 'react-navigation'; // import {createStackNavigator} from 'react-navigation'; import { createDrawerNavigator } from 'react-navigation-drawer'; import MapScreen from './screens/ScreenMapa' import LoginScreen from './screens/LoginScreen' import CuentaScreen from './screens/ScreenCuenta' import PreferenciasScreen from './screens/ScreenPreferencias' import { TouchableOpacity, StyleSheet, Text } from 'react-native'; export default class App extends Component { navegar() { this.props.navigation.openDrawer(); } render() { return ( <Drawer /> ); } } // const Stack = createStackNavigator({ // Map: MapScreen, // }) // const Mapa = createStackNavigator({ // Map: MapScreen, // }) const Drawer = createDrawerNavigator ({ Cuenta: {screen: CuentaScreen}, Preferencias: {screen: PreferenciasScreen}, LogIn: {screen: LoginScreen}, Inicio: {screen: MapScreen}, // Configuracion: {xcreen: ConfiguracionScreen}, // Stack: {screen: Stack}, // Mapa: {screen: Mapa}, })
import React from "react"; import AlbumWithArtworkComponent from './AlbumWithArtwork.component'; type Props = { albums: [Object] }; const AlbumGrid = (props: Props) => { const albums = props.albums.filter((album) => album.hasOwnProperty('coverArt')); return ( <div style={{'display': 'flex', 'flexWrap': 'wrap', 'flexDirection': 'row', 'alignItems': 'center'}}> { albums.map((album) => { return <AlbumWithArtworkComponent artist={album.artist} title={album.name} artworkID={album.coverArt} id={album.id}/> } ) } </div>); } export default AlbumGrid;
import React, { Component } from 'react'; import axios from 'axios' class FriendForm extends Component { constructor(props) { super(props); this.state = { name: '', age: '', email: '', } } addFriend = event => { event.preventDefault(); const friend = { name: this.state.name, age: this.state.age, email: this.state.email }; axios .post(`http://localhost:5000/friends`, friend) .then(savedNote => { console.log(savedNote); }) .catch(err => { console.log(err); }); this.setState({ name: '', age: '', email: '' }); window.location.reload(); }; handleTextInput = e => { this.setState({ [e.target.name]: e.target.value}); }; render() { return ( <div> <form className="Form__Container"> <input className="Friend__Form Form" type= 'text' placeholder= 'Name' name= 'name' value= { this.state.name } onChange={ this.handleTextInput } /> <input className="Friend__Form Form" type= 'text' placeholder= 'Age' name= 'age' value= { this.state.age } onChange={ this.handleTextInput } /> <input className="Friend__Form Form" type= 'text' placeholder= 'Email' name= 'email' value= { this.state.email } onChange= { this.handleTextInput } /> </form> <button onClick={ this.addFriend }>Make A Friend</button> </div> ) } } export default FriendForm;
const decks = [ { id: 1, name: 'Aggro Goodstuffs' }, { id: 2, name: 'Midrange Goodstuffs' } ] module.exports = { get } function get () { return decks.slice() }
class Todo { constructor(){ var x = Connector.getTodosFromDB() console.log(x) this.todos = [] } getTodos (){ return this.todos } getTodo(todoId) { return this.todos.find(({id}) => id === todoId) } addTodo(name, id) { this.todos = [...this.todos, {id, isDone: false, name}] addTodoIntoDB(name, id) } updateTodo(todoId, newTodo) { const index = this.todos.map(({id}) => id).indexOf(todoId); let oldName = this.todos[index].name let oldIsDone = this.todos[index].isDone this.todos[index].name = typeof newTodo.name !== "undefined" ? newTodo.name : oldName this.todos[index].isDone = typeof newTodo.isDone !== 'undefined' ? newTodo.isDone : oldIsDone } deleteTodo(todoId) { const index = this.todos.map(({id}) => id).indexOf(todoId); this.todos.splice(index, 1); } clearCompletedTodo () { this.todos = this.todos.filter(({isDone}) => !isDone) } toggleAllTodo (toggleStatus) { // console.log(this.todos) this.todos = this.todos.map(({id, name}) => ({ id, isDone: !toggleStatus, name })) } } export const TodoService = new Todo()
import React, { Component } from 'react'; class FormGuide extends Component { state = { searchValue: '', title: '', date: '', time: '', description: '', location: '', expertise: '', duration: '', } handleForm = (event) => { event.preventDefault(); const { title, date, time, description, location, expertise, duration } = this.state const data = {title, date, time, description, location, expertise, duration } this.props.onSubmit(data); } handleChange = (event) => { event.preventDefault(); this.setState({ [event.target.name]: event.target.value, }) } render() { return ( <form onSubmit={this.handleForm} className="create-edit-form"> <input type="text" placeholder="Title" name="title" className="create-edit-input" onChange={this.handleChange} value={this.state.title}/> <input type="text" placeholder="Description" name="description" className="create-edit-input desc" onChange={this.handleChange} value={this.state.description} /> <input type="text" placeholder="Location" name="location" className="create-edit-input" onChange={this.handleChange} value={this.state.location} /> <input type="text" placeholder="Date" name="date" className="create-edit-input" onChange={this.handleChange} value={this.state.date} /> <input type="text" placeholder="Time" name="time" className="create-edit-input" onChange={this.handleChange} value={this.state.time} /> <button type="submit" className="btn-create">Create</button> </form> ); } } export default FormGuide;
const test = require('ava'); const sdk = require('../src/sdk'); test('sdk projects', async (t) => { const projects = await sdk.getProjects(); t.is(projects.length > 0, true); }); test('sdk sections', async (t) => { const sections = await sdk.getSections(); t.is(sections.length > 0, true); }); test('sdk labels', async (t) => { const labels = await sdk.getLabels(); t.is(labels.length > 0, true); }); test('sdk active tasks', async (t) => { const tasks = await sdk.getActiveTasks(); t.is(tasks.length > 0, true); }); test('sdk complete tasks', async (t) => { const tasks = await sdk.getCompletedTasks(); t.is(tasks.length >= 0, true); });
module.exports = { allowList: [ /^\/ch\/\d+\/mix\/fader$/, // /^\/ch\/\d+\/preamp$/, ], denyList: [ /^meters\/\d+$/, /^\/batchsubscribe$/, /^\/xremotenfb$/, /^\/renew$/, ], };
'use-strict'; var util = require('util'); var format = util.format; var type = null; var start = function(str){ return format('%s - %s starts...',str,type); }; var end = function(str){ return format('%s - %s end...',str,type); }; var error = function(str){ return format('%s - %s failed...',str,type); }; var setType = function(type){ type = type; }; module.exports = { Start : start, End : end, Error : error, SetType : setType, Type : type }
/* ============================================================ * directives.js * All common functionality & their respective directive * ============================================================ */ angular.module('app') .directive('postcardModal', function () { return { restrict: 'EA', templateUrl: "tpl_postcardmodal", link: function ($scope, element, attrs) { element.bind('click', function (event) { $scope.$apply(attrs.postcardModal); }); } }; }); angular.module('app') .directive('postcard', function () { return { restrict: 'A', link: function ($scope, element, attrs) { element.bind('click', function (event) { $scope.$apply(attrs.postcard); }); }, controller: function ($scope, $http, $timeout, inArray, $state) { // Open share popup.. $scope.popUpDropdrow = 0; $scope.openSharePostPopUp = function (post_id) { }; /*---------- Open popUp drop down menu when user click on .... sing ----------------------- */ // This function user for postcard modal and post card details .. $scope.report = function (post) { var $newShrBtns = $(".newShrBtns"); $newShrBtns.find(".otherSubsh").show(); $newShrBtns.find(".subOverlaysh").show(); // alert('clicked'); // if($newShrBtns.find(".otherSubsh").parents('.profileCommentBoxTop').hasClass('has-big-zindex')){ // $newShrBtns.find(".otherSubsh").parents('.profileCommentBoxTop').removeClass('has-big-zindex') // } else { // $newShrBtns.find(".otherSubsh").parents('.profileCommentBoxTop').addClass('has-big-zindex') // } var flag = 0; if ($state.current.name == 'profile') { if (post.child_post_user_id != $scope.user.id) { flag = 1; } else { flag = 0; } } else if ($state.current.name == 'account') { if (post.created_by != $scope.user.id) { flag = 1; } else { flag = 0; } } else { if (post.created_by == $scope.user.id || post.child_post_user_id == $scope.user.id) { flag = 0; } else { flag = 1; } } $scope.isShowPostReportLink = flag; }; $scope.closeOverLayout = function () { $(".subOverlaysh , .otherSubsh").hide(); }; } }; }); angular.module('app') .directive('webscrolling', function () { return { restrict: 'A', link: function (scope, element, attrs) { element.bind("scroll", function () { var scrollTopHeightM = 5; var scrollOuterPosM = $(".modalMobileScroll > .row").offset().top - 38; var scrollOuterPosnewM = Math.abs(scrollOuterPosM) var scrollPercentM = 100 * (scrollOuterPosnewM - scrollTopHeightM) / ($("#myModal .profileNewLeft").height() - $(".modalMobileScroll").height()); if ($(".profileNewLeft").innerHeight() >= $(".modalMobileScroll").innerHeight() && scrollOuterPosM <= 0) { $(".mobileBarLong").css("width", scrollPercentM + "%"); } }); } } }); angular.module('app') .directive('webscrolling2', function () { return { restrict: 'A', link: function (scope, element, attrs) { $(window).bind("scroll", function () { var scrollTopHeightM2 = 5; var scrollOuterPosM2 = $("body").scrollTop() - 38; var scrollOuterPosnewM2 = Math.abs(scrollOuterPosM2) var scrollPercentM2 = 100 * (scrollOuterPosnewM2 - scrollTopHeightM2) / ($(".cardDetailsPG_modal .profileNewLeft").height() - $(window).height()); if ($(".cardDetailsPG_modal .profileNewLeft").innerHeight() >= $(window).height() && scrollOuterPosM2 >= 0) { $(".mobileBarLong2").css("width", scrollPercentM2 + "%"); } }); } } }); /* ====================================================================== * Directive: OTHERS , DELETE POSTCARD MODAL AND REPORT POST CARD MODAL * Prepare Bootstrap dropdowns to match Pages theme * ===================================================================== */ angular.module('app') .directive('postCardMenu', function ($rootScope, $http) { return { restrict: 'E', link: function ($scope, element, attrs) { $scope.openDeletePostModal = function (post_id) { $rootScope.mypostid = post_id; $scope.closeOverLayout(); }; // Report post. $scope.openReportPostModal = function (post_id) { // Initialize. $rootScope.report_post_ids = []; $rootScope.reportPostModalLoader = true; var url = '/api/fetchReportPostData'; var postData = { post_id: post_id }; $http.post(url, postData) .then(function (response) { var report_ids = response.data.report_ids; if (report_ids.length > 0) { report_ids.forEach(function (v) { $rootScope.report_post_ids.push(v); }); } $rootScope.reportPostModalLoader = false; }, function (response) { $rootScope.reportPostModalLoader = false; } ); $rootScope.mypostid = post_id; $scope.closeOverLayout(); }; // After clicking downvote then postcard other will be closed $scope.closeOverLayout = function () { $scope.popUpDropdrow = 0; $scope.popUpReportDropdrow = 0; }; }, templateUrl: 'tpl.post-card-menu' }; }); angular.module('app') .directive('deletePostModal', function ($http) { return { restrict: 'E', link: function ($scope, element, attrs) { // Delete postcard and also their child postcard also.. $scope.deleteMyPost = function (post_id) { $scope.disableClick = true; $http({ method: 'POST', url: "angular/deleteMyPost", params: {post_id: post_id} }).then(function (response) { location.href = 'profile'; }, function (response) { alert('Sorry! we cannot process your request.'); }); } }, templateUrl: 'tpl_deletePostModal' }; }); angular.module('app') .directive('reportPostModal', function () { return { restrict: 'E', link: function (scope, element, attrs) { }, templateUrl: 'tpl_reportPostModal', controller: function ($scope, $log, $http) { $scope.doPostReport = function (post_id, report_id) { $("#reportPostModal").modal("toggle"); $http({ method: 'POST', url: "angular/doPostReport", params: { post_id: post_id, report_id: report_id } }).then(function (response) { }, function (response) { // $log.info('Some error is occurred.'); }); } } }; }); /* ============================================================ * Directive: POST UPVOTES AND DOWNVOTES * Prepare Bootstrap dropdowns to match Pages theme * ============================================================ */ angular.module('app') .directive('upvotes', function () { return { restrict: 'A', link: function (scope, element, attrs) { element.bind('click', function (event) { scope.$apply(attrs.upvotes); }); }, controller: function ($scope, $http, inArray, $state, userDataService) { $scope.doUpvotes = function (post_id, childPostId, type) { // Dynamic binding new edition 24-11-2016 if (angular.isArray($scope.commonData.allPosts)) { angular.forEach($scope.commonData.allPosts, function (value, key) { if (value.id == post_id) { if ($scope.commonData.allPosts[key].isUpvote == 'N') { $scope.commonData.allPosts[key].isUpvote = 'Y'; $scope.commonData.allPosts[key].upvotes = $scope.commonData.allPosts[key].upvotes + 1; } else { $scope.commonData.allPosts[key].isUpvote = 'N'; //console.log('2'); $scope.commonData.allPosts[key].upvotes = $scope.commonData.allPosts[key].upvotes - 1; } if ($scope.commonData.allPosts[key].isDownvote == 'Y') { $scope.commonData.allPosts[key].downvotes = $scope.commonData.allPosts[key].downvotes - 1; $scope.commonData.allPosts[key].isDownvote = 'N'; } } }); } // For postcard if (type == 'M') { if ($scope.post.isUpvote == 'N') { $scope.post.isUpvote = 'Y'; $scope.post.upvotes = $scope.post.upvotes + 1 // Update post point on modal :: // if logged in user and post creator is same then point is not update if ($scope.post.created_by != $scope.user.id) { $scope.post.points = $scope.post.points + 2; } } else { $scope.post.isUpvote = 'N'; $scope.post.upvotes = $scope.post.upvotes - 1 // Update post point on modal :: // if logged in user and post creator is same then point is not update if ($scope.post.created_by != $scope.user.id) { $scope.post.points = $scope.post.points - 2; } } if ($scope.post.isDownvote == 'Y') { $scope.post.downvotes = $scope.post.downvotes - 1; $scope.post.isDownvote = 'N'; // Update post point on modal :: // if downvote cancel then execute ... // if logged in user and post creator is same then point is not update if ($scope.post.created_by != $scope.user.id) { $scope.post.points = $scope.post.points + 2; } } } // end Dynamic binding new edition 24-11-2016 $http({ method: "POST", url: "angular/upVotePost", params: {post_id: post_id, childPostId: childPostId} }).then(function (response) { if (!$scope.post) { $scope.post = {}; $scope.post.user = {}; } /* ============================================================ * For Updating profile points * ============================================================ */ if (angular.isArray($scope.post.getUser)) { angular.forEach($scope.post.getUser, function (value, key) { angular.forEach(response.data.user, function (val, k) { if (value.id == val.id) { $scope.post.getUser[key].points = val.points; } }); }); } // For updateing profile points if ($state.current.name == 'profile' || $state.current.name == 'account') { if ($scope.userData.id != $scope.user.id) { var user_points = response.data.user[0].points; userDataService.updateUserData(user_points); userDataService.getData(); } } }); }; $scope.doDownVotes = function (post_id, childPostId, type) { // Dynamic binding new edition 24-11-2016 if (angular.isArray($scope.commonData.allPosts)) { angular.forEach($scope.commonData.allPosts, function (value, key) { if (value.id == post_id) { if ($scope.commonData.allPosts[key].isDownvote == 'N') { $scope.commonData.allPosts[key].isDownvote = 'Y'; $scope.commonData.allPosts[key].downvotes = $scope.commonData.allPosts[key].downvotes + 1; } else { $scope.commonData.allPosts[key].isDownvote = 'N'; $scope.commonData.allPosts[key].downvotes = $scope.commonData.allPosts[key].downvotes - 1; } if ($scope.commonData.allPosts[key].isUpvote == 'Y') { $scope.commonData.allPosts[key].upvotes = $scope.commonData.allPosts[key].upvotes - 1; $scope.commonData.allPosts[key].isUpvote = 'N'; } } }); } // For postcard if (type == 'M' || type == 'PD') { // M for modal if ($scope.post.isDownvote == 'N') { $scope.post.isDownvote = 'Y'; $scope.post.downvotes = $scope.post.downvotes + 1 // Update post point on modal :: // if logged in user and post creator is same then point is not update if ($scope.post.created_by != $scope.user.id) { $scope.post.points = $scope.post.points - 2; } } else { $scope.post.isDownvote = 'N'; $scope.post.downvotes = $scope.post.downvotes - 1 // Update post point on modal :: // if logged in user and post creator is same then point is not update if ($scope.post.created_by != $scope.user.id) { $scope.post.points = $scope.post.points + 2; } } if ($scope.post.isUpvote == 'Y') { $scope.post.upvotes = $scope.post.upvotes - 1; $scope.post.isUpvote = 'N'; // Update post point on modal :: // if upvote cancel then execute ... // if logged in user and post creator is same then point is not update if ($scope.post.created_by != $scope.user.id) { $scope.post.points = $scope.post.points + 2; } } } // Dynamic binding new edition 24-11-2016 $http({ method: "POST", url: "angular/downVotePost", params: {post_id: post_id, childPostId: childPostId} }).then(function (response) { if (!$scope.post) { $scope.post = {}; $scope.post.user = {}; } /* ============================================================ * For Updating profile points * * ============================================================ */ if (angular.isArray($scope.post.getUser)) { angular.forEach($scope.post.getUser, function (value, key) { angular.forEach(response.data.user, function (val, k) { if (value.id == val.id) { $scope.post.getUser[key].points = val.points; } }); }); } // For updateing profile points if ($state.current.name == 'profile' || $state.current.name == 'account') { if ($scope.userData.id != $scope.user.id) { var user_points = response.data.user[0].points; userDataService.updateUserData(user_points); userDataService.getData(); } } $(".subOverlaysh , .otherSubsh").hide(); }); }; } }; }); /* ============================================================ * Directive: Open share post modal, share post * Prepare Bootstrap dropdowns to match Pages theme * ============================================================ */ angular.module('app') .directive('sharepostCard', function () { return { restrict: 'E', templateUrl: "tpl.sharepost-card", link: function (scope, element, attrs) { }, controller: function ($scope, $http, $timeout) { // Initialize privacies.. $scope.privacies = {}; // Fetch privacies.. $http.get('api/privacy').then(function (response) { if (response.data) { $scope.privacies = response.data; $scope.privacy_id = $scope.privacies[0]; } }); $scope.sharePopUp = function (post_id, childPostUserId, childPostId, is_openFromPostcardModal) { $scope.sharedPost = {}; var url = 'angular/showPostDetails'; var postData = { post_id: post_id, child_post_id: childPostId, is_briefed: 1, initiator: 'share_popup' }; $http.post(url, postData) .then(function (response) { $scope.sharedPost = response.data.post; // $scope.loginUser = response.data.user; $scope.popUpDropdrow = 0; $scope.postId = post_id; $scope.caption = ''; $scope.postUserId = childPostUserId; $scope.childPostId = childPostId; // find original post creator :: var postModalUser = response.data.post.getUser; angular.forEach(postModalUser, function (value, key) { $scope.originalPostUserName = value.username; $scope.originalPostFirstName = value.first_name; $scope.originalPostLastName = value.last_name; $scope.originalPostProfileImage = value.thumb_image_url; $scope.originalPostUserColor = (value.id % 2 == 0) ? 's1' : 's0'; }); $timeout(function () { angular.element("#shareModal").modal(); angular.element(".subOverlay").triggerHandler("click"); $timeout(function () { angular.element("html").addClass("scrollHidden"); angular.element("body").addClass("modal-open"); }, 1000); if (is_openFromPostcardModal == 1) { $("#myModal").modal("toggle"); } }, 100); }); }; } }; }); angular.module('app') .directive('share', function (notify, $state) { return { restrict: 'A', link: function (scope, element, attrs) { element.bind('click', function () { scope.$apply(attrs.share); }); }, controller: function ($scope, $http, $timeout) { $scope.shareThisPost = function (post_id, childPostId, postUserId) { $http({ method: "POST", url: "angular/shareThisPost", params: { caption: $scope.caption, post_id: $scope.postId, profile_id: postUserId, childPostId: childPostId, privacy_id: $scope.privacy_id } }).then(function (response) { $("#shareModal").modal('toggle'); $(".sharedSuccessLoader").show(); $timeout(function () { $(".sharedSuccessLoader").hide(); }, 2000); $timeout(function () { var notification = { 'message': 'You have successfully re-share this post.', 'color': 'success', 'timeout': 5000 }; notify(notification); }, 2100); $timeout(function () { $state.go("profile"); }, 3000); }); }; } }; }); /* ============================================================ * Directive: Postview Scrolling * ============================================================ */ angular.module('app') .directive('viewpost', function (userDataService) { return { restrict: "A", link: function (scope, element, attrs) { element.bind("click", function () { scope.$apply(attrs.viewpost); }); }, controller: function ($scope, $http, $window, $state) { $scope.externalLink = function (postID, childPostID) { $http({ method: "POST", url: "angular/viewPost", data: { postID: parseInt(postID), childPostID: childPostID, postType: 4 } }).then(function (response) { // userData is update on proilfe or account . if ($state.current.name == 'profile' || $state.current.name == 'account') { var points = response.data.post.getUsers[0].points; userDataService.updateUserData(points); userDataService.getData(); } // Update dynamically total number of post view var p; for (p in $scope.commonData.allPosts) { if ($scope.commonData.allPosts[p].id == postID) { $scope.commonData.allPosts[p].totalPostViews = response.data.post.totalPostViews; // break; } } // update user points dynamically on popup........ if (angular.isArray($scope.post.getUser)) { angular.forEach($scope.post.getUser, function (value, key) { angular.forEach(response.data.post.getUsers, function (val, k) { if (value.id == val.id) { $scope.post.getUser[key].points = val.points; } }); }); } // update total access on popup :: $scope.post.totalPostViews = response.data.post.totalPostViews; $scope.post.points = response.data.post.points; // $window.open(external_link, '_blank'); }, function (error) { // console.log('Error occurred.'); }); }; } }; }); /* ============================================================ * Directive: PROFILE NAV SLIDER * ============================================================ */ angular.module('app') .directive('exploreTab', function () { return { restrict: 'E', templateUrl: "tpl_explore_tab" }; }); /*angular.module("app") .filter('displayBestTab', function () { return function (x) { }; });*/ /* ============================================================ * Directive: Follow users * ============================================================ */ angular.module('app') .directive('allfollowuser', function () { return { restrict: 'A', link: function ($scope, element, attrs) { element.bind('click', function (event) { $scope.$apply(attrs.allfollowuser); }); }, controller: function ($scope, $http, $timeout, inArray, $state) { /* ============================================================ * Functionality: Profile page follow,unfollow only postcard modal * ============================================================ */ $scope.followUser = function (user_id, type, following) { // For instance update if ($state.current.name == 'profile' || $state.current.name == 'account') { if ($scope.userData.username == $scope.user.username) { if (inArray.arrayIndexOf($scope.userFollowing, user_id) != -1) { $scope.userFollowing.splice(inArray.arrayIndexOf($scope.userFollowing, user_id), 1); angular.isArray($scope.userData.following) { angular.forEach($scope.userData.following, function (val, key) { if (val.user_id == user_id) { $scope.userData.following.splice(key, 1); $scope.userDataTotalFollowing = $scope.userData.following.length; return false; } }); } $scope.userData.userDataTotalFollowing = $scope.userFollowing.length; if (angular.isArray($scope.post.getUser)) { angular.forEach($scope.post.getUser, function (value, key) { if (value.id === user_id) { $scope.post.getUser[key].is_follow = $scope.post.getUser[key].is_follow - 1; } }); } } else { $scope.userFollowing.push(parseInt(user_id)); $scope.userData.userDataTotalFollowing = $scope.userData.following.length; if (angular.isArray($scope.post.getUser)) { angular.forEach($scope.post.getUser, function (value, key) { if (value.id === user_id) { $scope.post.getUser[key].is_follow = $scope.post.getUser[key].is_follow + 1; } }); } } } else { if (inArray.arrayIndexOf($scope.userFollowing, user_id) != -1) { $scope.userFollowing.splice(inArray.arrayIndexOf($scope.userFollowing, user_id), 1); if (angular.isArray($scope.post.getUser)) { angular.forEach($scope.post.getUser, function (value, key) { if (value.id === user_id) { $scope.post.getUser[key].is_follow = $scope.post.getUser[key].is_follow - 1; } }); } $scope.resetPostData(); $scope.loadMore('all'); } else { $scope.userFollowing.push(parseInt(user_id)); if (angular.isArray($scope.post.getUser)) { angular.forEach($scope.post.getUser, function (value, key) { if (value.id === user_id) { $scope.post.getUser[key].is_follow = $scope.post.getUser[key].is_follow + 1; } }); } $scope.userData.userDataTotalFollower = $scope.userData.userDataTotalFollower + 1; $scope.resetPostData(); $scope.loadMore('all'); } } } else { if (inArray.arrayIndexOf($scope.userFollowing, user_id) != -1) { $scope.userFollowing.splice(inArray.arrayIndexOf($scope.userFollowing, user_id), 1); // start this block use for post detail page if ($scope.post && angular.isArray($scope.post.getUser)) { angular.forEach($scope.post.getUser, function (value, key) { if (value.id === user_id) { $scope.post.getUser[key].is_follow = $scope.post.getUser[key].is_follow - 1; } }); } } else { $scope.userFollowing.push(parseInt(user_id)); // start this block use for post detail page if ($scope.post && angular.isArray($scope.post.getUser)) { angular.forEach($scope.post.getUser, function (value, key) { if (value.id === user_id) { $scope.post.getUser[key].is_follow = $scope.post.getUser[key].is_follow + 1; } }); } } } // end $http({ method: "POST", url: "angular/followUser", params: {user_id: user_id, following: following} }).then(function (response) { if ($state.current.name == 'profile' || $state.current.name == 'account') { if ($scope.userData.username == $scope.user.username) { if (inArray.arrayIndexOf($scope.userFollowing, user_id) != -1) { } else { $scope.userData.following.push(response.data.getFollower); } } } }); }; /* ======================================================================= * Functionality: Follow user form follower tab . If login user follow from own profile then increase number of following * ====================================================================== */ $scope.followUserFromFollowerTab = function (user_id, type, following) { if ($scope.userData.username == $scope.user.username) { if (inArray.arrayIndexOf($scope.userFollowing, user_id) != -1) { $scope.userFollowing.splice(inArray.arrayIndexOf($scope.userFollowing, user_id), 1); $scope.userData.userDataTotalFollowing = $scope.userData.userDataTotalFollowing - 1; } else { $scope.userFollowing.push(parseInt(user_id)); $scope.userData.userDataTotalFollowing = $scope.userData.userDataTotalFollowing + 1; } } else { if (inArray.arrayIndexOf($scope.userFollowing, user_id) != -1) { $scope.userFollowing.splice(inArray.arrayIndexOf($scope.userFollowing, user_id), 1); } else { $scope.userFollowing.push(parseInt(user_id)); } } $http({ method: "POST", url: "angular/followUser", params: {user_id: user_id, following: following} }).then(function (response) { }); }; /* ======================================================================= Functionality: Follow user form following tab . If login user follow from own profile then increase number of following ====================================================================== */ $scope.followUserFromFollowingTab = function (user_id, type, following) { if ($scope.userData.username == $scope.user.username) { if (inArray.arrayIndexOf($scope.userFollowing, user_id) != -1) { $scope.userFollowing.splice(inArray.arrayIndexOf($scope.userFollowing, user_id), 1); $scope.userData.userDataTotalFollowing = $scope.userData.userDataTotalFollowing - 1; } else { $scope.userFollowing.push(parseInt(user_id)); $scope.userData.userDataTotalFollowing = $scope.userData.userDataTotalFollowing + 1; } } else { if (inArray.arrayIndexOf($scope.userFollowing, user_id) != -1) { $scope.userFollowing.splice(inArray.arrayIndexOf($scope.userFollowing, user_id), 1); } else { $scope.userFollowing.push(parseInt(user_id)); } } $http({ method: "POST", url: "angular/followUser", params: {user_id: user_id, following: following} }).then(function (response) { }); } /* ======================================================================= * Functionality: Follow user form timeline follow tab and tag page follow button * postcard and postcard modal * ====================================================================== */ $scope.followTab = function (user_id, type, following) { if (type == 'T') { if (inArray.arrayIndexOf($scope.userFollowing, user_id) != -1) { $scope.userFollowing.splice(inArray.arrayIndexOf($scope.userFollowing, user_id), 1); $scope.userData.userDataTotalFollower = $scope.userData.userDataTotalFollower - 1; $scope.resetPostData(); //$scope.loadMore('all'); setTimeout(function () { $scope.loadMore('all'); }, 500); } else { $scope.userFollowing.push(parseInt(user_id)); $scope.userData.userDataTotalFollower = $scope.userData.userDataTotalFollower + 1; $scope.resetPostData(); //$scope.loadMore('all'); setTimeout(function () { $scope.loadMore('all'); }, 500); } } $http({ method: "POST", url: "angular/followUser", params: {user_id: user_id, following: following} }).then(function (response) { }); } } }; }); /* ============================================================ * Directive: Report comments * ============================================================ */ angular.module('app') .directive('reportCommentModal', function () { return { restrict: 'E', link: function (scope, element, attrs) { }, templateUrl: 'tpl_reportCommentModal', controller: function ($scope, $log, $http) { $scope.openReportCommentModal = function (comment_id) { // Initialize. $scope.report_comment_ids = []; $scope.reportCommentModalLoader = true; var url = '/api/fetchReportCommentData'; var postData = { comment_id: comment_id }; $http.post(url, postData) .then(function (response) { var report_ids = response.data.report_ids; if (report_ids.length > 0) { report_ids.forEach(function (v) { $scope.report_comment_ids.push(v); }); } $scope.reportCommentModalLoader = false; }, function () { $scope.reportCommentModalLoader = false; } ); $scope.comment_id = comment_id; $scope.closeOverLayout(); }; $scope.doCommentReport = function (commentId, reportId) { //$("#reportCommentModal").modal("toggle"); $('.reporPopupVW').hide(); $http({ method: 'POST', url: "angular/doCommentReport", data: { commentId: commentId, reportId: reportId } }).then(function (response) { }, function (response) { $log.info('Some error is occurred.'); }); } } }; }); /* ============================================================ * Directive: Social sharing * Facebook Share API * ============================================================ */ angular.module('app') .directive('socialSharing', function ($window, $http, $interval, notify, $timeout) { return { restrict: "A", link: function ($scope, element, attrs) { element.bind('click', function (event) { $scope.$apply(attrs.socialSharing); }); $scope.facebook = function (post, type) { $window.fbAsyncInit = function () { FB.init({ appId: '1050589168353691', status: true, cookie: true, xfbml: true, version: 'v2.4' }); }; var obj = {}; var thumbnail = ''; obj.method = 'feed'; if (post.post_type == 5) { // :: For status post :: //StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,""); obj.title = post.caption.replace(/(<([^>]+)>)/ig, ""); } else { if (post.title != '') { obj.title = post.title.replace(/(<([^>]+)>)/ig, ""); } else { obj.title = post.caption.replace(/(<([^>]+)>)/ig, ""); } } if (post.post_url != '') { obj.link = post.post_url; } if (post.post_type == 3) { // :: For article post :: if (post.short_description == '') { var OriginalString = post.content; var cont = OriginalString.replace(/(<([^>]+)>)/ig, ""); obj.description = cont.substr(0, 100); } else if (post.short_description != '') { obj.description = post.short_description; } else { obj.description = " "; } } else { if (post.short_description != '') { obj.description = post.short_description; } else { obj.description = " "; } } if (post.post_type == 1 || post.post_type == 3 || post.post_type == 4) { if (post.image != '') { obj.picture = post.image; } } else if (post.post_type == 2) { // For video post .. if (post.embed_code != '') { // for embed code if (post.embed_code_type == 'youtube') { var pic = 'https://img.youtube.com/vi/' + post.videoid + '/0.jpg'; obj.picture = pic; } else if (post.embed_code_type == 'dailymotion') { thumbnail = 'https://www.dailymotion.com/thumbnail/video/' + post.videoid; obj.picture = thumbnail; } else if (post.embed_code_type == 'vimeo') { thumbnail = 'https://i.vimeocdn.com/video/' + post.videoid + '_640.jpg'; obj.picture = thumbnail; } //obj.source=post.embed_code; } else if (post.video != '') { // html5 var video_poster = post.video_poster; obj.picture = video_poster; var url = post.video obj.source = url; } } else if (post.post_type == 5) { // for status post if (post.image != '') { obj.picture = post.image; } else { if (post.embed_code != '') { // for embed code if (post.embed_code_type == 'youtube') { var pic = 'https://img.youtube.com/vi/' + post.videoid + '/0.jpg'; obj.picture = pic; } else if (post.embed_code_type == 'dailymotion') { thumbnail = 'https://www.dailymotion.com/thumbnail/video/' + post.videoid; obj.picture = thumbnail; } else if (post.embed_code_type == 'vimeo') { thumbnail = 'https://i.vimeocdn.com/video/' + post.videoid + '_640.jpg'; obj.picture = thumbnail; } } else if (post.video != '') { // html5 var video_poster = post.video_poster; obj.picture = video_poster; var url = post.video; obj.source = url; } } } FB.ui(obj, function (response) { if (response && !response.error_message) { // update postcard total share ... if (angular.isArray($scope.commonData.allPosts)) { angular.forEach($scope.commonData.allPosts, function (value, key) { if (value.id == post.id) { $scope.commonData.allPosts[key].totalShare = $scope.commonData.allPosts[key].totalShare + 1; return false; } }); } // update postcard modal if (type == 'M') { if ($scope.user.id != $scope.post.child_post_user_id) { $scope.post.points = $scope.post.points + 10; } $scope.post.totalShare = $scope.post.totalShare + 1; $scope.post.totalFBshare = $scope.post.totalFBshare + 1; } $http({ method: 'POST', url: "sharedPostInSocialNetworkingForFacebook", data: { post_id: post.id, child_post_id: post.child_post_id, activityType: 4, // shared to facebook } }).then(function (response) { }, function (response) { console.log('Some error is occurred.'); }); } else { console.log('Error while posting.'); } }); }; // end of a function $window.$scope = $scope; $scope.twitter = function (post, card_type) { flag = 0; var callAjax = 0; if ($scope.user.guest == 0) { $http({ method: "POST", url: "accessTokenVerify", }).then(function (response) { flag = response.data; $scope.twitterPopUp(flag, post, card_type) }, function (eror) { console.log('some error has occurred'); }); } else { flag = 0; $scope.twitterPopUp(flag, post, card_type) } }; // end of a twitter function $scope.twitterPopUp = function (flag, post, card_type) { if (parseInt(flag) == 0) { var left = screen.width / 2 - 200; var top = screen.height / 2 - 250; var popup = $window.open('twitter_connect/' + 1, '', 'left=' + left + ',top=' + top + ',width=550,height=450,personalbar=0,toolbar=0,scrollbars=0,resizable=0'); var interval = 1000; // create an ever increasing interval to check a certain global value getting assigned in the var i = $interval(function () { interval += 500; try { // value is the user_id returned from paypal if (popup.value) { $interval.cancel(i); popup.close(); $scope.postToTwitter(post, card_type); } } catch (e) { console.error(e); } }, interval); } else { $scope.postToTwitter(post, card_type); } }; $scope.postToTwitter = function (post, card_type) { // **** start update scope data ***** // update postcard total share ... if (angular.isArray($scope.commonData.allPosts)) { angular.forEach($scope.commonData.allPosts, function (value, key) { if (value.id == post.id) { $scope.commonData.allPosts[key].totalShare = $scope.commonData.allPosts[key].totalShare + 1; return false; } }); } // update postcard modal if (card_type == 'M') { if ($scope.user.id != $scope.post.child_post_user_id) { $scope.post.points = $scope.post.points + 10; } $scope.post.totalShare = $scope.post.totalShare + 1; $scope.post.totalTwittershare = $scope.post.totalTwittershare + 1; } // ***** end update scope data ****** $timeout(function () { var notification = { 'message': 'You have successfully shared this post to twitter.', 'color': 'success', 'timeout': 5000 }; notify(notification); }, 2100); $http({ method: 'POST', url: "postToTwitter", data: { post_id: post.id, child_post_id: post.child_post_id, } }).then(function (response) { }, function (error) { console.log('Some error is occurred.'); }); }; }, } }); /* ============================================================ * Directive: Prompt Sign in Box * Alert for Non logged in users * ============================================================ */ angular.module('app') .directive('promptSigninBox', function () { return { restrict: 'E', link: function ($scope, element, attrs) { }, templateUrl: 'tpl_promptSinginBox' }; }); /* ============================================================ * Directive: Book Mark * User can bookmark through * ============================================================ */ angular.module('app') .directive('bookMark', function ($http) { return { restrict: "A", link: function ($scope, element, attrs) { element.bind('click', function (event) { $scope.$apply(attrs.bookMark); }); }, controller: function ($scope) { $scope.bookMarkProcess = function (postID, type) { // M : Modal ,P: Postcard if (angular.isArray($scope.commonData.allPosts)) { var isChange = 0; angular.forEach($scope.commonData.allPosts, function (value, key) { if ($scope.commonData.allPosts[key].id == postID) { if ($scope.commonData.allPosts[key].isBookMark == 'Y') { $scope.commonData.allPosts[key].isBookMark = 'N'; // For left panel update total book marks isChange = 1; } else { $scope.commonData.allPosts[key].isBookMark = 'Y'; // For left panel update total book marks isChange = 2; } return; } }); } if (type == 'M') { // Dynamick binding for postcard modal if ($scope.post.isBookMark == 'Y') { $scope.post.isBookMark = 'N'; $scope.post.totalBookMark = $scope.post.totalBookMark - 1; // post total bookmark isChange = 1; } else { $scope.post.isBookMark = 'Y'; $scope.post.totalBookMark = $scope.post.totalBookMark + 1; // post total book mark isChange = 2; } } // user total bookmark if (isChange == 1) { $scope.user.totalBookMarks = $scope.user.totalBookMarks - 1; } if (isChange == 2) { $scope.user.totalBookMarks = $scope.user.totalBookMarks + 1; } $http({ method: 'POST', url: "angular/bookmark", data: {postID: postID} }).then(function (response) { }, function (error) { console.log('Sorry! we cannot process your request.'); }); } } }; }); /* ============================================================ * Directive: Connect to social media * facebook * ============================================================ */ angular.module('app') .directive('connectSocialMedia', function ($window, $http, $interval) { return { restrict: 'A', link: function ($scope, element, attrs) { element.bind('click', function (event) { $scope.$apply(attrs.connectSocialMedia); }); // connect to facebook $window.$scope = $scope; $scope.connectFacebook = function () { var left = screen.width / 2 - 200; var top = screen.height / 2 - 250; var popup = $window.open('facebookLogin/', '', 'left=' + left + ',top=' + top + ',width=550,height=450,personalbar=0,toolbar=0,scrollbars=0,resizable=0'); var interval = 1000; // create an ever increasing interval to check a certain global value getting assigned in the var i = $interval(function () { interval += 500; try { // value is the user_id returned from paypal if (popup.value) { $interval.cancel(i); popup.close(); } } catch (e) { console.error(e); } }, interval); }; } }; });
import { SET_SHOP_CATEGORIES, // SET_NAVBAR_LINKS, SET_SHOP_PRODUCTS, FILTER_PRODUCTS_WITH_CATEGORY_ID, FILTER_PRODUCTS_WITH_QUERY, } from './types' export function filterProductsWithQuery(fields) { return { type: FILTER_PRODUCTS_WITH_QUERY, payload: fields, } } export function filterProductsWithCategoryId(id) { console.log(id) return { type: FILTER_PRODUCTS_WITH_CATEGORY_ID, payload: id, } } export function fetchShopCategories() { return { type: SET_SHOP_CATEGORIES, payload: [ { id: 0, title: 'All', }, { id: 1, title: 'JavaScript', }, { id: 2, title: 'UX/UI', }, { id: 3, title: 'Data-Management', }, { id: 4, title: 'Abstract Concepts for Junior Devs', }, ], } } export function fetchShopProducts() { return { type: SET_SHOP_PRODUCTS, payload: [ { id: 0, title: 'JavaScript in the browser', description: 'Learn all there is to know about JavaScripts powerful V8 engine', price: 12.99, belongsTo: [0, 1], imageUrl: 'http://via.placeholder.com/80x80', }, { id: 1, title: 'Graph Databases', description: 'Learn How to work with Graph Databases Online', price: 9.99, belongsTo: [0, 3], imageUrl: 'http://via.placeholder.com/80x80', }, { id: 2, title: 'Full Stack Development', description: "The in's-and-out's of full stack development", price: 15.99, belongsTo: [0, 4, 1], imageUrl: 'http://via.placeholder.com/80x80', }, { id: 3, title: 'Data Structures Course', description: 'What you need to know about data-structures', price: 20.0, belongsTo: [0, 3], imageUrl: 'http://via.placeholder.com/80x80', }, { id: 4, title: 'Job preperation pointers', description: "In a highly competetive market, these are tips youl'll be glad you had", price: 5.0, belongsTo: [0, 4], imageUrl: 'http://via.placeholder.com/80x80', }, { id: 5, title: 'Adavanced OOP Course', description: 'High-Level break down of OOP', price: 18.99, belongsTo: [0, 1], imageUrl: 'http://via.placeholder.com/80x80', }, { id: 6, title: 'User Experience Design', description: 'UX 101', price: 18.99, belongsTo: [0, 2], imageUrl: 'http://via.placeholder.com/80x80', }, { id: 7, title: 'User interface design', description: 'How to create a dynamic user interface', price: 14.99, belongsTo: [0, 2], imageUrl: 'http://via.placeholder.com/80x80', }, { id: 8, title: 'Uniform Modeling Language', description: 'An in depth look at how to structure your application', price: 6.99, belongsTo: [0, 4], imageUrl: 'http://via.placeholder.com/80x80', }, ], } }
/* * The reducer takes care of state changes in our app through actions */ import { FETCH_HARDCODE_SECRET, FETCH_HARDCODE_SECRET_FULFILLED, CREATE_HARDCODE_SECRET, CREATE_HARDCODE_SECRET_FULFILLED, UPDATE_HARDCODE_SECRET, UPDATE_HARDCODE_SECRET_FULFILLED, HARDCODE_SECRET_OPERATION_REJECTED } from '../Actions/ActionTypes' // The initial hardcode secret state let initialState = { hardcodeSecrets: null, createResponse: false, updateResponse: false, fetching: false, fetched: false, error: null } // Takes care of changing the hardcode secret state function reducer(state = initialState, action) { switch (action.type) { case FETCH_HARDCODE_SECRET: return { ...state, fetching: true, createResponse: false, updateResponse: false, } case FETCH_HARDCODE_SECRET_FULFILLED: return { ...state, fetched: true, hardcodeSecrets: action.payload } case CREATE_HARDCODE_SECRET: return { ...state, fetching: true, createResponse: false, } case CREATE_HARDCODE_SECRET_FULFILLED: return { ...state, fetched: true, createResponse: true, } case UPDATE_HARDCODE_SECRET: return { ...state, fetching: true, updateResponse: false, } case UPDATE_HARDCODE_SECRET_FULFILLED: return { ...state, fetched: true, updateResponse: true, } case HARDCODE_SECRET_OPERATION_REJECTED: return { ...state, fetched: false, error: action.payload, } default: return state } } export default reducer;
import GroupDelete from "./GroupDelete"; export {GroupDelete} export default GroupDelete
export default { name: 'featureModule', title: 'Feature Module', type: 'document', fields: [ { title: 'Title', name: 'title', type: 'string' }, { title: 'Features', name: 'features', type: 'array', of: [{ type: 'features' }] } ] };
const express = require('express'); const bodyParser = require('body-parser') const path = require('path'); const app = express(); const MongoClient = require('mongodb').MongoClient; const assert = require('assert'); const router = express.Router() app.use(bodyParser.urlencoded({extended:true})) app.use(bodyParser.json()) // Connection URL const url = 'mongodb://localhost:27017/'; // Database Name const dbName = 'AnimeTracker'; // Use connect method to connect to the server MongoClient.connect(url, function(err, client) { assert.equal(null, err); console.log("Connected successfully to server"); const db = client.db(dbName); client.close(); }); app.post('/quotes', (req, res) => { MongoClient.connect(url, function(err, db) { var db = db.db(dbName); assert.equal(null, err); db.collection('quotes').insertOne(req.body, (err, result) => { if (err) return console.log(err) console.log('saved to database') res.redirect('/') }) }); }) app.use(express.static(path.join(__dirname, 'build'))); app.get('/ping', function (req, res) { return res.send('pong'); }); app.get('/', function (req, res) { res.sendFile(path.join(__dirname, 'build', 'index.html')); }); app.listen(process.env.PORT || 8080);
/** * Arquivo: server.js * Descrição: servidor node.js * Author: Leandro Mello * Data: 11/03/2019 */ const express = require('express'); const app = express(); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const perfilUsuario = require('./app/models/perfilUsuario'); // URI: MongoDB - conexão do mongoose: mongoose.connect('mongodb://localhost:27017/jobMatch', { useNewUrlParser: true }) // configuração da variavel app, atraves do 'bodyParser' e retornando dados no formato 'JSON': app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // configurando a porta, onde será executada nossa api: const port = process.env.port || 9000; // rotas da nossa API: //============================================================================================= // configurando as rotas com a criação de uma instância via express: const router = express.Router(); router.use(function(req, res, next) { console.log('Iniciando fluxo JobMatch'); next(); }); // rota de exemplo: router.get('/', function(req, res) { res.json({ message: 'Cadastrando um novo perfil de usuario'}) }); // API´s //============================================================================================ // rotas que terminarem com '/perfilUsuarios' (servir: GET ALL & POST) router.route('/perfilUsuario') /* 1° Método: Criar Perfil Usuario (acessar em: POST http://localhost:9000/api/perfilUsuario)*/ .post(function(req, res) { var PerfilUsuario = new perfilUsuario(); // aqui vamos setar os campos do produto (via request): PerfilUsuario.nome = req.body.nome; PerfilUsuario.cargoAtual = req.body.cargoAtual; PerfilUsuario.areaAtual = req.body.areaAtual; PerfilUsuario.userId = req.body.userId; PerfilUsuario.dataNascimeto = req.body.dataNascimeto; PerfilUsuario.save(function(error) { if(error) { res.send('Erro ao tentar salvar o Perfil do usuario' + error); } else { res.json({ message: 'Perfil Usuario cadastrado com sucesso'}); }; }); }); // definindo um padrão das rotas prefixadas: '/api': app.use('/api', router); // iniciando a Aplicação (servidor): app.listen(port); console.log('Servidor rodando na porta:', port);
/** * Created by Jack Kettle on 29/10/2014. */ module.exports = function (grunt) { grunt.initConfig({ // Compile specified less files less: { compile: { options: { // These paths are searched for @imports paths: ["less/"] }, files: { "src/css/main.css": "src/less/style.less" } } }, // concat all js files concat: { js: { src: ['src/js/dev/main.js', 'src/js/dev/**/*.js'], dest: 'src/js/dest/concat.js' } }, // minifyjs uglify: { options: { compress: false, mangle: false, beautify: true }, js: { files: { 'src/js/dest/main.min.js': ['src/js/dest/concat.js'] } } }, karma: { unit: { options: { frameworks: ['jasmine'], singleRun: true, browsers: ['PhantomJS'], files: [ 'src/vendor/js/jquery-1.10.2.min.js', 'src/bower_components/angular/angular.min.js', 'src/bower_components/angular-ui-router/release/angular-ui-router.min.js', 'src/bower_components/angular-cookies/angular-cookies.min.js', 'src/bower_components/angular-mocks/angular-mocks.js', 'src/bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js', 'src/bower_components/ng-table/dist/ng-table.min.js', 'src/bower_components/file-saver/FileSaver.min.js', 'src/js/dest/main.min.js', 'https://apis.google.com/js/client.js', 'src/js/test/**/*.js' ] } } }, ftpush: { build: { auth: { host: 'ftp1.reg365.net', "username": "isto.ie", "password": "" }, simple: true, src: 'src/', dest: 'web/' } }, watch: { styles: { files: ["**/*.less"], tasks: "less", options: { livereload: true } }, scripts: { files: ["src/js/dev/**"], tasks: ['concat', 'uglify'] } } }); // Load tasks so we can use them grunt.loadNpmTasks("grunt-contrib-watch"); grunt.loadNpmTasks("grunt-contrib-less"); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-ftpush'); // The dev task will be used during development grunt.registerTask("default", ["watch"]); };
import React from 'react'; import './App.scss'; import Navbar from "./components/Navbar/Navbar"; import TourList from './components/TourList'; import About from './components/About/About'; import Home from './components/Home/Home'; import { Route, BrowserRouter, Switch } from 'react-router-dom'; function App() { return ( <React.Fragment> <BrowserRouter> <Navbar /> <Switch> <Route exact path="/home" component={Home} /> <Route exact path="/about" component={About} /> <Route exact path="/tour-list" component={TourList} /> </Switch> </BrowserRouter> </React.Fragment> ) } export default App;
const Word = { template: ` <div class="word"> <div>{{ word.english }}</div> <div>{{ word.japanese }}</div> </div> `, props: ['word'] }; const AddWordForm = { template: ` <div class="addWordForm"> <form @submit.prevent="addNewWord" class="addWordForm"> <input v-model="english" ref="englishInput" placeholder="English"> <input v-model="japanese" placeholder="日本語"> <button type="submit">追加</button> </form> </div> `, data() { return { english: '', japanese: '', } }, methods: { addNewWord() { const { english, japanese } = this; if (english !== '' && japanese !== '') { this.$root.words.push({ english, japanese, done: false, cleared: false }); this.clearForm(); } }, clearForm() { this.english = ''; this.japanese = ''; this.$refs.englishInput.focus(); } } }; const List = { template: ` <div :class="'list ' + className"> <div class="listLabel"> {{ label }} </div> <div class="wordContainer"> <word v-for="word in words" :word="word"></word> <add-word-form v-if="addable"></add-word-form> </div> </div> `, components: { Word, AddWordForm }, props: ['words', 'className', 'label', 'addable'] }; module.exports = { template: ` <div> <div class="testStartButton"> <button @click="startTest">テストスタート</button> </div> <div class="mainContainer"> <list :words="normalWords" className="normal" label="Cards" :addable="true"></list> <list :words="clearedWords" className="cleared" label="Cleared"></list> <list :words="notClearedWords" className="notCleared" label="Not Cleared"></list> </div> </div> `, components: { List }, props: ['words'], computed: { normalWords() { return this.words.filter((word) => !word.done); }, clearedWords() { return this.words.filter((word) => (word.done && word.cleared)); }, notClearedWords() { return this.words.filter((word) => (word.done && !word.cleared)); }, testWords() { return this.words.filter((word) => (!word.cleared)); } }, methods: { startTest() { this.$root.startTest(this.testWords); } } };
'use strict'; /** * @ngdoc function * @name dssiFrontApp.controller:ChecklistAdminCtrl * @description * # ChecklistAdminCtrl * Controller of the dssiFrontApp */ angular.module('dssiFrontApp') .controller('ChecklistAdminCtrl', function ($scope, ChecklistItemGroup, Checklist, ChecklistItem, $localStorage, $uibModal, notificationService, $log) { var vm = this; vm.checklistItemCreate = checklistItemCreate; vm.checklistItemGroupCreate = checklistItemGroupCreate; vm.updateChecklistItem = updateChecklistItem; vm.checklistItemGroups = [] loadChecklistItemGroups(); vm.checklist = {}; loadChecklist(); $scope.loadChecklist = vm.loadChecklist; $scope.loadChecklistItems = loadChecklistItems; //////////// function loadChecklist(){ vm.checklist = Checklist.get({ property_id: $localStorage.property_id }); $scope.checklist = vm.checklist; vm.checklist.$promise.then(function(){ vm.checklistItems = vm.checklist.checklist_items; }); } function loadChecklistItems(){ if(vm.checklist.id){ vm.checklistItems = ChecklistItem.query({ checklist_id: vm.checklist.id }); vm.checklistItems.$promise.then(function(){ vm.checklist.checklist_items = vm.checklistItems; }); } } function loadChecklistItemGroups(){ vm.checklistItemGroups = ChecklistItemGroup.query({ property_id: $localStorage.property_id }); $scope.checklistItemGroups = vm.checklistItemGroups; } function updateChecklistItem(checklistItem){ if(checklistItem.checklist_item_group_id){ delete checklistItem.checklist_item_group; ChecklistItem.update({id: checklistItem.id}, { checklist_item_group_id: checklistItem.checklist_item_group_id, status: checklistItem.status }).$promise.then(function(){ notificationService.success('¡Actualizado!'); }, function(){ notificationService.error('No ha sido posible atender la solicitud.'); }); } } function checklistItemCreate(){ $uibModal.open({ animation: true, templateUrl: 'views/modal-bind-compile.html', size: 'md', controller: 'ModalDefaultCtrl', controllerAs: 'modal', scope: $scope,// This $scope as parent of child element resolve: { options: { title: 'Crear Item para Checklist', content: '<div ng-controller="ChecklistItemCreateCtrl as checklistItemCreate" ng-include="\'views/access-control/checklist-items/create.html\'"></div>', //ok_text: 'Guardar', without_footer: true } } }).result.finally(function() { loadChecklistItems(); }); } function checklistItemGroupCreate(){ $uibModal.open({ animation: true, templateUrl: 'views/modal-bind-compile.html', size: 'md', controller: 'ModalDefaultCtrl', controllerAs: 'modal', scope: $scope,// This $scope as parent of child element resolve: { options: { title: 'Crear Grupo para Item de Checklist', content: '<div ng-controller="ChecklistItemGroupCreateCtrl as checklistItemGroupCreate" ng-include="\'views/access-control/checklist-item-groups/create.html\'"></div>', without_footer: true } } }).result.finally(function() { loadChecklistItemGroups(); loadChecklistItems(); }); } });
//mouseover// const busImage = document.querySelector('.intro > img'); busImage.addEventListener("mouseenter", () => { busImage.style.transform = "scale(1.8)"; busImage.style.transition = 'all 0.3s' console.log('bus image enlarged under mouse') }); busImage.addEventListener('mouseleave', () => { busImage.style.transform = 'scale(1)' console.log('bus image shrunk away from mouse') }); const mapImage = document.querySelector('.img-content > img'); mapImage.addEventListener("mouseenter", () => { mapImage.style.transform = "scale(1.3)"; mapImage.style.transition = 'all 0.3s' console.log('map image enlarged under mouse') }); mapImage.addEventListener('mouseleave', () => { mapImage.style.transform = 'scale(1)' console.log('map image shrunk away from mouse') }); //keydown// let keyDown = document.addEventListener('keydown', () => { document.body.style.backgroundColor='black'; console.log('background goes black on key press') }); //wheel// let flasher = true; const wheel = document.addEventListener('wheel', () => { if (flasher === true) { document.body.style.backgroundColor='yellow'; flasher = false; } else { document.body.style.backgroundColor='blue'; flasher = true; } console.log('background changed color on scroll') }); //drag and drop// //const boatImg = document.querySelector('.content-destination > img'); document.addEventListener('drag', (event) => { console.log(`dragged item, ${event.x}, ${event.y}`); // boatImg.style.width = (event.x) + 'px' }); const footerBar = document.querySelector(".footer"); footerBar.addEventListener('dragover', (event) => { event.preventDefault() }) footerBar.addEventListener('drop', () => { console.log('dropped image') }) //load// const loaded = window.addEventListener('load', () => { console.log('this page has loaded') }); //blur//// const riverImg = document.querySelector('.img-fluid'); riverImg.addEventListener('click', (event) => { event.target.style.filter = 'blur(10px)'; console.log('image blurred') }); //resize// //const mainNav = document.querySelector('.container > .nav-container') window.addEventListener('resize', () => { console.log('window resized'); }); //double-click// const changeImg = document.querySelector('.intro > img'); changeImg.addEventListener('dblclick', () => { changeImg.src='https://s3-us-west-2.amazonaws.com/s.cdpn.io/780593/cat-lambda.png' console.log('changed image with double click') }) //stop propagation// const btnCard = document.querySelector('.destination'); btnCard.addEventListener('click', () => { btnCard.style.backgroundColor='orange'; console.log('change card color'); }) const btn = document.querySelector('.btn'); btn.addEventListener('click', (event) => { btn.style.backgroundColor='olive'; event.stopPropagation(); console.log('change btn color only'); }) //prevent links from loading// const nav = document.querySelector('nav') nav.addEventListener('click', (event) => { event.preventDefault(); console.log('clicked a link prevented'); })
define(['SocialNetView', 'models/Generic','models/GenericCollection', 'views/profession/listprofession','text!templates/profession/listprofessions.html', 'views/profession/searching'], function(SocialNetView, Model, Collection, ProfessionView,professionTemplate, SearchingView) { var professionsView = SocialNetView.extend({ myTarget:'', isDraggable:false, events:{ 'keyup input[id=searching]':'searching' }, initialize: function(options) { this.options= options; options.socketEvents.bind('addProffession:me',this.onSocketAdded,this); this.collection.on('reset', this.renderCollectionReset, this); }, onSocketAdded: function(data){ var newData=data.data; this.collection.add(new Model(newData)); }, renderCollectionReset: function(collection) { var that= this; collection.each(function(model){ that.onAdded(model,that.options.myTarget); }); }, onAdded: function(profession,myTarget){ var html = (new ProfessionView({model:profession,myTarget:myTarget,isDraggable:this.options.isDraggable})).render().el; }, searching: function(e){ var view= this; $('#list-profession').empty(); if($('#searching').val().length>0){ var professionsColec = new Collection(); professionsColec.url = '/professions/me/NaN/'+$('#searching').val()+'/findprofession'; var htmlS = (new SearchingView({collection:professionsColec})).render().el; $(htmlS).appendTo('#list-profession'); professionsColec.fetch(); //this.renderCollectionReset(professionsColec); }else{ var fields='NaN'; var table='NaN'; var w = 'NaN'; var listCollection = new Collection(); listCollection.url = '/professions/me/'+w+'/'+fields+'/'+table+'/resultarray'; this.renderCollectionReset(listCollection); //var listHtml = (new SearchingView({collection:listCollection})).render().el; //$(listHtml).appendTo("#show-list-professions"); listCollection.fetch(); } }, render: function(resultList) { //this.$el.html(_.template(professionTemplate)); return this; } }); return professionsView; });
const express = require('express') global.router = express.Router() global.verify = require('../middleware/auth') global.fileComponent = require('./components/file') global.blogComponent = require('./components/blog') global.errorComponent = require('./components/error') global.messageComponent= require('./components/message') global.userComponent=require('./components/user/index')
import React from "react"; import { Actions, ActionsLabel, ActionsGroup, ActionsButton, Link, Button} from 'framework7-react'; import { dict} from '../../Dict'; const ReportMenu = (props) => { if (props.report){ return( <React.Fragment> <Actions id={"actions-two-groups-"+props.report.id}> <ActionsGroup> <ActionsLabel>{dict.social_acts}</ActionsLabel> <ActionsButton onClick={props.report.bookmarked ? '': () => props.interaction('Bookmark', props.report.id, 'Report')}><i class="va ml-5 fas fa-bookmark"></i>{dict.bookmark} ({props.report.bookmarks})</ActionsButton> <ActionsButton onClick={props.report.liked ? '':() => props.interaction('Like', props.report.id, 'Report')}><i class="va ml-5 fas fa-heart"></i>{dict.like} ({props.report.likes})</ActionsButton> <ActionsButton ><i class="va ml-5 fas fa-retweet"></i>{dict.share}</ActionsButton> <ActionsButton onClick={props.report.followed ? '':() => props.interaction('Follow', props.report.id, 'Report')}><i class="va ml-5 fas fa-link"></i>{dict.follow} ({props.report.follows})</ActionsButton> </ActionsGroup> <ActionsGroup> <ActionsButton color="red">{dict.cancel}</ActionsButton> </ActionsGroup> </Actions> <Link className="btn-notice"></Link> <Button className="col btn" fill href={false} actionsOpen={"#actions-two-groups-"+props.report.id}><i class="va fas fa-users"></i></Button> </React.Fragment> ) } else { return(null) } } export default ReportMenu;
define([ 'common/views/visualisations/availability/uptime-number', 'common/collections/availability', 'extensions/models/model' ], function (UptimeNumber, AvailabilityCollection) { describe('UptimeNumber', function () { var options = { checkName: 'anything', dataSource: { 'data-group': 'anything', 'data-type': 'monitoring', 'query-params': { period: 'day' } }, parse: true }; it('should display (no data) rather than NaN when response is null', function () { var availabilityData = { 'data': [ { 'uptime:sum': null, 'downtime:sum': null, 'unmonitored:sum': null, 'avgresponse:mean': null } ]}; var collection = new AvailabilityCollection(availabilityData, options); var view = new UptimeNumber({ collection: collection }); expect(view.getValue()).toEqual('<span class="no-data">(no data)</span>'); }); it('should display (no data) when hovering over data that doesn\'t exist', function () { var availabilityData = { 'data': [ { 'uptime:sum': 13, 'downtime:sum': 15, 'unmonitored:sum': 17, 'avgresponse:mean': 29, '_start_at': '2013-05-17T00:00:00+00:00' }, { 'uptime:sum': null, 'downtime:sum': null, 'unmonitored:sum': null, 'avgresponse:mean': null, '_start_at': '2013-05-18T00:00:00+00:00' } ]}; var collection = new AvailabilityCollection(availabilityData, options); var view = new UptimeNumber({ collection: collection }); collection.selectItem(1); var selection = collection.getCurrentSelection(); expect(view.getValueSelected(selection)).toEqual('<span class="no-data">(no data)</span>'); }); }); });
var app = getApp(); Page({ data: { searchKey:"", recList:[ ] }, //获取input文本 getSearchKey: function (e) { this.setData({ searchKey: e.detail.value, //app.globalData.input = this.data.searchKey, }) //console.log(app.input) }, btnClick: function (event) { var that = this; wx.request({ // url: 'http://129.211.44.111:10000/paper?number_begin=0&number_end=20&userID=' + app.globalData.openid, //接口名称 url: 'https://www.zhouwk.club:10000/findPaperByKeywords', header: { 'content-type': 'application/json' // 默认值(固定,我开发过程中还没有遇到需要修改header的) }, data: { userID: app.globalData.openid,//我的ID keyword: this.data.searchKey }, success(res) { console.log('setData') that.setData({ recList: res.data.paper, // whichfirst: that.data.whichfirst + 1, // whichlast: that.data.whichlast + 1 }) } }) }, goContentDetail(e) { wx.navigateTo({ url: '../../pages/contentDetail/contentDetail?paperID=' + e.target.dataset.agree1 + '&title=' + e.target.dataset.title + '&content=' + e.target.dataset.content + '&agree=' + e.target.dataset.agree + '&haha=' + e.target.dataset.haha + '&dates=' + e.target.dataset.dates + '&name=' + e.target.dataset.name + '&image=' + e.target.dataset.image, }), console.log(e.target.dataset.haha) }, //每次显示钩子函数都去读一次本地storage onShow: function () { } })
var express = require('express'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); var pg = require ('pg'); var con_string = 'tcp://Dell-pc:rainbow@localhost/chatdb'; var pg_client = new pg.Client(con_string); pg_client.connect(); app.use(express.static(__dirname + '/public')); app.get('/', function(req, res){ res.sendFile(__dirname + '/about.html'); }); app.get('/try_it', function(req, res) { res.sendFile(__dirname + '/index.html'); // res.render('about', { }); }); var user=0; io.on('connection', function(socket){ console.log("user :"+ ++user); socket.on('connected',function(data){ socket.emit("connected",{username:data.username, gender:data.gender}); }); socket.on('notifyUser', function(user){ io.emit('notifyUser', user); }); /*socket.on('chat message', function(data){ console.log(data.msg1 + " encrypted to " + data.msg2); io.emit('chat message', {msg1:data.msg1}); });*/ socket.on('chat message', function(data){ console.log(data.msg1 + " encrypted to " + data.msg2 + ", gender = "+data.gender); // pg.connect(pg_client, function(err, client) { // if (err) return console.log(err); // else pg_client.query("INSERT INTO chat values($1,$2,$3,$4)",[data.user,data.gender,data.msg1,data.msg2] ,function(err,results){ console.log(results); // }); }); io.emit('chat message', {user:data.user,gender:data.gender,msg1:data.msg1}); }); socket.on('disconnect', function(){ console.log("users now :"+ --user); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); });
import React from 'react' import Sun from './Sun'; import Earth from './Earth'; import Car from './Car'; import Mars from './Mars'; import Timer from './Timer'; const Space = props => { const divStyle = { marginTop: "70px" } return ( <div style={divStyle} className="row"> <Sun /> <Earth /> <Car percentComplete={props.percentComplete} /> <Mars /> </div> ) } export default Space
import { assert } from '@ember/debug'; const attributes = [ 'src', 'alt', 'href', 'target' ]; const createDocument = () => { if(typeof document === 'undefined') { // eslint-disable-next-line no-undef let { Document } = FastBoot.require('simple-dom'); return new Document(); } return document; } export const toDOM = tree => { let document = createDocument(); let components = []; const toElements = (parent, nodes=[]) => { nodes?.forEach(node => { let el = toElement(node); if(el) { parent.appendChild(el); } }); return parent; }; const createElement = (name, node, className) => { let element = document.createElement(name); let properties = node.properties; let classNames = []; if(properties) { if(properties.className) { classNames.push(...properties.className); } for(let key in properties) { if(attributes.includes(key)) { let value = properties[key]; element.setAttribute(key, value); } else { // temporary if(key !== 'className') { console.warn('Unmapped node property', key); } } } } if(className) { classNames.push(className); } if(classNames.length) { element.setAttribute('class', classNames.join(' ')); } return element; } const toElement = node => { if(node) { let { type } = node; if(type === 'root') { let element = createElement('div', node, 'root'); return toElements(element, node.children); } else if(type === 'element') { let element = createElement(node.tagName, node); return toElements(element, node.children); } else if(type === 'text') { return document.createTextNode(node.value); } else if(type === 'component') { let element = createElement(node.inline ? 'span' : 'div', node, 'component'); let { name, model } = node; let content = toElements(document.createElement('span'), node.children); components.push({ element, name, model, content }); return element; } assert(`Unsupported node '${type}'`, false); } } let element = toElement(tree); return { element, components }; }
/* eslint-disable no-underscore-dangle */ import EventEmitter from '../events.js'; import { colorscales, sizeOfCircle } from '../tools/helpers.js'; /** * The Class represents the projection. * It contains three main parts. * @extends EventEmitter */ class UMAPprojection extends EventEmitter { /** * * @param {String} root - the name of the view. The name is prependend to every HTML-elemnts id. */ constructor(root) { super(); // call the constructor of the EventEmitter class. this._prefix = root; // 'umap' this._viewDivId = `${root}-view`; // points to the encapsulating div // this._menuDivId = `${root}-menu`; this._startTime = 0; // needed for time measurement. this._stopTime = 0; this._currentColorScale = colorscales.cve; this.MARGINS = { top: 20, right: 20, bottom: 20, left: 20, }; /* contains the current status of the control. * the keys of the object reflects the HTML-elements id. */ this._controlStatus = { showIntersection: false }; this._width = -1; this._height = -1; this._rootSvg = -1; this._legendSvg = -1; this._edgeLen = -1; this._dataSet = []; this._filteredElems = []; this._dataClusterVendor = []; this._dataCluster = []; this._currentlyClickedElemsId = []; this._zoom = ''; this._colorScale = ''; this._xScale = ''; this._yScale = ''; this._gDot = ''; this._zoomed = ''; this._clickSelection = []; this._circleScale = ''; this._scalingFaktor = 3; this.sigletonMove = true; this.initView(); } /** * retrievs and stores the width and height. * creates the artifact-views svg element which contains each artifact. */ initView() { // All elements created by the view are children of the viewDiv. const viewDiv = d3.select(`#${this._viewDivId}`); const offset = 50; this._width = viewDiv.node().offsetWidth - offset; this._widthRightMenu = viewDiv.node().offsetWidth - this._width - 5; // padding /* * when creating the first view, $('.view-menu').outerHeight(true) is 0. * therfore we use the constant 70 which is approx. 2* the height of a bootstrap dropdown menu */ this._height = window.innerHeight - $('#nav-bar').outerHeight(true) - 70 - this.MARGINS.bottom - 40; this._rootSvg = viewDiv .append('svg') .attr('id', () => `${this._viewDivId}-svg`) // svg that contains all g-Artifacts .attr('width', this._width) .attr('height', this._heigt) .attr('style', 'background-color: #6c757d;') .attr('viewBox', `0,0 ${this._width} ${this._height}`); // viewBox for zooming and panning // this.initViewControlls(); this._rightMenuSvg = viewDiv .append('svg') .attr('id', () => `${this._viewDivId}-rightMenu-svg`) // svg that contains all g-Artifacts .attr('width', this._widthRightMenu) .attr('height', this._height); // .attr('viewBox', `0,0 ${this._width} ${this._height}`); // viewBox for zooming and panning // this.initViewControlls(); // Box on the bottom of the vis. // this._legendSvg = viewDiv // .append('svg') // .attr('id', () => `${this._viewDivId}-legend-svg`) // svg that contains all g-Artifacts // .attr('style', 'overflow: scroll;') // .attr('width', this._width + offset) // .attr('height', 70 + 40); // this._colorScale = d3.scaleOrdinal() // .domain(this._dataSet.map((d) => d.cluster)) // .range(d3.schemeTableau10); // const gGrid = this._rootSvg.append('g'); this._xScale = d3.scaleLinear() .domain([0, 1]) .range([60, this._width - 60]); this._yScale = d3.scaleLinear() .domain([0, 1]) .range([60, this._height - 60]); this._gDot = this._rootSvg.append('g') .attr('fill', 'none') .attr('stroke-linecap', 'round'); this._circleScale = d3.scaleSqrt() .domain([1, 739]) .range([sizeOfCircle, sizeOfCircle]); const zoomScale = ''; const zoomTranslate = ''; // const xScale = d3.scaleLinear().domain([0, this._width]).range([0, this._width]); // const yScale = d3.scaleLinear().domain([0, this._height]).range([0, this._height]); const zoomTransform = ''; this._zoomed = ({ transform }) => { // zoomTransform = transform; // zTransform = d3.zoomTransform // console.log(`zoomTraslate: ${transform.transform} :: zoomScale: ${zoomScaleEr}`); this._zoom.transform = d3.zoomTransform(d3.select('#umap-view-svg').select('g').node()); // const x_scale = d3.scale.linear().domain([0, this._width]).range([0, this._width]); // const y_scale = d3.scale.linear().domain([0, chartHeight]).range([0, chartHeight]); // brushExtend = [[], []]; this._gDot.attr('transform', transform).attr('stroke-width', 5 / transform.k); // gx.call(xAxis, zx); // gy.call(yAxis, zy); // console.log(zy); // gGrid.call(grid, zx, zy); }; this._zoom = d3.zoom() .scaleExtent([0.5, 2.5]) // .x(xScale()) // .y(yScale()) .on('zoom', this._zoomed); this._brush = d3.brush() // Add the brush feature using the d3.brush function // initialise the brush area .extent([[0, 0], [this._width, this._height]]) .on('start brush end', (event) => { const extent = event.selection; if (extent !== [] && extent !== null) { const transform = d3.zoomTransform(this._rootSvg.select('circle').node()); // first node in the projection // extent[0] = [transform.x + extent[0][0], transform.y + extent[0][1]]; // extent[1] = [transform.x + extent[1][0], transform.y + extent[1][1]]; const eachSelectedELemsData = this._rootSvg .selectAll('circle') .filter(function x() { const currentCircle = d3.select(this); // console.log(c); const cxy = [currentCircle.attr('cx'), currentCircle.attr('cy')]; /// /transform.apply( const isCircleSelected = extent[0][0] <= cxy[0] && extent[1][0] >= cxy[0]// X coord && extent[0][1] <= cxy[1] && extent[1][1] >= cxy[1]; // And Y coordinate return isCircleSelected; }) .filter(function x() { const elemclass = d3.select(this).attr('class'); if (elemclass !== 'filtered') { return true; } return false; }) .data(); const brushedElemsIds = []; eachSelectedELemsData.forEach((selElem) => { if (event.type === 'end') { console.log(selElem.cve); d3.select(`#${selElem.cve}`) .attr('stroke', (d) => colorscales.cluster(selElem.cluster)) .attr('stroke-width', 1) .attr('stroke-opacity', 1) .attr('style', 'black'); } brushedElemsIds.push(selElem.cve); if (event.type === 'start' || event.type === 'brush') { d3.select(`#${selElem.cve}`) .transition(d3.easeQuadIn(250)) .attr('r', 3 * sizeOfCircle * this._scalingFaktor) .transition(d3.easeQuadIn(100)) .attr('r', colorscales.circleScale(selElem.numb_affected_apps)); } }); console.log(brushedElemsIds); d3.select('#umap-view-svg') .selectAll('circle') .filter((d) => brushedElemsIds.indexOf(d.cve) === -1) .attr('stroke-width', 0) .attr('style', (d) => `fill:${colorscales.cluster(d.cluster)}`); if (event.type === 'end' && brushedElemsIds) { this.emit('clickedVulnerability', brushedElemsIds); } } }); } /** * The render function renders the data on the screen. * @param {String} scaleSelection - name of a scale. * @param {Number} tansitionTime - time in ms a transition takes place. */ render(scaleSelection = '', tansitionTime = 2500) { if (scaleSelection !== '') { // if we passed a new color-scale name. this._currentColorScale = colorscales[scaleSelection]; } console.log('projection.js render()'); const keys = []; this._dataCluster.forEach((c) => { keys.push([c.cluster, c.cluster_main_words]); }); const size = 10; d3.select('#filters').append('div').attr('class', 'row myClusters') .append('p') .attr('class', 'rangeSlider label') .text('Top 5 words for each cluster. click to hide selected cluster.'); this._rightMenuSvg = d3.select('.myClusters').append('svg'); this._rightMenuSvg .append('g') .attr('id', 'cluster-group') .selectAll('dots') .data(keys) .enter() .append('g') .attr('class', (d) => `cluster_${d[0]} c`) .append('rect') .attr('x', 5) .attr('y', (d, i) => 10 + i * (size + 5)) // 100 is where the first dot appears. 25 is the distance between dots .attr('width', 10) .attr('height', 10) .style('fill', (d) => colorscales.cluster(d[0])) .attr('class', 'clusterSelected'); // do not remove! this._rightMenuSvg .insert('g', 'g') .append('rect') .attr('x', 0) .attr('y', 0) // 100 is where the first dot appears. 25 is the distance between dots .attr('width', this._width) .attr('height', 140) .style('fill', '#6c757d'); this._rightMenuSvg .selectAll('g .c') .append('text') .raise() .attr('class', 'cluster-label') .attr('x', 5 + 10) .attr('y', (d, i) => 10 + i * (size + 5) + (size / 2)) // 100 is where the first dot appears. 25 is the distance between dots .style('fill', (d) => colorscales.cluster(d[0])) .text((d) => d[1]) // .attr('textLength', 100) .attr('text-anchor', 'left') .style('dominant-baseline', 'middle'); this._rightMenuSvg .selectAll('g .c') .on('click', (event) => { const clusterId = d3.select(event.currentTarget).attr('class').split('_')[1]; // int between -1 and n d3.select(event.currentTarget) .select('rect') .classed('clusterSelected', !d3.select(event.currentTarget).select('rect').classed('clusterSelected')); d3.select(event.currentTarget) .classed('filtered', !d3.select(event.currentTarget).classed('filtered')); const test = []; keys.forEach((k) => { const classLabel = `cluster_${k[0]}`; const currenClassValue = d3.select('#filters').select(`.${classLabel}`) .select('rect') .attr('class'); if (currenClassValue !== '') { // value of rect test.push(k[0]); } }); d3.select('#filters') .selectAll('g') .attr('style', 'opacity:1;'); d3.selectAll('g.filtered') .attr('style', 'opacity:0.20;'); // console.log(test); // d3.selectAll('circle') // .filter((d) => d.cluster === Number(clusterId)) // .style('fill', 'blue'); console.log(test); this.emit('clusterSelectionChanged', test); }); const dimOfClusterSelectionMenu = document.getElementById('cluster-group').getBBox(); const template = document.getElementById('toolSelectionTemp').innerHTML; const rangFilterDivRow = d3.select('#filters') .append('div') // place different ns in svg. .attr('class', 'row') .attr('width', '100%') .attr('height', '30%') .attr('x', 5) .attr('y', dimOfClusterSelectionMenu.height + 30); // 10px offset rangFilterDivRow .html(template); const simulation = d3.forceSimulation(this._dataSet) .force('force_x', d3.forceX((d) => this._xScale(d.x_projection))) .force('force_y', d3.forceY((d) => this._yScale(d.y_projection))) .force('collide', d3.forceCollide((d) => this._circleScale(d.numb_affected_apps))); // Run the simulation for 100 steps for (let i = 0; i < 100; i += 1) { simulation.tick(); } simulation.stop(); console.log(this._dataSet); this.renderProjection(this._dataSet, true); d3.select('#toogleToolSelection') .on('click', (event) => { const selectedTool = event.target.id; if (selectedTool) { if (selectedTool === 'brush') { // const extent = this._rootSvg.select('umap-view-svg') // . console.log(selectedTool); this._zoom.on('zoom', null); // this._brush.on('click', this._brush); d3.select('#umap-view-svg').insert('g', 'g') .attr('class', 'mybrush') .call(this._brush); } else if (selectedTool === 'zoom') { this._rootSvg.selectAll('.mybrush').remove(); // this._rootSvg.selectAll('.overlay').remove(); this._zoom.on('zoom', this._zoomed); // this._brush.on('click', null); } } }); const gx = this._rootSvg.append('g'); const gy = this._rootSvg.append('g'); // this._rootSvg.call(this._brush); this._rootSvg.call(this._zoom).call(this._zoom.transform, d3.zoomIdentity); // d3.select('#umap-view').call(this._brush); // d3.selectAll('circle') // .filter((d) => this._filteredElems.indexOf(d.cve) > -1) // .style('fill', 'red'); this.addRangeSlider(); // this._rootSvg.call(zoom).call(zoom.transform, d3.zoomIdentity); // function zoomed({ transform }) { // const zx = transform.rescaleX(x).interpolate(d3.interpolateRound); // const zy = transform.rescaleY(y).interpolate(d3.interpolateRound); // gDot.attr('transform', transform).attr('stroke-width', 5 / transform.k); // gx.call(xAxis, zx); // gy.call(yAxis, zy); // gGrid.call(grid, zx, zy); // } // this._rootSvg // .selectAll('g') // // key function - return a unique id. Each array elem stays joined to the same DOM elem. // .data(this._dataSet, (d) => d.id) // .join( // (enter) => { // const gs = enter // .append('g') // .attr('class', `${this._viewDivId}-g`); // each artifact has its own group. // gs // .append('rect') // .attr('class', 'default') // .attr('rx', '3px') // .attr('width', artifactDimWidth) // .attr('height', artifactDimHeight) // .attr('stroke', (d) => this._currentColorScale(d.color)) // .attr('stroke-opacity', 0.7) // .attr('style', (d) => `fill:${this._currentColorScale(d.color)}`) // .attr('fill-opacity', 0.35); // /* // * A <g> element has two working modes. // * 1. element is clicked for less then 500ms. (normal) // * 2. elmeent is clicked and the key is hold for more than 500ms. // */ // gs // .on('mousedown', () => { // this._startTime = performance.now(); // }) // .on('mouseup', (clickedElem, attachedData) => { // this._stopTime = performance.now(); // const timeElapsed = this._stopTime - this._startTime; // in ms // if (timeElapsed <= 500) { // /* // * Important! // * if the artifacts are presented as a List, // * a user could also click on the corresponding text. // * We always want to work on the 'rect element, // * hence we select the enclosing 'g' first // */ // const clicked = d3.select(clickedElem.target.parentElement).select('rect'); // if (clicked.classed('clicked')) { // // check if the class string contains 'clicked'. // // In ECMA6 remove elemId from array // this._currentlyClickedElemsId = this._currentlyClickedElemsId // .filter((e) => e !== attachedData.id); // clicked // .classed('clicked', false) // .attr('fill-opacity', 0.35) // .attr('stroke-opacity', 0.7); // } else { // this._currentlyClickedElemsId.push(attachedData.id); // clicked // .classed('clicked', true) // .attr('fill-opacity', 1) // .attr('stroke-opacity', 1); // } // this.emit('clickArtifact', [this._prefix, attachedData.id]); // } else { // // this additional funtionality is not yet implemented. // this.emit('createDependencyGraph', [this._prefix, attachedData.id]); // } // }) // .on('mouseover mousemove', (event, attachedData) => { // this._updateControlStatus('xPos', event.pageX); // this._updateControlStatus('yPos', event.pageY); // this.emit('updateTooltip', [this._prefix, attachedData.id]); // }) // .on('mouseleave', () => { // d3.select('#tooltip') // .style('opacity', 0) // // we move the tootip to the top left corner and shrik it to the minimum size. // // this prevents an 0 opacity tooltip from overlapping artifacts. // .style('left', '0px') // .style('top', '0px') // .html(''); // }); // return gs; // }, // (update) => { // update // .selectAll('.clicked') // .attr('fill-opacity', 1); // update // .selectAll('rect') // .attr('width', artifactDimWidth) // .attr('height', artifactDimHeight) // .attr('stroke', (d) => this._currentColorScale(d.color)) // .attr('style', (d) => `fill:${this._currentColorScale(d.color)}`); // return update; // }, // (exit) => { // exit // .attr('class', 'exit') // // eslint-disable-next-line no-shadow // .call((exit) => exit.transition().duration(2000) // // eslint-disable-next-line no-unused-vars // .attr('transform', (d, i) => `translate( // ${Math.floor(Math.random() * this._width) + 1}, ${2 * this._height})`) // .remove()); // }, // ) // .call((s) => { // s.transition().duration(tansitionTime) // .attr('transform', (d, i) => `translate(${gx(d, i)}, ${gy(d, i)})`); // }); // /* // * if we display the artifacts in a List, we want to use the extra space to // * show more information in each artifact/List-Element. // */ // if (flagListDisplay) { // const idArray = []; // d3.selectAll(`.${this._viewDivId}-g`) // .selectAll('*:not(exit)') // .each((d) => { // idArray.push(d.id); // }); // this.emit('getListsTextValues', [this._prefix, idArray]); // } else { // d3.select(`#${this._viewDivId}-svg`) // .selectAll('.text.label') // .remove(); // } // // This function is needed durign redrawing. it takes care of all clicked elements. // // clicked elements should be clicked if redrawed // d3.selectAll(`.${this._viewDivId}-g`) // .filter((d) => this._currentlyClickedElemsId.includes(d.id)) // .selectAll('rect') // .classed('clicked', true) // .attr('fill-opacity', 1); // this._rootSvg // .on('click', () => { // this.clickIntersection(); // }); } renderProjection(data, renderEverything = false) { const menu = [ { title: 'add to new cluster' }, { divider: true, }, ]; if (renderEverything) { this._dataCluster.forEach((c) => { menu.push( { title: `clusterID: ${c.cluster} :: ${c.cluster_main_words}`, action: (d, event) => { const information = [d.cve, c.cluster, c.cluster_main_words]; console.log(information); this.updateCveCluster(information); this.emit('assignCveToNewCluster', information); }, }, ); }); } console.log(data); this._gDot.selectAll('circle') .data(data, (d) => d.cve) .join( (enter) => { enter .append('circle') .attr('cx', (d) => d.x) .attr('cy', (d) => d.y) .attr('r', (d) => colorscales.circleScale(d.numb_affected_apps)) .attr('id', (d) => d.cve) // .attr('stroke', (d) => this._currentColorScale(d.cvssScore)) // ) // .attr('stroke-width', '1') // .attr('stroke-opacity', 1) .attr('style', (d) => `fill:${colorscales.cluster(d.cluster)}`) .attr('fill-opacity', 1) .on('mouseover mousemove', (event, attachedData) => { this._updateControlStatus('xPos', event.pageX); this._updateControlStatus('yPos', event.pageY); this.updateTooltip(attachedData); // this.emit('updateTooltip', [this._prefix, attachedData.cve]); }) .on('mouseleave', () => { d3.select('#tooltip') .style('opacity', 0) // we move the tootip to the top left corner and shrik it to the minimum size. // this prevents an 0 opacity tooltip from overlapping artifacts. .style('left', '0px') .style('top', '0px') .html(''); }) .on('contextmenu', d3.contextMenu(menu)) .on('click', (event) => { if (event.shiftKey === true) { this._clickSelection.push(event.target.id); } else if (this._clickSelection.length >= 1) { this._clickSelection.push(event.target.id); this.emit('clickedVulnerability', this._clickSelection); this._clickSelection = []; } else { this.emit('clickedVulnerability', [event.target.id]); } // console.log(event.target.id); }); }, (update) => { console.log(update); update // .selectAll('circle') .attr('fill-opacity', 1) .attr('cx', (d) => d.x) .attr('cy', (d) => d.y) .attr('r', (d) => colorscales.circleScale(d.numb_affected_apps)) .attr('style', (d) => `fill:${colorscales.cluster(d.cluster)}`); // update // .selectAll('rect') // .attr('width', artifactDimWidth) // .attr('height', artifactDimHeight) // .attr('stroke', (d) => this._currentColorScale(d.color)) // .attr('style', (d) => `fill:${this._currentColorScale(d.color)}`); return update; }, (exit) => { // there is no exiting of elements. hence this funciton is empty. }, ); } /** * The function appends <text> to the matching artifact. * @param {Object} data - contains the text for the respectiv key(id). */ displayTextinList(data) { // the keys of the argument are ids. const idArray = Object.keys(data); // select all artifacts for which the data argument contains a matching id. d3.selectAll(`.${this._viewDivId}-g`) .filter((d) => idArray.includes(d.id)) .append('text') .attr('dy', 2 * this._edgeLen - 2) .attr('class', 'text label') .attr('dx', '1') .text((d) => data[d.id].name); } /** * The control elements are placed above and beneath the actural view. * above: search field * beneath: orderings and colorings */ initViewControlls() { const textSearchId = `${this._menuDivId}-search`; // all template files are stored in apps.html. const templateOrderings = document.getElementById(`template-view-orderings-${this._prefix}`).innerHTML; const templateColor = document.getElementById(`template-view-color-${this._prefix}`).innerHTML; d3.select(`#${this._prefix}-menu`) // the div above the artifact view. .append('div') .attr('id', 'entry input-group col-xs-12'); const bottomDiv = d3.select(`#${this._prefix}-bottom`).append('div'); // the div beneath the artifact view. bottomDiv .html(templateColor + templateOrderings); // append the temples html code to the bottom div. bottomDiv .select('div .dropdown-menu.orderings') .on('click', (event) => { // id has the form <viewprefix-ordering-o>. Example: app-cves-o const [, selectedOrdering] = event.target.id.split('-'); // ignoring the first eleme in the split array. const classes = d3.select(`#${event.target.id}`) .attr('class'); const matches = classes.match(/\[(.*?)\]/)[1]; d3.select(`#${this._prefix}-orderings`) .text(`Ordering:${matches}`); this.emit('newOrdering', [this._prefix, selectedOrdering]); }); bottomDiv .select('div .dropdown-menu.color') .on('click', (event) => { // id has the form <viewprefix-ordering-o>. Example: app-cves-o const [, selectedColormapping] = event.target.id.split('-'); // ignoring the first eleme in the split array. this._controlStatus.color = selectedColormapping; const classes = d3.select(`#${event.target.id}`) .attr('class'); const matches = classes.match(/\[(.*?)\]/)[1]; d3.select(`#${this._prefix}-color`) .text(`Color:${matches}`); this.emit('newColorMapping', [this._prefix, selectedColormapping]); }); /* Init Search function */ d3.select(`#${this._menuDivId}`) .append('div') .attr('class', 'input-group') .append('div') .attr('class', 'form-outline') .append('input') .attr('type', 'search') .attr('id', textSearchId) .attr('placeholder', `${this._prefix} view`) .attr('class', 'form-control'); d3.select(`#${textSearchId}`) .on('input onclick', () => { // views can filter on their own. Do not have to emit an event! // onclick - chrome event. little blue cross-icon const dynamicOpacity = 0.35; const currentInputValue = d3.select(`#${this._menuDivId}-search`) .node() .value .toLowerCase(); // case of the input is 'ignored'. // If the search field is empty. we have an empty string, which machtes every artifact id. if (currentInputValue.length >= 1) { d3.selectAll(`.${this._viewDivId}-g`) .filter((d) => d.id.toLowerCase().includes(currentInputValue)) .attr('style', 'opacity:1') .classed('foundBySearch', true); d3.selectAll(`.${this._viewDivId}-g`) .filter((d) => !(d.id.toLowerCase().includes(currentInputValue))) .classed('foundBySearch', false) .attr('style', `opacity: ${dynamicOpacity}`); } else { // search field is empty. d3.selectAll(`.${this._viewDivId}-g`) .attr('style', 'opacity:1') .classed('foundBySearch', false); } }); } /** * fills the tooltip with the parameters information. * @param {Object} data - all information about a single artifact. */ updateTooltip(data) { let dynamicHtml = `${data.cve}`; const [vector, score, affectedApps, namedEntities, cluster] = [data.cvssVector, data.cvssScore, data.numb_affected_apps, data.named_entities, data.cluster]; let desc = data.description; namedEntities.forEach((e) => { desc = desc.replaceAll(e, `<b>${e}</b>`); }); dynamicHtml += `<p style="text-align: center; color: darkgrey"> <b>score: ${score} </b></p>`; dynamicHtml += '<table style="width:100%; align:left"><tr><th></th><th></th></tr>'; dynamicHtml += `<tr><td>cluster</td><td>${cluster}</td></tr>`; dynamicHtml += `<tr><td>Affected applications</td><td>${affectedApps}</td></tr>`; dynamicHtml += `<tr><td>Vector</td><td>${vector}</td></tr>`; dynamicHtml += `<tr><td>Description</td><td>${desc}</td></tr>`; d3.select('#tooltip') .attr('style', 'opacity: 0.85') .html(dynamicHtml) .style('left', `${this._controlStatus.xPos + 50}px`) .style('top', `${this._controlStatus.yPos}px`); } /** * @param {Object} idArray - array of ids */ changeOpacityOfFilteredElements(idArray) { const artifacSelection = this._rootSvg.selectAll('circle'); let datapointeToFilter = idArray; if (typeof idArray === 'object') { datapointeToFilter = Object.values(idArray); } console.log(datapointeToFilter); artifacSelection .filter((d) => !(datapointeToFilter.includes(d.cve))) // all elements that are not included. .classed('filtered', true); artifacSelection .filter((d) => datapointeToFilter.includes(d.cve)) // select all elements that are included .classed('filtered', false); } // /** // * @param {Object} idArray - array of ids // */ // filterCvssVersion(idArray) { // const artifacSelection = d3.selectAll(`.${this._viewDivId}-g`); // artifacSelection // .filter((d) => !(idArray.includes(d.id))) // select all elements that are not included. // .attr('style', 'opacity:0.35'); // artifacSelection // .filter((d) => idArray.includes(d.id)) // select all elements that are not included. // .attr('style', 'opactiy:1'); // } clickIntersection() { // We count the number of clicked elements inside each ArtifacView. let numbOfClickedElems = 0; /* * randomClickedElemsId contains the id of a clicked Artifact. * this id will triggering the redrawing of all selected elemets when * the checkbox is not checked anymore. (quick and dirty) * */ const clickedElemIds = []; d3.select(`#${this._viewDivId}-svg`) .selectAll('rect') // need anonym function to have the right scope! (arrow-func does not work)! // eslint-disable-next-line func-names .each(function (d) { if (d3.select(this).classed('clicked')) { numbOfClickedElems += 1; clickedElemIds.push(d.id); } }); if (numbOfClickedElems <= 1) { this.emit('resetAllIntersectedElem'); } // _controlStatu knows if the radiobutton is curently selected. if (this._controlStatus.showIntersection) { // case: the radiobutton for this view is checked if (numbOfClickedElems >= 2) { /* To get here - two or more elements are clicked * + * we selected this view to show the intersection. */ this.emit('displayIntersection', this._prefix); } } } /* * * * The following funcitons are small helper functions. * * */ currentlySeletedColorMapping() { return this._controlStatus.color; } /** * returns current size of the views root svg element. * @returns {Object} */ rootSvgDim() { const rootSvg = document.getElementById(`${this._viewDivId}-svg`); const dim = {}; dim.width = rootSvg.clientWidth; dim.height = rootSvg.clientHeight; return dim; } removeAllArtifacts() { d3.select(`#${this._viewDivId}-svg`) .selectAll('*') .remove(); } updateCveCluster(data) { console.log(data); const [cve, newCluster] = data; const currentData = this._rootSvg.selectAll('circle') .filter((d) => d.cve === cve) .datum(); // data bound to the DOM element // find entry that has the same cve + save it // const index = currentData.findIndex((key) => key.cve === cve); // console.log(index); // let dataElem = this._dataSet.splice(index, 1); // delete it from current Data // if (typeof (dataElem) === ) { // we found a matching element // [dataElem] = dataElem; // } else { // console.log('error in updateCveCluster: found no matching element for cve or found several elements.'); // } console.log(this._dataSet); console.log(newCluster); currentData.cluster = newCluster; // +1 indexing problems! chose -1 as a key. // eslint-disable-next-line prefer-destructuring currentData.cluster_main_words = this._dataCluster[newCluster + 1].cluster_main_words; this.renderProjection([currentData]); // modify/ update the saved version // push it back into the dataset // call dataSet(updatedData) } set dataSet(newData) { if (this.sigletonMove) { this._initData = newData; // need this data for recalc of the focedirected layout. this.sigletonMove = false; } this._dataSet = newData; // this data is updateted by the backend. } set dataCluster(newData) { this._dataCluster = newData; console.log(typeof (Object.keys(newData)[0])); } set dataClusterVendor(newData) { this._dataClusterVendor = newData; } set filteredElements(newData) { this._filteredElems = Object.values(newData); this._dataSet = this._filteredElems; } fireClick() { this.clickIntersection(); } get prefix() { return this._prefix; } viewControlStatus(elem) { return this._controlStatus[elem]; } _updateControlStatus(elem, newStatus) { this._controlStatus[elem] = newStatus; } addRangeSlider() { let rangFilterDivRow = d3.select('#umap-view') .append('div') .attr('class', 'row'); rangFilterDivRow = rangFilterDivRow .append('div') .attr('id', 'slider-range') .attr('class', 'col'); const dataTime = d3.range(0, 16).map((d) => 2005 + d); // Range const sliderRange = d3 .sliderBottom() .min(d3.min(dataTime)) // min:0 and max:10 CVSS score .max(d3.max(dataTime)) .step(1)// .step(1000 * 60 * 60 * 24 * 365) .width(this._width - this.MARGINS.left) .tickFormat(d3.format('d')) // .ticks(12) .default([2005, 2020]) .fill('gray') .on('end', (rangeArray) => { const rangeArrayFixed = [rangeArray[0], rangeArray[1]]; this.emit('rangeSliderYearChanged', rangeArrayFixed); }); const gRange = d3 .select('div#slider-range') .append('svg') .attr('width', this._width + this.MARGINS.left + this.MARGINS.right) // -39 == size of dropup menu .attr('height', window.innerHeight - $('#nav-bar').outerHeight(true) - $('#umap-view-svg').outerHeight(true) - 39) .append('g') .attr('transform', `translate(${this.MARGINS.left},${this.MARGINS.top})`); gRange.call(sliderRange); d3.select('p#value-range').text( sliderRange .value(), // .map(d3.timeFormat('%Y')), // .join('-'), ); gRange .append('g') .attr('transform', `translate(${(this._width) / 2 - 10},50)`) .append('text') .attr('class', 'x label') .attr('text-anchor', 'middle') .text('filter CVEs by year'); gRange .append('g') .attr('transform', 'translate(0,50)') .append('text') .attr('class', 'min-x label') .attr('text-anchor', 'middle') .text('oldest'); gRange .append('g') .attr('transform', `translate(${this._width - 20},50)`) .append('text') .attr('class', 'max-x label') .attr('text-anchor', 'middle') .text('newest'); // gRange // .append('g') // .attr('transform', 'translate(0,70)') // .append('text') // .attr('class', 'rangeSlider label') // .text('Range Slider: Description Text'); const dropup = d3.select('#slider-range') // .append('foreignObject') // .attr('x', 5) // .attr('y', 5) // .attr('width', 100) // .attr('height', 100) .append('div') .attr('class', 'btn-group dropup'); dropup .append('button') .attr('type', 'button') .attr('class', 'btn btn-secondary dropdown-toggle') .attr('data-toggle', 'dropdown') .text('mappings'); const menu = dropup .append('div') .attr('class', 'dropdown-menu'); menu .append('a') .attr('class', 'dropdown-item') .attr('id', 'numbAffectedApps') .text('numb of affected applications to size'); menu .append('a') .attr('class', 'dropdown-item') .attr('id', 'numbAffectedApps') // whaa! take another id .text('numb of affected libraries to size'); menu .append('a') .attr('class', 'dropdown-item') .text('none::default'); menu.selectAll('.dropdown-item') .on('click', (event) => { if (event.target.id === 'numbAffectedApps') { colorscales.circleScale = d3.scaleSqrt() .domain([1, 739]) .range([1, sizeOfCircle * this._scalingFaktor]); const simulation = d3.forceSimulation(this._initData) .force('x', d3.forceX((d) => this._xScale(d.x_projection))) .force('y', d3.forceY((d) => this._yScale(d.y_projection))) .force('collide', d3.forceCollide((d) => colorscales.circleScale(d.numb_affected_apps))); // Run the simulation for 100 steps for (let i = 0; i < 100; i += 1) { simulation.tick(); } simulation.stop(); console.log('this._dataSet'); // this.renderProjection(this._dataSet); } else { colorscales.circleScale = d3.scaleSqrt() .domain([1, 739]) .range([sizeOfCircle, sizeOfCircle]); const simulation = d3.forceSimulation(this._initData) .force('x', d3.forceX((d) => this._xScale(d.x_projection))) .force('y', d3.forceY((d) => this._yScale(d.y_projection))) .force('collide', d3.forceCollide((d) => colorscales.circleScale(d.numb_affected_apps))); for (let i = 0; i < 100; i += 1) { simulation.tick(); } simulation.stop(); } this.renderProjection(this._initData); }); } } // eslint-disable-next-line import/prefer-default-export export { UMAPprojection };
Ext.define('dlmsprint2a.view.RuleGrid', { extend : 'Ext.grid.GridPanel', alias : 'widget.rulegrid', //store : Ext.create('dlm.store.DlmFilesStore'), name : 'rulegrid', //border : false, //title : 'Editor', dockedItems : [{ xtype : 'toolbar', items : [{ xtype : 'tbspacer', width: 6, },{ xtype : 'textfield', fieldLabel: 'Filter', value: 'lobal.DAT', labelWidth : 30, //iconCls : 'upload', },{ xtype : 'tbspacer', width: 6, },{ xtype : 'textfield', fieldLabel: 'Export Template', value: 'lobal.DAT', labelWidth : 90, //iconCls : 'upload', },{ xtype : 'tbspacer', width: 6, },{ xtype: 'textareafield', name: 'textarea1', fieldLabel: 'Description', labelWidth : 60, value: 'Only low balance accounts', }], }], columns : [{ text : 'Structure', columns : [{ text : 'Del', width : 40, },{ text : 'Insert', width : 40, }], },{ text : 'Filter', width : 200, },{ text : 'Content', columns : [{ text : 'not', width : 40, },{ text : 'or', width : 40, },{ text : 'Criterion', width : 100, },{ text : 'Op', width : 40, },{ text : 'Value', width : 100, }], }], });
import { createSelector } from 'reselect'; import { selectCurrentDate } from '@/containers/DateSelector/selectors'; import { toPrecision } from '@/utils/formatData'; import { withDataHashKey } from '@/utils/hashData'; import { COLORS } from '@/utils/styleConstants'; import CONSTANTS, { LABELS, RESULT_KEY } from './constants'; import { initialState } from './reducer'; export const selectResults = state => state[CONSTANTS.REDUCER_KEY.KEY]?.[CONSTANTS.REDUCER_KEY.RESULTS] || initialState[CONSTANTS.REDUCER_KEY.RESULTS]; const selectResultsByRange = state => state[CONSTANTS.REDUCER_KEY.KEY]?.[CONSTANTS.REDUCER_KEY.RESULTS_BY_RANGE] || initialState[CONSTANTS.REDUCER_KEY.RESULTS_BY_RANGE]; const selectStatus = state => state[CONSTANTS.REDUCER_KEY.KEY]?.[CONSTANTS.REDUCER_KEY.STATUS] || initialState[CONSTANTS.REDUCER_KEY.STATUS]; const CHART_COLORS = [ COLORS.CHARTS.PARALLEL_COORDINATES.LIGHT_BLUE, COLORS.CHARTS.PARALLEL_COORDINATES.GREY, COLORS.CHARTS.PARALLEL_COORDINATES.BLUE, COLORS.CHARTS.PARALLEL_COORDINATES.DARK_GRAY ]; export const makeSelectStatus = key => createSelector( selectStatus, status => status[key] ); const makeSelectCurrentResults = () => createSelector( selectResultsByRange, selectCurrentDate, (resultsByRange, currentDate) => { const result = resultsByRange.filter(({ id }) => id === currentDate); if (result.length === 0) { return null; } return result[0]; } ); export const makeSelectResultsByRange = () => createSelector( makeSelectCurrentResults(), result => { if (!result) { return withDataHashKey({}); } const data = { data: [], variables: [ { key: RESULT_KEY.PEAK_POWER, type: 'linear', legend: LABELS[RESULT_KEY.PEAK_POWER], legendPosition: 'start', legendOffset: 10 }, { key: RESULT_KEY.TIME, type: 'linear', legend: LABELS[RESULT_KEY.TIME], legendPosition: 'start', legendOffset: 10 }, { key: RESULT_KEY.AP, type: 'linear', legend: LABELS[RESULT_KEY.AP], legendPosition: 'start', legendOffset: 10 }, { key: RESULT_KEY.RPM, type: 'linear', legend: LABELS[RESULT_KEY.RPM], legendPosition: 'start', legendOffset: 10 } ] }; result?.[RESULT_KEY.LOAD].forEach((value, index) => { data.data.push({ [RESULT_KEY.AP]: toPrecision(result?.[RESULT_KEY.AP]?.[index] ?? 0, 0), [RESULT_KEY.APR]: toPrecision(result?.[RESULT_KEY.APR]?.[index] ?? 0, 0), [RESULT_KEY.TIME]: toPrecision(result?.[RESULT_KEY.TIME]?.[index] ?? 0, 0), [RESULT_KEY.PEAK_POWER]: toPrecision(result?.[RESULT_KEY.PEAK_POWER]?.[index] ?? 0, 0), [RESULT_KEY.RELATIVE_POWER]: toPrecision( result?.[RESULT_KEY.RELATIVE_POWER]?.[index] ?? 0, 0 ), [RESULT_KEY.RPM]: toPrecision(result?.[RESULT_KEY.RPM]?.[index] ?? 0, 0), [RESULT_KEY.LOAD]: toPrecision(value, 0), color: CHART_COLORS[index] || COLORS.CHARTS.PARALLEL_COORDINATES.BLUE }); }); return withDataHashKey(data); } ); export const makeSelectLegend = () => createSelector( makeSelectCurrentResults(), result => { if (!result) { return []; } const data = []; result?.[RESULT_KEY.LOAD].forEach((value, index) => { data.push({ id: value, color: CHART_COLORS[index] || COLORS.CHARTS.PARALLEL_COORDINATES.BLUE, label: `нагрузка ${value} кг` }); }); return data; } );
// change this for sign up - right now its copied from Login.jsx import React from 'react'; import { connect } from 'react-redux'; import { signupUser } from '../reducers/user'; export const SignUp = ({ signup }) => ( <form onSubmit={evt => { evt.preventDefault(); signup(evt.target.username.value, evt.target.password.value); }} > <input name="username" /> <input name="password" type="password" /> { / *Other fields should go here for storage in database if necessary*/ } <input type="submit" value="Signup" /> </form> ); const mapDispatch = (dispatch) => ({ signup: (email, password) => dispatch(signupUser(email, password)) }); export default connect(null, mapDispatch)(SignUp);
var assert = require('chai').assert; var rules = require('../src/rules_functions.js'); describe('Should fail after_or rule', () => { it('is 2010-10-01 after_or 2010-10-02', () => { var result = rules.afterOr('2010-10-01', {after_or: '2010-10-02'}); assert.equal(result, false); }); it('is 2010-10-01 after_or 2018-01-01', () => { var result = rules.afterOr('2010-10-01', {after_or: '2018-01-01'}); assert.equal(result, false); }); it('is 10/01/1987 after_or 01/01/2000', () => { var result = rules.afterOr('10/01/1987', {after_or: '01/01/2000'}); assert.equal(result, false); }); it('is 10/01/87 after_or 2010-10-01', () => { var result = rules.afterOr('10/01/87', {after_or: '2010-10-01'}); assert.equal(result, false); }); it('is 10/01/87 after_or new Date(2010-10-01)', () => { var result = rules.afterOr('10/01/87', {after_or: new Date('2010-10-01')}); assert.equal(result, false); }); it('is 2010-10-01 after_or 2018-01-01 05:01:00', () => { var result = rules.afterOr('2010-10-01', {after_or: '2018-01-01 05:01:00'}); assert.equal(result, false); }); it('is 2010-10-01 after_or 2010-10-01 00:00:01', () => { var result = rules.afterOr('2010-10-01', {after_or: '2010-10-01 00:00:01'}); assert.equal(result, false); }); it('is 2010-10-01 00:00:01 after_or 2010-10-01 00:00:02', () => { var result = rules.afterOr('2010-10-01 00:00:01', {after_or: '2010-10-01 00:00:02'}); assert.equal(result, false); }); it('is new Date(2010-10-01 00:00:01) after_or new Date(2010-10-01 00:00:02)', () => { var test_date = new Date('2010-10-01 00:00:01'); var rules_date = new Date('2010-10-01 00:00:02'); var result = rules.afterOr(test_date, {after_or: rules_date}); assert.equal(result, false); }); }); describe('Should pass after_or rule', () => { it('is 2010-10-02 after_or 2010-10-01', () => { var result = rules.afterOr('2010-10-02', {after_or: '2010-10-01'}); assert.equal(result, true); }); it('is 2018-01-01 after_or 2018-01-01', () => { var result = rules.afterOr('2018-01-01', {after_or: '2018-01-01'}); assert.equal(result, true); }); it('is 01/01/2000 after_or 10/01/1987', () => { var result = rules.afterOr('01/01/2000', {after_or: '10/01/1987'}); assert.equal(result, true); }); it('is 10/01/87 after_or 10/01/87', () => { var result = rules.afterOr('10/01/87', {after_or: '10/01/87'}); assert.equal(result, true); }); it('is 10/01/87 after_or new Date(10/01/87)', () => { var result = rules.afterOr('10/01/87', {after_or: new Date('10/01/87')}); assert.equal(result, true); }); it('is 2010-10-01 00:00:01 after_or 2010-10-01 00:00:01', () => { var result = rules.afterOr('2010-10-01 00:00:01', {after_or: '2010-10-01 00:00:01'}); assert.equal(result, true); }); it('is new Date(2010-10-01 00:00:02) after_or new Date(2010-10-01 00:00:01)', () => { var test_date = new Date('2010-10-01 00:00:02'); var rules_date = new Date('2010-10-01 00:00:01'); var result = rules.afterOr(test_date, {after_or: rules_date}); assert.equal(result, true); }); });
(function () { //Назначаем обработчик на кнопку добавления ИП document.getElementById('problem_create').addEventListener("click", function () { //Очищаем локальное хранилище cliensessionStorage(); //Ожидаем постройки DOM модального окна setTimeout(function () { //Вставляем кнопку переводчика var modal = document.getElementsByClassName('modal-footer'); var buttonTranslit = "<button id=\"translater\" type=\"button\" class=\"btn btn-info\">Перевести</button>"; modal[0].innerHTML = buttonTranslit + modal[0].innerHTML; //Устанавливаем обработчик на кнопку Перевести document.getElementById('translater').addEventListener("click", function () { delete document.querySelectorAll('.modal-footer')[0] main(sessionStorage["master"] || "ru") }); //Вешаем обработчики событий на кнопки закрытия модального окна для очистки хранилища document.querySelectorAll('.modal-footer')[0].children[1].addEventListener("click", cliensessionStorage); document.querySelectorAll('.modal-footer')[0].children[2].addEventListener("click", cliensessionStorage); document.querySelectorAll('.modal-header')[0].children[0].addEventListener("click", cliensessionStorage); }, 100) }); //Выбираем источник получения данных для вывода function main(master) { if (master === "ru") { sessionStorage["translit"] = document.getElementById('create-info').value; requestTrans(document.getElementById('create-info').value).then(function (response) { return JSON.parse(response).trans }).then(function (response) { sessionStorage["master"] = "uk"; backResult(response) }); } else if (master === "uk") { if(sessionStorage["translit"]){ sessionStorage["master"] = "ru"; backResult(sessionStorage["translit"]); } else { alert("Архив не найден в sessionStorage") } } else { alert("Ошибка выбора языка") } } //Вызываем API Google переводчика function requestTrans(text){ var requestURL = "https://script.google.com/macros/s/AKfycbys4Q7s43XcosBx5hKmGPVhWOyrl5_cRKXe2YCBvYWB3EZ9RH0P/exec?text=" + text; return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.open('GET', requestURL); req.onload = function() { if (req.status == 200) { resolve(req.responseText); } else { reject(Error(req.statusText)); } }; req.onerror = function() { reject(Error("Network Error")); }; req.send(); }); } //Вставляем результат перевода function backResult(text){ document.getElementById('create-info').value = text; } //удаляет все элементы из sessionStorage function cliensessionStorage(){ delete sessionStorage["translit"]; delete sessionStorage["master"]; } })();
(function () { 'use strict'; angular.module('AdBase').controller('localityController',localityController); localityController.$inject = ['$scope', 'localityService','countryService']; function localityController($scope,localityService,countryService){ var self = this ; self.searchInput = {}; self.totalItems ; self.itemPerPage=25 ; self.currentPage = 1; self.maxSize = 5 ; self.localitys = []; self.countrys = []; self.searchEntity = {}; self.selectedIndex ; self.handleSearchRequestEvent = handleSearchRequestEvent; self.handlePrintRequestEvent = handlePrintRequestEvent; self.paginate = paginate; init(); function init(){ self.searchInput = { entity:{}, fieldNames:[], start:0, max:self.itemPerPage } loadCountry(); findAllActive(self.searchInput); } function findAllActive(searchInput){ localityService.findAllActive(searchInput).then(function(entitySearchResult) { self.localitys = entitySearchResult.resultList; self.totalItems = entitySearchResult.count ; }); } function doFind(searchInput){ localityService.doFind(searchInput).then(function(entitySearchResult) { self.localitys = entitySearchResult.resultList; self.totalItems = entitySearchResult.count ; }); } function processSearchInput(){ var fileName = []; if(self.searchInput.entity.ouIdentif){ fileName.push('ouIdentif') ; } if(self.searchInput.entity.ctryISO3){ fileName.push('ctryISO3') ; } if(self.searchInput.entity.region){ fileName.push('region') ; } if(self.searchInput.entity.locStr){ fileName.push('locStr') ; } self.searchInput.fieldNames = fileName ; return self.searchInput ; }; function handleSearchRequestEvent(){ var searchInput = processSearchInput(); doFind(searchInput); }; function paginate(){ self.searchInput.start = ((self.currentPage - 1) * self.itemPerPage) ; self.searchInput.max = self.itemPerPage ; doFind(self.searchInput); }; function loadCountry(){ countryService.findActifsFromNow().then(function(data){ self.countrys=data; }); } function handlePrintRequestEvent(){ } }; })();
// _________Задание 1.a______ let printNumbers = (from, to) => { let counter = from; setTimeout(function start() { console.log(counter); if (counter < to) { setTimeout(start, 1000); } counter++; }, 1000); } // printNumbers(1, 20); // _________Задание 1.b______ let printNumbers2 = () => { let i = 1; let timerId = setInterval(() => { console.log(i); if (i == 20) clearInterval(timerId); i++; }, 100); } // printNumbers2(); // _________Задание 1.b______ let div = document.querySelector(".notify") let message = "Привет"; let time = 3000; let notify = (message, time)=>{ let i = Math.floor(Math.random()*10); div.innerHTML+=`<div class="notify__mass" id="${i}">${message}</div>`; console.log("1"); console.log(message,time); console.log(i); setTimeout(function delite(){ let box = document.getElementById(i); box.remove(); }, time) let box = document.querySelectorAll(".notify__mass"); console.log(box); box.forEach((item)=>{ item.addEventListener("click",()=>{ item.remove(); }); }); }; // // let box1 = document.querySelector("notify__mass") // box1.addEventListener("click", ()=>{ // box1.remove(); // }) //________Задача 2 _____________ function delay(ms){ return new Promise(resolve => setTimeout(resolve, ms)) } // delay(3000).then(() => alert('Привет'));
document.querySelector(".container").addEventListener("click", () => { document.querySelector("nav").classList.add("toggled"); document.querySelector(".X").classList.add("toggled"); }); document.querySelector(".X").addEventListener("click", () => { document.querySelector("nav").classList.remove("toggled"); document.querySelector(".X").classList.remove("toggled"); }); x = document.querySelectorAll("nav a"); for (let index = 0; index < x.length; index++) { const i = x[index]; i.addEventListener("click", () => { document.querySelector("nav").classList.remove("toggled"); document.querySelector(".X").classList.remove("toggled"); }); }
(function(angular) { 'use strict'; // Referencia para o nosso app var app = angular.module('app'); // Cria o controlador de pessoas app.controller('PeopleController', ['$scope', 'User', function($scope, User) { $scope.authUser = User.getAuthenticated(); // Redireciona para a página de autenticação if (!$scope.authUser) { window.location = 'index.html'; return; } $scope.users = User.all(); this.searchPeople = function() { $scope.key_aux = $scope.key; $scope.peoplefound = User.findAll({name : $scope.key}); } this.follow = function(user) { alert(user.name); } }]); })(window.angular);
App({ onLaunch: function () { String.prototype.trim = function () { return this.replace(/(^\s*)|(\s*$)/g, '') } }, login: function (options) { console.log('login invoke') var that = this wx.login({ success: function (res) { if (!res.code) { return } var loginData = {} loginData.code = res.code wx.getUserInfo({ success: function (res) { console.log('getUserInfo success=>') console.log(res) if (!res.encryptedData || !res.iv) { return } loginData.iv = res.iv loginData.raw_data = res.encryptedData that.getUserInfo(loginData, options) } }) } }) }, getUserInfo: function (loginData, options) { var that = this; wx.request({ url: 'https://www.kingco.tech/freeman/api/login.php', data: loginData, success: function (res) { console.log('getUserId success=>') console.log(res) var resData = JSON.parse(res.data.trim()) console.log(resData) if (!resData.uid ||!resData.proj_id) { return } that.globalData.uid = parseInt(resData.uid) that.globalData.role = parseInt(resData.role) that.globalData.projId = parseInt(resData.proj_id) that.globalData.groupId = parseInt(resData.group_id) var quit = that.checkOption(options) if (quit) { return } if (parseInt(resData.proj_id) !== 0) { that.updateMarker() wx.switchTab({ url: '/pages/project/project' }) } else { wx.redirectTo({ url: '/pages/include/noproj' }) } } }) }, checkOption: function (options) { var that = this if (parseInt(options.role) === 1) { var reqData = { uid: this.globalData.uid, role: parseInt(options.role) } console.log(reqData) wx.request({ url: 'https://www.kingco.tech/freeman/api/changeRole.php', data: reqData, success: function(res){ console.log('changeRole success=>') console.log(res) that.globalData.role = parseInt(options.role) wx.showToast({ title: '成功自由人导师!', icon: 'success' }) wx.switchTab({ url: '/pages/group/group' }) } }) return true } if (parseInt(options.projId)) { var reqData = { uid: this.globalData.uid, proj_id: parseInt(options.projId) } console.log(reqData) wx.request({ url: 'https://www.kingco.tech/freeman/api/addProjMember.php', data: reqData, success: function (res) { console.log('addProjMember success=>') console.log(res) wx.showToast({ title: '成功加入项目!', icon: 'success' }) that.globalData.projId = parseInt(options.projId) wx.switchTab({ url: '/pages/project/project' }) } }) return true } if (parseInt(options.groupId)) { if (this.globalData.projId) { var reqData = { proj_id: this.globalData.projId, group_id: parseInt(options.groupId) } wx.request({ url: 'https://www.kingco.tech/freeman/api/addGroupProj.php', data: reqData, success: function (res) { console.log('addGroupProj success=>') console.log(res) wx.showToast({ title: '成功加入群组!', icon: 'success' }) that.globalData.groupId = parseInt(options.groupId) wx.switchTab({ url: '/pages/group/group' }) } }) } else { wx.redirectTo({ url: '/pages/project/newproj?gruopId=' + parseInt(options.groupId) }) } return true } return false }, updateMarker: function () { var that = this wx.request({ url: 'https://www.kingco.tech/freeman/api/getMarker.php', data: { uid: this.globalData.uid, proj_id: this.globalData.projId }, success: function (res) { console.log('getMark success=>') var resData = JSON.parse(res.data.trim()) console.log(resData) that.globalData.marker = null that.globalData.marker = resData } }) }, qrScan: function () { var that = this wx.scanCode({ success: function (res) { console.log('scanCode success=>') console.log(res) var resData = that.queryString(res.path) console.log(resData) if (parseInt(resData.projId)) { var projId = parseInt(resData.projId) wx.request({ url: 'https://www.kingco.tech/freeman/api/addProjMember.php', data: { uid: that.globalData.uid, proj_id: projId }, success: function (res) { console.log('addProjMember success=>') console.log(res) wx.showToast({ title: '成功加入项目!', icon: 'success' }) var resData = JSON.parse(res.data.trim()) if (parseInt(resData.group_id)) { that.globalData.groupId = parseInt(resData.group_id) } that.globalData.projId = projId that.globalData.projUpdated = true wx.switchTab({ url: '/pages/project/project' }) } }) } if (parseInt(resData.groupId) && that.globalData.projId) { wx.request({ url: 'https://www.kingco.tech/freeman/api/addGroupProj.php', data: { proj_id: that.globalData.projId, group_id: resData.groupId }, success: function (res) { console.log('addGroupProj success=>') console.log(res) wx.showToast({ title: '成功加入群组!', icon: 'success' }) that.globalData.groupId = parseInt(resData.groupId) } }) } } }) }, queryString: function (url) { var urlObject = {} if (/\?/.test(url)) { var urlString = url.substring(url.indexOf('?') + 1) var urlArray = urlString.split('&') for (var i = 0, len = urlArray.length; i < len; i++) { var urlItem = urlArray[i] var item = urlItem.split('=') urlObject[item[0]] = item[1] } return urlObject } }, formToast: function(){ wx.showToast({ title: '提交成功,跳转中……', icon: 'loading', duration: 5000, mask: true }) }, loadToast: function(){ wx.showToast({ title: '请稍候……', icon: 'loading', duration: 5000, mask: true }) }, globalData: { uid: 0, projId: 0, groupId: 0, role: 0, projUpdated: false, groupUpdated: false, pulseUpdated: false, canvasUpdated: false, cardUpdate: false, comntUpdated: false, marker: {} } })
import uuid from '@/utils/uuid' export default [ { id: uuid(), title: 'CSS Tips & Tricks', category: 'Frontend', duration: 60, }, { id: uuid(), title: 'Frontend for dummmies', category: 'Frontend', duration: 90, }, { id: uuid(), title: 'Vue.js Pro Tips', category: 'Advanced Topics', duration: 60, }, { id: uuid(), title: 'Vue.js Composition API', category: 'Advanced Topics', duration: 55, }, { id: uuid(), title: 'Choosing the best folder structure for your application', category: 'Advanced Topics', duration: 100, }, { id: uuid(), title: 'Successful Elixir Cases', category: 'Backend', duration: 65, }, { id: uuid(), title: 'Node.js & Redis. High performance caching', category: 'Backend', duration: 40, }, { id: uuid(), title: 'Unit Testing React Components', category: 'Test', duration: 60, }, { id: uuid(), title: 'Best Easy Practices of Javascript', category: 'Beginner', duration: 70, }, { id: uuid(), title: 'JavaScript Clean Code — Quick Best Practices', category: 'Beginner', duration: 50, }, { id: uuid(), title: 'A way to learn React', category: 'Beginner', duration: 80, }, { id: uuid(), title: 'Creative Mobile Onboarding Concepts', category: 'Frontend', duration: 95, }, { id: uuid(), title: 'TDD Timeless', category: 'Test', duration: 45, }, { id: uuid(), title: 'Understanding JavaScript/TypeScript Memoization', category: 'Backend', duration: 80, }, { id: uuid(), title: 'Domain Driven Design in JavaScript', category: 'Advanced Topics', duration: 105, }, { id: uuid(), title: 'Deno vs. Node.js — Key Differences', category: 'Backend', duration: 0, }, { id: uuid(), title: 'Looking into Svelte 3', category: 'Beginner', duration: 45, }, { id: uuid(), title: 'Javascript Closure: Simply Explained', category: 'Beginner', duration: 30, }, { id: uuid(), title: 'STOP!! You don’t need Microservices', category: 'Backend', duration: 70, }, { id: uuid(), title: 'Unit tests in TypeScript', category: 'Test', duration: 90, }, { id: uuid(), title: 'Vuex made simple — getting started!', category: 'Beginner', duration: 30, }, { id: uuid(), title: 'Functional Programming in Frontend', category: 'Frontend', duration: 125, }, ]
var gulp = require('gulp'); var browserify = require('browserify'); var babelify = require('babelify'); var ngannotate = require('browserify-ngannotate'); var plumber = require('gulp-plumber'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var source = require('vinyl-source-stream'); var buffer = require('vinyl-buffer'); var jQuery = require('jquery'); gulp.task('bundle', function(){ return browserify({ entries: "./src/main.js", debug: true, transform: [ babelify.configure({ presets: ['es2015', 'es2016', 'stage-3'], sourceMaps: true }), ngannotate ], paths: "./src/**/*.js" }).bundle() .pipe(plumber()) .pipe(source('main.js')) .pipe(gulp.dest('./dist/')) .pipe(buffer()) .pipe(rename({ suffix: ".min" })) .pipe(uglify()) .pipe(gulp.dest('./dist/')) }); gulp.task('html', function(){ return gulp.src('./src/**/*.html') .pipe(gulp.dest('./dist/')); }); gulp.task('resources', function(){ return gulp.src([ './src/images/*.png' ]) .pipe(gulp.dest('./dist/images')); }); gulp.task('build', ['bundle', 'html', 'resources']);
import React, { Component } from "react"; import Dialog from "@material-ui/core/Dialog"; import AppBar from "@material-ui/core/AppBar"; import { ThemeProvider as MuiThemeProvider } from "@material-ui/core/styles"; import Button from "@material-ui/core/Button"; import Company from './Company'; export class WorkForm extends Component { continue = (e) => { e.preventDefault(); this.props.nextStep(); }; back = (e) => { e.preventDefault(); this.props.prevStep(); }; addCompany = (e) => { e.preventDefault(); this.props.addCompany(); }; render() { const { values, handleChange } = this.props; return ( <MuiThemeProvider> <> <Dialog open fullWidth maxWidth="sm"> <AppBar title="Enter Work experience" /> {values.companies?.map((company,idx) => { return ( <div className="company" key={'company'+idx}> <h3>Company {idx+1}</h3> <Company values={company} idx={idx} handleChange={handleChange}/> </div> ) })} <br /> <Button color="primary" variant="contained" onClick={this.addCompany}> Add company </Button> <br /> <Button color="secondary" variant="contained" onClick={this.back}> Back </Button> <Button color="primary" variant="contained" onClick={this.continue}> Continue </Button> </Dialog> </> </MuiThemeProvider> ); } } export default WorkForm;
import React, { Component } from 'react'; import { View, Modal, Text, TouchableHighlight, ScrollView } from 'react-native'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { List, ListItem } from 'react-native-elements'; import ActionSheet from '@yfuks/react-native-action-sheet'; import { userLogout } from '../actions/userActions'; import { changeMapStyle } from '../actions/settingsActions'; import * as css from './Styles'; var Options = [ 'aubergine', 'dark', 'night', 'retro', 'silver', 'standard' ]; var DESTRUCTIVE_INDEX = 1; var CANCEL_INDEX = 2; class SettingsList extends Component { render() { const { mapStyle, username } = this.props; const list = [{ title: username, icon: { type: 'entypo', name: 'user' }, onPress: () => this.props.showModal('no options here') }, { title: 'Change map style', subtitle: mapStyle, icon: { name: 'google-maps', type: 'material-community' }, onPress: () => { ActionSheet.showActionSheetWithOptions({ options: Options, cancelButtonIndex: CANCEL_INDEX, destructiveButtonIndex: DESTRUCTIVE_INDEX, tintColor: 'blue' }, (buttonIndex) => { if (buttonIndex !== undefined) { this.props.changeMapStyle(Options[buttonIndex]); } })} }, { title: 'Logout', icon: { name: 'logout', type: 'material-community' }, onPress: this.props.userLogout }]; return ( <ScrollView> <List> {list.map((item, i) => ( <ListItem key={i} title={item.title} subtitle={item.subtitle} leftIcon={item.icon} onPress={item.onPress}/> ))} </List> </ScrollView> ); } } export default connect(state => ({ mapStyle: state.session.settings.mapStyle, username: state.session.user.username }),(dispatch) => bindActionCreators({ userLogout: userLogout, changeMapStyle: changeMapStyle }, dispatch) )(SettingsList);
angular.module('mutt-match') .controller('messageEntryCtrl', ['messageService', function(messageService) { const vm = this; vm.click = click; vm.sendMessage = sendMessage; vm.isTrue = false; vm.text; function click() { console.log('click'); vm.isTrue = !vm.isTrue; }; function sendMessage(text, to) { console.log('send', text); console.log('to', to); vm.text = ''; messageService.sendMessage(text, to) .then((response) => { console.log('messageEntry sendMessage success', response); }) .catch((error) => { console.log('messageEntry sendMEssage fail', error); }); }; vm.openDialog = function($event) { $mdDialog.show({ controller: DialogCtrl, controllerAs: 'ctrl', templateUrl: 'dialog.tmpl.html', parent: angular.element(document.body), targetEvent: $event, clickOutsideToClose:true }); }; }]) .directive('messageEntry', function() { return { scope: { message: '<' }, controller: 'messageEntryCtrl', controllerAs: 'ctrl', bindToController: true, templateUrl: './states/home/message/messageEntry.html' } })
google.charts.load("current", {packages:['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ["Month", "Temperature", { role: "style" } ], ["January", -2.4, "rgb(226, 38, 38)"], ["Feburary", 0.4, "rgb(226, 116, 38)"], ["March", 5.7, "rgb(227, 230, 49)"], ["April", 12.5, "rgb(161, 230, 49)"], ["May", 17.8, "rgb(25, 194, 84)"], ["June", 22.2, "rgb(24, 224, 171)"], ["July", 24.9, "rgb(24, 224, 221)"], ["August", 25.7, "rgb(23, 167, 215)"], ["September", 21.2, "rgb(23, 97, 215)"], ["October", 14.8, "rgb(76, 30, 214)"], ["November", 7.2, "rgb(208, 39, 231)"], ["December", 0.4, "rgb(231, 39, 112)"] ]); var view = new google.visualization.DataView(data); view.setColumns([0, 1, { calc: "stringify", sourceColumn: 1, type: "string", role: "annotation" }, 2]); var options = { title: "1981-2010 monthly average of temperature(Seoul)", width: 1600, height: 600, bar: {groupWidth: "95%"}, legend: { position: "none" }, }; var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values")); chart.draw(view, options); }
/** * @file TreeNode.js Tree节点 * @author zhangzhe(zhangzhe@baidu.com) */ import _ from 'lodash'; import {DataTypes, defineComponent} from 'san'; import TextBox from './TextBox'; import CheckBox from './CheckBox'; import {create, confirm} from './util'; const cx = create('ui-tree'); /* eslint-disable */ const commonTemplate = ` <div class="${cx('content-wrapper')}" on-click="onNodeClick($event)"> <span class="{{indicatorClass}}"></span> <div s-if="multi && !isUpdating" class="${cx('item-content')}"> <ui-checkbox checked="{=isSelected=}" title="{{text}}" on-change="onCheckboxChange($event)" on-click="onCheckboxClick" /> </div> <div s-if="!multi && !isUpdating" class="${cx('item-content')}">{{text}}</div> <ui-textbox s-if="isUpdating" class="${cx('edit-input')}" autofocus="{{true}}" focus-position="all" value="{{text}}" width="{{100}}" on-enter="onTextboxEnter" on-click="onTextboxClick" on-blur="onTextboxBlur" /> <div s-if="edit" class="${cx('edit-content')}"> <a class="create" href="javascript:;" on-click="onCreate" title="添加"><i class="iconfont icon-icon-test"></i></a> <a class="update" href="javascript:;" on-click="onUpdate" title="更新"><i class="iconfont icon-business-consult"></i></a> <a class="delete" href="javascript:;" on-click="onDelete" title="删除"><i class="iconfont icon-close"></i></a> </div> </div> <ul s-if="hasChildren" class="${cx('sub-root')} ${cx('sub-root-{{expandedFlag}}')}"> <ui-tree-node s-for="node in children" value="{{node.value}}" text="{{node.text}}" level="{{level + 1}}" children="{{node.children}}" expand-all="{{expandAll}}" multi="{{multi}}" edit="{=edit=}" isUpdating="{{node.isUpdating}}" parents="{{newParents}}" tree-value="{{treeValue}}" active-value="{{activeValue}}" /> </ul>`; const template = `<template> <div s-if="isRoot" class="{{mainClass}}" data-value="{{value}}" data-level="{{level}}">${commonTemplate}</div> <li s-else class="{{mainClass}}" data-value="{{value}}" data-level="{{level}}">${commonTemplate}</li> </template>`; /* eslint-enable */ export default defineComponent({ template, components: { 'ui-tree-node': 'self', 'ui-checkbox': CheckBox, 'ui-textbox': TextBox }, computed: { isRoot() { return this.data.get('level') === 0; }, currentNode() { const node = { value: this.data.get('value'), text: this.data.get('text'), level: this.data.get('level'), parents: this.data.get('parents') }; if (this.data.get('hasChildren')) { node.children = this.data.get('children'); } return node; }, hasChildren() { const children = this.data.get('children'); return children && children.length > 0; }, expandedFlag() { return this.data.get('isExpanded') ? 'expanded' : 'collapsed'; }, mainClass() { const level = this.data.get('level'); const expandedStr = this.data.get('expandedFlag'); const klass = [cx('node'), cx(`node-level-${level}`)]; if (this.data.get('isRoot')) { // 根节点的样式 klass.push(cx('root')); klass.push(cx(`root-${expandedStr}`)); } // 如果没有儿子 if (!this.data.get('hasChildren')) { klass.push(cx('root-empty')); if (this.data.get('activeValue') === this.data.get('value')) { klass.push(cx('node-active')); } } else { klass.push(cx(`node-${expandedStr}`)); } return klass; }, indicatorClass() { const level = this.data.get('level'); const expandedStr = this.data.get('expandedFlag'); const klass = [cx('node-indicator'), cx(`node-indicator-level-${level}`)]; // 如果没有儿子 if (!this.data.get('hasChildren')) { klass.push(cx('node-indicator-empty')); } else { klass.push(cx(`node-indicator-${expandedStr}`)); } return klass; }, isSelected() { // checkbox是否被选中 return this.data.get('multi') && _.includes(this.data.get('treeValue'), this.data.get('value')); }, newParents() { let newParents = _.clone(this.data.get('parents')); newParents.push(this.data.get('value')); return newParents; } }, initData() { return { value: '', level: 0, // level为0时,代表根节点 text: '', children: [], // 儿子节点 isExpanded: false, // 是否打开,当children.length > 0时有意义 parents: [], // 完整的祖先路径 isUpdating: false // 是否在更新中 }; }, inited() { // 默认打开机制,根节点默认第一次都是打开的 if (this.data.get('expandAll') || this.data.get('isRoot')) { this.data.set('isExpanded', true); } }, dataTypes: { /** * value */ value: DataTypes.string, /** * 层级:0代表根节点,以此类推 */ level: DataTypes.number, /** * 名字 */ text: DataTypes.string, /** * 儿子节点们,当children.length === 0,代表是叶子节点 */ children: DataTypes.array, /** * 是否打开子节点 */ isExpanded: DataTypes.bool, /** * 所有祖先 */ parents: DataTypes.array, isUpdating: DataTypes.bool }, // 打开关闭操作 onNodeClick(evt) { const node = this.data.get('currentNode'); // 如果没有儿子则只触发click事件 if (!this.data.get('hasChildren')) { this.dispatch('click', node); return; } const isExpanded = this.data.get('isExpanded'); // 设置反向状态 this.data.set('isExpanded', !isExpanded); if (isExpanded) { this.dispatch('collapse', node); } else { this.dispatch('expand', node); } }, onCheckboxClick(evt) { // 阻止事件冒泡 evt.stopPropagation(); }, onCheckboxChange(evt) { const node = this.data.get('currentNode'); if (evt.value) { this.dispatch('select', node); } else { this.dispatch('unselect', node); } }, onCreate(evt) { evt.stopPropagation(); // 默认展开当前节点 this.data.set('isExpanded', true); this.data.set('edit', false); const parentNode = this.data.get('currentNode'); this.dispatch('creating', parentNode); }, onDelete(evt) { evt.stopPropagation(); const node = this.data.get('currentNode'); const text = this.data.get('text'); const title = '提示'; const message = `是否确认删除节点“${text}“` + (this.data.get('hasChildren') ? '及其所有的子孙节点' : '') + '?'; confirm({title, message, width: 600}) .then(() => this.dispatch('delete', node)); }, onUpdate(evt) { evt.stopPropagation(); this.data.set('isUpdating', true); this.data.set('edit', false); }, onTextboxClick(evt) { evt.stopPropagation(); }, onTextboxEnter(evt) { // 确认更新 const text = evt.target.value; if (text === '') { return; } this.data.set('text', text); const node = this.data.get('currentNode'); this.dispatch('confirm', node); this.data.set('isUpdating', false); this.data.set('edit', true); }, onTextboxBlur(evt) { const newText = evt.target.value; const oldText = this.data.get('text'); this.data.set('isUpdating', false); this.data.set('edit', true); if (newText && newText !== oldText) { // 确认编辑 this.data.set('text', newText); const node = this.data.get('currentNode'); this.dispatch('confirm', node); } else { // 取消编辑 const node = this.data.get('currentNode'); this.dispatch('cancelEdit', node); } } });
export default [ { user: { id: '1', imageUri: 'https://images.unsplash.com/photo-1520271348391-049dd132bb7c?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=934&q=80', name: 'Lukas', }, stories: [ { imageUri: 'https://images.unsplash.com/photo-1603258849062-0f9f0d97cb47?ixid=MXwxMjA3fDB8MHx0b3BpYy1mZWVkfDE0fHRvd0paRnNrcEdnfHxlbnwwfHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=900&q=60', postedTime: '1 h', }, { imageUri: 'https://images.unsplash.com/photo-1612520928889-e907eca88da3?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=594&q=80', postedTime: '3 h', }, ], }, { user: { id: '2', imageUri: 'https://images.unsplash.com/photo-1502980426475-b83966705988?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1yZWxhdGVkfDE4fHx8ZW58MHx8fA%3D%3D&auto=format&fit=crop&w=800&q=60', name: 'Igor', }, stories: [ { imageUri: 'https://images.unsplash.com/photo-1612226397265-7a10ea8dd13b?ixid=MXwxMjA3fDB8MHx0b3BpYy1mZWVkfDEyfHRvd0paRnNrcEdnfHxlbnwwfHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=900&q=60', postedTime: '1 h', }, { imageUri: 'https://images.unsplash.com/photo-1612217088043-3628414d8e8d?ixid=MXwxMjA3fDB8MHx0b3BpYy1mZWVkfDExfHRvd0paRnNrcEdnfHxlbnwwfHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=900&q=60', postedTime: '3 h', }, ], }, { user: { id: '3', imageUri: 'https://images.unsplash.com/photo-1518806118471-f28b20a1d79d?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80', name: 'Ron', }, stories: [ { imageUri: 'https://images.unsplash.com/photo-1602338681424-e148ee1cc7f9?ixid=MXwxMjA3fDB8MHx0b3BpYy1mZWVkfDQzfGJvOGpRS1RhRTBZfHxlbnwwfHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=900&q=60', postedTime: '30 m', }, ], }, { user: { id: '4', imageUri: 'https://images.unsplash.com/photo-1486074051793-e41332bf18fc?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1yZWxhdGVkfDh8fHxlbnwwfHx8&auto=format&fit=crop&w=800&q=60', name: 'Vanessa', }, stories: [ { imageUri: 'https://images.unsplash.com/photo-1612191160114-d5778e665595?ixid=MXwxMjA3fDB8MHx0b3BpYy1mZWVkfDIwfHRvd0paRnNrcEdnfHxlbnwwfHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=900&q=60', postedTime: '30 m', }, { imageUri: 'https://images.unsplash.com/photo-1612190377025-76afa396bc20?ixid=MXwxMjA3fDB8MHx0b3BpYy1mZWVkfDE5fHRvd0paRnNrcEdnfHxlbnwwfHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=900&q=60', postedTime: '32 m', }, ], }, { user: { id: '5', imageUri: 'https://images.unsplash.com/photo-1533461502717-83546f485d24?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1yZWxhdGVkfDN8fHxlbnwwfHx8&auto=format&fit=crop&w=800&q=60', name: 'Queen', }, stories: [ { imageUri: 'https://images.unsplash.com/photo-1603251581451-c87f8ee7febc?ixid=MXwxMjA3fDB8MHx0b3BpYy1mZWVkfDEyfGJvOGpRS1RhRTBZfHxlbnwwfHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=900&q=60', postedTime: '2 h', }, { imageUri: 'https://images.unsplash.com/photo-1602607054837-b2b61a3692c0?ixid=MXwxMjA3fDB8MHx0b3BpYy1mZWVkfDE4fGJvOGpRS1RhRTBZfHxlbnwwfHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=900&q=60', postedTime: '3 h', }, ], }, ]; // moment js
// const { FETCH_ALL_CINEMA_SYSTEM_REQUEST, FETCH_ALL_CINEMA_SYSTEM_SUCCESS, FETCH_ALL_CINEMA_SYSTEM_FAIL } = require("./types"); // const initialState = { // listCinemaSystem: [], // loading: false, // error: null, // } // const cinemaSystemReducer = (state = initialState, { type, payload }) => { // switch (type) { // case FETCH_ALL_CINEMA_SYSTEM_REQUEST: // return { ...state, loading: true }; // case FETCH_ALL_CINEMA_SYSTEM_SUCCESS: // return { ...state, loading: false, listCinemaSystem: payload }; // case FETCH_ALL_CINEMA_SYSTEM_FAIL: // return { ...state, loading: false, error: payload }; // default: // return state; // } // } // export default cinemaSystemReducer;
import PropTypes from 'prop-types'; import React from 'react'; import { css } from 'styled-components'; import { RESULT_KEY } from '@/athleteTests/Caliperometry/constants'; import injectStyles from '@/utils/injectStyles'; import { COLORS } from '@/utils/styleConstants'; const Label = ({ className, label, value }) => ( <div className={className}> <p>{label}</p> <p>{value} мм</p> </div> ); Label.propTypes = { className: PropTypes.string.isRequired, // Used by StyledComponents id: PropTypes.string.isRequired, // eslint-disable-line react/no-unused-prop-types // Used by StyledComponents gender: PropTypes.oneOf(['F', 'M']).isRequired, // eslint-disable-line react/no-unused-prop-types label: PropTypes.string.isRequired, value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired }; Label.defaultProps = {}; Label.displayName = 'CaliperometryChartComponentLabelElement'; const styles = css` position: absolute; & > p { margin: 0; color: ${COLORS.BUTTON.PRIMARY.ORDINARY}; font: 700 14px/16px var(--dff); text-align: center; &:nth-child(2) { margin-top: 8px; font-size: 20px; line-height: 23px; } } ${props => props.id === RESULT_KEY.CHEST && css` top: 4px; left: 4px; width: 120px; ${props.gender === 'F' && css` display: none; `} `} ${props => props.id === RESULT_KEY.BICEPS && css` top: 82px; left: 28px; width: 58px; `} ${props => props.id === RESULT_KEY.FOREARM && css` top: 174px; left: 16.5px; width: 80px; `} ${props => props.id === RESULT_KEY.WRIST && css` top: 237px; left: 27.5px; width: 58px; `} ${props => props.id === RESULT_KEY.ILIAC && css` top: 299px; left: 7px; width: 100px; `} ${props => props.id === RESULT_KEY.SHIN && css` top: 427px; left: 22.5px; width: 68px; & > p { color: ${COLORS.TEXT.PRIMARY}; } `} ${props => props.id === RESULT_KEY.UNDER_SHOULDER_BLADE && css` top: ${props.gender === 'M' ? 73.5 : 55}px; left: 401px; width: 99px; & > p { color: ${COLORS.TEXT.PRIMARY}; } `} ${props => props.id === RESULT_KEY.TRICEPS && css` top: 136px; left: 415px; width: 71px; & > p { color: ${COLORS.TEXT.PRIMARY}; } `} ${props => props.id === RESULT_KEY.BELLY && css` top: 194px; left: 415px; width: 72px; `} ${props => props.id === RESULT_KEY.HIP_UP && css` top: 261px; left: 413px; width: 74px; `} ${props => props.id === RESULT_KEY.HIP_MID && css` top: 365px; left: 397px; width: 108px; `} `; export default injectStyles(Label, styles);
import React from "react"; import Layout from "../components/layout"; import SEO from "../components/seo"; import Intro from "../components/Intro/intro"; import HeroInquire from "../components/Hero/heroInquire"; import Form from "../components/Form/form"; import EBMIcon from "../images/ebm-icon.inline.svg"; import "../components/Hero/hero.scss"; const Inquire = () => ( <Layout> <SEO title="Inquire | Events by Mosaic" /> <div className="hero-block"> <div className="hero-head"> <div className="hero-icon"> <EBMIcon /> </div> <h3>INQUIRE</h3> </div> <div className="hero-body"> <h1 className="hero-headline">Contact us</h1> <div className="hero-img-tint" /> <HeroInquire /> </div> </div> <Intro text="We’re here to help and quick to respond! Give us a ping and we’ll hit the ground running to make sure you’re on your way to your big day." /> <Form /> </Layout> ) export default Inquire
// Colors var WHITE = 'rgb(255, 255, 255)'; var BLACK = 'rgb(0,0,0)'; var NAVYBLUE = 'rgb(60, 60, 100)'; var GREEN = 'rgb(0, 255, 0)'; var BLUE = 'rgb(0, 0, 255)'; var GRAY = 'rgb(230, 230, 230)'; var BGCOLOR = WHITE; var TEXTCOLOR = BLACK; // Dimensions var WINDOWWIDTH = 1000; var WINDOWHEIGHT = 800; var letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; Graphics = function(){ console.log("Initializing graphics") this.canvas = { 'current': document.getElementById('canvas_current'), 'flip': document.getElementById('canvas_flip'), 'tiles': document.getElementById('canvas_tiles'), 'your': document.getElementById('canvas_your'), 'self_words': document.getElementById('canvas_self_words'), 'opp': document.getElementById('canvas_opp'), 'opp_words': document.getElementById('canvas_opp_words'), 'guess': document.getElementById('canvas_guess'), 'status': document.getElementById('canvas_status') } this.ctx = { 'current': this.canvas.current.getContext('2d'), 'flip': this.canvas.flip.getContext('2d'), 'tiles': this.canvas.tiles.getContext('2d'), 'your': this.canvas.your.getContext('2d'), 'self_words': this.canvas.self_words.getContext('2d'), 'opp': this.canvas.opp.getContext('2d'), 'opp_words': this.canvas.opp_words.getContext('2d'), 'guess': this.canvas.guess.getContext('2d'), 'status': this.canvas.status.getContext('2d') } this.ctx.tiles.translate(0.5, 0.5); this.ctx.tiles.ImageSmoothingEnabled = false; // CANVAS LOCATION this.canvas.current.style.top = '20px'; this.canvas.current.style.left = '10px'; this.canvas.flip.style.top = '55px'; this.canvas.flip.style.left = '12px'; this.canvas.tiles.style.top = '25px'; this.canvas.tiles.style.left = '150px'; this.canvas.your.style.top = '100px'; this.canvas.your.style.left = '10px'; this.canvas.self_words.style.top = '150px'; this.canvas.self_words.style.left = '10px'; this.canvas.opp.style.top = '100px'; this.canvas.opp.style.left = '510px'; this.canvas.opp_words.style.top = '150px'; this.canvas.opp_words.style.left = '510px'; this.canvas.guess.style.top = '650px'; this.canvas.guess.style.left = '10px'; this.canvas.status.style.top = '700px'; this.canvas.status.style.left = '10px'; /* this.canvas.current.width = '140px'; this.canvas.current.height = '25px'; this.canvas.flip.width = '100px'; this.canvas.flip.height = '30px'; this.canvas.your.width = '200px'; this.canvas.your.height = '50px'; this.canvas.self_words.width = '470px'; this.canvas.self_words.height = '510px'; this.canvas.opp.width = '400px'; this.canvas.opp.height = '50px'; this.canvas.opp_words.width = '470px'; this.canvas.opp_words.height = '510px'; this.canvas.guess.width = '500px'; this.canvas.guess.height = '100px'; this.canvas.status.width = '900px'; this.canvas.status.height = '100px'; */ /* var current_style = document.getElementById("div_current").style var flip_style = document.getElementById("div_flip").style var tiles_style = document.getElementById("div_tiles").style var your_style = document.getElementById("div_your").style var self_words_style = document.getElementById("div_self_words").style var opp_style = document.getElementById("div_opp").style var opp_words_style = document.getElementById("div_opp_words").style var guess_style = document.getElementById("div_guess").style var status_style = document.getElementById("div_status").style this.canvas_xy = { 'current': {x: current_style.x, y: current_style.y}, 'flip': {x: flip_style.x, y: flip_style.y}, 'tiles': {x: tiles_style.x, y: tiles_style.y}, 'your': {x: your_style.x, y: your_style.y}, 'self_words': {x: self_words_style.x, y: self_words_style.y}, 'opp': {x: opp_style.x, y: opp_style.y}, 'opp_words': {x: opp_words_style.x, y: opp_words_style.y}, 'guess': {x: guess_style.x, y: guess_style.y}, 'status': {x: status_style.x, y: status_style.y}, } this.canvas_dims = { 'current': {x: current_style.x, y: current_style.y}, 'flip': {x: flip_style.x, y: flip_style.y}, 'tiles': {x: tiles_style.x, y: tiles_style.y}, 'your': {x: your_style.x, y: your_style.y}, 'self_words': {x: self_words_style.x, y: self_words_style.y}, 'opp': {x: opp_style.x, y: opp_style.y}, 'opp_words': {x: opp_words_style.x, y: opp_words_style.y}, 'guess': {x: guess_style.x, y: guess_style.y}, 'status': {x: status_style.x, y: status_style.y}, } */ this.first_time = true; this.gap_factor = 1.5; this.default_font = 'px Arial Black'; this.default_color = BLACK; this.gap_factor = 1.5; this.default_size_tiles = 32; this.default_tiles_per_row = (this.canvas.tiles.width / (this.default_size_tiles * this.gap_factor)); this.default_size_words = this.default_size_tiles; this.default_words_per_col = (this.canvas.self_words.height / (this.default_size_words * this.gap_factor)); this. tile_dict = {}; for (let i = 0; i < letters.length; i++){ let letter = letters[i]; this.tile_dict[letter] = document.getElementById(letter); } this.tile_orig_width = this.tile_dict['A'].naturalWidth; this.tile_orig_height = this.tile_dict['A'].naturalHeight; // 'Current' before tiles this.current = { 'font': this.default_font, 'size': 24, 'color': this.default_color, 'x': 10, 'y': 20 } // Flip status this.flip = { 'font': this.default_font, 'size': 14, 'color': this.default_color, 'x': 20, 'y': 60 } // Tiles this.tiles = { 'font': this.default_font, 'size': 32, 'color': this.default_color, 'x_0': 150, 'y_0': 38, 'x_gap': 30, 'y_gap': 50 } // 'Your Words' (the text above your words) this.your = { 'font': this.default_font, 'size': 24, 'color': this.default_color, 'x': 10, 'y': 100, 'y_gap': 70 } // Your words (the actual words themselves) this.self_words = { 'font': this.default_font, 'size': 48, 'color': this.default_color, 'x': 30, 'y': this.your.y + this.your.y_gap, 'x_gap': 150, 'y_gap': 50 } // 'Opponent's Words' (the text above your words) this.opp = { 'font': this.default_font, 'size': 24, 'color': this.default_color, 'x': WINDOWWIDTH / 2 + 10, 'y': 100, 'y_gap': 70 } // Opponent's words (the words themselves) this.opp_words = { 'font': this.default_font, 'size': 48, 'color': this.default_color, 'x': WINDOWWIDTH / 2 + 30, 'y': this.opp.y + this.opp.y_gap, 'x_gap': 150, 'y_gap': 50 } // Guess this.guess = { 'font': this.default_font, 'size': 32, 'color': this.default_color, 'x': 10, 'y': WINDOWHEIGHT - 140 } // Status this.status = { 'font': this.default_font, 'size': 20, 'color': this.default_color, 'x': 10, 'y': WINDOWHEIGHT - 100 } this.color_taken = BLUE; /* this.loadImages = function(letters){ var result = {}; var tile_dict = {}; for (let i = 0; i < letters.length; i++){ let letter = letters[i]; tile_dict[letter] = document.getElementById(letter); } return tile_dict; } */ scaleIt = function(source, scaleFactor){ var c = document.createElement('canvas'); var ctx_temp = c.getContext('2d'); var w = source.width * scaleFactor; var h = source.height * scaleFactor; c.width = w; c.height = h; ctx_temp.drawImage(source, 0, 0, w, h); return(c); } this.draw_tile = function(ctx, img, x, y, size){ original_width = img.width; scale_factor = size / img.width; root_scale = Math.sqrt(scale_factor); // scale the 1000x669 image in half to 500x334 onto a temp canvas var c1 = scaleIt(img, root_scale); final_width = c1.width * root_scale; final_height = c1.height * root_scale; // scale the 500x335 canvas in half to 250x167 onto the main canvas ctx.drawImage(c1, x, y, final_width, final_height); } this.draw_word = function(ctx, word, x, y, size){ console.log(`Drawing word ${word}`); for (let i = 0; i < word.length; i++){ // ctx.drawImage(this.tile_dict[word.charAt(i)], x, y, size, size); this.draw_tile(ctx, this.tile_dict[word.charAt(i)], x, y, size); x += size; } } this.draw_word_list = function(ctx, words_list){ if (words_list.length <= this.default_words_per_col * 2){ var size_words = this.default_size_words; var words_per_col = Math.floor(this.canvas.self_words.height / (size_words * this.gap_factor)); } else{ var size_words = this.default_size_words/ 1.5; var words_per_col = Math.floor(this.canvas.self_words.height / (size_words * this.gap_factor)); } var x_gap = size_words; var y_gap = size_words * 1.5; var x = 0; var y = 0; var second_column = false; var word_end_x = []; for (let i = 0; i < words_list.length; i++){ if (second_column){ this.draw_word(ctx, words_list[i], word_end_x[i - words_per_col], y, size_words); } else{ this.draw_word(ctx, words_list[i], 0, y, size_words); } if (i % words_per_col == words_per_col - 1){ second_column = true; y = 0; } else{ y += y_gap } word_end_x.push(words_list[i].length * size_words + x_gap); } } this.update_display = function(game, player, graphics_to_update, guess, status){ var gap_btwn_cols = 10; if (graphics_to_update.includes('self_words')){ if (player == 1){ var self_words_list = game.player1words_list; var opp_words_list = game.player2words_list; } else{ var self_words_list = game.player2words_list; var opp_words_list = game.player1words_list; } } if (graphics_to_update.includes('flip')){ this.ctx.flip.clearRect(0, 0, this.canvas.flip.width, this.canvas.flip.height); this.ctx.flip.font = this.flip.size.toString() + this.default_font; this.ctx.flip.fillStyle = this.default_color; this.ctx.flip.fillText(game.flip_status, 0, this.flip.size + 5); } if (graphics_to_update.includes('guess')){ this.ctx.guess.clearRect(0, 0, this.canvas.guess.width, this.canvas.guess.height); this.ctx.guess.font = this.guess.size.toString() + this.default_font; this.ctx.guess.fillStyle = this.default_color; this.ctx.guess.fillText('Guess: ' + guess, 0, this.guess.size); } if (graphics_to_update.includes('status')){ this.ctx.status.clearRect(0, 0, this.canvas.status.width, this.canvas.status.height); this.ctx.status.font = this.status.size.toString() + this.default_font; this.ctx.status.fillStyle = this.default_color; this.ctx.status.fillText(status, 0, this.status.size); } if (graphics_to_update.includes('tiles')){ this.ctx.tiles.clearRect(0, 0, this.canvas.tiles.width, this.canvas.tiles.height); // Based on how many tiles there are, calculate tile size and tiles per row // console.log(`Current length: ${game.current.length}`); // console.log(`Tiles per row: ${this.default_tiles_per_row}`); if (game.current.length <= this.default_tiles_per_row * 2){ // console.log(`Go with default tile size: ${this.default_size_tiles}`); var size_tiles = this.default_size_tiles; var tiles_per_row = Math.floor(this.canvas.tiles.width / (size_tiles * this.gap_factor)); } else{ var size_tiles = this.default_size_tiles / 1.5; var tiles_per_row = Math.floor(this.canvas.tiles.width / (size_tiles * this.gap_factor)); } var x_gap = size_tiles * 1.2; var y_gap = size_tiles * 1.2; var x = 0; var y = 0; for (let i = 0; i < game.current.length; i++){ // console.log(`Size of tiles: ${size_tiles}`) // this.ctx.tiles.drawImage(this.tile_dict[game.current[i]], x, y, size_tiles, size_tiles); this.draw_tile(this.ctx.tiles, this.tile_dict[game.current[i]], x, y, size_tiles); if (i % tiles_per_row == tiles_per_row - 1){ x = 0; y += y_gap; } else{ x += x_gap } } } if (graphics_to_update.includes('self_words')){ console.log(`Updating self words: ${self_words_list}`); this.ctx.self_words.clearRect(0, 0, this.canvas.self_words.width, this.canvas.self_words.height); this.draw_word_list(this.ctx.self_words, self_words_list); } if (graphics_to_update.includes('opp_words')){ console.log(`Updating opp words: ${opp_words_list}`); this.ctx.opp_words.clearRect(0, 0, this.canvas.opp_words.width, this.canvas.opp_words.height); this.draw_word_list(this.ctx.opp_words, opp_words_list); } } this.display_init = function(){ // Run only when you start the game, displays the fixed things that won't change // Display "Current:" this.ctx.current.font = this.current.size.toString() + this.default_font; this.ctx.current.fillStyle = this.default_color; this.ctx.current.fillText('Current:', 0, this.current.size); // Display "Your Words:" this.ctx.your.font = this.your.size.toString() + this.default_font; this.ctx.your.fillStyle = this.default_color; this.ctx.your.fillText('Your Words:', 0, this.your.size); // Display "Opponent's Words:" this.ctx.opp.font = this.opp.size.toString() + this.default_font; this.ctx.opp.fillStyle = this.default_color; this.ctx.opp.fillText('Opponent\'s Words:', 0, this.opp.size); // Guess this.ctx.guess.font = this.guess.size.toString() + this.default_font; this.ctx.guess.fillStyle = this.default_color; this.ctx.guess.fillText('Guess: ' + guess, 0, this.guess.size); } }
const _ = require('lodash'); const express = require('express'); const bodyParser = require('body-parser'); var path = require('path'); const fs = require('fs'); // Line ChatBot const LineBot = require('line-bot-sdk'); const client = LineBot.client({ channelID: '1478428116', channelSecret: '8a5f63c7ba9a908b161f9d35506c1ed2', channelMID: 'u8c63910602e679d636cd54aff4fd1b0d' }); //Server configurations var app = express(); app.set('port', 3000); app.set('host','52.45.30.158'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false, limit: 2 * 1024 * 1024 })); app.use(bodyParser.json({ limit: 2 * 1024 * 1024 })); app.get('/',function(req, res){ res.send('hello'); console.log(req); }); app.get('/hello',function(req, res){ res.send('xin chào Việt Nam'); }); app.post('/lineCallback', function (req, res) { console.log(req.body.result); var receives = client.createReceivesFromJSON(req.body); _.each(receives, function(receive){ if(receive.isMessage()){ if(receive.isText()){ console.log(receive.getText()); client.sendText(receive.getFromMid(), 'Hi! I\'m BOT'); }else if(receive.isImage()){ client.sendText(receive.getFromMid(), 'Thanks for the image!'); var contentId = receive.getContentId(); console.log('contentId: ' + contentId); var lineControl = require('./controllers/controller_line.js'); lineControl.getMessageContent(contentId, function(response, error) { if (response != null) { //Get photo successful var filename = contentId; var pathControl = require('./controllers/controller_path.js'); var ocrControl = require('./controllers/controller_ocr.js'); // Using OCR of Google Cloud Vision var inputFilePath = pathControl.getImagePath(filename); var originalOcrPath = 'ocr_results/'; // console.log(inputFilePath); var outputFilePath = originalOcrPath + filename + '_googleVisionResult.txt'; // logger.log('info','OCR- Input:%s - Output:%s',inputFilePath, outputFilePath); ocrControl.handleImageUsingGoogleVisionOcrWithImagePath(inputFilePath, function(text, error){ if(text != null) { // logger.log('info', 'GoogleCloudVision: \n %s', text); client.sendText(receive.getFromMid(), 'Google Cloud Vision:\n' + text); // var billId = restaurantControl.getBillId(text); // logger.log('info','GoogleCloudVision-BillId: \n %s', billId); // client.sendText(receive.getFromMid(), 'Google Cloud Vision-BillId:' + billId); fs.writeFile(path.join(__dirname, outputFilePath), text, (err) => { if (err) return console.log(err); console.log('It\'s saved!'); }); } }); }else { //Send Error message client.sendText(receive.getFromMid(), 'Can\'t read text form image'); } }); }else if(receive.isVideo()){ client.sendText(receive.getFromMid(), 'Thanks for the video!'); }else if(receive.isAudio()){ client.sendText(receive.getFromMid(), 'Thanks for the audio!'); }else if(receive.isLocation()){ client.sendLocation( receive.getFromMid(), receive.getText() + receive.getAddress(), receive.getLatitude(), receive.getLongitude() ); }else if(receive.isSticker()){ // This only works if the BOT account have the same sticker too client.sendSticker( receive.getFromMid(), receive.getStkId(), receive.getStkPkgId(), receive.getStkVer() ); }else if(receive.isContact()){ client.sendText(receive.getFromMid(), 'Thanks for the contact'); }else{ console.error('found unknown message type'); } }else if(receive.isOperation()){ console.log('found operation'); }else { console.error('invalid receive type'); } }); res.send('ok'); }); app.get('/getuserid',function(req,res){ var AWS = require('aws-sdk'); AWS.config.update({ region: "us-east-1", endpoint: "https://dynamodb.us-east-1.amazonaws.com" }); var docClient = new AWS.DynamoDB.DocumentClient(); var uid = req.query.userid; var tableName = "membershipcard-mobilehub-105694150-Members"; var params = { TableName: tableName, KeyConditionExpression: "userId = :uid", ExpressionAttributeValues:{ ":uid" : uid } }; docClient.query(params, function(err, data) { if (err) res.send(err); else res.send(data); }); }); app.listen(app.get('port'), function() { console.log('Listening on host:' + app.get('host') + ':' + app.get('port')); });
var inquirer = require("inquirer"); var mysql = require("mysql"); require("console.table"); var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : 'Lin91650', database : 'bamazon_db', }); // Initiate MySQL Connection. connection.connect(function(err) { if (err) { console.error("error connecting: " + err.stack); return; } // console.log("connected as id " + connection.threadId); }); function supervisorView(){ console.log("1) View Product Sales by Department") console.log("2) Create New Department") inquirer.prompt([ {type: "input", name: "supervisorChoice", message: "What would you like to do (select number from list above)?"} ]).then(function(data){ if(data.supervisorChoice == 1){ connection.query('SELECT d.id, d.department_name, d.over_head_costs, SUM(s.quantity_purchased * p.price) AS Product_Sales, SUM(d.over_head_costs - (s.quantity_purchased * p.price)) AS Total_Profit FROM departments d left join products p on d.id = p.department_id left join sales s on s.product_id = p.id GROUP BY d.id;', function (error, results){ // console.table(results) console.table(results) // for(var i=0; i < results.length; i++){ // console.table([ // { // DepartmentId : results[i].id, // Department_Name : results[i].department_name, // Over_Head_Costs : results[i].over_head_costs, // Product_Sales : "$" + results[i].Product_Sales, // Total_Profit : "$" + results[i].Total_Profit // } // ]); // } supervisorView() }) }else if(data.supervisorChoice == 2){ inquirer.prompt([ {type: "input", name: "department_name", message: "What is the name of the department you would like to add?"}, {type: "input", name: "over_head_cost", message: "How much are the over_head_costs?"} ]).then(function(data){ var name = data.department_name var overHead = data.over_head_cost; connection.query('INSERT INTO departments SET ?', { department_Name : name, over_head_costs : overHead }, function (error, results) { console.log('Department Inserted!') }) }) }else{ console.log("Invalid Selection") supervisorView(); } }) }supervisorView()
export const mkTime = (row, column, cellValue) => { let time = new Date(cellValue) let month = time.getMonth() + 1 let date = time.getDate() let hour = time.getHours() let minute = time.getMinutes() let second = time.getSeconds() return `${time.getFullYear()}-${month < 10 ? '0' + month : month}-${date < 10 ? '0' + date : date} ${hour < 10 ? '0' + hour : hour}:${minute < 10 ? '0' + minute : minute}:${second < 10 ? '0' + second : second}` } export const getTaskStatus = (row) => { if (!row.enable) { return '停止/已删除' } else if (row.pause) { return '暂停' } else { return '开启' } }
/** * 模拟 new 实现 * 1. 创建一个对象 * 2. 该对象原型链访问到构造函数的原型 * 3. 执行构造函数并改变 this 为该对象 * 4. 若构造函数返回一个对象则返回,否则返回 this */ function newFn() { const Constructor = [].shift.call(arguments); const obj = Object.create(Constructor.prototype); const result = Constructor.apply(obj, arguments); if (!result) return obj; if (typeof result === 'object' || typeof result === 'function') return result; } function Foo(name) { this.name = name; } Foo.prototype.log = function () { console.log('Foo log'); }; const f1 = newFn(Foo, 'f1');
import {join} from 'path'; import {remote, shell} from 'electron'; import React, {PropTypes} from 'react'; import {connect} from 'react-redux'; import {ApplicationMenu, MenuItem} from 'electron-menu-react'; import {updateConfig} from '../modules/config'; import {startGame} from '../modules/game'; import {reloadPlayers} from '../modules/players'; import {B, W} from '../oth'; const Menu = ({dispatch, player, players}) => <ApplicationMenu> <MenuItem label="Game"> <MenuItem click={() => {dispatch(startGame());}} label="New Game" /> <MenuItem type="separator" /> <MenuItem label="Black"> {Object.keys(players).map(name => <MenuItem click={() => {dispatch(updateConfig({path: ['player', B], value: name}));}} type="radio" label={name} checked={name === player[B]} key={name} />, )} </MenuItem> <MenuItem label="White"> {Object.keys(players).map(name => <MenuItem click={() => {dispatch(updateConfig({path: ['player', W], value: name}));}} type="radio" label={name} checked={name === player[W]} key={name} />, )} </MenuItem> <MenuItem type="separator" /> <MenuItem click={() => {shell.openItem(join(remote.app.getPath('userData'), 'oth-config'));}} label="Config..." /> <MenuItem type="separator" /> <MenuItem click={(_, win) => {win.reload();}} label="Reload" accelerator="CommandOrControl+R" /> <MenuItem click={() => {dispatch(reloadPlayers());}} label="Quick Reload" /> <MenuItem type="separator" /> <MenuItem role="quit" /> </MenuItem> </ApplicationMenu>; Menu.propTypes = { dispatch: PropTypes.func.isRequired, player: PropTypes.object.isRequired, players: PropTypes.object.isRequired, }; const MenuContainer = connect(({config: {player}, players}) => ({player, players}))(Menu); export default MenuContainer;
//---------Pseudocode----------- // create an object called theGame // Make 3 different API calls to fetch 15 questions in varying difficulties. // Store these questions in an array of objects. // const displayQuestion = function (question) { // correctAnswer = question.correct_answer; // incorrectAnswer = question.incorrect_answers; // const randomize = function (correctAnswer, incorrectAnswer) { // //do stuff to randomnize // return arrayOfRandomnizedAnswers // } // } // When user clicks start, display the first question using the displayQuestion function shown above. // if user selects the right answer that matches the correctAnswer then show that they are correct and proceed to the next question // if user selects a wrong answer, then show the correct answer and display game over and their final score. const app = {}; app.level = 0; app.questions = []; app.correctAnswers = []; app.incorrectAnswers = []; app.randomizedAnswers = []; app.correctIndex; app.userAnswer; app.isPaused = false; app.$question; app.$widgets; app.$popup; app.$body; //this function takes in a the correct answer as well as the array of wrong answers and randomly injects the correct answer on the array of wrong answers. app.randomizeAnswers = (correct, wrongAnswer) => { //app.correctIndex stores the position of the correct answer on the array allAnswers app.correctIndex = Math.floor(Math.random() * 4); //declare allAnswers initially as a copy of wrongAnswers const allAnswers = [...wrongAnswer]; //inject the correctIndex randomly on allAnswers allAnswers.splice(app.correctIndex, 0, correct); return allAnswers; } app.makeTimer = (timeLeft) => { //declare jquery selectors for better performance $countdown = $(".countdown"); $progressBar = $(".progressInner"); // app.isPaused = false; //display the initial time remaining on page $countdown.html(`<p>${timeLeft}</p>`); //define the width of the initial progress bar as 100; let progressWidth = 100; //set the width increment as a function of timeLeft. let widthIncrement = progressWidth / timeLeft / 100 //define the setInterval function let timer = setInterval(()=> { if(!app.isPaused){ //reduce timeLeft in 0.01 second increments. timeLeft = timeLeft - 1 / 100; //reduce the width of the progress bar the size of the widthIncrement progressWidth = progressWidth - widthIncrement; } //display timeLeft on the html $countdown.html(`<p>${Math.round(timeLeft)}</p>`); ///update the width of the progress bar on html $progressBar.width(`${progressWidth}%`); //when timeLeft is less than 1 second, make seconds singular ie. second if (timeLeft < 10) { $countdown.html(`<p>${Math.round(timeLeft * 10) / 10}</p>`); } //on user clicking submit, app.$question.on('click', '.submit', () => { //only if user has selected an answer (ie app.userAnswer is not undefined) reset timer. if (app.userAnswer) { clearInterval(timer); } }); //when width of the progress bar is zero, clearInterval, completely hide the outer progress bar and push the user to the game over screne. if (progressWidth <= 0) { clearInterval(timer); $('.progressOuter').hide(); app.gameOver(); } }, 10); } //this is a helper function for fifty fifty. It picks two random indices that don't contain the correct answer to remove from the array. app.indicesToRemove = () => { //declare an array of all the possible indices let arrayOfIndices = [0, 1, 2, 3]; //first remove the correctIndex from the array. arrayOfIndices.splice(app.correctIndex, 1); //then pick a random index and remove it from the array as well. let indextoRemove = Math.floor(Math.random() * 3); arrayOfIndices.splice(indextoRemove, 1); //return the remaining array. return arrayOfIndices } //this is the fifty fifty lifeline. When user clicks fifty-fifty, it removes two random answers that are not the right answer app.fiftyFifty = () => { app.$widgets.on('click', '.fiftyFifty', () => { //call the helper function to pick two indices that will be removed. let indicesToRemove = app.indicesToRemove(); //select the two indicesTo be removed and empty their containers. $(`.answer:nth-child(${indicesToRemove[0] + 1})`).empty(); $(`.answer:nth-child(${indicesToRemove[1] + 1})`).empty(); //once the lifeline has been used, add a class that greys the button out as well as turn off the event listener so the user can't use it again. $('.fiftyFifty').addClass('usedLifeline'); app.$widgets.off('click', '.fiftyFifty'); }) } //this is a helper function for both askFriend and askTheAudeince Widgets. This function controls whether the user will be directed to the right answer. //between levels 0 and 5, the hint is always correct. //between levels 5 and 10, the hint is 80% likely to be correct. //between levels 10 and 15, the hiny is 50% likely to be correct. app.hintAccuracy = () =>{ //randomizer is the decision variable that controls whether the user is directed to the right answer. let randomizer = Math.random(); if (app.level < 5) { return app.correctIndex; } else if (app.level < 10 && randomizer >= .2) { return app.correctIndex; } else if (app.level >= 10 && randomizer >= .5) { return app.correctIndex; } else { if (app.correctIndex === 0) { return app.correctIndex + 1; } else { return app.correctIndex - 1; } } } //this is the Ask a Friend widget. It creates a pop up that offers the user a hint. Hint accuracy is controlled by the app.hintAccuracy() function. app.askFriend = () => { app.$widgets.on('click', '.askFriend', () => { //prevent scrolling when the pop up appears app.$body.addClass('preventScrolling'); let hintIndex = app.hintAccuracy(); let response = app.friendsResponse(app.level); //once its decided what the hint will be, it is displayed to the user. app.$popup.html(` <div class="takeOver"> <div class="popupBox askAFriendBox"> <h4>Ask a Friend</h4> <div class="imageContainer"><img src="./assets/8BitBrent.png" alt="photo of a good looking CTO"> </div> <div class="messageContainer"> <p><span class="friend">Hi I'm Brent</span>, your friendly neighbourhood CTO. ${response} <span>${app.randomizedAnswers[hintIndex]}</span>.</p > <button class="close">Close</button> </div> </div> </div>`); app.isPaused = true; //once the user is done reading the hint, they click "close" to close the popup. Once the button is clicked, the popup is cleared and the event listener is turned off. app.$popup.on('click', '.close', () => { app.$body.removeClass('preventScrolling'); app.$popup.empty(); app.$popup.off('click', '.close') app.isPaused = false; }); //once the lifeline has been used, add a class that greys the button out as well as turn off the event listener so the user can't use it again. $('.askFriend').addClass('usedLifeline'); app.$widgets.off('click', '.askFriend'); }); } //this is a helper function for ask a friend lifeline. It that adds a layer of humanity to our AI. app.friendsResponse = (level) =>{ if(level <5){ return "Why are you wasting my valuable time?. The answer is obviously: " } if(level <10){ return "While I'm not 100% sure, I think the correct answer is:" } return "Wow, this is tough one but if I had to guess, I would pick: " } app.askTheAudience = () => { //a helper function to rapidly generate percentages as audience feedback. const getRandomArbitrary = (min, max) => { return Math.floor(Math.random() * (max - min) + min); } app.$widgets.on('click', '.askTheAudience', () => { //prevent scrolling when the pop up appears app.$body.addClass('preventScrolling'); //generate 4 random percentages to be displayed to the user. First percent is limited to 75% so that numbers are more evenly distributed. let percent1 = getRandomArbitrary(0, 76); let percent2 = getRandomArbitrary(0, 101 - percent1); let percent3 = getRandomArbitrary(0, 101 - percent1 - percent2); let percent4 = 100 - percent1 - percent2 - percent3; //push the percentages to an array called audiencePoll to later on display in the pop up. let audiencePoll = [percent1, percent2, percent3, percent4]; //find what the highest percentage is on the array. let maxPercent = Math.max(...audiencePoll); //find what index is the maxPercent indexOfMax = audiencePoll.indexOf(maxPercent); //remove the highest percentage out of the audiencePoll array, to inject it back based on the app.hintAccuracy() outcome. audiencePoll.splice(indexOfMax, 1); //based on app.hintAccuracy() outcome, hintIndex contains an index that will contain the highest percentage. let hintIndex = app.hintAccuracy(); //maxPercent gets injected back into the hintIndex position. audiencePoll.splice(hintIndex, 0, maxPercent); //generate the popup html. app.$popup.html(` <div class="takeOver"> <div class="popupBox audienceChart"> <h4>Ask the Audience</h4> <div class="chartContainer"> <div class="bar0 bar"><p>A</p></div> <div class="bar1 bar"><p>B</p></div> <div class="bar2 bar"><p>C</p></div> <div class="bar3 bar"><p>D</p></div> </div> <p>The audience thinks <span class>${app.randomizedAnswers[hintIndex]}</span> is the right answer</p> <button class="close">Close</button> </div> </div>`); app.isPaused = true; //create a graph with 4 bars based on the numbers specified by audiencePoll array. for (i = 0; i < audiencePoll.length; i++) { // dividing over maxPercent ensures that largest number always has a width of 100%. $(`.bar${i}`).width(`${audiencePoll[i] / maxPercent * 100}%`); $(`.bar${i}>p`).html(`${audiencePoll[i]}%`); } //color the audience favourite orange. $(`.bar${hintIndex}`).css("background", "#f39c12"); //once the user is done reading the hint, they click "close" to close the popup. Once the button is clicked, the popup is cleared and the event listener is turned off. app.$popup.on('click', '.close', () => { app.$body.removeClass('preventScrolling'); app.$popup.empty(); app.$popup.off('click', '.close') app.isPaused = false; }); //once the lifeline has been used, add a class that greys the button out as well as turn off the event listener so the user can't use it again. $('.askTheAudience').addClass('usedLifeline'); app.$widgets.off('click', '.askTheAudience'); }); } //when called, loads the game over page. app.gameOver = () => { app.$widgets.empty(); app.$question.html(`<h2>Game Over!</h2> <p>Some people just aren't cut out to be developers.</p> <button class="reset">Play Again</button>`) //if .reset is clicked, reset the game app.resetGame(); } //when called, loads the you won page. app.youWon = () => { app.$widgets.empty(); app.$question.html(`<h2>Congratulations!</h2><p>Looks like you are an awesome developer!</p><button class="reset">Play Again</button>`) //if .reset is clicked, reset the game app.resetGame(); } //when called activates the event listener to reset the game. app.resetGame = () => { app.$question.on('click', '.reset', () => { //remove all the styling that gives indication of the current question. $(`aside li:nth-child(${app.level + 1})`).removeClass('currentQuestion'); //reset all game variables. app.level = 0; app.questions = []; app.correctAnswers = []; app.incorrectAnswers = []; app.randomizedAnswers = []; app.correctIndex = 0; //take the user back to the start screen and make a new API call. app.loadStartScreen(); app.getData(); //remove usedLifeLine class from all lifelines so they longer appear greyed out. $('.usedLifeline').removeClass('usedLifeline'); //remove class that hides the logo to display on the start screen. $('h1').removeClass("hiddenOnMobile"); // ensure that widgets bar is shown app.$widgets.show(); //turn off the event listener for .reset button. app.$question.off('click', '.reset'); }) } //when called loads the Next Question with all the wid app.loadNextQuestion = (question, correct, wrong) => { //first randomly inject the correct answer into the array of randomizedAnswers. app.randomizedAnswers = app.randomizeAnswers(correct[app.level], wrong[app.level]); //generate a timer to be displayed to the user. app.makeTimer(60); //generate the frame that displays the question along with the answers to the user. let frame = `<h2>${question[app.level]}</h2> <form action=""> <div class="answers"> <div class="answer"> <input type="radio" id="answer1" name="answers" value="0"> <label for="answer1">A. <span>${app.randomizedAnswers[0]}</span></label> </div> <div class="answer"> <input type="radio" id="answer2" name="answers" value="1"> <label for="answer2">B. <span>${app.randomizedAnswers[1]}</span></label> </div> <div class="answer"> <input type="radio" id="answer3" name="answers" value="2" > <label for="answer3">C. <span>${app.randomizedAnswers[2]}</span></label> </div> <div class="answer"> <input type="radio" id="answer4" name="answers" value="3" > <label for="answer4">D. <span>${app.randomizedAnswers[3]}</span></label> </div> </div> </form> <button class="submit">Submit <i class="fas fa-long-arrow-alt-right" aria-label="Begin"></i></button>` //load the question to the user. app.$question.html(frame); //iterate the class of currentQuestion on the next list item so that next list item is highlighted. $(`aside li:nth-child(${app.level + 1})`).addClass('currentQuestion'); $(`aside li:nth-child(${app.level})`).removeClass('currentQuestion'); } // when called loads the start screen. app.loadStartScreen = () => { let frame = `<h2>Welcome</h2> <p>Welcome to Who Wants to be a Developer! Answer all 15 questions to prove your computer science skills. If you get stuck, don't forget to use your lifelines – 50/50, Ask the Audience, and Ask a Friend.</p> <button class="loading">Loading <i class="fas fa-long-arrow-alt-right"></i></button>` app.$question.html(frame); } // when called loads the widgets bar along with all the individual widget listeners. app.loadWidgets = () => { app.$widgets.html(` <div class="progressOuter"> <div class="progressInner"></div> <div class="countdown"><p>60</p></div> </div> <ul class="lifelines"> <li><button class="fiftyFifty" aria-label="fifty fifty lifeline" title="Fifty Fifty"><i class="fas fa-divide"></i></button></li> <li><button class="askTheAudience" aria-label="ask the audience lifeline" title="Ask the Audience"><i class="fas fa-chart-bar"></i></button></li> <li><button class="askFriend" aria-label="ask a friend lifeline" title="Ask a Friend"><i class="far fa-comment"></i></button></li> </ul> `) //before turning on any widget, make sure all their event listeners are off. app.$widgets.off(); //turn on all the event listeners for all the widgets. app.fiftyFifty(); app.askFriend(); app.askTheAudience(); } //this is a function that takes in a sting (the difficulty) and makes an API call to the open trivia db to get 5 questions on computer science category (category 18). app.getQuestions = (difficulty) => { return $.ajax({ url: `https://opentdb.com/api.php?amount=5&category=18&difficulty=${difficulty}&type=multiple`, method: `GET`, dataType: `json` }); } //this function makes the 3 API calls to get the questions and their associated answers from the Open Trivia DB API. //Open Trivia DB documentation can be found on the link below: //https://opentdb.com/ app.getData = async function () { //GET 5 easy questions const easyQuestions = await app.getQuestions('easy'); //GET 5 medium questions const mediumQuestions = await app.getQuestions('medium'); //GET 5 hard questions const hardQuestions = await app.getQuestions('hard'); //Once all API calls are complete, concatenate the results of each into one object called arrayOfQuestions const arrayOfQuestions = ((easyQuestions.results).concat(mediumQuestions.results)).concat(hardQuestions.results); //parse the arrayOfQuestions to seperate the questions, correct answers and incorrectAnswers from each other. arrayOfQuestions.forEach((arrayItem) => { app.questions.push(arrayItem.question); app.correctAnswers.push(arrayItem.correct_answer); app.incorrectAnswers.push(arrayItem.incorrect_answers); }) //once the API call is completed, change the color of the button by adding a class to indicate the user that the game is ready. $('.loading').html('Begin <i class="fas fa-long-arrow-alt-right"></i>').removeClass('loading').addClass('begin'); $('.begin').focus(); } app.init = () => { //get the Data from the API app.getData(); // cache selectors app.$question = $('.question'); app.$widgets = $('.widgets'); app.$popup = $('.popup'); app.$body = $('body') // preload images $('<img />').attr('src', './assets/8BitBrent.png').appendTo('body').css('display', 'none'); //when user clicks begin, do the following: app.$question.on('click', '.begin', (e) => { //prevent default behaviour of the button. e.preventDefault(); $('h1').addClass("hiddenOnMobile"); //load all the widgets app.loadWidgets(); //load the next question app.loadNextQuestion(app.questions, app.correctAnswers, app.incorrectAnswers); }) app.$question.on('click', '.submit', (e) => { //prevent default behaviour of the button. e.preventDefault(); //store the index of the value of the input the user checked when they submitted the button. app.userAnswer = $("input[name=answers]:checked").val(); //check if the user answer has a value. If its undefined, don't do anything and wait for the user to chose an answer. if (app.userAnswer) { //hide the submit button so user can't click submit again while waiting to see if they got the right answer. $('.submit').hide(); app.$widgets.hide(); //color the users choice to orange before setting a timeout. $("input[name=answers]:checked ~ label").css('background', '#f39c12'); //set a timeout of 1 second between the submit and revealing whether the user got the right answer. setTimeout(() => { //if user got the right answer and are at the last question, then first reveal that they got the question right, then move them to the you won page. if (app.correctIndex === parseInt(app.userAnswer, 10) && app.level === 14) { //color the answer green because the user was right. $("input[name=answers]:checked ~ label").css('background', '#49E68D'); //show that the user was correct for a second. setTimeout(app.youWon, 1000); } //if user is right, reveal that they got the question right, then move them to the you won page. else if (app.correctIndex === parseInt(app.userAnswer, 10)) { //color the answer green because the user was right. $("input[name=answers]:checked ~ label").css('background', '#49E68D'); //show that the user was correct for a second. setTimeout(() => { //increment the level app.level++; //take the user to the next question. app.loadNextQuestion(app.questions, app.correctAnswers, app.incorrectAnswers); app.$widgets.show(); }, 1000); } else { //color the answer red because the user was wrong. $("input[name=answers]:checked ~ label").css('background', '#e74c3c'); //set a timeout to display the user that they were wrong for a second. setTimeout(() => { //reveal the right answer to the user. $(`.answer:nth-child(${app.correctIndex + 1}) > label`).css('background', '#49E68D'); //and finally take them to the game over page after a second. setTimeout(app.gameOver, 1000) }, 1000); } }, 1000); } }) } $(function () { app.init(); });
define(['knockout', 'webApiClient', 'messageBox', 'page', 'moment', 'common'], function (ko, webApiClient, messageBox, page, moment, common) { "use strict"; var projectViewModel = ko.validatedObservable({ EntityName: "Project", Url: "/projects/", CanDeleteEntity: true, CanEditEntity: true, Name: ko.observable().extend({ maxLength: 100, required: true }), Description: ko.observable().extend({ maxLength: 400, required: false }), ApiUrl: ko.observable().extend({ maxLength: 400, required: false }), FieldPrefix: ko.observable().extend({ maxLength: 20, required: false }), SiteDataCount: ko.observable(), FieldDataCount: ko.observable(), SummaryDataCount: ko.observable(), DataLastUpdated: ko.observable(), SetModel: function (objFromServer) { var self = this; if (!objFromServer) return; self.Name(objFromServer.Name); self.Description(objFromServer.Description); self.ApiUrl(objFromServer.ApiUrl); self.FieldPrefix(objFromServer.FieldPrefix); self.SiteDataCount(objFromServer.SiteDataCount); self.FieldDataCount(objFromServer.FieldDataCount); self.SummaryDataCount(objFromServer.SummaryDataCount); if (objFromServer.DataLastUpdated) { self.DataLastUpdated(moment(objFromServer.DataLastUpdated).format(common.CLIENT_DATE_FORMAT)); } else { self.DataLastUpdated("Never"); } }, GetEntityModel: function () { var self = this; return { Name: self.Name(), Description: self.Description(), ApiUrl: self.ApiUrl(), FieldPrefix: self.FieldPrefix() }; }, TestUrl: function () { var self = this; messageBox.Hide(); var entityModel = self.GetEntityModel(); webApiClient.ajaxPut(self.Url, "testUrl", ko.toJSON(entityModel), function (model) { if (model === true) { messageBox.ShowSuccess("URL Contacted Successfully"); } else { messageBox.ShowErrors("Unable to contact URL"); } }, function (errorResponse) { messageBox.ShowErrors("Error testing URL:", errorResponse); }); }, SyncDetails: function () { var self = this; var entityId = page.RecordId; if (entityId != 'add') { messageBox.Hide(); webApiClient.ajaxPut(self.Url, entityId + "/syncDetails", null, function (model) { messageBox.ShowSuccess("Sync Details Requested Successfully"); }, function (errorResponse) { messageBox.ShowErrors("Error requesting details:", errorResponse); }); } } }); return projectViewModel; });
'use strict' let mongoose = require('mongoose'), Comment = require('../models/commentModel') exports.listAllComments = function (req, res) { Comment .find({}, function (err, comments) { if (err) { res.send(err) } else { res.json(comments) } }) } exports.createComment = function (req, res) { let new_comment = new Comment(req.body) new_comment.save(function (err, comment) { if (err) { res.send(err) } else { res.json(comment) } }) } exports.readComment = function (req, res) { Comment .findById(req.params.commentId, function (err, comment) { if (err) { res.send(err) } else if (!comment) { res.status(204).send() } else { res.json(comment) } }) } exports.updateComment = function (req, res) { Comment .findOneAndUpdate({ _id: req.params.commentId }, req.body, { new: true }, function (err, comment) { if (err) { res.send(err) } else if (!comment) { res.status(204).send() } else { res.json(comment) } }) } exports.deleteComment = function (req, res) { Comment .findOneAndRemove({ _id: req.params.commentId }, function (err, comment) { if (err) { res.send(err) } else if (!comment) { res.status(204).send() } else { res.json({ message: 'Comment successfully deleted' }) } }) }
import Vue from 'vue' import Modal from '~/components/Shared/Modal.vue' import AppLoader from '~/components/Shared/Loader' import SearchField from '~/components/Shared/SearchField' import ShowFutureFlights from '~/components/Shared/ShowFutureFlights' Vue.component('Modal', Modal) Vue.component('AppLoader', AppLoader) Vue.component('SearchField', SearchField) Vue.component('ShowFutureFlights', ShowFutureFlights)
import React, { Component } from 'react' import animate from './animations' import Context from './index.js' import routes from './routes' const desktopDelay = 1100 const mobileDelay = 1000 export default class Provider extends Component { state = { open: false, routes: routes, active: true, animating: false, setActive: () => { this.setState({ active: !this.state.active}) }, toggleDesktopNav: (open, tray, logo) => { this.setState({ open: !this.state.open}) animate.toggleDesktopNav(open, tray, logo) this.setState({ animating: !this.state.animating }) setTimeout(() => { this.setState({ animating: !this.state.animating })}, desktopDelay) }, toggleMobileNav: (open, tray) => { this.setState({ open: !this.state.open}) animate.toggleMobileNav(open, tray) this.setState({ animating: !this.state.animating }) setTimeout(() => { this.setState({ animating: !this.state.animating })}, mobileDelay) } } componentDidMount = () => console.log(this.state.open) render() { const { children } = this.props return ( <Context.Provider value={this.state}> {children} </Context.Provider> ) } }
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/home.vue' import Index from '../views/index.vue' import Product from '../views/product.vue' import Detail from '../views/detail.vue' import Cart from '../views/cart.vue' import Order from '../views/order.vue' import OrderList from '../views/orderList.vue' import OrderConfirm from '../views/orderConfirm.vue' import OrderPay from '../views/orderPay.vue' import Alipay from '../views/alipay.vue' Vue.use(VueRouter) const routes = [ { path:'/', name:'home', component:Home, redirect:'index', children:[ { path:'index', name:'index', component:Index }, { path:'product/:id', name:'product', component:Product }, { path:'detail/:id', name:'detail', component:Detail } ] }, { path:'/cart', name:'cart', component:Cart, }, { path:'/order', name:'order', component:Order, children:[ { path:'list', name:'order-list', component:OrderList }, { path:'confirm', name:'order-confirm', component:OrderConfirm }, { path:'pay', name:'order-pay', component:OrderPay }, { path:'alipay', name:'alipay', component:Alipay } ] }, ] const router = new VueRouter({ routes }) export default router
/** * 2013.10. * Heo Util ver 0.02 * Author : Heonwongeun * FaceBook : https://www.facebook.com/heo.wongeun */ (function(){ var Util = {}; var UA = require('../info/UA')(); if(typeof Heo == 'undefined')Heo = {}; Heo.Util = Util; Util._bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; /* ************************************************************ Change Image To Canvas ************************************************************ */ Heo.Util.changeToCanvas = function($img){ var w = $img.width(), h = $img.height(); var image = new Image(); image.src = $img.attr('src'); image.onload = function(){ w = image.width; h = image.height; var canvas = $('<canvas width="'+w+'" height="'+h+'"></canvas>').addClass($img[0].className).css({display:'block'}); var ctx = canvas[0].getContext("2d"); $img.before(canvas); $.extend(canvas.data(),$img.data()); if($img[0].id != 'undefined')canvas.attr('id',$img[0].id); canvas.width = w; canvas.height = h; ctx.drawImage(image, 0, 0, w, h); $img.remove(); } } /* ************************************************************ Scroll Event On / Off ************************************************************ */ var keys = {37: 1, 38: 1, 39: 1, 40: 1}; function preventDefault(e) { e = e || window.event; if (e.preventDefault) e.preventDefault(); e.returnValue = false; } function preventDefaultForScrollKeys(e) { if (keys[e.keyCode]) { preventDefault(e); return false; } } Heo.Util.DisableScroll = function(){ if (window.addEventListener) // older FF window.addEventListener('DOMMouseScroll', preventDefault, false); window.onwheel = preventDefault; // modern standard window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE window.ontouchmove = preventDefault; // mobile document.onkeydown = preventDefaultForScrollKeys; } Heo.Util.EnableScroll = function(){ if (window.removeEventListener) window.removeEventListener('DOMMouseScroll', preventDefault, false); window.onmousewheel = document.onmousewheel = null; window.onwheel = null; window.ontouchmove = null; document.onkeydown = null; } /* *************************************************************************************** set transition require : jQuery *************************************************************************************** */ Util.Css = {}; Util.Css.setTransition = function(obj,duration,ease){ var css = duration +'s '+ease; obj.css({"-webkit-transition" : css, "transition" : css}); }, Util.Css.setTransitionDuration = function(obj,duration){ var css = duration +'s'; obj.css({"-webkit-transition-duration" : css, "transition-duration" : css}); } Util.Css.setTransitionDelay = function(obj,duration){ var css = duration +'s'; obj.css({"-webkit-transition-delay" : css, "transition-delay" : css}); } Util.Css.addWillChange = function(obj,property){ obj[0].style.willChange = property; } Util.Css.removeWillChange = function(obj){ obj[0].style.willChange = 'auto'; } /* ************************************************************ favorite ease ************************************************************ */ /* ************************************************************ Math ************************************************************ */ Util.Math = {}; Util.Math.getRandom = function(max,min){ return Math.floor(Math.random() * (max - min)) + min; } Util.Math.getToRadian = function(degree){ return Math.PI * degree / 180; } Util.Math.getToDegree = function(radian){ return radian * 180 / Math.PI; } /* ************************************************************ Array ************************************************************ */ Util.Array = {}; Util.Array.shuffle = function(array){ var n = array.length, t, i; while (n) { i = Math.floor(Math.random() * n--); t = array[n]; array[n] = array[i]; array[i] = t; } return array; } Util.Array.ascendingSort = function(array,key) { array.sort(function(a, b) { // 오름차순 return a[key] - b[key]; }); } Util.Array.descendingSort = function(array,key) { array.sort(function(a, b) { // 내림차순 return b[key] - a[key]; }); } /* 이름순으로 정렬 */ // student.sort(function(a, b) { // 오름차순 // return a.name < b.name ? -1 : a.name > b.name ? 1 : 0; // // 광희, 명수, 재석, 형돈 // }); // student.sort(function(a, b) { // 내림차순 // return a.name > b.name ? -1 : a.name < b.name ? 1 : 0; // // 형돈, 재석, 명수, 광희 // }); // 나이순으로 정렬 // var sortingField = "age"; // student.sort(function(a, b) { // 오름차순 // return a[sortingField] - b[sortingField]; // // 13, 21, 25, 44 // }); // student.sort(function(a, b) { // 내림차순 // return b[sortingField] - a[sortingField]; // // 44, 25, 21, 13 // }); /* ************************************************************ Touch require : jQuery ************************************************************ */ Util.Touch = {}; Util.Touch.getTouchEvent = function(target,config){ var touchMoveOffset = 0, touchStartPos = {}, touchMovePos = {}; var isDown = false; var infos = { start:{x:0,y:0}, move:{x:0,y:0}, end:{x:0,y:0}, distance:{x:0,y:0}, distanceOffset : function(){ return {x:Math.abs(this.distance.x),y:Math.abs(this.distance.y)}; } } var _config = { moveWhileDown : true, onStart : function(e){}, onMove : function(e){}, onEnd : function(e){}, }; $.extend(_config,config); if(UA.isPC){ $(target).bind('mousedown',onStart); $(target).bind('mousemove',onMove); $(target).bind('mouseup',onEnd); }else{ $(target).bind('touchstart',onStart); $(target).bind('touchmove',onMove); $(target).bind('touchend',onEnd); } function onStart(e){ if(UA.isPC)e.preventDefault(); infos.start = getPageInfo(e); infos.move = {x:0,y:0}; infos.end = {x:0,y:0}; infos.distance = {x:0,y:0}; _config.onStart(infos); isDown = true; // if(UA.isPC){ // $(target).bind('mousemove',onMove); // }else{ // $(target).bind('touchmove',onMove); // } } function onMove(e){ e.preventDefault(); infos.move = getPageInfo(e); infos.distance.x = infos.start.x - infos.move.x; infos.distance.y = infos.start.y - infos.move.y; if(_config.moveWhileDown){ if(isDown)_config.onMove(infos); }else{ _config.onMove(infos); } } function onEnd(e){ infos.end = infos.move; if(_config.moveWhileDown){ if(isDown)_config.onEnd(infos); }else{ _config.onEnd(infos); } isDown = false; // if(UA.isPC){ // $(target).unbind('mousemove',onMove); // }else{ // $(target).unbind('touchmove',onMove); // } } } function getPageInfo(e){ var info = {x:0, y:0}; var supportTouch = 'ontouchstart' in window; if(UA.isMozilla && UA.isPC)supportTouch = false; if(supportTouch) { var touch; if (e.touches != null) { touch = e.touches[0]; } else { touch = e.originalEvent.touches[0]; } info.x = touch.clientX; info.y = touch.clientY; } else { info.x = e.clientX; info.y = e.clientY; } return info; } /* ************************************************************ get Window Size ************************************************************ */ Heo.Util.windowSize = function(){ var size = { width:0,height:0}; if (document.documentElement.clientHeight) { size.width = document.documentElement.clientWidth; size.height = document.documentElement.clientHeight; } else if (document.body.clientHeight) { size.width = document.body.clientWidth; size.height = document.body.clientHeight; } else if (stage.height) { size.width = stage.width; size.height = stage.height; } size.halfX = size.width * 0.5; size.halfY = size.height * 0.5; return size; } /* ************************************************************ change scope ************************************************************ */ Heo.Util.changeScope = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; module.exports = Heo; }).call(this); // HEO_Util = function(){ // this.init = function(){} // /* *************************************************************************************** // set transition // *************************************************************************************** */ // this.setTransition = function(obj,duration,easing){ // var css = duration +'s '+easing; // obj.css({"-webkit-transition" : css, "transition" : css}); // } // this.setTransitionDuration = function(obj,duration){ // var css = duration +'s'; // obj.css({"-webkit-transition-duration" : css, "transition-duration" : css}); // } // /* *************************************************************************************** // get touch info // *************************************************************************************** */ // this.touchHandler = function(target,callBack){ // var touchMoveOffset = 0, // touchStartPos = {}, // touchMovePos = {}; // // console.log(target); // $(target).bind("touchstart", function(e){ // touchMoveOffset = 0; // touchStartPos = getTouchInfo(e); // touchMovePos = getTouchInfo(e); // }); // $(target).bind("touchmove", function(e){ // e.preventDefault(); // touchMovePos = getTouchInfo(e);w // var movedY = touchStartPos.y - touchMovePos.y, // movedX = touchStartPos.x - touchMovePos.x; // touchMoveOffset = Math.abs(movedX) < Math.abs(movedY)?0:movedX; // }); // $(target).bind("touchend", function(e){ // callBack(touchMoveOffset); // }); // } // *************************************************************************************** // get window size // *************************************************************************************** // this.windowSize = function(){ // var size = { width:0,height:0}; // if (document.documentElement.clientHeight) { // size.width = document.documentElement.clientWidth; // size.height = document.documentElement.clientHeight; // } else if (document.body.clientHeight) { // size.width = document.body.clientWidth; // size.height = document.body.clientHeight; // } else if (stage.height) { // size.width = stage.width; // size.height = stage.height; // } // size.halfX = size.width * 0.5; // size.halfY = size.height * 0.5; // return size; // } // this.init(); // /* ************************************************************ // ************************************************************ */ // this.Renderer = function{ // renderID : null, // list : {}, // addList : function(name,fn){ // this.list[name] = {update:fn,freeze:false}; // return this.list[name]; // }, // start : function(){ // var _this = this; // this.render = _bind(this.render,this) // this.renderID = requestAnimationFrame(this.render); // }, // stop : function(){}, // render : function(){ // for(var o in this.list){ // if(!this.list[o].freeze)this.list[o].update(); // } // this.renderID = requestAnimationFrame(this.render); // } // } // /* ************************************************************ // ************************************************************ */ // } // HEO_Util.prototype.constructor = HEO_Util; // this.HEO_Util = HEO_Util;
export * from '../dist/vl-wizard-all.src.js';
[ { "creatDate": "2018-09-10", "id": "11161", "image": "/d/file/meinvzhubo/kr/2018-09-10/f750b172b33aeabd71b070407da99145.jpg", "longTime": "00:38:23", "title": "韩国美乳极品美女主播裸舞直播 是不是眼睛都冒绿光了", "video": "https://play.cdmbo.com/20180909/Kekvnwqi/index.m3u8" } ]
import React from 'react' import PropTypes from 'prop-types' import MonacoEditor from 'react-monaco-editor' import { CastaneaContainer, CastaneaHeader } from '../../../core/components/castanea' import CastaneaMenu from '../../castanea.menu' import { Button, Tooltip, TreeView } from "../../../core/ui"; import { Save as SaveIcon } from '../../../core/icons' import './codes-workspace.scss' import { CODES_HOME, HOME_ROUTE } from "../../castanea.routes"; import TabsClosable, { TabsClosablePanel } from "../../../core/ui/tabs-closable"; const breadcrumb = [ { to: HOME_ROUTE.url, label: HOME_ROUTE.label, }, { to: CODES_HOME.url, label: CODES_HOME.label, }, ] function CodesWorkspace({ codesProject, selectedCodeIndex, onCodeChanged, openedFiles, onSaveFile, onActions, }) { const [tabs, setTabs] = React.useState([]) const [currentEditor, setCurrentEditor] = React.useState(null) React.useEffect(() => { const mappedFiles = openedFiles.map(mapOpenedFileToTab) setTabs(mappedFiles) }, [openedFiles]) React.useEffect(() => { window.addEventListener('resize', handleWindowResize) return () => { window.removeEventListener('resize', handleWindowResize) } }) function handleWindowResize() { if(currentEditor !== null) { currentEditor.layout() } } function editorMounted(editor, monaco) { setCurrentEditor(editor) addSaveActionToEditor(editor, monaco) addCloseTabActionToEditor(editor, monaco) } function addSaveActionToEditor(editor, monaco) { editor.addAction({ id: 'save-action', label: 'Save', keybindings: [ monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, ], contextMenuGroupId: 'navigation', contextMenuOrder: 1.5, run: (editor) => onSaveFile(editor.getValue()), }) } function addCloseTabActionToEditor(editor, monaco) { editor.addAction({ id: 'close-tab', label: 'Close', keybindings: [ monaco.KeyMod.WinCtrl | monaco.KeyCode.KEY_W, ], contextMenuGroupId: 'navigation', contextMenuOrder: 1.5, run: (editor) => { onActions('tabs:selected', { payload: { index: selectedCodeIndex === 0 ? 0 : selectedCodeIndex - 1 } }) onActions('tabs:closeFile', { payload: { index: selectedCodeIndex } }) }, }) } function handleEditorChange(value) { onCodeChanged(value, selectedCodeIndex) } function mapOpenedFileToTab(item, key) { return { id: item.id, label: item.module, } } return ( <CastaneaContainer className="codes-workspace-main" menu={CastaneaMenu}> <CastaneaHeader breadcrumb={breadcrumb}>{codesProject.name}</CastaneaHeader> <nav className="codes-workspace-nav"> <ul> <Tooltip text="Save file"> <li> <span> <Button className="codes-workspace-actions-btn" onClick={() => onSaveFile()}> <SaveIcon size={18} /> </Button> </span> </li> </Tooltip> </ul> </nav> <div className="codes-workspace-container"> <div className="codes-workspace-files"> <TreeView data={codesProject.tree} onActions={onActions} /> </div> <div className="codes-workspace-code-area"> {tabs && (<TabsClosable className="codes-workspace-tabs" selectedIndex={selectedCodeIndex} onItemSelected={(index) => onActions('tabs:selected', { payload: { index } })} onItemClose={(index) => onActions('tabs:closeFile', { payload: { index } })} tabs={tabs} /> )} {openedFiles && ( openedFiles.map( (file, index) => ( <TabsClosablePanel className="codes-workspace-panel codes-workspace-code-area-content" key={index} index={selectedCodeIndex} value={index} > <MonacoEditor value={String(file.content)} language={file.language} editorDidMount={editorMounted} onChange={handleEditorChange} options={{ minimap: { enabled: false }, wordWrap: 'on', automaticLayout: true, scrollBeyondLastLine: false, }} width="100%" height="100%" /> </TabsClosablePanel> ) ) )} </div> </div> </CastaneaContainer> ) } CodesWorkspace.propTypes = { onActions: PropTypes.func, onCodeChanged: PropTypes.func, openedFiles: PropTypes.arrayOf(PropTypes.object), codesProjects: PropTypes.shape({ name: PropTypes.string, description: PropTypes.string, files: PropTypes.arrayOf(PropTypes.object), }).isRequired, } CodesWorkspace.defaultProps = { openedFiles: [], codesProjects: {}, onActions: () => {}, onCodeChanged: () => {}, } export default CodesWorkspace
var BITLY_ACCESS_TOKEN = process.env.BITLY_ACCESS_TOKEN; var STORAGE_ACCOUNT_KEY = process.env.STORAGE_ACCOUNT_KEY; var STORAGE_ACCOUNT_NAME = process.env.STORAGE_ACCOUNT_NAME; var PRIVATE_PREVIEW_PASSWORD = process.env.PRIVATE_PREVIEW_PASSWORD; var FACEBOOK_PREVIEW_PASSWORD = process.env.FACEBOOK_PREVIEW_PASSWORD; var express = require('express'); var router = express.Router(); var randomString = require('random-string'); var fs = require('fs'); var azure = require('azure-storage'); var async = require('async'); var Bitly = require('bitly'); var bitly = new Bitly(BITLY_ACCESS_TOKEN); var imageCacheQueue= []; /* GET home page. */ router.get('/', function(req, res, next) { if (req.mobile == true) { res.render('index', { mobile: "true" }); } else { res.render('index', { mobile: "false" }); } }); /* private preview endpoints router.post('/enter', function(req, res, next) { if (req.mobile == true) { res.render('index', { mobile: "true" }); } else { res.render('index', { mobile: "false" }); } }); */ router.get('/faq', function(req, res, next) { if (req.mobile == true) { res.render('faq', { mobile: "true" }); } else { res.render('faq', { mobile: "false" }); } }); router.get('/privacy', function(req, res, next) { if (req.mobile == true) { res.render('privacy', { mobile: "true" }); } else { res.render('privacy', { mobile: "false" }); } }); router.get('/shorten/:url', function(req, res) { console.log("TWITTER START: "); bitly.shorten("http://"+req.params.url) // considered invalid uri without 'http' .then(function(response) { var shortUrl = response.data.url; res.json({ shortUrl: shortUrl, response: response, error: null }); }, function(error) { res.json({ erorr: error }); //throw error; }); }) router.post('/upload', function(req, res) { var image = req.body.img.replace(/^data:image\/png;base64,/, ""); var fileName= randomString({ length: 20, numeric: true, letters: true, special: false }); imageCacheQueue.push(fileName); if (imageCacheQueue.length > 10) { var fileToDelete = imageCacheQueue.shift(); fs.unlink("imageCache/"+fileToDelete+".png"); } fs.writeFile("imageCache/"+ fileName +".png", image, 'base64', function(err) { if (err) { console.log(err); return; } var accountName = STORAGE_ACCOUNT_NAME; var accountKey = STORAGE_ACCOUNT_KEY; var host = accountName + '.blob.core.windows.net'; var container = 'meatface'; var blobSvc = azure.createBlobService(accountName, accountKey, host); blobSvc.createContainerIfNotExists(container, { publicAccessLevel : 'blob' }, function(error, result, response){ if (error) { console.log(error); return; } if (!error){ //Container exists and allows //anonymous read access to blob //content and metadata within this container // createBlockBlobFromStream(containerName, fileName, stream, size, callback) blobSvc.createBlockBlobFromLocalFile( container, fileName, "imageCache/"+fileName+".png", function(error, result, response){ if (error) { console.log(error); return; } if (!error){ // file uploaded // console.log(error); res.json({ url: host + "/" + container + "/" + fileName }) } }); } }); }); }); module.exports = router;
//= require jquery //= require jquery_ujs //= require turbolinks //= require jquery.turbolinks //= require_tree . // Init page modules $(document).ready(function() { application.init(); live.init(); welcome.init(); }); var application = { init: function() { this.bindUIElements(this.settings); this.getNowPlaying(); }, settings: { isStreamPlaying: false }, bindUIElements: function(settings) { var audio = $('.audio-stream')[0]; $('.header').on('click', '.player', function(event) { if (settings.streamIsPlaying) { audio.play(); } else { audio.pause(); } $('.audio-player').toggleClass('playing').toggleClass('not-playing'); settings.isStreamPlaying = !settings.isStreamPlaying; }); }, getNowPlaying: function() { $.get( "/now-playing", function(data) { $(".now-playing-song").text(data.song.title); $(".now-playing-artist").text(data.song.artist); // Poll the "now-playing" endpoint every 30 seconds // This is a terrible solution but hey here we are setTimeout(this.getNowPlaying, 30000); }.bind(this) ); } }
// A non-empty array A consisting of N integers is given. The product of triplet (P, Q, R) equates to A[P] * A[Q] * A[R] (0 ≤ P < Q < R < N). // // For example, array A such that: // // A[0] = -3 // A[1] = 1 // A[2] = 2 // A[3] = -2 // A[4] = 5 // A[5] = 6 // contains the following example triplets: // // (0, 1, 2), product is −3 * 1 * 2 = −6 // (1, 2, 4), product is 1 * 2 * 5 = 10 // (2, 4, 5), product is 2 * 5 * 6 = 60 // Your goal is to find the maximal product of any triplet. // // Write a function: // // function solution(A); // // that, given a non-empty array A, returns the value of the maximal product of any triplet. // // For example, given array A such that: // // A[0] = -3 // A[1] = 1 // A[2] = 2 // A[3] = -2 // A[4] = 5 // A[5] = 6 // the function should return 60, as the product of triplet (2, 4, 5) is maximal. // // Assume that: // // N is an integer within the range [3..100,000]; // each element of array A is an integer within the range [−1,000..1,000]. // Complexity: // // expected worst-case time complexity is O(N*log(N)); // expected worst-case space complexity is O(1) (not counting the storage required for input arguments). var A =[-3,1, 2, -2, 5, 6, -4] function solution(A) { var s= A.sort((a,b)=>b-a) //console.log(s) var len = s.length var combAllPositive = s[0] * s[1] * s[2] var combTwoNegAndOnePos = s[0] * s[len-2] *s[len-1] return combAllPostive > combTwoNegAndOnePos ? combAllPostive : combTwoNegAndOnePos } console.log(solution(A))
const { OK, CREATED } = require('http-status-codes'); const authService = require('../services/authService'); const register = async (req, res, next) => { try { const result = await authService.register(req.body); res.status(CREATED).json(result); } catch (serviceError) { next(serviceError); } }; const login = async (req, res, next) => { try { const result = await authService.login(req.body); res.status(OK).json(result); } catch (serviceError) { next(serviceError); } }; module.exports = { register, login, };
/** * @param {number[]} nums * @return {number} */ var findMin = function (nums) { let currentLowest = nums[0]; let start = 0; let end = Math.floor(nums.length / 2); while (start !== end) { const startingNum = nums[start]; const endingNum = nums[end]; if (endingNum < startingNum) { currentLowest = endingNum; end = Math.floor((start + end) / 2); } else { start = end; end = nums.length - 1; } } return currentLowest; }; module.exports = { findMin }
const handleBadRequest = (req, res, message, details) => { if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line no-console console.error(details); } return res.status(400).json({ status: 400, title: 'Bad request', message, details: process.env.NODE_ENV !== 'production' ? details : null, }); }; const handleInternalServerError = (req, res, message, details) => { if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line no-console console.error(details); } return res.status(500).json({ status: 500, title: 'Internal server error', message, details: process.env.NODE_ENV !== 'production' ? details : null, }); }; const handleForbidden = (req, res, message, details) => { res.status(403).json({ status: 403, title: 'Forbidden', message, details: process.env.NODE_ENV !== 'production' ? details : null, }); }; const handleNotFound = (req, res, message, details) => { res.status(404).json({ status: 404, title: 'Not found!', message, details: process.env.NODE_ENV !== 'production' ? details : null, }); }; const handleConflict = (req, res, message, details) => { res.status(409).json({ status: 409, title: 'Conflict', message, details: process.env.NODE_ENV !== 'production' ? details : null, }); }; const handleSuccess = (req, res, payload) => { res.status(200).json({ status: 200, payload, }); }; module.exports = (req, res, next) => { res.success = payload => handleSuccess(req, res, payload); res.forbidden = ({ message = null, details = null } = {}) => handleForbidden(req, res, message, details); res.badRequest = ({ message = null, details = null } = {}) => handleBadRequest(req, res, message, details); res.notFound = ({ message = null, details = null } = {}) => handleNotFound(req, res, message, details); res.conflict = ({ message = null, details = null } = {}) => handleConflict(req, res, message, details); res.internalServerError = ({ message = null, details = null } = {}) => handleInternalServerError(req, res, message, details); next(); };
import React, {Component} from "react"; import { withStyles } from '@material-ui/core/styles'; import { IconButton } from "@material-ui/core"; const styles = theme => ({ btnstyle: { '& svg': { fontSize: 100, display: 'block', margin: 'auto'} }, }); class Buttonst extends Component { handleClick = () => { this.props.clickColor(this.props.id); }; render() { const {classes} = this.props; return ( <IconButton variant="contained" color={this.props.id === this.props.afd ? "primary" : "none"} className={classes.btnstyle} onClick={this.handleClick}> {this.props.updown} </IconButton> ); } } export default withStyles(styles)(Buttonst)
define(function () { function toTypedUrl(documents, couchUrl, database) { if (!Array.isArray(documents)) throw new Error('Array expected'); for (var i = 0; i < documents.length; i++) { var content = documents[i].$content; processObject(content, documents[i]); } function processObject(obj, documents) { if (obj instanceof Object) { if (typeof obj.filename === 'string' && typeof obj.type === 'string') { obj.url = `${couchUrl}/db/${database}/${documents._id}/${obj.filename}`; } for (var key in obj) { processObject(obj[key], documents); } } else if (Array.isArray(obj)) { for (var i = 0; i < obj.length; i++) { processObject(obj[i], documents); } } } return documents; } return toTypedUrl; });
// we try to build the API location from the client's URL // (in a rather crude manner) const guessAPILocation = (clientURL, defaultURL) => { if ((clientURL.indexOf('3000') >= 0) && (clientURL.indexOf('http') >= 0)){ // this cleanup is to make the guess work within Gitpod, where the "(mini-)browser" reports an URL // such as "wss://8000-apricot-lizard-sa8u19n5.ws-eu17.gitpod.io/?vscodeBrowserReqId=1635860969945" // (as opposed to "ordinary" browsers where the URL would end with "...gitpod.io/") const gpCleanedClientURL = clientURL.indexOf('?') >= 0 ? clientURL.slice(0, clientURL.indexOf('?')) : clientURL // now the 'standard' guesswork can start const apiLoc = gpCleanedClientURL.replace('3000', '8000').replace('http', 'ws') if (apiLoc[apiLoc.length - 1] === '/'){ // get rid of trailing '/' return apiLoc.slice(0, -1) }else{ return apiLoc } }else{ return defaultURL } } export default guessAPILocation
import React, { Component } from 'react' export default class Notification extends Component { componentWillMount() { addEventListener('scroll', this._stickyNotification.bind(this)) } componentWillUnmount() { removeEventListener('scroll', this._stickyNotification.bind(this)) } _stickyNotification() { let rect = this.notificationWrapper.getBoundingClientRect() if (rect.top < 0) { this.notification.classList.add('liveblog-posts--notification--sticky') } else if (rect.top >= 0) { this.notification.classList.remove('liveblog-posts--notification--sticky') } } render() { var newPostText = '' if (this.props.newPosts.length == 1) { newPostText = (<span>1 new post. <button className="link" onClick={this.props.loadNewPosts}>Click here</button> to load it.</span>) } else if (this.props.newPosts.length > 1) { newPostText = ( <span>{ this.props.newPosts.length } new posts.&nbsp; <button className="link" onClick={this.props.loadNewPosts}>Click here</button> to load them. </span> ) } return ( <div className="liveblog-notification-wrapper" ref={wrapper => this.notificationWrapper = wrapper}> <div ref={(notifications) => this.notification = notifications}> { newPostText && <div className="liveblog-posts-new"> { newPostText } </div> } </div> </div> ) } }
import React from 'react'; import './app.scss'; import data from './../data'; import Search from './search'; import Results from './results'; // Allows results to be independent of the original data let results = [...data]; class App extends React.Component { state = { data: data, results: results, sortBy: '' } sortResults = (sortBy) => { console.log('sorting'); let results = this.state.results; switch(sortBy) { case 'from': if (this.state.sortBy === 'from') { results.sort(function(a, b) { if (a.from < b.from) return 1; if (a.from > b.from) return -1; return 0; }); this.setState({ results: results, sortBy: 'from-reverse' }); } else if (this.state.sortBy === 'from-reverse') { results = [...data]; this.setState({ results: results, sortBy: '' }); } else { results.sort(function(a, b) { if (a.from < b.from) return -1; if (a.from > b.from) return 1; return 0; }); this.setState({ results: results, sortBy: 'from' }); } break; case 'to': if (this.state.sortBy === 'to') { results.sort(function(a, b) { if (a.to < b.to) return 1; if (a.to > b.to) return -1; return 0; }); this.setState({ results: results, sortBy: 'to-reverse' }); } else if (this.state.sortBy === 'to-reverse') { results = [...data]; this.setState({ results: results, sortBy: '' }); } else { results.sort(function(a, b) { if (a.to < b.to) return -1; if (a.to > b.to) return 1; return 0; }); this.setState({ results: results, sortBy: 'to' }); } break; case 'subject': if (this.state.sortBy === 'subject') { results.sort(function(a, b) { if (a.subject < b.subject) return 1; if (a.subject > b.subject) return -1; return 0; }); this.setState({ results: results, sortBy: 'subject-reverse' }); } else if (this.state.sortBy === 'subject-reverse') { results = [...data]; this.setState({ results: results, sortBy: '' }); } else { results.sort(function(a, b) { if (a.subject < b.subject) return -1; if (a.subject > b.subject) return 1; return 0; }); this.setState({ results: results, sortBy: 'subject' }); } break; case 'date': if (this.state.sortBy === 'date') { results.sort(function(a, b) { if (a.date < b.date) return 1; if (a.date > b.date) return -1; return 0; }); this.setState({ results: results, sortBy: 'date-reverse' }); } else if (this.state.sortBy === 'date-reverse') { results = [...data]; this.setState({ results: results, sortBy: '' }); } else { results.sort(function(a, b) { if (a.date < b.date) return -1; if (a.date > b.date) return 1; return 0; }); this.setState({ results: results, sortBy: 'date' }); } break; default: // do nothing } // results.sort(function(a, b) { // var keyA = new Date(a.updated_at), // keyB = new Date(b.updated_at); // Compare the 2 dates // if (keyA < keyB) return -1; // if (keyA > keyB) return 1; // }); } render() { console.log('data', this.state.data); console.log('results', this.state.results); return ( <div className="App"> <Search /> <Results results={this.state.results} sortResults={this.sortResults} /> </div> ); } }; export default App;
'use strict'; // https://www.d3-graph-gallery.com/graph/line_cursor.html let formatTime = d3.timeParse("%b %d %Y") let presentTime = d3.timeFormat("%B %d, %Y") const loadData = d3.csv('AidCoin.csv').then(data => { data.forEach(d => { d.Open = +d.Open; d.High = +d.High; d.Low = +d.Low; d.Close = +d.Close; d.Volume = +d.Volume; d.Date = formatTime(d.Date); }) return data }); const movingAverage = (data, numberOfPricePoints) => { return data.map((row, index, total) => { const start = Math.max(0, index - numberOfPricePoints) const end = index const subset = total.slice(start, end + 1) const sum = subset.reduce((a,b) => { return a + b.Close },0); return { date: row.Date, average: sum / subset.length } }) } loadData.then(data => { initializeChart(data) }) // credits: https://brendansudol.com/writing/responsive-d3 const responsivefy = svg => { // get container + svg aspect ratio const container = d3.select(svg.node().parentNode), width = parseInt(svg.style('width')), height = parseInt(svg.style('height')), aspect = width / height; // get width of container and resize svg to fit it const resize = () => { var targetWidth = parseInt(container.style('width')); svg.attr('width', targetWidth); svg.attr('height', Math.round(targetWidth / aspect)); }; // add viewBox and preserveAspectRatio properties, // and call resize so that svg resizes on inital page load svg .attr('viewBox', '0 0 ' + width + ' ' + height) .attr('perserveAspectRatio', 'xMinYMid') .call(resize); // to register multiple listeners for same event type, // you need to add namespace, i.e., 'click.foo' // necessary if you call invoke this function for multiple svgs // api docs: https://github.com/mbostock/d3/wiki/Selections#on d3.select(window).on('resize.' + container.attr('id'), resize); }; const initializeChart = data => { const margin = { top: 50, right: 50, bottom: 50, left: 50 }; const width = window.innerWidth - margin.left - margin.right; const height = window.innerHeight - margin.top - margin.bottom; const xMin = d3.min(data, d => d.Date) const xMax = d3.max(data, d => d.Date) const yMin = d3.min(data, d => d.Close) const yMax = d3.max(data, d => d.Close) // Scale using range const xScale = d3 .scaleTime() .domain([data[616].Date, data[0].Date]) .range([0, width]) const yScale = d3 .scaleLinear() .domain([yMin, yMax]) .range([height, 0]) // adds SVG chart to page const svg = d3 .select('#chart') .append('svg') .attr('width', width + margin.left + margin.right) .attr('height', height + margin.top + margin.bottom) .call(responsivefy) .append('g') .attr('transform', `translate(${margin['left']}, ${margin['top']})`); // Create Axis svg .append('g') .attr('id', 'xAxis') .attr("class", "axis") .attr('transform', `translate(0, ${height})`) .call(d3.axisBottom(xScale) // .ticks(12) ) svg .append('g') .attr('id', 'yAxis') .attr("class", "axis") .attr('transform', `translate(0, 0)`) .call(d3.axisLeft(yScale) // .ticks(5) // .tickValues() // .tickFormat(d => d + '%') ) // renders close price line chart and moving average line chart // generates lines when called const line = d3 .line() .x(d => xScale(d.Date)) .y(d => yScale(d.Close)) const movingAverageLine = d3 .line() .x(d => xScale(d.date)) .y(d => yScale(d.average)) .curve(d3.curveBasis) svg .append('path') .data([data]) .style('fill', 'none') .attr('id', 'priceChart') .attr('stroke', 'steelblue') .attr('stroke-width', '1.5') .attr('d', line) // .on('click', d => console.log(d)) // title svg.append("text") .attr("x", (width / 2)) .attr("y", 0 + (margin.top / 2)) .attr("text-anchor", "middle") .style("font-size", "40px") .style("text-decoration", "underline") .style('fill', 'white') .text("Aid Coin"); // calculates simple moving average over 50 days const movingAverageData = movingAverage(data, 49) svg .append('path') .data([movingAverageData]) .style('fill', 'none') .attr('id', 'movingAverageLine') .attr('stroke', '#FF8900') .attr('d', movingAverageLine) // create circle that travels along the line of chart let focus = svg .append('g') .append('circle') .style("fill", "none") .attr("stroke", "white") .attr('r', 8.5) .style("opacity", 0) // create text that travels along the line of the chart let focusText = svg .append('g') .append('text') .style("opacity", 0) .style("fill", "white") .attr("text-anchor", "left") .attr("alignment-basline", "middle") // let focusText = d3.select('#chart') // .append('div') // .style("opacity", 0) // .attr("class", "tooltip") // .style("background-color", "white") // .style("border", "solid") // .style("border-width", "2px") // .style("border-radius", "5px") // .style("padding", "5px") // create rect on top of svg area that recovers mouse position svg .append('rect') .style("fill", "none") .style("pointer-events", "all") .attr('width', width) .attr('height', height) .on('mouseover', mouseover) .on('mousemove', mousemove) .on('mouseout', mouseout) function mouseover() { focus.style("opacity", 1) focusText.style("opacity", 1) } const bisect = d3.bisector(d => d.Date).left function mousemove() { // find the closest X index of the mouse // recover coordinate we need let x0 = xScale.invert(d3.mouse(this)[0]) // let i = bisect(data, x0, 1) let index = 0 for(let i=data.length -1; i>0; i--) { if (x0 < data[i].Date) { index = i break } } console.log("index: ", index) let selectedData = data[index] console.log(`Data: ${selectedData.Date} and ${selectedData.Close}`) focus .attr("cx", xScale(selectedData.Date)) .attr("cy", yScale(selectedData.Close)) focusText .html(`Close: $${selectedData.Close} ${presentTime(selectedData.Date)}`) .attr("x", xScale(selectedData.Date)+15) .attr("y", yScale(selectedData.Close)) } function mouseout() { focus.style("opacity", 0) focusText.style("opacity", 0) } };
let mongoose = require('mongoose'), Schema = mongoose.Schema, TeacherSchema = new Schema({ lastName: String, classes: Array, hours: Object, email: String, homeroom: Number, extension: Number }); module.exports = mongoose.model('Teacher', TeacherSchema);
import React from "react"; import MoviesForm from "./MoviesForm"; import MoviesList from "./MoviesList"; import MoviesStats from "./MoviesStats"; const MoviesContainer = (props) => { return ( <div> <MoviesList /> <MoviesForm /> <MoviesStats /> </div> ); }; export default MoviesContainer;