text
stringlengths
7
3.69M
import React from "react"; import { List, ListItem, CardHeader, CardContent, CardFooter } from 'framework7-react'; import crypto from 'crypto-js'; import { dict } from "../../Dict"; import Moment from 'react-moment'; import JDate from 'jalali-date'; import 'moment-timezone'; import 'moment/locale/fa'; const StatusesList = (props) => { if (props.works) { return ( <React.Fragment> <CardHeader> {props.header} </CardHeader> <CardContent className='h-120'> <List mediaList className='fs-11'> {props.works.map((work) => <ListItem className='fs-10' key={'workList'+work.id} title={work.title} text={work.task.title} after={alerts(work)} link={'/works/' + work.id}></ListItem> )} </List> </CardContent> <CardFooter> </CardFooter> </React.Fragment> ) } else { return (<ul></ul>) } } export default StatusesList;
'use strict'; /** * @ngdoc function * @name dssiFrontApp.controller:VisitsCheckoutCtrl * @description * # VisitsCheckoutCtrl * Controller of the dssiFrontApp */ angular.module('dssiFrontApp') .controller('VisitsCheckoutCtrl', function () { });
export const globalConfig = { "theme": "nzo", // dentasol || isar || nzo || zcor "BackendURL": "https://ssl-account.com/mobileapi.dentasol.eu/v1/dev.php", // "BackendURL": "http://mobileapi.dentasol.eu/v2/", "version": "0.0.1", };
/** * @properties={typeid:24,uuid:"D7BBA87D-C50A-483E-BD5B-DCF74864D5AF"} */ function getButtonObject() { var _enabled = globals.getTipologiaDitta(idditta) == globals.Tipologia.ESTERNA || globals.ma_utl_hasKey(globals.Key.GEST_ANAG_DITTA); var btnObj = _super.getButtonObject(); btnObj.btn_new = { enabled: false }; btnObj.btn_edit = { enabled: _enabled }; btnObj.btn_delete = { enabled: false }; btnObj.btn_duplicate = { enabled: false }; return btnObj; } /** * @param _rec * * @properties={typeid:24,uuid:"E0BF4EC8-7C84-4B94-9BBB-7C2A1BC35C7B"} */ function updateTipoSoggetto(_rec) { codtiposoggetto = _rec['codice']; } /** * @param _rec * * @properties={typeid:24,uuid:"F05F4901-82A9-47FF-A433-A9587A023E91"} */ function updateNaturaGiuridica(_rec) { codnaturagiuridica = _rec['codice']; } /** * * @param {Boolean} firstShow * @param {JSEvent} event * @param {Boolean} svyNavBaseOnShow * * @properties={typeid:24,uuid:"ADFAAB20-7503-4C3E-81EE-83BEB25B43A5"} */ function onShowForm(firstShow, event, svyNavBaseOnShow) { controller.readOnly = true; return _super.onShowForm(firstShow, event, false) }
var authenticate = require('../authenticate'); const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const Location = require('../models/location'); const SensorInst = require('../models/sensor_instance'); const Sensor = require('../models/sensor'); const Maps = require('../models/custom_map'); var passport = require('passport'); const alertRouter = express.Router(); alertRouter.use(bodyParser.json()); function eachInstance(instance,username){ var inst = {}; inst.sensorinstid = instance._id; inst.checked = false; console.log("reached"); var k; for(k=0;k<instance.alert_users.length;k++){ console.log("stored : " + instance.alert_users[k] + " == username : "+ username); console.log("stored : " + typeof instance.alert_users[k] + " == username : "+ typeof username); //if( JSON.stringify(instance.alert_users[k]) === JSON.stringify(userid) ){ if( instance.alert_users[k] === username ){ console.log("matched"); inst.checked = true; } } return Sensor.find({ _id: instance.sensorid }) .then((sensors) => { inst.sensorname = sensors[0].name; inst.sensor_type = sensors[0].sensor_type; inst.data_type = sensors[0].data_type; return inst; }, (error) => { return {}; }) .catch((error) => { return {}; }); } function loc_name(mapid){ return Maps.find({_id : mapid}) .then((map) => { return map[0].name; },(err) => { return 'no name found'; }) .catch((err) => { return 'no name found'; }); } async function eachLocation(location,username){ var loc = {}; loc.name = location.name; if(location['mapid'] == 'global') loc.map_name = "global"; else loc['map_name'] = await loc_name(location['mapid']); loc.latitude = location.latitude; loc.longitude = location.longitude; loc.sensinst = []; return SensorInst.find({ locationid : location._id }) .then( async (instances) => { var instance = {}; var j; for(j=0;j<instances.length;j++){ instance = await eachInstance(instances[j],username); loc.sensinst.push(instance); } return loc; }, (error) => { return {}; }) .catch((error) => { return {}; }); } alertRouter.route('/') .get(authenticate.verifyUser,(req,res,next) => { var keyuserid; var userid = req.user._id; if(req.user.usertype == 'admin') keyuserid = req.user._id; else keyuserid = req.user.parentid; Location.find({ userid: keyuserid }) .then( async (locations) => { var i; var global = []; for(i=0;i<locations.length;i++){ var local = {}; local = await eachLocation(locations[i],req.user.username); global.push(local); } res.statusCode = 200; res.setHeader('Content-Type','application/json'); res.json({locations:global}); }, (error) => { res.statusCode = 403; res.end('POST operation not supported on /alert'); }) .catch((error) => { res.statusCode = 403; res.end('POST operation not supported on /alert'); }); }) .post(authenticate.verifyUser, (req,res,next) => { var i; var check = req.body.selected; console.log("check--"); console.log(check); for(i=0;i<check.length;i++){ console.log("locationid : " + check[i]); SensorInst.findOne({ _id: check[i] }) .then((instance) => { var id = req.user.username; instance.alert_users.push(id); instance.save() .then((instance)=>{ },(err) => { res.status(404).send(error); }) .catch((error) => { res.status(404).send(error); }); },(err) => { res.status(404).send(err); }) .catch((err) => { res.status(404).send(err); }); } res.statusCode = 200; res.setHeader('Content-Type','application/json'); res.json({message:'Created Alert Succesfully!'}); }); module.exports = alertRouter;
import React from 'react'; import './Home.scss' // import { act } from 'react-dom/test-utils'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import container from '../../Assets/srstore1.png' import logo from "../../Assets/srstore2.png" import * as actionUser from '../../Redux/Actions/UserAction' // import Login from '../Login/Login'; const Home = () => { return (<div className="home"> <div className="navbar"> <li className="logo"><img src={logo} alt="logo"/></li> <li className='search'><input type="text" placeholder="Search you desired product" /><i>Search</i></li> <li className="status"> <span className="user">Login / Register</span> <span className="cart"> My Cart 0</span> </li> </div> <div className="container"> <div className="img"><img src={container} alt="container" /></div> <div className="about"> <h2>About us</h2> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum...<span><b style={{cursor:'pointer'}}>Read more</b></span></p> </div> </div> <div className="cat-carosuel"> <li>Trending</li> <li>Footwear</li> <li>Clothing</li> <li>Electronic</li> <li>Fashion</li> <li>Grocery</li> </div> <div className="product"> <div className="filter"> <li>Sort by</li> <li>Category</li> </div> <div className="item"> <div className="line1"> <li>Search Results</li> <li>View Type</li> </div> </div> </div> </div>) } const mapStateToProps = (state) => ({ test:state.user.test }) const mapDispatchToProps = (dispatch) => ({ actionUser:bindActionCreators(actionUser,dispatch) }) export default connect(mapStateToProps,mapDispatchToProps) (Home);
// first tutorial WebGL var gl; function initGL(canvas){ try{ gl = canvas.getContext("experimental-webgl"); gl.viewportWidth = canvas.width; gl.viewportHeight = canvas.height; } catch(error){ } if(!gl){ alert("webGL not working!"); } } function initShaders(){ } function initBuffers(){ } function drawScene(){ } function webGLInit(){ var canvas = document.getElementById("webgl-demo"); initGL(canvas); initShaders(); initBuffers(); gl.clearColor(0.0, 0.0, 0.0, 1.0); gl.enable(gl.DEPTH_TEST); drawScene(); }
var findSmallestSetOfVertices = function(n, edges) { };
var vt = vt = vt || {}; vt.LogicClass_500551 = cc.Class.extend({ m_view: null, ctor: function () {}, setTableView: function (view) { this.m_view = view; }, refreshTableView: function () { //this.m_view.reloadData(); }, setVar: function (key, value) { this[key] = value; }, run: function (context, targetObject) { var _this = this; var localVar={}; //add by wang_dd var logicName = ""; var notifyToken = NotifyCenter.getInstance().subscribe("加载",function() { if(context._parent) { (function () { var httpHead = window.G_dizhi; var httpParse = (function () { var arr = []; var eleValue = "aid"; arr.push(eleValue); var eleValue = "5"; arr.push(eleValue); var eleValue = "mid"; arr.push(eleValue); var eleValue = "2"; arr.push(eleValue); var eleValue = "userId"; arr.push(eleValue); var eleValue = window.G_id; arr.push(eleValue); return arr; })() ; var http = httpHead + "?"; for(var i = 0;i < httpParse.length;i ++){ http += httpParse[i]; if(i < httpParse.length - 1 && ((i - 1) % 2) === 0){ http += "&"; } if((i % 2) === 0){ http += "="; } } var xhr = cc.loader.getXMLHttpRequest(); xhr.open("GET", http, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) { var httpStatus = xhr.responseText; var httpRequestData = JSON.parse(httpStatus); context.a = (function(){ var separator = ','; var str = (function(){ //add by wang_dd var memberVar = "properties"; var tempVar = memberVar.substr(8,memberVar.length-8); if(targetObject && targetObject[tempVar] != undefined) { return targetObject[tempVar]; } else { var data = ""; var datas = (function () { var data; if(httpRequestData) { data = httpRequestData; } return data; })() ; var parse = "properties"; data = datas[parse]; return data; } })(); var result = str.split(separator); return result; })();var funData = (function () { var arr = []; var eleValue = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[0] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })(); arr.push(eleValue); var eleValue = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[1] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })(); arr.push(eleValue); return arr; })() if(200000===LogicParObj.var_member) { if(typeof(context.window.G_canshu) != "undefined") { context.window.G_canshu = funData; } } else if (200000===LogicParObj.var_global) { var gettype=Object.prototype.toString; var isString=false, isUserVar=false; var varValue; if(typeof (funData)==='undefined') { varValue=funData; window.G_canshu = varValue; isUserVar=true; } if(!isUserVar) { var temp=funData; if(gettype.call(temp)==='[object String]'){ window.G_canshu = temp; isString=true; } if(!isString) { if(typeof temp ==='undefined') { window.G_canshu = temp; } } if (!isString) { if(!(gettype.call(temp)=='[object Null]')) { window.G_canshu = temp; } } } } else { window.G_canshu = funData; }var funData = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[2] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })() if(200000===LogicParObj.var_member) { if(typeof(context.window.G_a2) != "undefined") { context.window.G_a2 = funData; } } else if (200000===LogicParObj.var_global) { var gettype=Object.prototype.toString; var isString=false, isUserVar=false; var varValue; if(typeof (funData)==='undefined') { varValue=funData; window.G_a2 = varValue; isUserVar=true; } if(!isUserVar) { var temp=funData; if(gettype.call(temp)==='[object String]'){ window.G_a2 = temp; isString=true; } if(!isString) { if(typeof temp ==='undefined') { window.G_a2 = temp; } } if (!isString) { if(!(gettype.call(temp)=='[object Null]')) { window.G_a2 = temp; } } } } else { window.G_a2 = funData; }var funData = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[3] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })() if(200000===LogicParObj.var_member) { if(typeof(context.window.G_a3) != "undefined") { context.window.G_a3 = funData; } } else if (200000===LogicParObj.var_global) { var gettype=Object.prototype.toString; var isString=false, isUserVar=false; var varValue; if(typeof (funData)==='undefined') { varValue=funData; window.G_a3 = varValue; isUserVar=true; } if(!isUserVar) { var temp=funData; if(gettype.call(temp)==='[object String]'){ window.G_a3 = temp; isString=true; } if(!isString) { if(typeof temp ==='undefined') { window.G_a3 = temp; } } if (!isString) { if(!(gettype.call(temp)=='[object Null]')) { window.G_a3 = temp; } } } } else { window.G_a3 = funData; }var funData = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[4] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })() if(200000===LogicParObj.var_member) { if(typeof(context.window.G_a4) != "undefined") { context.window.G_a4 = funData; } } else if (200000===LogicParObj.var_global) { var gettype=Object.prototype.toString; var isString=false, isUserVar=false; var varValue; if(typeof (funData)==='undefined') { varValue=funData; window.G_a4 = varValue; isUserVar=true; } if(!isUserVar) { var temp=funData; if(gettype.call(temp)==='[object String]'){ window.G_a4 = temp; isString=true; } if(!isString) { if(typeof temp ==='undefined') { window.G_a4 = temp; } } if (!isString) { if(!(gettype.call(temp)=='[object Null]')) { window.G_a4 = temp; } } } } else { window.G_a4 = funData; }var funData = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[5] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })() if(200000===LogicParObj.var_member) { if(typeof(context.window.G_a5) != "undefined") { context.window.G_a5 = funData; } } else if (200000===LogicParObj.var_global) { var gettype=Object.prototype.toString; var isString=false, isUserVar=false; var varValue; if(typeof (funData)==='undefined') { varValue=funData; window.G_a5 = varValue; isUserVar=true; } if(!isUserVar) { var temp=funData; if(gettype.call(temp)==='[object String]'){ window.G_a5 = temp; isString=true; } if(!isString) { if(typeof temp ==='undefined') { window.G_a5 = temp; } } if (!isString) { if(!(gettype.call(temp)=='[object Null]')) { window.G_a5 = temp; } } } } else { window.G_a5 = funData; }var funData = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[6] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })() if(200000===LogicParObj.var_member) { if(typeof(context.window.G_a6) != "undefined") { context.window.G_a6 = funData; } } else if (200000===LogicParObj.var_global) { var gettype=Object.prototype.toString; var isString=false, isUserVar=false; var varValue; if(typeof (funData)==='undefined') { varValue=funData; window.G_a6 = varValue; isUserVar=true; } if(!isUserVar) { var temp=funData; if(gettype.call(temp)==='[object String]'){ window.G_a6 = temp; isString=true; } if(!isString) { if(typeof temp ==='undefined') { window.G_a6 = temp; } } if (!isString) { if(!(gettype.call(temp)=='[object Null]')) { window.G_a6 = temp; } } } } else { window.G_a6 = funData; }var funData = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[7] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })() if(200000===LogicParObj.var_member) { if(typeof(context.window.G_a7) != "undefined") { context.window.G_a7 = funData; } } else if (200000===LogicParObj.var_global) { var gettype=Object.prototype.toString; var isString=false, isUserVar=false; var varValue; if(typeof (funData)==='undefined') { varValue=funData; window.G_a7 = varValue; isUserVar=true; } if(!isUserVar) { var temp=funData; if(gettype.call(temp)==='[object String]'){ window.G_a7 = temp; isString=true; } if(!isString) { if(typeof temp ==='undefined') { window.G_a7 = temp; } } if (!isString) { if(!(gettype.call(temp)=='[object Null]')) { window.G_a7 = temp; } } } } else { window.G_a7 = funData; }var funData = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[8] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })() if(200000===LogicParObj.var_member) { if(typeof(context.window.G_a8) != "undefined") { context.window.G_a8 = funData; } } else if (200000===LogicParObj.var_global) { var gettype=Object.prototype.toString; var isString=false, isUserVar=false; var varValue; if(typeof (funData)==='undefined') { varValue=funData; window.G_a8 = varValue; isUserVar=true; } if(!isUserVar) { var temp=funData; if(gettype.call(temp)==='[object String]'){ window.G_a8 = temp; isString=true; } if(!isString) { if(typeof temp ==='undefined') { window.G_a8 = temp; } } if (!isString) { if(!(gettype.call(temp)=='[object Null]')) { window.G_a8 = temp; } } } } else { window.G_a8 = funData; }var funData = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[9] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })() if(200000===LogicParObj.var_member) { if(typeof(context.window.G_a9) != "undefined") { context.window.G_a9 = funData; } } else if (200000===LogicParObj.var_global) { var gettype=Object.prototype.toString; var isString=false, isUserVar=false; var varValue; if(typeof (funData)==='undefined') { varValue=funData; window.G_a9 = varValue; isUserVar=true; } if(!isUserVar) { var temp=funData; if(gettype.call(temp)==='[object String]'){ window.G_a9 = temp; isString=true; } if(!isString) { if(typeof temp ==='undefined') { window.G_a9 = temp; } } if (!isString) { if(!(gettype.call(temp)=='[object Null]')) { window.G_a9 = temp; } } } } else { window.G_a9 = funData; }var funData = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[10] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })() if(200000===LogicParObj.var_member) { if(typeof(context.window.G_a10) != "undefined") { context.window.G_a10 = funData; } } else if (200000===LogicParObj.var_global) { var gettype=Object.prototype.toString; var isString=false, isUserVar=false; var varValue; if(typeof (funData)==='undefined') { varValue=funData; window.G_a10 = varValue; isUserVar=true; } if(!isUserVar) { var temp=funData; if(gettype.call(temp)==='[object String]'){ window.G_a10 = temp; isString=true; } if(!isString) { if(typeof temp ==='undefined') { window.G_a10 = temp; } } if (!isString) { if(!(gettype.call(temp)=='[object Null]')) { window.G_a10 = temp; } } } } else { window.G_a10 = funData; }var funData = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[11] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })() if(200000===LogicParObj.var_member) { if(typeof(context.window.G_a11) != "undefined") { context.window.G_a11 = funData; } } else if (200000===LogicParObj.var_global) { var gettype=Object.prototype.toString; var isString=false, isUserVar=false; var varValue; if(typeof (funData)==='undefined') { varValue=funData; window.G_a11 = varValue; isUserVar=true; } if(!isUserVar) { var temp=funData; if(gettype.call(temp)==='[object String]'){ window.G_a11 = temp; isString=true; } if(!isString) { if(typeof temp ==='undefined') { window.G_a11 = temp; } } if (!isString) { if(!(gettype.call(temp)=='[object Null]')) { window.G_a11 = temp; } } } } else { window.G_a11 = funData; }var funData = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[12] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })() if(200000===LogicParObj.var_member) { if(typeof(context.window.G_a12) != "undefined") { context.window.G_a12 = funData; } } else if (200000===LogicParObj.var_global) { var gettype=Object.prototype.toString; var isString=false, isUserVar=false; var varValue; if(typeof (funData)==='undefined') { varValue=funData; window.G_a12 = varValue; isUserVar=true; } if(!isUserVar) { var temp=funData; if(gettype.call(temp)==='[object String]'){ window.G_a12 = temp; isString=true; } if(!isString) { if(typeof temp ==='undefined') { window.G_a12 = temp; } } if (!isString) { if(!(gettype.call(temp)=='[object Null]')) { window.G_a12 = temp; } } } } else { window.G_a12 = funData; }var funData = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[13] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })() if(200000===LogicParObj.var_member) { if(typeof(context.window.G_a13) != "undefined") { context.window.G_a13 = funData; } } else if (200000===LogicParObj.var_global) { var gettype=Object.prototype.toString; var isString=false, isUserVar=false; var varValue; if(typeof (funData)==='undefined') { varValue=funData; window.G_a13 = varValue; isUserVar=true; } if(!isUserVar) { var temp=funData; if(gettype.call(temp)==='[object String]'){ window.G_a13 = temp; isString=true; } if(!isString) { if(typeof temp ==='undefined') { window.G_a13 = temp; } } if (!isString) { if(!(gettype.call(temp)=='[object Null]')) { window.G_a13 = temp; } } } } else { window.G_a13 = funData; }var funData = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[14] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })() if(200000===LogicParObj.var_member) { if(typeof(context.window.G_a14) != "undefined") { context.window.G_a14 = funData; } } else if (200000===LogicParObj.var_global) { var gettype=Object.prototype.toString; var isString=false, isUserVar=false; var varValue; if(typeof (funData)==='undefined') { varValue=funData; window.G_a14 = varValue; isUserVar=true; } if(!isUserVar) { var temp=funData; if(gettype.call(temp)==='[object String]'){ window.G_a14 = temp; isString=true; } if(!isString) { if(typeof temp ==='undefined') { window.G_a14 = temp; } } if (!isString) { if(!(gettype.call(temp)=='[object Null]')) { window.G_a14 = temp; } } } } else { window.G_a14 = funData; }var funData = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[15] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })() if(200000===LogicParObj.var_member) { if(typeof(context.window.G_a15) != "undefined") { context.window.G_a15 = funData; } } else if (200000===LogicParObj.var_global) { var gettype=Object.prototype.toString; var isString=false, isUserVar=false; var varValue; if(typeof (funData)==='undefined') { varValue=funData; window.G_a15 = varValue; isUserVar=true; } if(!isUserVar) { var temp=funData; if(gettype.call(temp)==='[object String]'){ window.G_a15 = temp; isString=true; } if(!isString) { if(typeof temp ==='undefined') { window.G_a15 = temp; } } if (!isString) { if(!(gettype.call(temp)=='[object Null]')) { window.G_a15 = temp; } } } } else { window.G_a15 = funData; }var funData = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[16] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })() if(200000===LogicParObj.var_member) { if(typeof(context.window.G_a16) != "undefined") { context.window.G_a16 = funData; } } else if (200000===LogicParObj.var_global) { var gettype=Object.prototype.toString; var isString=false, isUserVar=false; var varValue; if(typeof (funData)==='undefined') { varValue=funData; window.G_a16 = varValue; isUserVar=true; } if(!isUserVar) { var temp=funData; if(gettype.call(temp)==='[object String]'){ window.G_a16 = temp; isString=true; } if(!isString) { if(typeof temp ==='undefined') { window.G_a16 = temp; } } if (!isString) { if(!(gettype.call(temp)=='[object Null]')) { window.G_a16 = temp; } } } } else { window.G_a16 = funData; }var funData = (function(){ var value; var arg0=Number((function(){ var value; var arg0=Number(context.a[17] ); var arg2=Number(1000); if('*'==='+') { value = arg0 + arg2; } else if('*'==='-') { value=arg0 - arg2; } else if ('*'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })()); var arg2=Number(1000); if('/'==='+') { value = arg0 + arg2; } else if('/'==='-') { value=arg0 - arg2; } else if ('/'==='/') { value=arg0 / arg2; } else { value=arg0 * arg2; } return value; })() if(200000===LogicParObj.var_member) { if(typeof(context.window.G_a17) != "undefined") { context.window.G_a17 = funData; } } else if (200000===LogicParObj.var_global) { var gettype=Object.prototype.toString; var isString=false, isUserVar=false; var varValue; if(typeof (funData)==='undefined') { varValue=funData; window.G_a17 = varValue; isUserVar=true; } if(!isUserVar) { var temp=funData; if(gettype.call(temp)==='[object String]'){ window.G_a17 = temp; isString=true; } if(!isString) { if(typeof temp ==='undefined') { window.G_a17 = temp; } } if (!isString) { if(!(gettype.call(temp)=='[object Null]')) { window.G_a17 = temp; } } } } else { window.G_a17 = funData; }var argu1 = window.G_loadplus, argu2 = 1, lenghtOne = 0, lenghtSec = 0, arguOneArray = argu1.toString().split("."), arguTwoArray = argu2.toString().split("."); if(arguOneArray[1]) lenghtOne = arguOneArray[1].length; if(arguTwoArray[1]) lenghtSec = arguTwoArray[1].length; if(lenghtOne == 0 && lenghtSec == 0) { window.G_loadplus+=1; } else if (lenghtOne != 0 || lenghtSec != 0) { var divisor = "1"; if(lenghtOne >= lenghtSec) { for (var i = 0; i < lenghtOne; ++i) { divisor += 0; } } else { for (var i = 0; i < lenghtSec; ++i) { divisor += 0; } } divisor = parseInt(divisor); window.G_loadplus = ( window.G_loadplus*divisor + 1*divisor )/divisor; } } }; xhr.send(); })(); } }); } });
import React from 'react' import { Text, Image, View, Linking } from 'react-native' import Card from './Card' import CardSection from './CardSection' import Button from './Button' const AlbumDetail = ({ album }) => { const { title, artist, thumbnail_image, image, url } = album return ( <Card> <CardSection> <View > <Image style={ styles.thumbnailContainer } source={{uri: thumbnail_image}} /> </View> <View style={styles.headerTextContainer}> <Text style = { styles.headerText } > {title} </Text> <Text > {artist} </Text> </View> </CardSection> <CardSection> <Image style={ styles.mainImage } source={{uri: image}} /> </CardSection> <CardSection> <Button onPress = { () => Linking.openURL(url) } text ="Buy Now" /> </CardSection> </Card> ) } const styles = { viewStyle: { flexDirection: 'column', justifyContent: 'center', alignItems: 'center', paddingTop: 20 }, thumbnailContainer: { width: 50, height: 50, marginLeft: 10, marginRight: 5, justifyContent: 'center', alignItems: 'center' }, headerText: { fontSize: 18 }, headerTextContainer: { flexDirection: 'column', justifyContent: 'space-around', marginLeft: 0 }, mainImage:{ height: 300, width: null, flex: 1 } } export default AlbumDetail
import request from '@/utils/request' import { urlLabel } from '@/api/commUrl' // 人标签查询--李义广接口 const url = urlLabel + 'peopleLabel/' const urlS = urlLabel + 'labelUser/' const urlD = urlLabel + 'labelUserInfo/' const urlF = urlLabel + 'labelConfig/' // 人标签节点添加 export function peopleLabelAdd(params) { return request({ url: url + 'save', method: 'post', data: params }) } // 人标签子集查询 export function getPeopleChildSearch(params) { return request({ url: url + 'list', method: 'post', data: params }) } // 人标签节点名称修改 export function peopleLabelUpload(params) { return request({ url: url + 'updatePeopleLabelTree', method: 'post', data: params }) } // 人标签节点删除 export function peopleLabelDelete(params) { return request({ url: url + 'deletePeopleLabelTree', method: 'post', data: params }) } // =============================================下边是用户列表页面的接口======================= // 人签用户基本信息表的列表查询接口 export function peopleLabelBasicInfo(params) { return request({ url: urlD + 'list', method: 'post', data: params }) } // 查询人签用户基本信息表的详情接口 export function peopleLabelDetailInfo(params) { return request({ url: urlD + 'userDetailed', method: 'post', data: params }) } // 查询人签用户基本信息表的详情并且把信息拼接在树上 export function peopleUserDetailedTree(params) { return request({ url: urlD + 'userDetailedTree', method: 'post', data: params }) } // 平台创建标签页面=======页面========页面=======页面====页面========== // 查询系统标签配置信息列表 export function factorylabelSearch(params) { return request({ url: urlF + 'list', method: 'post', data: params }) } // 修改系统标签配置信息 export function factorylabelUpload(params) { return request({ url: urlF + 'update', method: 'post', data: params }) } // 下边用户自定义标签接口部分======页面===页面=====页面=================================== // 查询用户自定义表签列表 export function userDefined(params) { return request({ url: urlS + 'list', method: 'post', data: params }) } // 李义广新增接口 export function baseLabelNameSearchList(params) { return request({ url: urlD + 'userLabelList', method: 'post', data: params }) }
var React = require('react'); var Component = require('./Component.tl'); module.exports = React.createClass({ render: function() { return Component.render({ foo: 23 }); } });
$('.button__submit').on('click', function() { var $name = $('#username').val(); $('.hello-card').text($name); $('.user-form').css("display", "none"); $('.hello-card').css("display", "block"); });
import { OpenGymInst } from "../OpenGymInst"; import PortlandTennisCenter from "./images/PortlandTennisCenter.jpg"; import StJohnsRacquetCenter from "./images/StJohnsRacquetCenter.jpg"; import LakeOswegoTennisCenter from "./images/LakeOswegoTennisCenter.jpeg"; const gyms = [ //mon - fri new OpenGymInst (PortlandTennisCenter, "Portland Tennis Center", "324 NE 12th Avenue, Portland, Oregon 97232", "https://goo.gl/maps/pD42T9Nez3XxQejD7", "Tennis", "Monday Tuesday Wednesday Thursday Friday", "5:30am to 11:00pm", "$16.00 per Court for 75 minutes", "Singles/Doubles", "http://www.thprd.org/facilities/recreation/conestoga/schedule/dropinsports/#dropin", "Reservations open 3 days in advance at 8:30am.", "8", "Indoor", "None", "45.525501", "-122.652735"), //sat & sun new OpenGymInst (PortlandTennisCenter, "Portland Tennis Center", "324 NE 12th Avenue, Portland, Oregon 97232", "https://goo.gl/maps/pD42T9Nez3XxQejD7", "Tennis", "Saturday Sunday", "6:30am to 10:00pm", "$16.00 per Court for 75 minutes", "Singles/Doubles", "http://www.thprd.org/facilities/recreation/conestoga/schedule/dropinsports/#dropin", "Reservations open 3 days in advance at 8:30am.", "8", "Indoor", "None", "45.525501", "-122.652735"), //mon - thurs new OpenGymInst (StJohnsRacquetCenter, "St. Johns Racquet Center", "7519 N Burlington Ave, Portland, OR 97203", "https://goo.gl/maps/d7WVkBReSGAJVeb4A", "Tennis", "Monday Tuesday Wednesday Thursday", "8:00am to 2:00pm and 6:00pm to 10:00pm", "$30.00 per Court 75 minutes", "Singles/Doubles", "https://www.stjohnsracquetcenter.org/", "Courts can be booked up to 7 days in advance.", "8", "Indoor", "None", "45.591440", "-122.754664"), //fri - sun new OpenGymInst (StJohnsRacquetCenter, "St. Johns Racquet Center", "7519 N Burlington Ave, Portland, OR 97203", "https://goo.gl/maps/d7WVkBReSGAJVeb4A", "Tennis", "Friday Saturday Sunday", "8:00am to 10:00pm", "$30.00 per Court 75 minutes", "Singles/Doubles", "https://www.stjohnsracquetcenter.org/", "Courts can be booked up to 7 days in advance.", "8", "Indoor", "None", "45.591440", "-122.754664"), //all days new OpenGymInst (LakeOswegoTennisCenter, "Lake Oswego Tennis Center", "2900 SW Diane Dr, Lake Oswego, OR 97035", "https://goo.gl/maps/3QUUnJDZjpMpqtF17", "Tennis", "Monday Tuesday Wednesday Thursday Friday Saturday Sunday", "6:00am to 10:00pm", "$22.00 per Court 60 minutes", "Singles/Doubles", "https://www.ci.oswego.or.us/parksrec/indoor-tennis-center", "Courts can be booked up to 7 days in advance.", "8", "Indoor", "None", "45.421863", "-122.706789"), ]; export default gyms;
import store from "./store"; export function formatMoneyForDisplay(monetaryAmount, isFiat = false, minimumAmountOfDecimals = 0) { // default use 2 decimals; let decimals = 2; // for fiat we always use 2 decimals, but if it's not for fiat... if (!isFiat) { // get number of decimals decimals from state decimals = store.state.app.decimals; // use minimumAmountOfDecimals if it's more than current decimals if (minimumAmountOfDecimals > decimals) { decimals = minimumAmountOfDecimals; } } // trunctate the amount to specified decimal places return (Math.floor(monetaryAmount / Math.pow(10, 8 - decimals)) / Math.pow(10, decimals)).toFixed(decimals); } export function displayToMonetary(displayAmount) { // note: do not divide by 100000000 because it will sometimes give rounding issues // convert the amount to string let str = displayAmount.toString(); // find the index decimal separator let idx = str.indexOf("."); // if the decimal separator doesn't exist... if (idx === -1) { // add the decimal separator at the end str += "."; // and update the index idx = str.length; } // add 8 zeroes at the end, maybe there are too many now str += "0".repeat(8); // but here they are removed from the tail str = str.substring(0, idx + 9); // now remove the . and then parse the string to integer return parseInt(str.replace(".", "")); }
export const computedProp = { computed: { reversedString(){ return this.message.split("").reverse().join(""); }, appendedLength(){ var length = this.message.length; return this.message + ' ' + '(' + length + ')' } } }
function BookListCtrl($scope, $http, $templateCache) { $scope.listBooks = function() { $http({method: 'GET', url: './api/book'}). success(function(data, status, headers, config) { $scope.books = data; //set view model $scope.view = './Partials/list.html'; //set to list view }). error(function(data, status, headers, config) { $scope.books = data || "Request failed"; $scope.status = status; $scope.view = './Partials/list.html'; }); } $scope.showBook = function(id) { $http({method: 'GET', url: './api/book/' + id}). success(function(data, status, headers, config) { $scope.bookDetail = data; //set view model $scope.view = './Partials/detail.html'; //set to detail view }). error(function(data, status, headers, config) { $scope.bookDetail = data || "Request failed"; $scope.status = status; $scope.view = './Partials/detail.html'; }); } $scope.updateBook = function(book) { $http({method: 'PUT', url: './api/book/' + book.isbn, data: book }). success(function(data,status,headers,config) { $scope.bookDetail = data; //set view model $scope.view = './Partials/detail.html'; //set to detail view }). error(function(data,status,headers,config) { $scope.bookDetail = data || "Request failed"; $scope.status = status; $scope.view = './Partials/detail.html'; }); } $scope.addBook = function(book) { $http({method: 'POST', url: './api/book/', data: book }). success(function(data,status,headers,config) { $scope.bookDetail = data; //set view model $scope.view = './Partials/detail.html'; //set to detail view }). error(function(data,status,headers,config) { $scope.bookDetail = data || "Request failed"; $scope.status = status; $scope.view = './Partials/detail.html'; }); } $scope.view = './Partials//list.html'; //set default view $scope.listBooks(); } BookListCtrl.$inject = ['$scope', '$http', '$templateCache'];
//Janay Peters // 04/29/2015 // Functions Assignment var car1 = prompt ("Hello, I am conducting a study about gas mileage! Lets say that you have two cars with full tanks of gas, " + "we have to figure out which one could travel the furthest distance! What size gallon tank does your first car have?"); //I used 16 var mile = prompt ("What are the average miles per gallon?") //I said 25 var total = mpg (car1, mile); function mpg(m, g){ var distance = m * g; return distance; } console.log(total); var car2 = prompt("Now lets find out what size tank your second car has!");//I used 21 var mile2 = prompt("What are the average miles per gallon?");//I said 20 var mpg2 = function(m2 , g2){ var distance2 = m2 * g2; return distance2; } var a = mpg2(car2, mile2); console.log(a); if (total > a){ console.log("Your first car will go the furthest!"); }else{ console.log("Your second car will go the furthest!");//My second car went the furthest! } // I typed 16 for size of tank, car 1, and 25 for mpg; I got 400. // I typed 21 for size of tank, car 2, and 20 for mpg; I got 420. // My second car would go the furthest!
if (self.CavalryLogger) { CavalryLogger.start_js(["KVE6r"]); } __d("isRetina",[],(function a(b,c,d,e,f,g){"use strict";f.exports=function(){return(window.devicePixelRatio||1)>1}}),null);
import { setAuthToken } from "../../utils"; import { useState, useContext, useEffect } from "react"; import styled from "styled-components"; import PropTypes from "prop-types"; import { useHistory } from "react-router-dom"; import { register, getMe } from "../../WebAPI"; import { AuthContext } from "../../contexts"; import Loading from "../../components/Loading"; import { LoadingContext } from "../../contexts"; const Input = styled.input` color: #373f27; margin-bottom: 5px; padding: 5px; border: 1px solid #cda34f; border-radius: 3px; &:focus { outline: none; } `; const Button = styled.button` padding: 5px 10px; background: #e9e7da; color: #636b46; border: 1px solid #636b46; border-radius: 3px; margin-top: 10px; &:hover { color: #373f27; cursor: pointer; } `; const Title = styled.h1` margin-top: 0px; `; const ErrMessage = styled.div` color: red; `; export default function HomePage() { const { setUser } = useContext(AuthContext); const { isLoading, setIsLoading } = useContext(LoadingContext); const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [nickname, setNickname] = useState(""); const [errMessage, setErrMessage] = useState(); const history = useHistory(); // 註冊成功 → 寫入 token + 導向首頁 const handleSubmit = (e) => { e.preventDefault(); if (isLoading) return; setIsLoading(true); setErrMessage(""); register(username, password, nickname).then((res) => { if (res.ok !== 1) { setIsLoading(false); return setErrMessage(res.message); } setAuthToken(res.token); getMe().then((response) => { if (response.ok !== 1) { setAuthToken(null); setIsLoading(false); return setErrMessage(response.message); } setUser(response.data); setIsLoading(false); history.push("/"); }); }); }; // 防止這頁還沒跑完其他頁也不能跑 useEffect(() => { return () => { setIsLoading(false); }; }, []); return ( <> {isLoading && <Loading />} <Title>會員註冊</Title> <form onSubmit={handleSubmit}> <div> 帳號: <br /> <Input value={username} onChange={(e) => setUsername(e.target.value)} /> </div> <div> 密碼: <br /> <Input type='password' value={password} onChange={(e) => setPassword(e.target.value)} /> </div> <div> 暱稱: <br /> <Input value={nickname} onChange={(e) => setNickname(e.target.value)} /> </div> {errMessage && <ErrMessage>{errMessage}</ErrMessage>} <Button>送出</Button> </form> </> ); }
angular.module("apiTool", ["ngAnimate", "ngRoute", "shared", "moduleMessageEditor"]) .run(["$rootScope", "$window", "application", "SpecFactory", function setupElectronMenu($rootScope, $window, application, SpecFactory) { $rootScope.application = application; var name = application.getName(); var updateMenu = function() { menu.items.forEach(function processMenus(menu) { if (menu.submenu) { if (menu.label === "File") { menu.submenu.items.forEach(function processSubMenu(subMenuItem) { var hasSpec = !!application.spec; if (subMenuItem.label === "New" || subMenuItem.label === "Open") { subMenuItem.enabled = !hasSpec; } else if (subMenuItem.label === "Save" || subMenuItem.label === "Save As" || subMenuItem.label === "Close") { subMenuItem.enabled = hasSpec; } }); } else if (menu.label === "Edit") { } else if (menu.label === "Tools") { } } }); if (application.spec) {} }; var confirmSpecChange = function(action, focusedWindow, callback) { application.dialog.showMessageBox(focusedWindow, { type: "question", buttons: ["OK", "Cancel"], title: "Unsaved Changes", message: "There are unsaved changes to the API.\n\n Are you sure you want to " + action + "?", cancelId: -1 }, function confirmResult(choice) { if (!choice) { callback(); } }); }; $window.onbeforeunload = function(e) { if (application.spec && application.spec.isDirty) { confirmSpecChange("exit", null, function() { application.spec.isDirty = false; // FIXME : Put this back in // $window.close(); }); e.returnValue = false; } }; var template = [{ label: 'File', submenu: [{ label: "New", accelerator: "CmdOrCtrl+N", click: function newProject(item, focusedWindow) { var selectWhatToCreate = function() { application.dialog.showMessageBox(focusedWindow, { type: "question", buttons: ["Product", "Entity", "Cancel"], title: "New", message: "Please select what you would like to create.", cancelId: -1 }, function createNew(choice) { $rootScope.$apply(function() { var update = false; switch (choice) { case 0: application.reset(); application.createProductSpec = SpecFactory.create("product"); update = true; break; case 1: application.reset(); application.spec = SpecFactory.create("module-class"); update = true; break; default: break; } if (update) { updateMenu(); } }); }); }; if (application.spec && application.spec.isDirty) { confirmSpecChange("create a new API", focusedWindow, selectWhatToCreate); } else { selectWhatToCreate(); } } }, { label: "Open", accelerator: "CmdOrCtrl+O", click: function openFileSelector(item, focusedWindow) { var openSpec = function() { application.dialog.showOpenDialog(focusedWindow, { properties: ["openFile"], defaultPath: application.filePath ? application.filePath : undefined, title: "Open Existing API" // FIXME : Should be whatever we call the file name: filters : [""] }, function fileSelected(files) { console.warn("File Selected", arguments); if (files && files.length === 1) { application.loadSpecFromFile(files[0], function(err, data) { if (err) { console.error("Couldn't load"); return; } $rootScope.$apply(function() { application.spec = SpecFactory.load(data); updateMenu(); }); }); } }); }; if (application.spec && application.spec.isDirty) { confirmSpecChange("open another API", focusedWindow, openSpec); } else { openSpec(); } } }, { label: 'Save', accelerator: 'CmdOrCtrl+S', enabled: false, click: function saveApiFile(fileItem, focusedWindow) { if (application.filePath) { $rootScope.$apply(function() { application.saveSpecToFile(); application.spec.isDirty = false; }); } else { application.dialog.showSaveDialog(focusedWindow, { defaultPath: application.filePath ? application.filePath : undefined, title: "Save API" }, function saveSelected(filePath) { if (filePath) { application.saveSpecToFile(filePath, function saveCompleted(err) { if (err) { console.error("Uh Oh", err); return; } $rootScope.$apply(function() { application.spec.isDirty = false; }); }); } }); } } }, { label: 'Save As', accelerator: 'CmdOrCtrl+Shift+S', enabled: false, click: function saveApiFile(fileItem, focusedWindow) { application.dialog.showSaveDialog(focusedWindow, { defaultPath: application.filePath ? application.filePath : undefined, title: "Save As" }, function saveSelected(filePath) { if (filePath) { application.saveSpecToFile(filePath, function saveCompleted(err) { if (err) { console.error("Uh Oh", err); return; } $rootScope.$apply(function() { application.spec.isDirty = false; }); }); } }); } }, { label: 'Close', // Ctrl+F4accelerator: 'CmdOrCtrl+', enabled: false, click: function closeApiFile(fileItem, focusedWindow) { var closeSpec = function() { $rootScope.$apply(function closeApp() { // FIXME : Check for any non-saved changes application.spec = null; updateMenu(); }); }; if (application.spec && application.spec.isDirty) { confirmSpecChange("close", focusedWindow, closeSpec); } else { closeSpec(); } } }, { type: "separator" }, { label: 'Exit', accelerator: 'CmdOrCtrl+Q', click: function closeApp(item, focusedWindow) { var exitApp = function() { if (focusedWindow) { focusedWindow.close(); } }; if (application.spec && application.spec.isDirty) { confirmSpecChange("exit", focusedWindow, exitApp); } else { exitApp(); } } }] }, { label: "Edit", submenu: [{ label: "Undo", accelerator: "CmdOrCtrl+Z", role: "undo", enabled: false }, { label: "Redo", accelerator: "Shift+CmdOrCtrl+Y", role: "redo", enabled: false }, { label: 'Revert', accelerator: 'Shift+CmdOrCtrl+R', enabled: false, click: function revertAllChanges() { } }] }, { label: "Tools", submenu: [{ label: "Refresh", accelerator: "CmdOrCtrl+R", click: function refresh(item, focusedWindow) { if (focusedWindow) { focusedWindow.reload(); } } }] }]; if (process.platform == 'darwin') { template.unshift({ label: name, submenu: [{ label: 'About ' + name, role: 'about' }, { type: 'separator' }, { label: 'Services', role: 'services', submenu: [] }, { type: 'separator' }, { label: 'Hide ' + name, accelerator: 'Command+H', role: 'hide' }, { label: 'Hide Others', accelerator: 'Command+Shift+H', role: 'hideothers' }, { label: 'Show All', role: 'unhide' }, { type: 'separator' }, { label: 'Quit', accelerator: 'Command+Q', click: function() { window.close(); } }, ] }); // Window menu. template[3].submenu.push({ type: 'separator' }, { label: 'Bring All to Front', role: 'front' }); } menu = application.Menu.buildFromTemplate(template); application.Menu.setApplicationMenu(menu); } ]);
var cars = ["saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars; var cars = ["saab", "Volvo", "BMW"]; document.getElementById("demo1").innerHTML = cars[0]; var cars = ["Saab", "Volvo", "BMW"]; cars[0] = "Toyota"; document.getElementById("demo2").innerHTML = cars; var persons = ["john", "blaster", 384]; document.getElementById("demo3").innerHTML = persons[2]; var persons = {firstName:"john", lastName:"blaster", age:"18"} document.getElementById("demo4").innerHTML = persons["firstName"]; var fruit = ["mango","apple","banana","starfruit"] document.getElementById("demo5").innerHTML = fruit.length; var fruit = ["mango", "apple", "banana","starfruit"]; var first = fruit[1]; document.getElementById("demo6").innerHTML = first; var fruit = ["mango", "apple","banana", "starfruit"]; var last = fruit[fruit.length-1]; document.getElementById("demo7").innerHTML = last; var fruit, text, fLen, i; fruit = ["banana", "orange", "apple", "mango"]; fLen = fruit.length; text = "<ul>"; for(i = 0; i < fLen; i++){ text+="<li>" + fruit[i] +"</li>" } text+=""; document.getElementById("demo8").innerHTML = text; var fruit, text; fruit = ["banana", "orange", "apple", "mango"]; text = "<ul>"; fruit.forEach(myFunction); text +="</ul>"; document.getElementById("demo9").innerHTML = text; function myFunction(value){ text+= "<li>"+ value + "</li>" } var fruits = ["banana", "orange", "apple", "mango"] document.getElementById("demo10").innerHTML = fruit; function myFunction(){ fruit.push("lemon"); document.getElementById("demo10").innerHTML = fruit; } var fruit = ["banana", "orange", "orange", "mango"] document.getElementById("demo11").innerHTML = fruit; function myFunction1(){ fruit[fruit.length]= "lemons"; document.getElementById("demo11").innerHTML =fruit ; } var fruit, text, fLen, i; fruit =["banana", "orange","apple","lemon"] fruit[6]="mango"; fLen = fruit.length; text =""; for (i=0; i<fLen; i++){ text += fruit[i] + "<br>"; } document.getElementById("demo12").innerHTML = text; var person = []; person[0]="john"; person[1]="doe"; person[2]= 15; document.getElementById("demo12").innerHTML = person[0]+" "+person.length var person = []; person ["firstName"]="john"; person["lastName"]="doe" person["age"]=18; document.getElementById("demo13").innerHTML = person[0] + " "+ person.length; var point = [15,235,523,43,63,634,643] document.getElementById("demo14").innerHTML = point[0]; // var point = new Array (0) // document.getElementById("15").innerHTML = point [0]; var fruit = ["banana","apple","mango","lemon"]; document.getElementById("demo16").innerHTML =typeof fruit; var fruit = ["banana","apple", "mango", "lemon"] document.getElementById("demo17").innerHTML = Array.isArray(fruit); var fruit = ["banana", "apple", "mango", "lemon"]; document.getElementById("demo18").innerHTML = isArray(fruit); function isArray(myArray){ return myArray.constructor.toString().indexOf("Array")> -1; } var fruit =["banana","lemon","apple", "mango"]; document.getElementById("demo19").innerHTML =fruit instanceof Array; var fruit = ["banana", "mango", "orange", "apple"] document.getElementById("demo20").innerHTML = fruit; function myFunction2(){ fruit.sort(); document.getElementById("demo20").innerHTML = fruit } var fruit = ["banana", "mango", "orange", "apple"]; document.getElementById("demo21").innerHTML = fruit; function myFunction3(){ fruit.sort(); fruit.reverse() document.getElementById("demo21").innerHTML = fruit; } var points =[423,324,35,35,332]; document.getElementById("demo22").innerHTML = points; function myFunction4(){ points.sort(function(a,b){return a-b}); document.getElementById("demo22").innerHTML = points; } var points = [21,34,465,64,36]; document.getElementById("demo23").innerHTML = points function myFunction5(){ points.sort(function(a,b){return b-a}) document.getElementById("demo23").innerHTML = point; } var points1 = [40,100,1,5,25,10]; document.getElementById("demo24").innerHTML = points1; function myFunction6(){ points1.sort(); document.getElementById("demo24").innerHTML = points1; } function myFunction7(){ points1.sort(function(a,b){return a-b}) document.getElementById("demo24").innerHTML = points1; } var points= [12,32,54,45,36,67] document.getElementById("demo25").innerHTML = points; function myFunction8(){ points.sort(function(a,b){return 0.5 - Math.random()}) document.getElementById("demo25").innerHTML = points; } var poin = [32,43,5,1,15,3]; poin.sort(function(a,b){return a-b}) document.getElementById("demo26").innerHTML = poin[0]; var poin1 = [ 123,234,343,25,235,1]; poin1.sort(function(a,b){return b-a}) document.getElementById("demo27").innerHTML = poin1[0] var point2 = [2,3,53,5,356,6432]; document.getElementById("demo28").innerHTML = myArrayMax(point2); function myArrayMax(arr){ return Math.max.apply(null, arr); } var point3 = [43,324,43543,5432]; document.getElementById("demo29").innerHTML = myArrayMin(point3); function myArrayMin(arr){ return Math.min.apply(null,arr); } var car = [ {type:"Volvo", year:"2016"}, {type:"saab", year:"2001"}, {type:"BMW", year:"2010"} ]; displaysCars(); function myFunction9(){ car.sort(function (a,b){return a.year-b.year}); displaysCars(); } function displaysCars(){ document.getElementById("demo30").innerHTML = car[0].type + " " + car[0].year +"<br>"+ car[1].type + " " + car[1].year +"<br>"+ car[2].type + " " + car[2].year +"<br>"; } var cars = [ {type:"Volvo", year:"2016"}, {type:"Saab", year:"2001"}, {type:"BMW", year:"2010"} ]; function myFunction10(){ cars.sort(function(a,b){ var x = a.type.toLowerCase(); var y = b.type.toLowerCase(); if ( x<y){return -1;} if (x>y){return 1;} return 0; }); displaysCars(); } function displaysCars(){ document.getElementById("demo31").innerHTML = cars[0].type + " " + cars[0].year + "<br>"+ cars[1].type + " " + cars[1].year + "<br>"+ cars[2].type + " " + cars[2].year; } var text = ""; var numbers = [32,343,5,3,234,]; numbers.forEach(myFunction11); document.getElementById("demo32").innerHTML = text; function myFunction11(value,index,array){ text= text+value+"<br>"; } var text1 = ""; var numbers =[23,355,46,64,654]; numbers.forEach(myFunction12); document.getElementById("demo33").innerHTML = text1; function myFunction12(value){ text1 = text1 + value +"<br>" } var numbers1 = [23,53,45,64,2,54]; var numbers2 = numbers1.map(myFunction13); document.getElementById("demo34").innerHTML = numbers2; function myFunction13(value,index,array){ return value *2; } var numbers3 = [23,43,4,54,6,46]; var numbers4 = numbers.map(myFunction13) document.getElementById("demo35").innerHTML = numbers4; function myFunction13(value){ return value *2 } var numbers5 = [234,54,35,646,]; var over50 = numbers5.filter(myFunction14) document.getElementById("demo36").innerHTML = over50; function myFunction14(value,index,array){ return value >50 } var numbers6 = [324,545,6,64,6,64]; var over30 = numbers6.filter(myFunction15) document.getElementById("demo37").innerHTML = over30; function myFunction15(value){ return value>30; } var numbers7 = [32,35,3,64,64]; var sum= numbers7.reduce(myFunction16); document.getElementById("demo38").innerHTML ="the sum is"+sum; function myFunction16(total,value,index,array){ return total + value; } var numbers8 = [324,35,3,64,45]; var sum1 = numbers8.reduce(myFunction17); document.getElementById("demo39").innerHTML = "the sum is" + sum; function myFunction17(total, value){ return total + value; } var numbers9 = [23,53,54,6,46]; var sum2 = numbers9.reduceRight(myFunction18); document.getElementById("demo40").innerHTML = "the sum is" +sum; function myFunction18(total, value){ return total + value; } var numbers10 = [234,53,35,423,64,43]; var first = numbers10.find(myFunction19); document.getElementById("demo41").innerHTML ="first number over 18 is"+first; function myFunction19(value,index,array){ return value>18 }
import React from "react"; import './PickFile.css' import MainHeader from './Header' import { Checkbox} from 'semantic-ui-react' import StepBar from './Components/StepBar' import RouteButtonNext from './Components/RouteButtonNext' import RouteButtonBack from './Components/RouteButtonBack' import axios from 'axios'; import Loading from './Components/Loading' import AlertMessage from './AlertMessage' class PickFile extends React.Component { constructor(props) { super(props) this.state = { selectedFile: null, filePath: null, studentsBeforeArrange: null, finalArr: null, showLoading: false } } onChangeHandler = (event) => { this.setState({ selectedFile: event.target.files[0], showLoading: true }, () => { this.handleUpload(); }); } handleUpload = () => { const data = new FormData() data.append('file', this.state.selectedFile) axios({ method: 'post', url: 'http://localhost:61009/Api/Upload', data: data, }).then(this.handleResponse) .catch(error => this.setState({ message: "הייתה שגיאה בחיבור לשרת", errorStatus: true, Loading: false, title: "שגיאה!" })); } handleResponse = (response) => { if (response.status != 201) { throw Error(response.statusText); } else { this.setState({ filePath: response.data }, () => { this.handleGetTeams(); }); } } handleGetTeams() { var prePath = this.state.filePath.substring(0, (this.state.filePath.length - 5)) var path = prePath.substring(14); axios({ method: 'Get', url: 'http://localhost:61009//api/NewGame/' + path, }) .then(this.handleRawData) .catch(error => this.setState({ message: "הייתה שגיאה בחיבור לשרת", errorStatus: true, Loading: false, title: "שגיאה!" })); } handleRawData = (response) => { if (response.status != 200) { throw Error(response.statusText); } else { this.setState({ studentsBeforeArrange: response.data }, () => { this.handleArrangeTeams() }); } } handleFaterState = (e) => { this.props.handleArrangedTeams(e) this.props.HandleNextPage() } //Aranging data from the excel into student groups handleArrangeTeams = () => { var teams = null; teams = this.ArangeData(this.state.studentsBeforeArrange); var finalArr = []; for (let i = 0; i < teams.length; i++) { const team = teams[i]; for (let y = 0; y < team.length; y++) { const item = team[y]; finalArr.push(item) } } this.setState({ finalArr: finalArr }, () => { this.handleFaterState(this.state.finalArr) }) } //Create teams out of excel file ArangeData(data) { var listGroup = []; var teamNum = 1; for (var i = 0; i < data.length; i++) { var tempGroup = data[i]; if (tempGroup[0] == "קבוצה") { listGroup.push(this.createGroup(data, i + 1, teamNum)); teamNum = teamNum + 1; } } return listGroup; } //Create 1 team to insert students to.. createGroup(data, index, teamNum) { var id = 0; var firstName = 1; var lastName = 2; var email = 3; var newGroup = []; if (this.props.lottery) { teamNum = 0 } for (var i = index; data.length; i++) { var tempStudent = data[i]; if (typeof tempStudent === "undefined" || tempStudent[id] == null || tempStudent[id] == "קבוצה") { break; } var objectStudent = this.createStudent(tempStudent[id], tempStudent[firstName], tempStudent[lastName], tempStudent[email], teamNum); newGroup.push(objectStudent); } return newGroup; } //Create student to insert into team createStudent(Id, FName, LName, Email, team) { return { Id, FName, LName, Email, EnableNot: true, team } } render() { const element = this.props.ArrangedTeams.length == 0 ? null : (<div onClick={this.props.HandleNextPage}> <RouteButtonNext /> </div>) const classname = this.props.ArrangedTeams.length == 0 ? "emptyDiv" : null if (this.state.showLoading) { return (<Loading Loading={"אנא המתן. נתונים נטענים.."}/>) } else { return ( <div > <StepBar stepStage={1} /> <MainHeader text={"בחירת קובץ"} /> <div className="divPickFile"> <h3>האם להגריל את הקבוצות?</h3> <Checkbox toggle checked={this.props.lottery} onChange={this.props.handleLottery} /> </div> <div className="divPickFile"> <input type="file" id="files" name="pic" accept=".xlsx" onChange={this.onChangeHandler} /> </div> <div className="contanerButtonsDiv"> <div onClick={this.props.HandlePreviousPage}> <RouteButtonBack /> </div> <div className={classname}>{element}</div> </div> <AlertMessage errorStatus={this.state.errorStatus} handleErrorsToFalse={this.handleErrorsToFalse} message={this.state.message} title={this.state.title} /> </div> ) } } } export default PickFile;
export default { data: () => ({ }), created: function () { }, methods : { } };
import { LightningElement, track } from 'lwc'; import { registerListener, unregisterAllListeners } from 'c/pubsub'; export default class TestLWC1 extends LightningElement { @track Message; connectedCallback() { registerListener('messageFromSpace', this.handleMessage, this); } handleMessage(myMessage) { this.Message = myMessage; //Add your code here } disconnectCallback() { unregisterAllListeners(this); } }
'use strict' const express = require('express'); var api= express.Router(); var middlewareAuth = require("../middlewares/authentication") var middlewareUploader = require("../middlewares/multimediaUploader") const GaleriaCotroller = require("../controllers/galeria.controller") api.put("/:idGaleria", middlewareAuth.authenticate("jwt",{session:false}), middlewareUploader.cargaFotosGaleria.array("fotos"), GaleriaCotroller.CargaFotos) api.get("/:idGaleria/:file",GaleriaCotroller.getFoto) api.delete("/:idGaleria/:idFoto",middlewareAuth.authenticate("jwt",{session:false}),GaleriaCotroller.eliminaFoto) module.exports = api;
"use strict"; $(document).ready(function () { let users = [ { username: 'mdklanica', password: 'captainkirk', emailaddress: 'mdklanica@gmail.com', aboutuser: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius est incidunt modi praesentium' + ' reprehenderit similique tempora temporibus vitae voluptate voluptatem! Beatae distinctio fugiat laudantium repudiandae voluptatibus. Blanditiis eaque libero porro.' }, { username: 'johnnywaco', password: 'mybloodyvalentine', emailaddress: 'johnnywaco@gmail.com', aboutuser: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius est incidunt modi praesentium' + ' reprehenderit similique tempora temporibus vitae voluptate voluptatem! Beatae distinctio fugiat laudantium repudiandae voluptatibus. Blanditiis eaque libero porro.' }, { username: 'marcus-marcus', password: 'olblockhead', emailaddress: 'marcus@yahoo.com', aboutuser: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius est incidunt modi praesentium' + ' reprehenderit similique tempora temporibus vitae voluptate voluptatem! Beatae distinctio fugiat laudantium repudiandae voluptatibus. Blanditiis eaque libero porro.' }, { username: 'mrwenner', password: 'pigeonsarecool', emailaddress: 'garland@gmail.com', aboutuser: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius est incidunt modi praesentium' + ' reprehenderit similique tempora temporibus vitae voluptate voluptatem! Beatae distinctio fugiat laudantium repudiandae voluptatibus. Blanditiis eaque libero porro.' } ] $('#main-display').empty() let html = ""; for (let i = 0; i <= users.length - 1; i++) { let userName = users[i].username; let passWord = users[i].password; let emailAddress = users[i].emailaddress; let aboutUser = users[i].aboutuser; console.log(i, userName, passWord, emailAddress, aboutUser); html += `<h2>Username: ${userName}</h2>` + `<h3>Email: ${emailAddress}</h3>` + `<h4>Password: ${passWord}</h4>` + `<p>Bio: ${aboutUser}</p>` } $("#main-display").append(html); $('#add-user').click(function (e) { e.preventDefault(); let userName = $('#user-name').val(); let emailAddress = $('#email-address').val(); let passWord = $('#pass-word').val(); let aboutUser = $('#about-user').val(); }) });
var CmdType = { Joint: "Joint", PTP: "PTP", Line: "Line", Shift_X: "Shift_X", Shift_Y: "Shift_Y", Shift_Z: "Shift_Z", Rotate_X: "Rotate_X", Rotate_Y: "Rotate_Y", Rotate_Z: "Rotate_Z", Vaccum: "Vaccum", Base_Init: "Base_Init", Base_Stop: "Base_Stop", Base_Vel : "Base_Vel", Base_Pos_Index_1: "Base_Pos_Index_1", Base_Pos_Index_2: "Base_Pos_Index_2", Base_Pos_Index_3: "Base_Pos_Index_3" }; function command_selected(cmd){ //console.log('cmd='+cmd); var command_select = '<select class="options_cmd_none" disabled="disabled" onchange="Cmd_change(this)">'+ '<option value="Joint"'+((cmd==CmdType.Joint)?"selected":"")+'>Joint</option>'+ '<option value="PTP"'+((cmd==CmdType.PTP)?"selected":"")+'>PTP</option>'+ '<option value="Line"'+((cmd==CmdType.Line)?"selected":"")+'>Line</option>'+ '<option value="Shift_X"'+((cmd==CmdType.Shift_X)?"selected":"")+'>Shift_X</option>'+ '<option value="Shift_Y"'+((cmd==CmdType.Shift_Y)?"selected":"")+'>Shift_Y</option>'+ '<option value="Shift_Z"'+((cmd==CmdType.Shift_Z)?"selected":"")+'>Shift_Z</option>'+ '<option value="Rotate_X"'+((cmd==CmdType.Rotate_X)?"selected":"")+'>Rotate_X</option>'+ '<option value="Rotate_Y"'+((cmd==CmdType.Rotate_Y)?"selected":"")+'>Rotate_Y</option>'+ '<option value="Rotate_Z"'+((cmd==CmdType.Rotate_Z)?"selected":"")+'>Rotate_Z</option>'+ '<option value="Vaccum"'+((cmd==CmdType.Vaccum)?"selected":"")+'>Vaccum</option>'+ '<option value="-----------------------">----------------------</option>'+ '<option value="Base_Init"'+((cmd==CmdType.Base_Init)?"selected":"")+'>Base_Init</option>'+ '<option value="Base_Stop"'+((cmd==CmdType.Base_Stop)?"selected":"")+'>Base_Stop</option>'+ '<option value="Base_Vel"'+((cmd==CmdType.Base_Vel)?"selected":"")+'>Base_Vel</option>'+ '<option value="Base_Pos_Index_1"'+((cmd==CmdType.Base_Pos_Index_1)?"selected":"")+'>Base_Pos_Index_1</option>'+ '<option value="Base_Pos_Index_2"'+((cmd==CmdType.Base_Pos_Index_2)?"selected":"")+'>Base_Pos_Index_2</option>'+ '<option value="Base_Pos_Index_3"'+((cmd==CmdType.Base_Pos_Index_3)?"selected":"")+'>Base_Pos_Index_3</option>'+ '</select>'; return command_select; } var addbtn = document.getElementById("addbtn"); var edit_img = '<img name="edit_btn" src="img/edit.png" onclick="edit_Cmd(this)"/>'; var true_img = '<img name="true_btn" src="img/true.png" class="img_show" onclick="save_Cmd(this)"/>'; var false_img = '<img name="false_btn" src="img/false.png" class="img_show" onclick="break_Cmd(this)"/>'; var delete_img = '<img name="delete_opt" src="img/delete.png" style="width:20px; height:auto; text-align:right;" onclick="delete_Cmd(this)"/>'; var teach_a = '<button name="teach_btn" class="btn btn-info btn-block" style="width:80px; display:none;" onclick="teach_click(this)"><span class="glyphicon glyphicon-pushpin"></span>Teach</button>'; var cmd_id; function hide_all(){ $("#block").hide(); $("#vaccum_block").hide(); $("#shift_block").hide(); $("#base_vel_block").hide(); } function order_list(){ var num = 1; $('#teach_table tr').each(function(){ cmd_id = 'cmd_' + num; $(this).attr('id',cmd_id); if($(this).children('td.order').length == 0){ $(this).children("td:first").before('<td class="order" onclick="copy(this)">'+$('#teach_table').children().length+'</td>'); }else{ $(this).children("td:first").remove(); $(this).children("td:first").before('<td class="order" onclick="copy(this)">'+num+'</td>'); } num++; }); mov_it(); } function copy(tr){ var tar_id = "cmd_"+$(tr)[0].outerText; var mod = $('tr#'+tar_id).find('[name=cmd_mod]').children('select').val(); $("#cmd_select").val(mod); cmd_select_change(tar_id,mod); } function mov_it(){ var mov = $("#move_cmd").prop("checked"); $('#teach_table tr').each(function(){ if(mov == true){ $(this).children("td:first").attr('draggable',true); $(this).children("td:first").attr('ondragstart','drag(event)'); $(this).children("td:first").attr('ondragenter','dragEnter(event)'); $(this).children("td:first").attr('ondragleave','dragLeave(event)'); }else{ $(this).children("td:first").removeAttr('draggable',true); $(this).children("td:first").removeAttr('ondragstart','drag(event)'); $(this).children("td:first").removeAttr('ondragenter','dragEnter(event)'); $(this).children("td:first").removeAttr('ondragleave','dragLeave(event)'); } }); } $("#move_cmd").change(function(){ console.log("Order Changed"); mov_it(); }); $("#cmd_select").change(function() { cmd_select_change(); }); function cmd_select_change(ev,mod){ var cmd = $("#cmd_select").val(); hide_all(); if(cmd==CmdType.Joint || cmd==CmdType.PTP || cmd==CmdType.Line){ $("#block").show(); $("#block").css("display","inline"); }else if(cmd==CmdType.Vaccum){ $("#vaccum_block").show(); $("#vaccum_block").css("display","inline"); }else if(cmd==CmdType.Shift_X || cmd==CmdType.Shift_Y || cmd==CmdType.Shift_Z || cmd==CmdType.Rotate_X || cmd==CmdType.Rotate_Y || cmd==CmdType.Rotate_Z){ $("#shift_block").show(); $("#shift_block").css("display","inline"); }else if(cmd==CmdType.Base_Vel){ $("#base_vel_block").show(); $("#base_vel_block").css("display","inline"); } if(ev != undefined){ if(mod==CmdType.Joint || mod==CmdType.PTP || mod==CmdType.Line){ var i = 1; $('#'+ev).children("td.SubCmd").children("input").each(function(){ $("#block_"+i++).val($(this).val()); }); }else if(mod==CmdType.Vaccum){ $("#vaccum_select").val($('#'+ev).find('[name=vaccum_select]').val()); }else if(mod==CmdType.Shift_X || mod==CmdType.Shift_Y || mod==CmdType.Shift_Z || mod==CmdType.Rotate_X || mod==CmdType.Rotate_Y || mod==CmdType.Rotate_Z){ $("#shift_val").val($('#'+ev).children("td.SubCmd").children("input").val()); } } } function get_block_tr(option_cmd,val){ var sub_cmd = ''; if(option_cmd==CmdType.Joint || option_cmd==CmdType.PTP || option_cmd==CmdType.Line){ if(val==undefined){ for(var i=1;i<=6;i++){ var t_id = '#block_'+i; sub_cmd += '<input class="block_sty_none" type="number" value="'+$(t_id).val()+'"readonly>'; } }else{ for(var i=0;i<6;i++){ sub_cmd += '<input class="block_sty_none" type="number" value="'+val[i]+'"readonly>\n'; } } }else if(option_cmd==CmdType.Vaccum){ if(val==undefined){ sub_cmd = '<select class="options_cmd_none" name="vaccum_select" disabled="disabled">' + '<option value="On"'+(($('#vaccum_select').val() == "On")?"selected":"")+'>On</option>'+ '<option value="Off"'+(($('#vaccum_select').val() == "Off")?"selected":"")+'>Off</option>' + '</select>'; }else{ sub_cmd = '<select class="options_cmd_none" name="vaccum_select" disabled="disabled">' + '<option value="On"'+((val==true)?"selected":"")+'>On</option>'+ '<option value="Off"'+((val==false)?"selected":"")+'>Off</option>' + '</select>'; //console.log("in vaccum",val); if(val == 'true') console.log("vaccum == true"); } }else if(option_cmd==CmdType.Shift_X || option_cmd==CmdType.Shift_Y || option_cmd==CmdType.Shift_Z|| option_cmd==CmdType.Rotate_X || option_cmd==CmdType.Rotate_Y || option_cmd==CmdType.Rotate_Z){ if(val==undefined){ sub_cmd = '<input class="block_sty_none" type="number" value="'+$('#shift_val').val()+'"readonly>'; }else{ sub_cmd = '<input class="block_sty_none" type="number" value="'+val+'"readonly>'; } }else if(option_cmd==CmdType.Base_Vel ){ if(val==undefined){ for(var i=1;i<=3;i++){ var t_id = '#base_vel_block_'+i; sub_cmd += '<input class="block_sty_none" type="number" value="'+$(t_id).val()+'"readonly>'; } }else{ for(var i=0;i<3;i++){ sub_cmd += '<input class="block_sty_none" type="number" value="'+val[i]+'"readonly>\n'; } } } var add_tr = '<tr class="font_black" id="" >' + '<td name="cmd_mod">'+command_selected(option_cmd)+'</td>'+ '<td class="SubCmd">'+sub_cmd+'</td>'+ '<td>'+edit_img+ true_img + false_img + teach_a + '</td>'+ '<td style="text-align:center;">'+delete_img+'</td>'+ '</tr>'; return add_tr; } addbtn.onclick = function(){ var cmd = $("#cmd_select").val(); var tr_html = ''; if(cmd != 'Choose') tr_html = get_block_tr(cmd); //console.log(tr_html); $('#teach_table').append(tr_html); $('#teach_table').scrollTop($('#teach_table')[0].scrollHeight); order_list(); } var cmd_edit = new Array; var vac_cmd; function Cmd_change(edit,val_6){ var cmd = $(edit).val(); var sub_cmd = ''; if(cmd==CmdType.Joint || cmd==CmdType.PTP || cmd==CmdType.Line){ if(val_6==undefined){ for(var i=1;i<=6;i++){ var t_id = '#block_'+i; sub_cmd += '<input class="block_sty" type="number" value="'+$(t_id).val()+'">'; } }else{ for(var i=0;i<6;i++){ sub_cmd += '<input class="block_sty" type="number" value="'+val_6[i]+'">\n'; } } }else if(cmd==CmdType.Vaccum){ sub_cmd = '<select class="options_cmd" name="vaccum_select">' + '<option value="On"'+(($('#vaccum_select').val() == "On")?"selected":"")+'>On</option>'+ '<option value="Off"'+(($('#vaccum_select').val() == "Off")?"selected":"")+'>Off</option>' + '</select>'; }else if(cmd==CmdType.Shift_X || cmd==CmdType.Shift_Y || cmd==CmdType.Shift_Z|| cmd==CmdType.Rotate_X || cmd==CmdType.Rotate_Y || cmd==CmdType.Rotate_Z){ sub_cmd = '<input class="block_sty" type="number" value="'+$('#shift_val').val()+'">'; } $(edit).parents("tr").children('.SubCmd').children().remove(); $(edit).parents("tr").children('.SubCmd').append(sub_cmd); } function edit_Cmd(edit){ var m_cmd_id = $(edit).parents('tr').attr('id'); console.log("m_cmd_id="+m_cmd_id); $('#'+m_cmd_id).find('[name=edit_btn]').hide(); $('#'+m_cmd_id).find('[name=true_btn]').show(); $('#'+m_cmd_id).find('[name=false_btn]').show(); $('#'+m_cmd_id).find('[name=teach_btn]').show(); $('#'+m_cmd_id).find('[name=teach_btn]').css('display','inline'); //var mod = $('#'+m_cmd_id).children("[name=cmd_mod]").text(); var mod = $('tr#'+m_cmd_id).find('[name=cmd_mod]').children('select').val(); $('#'+m_cmd_id).find('[name=cmd_mod]').children('select').attr("class","options_cmd"); $('#'+m_cmd_id).find('[name=cmd_mod]').children('select').removeAttr("disabled"); var i = 0; if(mod=='Base_Vel' || mod==CmdType.Joint || mod==CmdType.PTP || mod==CmdType.Line || mod==CmdType.Shift_X || mod==CmdType.Shift_Y || mod==CmdType.Shift_Z || mod==CmdType.Rotate_X || mod==CmdType.Rotate_Y || mod==CmdType.Rotate_Z || mod==CmdType.Base_Vel ){ $('#'+m_cmd_id).children("td.SubCmd").children("input").each(function(){ $(this).removeAttr("readonly"); //$(this).css("border-style","inset"); $(this).removeClass("block_sty_none"); $(this).addClass("block_sty"); cmd_edit[i++] = $(this).val(); }); }else if(mod==CmdType.Vaccum){ $('#'+m_cmd_id).find('[name=vaccum_select]').removeAttr("disabled"); $('#'+m_cmd_id).find('[name=vaccum_select]').attr("class","options_cmd"); vac_cmd = $('#'+m_cmd_id).find('[name=vaccum_select]').val(); } } function save_Cmd(edit){ var m_cmd_id = $(edit).parents('tr').attr('id'); console.log("m_cmd_id="+m_cmd_id); $('#'+m_cmd_id).find('[name=edit_btn]').show(); $('#'+m_cmd_id).find('[name=true_btn]').hide(); $('#'+m_cmd_id).find('[name=false_btn]').hide(); $('#'+m_cmd_id).find('[name=teach_btn]').hide(); var mod = $('tr#'+m_cmd_id).find('[name=cmd_mod]').children('select').val(); $('#'+m_cmd_id).find('[name=cmd_mod]').children('select').attr("class","options_cmd_none"); $('#'+m_cmd_id).find('[name=cmd_mod]').children('select').attr("disabled","disabled"); if(mod==CmdType.Joint || mod==CmdType.PTP || mod==CmdType.Line || mod==CmdType.Shift_X || mod==CmdType.Shift_Y || mod==CmdType.Shift_Z || mod==CmdType.Rotate_X || mod==CmdType.Rotate_Y || mod==CmdType.Rotate_Z || mod==CmdType.Base_Vel){ $('#'+m_cmd_id).children("td.SubCmd").children("input").each(function(){ //console.log("in save"); $(this).attr("readonly","readonly"); $(this).addClass("block_sty_none"); $(this).removeClass("block_sty"); $(this).attr("value",$(this).val()); }); }else if(mod==CmdType.Vaccum){ $('#'+m_cmd_id).find('[name=vaccum_select]').attr("disabled","disabled"); $('#'+m_cmd_id).find('[name=vaccum_select]').attr("class","options_cmd_none"); } } function break_Cmd(edit){ var m_cmd_id = $(edit).parents('tr').attr('id'); console.log("m_cmd_id="+m_cmd_id); $('#'+m_cmd_id).find('[name=edit_btn]').show(); $('#'+m_cmd_id).find('[name=true_btn]').hide(); $('#'+m_cmd_id).find('[name=false_btn]').hide(); $('#'+m_cmd_id).find('[name=teach_btn]').hide(); var mod = $('tr#'+m_cmd_id).find('[name=cmd_mod]').children('select').val(); $('#'+m_cmd_id).find('[name=cmd_mod]').children('select').attr("class","options_cmd_none"); $('#'+m_cmd_id).find('[name=cmd_mod]').children('select').attr("disabled","disabled"); var i = 0; if(mod==CmdType.Joint || mod==CmdType.PTP || mod==CmdType.Line || mod==CmdType.Shift_X || mod==CmdType.Shift_Y || mod==CmdType.Shift_Z || mod==CmdType.Rotate_X || mod==CmdType.Rotate_Y || mod==CmdType.Rotate_Z || mod==CmdType.Base_Vel){ $('#'+m_cmd_id).children("td.SubCmd").children("input").each(function(){ $(this).val(cmd_edit[i++]); $(this).attr("readonly","readonly"); $(this).addClass("block_sty_none"); $(this).removeClass("block_sty"); }); }else if(mod==CmdType.Vaccum){ $('#'+m_cmd_id).find('[name=vaccum_select]').val(vac_cmd); $('#'+m_cmd_id).find('[name=vaccum_select]').attr("disabled","disabled"); $('#'+m_cmd_id).find('[name=vaccum_select]').attr("class","options_cmd_none"); } } function delete_Cmd(edit){ var m_cmd_id = $(edit).parents('tr').attr('id'); console.log("m_cmd_id="+m_cmd_id); $('#'+m_cmd_id).remove(); order_list(); } function allowDrop(ev) { ev.preventDefault(); } var first_ev; function drag(ev) { console.log("drag",ev); first_ev = ev.target.outerText; } function drop(ev) { ev.preventDefault(); order_list(); } function dragEnter(ev) { var ty_id = ev.target.outerText; if(ev.offsetY < 10) $('#cmd_'+first_ev).insertAfter('#cmd_'+ty_id); else $('#cmd_'+first_ev).insertBefore('#cmd_'+ty_id); } function dragLeave(ev) { } $("#show_btn").click(function(){ $("#test_json_data").slideToggle("slow"); }); //=========================================================================================== //=========================================================================================== //=========================================================================================== //=========================================================================================== function get_twist(){ var twist = new ROSLIB.Message({ linear : { x : 0.0, y : 0.0, z : 0.0, }, angular : { x : 0.0, y : 0.0, z : 0.0, } }); return twist; } $("#run_btn").click(function() { $(this).removeClass('active'); $(this).addClass('disabled'); var mlist = []; //get each command $('#teach_table tr').each(function(){ var cmd_mod = $(this).find('[name=cmd_mod]').children('select').val(); console.log(cmd_mod); //-------------CmdType.Joint-------------// if(cmd_mod==CmdType.Joint){ var float_ary = []; $(this).children("td.SubCmd").children("input").each(function(){ var t_float = parseFloat( $(this).val() ); //console.log('$(this).val()='+t_float); float_ary.push(t_float); }); var cmd_msg = new ROSLIB.Message({ cmd : CmdType.Joint, joint_position : float_ary }); mlist.push(cmd_msg); //-------------CmdType.PTP-------------// }else if(cmd_mod==CmdType.PTP || cmd_mod==CmdType.Line){ var refer = $(this).children("td.SubCmd"); var twist = new ROSLIB.Message({ linear : { x : parseFloat(refer.children("input:nth-child(1)").val()), y : parseFloat(refer.children("input:nth-child(2)").val()), z : parseFloat(refer.children("input:nth-child(3)").val()), }, angular : { x : parseFloat(refer.children("input:nth-child(4)").val()), y : parseFloat(refer.children("input:nth-child(5)").val()), z : parseFloat(refer.children("input:nth-child(6)").val()), } }); console.log('twist.linear.x ='+ twist.linear.x +',y=' + twist.linear.y + ',z=' + twist.linear.z); var cmd_msg = new ROSLIB.Message({ cmd : cmd_mod, pose : twist }); mlist.push(cmd_msg); //-------------CmdType.Shift_X-------------// }else if(cmd_mod==CmdType.Shift_X || cmd_mod==CmdType.Shift_Y || cmd_mod==CmdType.Shift_Z|| cmd_mod==CmdType.Rotate_X || cmd_mod==CmdType.Rotate_Y || cmd_mod==CmdType.Rotate_Z ){ var data = $(this).children("td.SubCmd").children("input").val(); var twist = get_twist(); if(cmd_mod==CmdType.Shift_X){ twist.linear.x = parseFloat(data); }else if(cmd_mod==CmdType.Shift_Y){ twist.linear.y = parseFloat(data); }else if(cmd_mod==CmdType.Shift_Z){ twist.linear.z = parseFloat(data); }else if(cmd_mod==CmdType.Rotate_X){ twist.angular.x = parseFloat(data); }else if(cmd_mod==CmdType.Rotate_Y){ twist.angular.y = parseFloat(data); }else if(cmd_mod==CmdType.Rotate_Z){ twist.angular.z = parseFloat(data); } //console.log('twist.linear.x ='+ twist.linear.x +',y=' + twist.linear.y + ',z=' + twist.linear.z); console.log(cmd_mod,parseFloat(data)); var cmd_msg = new ROSLIB.Message({ cmd : cmd_mod, pose : twist }); mlist.push(cmd_msg); //-------------CmdType.Vaccum-------------// }else if(cmd_mod==CmdType.Vaccum){ var vaccum_yn = $(this).find('[name=vaccum_select]').val()=='On' ? true:false; var cmd_msg = new ROSLIB.Message({ cmd : CmdType.Vaccum, vaccum : vaccum_yn }); mlist.push(cmd_msg); }else if(cmd_mod==CmdType.Base_Vel ){ var refer = $(this).children("td.SubCmd"); var twist = new ROSLIB.Message({ linear : { x : parseFloat(refer.children("input:nth-child(1)").val()), y : parseFloat(refer.children("input:nth-child(2)").val()), z : 0, }, angular : { x : 0, y : 0, z : parseFloat(refer.children("input:nth-child(3)").val()), } }); //console.log('twist.linear.x ='+ twist.linear.x +',y=' + twist.linear.y + ',z=' + twist.linear.z); var cmd_msg = new ROSLIB.Message({ cmd : cmd_mod, pose : twist }); mlist.push(cmd_msg); //-------------CmdType.Shift_X-------------// }else if(cmd_mod==CmdType.Base_Init || cmd_mod==CmdType.Base_Stop || cmd_mod==CmdType.Base_Pos_Index_1 || cmd_mod==CmdType.Base_Pos_Index_2 || cmd_mod==CmdType.Base_Pos_Index_3){ var cmd_msg = new ROSLIB.Message({ cmd : cmd_mod }); mlist.push(cmd_msg); } }); //console.log('teachModeClient='+teachModeClient); var goal = new ROSLIB.Goal({ actionClient : teachModeClient, goalMessage : { cmd_list : mlist } }); goal.on('feedback', teach_feedback); goal.on('result', teach_result); teach_result_trigger = false; now_exe_id = 0; goal.send(); }); $("#file_save_btn").click(function() { $(this).removeClass('active'); $(this).addClass('disabled'); var save_data = "{\n"; var cmd_count = $('#teach_table tr').length; $('#teach_table tr').each(function(index,element) { var cmd_mod = $(this).children('[name=cmd_mod]').children('select').val(); //-------------CmdType.Joint-------------// save_data += '\t"'+$(this).children('td.order').html()+'":{\n'; if(cmd_mod==CmdType.Joint || cmd_mod==CmdType.PTP || cmd_mod==CmdType.Line){ save_data += '\t\t"cmd": "'+cmd_mod+'",\n'; // Joint or PTP or Line START save_data += '\t\t"val_6": '; //val_6 Start var float_ary = []; $(this).children("td.SubCmd").children("input").each(function() { var t_float = parseFloat( $(this).val() ); float_ary.push( t_float ); }); save_data += '[' + float_ary.toString()+"]\n"; //val_6 End //-------------CmdType.Shift-------------// }else if(cmd_mod==CmdType.Shift_X || cmd_mod==CmdType.Shift_Y || cmd_mod==CmdType.Shift_Z || cmd_mod==CmdType.Rotate_X || cmd_mod==CmdType.Rotate_Y || cmd_mod==CmdType.Rotate_Z ){ //save_data += '\t"'+cmd_mod+'":{\n'; // Shift_X or Shift_Y or Shift_Z START save_data += '\t\t"cmd": "'+cmd_mod+'",\n'; // Joint or PTP or Line START save_data += '\t\t"val": '; //Val Start var refer = $(this).children("td.SubCmd").children("input"); var val = refer.val(); save_data += val ; //Val End console.log('refer.prop("pose")='+refer.attr('pose')); if(refer.attr('pose')!=undefined){ save_data += ',\n'; save_data += '\t\t"pose": ' + '[' + refer.attr('pose') +"]\n"; //pose } save_data += '\n'; }else if(cmd_mod==CmdType.Vaccum){ //save_data += '\t"'+cmd_mod+'":{\n'; // Vaccum START save_data += '\t\t"cmd": "'+cmd_mod+'",\n'; // Joint or PTP or Line START save_data += '\t\t"val": '; //Val Start var vaccum_yn = $(this).find('[name=vaccum_select]').val()=='On' ? true:false; save_data += vaccum_yn +"\n"; //Val End //save_data += '\t},\n'; // Vaccum END }else if(cmd_mod==CmdType.Base_Vel){ save_data += '\t\t"cmd": "'+cmd_mod+'",\n'; //Base_Vel save_data += '\t\t"val_3": '; //val_3 Start var float_ary = []; $(this).children("td.SubCmd").children("input").each(function() { var t_float = parseFloat( $(this).val() ); float_ary.push( t_float ); }); save_data += '[' + float_ary.toString()+"]\n"; //val_3 End }else if(cmd_mod==CmdType.Base_Init || cmd_mod==CmdType.Base_Stop || cmd_mod==CmdType.Base_Pos_Index_1 || cmd_mod==CmdType.Base_Pos_Index_2 || cmd_mod==CmdType.Base_Pos_Index_3){ save_data += '\t\t"cmd": "'+cmd_mod+'"\n'; //Base_Vel } if(index==cmd_count-1){ save_data += '\t}\n'; }else{ save_data += '\t},\n'; } }); save_data += "}"; var request = new ROSLIB.ServiceRequest({ cmd : "Teach:SaveFile", req_s : save_data }); ui_client.callService(request, function(res) { console.log( 'Result : ' + res.result); $("#file_save_btn").removeClass('disabled'); $("#file_save_btn").addClass('active'); }); $("#test_json_data").val(save_data); }); $("#file_read_btn").click(function() { $(this).removeClass('active'); $(this).addClass('disabled'); var request = new ROSLIB.ServiceRequest({ cmd : "Teach:ReadFile" }); ui_client.callService(request, function(res) { console.log('Result : ' + res.result); cmd_id = 0; $('#teach_table').html(''); $("#test_json_data").val(res.res_s); var json = JSON.parse(res.res_s); for (var index in json) { var cmd = json[index].cmd; //console.log('cmd : ' + cmd); var tr_html = ''; if(cmd==CmdType.PTP || cmd==CmdType.Line|| cmd==CmdType.Joint){ tr_html = get_block_tr(cmd,json[index].val_6); }else if(cmd==CmdType.Vaccum){ tr_html = get_block_tr(cmd,json[index].val); }else if(cmd==CmdType.Shift_X || cmd==CmdType.Shift_Y || cmd==CmdType.Shift_Z|| cmd==CmdType.Rotate_X || cmd==CmdType.Rotate_Y || cmd==CmdType.Rotate_Z ){ tr_html = get_block_tr(cmd,json[index].val,json[index].pose); }else if(cmd==CmdType.Base_Vel){ tr_html = get_block_tr(cmd,json[index].val_3); }else if(cmd==CmdType.Base_Init || cmd==CmdType.Base_Stop || cmd==CmdType.Base_Pos_Index_1 || cmd==CmdType.Base_Pos_Index_2 || cmd==CmdType.Base_Pos_Index_3 ){ tr_html = get_block_tr(cmd); } $('#teach_table').append(tr_html); order_list(); } $("#file_read_btn").removeClass('disabled'); $("#file_read_btn").addClass('active'); }); }); function parse_json_2_cmd_list(cmd,val){ var tr_html = ''; console.log('cmd='+cmd+',val='+val) if(cmd==CmdType.PTP || cmd==CmdType.Line){ tr_html = get_block_tr(cmd,val.val_6); }else if(cmd==CmdType.Vaccum){ tr_html = get_block_tr(val.Val); }else if(cmd==CmdType.Shift_X || cmd==CmdType.Shift_Y || cmd==CmdType.Shift_Z || cmd==CmdType.Rotate_X || cmd==CmdType.Rotate_Y || cmd==CmdType.Rotate_Z ){ tr_html = get_block_tr(cmd,val.Val); }else{ return; } $('#teach_table').append(tr_html); } function teach_click(t){ var m_cmd_id = $(t).parents('tr').attr('id'); console.log("m_cmd_id="+m_cmd_id); var mod; if(m_cmd_id == undefined){ mod = $("#cmd_select").val(); }else{ mod = $('#'+m_cmd_id).children('[name=cmd_mod]').children('select').val(); } //console.log("mod="+mod); var i = 0; if(mod==CmdType.Joint){ var i = 0; $('#'+m_cmd_id).children("td.SubCmd").children("input").each(function(){ //$(this).val(joint_ary[i++].toFixed(5)); //toFixed ex: 0.123456789 -> 0.1234 console.log(joint_ary[i]); $(this).val(joint_ary[i++]); //ex: 0.123456789 -> 0.1234 }); }else if(mod==CmdType.PTP || mod==CmdType.Line){ var request = new ROSLIB.ServiceRequest({ cmd : "Teach:EEF_Pose", }); ui_client.callService(request, function(res) { var l = res.pose.linear; var a = res.pose.angular; console.log( 'Result : ' + res.result); console.log( 'Pose : ' + l.x + "," + l.y + "," + l.z + "," + a.x + "," + a.y + "," + a.z ); if(m_cmd_id == undefined){ var val_6 = [l.x,l.y,l.z,a.x,a.y,a.z]; if(mod != 'Choose') tr_html = get_block_tr(mod,val_6); $('#teach_table').append(tr_html); }else{ var refer = $('#'+m_cmd_id).children("td.SubCmd"); refer.children("input:nth-child(1)").val(l.x.toFixed(2)); refer.children("input:nth-child(2)").val(l.y.toFixed(2)); refer.children("input:nth-child(3)").val(l.z.toFixed(2)); refer.children("input:nth-child(4)").val(a.x.toFixed(2)); refer.children("input:nth-child(5)").val(a.y.toFixed(2)); refer.children("input:nth-child(6)").val(a.z.toFixed(2)); } }); }else if(mod==CmdType.Shift_X || mod==CmdType.Shift_Y || mod==CmdType.Shift_Z){ var find = false; var now_cmd_id = m_cmd_id; var request; var pre_pose = []; console.log(m_cmd_id); do{ var pre_id = $('#'+now_cmd_id).prev("tr").prop("id"); if(pre_id==undefined){ console.error('Teach Click -> Cannot find previous position'); return; } //get previous tr's command var pre_mod = $('#'+pre_id).children('[name=cmd_mod]').children('select').val(); if(pre_mod==CmdType.PTP || pre_mod==CmdType.Line){ var refer = $('#'+pre_id).children("td.SubCmd"); refer.children('input').each(function() { var t_float = parseFloat( $(this).val() ); pre_pose.push( t_float ); }); find = true; }else if(pre_mod==CmdType.Shift_X || pre_mod==CmdType.Shift_Y || pre_mod==CmdType.Shift_Z){ var pre_pose_str = $('#'+pre_id).children("td.SubCmd").children("input").attr('pose'); console.log('pre_pose_str='+pre_pose_str); if(pre_pose_str!=undefined){ var pre_pose_ary = pre_pose_str.split(","); for(var ind in pre_pose_ary){ console.log('str='+pre_pose_ary[ind]); pre_pose.push( parseFloat( pre_pose_ary[ind] ) ); } find = true; } } now_cmd_id = pre_id; }while(!find); if(!find) return; var twist = new ROSLIB.Message({ linear : { x : pre_pose[0], y : pre_pose[1], z : pre_pose[2] }, angular : { x : pre_pose[3], y : pre_pose[4], z : pre_pose[5] } }); //console.log('twist.linear.x ='+ twist.linear.x +',y=' + twist.linear.y + ',z=' + twist.linear.z); request = new ROSLIB.ServiceRequest({ cmd : "Teach:" + mod, pose : twist }); //client call service ui_client.callService(request, function(res) { var shift = res.f.toFixed(3); $('#'+m_cmd_id).children("td.SubCmd").children("input").val(shift);; var now_pose = pre_pose; if (mod==CmdType.Shift_X){ now_pose[0] += parseFloat(shift); now_pose[0] = now_pose[0].toFixed(3); } else if(mod==CmdType.Shift_Y){ now_pose[1] += parseFloat(shift); now_pose[1] = now_pose[1].toFixed(3); } else if(mod==CmdType.Shift_Z){ now_pose[2] += parseFloat(shift); now_pose[2] = now_pose[2].toFixed(3); } //console.log('new_now_pose='+now_pose.toString() ); $('#'+m_cmd_id).children("td.SubCmd").children("input").attr('pose',now_pose.toString()); }); } } //----------------------------------------ROS----------------------------------------// // Connecting to ROS var ros = new ROSLIB.Ros({ url : 'ws://localhost:9090' }); // If there is an error on the backend, an 'error' emit will be emitted. ros.on('error', function(error) {var request = new ROSLIB.ServiceRequest({ cmd : "Teach:EEF_Pose", }); ui_client.callService(request, function(res) { var l = res.pose.linear; var a = res.pose.angular; console.log( 'Result : ' + res.result); console.log( 'Pose : ' + l.x + "," + l.y + "," + l.z + "," + a.x + "," + a.y + "," + a.z ); var refer = $('#'+m_cmd_id).children("td.SubCmd"); refer.children("input:nth-child(1)").val(l.x.toFixed(2)); refer.children("input:nth-child(2)").val(l.y.toFixed(2)); refer.children("input:nth-child(3)").val(l.z.toFixed(2)); refer.children("input:nth-child(4)").val(a.x.toFixed(2)); refer.children("input:nth-child(5)").val(a.y.toFixed(2)); refer.children("input:nth-child(6)").val(a.z.toFixed(2)); }); console.log(error); }); // Find out exactly when we made a connection. ros.on('connection', function() { console.log('ROS Connection made!'); }); ros.on('close', function() { console.log('ROS Connection closed.'); }); //-----------ActionClient-------------// var teachModeClient = new ROSLIB.ActionClient({ ros : ros, serverName : '/mbot_control', actionName : 'mbot_control/TeachCommandListAction' }); var now_exe_id = 0; var teach_result_trigger = false; function teach_feedback(feedback){ if(teach_result_trigger) return; console.log('Feedback: ' + feedback.status); var arrow_img = '<img src="img/right_arrow.png" align="center" style="width: 35%;"/>'; //get cmd_id var fb_str = feedback.status; var str_index = fb_str.indexOf('->'); var exe_id = fb_str.substring(str_index+2,fb_str.length); var m_cmd_id = 'cmd_'+exe_id; console.log('m_cmd_id=' + m_cmd_id); //change to arrow_img $('#'+m_cmd_id).children("td:first").html(arrow_img); if(now_exe_id!=0){ m_cmd_id = 'cmd_'+now_exe_id; //change to number $('#'+m_cmd_id).children("td:first").html(now_exe_id.pad(3)); } now_exe_id = parseInt(exe_id); } function teach_result(result){ console.log('Final Result: ' + result.notify); $("#run_btn").removeClass('disabled'); $("#run_btn").addClass('active'); /* $('#teach_table tr').each(function() { $(this).children("td:first").html(now_exe_id.pad(3)); });*/ teach_result_trigger = true; if(now_exe_id!=0){ m_cmd_id = 'cmd_'+now_exe_id; //change to number $('#'+m_cmd_id).children("td:first").html(now_exe_id.pad(3)); } } // ------------------------------------// // Subscribing to a "joint_states" Topic // -----------------------------------// var joint_ary = new Float32Array(6);; var joint_sub = new ROSLIB.Topic({ ros:ros, name: '/joint_states', messageType : 'sensor_msgs/JointState' }); joint_sub.subscribe(function(msg){ for(var i =0 ;i < 6;i++){ joint_ary[i] = msg.position[i]; } }); // ------------------------------------// // Client for a "ui_server" Service // -----------------------------------// var ui_client = new ROSLIB.Service({ ros : ros, name : '/ui_server', serviceType : 'mbot_control/UI_Server' }); /* Teach:SaveFile test var request = new ROSLIB.ServiceRequest({ cmd : "Teach:SaveFile", req_s : "hello\niam from web\nhello\n" }); ui_client.callService(request, function(res) { console.log( 'Result : ' + res.result); }); */ /* Teach:ReadFile test var request = new ROSLIB.ServiceRequest({ cmd : "Teach:ReadFile" }); ui_client.callService(request, function(res) { console.log( 'res_s : ' + res.res_s); console.log( 'Result : ' + res.result); }); */
import React, { Component } from "react"; import { Typography } from 'components'; import ReactCountryFlag from "react-country-flag" import { connect } from 'react-redux'; import _ from 'lodash'; import "./index.css"; class Player extends Component { constructor(props){ super(props); this.state = { }; } render() { const { player } = this.props; return ( <div styleName="player"> <div styleName="picture"> <img src={player.image_url} width="100%"/> </div> <div styleName="info"> <div styleName="top"> <div styleName="name"> <Typography variant={'body'} color={'white'}>{player.name}</Typography> </div> <div styleName="flag"> <ReactCountryFlag countryCode={player.nationality} className="emojiFlag" style={{ width: '1em', height: '1em', }} title={player.hometown} /> </div> </div> <div styleName="field"> <div> <Typography variant={'x-small-body'} color={'grey'}>Name:</Typography> </div> <div> <Typography variant={'small-body'} color={'white'}>{player.first_name} {player.last_name}</Typography> </div> </div> <div styleName="field"> <div> <Typography variant={'x-small-body'} color={'grey'}>Home Town:</Typography> </div> <div> <Typography variant={'small-body'} color={'white'}>{player.hometown}</Typography> </div> </div> <div styleName="field"> <div> <Typography variant={'x-small-body'} color={'grey'}>Role:</Typography> </div> <div> <Typography variant={'small-body'} color={'white'}>{player.role}</Typography> </div> </div> </div> </div> ); } } function mapStateToProps(state){ return { profile : state.profile, ln: state.language }; } export default connect(mapStateToProps)(Player);
import { combineReducers } from 'redux' import user from './user' import expenses from './expenses' import modal from './modal' import date from './date' export default combineReducers({ user, expenses, modal, date })
const express = require('express'); const router = express.Router(); const mongoose = require('mongoose'); //Generate ID const checkAuth = require('../middleware/checkauth'); const Order = require('../models/order'); const Category = require('../models/category'); const User = require('../models/user'); const Event = require('../models/event'); const Image = require('../models/image'); const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; //=======================================================// //login passport.use(new LocalStrategy( function (email, password, done) { User.getUserByEmail(email, function (err, user) { if (err) throw err; if (!user) { return done(null, false, { message: 'Unknown User' }); } User.comparePassword(password, user.password, function (err, isMatch) { if (err) throw err; if (isMatch) { return done(null, user); } else { return done(null, false, { message: 'Invalid password' }); } }); }); })); passport.serializeUser(function (user, done) { done(null, user.id); }); passport.deserializeUser(function (id, done) { User.getUserById(id, function (err, user) { done(err, user); }); }); router.post('/login', passport.authenticate('local', { successRedirect: '/admin', failureRedirect: '/', failureFlash: true }), function (req, res) { res.redirect('/admin'); }); router.get('/logout', function (req, res) { req.logout(); req.flash('success_msg', 'You are logged out'); res.redirect('/'); }); // router.post('/login', (req, res, next) => { // User.find({ email: req.body.email }) // .exec() // .then(user => { // if(user.length < 1) { // return res.status(401).json({ // message: 'Auth failed' // }); // } // bcrypt.compare(req.body.password, user[0].password, (err, result) => { // if(err) { // return res.status(401).json({ // message: 'Auth failed' // }); // } // if(result) { // const token = jwt.sign({ // email: user[0].email, // userId: user[0]._id // }, // "bismillah" // ); // return res.redirect('/admin') // // res.status(200).json({ // // message: 'Auth successful', // // token: token, // // userId : user[0]._id // // }); // } // res.status(401).json({ // message: 'Auth failed' // }); // }); // }) // .catch(err => { // console.log(err); // res.status(500).json({ // error: err // }); // }); // }); //-------------- ORDERS --------------// //Get router.get('/orders', (req, res, next) => { Order.find() .populate('category', 'name') .populate('userId', 'name') .exec() .then(docs => { res.status(200).json({ count: docs.length, orders: docs.map(doc => { return { _id: doc._id, category: doc.category, date: doc.date, date_created: doc.date_created, budget: doc.budget, address: doc.address, description: doc.description, status: doc.status, userId: doc.userId, // request: { // type: "GET", // url: 'http://localhost:3000/admins/orders/' + doc._id // } } }) }); // res.render('AdminLTE-2.4.3/AdminLTE-2.4.3/events'); }) .catch(err => { res.status(500).json({ error: err }); }); }); router.get('/orders/new', (req, res, next) => { Order.find({status : "Waiting"}) .populate('category', 'name') .populate('userId', 'name') .exec() .then(docs => { res.status(200).json({ count: docs.length, neworders: docs.map(doc => { return { _id: doc._id, category: doc.category, date: doc.date, date_created: doc.date_created, budget: doc.budget, address: doc.address, description: doc.description, status: doc.status, userId: doc.userId, // request: { // type: "GET", // url: 'http://localhost:3000/admins/orders/' + doc._id // } } }) }); // res.render('AdminLTE-2.4.3/AdminLTE-2.4.3/events'); }) .catch(err => { res.status(500).json({ error: err }); }); }); //Status //Accepted router.post('/orders/accept/', (req, res, next) => { const id = req.body.id; Order.update({ _id: id }, { $set: {status : "Proccessed"} }) .exec() .then(result => { res.status(200).json({ message: "Order Accepted", // request: { // type: "PATCH", // url: "http://localhost:3000/events" + id // } }); }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); }); //Done router.post('/orders/done/', (req, res, next) => { const id = req.body.id; Order.update({ _id: id }, { $set: {status : "Done"} }) .exec() .then(result => { res.status(200).json({ message: "Order Finised", // request: { // type: "PATCH", // url: "http://localhost:3000/events" + id // } }); }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); }); //-------------- EVENTS --------------// //GET EVENTS router.get('/events', (req, res, next) => { Image.find() .populate('eventId', 'title date_create date_event description city status') .populate('userId', 'name') .populate('categoryevent', 'name') .exec() .then(docs => { const response = { count: docs.length, events: docs.map(doc => { return { id: doc._id, event_image_path: doc.event_image_path, title : doc.title, date_create : doc.date_create, date_event: doc.date_event, description:doc.description, city:doc.city, categoryevent:doc.categoryevent, userId: doc.userId, eventId: doc.eventId, status: doc.status, request: { type: "GET", url: "http://localhost:3000/images/" + doc._id } } }) }; res.status(200).json(response); }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); }); router.get('/events/new', (req, res, next) => { Image.find({status: "waiting admin's confirmation.."}) .populate('eventId', 'title date_create date_event description city status') .populate('userId', 'name') .populate('categoryevent', 'name') .exec() .then(docs => { const response = { count: docs.length, newevents: docs.map(doc => { return { id: doc._id, event_image_path: doc.event_image_path, title : doc.title, date_create : doc.date_create, date_event: doc.date_event, description:doc.description, city:doc.city, categoryevent:doc.categoryevent, userId: doc.userId, eventId: doc.eventId, status: doc.status, request: { type: "GET", url: "http://localhost:3000/images/" + doc._id } } }) }; res.status(200).json(response); }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); }); //status //Accepted router.post('/events/accept/', (req, res, next) => { const id = req.body.id; // const updateOps = {}; // for (const ops of req.body) { // updateOps[ops.propName] = ops.value; // } Image.update({ _id: id }, { $set: {status : "Accept"} }) .exec() .then(result => { res.status(200).json({ message: "Event Accepted", // request: { // type: "PATCH", // url: "http://localhost:3000/events" + id // } }); }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); }); //Rejected router.post('/events/reject/', (req, res, next) => { const id = req.body.id; // const updateOps = {}; // for (const ops of req.body) { // updateOps[ops.propName] = ops.value; // } Image.update({ _id: id }, { $set: {status : "Rejected"} }) .exec() .then(result => { res.status(200).json({ message: "Event Rejected", // request: { // type: "PATCH", // url: "http://localhost:3000/events" + id // } }); }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); }); //-------------- USERS --------------// //GET users router.get('/users', (req, res, next) => { User.find() .select('') .exec() .then(docs => { const response = { count: docs.length, users: docs.map(doc => { return { _id: doc._id, email: doc.email, name: doc.name, address: doc.address, phone_number: doc.phone_number, status: doc.status, // request: { // type: "GET", // url: "http://localhost:3000/admins/users/" + doc._id // } } }) }; res.status(200).json(response); // .render('AdminLTE-2.4.3/AdminLTE-2.4.3/users'); }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); }); router.post('/users/delete', (req, res, next) => { var id = req.body.id; console.log(id); User.update({ _id: id }, { $set: {status : "0"} }) .exec() .then(result => { res.status(200).json({ message: "User Deactivated", // request: { // type: "PATCH", // url: "http://localhost:3000/users" + id // } }); }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); }); module.exports = router;
import { FETCH_CLASSES_START, FETCH_CLASSES_SUCCESS, FETCH_CLASSES_ERROR, POST_CLASSES_START, POST_CLASSES_SUCCESS, POST_CLASSES_ERROR, EDIT_CLASSES_START, EDIT_CLASSES_SUCCESS, EDIT_CLASSES_ERROR, DELETE_CLASSES_START, DELETE_CLASSES_SUCCESS, DELETE_CLASSES_ERROR } from "../actions/classes"; const initialState = { classes: [], isLoading: false, error: null } export function reducer(state = initialState, action) { switch(action.type) { case FETCH_CLASSES_START: return { ...state, isLoading: true, error: null } case FETCH_CLASSES_SUCCESS: return { ...state, classes: action.payload, isLoading: false, error: null } case FETCH_CLASSES_ERROR: return { ...state, isLoading: false, error: action.payload } case POST_CLASSES_START: return { ...state, isLoading: true, error: null } case POST_CLASSES_SUCCESS: console.log(action.payload, 'payload') return { ...state, classes: [...state, action.payload], isLoading: false, error: null } case POST_CLASSES_ERROR: return { ...state, isLoading: false, error: action.payload } default: return state; } }
// @flow import { decodeJwtToken, getNumberOfDaysBetweenTwoDates, addDaysToDate, Cookie, } from '@vezeeta/web-utils'; import Cookies from 'js-cookie'; const signIn = (token: string) => { const expireDate = addDaysToDate( decodeJwtToken(token).payLoad.exp, parseInt(process.env.REACT_APP_SSO_COOKIE_EXPIRY_DATE), ); const expireDateDays = getNumberOfDaysBetweenTwoDates(new Date(), expireDate); const returnUrl = Cookie.get(Cookie.RETURN_URL); Cookie.remove(Cookie.RETURN_URL); // Cookie.set(Cookie.AUTH_TOKEN, token, { // expires: expireDateDays, // }); Cookies.set('VZT_TOKEN', token, { expires: expireDateDays, secure: process.env.REACT_APP_FORCE_HTTPS === 'true', domain: process.env.REACT_APP_TOKEN_DOMAIN, }); window.location = returnUrl || process.env.REACT_APP_SCHEDULE_URL; }; export default signIn;
var requirejs = require('requirejs'); var Table = require('./table'); var CompletionTable = requirejs('common/modules/completion_table'); module.exports = Table.extend(CompletionTable);
define([ 'client/controllers/module', 'common/modules/bar_chart_with_number', 'client/views/visualisations/bar_chart_with_number' ], function (ModuleController, BarChartController, BarChartView) { return ModuleController.extend(BarChartController).extend({ visualisationClass: BarChartView }); });
'use strict'; //Events service used for handling event data requests angular.module('events').service('EventsService', [ '$resource', function($resource) { return $resource('/events/:eventId', {eventId: '@eventId'}); } ]);
define( [ "jquery" ], function( $ ) { function $$( element, classname ) { return $( document.createElement( element ) ).addClass( classname ); } return function( $context ) { $( "[data-fileselect]", $context ).each(function() { var $input = $( ":text", this ), $grp = $$( "div", "input-group" ) .append( $input ) .appendTo( this ), $btn = $$( "button" ) .attr({ type: "button", tabindex: -1 }) .addClass( "btn fa fa-search" ) .appendTo( $$( "span", "input-group-btn" ) .appendTo( $grp ) ), $file = $$( "input" ) .attr({ type: "file" }) .addClass( "hidden" ) .appendTo( this ); $btn.click(function() { if ( !$input.is( ":disabled" ) ) { $file.click(); } }); $file.change(function() { $input // set new value .val( $file.val() ) // Ember doesn't notice the previous change event for some reason .trigger( "change" ); }); }); }; });
const express = require("express"); const app = new express(); const todoRouter = require("./router/todos"); app.use(express.urlencoded({ extended: true })); app.use(express.static("public")); app.set("view engine", "pug"); app.set("views", __dirname + "/views"); app.use("/todo", todoRouter); app.use("/note", (req, res) => { res.render("note"); }); const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`listen on ${port}...`); });
import React from "react"; import Row from "react-bootstrap/Row"; import Container from "react-bootstrap/Container"; import Col from "react-bootstrap/Col"; import Form from "react-bootstrap/Form"; import Button from "react-bootstrap/Button"; import "./style.css"; import server from "../ServerInterface/server"; import { Link, Redirect } from "react-router-dom"; class Review extends React.Component { constructor(props) { super(props); this.state = { name: "", rate: 0, location: "", description: "", review: "", type: "", add: false, }; } handleAddPlace = (event) => { server.addPlace( this.state.name, this.state.rate, this.state.location, this.state.description, this.state.review, this.state.type ); this.setState({ add: true }); event.preventDefault(); }; onChange = (event) => { const value = event.target.value; const name = event.target.name; this.setState({ [name]: value }); }; render() { if (this.state.add) { return <Redirect to="/" />; } return ( <div> <div className="search_title"> <Link to="/" className="title-link"> ReViewer </Link> </div> <Container> <Row> <Col className="review-input"> <Form> <Form.Group name="name"> <Form.Label>Name</Form.Label> <Form.Control type="text" name="name" placeholder="Enter Name of Place" value={this.state.name} onChange={this.onChange} /> </Form.Group> <Form.Group name="rate"> <Form.Label>Rate</Form.Label> <Form.Control as="select" name="rate" value={this.state.rate} onChange={this.onChange} > <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </Form.Control> </Form.Group> <Form.Group name="location"> <Form.Label>Location</Form.Label> <Form.Control type="text" name="location" placeholder="Enter location of Place" value={this.state.location} onChange={this.onChange} /> </Form.Group> <Form.Group name="description"> <Form.Label>Description</Form.Label> <Form.Control type="text" name="description" placeholder="Enter Description of Place" value={this.state.description} onChange={this.onChange} /> </Form.Group> <Form.Group name="review"> <Form.Label>Review</Form.Label> <Form.Control type="text" name="review" placeholder="Enter review of Place" value={this.state.review} onChange={this.onChange} /> </Form.Group> <Form.Group name="type"> <Form.Label>Type</Form.Label> <Form.Control as="select" name="type" value={this.state.type} onChange={this.onChange} > <option>restaurants</option> <option>mechanic</option> <option>shops</option> <option>gym</option> </Form.Control> </Form.Group> <Button variant="primary" type="submit" onClick={this.handleAddPlace} > Add </Button> </Form> </Col> </Row> </Container> </div> ); } } export default Review;
const { toMatchImageSnapshot } = require('jest-image-snapshot'); /** @type {import('@storybook/test-runner').TestRunnerConfig} */ const config = { setup() { expect.extend({ toMatchImageSnapshot }); }, async postRender(page, { title, name }) { // https://github.com/storybookjs/test-runner/issues/97#issuecomment-1134419035 const viewportParameters = await page.evaluate("window.STORY_VIEWPORT_PARAMETERS"); if (viewportParameters) { const viewport = viewportParameters.viewports[viewportParameters.defaultViewport]; await page.setViewportSize({ width: parseInt(viewport.styles.width, 10), height: parseInt(viewport.styles.height, 10) }); } const image = await page.screenshot({ animations: 'disabled' }); const storyPathParts = title.split('/'); const storyFileName = storyPathParts.pop(); const storyDir = `${__dirname}/../app/${storyPathParts.join('/')}`; expect(image).toMatchImageSnapshot({ customSnapshotsDir: `${storyDir}/__snapshots__/${storyFileName}`, customSnapshotIdentifier: name }); } }; module.exports = config;
const addTaskButton = document.querySelector('#add-task-button'); const input = document.querySelector('#task-input'); const taskList = document.querySelector('#task-list'); const allRemoveButton = document.querySelector('#removeFinishedTasksButton'); const errorMessageDiv1 = document.querySelector('#error-message1'); const errorMessageDiv2 = document.querySelector('#error-message2'); const errorMessage1 = 'Task must have more than 5 \n and less then 100 characters.'; const errorMessage2 = 'You must have completed tasks.'; const deleteErrorMessage = ''; const body = document.querySelector('body'); const counterSpan = document.querySelector('#counter'); let counter = 0; input.addEventListener('keyup', function (event) { if (event.keyCode === 13) { event.preventDefault(); document.getElementById("add-task-button").click(); }; }); addTaskButton.addEventListener('click', function (e) { e.preventDefault(); const inputValue = input.value; const newLi = document.createElement('li'); const newH1 = document.createElement('h2'); const deleteButton = document.createElement('button'); const completeButton = document.createElement('button'); counter++ if (inputValue.length > 5 && inputValue.length < 100) { const newTask = taskList.appendChild(newLi); const liLenght = document.querySelectorAll('.new-li'); newTask.appendChild(newH1).innerText = inputValue[0].toUpperCase() + inputValue.substr(1); newTask.appendChild(deleteButton).innerText = 'Delete'; newTask.appendChild(completeButton).innerText = 'Complete'; newLi.classList.add('new-li'); errorMessageDiv1.innerText = deleteErrorMessage; input.value = ''; counterSpan.innerText = liLenght.length + 1; } else { errorMessageDiv1.innerText = errorMessage1; }; deleteButton.addEventListener('click', function (e) { e.preventDefault(); taskList.removeChild(newLi); const liLenght = document.querySelectorAll('.new-li'); const doneTask = document.getElementsByClassName('done'); counterSpan.innerText = liLenght.length - doneTask.length; }); completeButton.addEventListener('click', function (e) { e.preventDefault(); const thisLi = this.parentElement; if (thisLi.classList.contains('done')) { thisLi.style.textDecoration = 'none'; thisLi.classList.remove('done'); } else { thisLi.style.textDecoration = 'line-through'; thisLi.classList.add('done'); }; const liLenght = document.querySelectorAll('.new-li'); const doneTask = document.getElementsByClassName('done'); counterSpan.innerText = liLenght.length - doneTask.length; }); }); allRemoveButton.addEventListener('click', function (e) { e.preventDefault(); const doneTask = document.getElementsByClassName('done'); if (doneTask.length > 0) { for (let i = doneTask.length - 1; i >= 0; i--) { const taskDeletedNow = doneTask[i]; taskDeletedNow.parentElement.removeChild(taskDeletedNow); }; const liLenght = document.querySelectorAll('.new-li'); counterSpan.innerText = liLenght.length - doneTask.length; errorMessageDiv2.innerText = deleteErrorMessage; input.value = ''; } else { errorMessageDiv2.innerText = errorMessage2; }; });
import React from 'react'; class AdminMenu extends React.Component { constructor(props) { super(); console.log(JSON.stringify(props, null, 2)); this.handleClick = this.handleClick.bind(this); } handleClick(value) { console.log('Click happened' + value); this.props.selectMenu(value); } render() { return ( <div> <div> <button onClick={() => {this.handleClick('manufacturer')}}>Manufacturer</button> </div> <div> <button onClick={() => {this.handleClick('transporter')}}>Transporter</button> </div> <div> <button onClick={() => {this.handleClick('distributor')}}>Distributor</button> </div> <div> <button onClick={() => {this.handleClick('retailer')}}>Retailer</button> </div> </div> ) } } export default AdminMenu;
var http = require('http'); var url = require('url'); var fs = require('fs'); //file system var events = require('events'); var eventEmitter = new events.EventEmitter(); var formidable = require('formidable'); //file uploads var nodemailer = require('nodemailer'); //send emails var express = require('express'); var mysql = require('mysql'); // console.log("to: ",to); // console.log("num: ",num); const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'printoverflow@gmail.com', pass: 'xxxpasswordxxx' } }); module.exports = function sendEmail(context) { var content = "You have printed " + context.pages + " pages."; const mailOptions = { from: 'printoverflow@gmail.com', to: context.netid, subject: 'PRINT OVERFLOW!', text: content, }; transporter.sendMail(mailOptions, function(error, info){ if (error) { console.log(error); } else { console.log(info); console.log('Email sent: ' + info.response); } }); };
import Sequelize from 'sequelize' import db from '../connect' const User_Organization = db.define( 'user_organization', { id: { type: Sequelize.UUID, defaultValue: Sequelize.UUIDV4, primaryKey: true }, userId: { type: Sequelize.STRING }, // organizationId:{ // type: Sequelize.UUID, // references: { // model: 'organization', // key: 'id' // }, // onDelete: 'CASCADE', // onUpdate: 'CASCADE' // }, role: { type: Sequelize.ENUM, values: ['admin', 'editor', 'contributor', 'pending'] } }, { freezeTableName: true } ) export default User_Organization
'use strict'; module.exports = (router, controllers) => { router.get('/travel/index.html', controllers.travel.index); };
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { /** 로그인 **/ login: { isLogin: sessionStorage.getItem('isLogin') == 'false' || sessionStorage.getItem('isLogin') == null ? false : true, }, /** 로그인 **/ /** 로더 **/ loader: { load: false, }, /** 로더 **/ /** 카메라 **/ camera: { isPhotoTaken: false, isClicked: false, mode: '', item: '', }, /** 카메라 **/ /** 상품 **/ product: { total: 0, category: '', productName: '', productNo: 0, productPrice: '', categorize: false, checkedList: [], categorizeItems: [], categorizeItem: '', searchName: '', reviewLink: '', }, /** 상품 **/ /** 쇼핑리스트 **/ shoppingList: { shoppingListName: '', shoppingListPrice: '', modalState: true, }, /** 쇼핑리스트 **/ /** 통합검색 **/ integratedSearch: [], /** 통합검색 **/ }, mutations: { /** 로더 **/ SET_LOADER_TRUE(state) { state.loader.load = true; }, SET_LOADER_FALSE(state) { state.loader.load = false; }, /** 로더 **/ //** 통합검색 Set **/ SET_INTEGRATED_SEARCH(state, payload) { state.integratedSearch.splice(0); //배열 내용 초기화해주기 state.integratedSearch = payload.response.data; }, SET_SERACH_NAME(state, payload) { console.log(payload.searchName); state.product.searchName = payload.searchName; }, //** 통합검색 Set **/ //** 상품정보 **/ //상품정보 넣어주기 SET_PRODUCT_INFO(state, payload) { console.log('리뷰set info'); console.log(payload.productInfo.reviewLink); state.product.productName = payload.productInfo.productName; state.product.productNo = payload.productInfo.productNo; state.product.productPrice = payload.productInfo.productPrice; state.product.reviewLink = payload.productInfo.reviewLink; console.log('리뷰@@@@@@@@@@@@'); console.log(state.product.reviewLink); }, // ** 로그인 시작 **// TOGGLE_LOGIN_STATE(state) { if (sessionStorage.getItem('isLogin') == 'false') { state.login.isLogin = false; } else { state.login.isLogin = true; } }, // ** 로그인 끝 **// // ** 카메라 시작 **// TOGGLE_CAMERA_CANVAS(state) { state.camera.isPhotoTaken = !state.camera.isPhotoTaken; }, TOGGLE_CAMERA_CLICKED(state) { state.camera.isClicked = !state.camera.isClicked; }, SET_CAMERA_MODE(state, payload) { state.camera.mode = payload.mode; }, SET_CAMERA_ITEM(state, payload) { state.camera.item = payload.item; }, // ** 카메라 끝 **// // ** 상품 관련 시작 ** // SET_ZERO_TOTAL(state) { state.product.total = 0; }, ADD_TOTAL_MONEY(state, payload) { state.product.total += payload.money; }, DEL_ITEM(state, payload) { state.product.total -= payload.money; }, TOGGLE_CATEGORIZE_STATE(state) { state.product.categorize = !state.product.categorize; }, ADD_CHECK_ITEM(state, payload) { state.product.checkedList.push(payload.payload); }, DEL_CHECK_ITEM(state, payload) { var length = state.product.checkedList.length; for (var i = 0; i < length; i++) { if (state.product.checkedList[i].shoppingListNo == payload.no) { state.product.checkedList.splice(i, 1); break; } } }, SET_CATEGORY_STATE(state, payload) { state.product.categorize = payload; }, SET_CATEGORIZE_ITEMS(state, payload) { state.product.categorizeItems = payload.categorizeItems; }, SET_CATEGORIZE_ITEM(state, payload) { state.product.categorizeItem = payload.categorizeItem; }, INIT_CHECKLIST(state) { state.product.checkedList.splice(0); }, TOGGLE_MODAL_STATE(state) { state.shoppingList.modalState = !state.shoppingList.modalState; }, // ** 상품 관련 끝 ** // }, actions: {}, modules: {}, getters: { // ** 로그인 시작 **// getIsLogin(state) { return state.login.isLogin; }, // ** 로그인 끝 **// // ** 카메라 시작**// getCameraIsPhotoTaken(state) { return state.camera.isPhotoTaken; }, getCameraMode(state) { return state.camera.mode; }, getCameraItem(state) { return state.camera.item; }, getCameraClicked(state) { return state.camera.isClicked; }, //** 카메라 끝**// // ** 상품 관련 시작 ** // getTotalMoney(state) { return state.product.total; }, getProductCategory(state) { return state.product.category; }, getProductNo(state) { return state.product.productNo; }, getProductName(state) { return state.product.productName; }, getProductPrice(state) { return state.product.productPrice; }, getCategorizeItems(state) { return state.product.categorizeItems; }, getCategorizeItem(state) { return state.product.categorizeItem; }, getCategorizeState(state) { return state.product.categorize; }, getCheckedList(state) { return state.product.checkedList; }, getModalState(state) { return state.shoppingList.modalState; }, // ** 상품 관련 끝 ** // SET_SERACH_NAME(state, payload) { console.log(payload.serachName); state.product.searchName = payload.serachName; }, getReviewLink(state, payload) { return state.product.reviewLink; }, //** 통합검색 **/ getintegratedSearch(state) { return state.integratedSearch; }, getSearchName(state) { return state.product.searchName; }, //** 통합검색 **/ //** 로더 **/ getLoader(state) { return state.loader.load; }, //** 로더 **/ }, });
const test = require('../../test'); module.exports = function(argv) { let options = { fnName: 'camelToKabob', esVersion: 5, allowHigherOrderFns: false }; let test1 = { input: 'camelToKabob("aVariableName")', expected: 'a-variable-name' }; let test2 = { input: 'camelToKabob("bob")', expected: 'bob' }; let test3 = { input: 'camelToKabob("bobsUsedBookStore")', expected: 'bobs-used-book-store' }; test(argv, [test1, test2, test3], options); };
import React, { Component } from 'react' import './media/css/out_of_navigation_area.css' class OutOfNavigationArea extends Component { goBack() { window.history.back() } render() { return ( <div className="out-of-navigation-area"> <div>You are out of the navigation area.</div> <div className="back-button" onMouseUp={this.goBack}>Go Back</div> </div> ) } } export default OutOfNavigationArea
function openbox(id){ display = document.getElementById(id).style.display; if(display=='none'){ document.getElementById(id).style.display='block'; }else{ document.getElementById(id).style.display='none'; } }; $('.video__a').on('click', function(e) { e.preventDefault(); var self = $(this); var videoSrc = self.attr('href'); var videoId = videoSrc.substr(videoSrc.length - 11) + '?rel=0&autoplay=1&controls=0&showinfo=0'; self.find('img').css('z-index', '0'); self.find('iframe').attr('src', 'https://www.youtube.com/embed/' + videoId); });
import React from "react"; import "./FriendsList.css"; import FriendsList from "./FriendsList"; class FriendCard extends React.Component { constructor(props) { super(props); this.state = { isEditing: false, name: "", age: "", email: "" }; } toggleEdit = (e, id) => { e.preventDefault(); this.setState(prevState => { return {isEditing: !prevState.isEditing}; }); }; updateHandler = e => { console.log(e.target.value); this.setState({[e.target.name]: e.target.value}); }; helper = e => { e.preventDefault(); const {name, age, email} = this.state; const updatedInfo = {name, age, email}; this.props.updateFriend(this.props.friend.id, updatedInfo); this.setState(prevState => { return {isEditing: !prevState.isEditing}; }); }; render() { const {friend} = this.props; return ( <div> <div> <div className="friend"> {!this.state.isEditing ? ( <div> <h2>{friend.name}</h2> <p>{`${friend.age} years old`}</p> <p>{friend.email}</p> <i className="fas fa-times" onClick={e => this.props.deleteFriend(e, friend.id)} title="Delete" /> <i className="fas fa-user-edit" title="Edit info" onClick={this.toggleEdit} /> </div> ) : ( <div> <form className="edit-mode" onSubmit={e => this.helper(e)}> <h4> {`Update ${friend.name}'s Info`}{" "} <i className="fas fa-pencil-alt" /> </h4> <input type="text" name="name" placeholder={friend.name} value={this.state.name} onChange={this.updateHandler} /> <br /> <input type="text" name="age" placeholder={friend.age} value={this.state.age} onChange={this.updateHandler} /> <br /> <input type="email" name="email" placeholder={friend.email} value={this.state.email} onChange={this.updateHandler} /> <br /> <button className="accept" type="submit"> Accept </button> <button onClick={this.toggleEdit} className="cancel"> Cancel </button> </form> </div> )} </div> </div> </div> ); } } export default FriendCard;
import React, { Component } from 'react' import { View, Text, Image, TouchableOpacity, ActivityIndicator } from 'react-native' import styles from './styles' export default class extends Component { static defaultProps = { index: 0, comic: null, onPress: () => {}, } constructor(props) { super(props); this.state = { loaded: false }; } render() { const { comic, index } = this.props; const title = comic ? comic.title : ''; const format = comic ? comic.format : ''; const image = comic && comic.thumbnail ? { uri: `${comic.thumbnail.path}.${comic.thumbnail.extension}` } : null; const characters = comic && comic.characters && comic.characters.available; return ( <TouchableOpacity style={styles.container} onPress={() => this.props.onPress(comic)}> <View style={styles.containerImage}> <Image source={image} style={styles.image} resizeMode={'stretch'} onLoadEnd={ () => { this.setState({ loaded: true }) } }> </Image> </View> <View style={styles.detailContainer}> <Text style={[styles.label, styles.name]}>{title}</Text> <Text style={styles.label}>{'Characters: '}{characters}</Text> </View> </TouchableOpacity> ); } }
"use strict"; exports.Const = require("./Const.js"); exports.Utils = require("./Utils.js"); exports.SDD = require("./SDD.js"); exports.map = require("./map.js"); if (exports.Utils.isBrowser) { exports.IGB = require("./IGB.js"); } exports.V_MAJOR = 0; exports.V_MINOR = 2; exports.V_PATCH = 0; exports.VERSION = exports.V_MAJOR + "." + exports.V_MINOR + "." + exports.V_PATCH;
$(document).ready(function() { $('#menulink').click(function(event) { event.preventDefault(); if($('.navigation-wrapper').hasClass('show-menu')) { $('.navigation-wrapper').removeClass('show-menu'); $('.navigation').hide(); $('.navigation li').removeClass('small-padding'); } else { $('.navigation-wrapper').addClass('show-menu'); $('.navigation').fadeIn(); $('.navigation li').addClass('small-padding'); } }); });
const express = require("express"); const passport = require("passport"); const authRoutes = require("./app/routes/authRoutes"); const bucketControllerRouter = require("./app/controllers/bucketController"); const assetsControllerRouter = require("./app/controllers/assetsController"); const router = express.Router(); router.use("/auth", authRoutes); router.use( "/bucket", passport.authenticate("jwt", { session: false }), bucketControllerRouter ); router.use( "/bucket/:bucket_id/assets", passport.authenticate("jwt", { session: false }), assetsControllerRouter ); module.exports = router;
import React, { Component } from 'react' import axios from 'axios' import {Link} from 'react-router-dom' export default class AddNewCustomer extends Component { state = { newCustomerFirstName: '', newCustomerLastName: '', newCustomerStyleProfile: '' } creatNewCustomer = () => { const newCustomer = { firstName: this.state.newCustomerFirstName, lastName: this.state.newCustomerLastName, styleProfile: this.state.newCustomerStyleProfile } axios.post('/api/customer', newCustomer) } onNewCustomerFirstNameChange = (event) => { const newCustomerFirstName = event.target.value; this.setState({newCustomerFirstName}) } onNewCustomerLastNameChange = (event) => { const newCustomerLastName = event.target.value; this.setState({newCustomerLastName}) } onNewCustomerStyleProfileChange = (event) => { const newCustomerStyleProfile = event.target.value; this.setState({newCustomerStyleProfile}) } render() { return ( <div className="form-container"> <h2>Add New Customer</h2> <form> <input type='text' placeholder='Customer First Name' name="newCustomerFirstName" required="required" onChange={this.onNewCustomerFirstNameChange} value={this.state.newCustomerFirstName} /> <input type='text' placeholder='Customer Last Name' name="newCustomerLastName" required="required" onChange={this.onNewCustomerLastNameChange} value={this.state.newCustomerLastName} /> <input type='text' placeholder='Style Profile' name="newCustomerStyleProfile" required="required" onChange={this.onNewCustomerStyleProfileChange} value={this.state.newCustomerStyleProfile} /> <input type='submit' onClick={() => this.creatNewCustomer()} /> </form> <br/> <br/> <Link to='/'>Home</Link> </div> ) } }
/*La sintaxis de asignación desestructurante (destructuring assignment) es una expresión que posibilita la extracción de datos de arrays, o de propiedades de objetos, en variables distintas..*/ let color1,color2, resto; [color1,color2]=["Rojo","Amarillo"]; console.log(`${color1} ${color2}`); [color1,color2,...resto] = ["Rojo","Negro","Amarillo","Azul","Verde","Naranja"]; [color1,color2]=[color2,color1]; //intercambiar valores en una sola instrucción. console.log(`${color1} ${color2}`); console.log(resto) var ClaveValor =[["Color4","Rojo"],["Color5","Amarillo"],["Color3","Esmeralda"]]; let mapaColores = new Map(ClaveValor); console.log(mapaColores); [...mapaColores.entries()] console.log(mapaColores.entries()); //Devuel el array 2d del mapa const mapaColores2= new Map([...mapaColores.entries()].sort((a,b)=>a[1].localeCompare(b[1]))); console.log(mapaColores2); //Añade una caracter al final de todas las cadenas pasadas function finalizaConI(c, ...otros) { for (i=0;i<=otros.length-1; i++){ otros[i]=otros[i]+c; } return otros } console.log(finalizaConI('X',"Linu","Molinu","Siu")); function finalizaConII(c, ...otros) { return otros.map(x=>x+c) } console.log(finalizaConII('F',"hola","mio","silla"));
import * as _ from './_'; /** * Tells whether argument passed is similar to an array. * @param {*} x * * @returns {boolean} */ export const isSimilar = x => _.isNumber(_.lengthOf(x)); const proto = _.prototypeOf(Array); const protoSlice = proto.slice; /** * Loops through the array and calls * iteratee with each item. * Equal to Array.prototype.forEach. * @param {Array} array * @param {Function} iteratee * * @returns {Array} */ export const loop = _.curry2((array, iteratee) => { array && proto.forEach.call(array, iteratee); return array; }); /** * Invokes all functions in the array. * @param {Array<Function>} array */ export const callAll = array => loop(array, a => a()); const arrayCall = func => _.curry2((arr, arg) => proto[func].call(arr, arg)); /** * Says whether `fn` evaluates to true * for at least one element of `array`. * Array.prototype.some * @param {Array} array * @param {function (item: *): boolean} fn * * @returns {boolean} */ export const any = arrayCall('some'); /** * Says whether `fn` evaluates to true * for every element of `array`. * Array.prototype.every * @param {Array} array * @param {function (item: *): boolean} fn * * @returns {boolean} */ export const every = arrayCall('every'); /** * Says whether `fn` evaluates to false * for every element of `array`. * Array.prototype.some * @param {Array} array * @param {function (item: *): boolean} fn * * @returns {boolean} */ export const none = _.curry2((arr, evalutor) => !any(arr, evalutor)); /** * Returns a new function by mapping every * element of the array into a new element. * @param {Array} array * @param {function (item: *): *} mapper * * @returns {Array} */ export const map = arrayCall('map'); /** * Maps each element using a mapping function and flattens the * result into a new array. * @param {Array} arr * @param {function (item: *): Array} mapper * @returns {Array} */ export const flatMap = _.curry2((arr, mapper) => { return arr |> map(mapper) |> reduce(mergeWith, []); }); /** * Returns a new array consisting of elements * from the orignal array that pass * the filter. * @param {Array} array * @param {function (item: *): boolean} filterer * * @returns {Array} */ export const filter = arrayCall('filter'); /** * Returns the index of the item in the array. * @param {Array} array * @param {*} item * * @returns {number} */ export const indexOf = arrayCall('indexOf'); /** * Returns a string by joining the elements of tha array. * @param {Array} array * @param {string} delimeter * * @returns {string} */ export const join = arrayCall('join'); /** * Returns a sorted array while sorting the array in place too. * @param {Array} array * @param {function (first: *, second: *): number} sorter Returns 1 if a > b, -1 if b > a, 0 if a == b * * @returns {Array} */ export const sort = arrayCall('sort'); /** * Tells whether or not an array contains the given member. * @param {Array} array * @param {Any} member * * @returns {boolean} */ export const contains = _.curry2( (array, member) => indexOf(array, member) >= 0 ); /** * Returns the index of the first item in an array * for which iteratee evaluates to true. * @param {Array} arr * @param {function (item: *): boolean} iteratee * @param {Any} item * @returns {boolean} * * @returns {number} */ export const findIndex = _.curry2((arr, iteratee) => { let arrayLen = _.lengthOf(arr); for (let i = 0; i < arrayLen; i++) { if (iteratee(arr[i], i, arr)) { return i; } } return -1; }); /** * Returns the first item in an array * for which iteratee evaluates to true. * @param {Array} arr * @param {function (item: *): boolean} iteratee * * @returns {Any} */ export const find = _.curry2((arr, iteratee) => { let index = findIndex(arr, iteratee); if (index >= 0) { return arr[index]; } }); /** * Prepends an item to an array. * @param {Array} array * @param {Any} member * * @returns {Array} */ export const prepend = _.curry2((array, member) => { const newArray = Array(_.lengthOf(array) + 1); newArray[0] = member; loop(array, (member, index) => (newArray[index + 1] = member)); return newArray; }); /** * Appends an item to an array. * @param {Array} array * @param {Any} member * * @returns {Array} */ export const append = _.curry2((array, member) => { const arrayLen = _.lengthOf(array); const newArray = Array(arrayLen + 1); newArray[arrayLen] = member; loop(array, (member, index) => (newArray[index] = member)); return newArray; }); /** * Returns an array with the member * removed from the original array. * Does not modify the original array. * @param {Array} array * @param {Any} member * * @returns {Array} */ export const remove = _.curry2((array, member) => filter(array, item => item !== member) ); /** * Returns the first item of the array. * @param {Array} array * * @returns {Any} */ export const first = array => array[0]; /** * Returns the last item of the array. * @param {Array} array * * @returns {Any} */ export const last = array => array[_.lengthOf(array) - 1]; /** * Returns a subarray from the array. * @param {Array} array * @param {number} from Initial index, included in the result * @param {number} to Last index, not included in the result * * @returns {Array} */ export const slice = _.curry3((array, from, to) => protoSlice.call(array, from, to) ); /** * Returns a subarray from the array * starting from the provided index, * till the end of the array * @param {Array} array * @param {number} from Initial index, included in the result * * @returns {Array} */ export const sliceFrom = _.curry2((array, from) => protoSlice.call(array, from) ); /** * Array.prototype.reduce * @param {Array} array * @param {function (accumulator: *, currentValue: *): *} reducer * @param {Any} initialValue * * @returns {Any} */ export const reduce = _.curry3((array, reducer, initialValue) => proto.reduce.call(array, reducer, initialValue) ); /** * Merges array1 into array2. * Result: [...array2, ...array2] * @param {Array} arr1 * @param {Array} arr2 * * @returns {Array} */ export const merge = _.curry2((arr1, arr2) => { const arr2Len = _.lengthOf(arr2); var combinedArray = Array(arr2Len + _.lengthOf(arr1)); loop(arr2, (member, index) => (combinedArray[index] = member)); loop(arr1, (member, index) => (combinedArray[index + arr2Len] = member)); return combinedArray; }); /** * Merges array1 with array2. * Result: [...array1, ...array2] * @param {Array} arr1 * @param {Array} arr2 * * @returns {Array} */ export const mergeWith = _.curry2((arr1, arr2) => { return merge(arr2, arr1); }); /** * Inserts (pushes) an element in the array * at the given index. * @param {Array} array * @param {*} item * @param {number} index * * @returns {Array} */ export const insertAt = _.curry3((array, item, index) => { if (index > array.length - 1) { const inserted = sliceFrom(array, 0); inserted[index] = item; return inserted; } else { const first = slice(array, 0, index); const middle = [item]; const end = sliceFrom(array, index); return first |> mergeWith(middle) |> mergeWith(end); } }); /** * Returns a new array with duplicates removed. Uses equality comparison to * check for duplicates. * * @param {Array} array * * @returns {Array} */ export const removeDuplicates = array => reduce( array, (result, item) => { if (!contains(result, item)) { result.push(item); } return result; }, [] );
const { createReadStream } = require('fs') const { createInterface } = require('readline') async function processLineByLine(file) { return new Promise((resolve, reject) => { const objs = [] const rl = createInterface({ input: createReadStream(file), crlfDelay: Infinity }); rl.on('line', (line) => { const obj = JSON.parse(line) objs.push(obj) }) rl.on('close', () => resolve(objs)) }) } module.exports = { processLineByLine }
import * as winston from 'winston' import fs from 'fs' import 'winston-daily-rotate-file' import config from 'config' const logDir = config.logPathConfig.infoLog; // directory path of log // check log exists fs.existsSync(logDir) || fs.mkdirSync(logDir); const logInfo = winston.createLogger({ format: winston.format.printf(info => `${info.message}`), transports: [ new winston.transports.DailyRotateFile({ filename: logDir + 'info_%DATE%.log', datePattern: 'YYYYMMDD_HH00', zippedArchive: false, maxSize: '20m', maxFiles: '1d' }) ], exitOnError: false }); export default logInfo
/** * Created by sammoth on 08/05/17. */ $(function() { const webSocketBridge = new channels.WebSocketBridge(); webSocketBridge.connect('/latest_blocks_list/'); var latest_blocks_table_rows = $("#latest-blocks-table>tbody tr"); var first_row = $("#latest-blocks-table>tbody tr:first"); webSocketBridge.socket.addEventListener('open', function() { webSocketBridge.listen(function (data, channel) { var message_type = data["message_type"]; if (message_type === "new_block") { var block_html = data["block_html"]; first_row.before(block_html); } if (message_type === "update_block") { var index = data["index"]; var block_html = data["block_html"]; var block_is_valid = data["block_is_valid"]; var row = latest_blocks_table_rows.eq(index); row.fadeOut('fast', function () { if (block_is_valid) { row.removeClass("warning") } else { row.addClass("warning") } row.html(block_html).fadeIn('fast') }); } }); }); });
/** * @theroyalwhee0/dynasty:test/depends.spec.js */ /** * Imports. */ const chai = require('chai'); const { DepGraph } = require('dependency-graph'); const { buildGraph, transformDeps, getDirectDependenciesOf } = require('../src/depends'); const { mockDepends } = require('./general.mock'); const { expect } = chai; /** * Test. */ describe('dynasty', () => { describe('depends', () => { describe('buildGraph', () => { it('should be a function', () => { expect(buildGraph).to.be.a('function'); expect(buildGraph.length).to.equal(1); }); it('should be able to build an empty graph', () => { const dg = buildGraph({ }); expect(dg).to.be.an.instanceOf(DepGraph); const nodeNames = Object.keys(dg.nodes); expect(nodeNames.length).to.equal(0); }); it('should be able to build a graph', () => { const input = { "start": { "name": "start", "depends": { "app": "app" } }, "app": { "name": "app", "attach": { "log": "log" }, "depends": { "reports": "reports" } }, "log": { "name": "log" }, "reports": { "name": "reports" } }; const dg = buildGraph(input); expect(dg).to.be.an.instanceOf(DepGraph); expect(dg.nodes).to.deep.equal({ "start": { "name": "start", "depends": { "app": "app" } }, "app": { "name": "app", "attach": { "log": "log" }, "depends": { "reports": "reports" } }, "log": { "name": "log" }, "reports": { "name": "reports" } }); expect(dg.outgoingEdges).to.deep.equal({ "start": [ "app" ], "app": [ "reports", "log" ], "log": [], "reports": [] }); expect(dg.incomingEdges).to.deep.equal({ "start": [], "app": [ "start" ], "log": [ "app" ], "reports": [ "app" ] }); expect(dg.circular).to.equal(undefined); }); }); describe('getDirectDependenciesOf', () => { it('should be a function', () => { expect(getDirectDependenciesOf).to.be.a('function'); expect(getDirectDependenciesOf.length).to.equal(2); }); it('should throw if not given depgraph', async () => { expect(() => { getDirectDependenciesOf(null, 'dne'); }).to.throw('"depGraph" must be a DepGraph'); }); it('should throw if node not found', () => { const depGraph= mockDepends(); expect(() => { getDirectDependenciesOf(depGraph, 'dne'); }).to.throw('Node "dne" not found'); }); it('should get direct depends', () => { const depGraph = mockDepends({ aaa: true, bbb: [ 'aaa', 'ccc' ], ccc: [ 'ddd' ], ddd: [ 'eee' ], eee: true, }); const results = getDirectDependenciesOf(depGraph, 'bbb'); expect(results).to.deep.equal([ 'aaa', 'ccc' ]); }); it('should get direct depends even if empty', () => { const depGraph = mockDepends({ aaa: true, bbb: [ 'aaa', 'ccc' ], ccc: [ 'ddd' ], ddd: [ 'eee' ], eee: true, }); const results = getDirectDependenciesOf(depGraph, 'eee'); expect(results).to.deep.equal([ ]); }); }); describe('transformDeps', () => { // NOTE: Object key is dependency name, object value is export name. it('should be a function', () => { expect(transformDeps).to.be.a('function'); expect(transformDeps.length).to.equal(1); }); it('should transform simple dependencies', () => { const results = transformDeps([ 'item1', 'item2' ]); expect(results).to.be.an('object'); expect(results).to.deep.equal({ item1: 'item1', item2: 'item2', }); }); it('should transform aliased dependencies', () => { const results = transformDeps([ 'item1', { item2: 'alias1' } ]); expect(results).to.be.an('object'); expect(results).to.deep.equal({ item1: 'item1', item2: 'alias1', }); }); it('should throw if given an array', () => { // NOTE: Numbers are not supported as names. expect(() => { transformDeps({ }); }).to.throw(/"dependancies" should be an array/i); }); it('should throw if given invalid type', () => { // NOTE: Numbers are not supported. expect(() => { transformDeps([ 1000 ]); }).to.throw(/unrecognized value "1000" \(number\)/i); }); it('should throw if given invalid object value type', () => { // NOTE: Numbers are not supported. expect(() => { transformDeps([ { item1: 1000 } ]); }).to.throw(/unrecognized object value "1000" \(number\)/i); }); }); }); });
import { Players } from '../../../api/players/players.js'; import { addPlayer } from '../../../api/players/methods.js'; Template.Hoc.events({ 'submit': (e, tmpl) => { e.preventDefault(); const player={ firstNameH: tmpl.find('#firstNameH').value, lastNameH: tmpl.find('#lastNameH').value, sportH: tmpl.find('#sportH').value, goalsH: tmpl.find('#goalsH').value, positionH: tmpl.find('#positionH').value }; tmpl.find('#firstNameH').value=""; tmpl.find('#lastNameH').value=""; tmpl.find('#goalsH').value=""; tmpl.find('#positionH').value=""; tmpl.find('#sportH').value=""; Players.insert(player); } });
'use strict'; /* Filters */ angular.module('scrobbleAlong.filters', []). filter('formatScrobbleTimeoutTime', function () { return function (timestamp) { var difference = timestamp - new Date().getTime(); if (difference < (60 * 1000)) { return "soon"; } else { var hours = parseInt(difference / (60 * 60 * 1000)); var minutes = Math.round((difference - (hours * 60 * 60 * 1000)) / (60 * 1000)); if (minutes == 60) { minutes = 0; hours++; } return "in " + hours + " hrs and " + minutes + " mins"; } }; });
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import 'babel-polyfill'; import path from 'path'; import express from 'express'; import cookieParser from 'cookie-parser'; import session from 'express-session'; import redis from 'connect-redis'; import bodyParser from 'body-parser'; import ReactDOM from 'react-dom/server'; import UniversalRouter from 'universal-router'; import PrettyError from 'pretty-error'; import routes from './routes'; import apiServer from './services'; import {apiFetch, javaApiFtech} from './services/services-util'; import assets from './assets'; // eslint-disable-line import/no-unresolved import {port, redisConfig, webUrl, Debug,imageCDN,appID} from './config'; import {serverFetch} from './utils/clientFetch'; import tokenRedis from "./wechat-sdk/caches"; import wxRedis from "redis"; import os from "os"; import wxConfig from "./wechat-sdk/param" import upload from './services/routes/upload'; const app = express(); const RedisStore = redis(session); // // Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the // user agent is not known. // ----------------------------------------------------------------------------- global.navigator = global.navigator || {}; global.navigator.userAgent = global.navigator.userAgent || 'all'; // // Register Node.js middleware // ----------------------------------------------------------------------------- app.use(express.static(path.join(__dirname, 'public'))); app.use(cookieParser()); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.use(session({ name: "SSID", secret: "mfmw02", cookie:{maxAge:7*24*60*60*1000}, resave: false, saveUninitialized: true, store: new RedisStore(redisConfig), })); function getClientIp(req) { var ipAddress; var forwardedIpsStr = req.header('x-forwarded-for'); if (forwardedIpsStr) { var forwardedIps = forwardedIpsStr.split(','); ipAddress = forwardedIps[0]; } if (!ipAddress) { ipAddress = req.connection.remoteAddress; } return ipAddress; }; async function getWXCofing(URL){ let wxConinfo = await new tokenRedis().getJSSDKConfig(URL); return wxConinfo; } let pubParam = {}; async function getOpenid(req) { let userInfo = {}; return new tokenRedis(req.query.code).getOpeind().then(async result=> { userInfo.openid = result.openid; if (Debug) { return await apiFetch(req, "/user/getjxzinfo", userInfo); } else { return await apiFetch(req, "/user/getjxzinfo", result); } }).then(res=> { if (res.code === 200) { userInfo.id = res.data.id; userInfo.user_vip_id = res.data.user_vip_id; pubParam[req.session.cookie] = userInfo; req.session.userInfo = pubParam[req.session.cookie]; return true; } return false; }) } function is_weixin(userAgent) { var ua = userAgent.toLowerCase(); if (ua.match(/MicroMessenger/i) == "micromessenger") { return true; } else { return false; } } app.get('/boutiquerMember/renew_get',(req,res,next)=>{ res.redirect("/boutiquerMember/renew/"); }) // // Register server-side rendering middleware // ----------------------------------------------------------------------------- app.get('*', async(req, res, next) => { try { let css = []; let statusCode = 200; let pageData = {}; let errorType; const template = require('./views/index.jade'); // eslint-disable-line global-require const data = {title: '', description: '', css: '', body: '', entry: assets.main.js}; /** * 存储用户的openid和 users_id */ if (Debug) { await getOpenid(req); } else { if (!req.session['userInfo']) { if (is_weixin(req.get("User-Agent"))) { if (req.query.code) { let openid = await getOpenid(req); if (!openid && req.url.split("?")[0] !== "/error") { errorType = "service"; res.redirect("/error?errorType=" + errorType); return true; } } else { let url = encodeURIComponent(webUrl + req.url); res.redirect(302, "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appID+"&redirect_uri=" + url + "&response_type=code&scope=snsapi_userinfo#wechat_redirect"); return true; } } else { if (req.url.split("?")[0] !== "/error") { errorType = "browse"; res.redirect(302, "/error?errorType=" + errorType); return true; } } } } await UniversalRouter.resolve(routes, { path: req.path, query: req.query, cookie: req.headers.cookie, session: req.session, context: { insertCss: (...styles) => { styles.forEach(style => css.push(style._getCss())); // eslint-disable-line no-underscore-dangle, max-len }, setTitle: value => (data.title = value), setMeta: (key, value) => (data[key] = value), setPageData: (key, value)=> { pageData[key] = value; }, getPageData(){ return false; } }, render(component, status = 200) { css = []; statusCode = status; data.pageData = `var pageData=${JSON.stringify(Object.assign(pageData))};`; data.body = ReactDOM.renderToString(component); data.css = css.join(''); data.remScript = "var _href=window.location.href;var _imgCDN = '" + imageCDN + "'; (function(){function a(d,c,e){if(d.addEventListener){d.addEventListener(c,e,false)}else{d.attachEvent('on'+c,e)}}" + "function b(){var c=document.documentElement.clientWidth||document.body.clientWidth;document.documentElement.style.fontSize=c/3.75+'px'}" + "b();a(window,'resize',b)}());"; return true; }, }); if (pubParam[req.session.cookie]) delete pubParam[req.session.cookie]; res.status(statusCode); res.send(template(data)); } catch (err) { next(err); } }); async function backWXResult(req) { return new Promise((resolve, reject)=> { req.on("data", async function (res) { let wxNotify; let task = await javaApiFtech(req, "/pay/nodenotify", {body: res.toString()}); if (task.code === 0 && task.data.valid) { if (task.data.success) { wxNotify = task.data.successResponse; } else { wxNotify = task.data.failureResponse; } } else { wxNotify = task.data.failureResponse; } resolve(wxNotify); }); }) } /** * 微信通知 */ app.post("/wxNotify", async(req, res)=> { let result = await backWXResult(req); res.setHeader('content-type', 'text/xml'); res.send(result); }) app.post("/wxCofig", async(req, res)=> { let WXConInfo = await getWXCofing(req.body.url); res.setHeader('content-type', 'application/json'); res.send(WXConInfo); }) app.use('/upload',upload); app.post('*', async(req, res, next) => { let _json; if (pubParam[req.session.cookie])req.session.userInfo = pubParam[req.session.cookie]; await UniversalRouter.resolve(apiServer, { path: req.path, query: req.query, req, res, taskURL:webUrl+"/wxNotify", ClientIp: getClientIp(req), send: function (content) { _json = content; }, }); res.json(_json); next(); }); // // Error handling // ----------------------------------------------------------------------------- const pe = new PrettyError(); pe.skipNodeFiles(); pe.skipPackage('express'); app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars console.log(pe.render(err)); // eslint-disable-line no-console const template = require('./views/error.jade'); // eslint-disable-line global-require const statusCode = err.status || 500; res.status(statusCode); res.send(template({ message: err.message, stack: process.env.NODE_ENV === 'production' ? '' : err.stack, })); }); // // Launch the server // ----------------------------------------------------------------------------- /* eslint-disable no-console */ app.listen(port, () => { console.log(`The server is running at http://localhost:${port}/`); }); /* eslint-enable no-console */
var form = document.getElementById('formsignup'); var firstName = document.getElementById("firstName").value; var lastName = document.getElementById('lastName').value; var password = document.getElementById('password').value; var email = document.getElementById('email').value; // form.addEventListener('submit', (e) => { // e.preventDefault(); // checkInputs(); // }); function checkInputs() { if (firstName == "") { setError(firstName, 'first name cannot be empty'); } else { setSuccess(firstName); } if (lastName == "") { setError(lastName, 'last name cannot be empty'); } else { setSuccess(lastName); } if (email == "") { setError(email, 'email cannot be empty'); } else if (!isEmail(emailValue)) { setError(email, 'email is not valid'); } else { setSuccess(email); } if (password == "") { setError(password, 'password cannot be empty'); } } function setError(input, message) { let signupControl = document.getElementById(input).nodeName; const small = signupControl.getElementById('small'); small.innerHTML = message; //signupControl.className += " error"; signupControl.classList.add(" error"); } function setSuccess(input) { const signupControl = input.parentElement; //signupControl.className += " success"; signupControl.classList.add(" success"); } function isEmail(email) { return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email); }
import React, { useEffect } from 'react'; import './App.css'; import { Switch } from '@material-ui/core'; import MediaCard from './Comphonent/comphonent/News.js/News'; import { useState } from 'react'; function App() { const [articles, setAirticles]= useState([]) useEffect( () => { fetch('https://newsapi.org/v2/top-headlines?country=us&apiKey=0fc06a8e019240e1ba2291db460dd336') .then(res=>res.json()) .then(data=>setAirticles(data.articles)) }, []) return ( <div> <Switch></Switch> <h1>news hadline{articles.length}</h1> { articles.map(article=><MediaCard article={article}></MediaCard>) } </div> ); } export default App;
var mongoose = require("mongoose"); var Schema = mongoose.Schema, ObjectId = Schema.ObjectId; // var CommentModel = require("./comments"); var mongoosepages=require('mongoose-pages'); var TaskSchema = new Schema({ email: String, firstName: String, lastName: String, password: String, confirmPassword: String, phone:Number }); mongoosepages.skip(TaskSchema); var task=mongoose.model('tasks', TaskSchema); module.exports = task;
/** * Created by Administrator on 16-9-6. */ //hodo owm (function() { var AttributeUI, ContentTools, CropMarksUI, StyleUI, TimeDialog, TimeTool, exports, _EditorApp, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __slice = [].slice; ContentTools = { bgcolor:null, color:null, on:false, hex:null, Tools: {}, CANCEL_MESSAGE: 'Your changes have not been saved, do you really want to lose them?'.trim(), DEFAULT_TOOLS: [['bold', 'italic', 'link', 'align-left', 'align-center', 'align-right'], ['heading', 'subheading', 'paragraph', 'unordered-list', 'ordered-list', 'table', 'indent', 'unindent', 'line-break'], ['image', 'video', 'preformatted'], ['undo', 'redo', 'remove','color','bgcolor']], DEFAULT_VIDEO_HEIGHT: 300, DEFAULT_VIDEO_WIDTH: 400, HIGHLIGHT_HOLD_DURATION: 2000, INSPECTOR_IGNORED_ELEMENTS: ['Fixture', 'ListItemText', 'Region', 'TableCellText'], IMAGE_UPLOADER: null, MIN_CROP: 10, RESTRICTED_ATTRIBUTES: { '*': ['style'], 'img': ['height', 'src', 'width', 'data-ce-max-width', 'data-ce-min-width'], 'iframe': ['height', 'width'] }, getEmbedVideoURL: function(url) { var domains, id, k, kv, m, netloc, paramStr, params, paramsStr, parser, path, v, _i, _len, _ref; domains = { 'www.youtube.com': 'youtube', 'youtu.be': 'youtube', 'vimeo.com': 'vimeo', 'player.vimeo.com': 'vimeo' }; parser = document.createElement('a'); parser.href = url; netloc = parser.hostname.toLowerCase(); path = parser.pathname; if (path !== null && path.substr(0, 1) !== "/") { path = "/" + path; } params = {}; paramsStr = parser.search.slice(1); _ref = paramsStr.split('&'); for (_i = 0, _len = _ref.length; _i < _len; _i++) { kv = _ref[_i]; kv = kv.split("="); if (kv[0]) { params[kv[0]] = kv[1]; } } switch (domains[netloc]) { case 'youtube': if (path.toLowerCase() === '/watch') { if (!params['v']) { return null; } id = params['v']; delete params['v']; } else { m = path.match(/\/([A-Za-z0-9_-]+)$/i); if (!m) { return null; } id = m[1]; } url = "https://www.youtube.com/embed/" + id; paramStr = ((function() { var _results; _results = []; for (k in params) { v = params[k]; _results.push("" + k + "=" + v); } return _results; })()).join('&'); if (paramStr) { url += "?" + paramStr; } return url; case 'vimeo': m = path.match(/\/(\w+\/\w+\/){0,1}(\d+)/i); if (!m) { return null; } url = "https://player.vimeo.com/video/" + m[2]; paramStr = ((function() { var _results; _results = []; for (k in params) { v = params[k]; _results.push("" + k + "=" + v); } return _results; })()).join('&'); if (paramStr) { url += "?" + paramStr; } return url; } return null; }, getRestrictedAtributes: function(tagName) { var restricted; restricted = []; if (ContentTools.RESTRICTED_ATTRIBUTES[tagName]) { restricted = restricted.concat(ContentTools.RESTRICTED_ATTRIBUTES[tagName]); } if (ContentTools.RESTRICTED_ATTRIBUTES['*']) { restricted = restricted.concat(ContentTools.RESTRICTED_ATTRIBUTES['*']); } return restricted; }, getScrollPosition: function() { var isCSS1Compat, supportsPageOffset; supportsPageOffset = window.pageXOffset !== void 0; isCSS1Compat = (document.compatMode || 4) === 4; if (supportsPageOffset) { return [window.pageXOffset, window.pageYOffset]; } else if (isCSS1Compat) { return [document.documentElement.scrollLeft, document.documentElement.scrollTop]; } else { return [document.body.scrollLeft, document.body.scrollTop]; } } }; if (typeof window !== 'undefined') { window.ContentTools = ContentTools; } if (typeof module !== 'undefined' && module.exports) { exports = module.exports = ContentTools; } ContentTools.ComponentUI = (function() { function ComponentUI() { this._bindings = {}; this._parent = null; this._children = []; this._domElement = null; } ComponentUI.prototype.children = function() { return this._children.slice(); }; ComponentUI.prototype.domElement = function() { return this._domElement; }; ComponentUI.prototype.isMounted = function() { return this._domElement !== null; }; ComponentUI.prototype.parent = function() { return this._parent; }; ComponentUI.prototype.attach = function(component, index) { if (component.parent()) { component.parent().detach(component); } component._parent = this; if (index !== void 0) { return this._children.splice(index, 0, component); } else { return this._children.push(component); } }; ComponentUI.prototype.addCSSClass = function(className) { if (!this.isMounted()) { return; } return ContentEdit.addCSSClass(this._domElement, className); }; ComponentUI.prototype.detatch = function(component) { var componentIndex; componentIndex = this._children.indexOf(component); if (componentIndex === -1) { return; } return this._children.splice(componentIndex, 1); }; ComponentUI.prototype.mount = function() {}; ComponentUI.prototype.removeCSSClass = function(className) { if (!this.isMounted()) { return; } return ContentEdit.removeCSSClass(this._domElement, className); }; ComponentUI.prototype.unmount = function() { if (!this.isMounted()) { return; } this._removeDOMEventListeners(); if (this._domElement.parentNode) { this._domElement.parentNode.removeChild(this._domElement); } return this._domElement = null; }; ComponentUI.prototype.addEventListener = function(eventName, callback) { if (this._bindings[eventName] === void 0) { this._bindings[eventName] = []; } this._bindings[eventName].push(callback); }; ComponentUI.prototype.createEvent = function(eventName, detail) { return new ContentTools.Event(eventName, detail); }; ComponentUI.prototype.dispatchEvent = function(ev) { var callback, _i, _len, _ref; if (!this._bindings[ev.name()]) { return !ev.defaultPrevented(); } _ref = this._bindings[ev.name()]; for (_i = 0, _len = _ref.length; _i < _len; _i++) { callback = _ref[_i]; if (ev.propagationStopped()) { break; } if (!callback) { continue; } callback.call(this, ev); } return !ev.defaultPrevented(); }; ComponentUI.prototype.removeEventListener = function(eventName, callback) { var i, suspect, _i, _len, _ref, _results; if (!eventName) { this._bindings = {}; return; } if (!callback) { this._bindings[eventName] = void 0; return; } if (!this._bindings[eventName]) { return; } _ref = this._bindings[eventName]; _results = []; for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { suspect = _ref[i]; if (suspect === callback) { _results.push(this._bindings[eventName].splice(i, 1)); } else { _results.push(void 0); } } return _results; }; ComponentUI.prototype._addDOMEventListeners = function() {}; ComponentUI.prototype._removeDOMEventListeners = function() {}; ComponentUI.createDiv = function(classNames, attributes, content) { var domElement, name, value; domElement = document.createElement('div'); if (classNames && classNames.length > 0) { domElement.setAttribute('class', classNames.join(' ')); } if (attributes) { for (name in attributes) { value = attributes[name]; domElement.setAttribute(name, value); } } if (content) { domElement.innerHTML = content; } return domElement; }; return ComponentUI; })(); ContentTools.WidgetUI = (function(_super) { __extends(WidgetUI, _super); function WidgetUI() { return WidgetUI.__super__.constructor.apply(this, arguments); } WidgetUI.prototype.attach = function(component, index) { WidgetUI.__super__.attach.call(this, component, index); if (!this.isMounted()) { return component.mount(); } }; WidgetUI.prototype.detatch = function(component) { WidgetUI.__super__.detatch.call(this, component); if (this.isMounted()) { return component.unmount(); } }; WidgetUI.prototype.show = function() { var fadeIn; if (!this.isMounted()) { this.mount(); } fadeIn = (function(_this) { return function() { return _this.addCSSClass('ct-widget--active'); }; })(this); return setTimeout(fadeIn, 100); }; WidgetUI.prototype.hide = function() { var monitorForHidden; this.removeCSSClass('ct-widget--active'); monitorForHidden = (function(_this) { return function() { if (!window.getComputedStyle) { _this.unmount(); return; } if (parseFloat(window.getComputedStyle(_this._domElement).opacity) < 0.01) { return _this.unmount(); } else { return setTimeout(monitorForHidden, 250); } }; })(this); if (this.isMounted()) { return setTimeout(monitorForHidden, 250); } }; return WidgetUI; })(ContentTools.ComponentUI); ContentTools.AnchoredComponentUI = (function(_super) { __extends(AnchoredComponentUI, _super); function AnchoredComponentUI() { return AnchoredComponentUI.__super__.constructor.apply(this, arguments); } AnchoredComponentUI.prototype.mount = function(domParent, before) { if (before == null) { before = null; } domParent.insertBefore(this._domElement, before); return this._addDOMEventListeners(); }; return AnchoredComponentUI; })(ContentTools.ComponentUI); ContentTools.Event = (function() { function Event(name, detail) { this._name = name; this._detail = detail; this._timeStamp = Date.now(); this._defaultPrevented = false; this._propagationStopped = false; } Event.prototype.defaultPrevented = function() { return this._defaultPrevented; }; Event.prototype.detail = function() { return this._detail; }; Event.prototype.name = function() { return this._name; }; Event.prototype.propagationStopped = function() { return this._propagationStopped; }; Event.prototype.timeStamp = function() { return this._timeStamp; }; Event.prototype.preventDefault = function() { return this._defaultPrevented = true; }; Event.prototype.stopImmediatePropagation = function() { return this._propagationStopped = true; }; return Event; })(); ContentTools.FlashUI = (function(_super) { __extends(FlashUI, _super); function FlashUI(modifier) { FlashUI.__super__.constructor.call(this); this.mount(modifier); } FlashUI.prototype.mount = function(modifier) { var monitorForHidden; this._domElement = this.constructor.createDiv(['ct-flash', 'ct-flash--active', "ct-flash--" + modifier, 'ct-widget', 'ct-widget--active']); FlashUI.__super__.mount.call(this, ContentTools.EditorApp.get().domElement()); monitorForHidden = (function(_this) { return function() { if (!window.getComputedStyle) { _this.unmount(); return; } if (parseFloat(window.getComputedStyle(_this._domElement).opacity) < 0.01) { return _this.unmount(); } else { return setTimeout(monitorForHidden, 250); } }; })(this); return setTimeout(monitorForHidden, 250); }; return FlashUI; })(ContentTools.AnchoredComponentUI); //hodo SectionUI ContentTools.SectionUI=(function(_super) { __extends(SectionUI, _super); function SectionUI(sectionName, listArr) { SectionUI.__super__.constructor.call(this); this.sectionName=sectionName; this.listArr=listArr; } SectionUI.prototype.mount = function() { SectionUI.__super__.mount.call(this); this._domElement = this.constructor.createDiv(['hd-editor']); console.log(this.parent()) this.parent().domElement().appendChild(this._domElement); var inithtml='<div class="hd-editor-nav">'+this.sectionName+'</div>'; function mount(listArr) { for(var i=0;i<listArr.length;i++){ inithtml+='<div class="hd-editor-list"><span class="list-hover"></span><span class="list-img"></span><span class="list-text">'+listArr[i]+'</span></div>'; } var _domElement=document.getElementsByClassName('hd-editor')[0]; _domElement.innerHTML=inithtml; } mount(this.listArr); function stylehover() { var editList = document.getElementsByClassName('hd-editor-list'); var listHover = document.getElementsByClassName('list-hover'); for (var i = 0; i < editList.length; i++) { editList[i].addEventListener('mousemove', (function (i) { return function () { listHover[i].style.backgroundColor = 'red'; } })(i)) editList[i].addEventListener('mouseout', (function (i) { return function () { listHover[i].style.backgroundColor = 'orange'; } })(i)) } } stylehover(); }; return SectionUI; })(ContentTools.WidgetUI); ContentTools.TagUI = (function(_super) { __extends(TagUI, _super); function TagUI(element) { this.element = element; this._onMouseDown = __bind(this._onMouseDown, this); TagUI.__super__.constructor.call(this); } TagUI.prototype.mount = function(domParent, before) { if (before == null) { before = null; } this._domElement = this.constructor.createDiv(['ct-tag']); this._domElement.textContent = this.element.tagName(); return TagUI.__super__.mount.call(this, domParent, before); }; TagUI.prototype._addDOMEventListeners = function() { return this._domElement.addEventListener('mousedown', this._onMouseDown); }; TagUI.prototype._onMouseDown = function(ev) { var app, dialog, modal; ev.preventDefault(); if (this.element.storeState) { this.element.storeState(); } app = ContentTools.EditorApp.get(); modal = new ContentTools.ModalUI(); dialog = new ContentTools.PropertiesDialog(this.element); dialog.addEventListener('cancel', (function(_this) { return function() { modal.hide(); dialog.hide(); if (_this.element.restoreState) { return _this.element.restoreState(); } }; })(this)); dialog.addEventListener('save', (function(_this) { return function(ev) { var applied, attributes, className, classNames, cssClass, detail, element, innerHTML, name, styles, value, _i, _j, _len, _len1, _ref, _ref1; detail = ev.detail(); attributes = detail.changedAttributes; styles = detail.changedStyles; innerHTML = detail.innerHTML; for (name in attributes) { value = attributes[name]; if (name === 'class') { if (value === null) { value = ''; } classNames = {}; _ref = value.split(' '); for (_i = 0, _len = _ref.length; _i < _len; _i++) { className = _ref[_i]; className = className.trim(); if (!className) { continue; } classNames[className] = true; if (!_this.element.hasCSSClass(className)) { _this.element.addCSSClass(className); } } _ref1 = _this.element.attr('class').split(' '); for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { className = _ref1[_j]; className = className.trim(); if (classNames[className] === void 0) { _this.element.removeCSSClass(className); } } } else { if (value === null) { _this.element.removeAttr(name); } else { _this.element.attr(name, value); } } } for (cssClass in styles) { applied = styles[cssClass]; if (applied) { _this.element.addCSSClass(cssClass); } else { _this.element.removeCSSClass(cssClass); } } if (innerHTML !== null) { if (innerHTML !== dialog.getElementInnerHTML()) { element = _this.element; if (!element.content) { element = element.children[0]; } element.content = new HTMLString.String(innerHTML, element.content.preserveWhitespace()); element.updateInnerHTML(); element.taint(); element.selection(new ContentSelect.Range(0, 0)); element.storeState(); } } modal.hide(); dialog.hide(); if (_this.element.restoreState) { return _this.element.restoreState(); } }; })(this)); app.attach(modal); app.attach(dialog); modal.show(); return dialog.show(); }; return TagUI; })(ContentTools.AnchoredComponentUI); //hodo own ContentTools.ColorPickerUI=(function (_super) { __extends(ColorPickerUI, _super); function ColorPickerUI() { ColorPickerUI.__super__.constructor.call(this); this._onStopDragging = __bind(this._onStopDragging, this); this._onStartDragging = __bind(this._onStartDragging, this); this._onDrag = __bind(this._onDrag, this); this._dragging = false; this._draggingOffset = null; /*this._domColorDrag=null; this._domColor=null;*/ }; ColorPickerUI.prototype.mount=function () { var coord, position, restore; this._domElement=this.constructor.createDiv(['cp-all']); this.parent().domElement().appendChild(this._domElement); this._domColorDrag= this.constructor.createDiv(['cp-colordrag']); this._domElement.appendChild(this._domColorDrag); this._domColor = this.constructor.createDiv(['cp-default']); this._domElement.appendChild(this._domColor); restore = window.localStorage.getItem('ct-colorpicker-position'); if (restore && /^\d+,\d+$/.test(restore)) { position = (function () { var _i, _len, _ref, _results; _ref = restore.split(','); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { coord = _ref[_i]; _results.push(parseInt(coord)); } return _results; })(); this._domElement.style.left = "" + position[0] + "px"; this._domElement.style.top = "" + position[1] + "px"; this._contain(); } return this._addDOMEventListeners(); }; ColorPickerUI.prototype.isDragging = function() { return this._dragging; }; ColorPickerUI.prototype._removeDOMEventListeners = function() { if (this.isMounted()) { return this._domElement.removeEventListener('mousedown', this._onStartDragging); } }; ColorPickerUI.prototype._addDOMEventListeners = function() { this._domColorDrag.addEventListener('mousedown', this._onStartDragging); } ColorPickerUI.prototype._onStartDragging = function(ev) { var rect; ev.preventDefault(); if (this.isDragging()) { return; } this._dragging = true; this.addCSSClass('ct-toolbox--dragging'); rect = this._domElement.getBoundingClientRect(); this._draggingOffset = { x: ev.clientX - rect.left, y: ev.clientY - rect.top }; document.addEventListener('mousemove', this._onDrag); document.addEventListener('mouseup', this._onStopDragging); return ContentEdit.addCSSClass(document.body, 'ce--dragging'); }; ColorPickerUI.prototype._onStopDragging = function(ev) { if (!this.isDragging()) { return; } this._contain(); document.removeEventListener('mousemove', this._onDrag); document.removeEventListener('mouseup', this._onStopDragging); this._draggingOffset = null; this._dragging = false; this.removeCSSClass('ct-toolbox--dragging'); return ContentEdit.removeCSSClass(document.body, 'ce--dragging'); }; ColorPickerUI.prototype._onDrag = function(ev) { ContentSelect.Range.unselectAll(); this._domElement.style.left = "" + (ev.clientX - this._draggingOffset.x) + "px"; return this._domElement.style.top = "" + (ev.clientY - this._draggingOffset.y) + "px"; }; ColorPickerUI.prototype._contain = function() { var rect; if (!this.isMounted()) { return; } rect = this._domElement.getBoundingClientRect(); if (rect.left + rect.width > window.innerWidth) { this._domElement.style.left = "" + (window.innerWidth - rect.width) + "px"; } if (rect.top + rect.height > window.innerHeight) { this._domElement.style.top = "" + (window.innerHeight - rect.height) + "px"; } if (rect.left < 0) { this._domElement.style.left = '0px'; } if (rect.top < 0) { this._domElement.style.top = '0px'; } rect = this._domElement.getBoundingClientRect(); return window.localStorage.setItem('ct-colorpicker-position', "" + rect.left + "," + rect.top); }; ColorPickerUI.prototype.show=function () { ContentTools.on=true; var fadeIn; if(document.getElementsByClassName('cp-default').length<1){ this.mount(); } fadeIn = (function(_this) { return function() { return _this.addCSSClass('ct-widget--active'); }; })(this); return setTimeout(fadeIn, 100); } ColorPickerUI.prototype.hide = function() { ContentTools.on=false; this._removeDOMEventListeners(); this.parent().domElement().removeChild(document.getElementsByClassName('cp-all')[0]); return this._domElement=null; }; return ColorPickerUI; })(ContentTools.WidgetUI); ContentTools.ToolUI = (function(_super) { __extends(ToolUI, _super); function ToolUI(tool) { this._onMouseUp = __bind(this._onMouseUp, this); this._onMouseLeave = __bind(this._onMouseLeave, this); this._onMouseDown = __bind(this._onMouseDown, this); this._addDOMEventListeners = __bind(this._addDOMEventListeners, this); ToolUI.__super__.constructor.call(this); this.tool = tool; this._mouseDown = false; this._disabled = false; } ToolUI.prototype.apply = function(element, selection) { var callback, detail; if (!this.tool.canApply(element, selection)) { return; } detail = { 'element': element, 'selection': selection }; callback = (function(_this) { return function(applied) { if (applied) { return _this.dispatchEvent(_this.createEvent('applied', detail)); } }; })(this); if (this.dispatchEvent(this.createEvent('apply', detail))) { return this.tool.apply(element, selection, callback); } }; ToolUI.prototype.disabled = function(disabledState) { if (disabledState === void 0) { return this._disabled; } if (this._disabled === disabledState) { return; } this._disabled = disabledState; if (disabledState) { this._mouseDown = false; this.addCSSClass('ct-tool--disabled'); return this.removeCSSClass('ct-tool--applied'); } else { return this.removeCSSClass('ct-tool--disabled'); } }; ToolUI.prototype.mount = function(domParent, before) { if (before == null) { before = null; } this._domElement = this.constructor.createDiv(['ct-tool', "ct-tool--" + this.tool.icon]); this._domElement.setAttribute('data-ct-tooltip', ContentEdit._(this.tool.label)); return ToolUI.__super__.mount.call(this, domParent, before); }; ToolUI.prototype.update = function(element, selection) { if (this.tool.requiresElement) { if (!(element && element.isMounted())) { this.disabled(true); return; } } if (this.tool.canApply(element, selection)) { this.disabled(false); } else { this.disabled(true); return; } if (this.tool.isApplied(element, selection)) { return this.addCSSClass('ct-tool--applied'); } else { return this.removeCSSClass('ct-tool--applied'); } }; ToolUI.prototype._addDOMEventListeners = function() { this._domElement.addEventListener('mousedown', this._onMouseDown); this._domElement.addEventListener('mouseleave', this._onMouseLeave); return this._domElement.addEventListener('mouseup', this._onMouseUp); }; ToolUI.prototype._onMouseDown = function(ev) { ev.preventDefault(); if (this.disabled()) { return; } this._mouseDown = true; return this.addCSSClass('ct-tool--down'); }; ToolUI.prototype._onMouseLeave = function(ev) { this._mouseDown = false; return this.removeCSSClass('ct-tool--down'); }; ToolUI.prototype._onMouseUp = function(ev) { var element, selection; if (this._mouseDown) { element = ContentEdit.Root.get().focused(); if (this.tool.requiresElement) { if (!(element && element.isMounted())) { return; } } selection = null; if (element && element.selection) { selection = element.selection(); } this.apply(element, selection); } this._mouseDown = false; return this.removeCSSClass('ct-tool--down'); }; return ToolUI; })(ContentTools.AnchoredComponentUI); ContentTools.AnchoredDialogUI = (function(_super) { __extends(AnchoredDialogUI, _super); function AnchoredDialogUI() { AnchoredDialogUI.__super__.constructor.call(this); this._position = [0, 0]; } AnchoredDialogUI.prototype.mount = function() { this._domElement = this.constructor.createDiv(['ct-widget', 'ct-anchored-dialog']); this.parent().domElement().appendChild(this._domElement); this._domElement.style.top = "" + this._position[1] + "px"; return this._domElement.style.left = "" + this._position[0] + "px"; }; AnchoredDialogUI.prototype.position = function(newPosition) { if (newPosition === void 0) { return this._position.slice(); } this._position = newPosition.slice(); if (this.isMounted()) { this._domElement.style.top = "" + this._position[1] + "px"; return this._domElement.style.left = "" + this._position[0] + "px"; } }; return AnchoredDialogUI; })(ContentTools.WidgetUI); ContentTools.DialogUI = (function(_super) { __extends(DialogUI, _super); function DialogUI(caption) { if (caption == null) { caption = ''; } DialogUI.__super__.constructor.call(this); this._busy = false; this._caption = caption; } DialogUI.prototype.busy = function(busy) { if (busy === void 0) { return this._busy; } if (this._busy === busy) { return; } this._busy = busy; if (!this.isMounted()) { return; } if (this._busy) { return ContentEdit.addCSSClass(this._domElement, 'ct-dialog--busy'); } else { return ContentEdit.removeCSSClass(this._domElement, 'ct-dialog--busy'); } }; DialogUI.prototype.caption = function(caption) { if (caption === void 0) { return this._caption; } this._caption = caption; return this._domCaption.textContent = ContentEdit._(caption); }; DialogUI.prototype.mount = function() { var dialogCSSClasses, domBody, domHeader; if (document.activeElement) { document.activeElement.blur(); window.getSelection().removeAllRanges(); } dialogCSSClasses = ['ct-widget', 'ct-dialog']; if (this._busy) { dialogCSSClasses.push('ct-dialog--busy'); } this._domElement = this.constructor.createDiv(dialogCSSClasses); this.parent().domElement().appendChild(this._domElement); domHeader = this.constructor.createDiv(['ct-dialog__header']); this._domElement.appendChild(domHeader); this._domCaption = this.constructor.createDiv(['ct-dialog__caption']); domHeader.appendChild(this._domCaption); this.caption(this._caption); this._domClose = this.constructor.createDiv(['ct-dialog__close']); domHeader.appendChild(this._domClose); domBody = this.constructor.createDiv(['ct-dialog__body']); this._domElement.appendChild(domBody); this._domView = this.constructor.createDiv(['ct-dialog__view']); domBody.appendChild(this._domView); this._domControls = this.constructor.createDiv(['ct-dialog__controls']); domBody.appendChild(this._domControls); this._domBusy = this.constructor.createDiv(['ct-dialog__busy']); return this._domElement.appendChild(this._domBusy); }; DialogUI.prototype.unmount = function() { DialogUI.__super__.unmount.call(this); this._domBusy = null; this._domCaption = null; this._domClose = null; this._domControls = null; return this._domView = null; }; DialogUI.prototype._addDOMEventListeners = function() { this._handleEscape = (function(_this) { return function(ev) { if (_this._busy) { return; } if (ev.keyCode === 27) { return _this.dispatchEvent(_this.createEvent('cancel')); } }; })(this); document.addEventListener('keyup', this._handleEscape); return this._domClose.addEventListener('click', (function(_this) { return function(ev) { ev.preventDefault(); if (_this._busy) { return; } return _this.dispatchEvent(_this.createEvent('cancel')); }; })(this)); }; DialogUI.prototype._removeDOMEventListeners = function() { return document.removeEventListener('keyup', this._handleEscape); }; return DialogUI; })(ContentTools.WidgetUI); ContentTools.ImageDialog = (function(_super) { __extends(ImageDialog, _super); function ImageDialog() { ImageDialog.__super__.constructor.call(this, 'Insert image'); this._cropMarks = null; this._imageURL = null; this._imageSize = null; this._progress = 0; this._state = 'empty'; if (ContentTools.IMAGE_UPLOADER) { ContentTools.IMAGE_UPLOADER(this); } } ImageDialog.prototype.cropRegion = function() { if (this._cropMarks) { return this._cropMarks.region(); } return [0, 0, 1, 1]; }; ImageDialog.prototype.addCropMarks = function() { if (this._cropMarks) { return; } this._cropMarks = new CropMarksUI(this._imageSize); this._cropMarks.mount(this._domView); return ContentEdit.addCSSClass(this._domCrop, 'ct-control--active'); }; ImageDialog.prototype.clear = function() { if (this._domImage) { this._domImage.parentNode.removeChild(this._domImage); this._domImage = null; } this._imageURL = null; this._imageSize = null; return this.state('empty'); }; ImageDialog.prototype.mount = function() { var domActions, domProgressBar, domTools; ImageDialog.__super__.mount.call(this); ContentEdit.addCSSClass(this._domElement, 'ct-image-dialog'); ContentEdit.addCSSClass(this._domElement, 'ct-image-dialog--empty'); ContentEdit.addCSSClass(this._domView, 'ct-image-dialog__view'); domTools = this.constructor.createDiv(['ct-control-group', 'ct-control-group--left']); this._domControls.appendChild(domTools); this._domRotateCCW = this.constructor.createDiv(['ct-control', 'ct-control--icon', 'ct-control--rotate-ccw']); this._domRotateCCW.setAttribute('data-ct-tooltip', ContentEdit._('Rotate') + ' -90°'); domTools.appendChild(this._domRotateCCW); this._domRotateCW = this.constructor.createDiv(['ct-control', 'ct-control--icon', 'ct-control--rotate-cw']); this._domRotateCW.setAttribute('data-ct-tooltip', ContentEdit._('Rotate') + ' 90°'); domTools.appendChild(this._domRotateCW); this._domCrop = this.constructor.createDiv(['ct-control', 'ct-control--icon', 'ct-control--crop']); this._domCrop.setAttribute('data-ct-tooltip', ContentEdit._('Crop marks')); domTools.appendChild(this._domCrop); domProgressBar = this.constructor.createDiv(['ct-progress-bar']); domTools.appendChild(domProgressBar); this._domProgress = this.constructor.createDiv(['ct-progress-bar__progress']); domProgressBar.appendChild(this._domProgress); domActions = this.constructor.createDiv(['ct-control-group', 'ct-control-group--right']); this._domControls.appendChild(domActions); this._domUpload = this.constructor.createDiv(['ct-control', 'ct-control--text', 'ct-control--upload']); this._domUpload.textContent = ContentEdit._('Upload'); domActions.appendChild(this._domUpload); this._domInput = document.createElement('input'); this._domInput.setAttribute('class', 'ct-image-dialog__file-upload'); this._domInput.setAttribute('name', 'file'); this._domInput.setAttribute('type', 'file'); this._domInput.setAttribute('accept', 'image/*'); this._domUpload.appendChild(this._domInput); this._domInsert = this.constructor.createDiv(['ct-control', 'ct-control--text', 'ct-control--insert']); this._domInsert.textContent = ContentEdit._('Insert'); domActions.appendChild(this._domInsert); this._domCancelUpload = this.constructor.createDiv(['ct-control', 'ct-control--text', 'ct-control--cancel']); this._domCancelUpload.textContent = ContentEdit._('Cancel'); domActions.appendChild(this._domCancelUpload); this._domClear = this.constructor.createDiv(['ct-control', 'ct-control--text', 'ct-control--clear']); this._domClear.textContent = ContentEdit._('Clear'); domActions.appendChild(this._domClear); this._addDOMEventListeners(); return this.dispatchEvent(this.createEvent('imageuploader.mount')); }; ImageDialog.prototype.populate = function(imageURL, imageSize) { this._imageURL = imageURL; this._imageSize = imageSize; if (!this._domImage) { this._domImage = this.constructor.createDiv(['ct-image-dialog__image']); this._domView.appendChild(this._domImage); } this._domImage.style['background-image'] = "url(" + imageURL + ")"; return this.state('populated'); }; ImageDialog.prototype.progress = function(progress) { if (progress === void 0) { return this._progress; } this._progress = progress; if (!this.isMounted()) { return; } return this._domProgress.style.width = "" + this._progress + "%"; }; ImageDialog.prototype.removeCropMarks = function() { if (!this._cropMarks) { return; } this._cropMarks.unmount(); this._cropMarks = null; return ContentEdit.removeCSSClass(this._domCrop, 'ct-control--active'); }; ImageDialog.prototype.save = function(imageURL, imageSize, imageAttrs) { return this.dispatchEvent(this.createEvent('save', { 'imageURL': imageURL, 'imageSize': imageSize, 'imageAttrs': imageAttrs })); }; ImageDialog.prototype.state = function(state) { var prevState; if (state === void 0) { return this._state; } if (this._state === state) { return; } prevState = this._state; this._state = state; if (!this.isMounted()) { return; } ContentEdit.addCSSClass(this._domElement, "ct-image-dialog--" + this._state); return ContentEdit.removeCSSClass(this._domElement, "ct-image-dialog--" + prevState); }; ImageDialog.prototype.unmount = function() { ImageDialog.__super__.unmount.call(this); this._domCancelUpload = null; this._domClear = null; this._domCrop = null; this._domInput = null; this._domInsert = null; this._domProgress = null; this._domRotateCCW = null; this._domRotateCW = null; this._domUpload = null; return this.dispatchEvent(this.createEvent('imageuploader.unmount')); }; ImageDialog.prototype._addDOMEventListeners = function() { ImageDialog.__super__._addDOMEventListeners.call(this); this._domInput.addEventListener('change', (function(_this) { return function(ev) { var file; file = ev.target.files[0]; ev.target.value = ''; if (ev.target.value) { ev.target.type = 'text'; ev.target.type = 'file'; } return _this.dispatchEvent(_this.createEvent('imageuploader.fileready', { file: file })); }; })(this)); this._domCancelUpload.addEventListener('click', (function(_this) { return function(ev) { return _this.dispatchEvent(_this.createEvent('imageuploader.cancelupload')); }; })(this)); this._domClear.addEventListener('click', (function(_this) { return function(ev) { _this.removeCropMarks(); return _this.dispatchEvent(_this.createEvent('imageuploader.clear')); }; })(this)); this._domRotateCCW.addEventListener('click', (function(_this) { return function(ev) { _this.removeCropMarks(); return _this.dispatchEvent(_this.createEvent('imageuploader.rotateccw')); }; })(this)); this._domRotateCW.addEventListener('click', (function(_this) { return function(ev) { _this.removeCropMarks(); return _this.dispatchEvent(_this.createEvent('imageuploader.rotatecw')); }; })(this)); this._domCrop.addEventListener('click', (function(_this) { return function(ev) { if (_this._cropMarks) { return _this.removeCropMarks(); } else { return _this.addCropMarks(); } }; })(this)); return this._domInsert.addEventListener('click', (function(_this) { return function(ev) { return _this.dispatchEvent(_this.createEvent('imageuploader.save')); }; })(this)); }; return ImageDialog; })(ContentTools.DialogUI); CropMarksUI = (function(_super) { __extends(CropMarksUI, _super); function CropMarksUI(imageSize) { CropMarksUI.__super__.constructor.call(this); this._bounds = null; this._dragging = null; this._draggingOrigin = null; this._imageSize = imageSize; } CropMarksUI.prototype.mount = function(domParent, before) { if (before == null) { before = null; } this._domElement = this.constructor.createDiv(['ct-crop-marks']); this._domClipper = this.constructor.createDiv(['ct-crop-marks__clipper']); this._domElement.appendChild(this._domClipper); this._domRulers = [this.constructor.createDiv(['ct-crop-marks__ruler', 'ct-crop-marks__ruler--top-left']), this.constructor.createDiv(['ct-crop-marks__ruler', 'ct-crop-marks__ruler--bottom-right'])]; this._domClipper.appendChild(this._domRulers[0]); this._domClipper.appendChild(this._domRulers[1]); this._domHandles = [this.constructor.createDiv(['ct-crop-marks__handle', 'ct-crop-marks__handle--top-left']), this.constructor.createDiv(['ct-crop-marks__handle', 'ct-crop-marks__handle--bottom-right'])]; this._domElement.appendChild(this._domHandles[0]); this._domElement.appendChild(this._domHandles[1]); CropMarksUI.__super__.mount.call(this, domParent, before); return this._fit(domParent); }; CropMarksUI.prototype.region = function() { return [parseFloat(this._domHandles[0].style.top) / this._bounds[1], parseFloat(this._domHandles[0].style.left) / this._bounds[0], parseFloat(this._domHandles[1].style.top) / this._bounds[1], parseFloat(this._domHandles[1].style.left) / this._bounds[0]]; }; CropMarksUI.prototype.unmount = function() { CropMarksUI.__super__.unmount.call(this); this._domClipper = null; this._domHandles = null; return this._domRulers = null; }; CropMarksUI.prototype._addDOMEventListeners = function() { CropMarksUI.__super__._addDOMEventListeners.call(this); this._domHandles[0].addEventListener('mousedown', (function(_this) { return function(ev) { if (ev.button === 0) { return _this._startDrag(0, ev.clientY, ev.clientX); } }; })(this)); return this._domHandles[1].addEventListener('mousedown', (function(_this) { return function(ev) { if (ev.button === 0) { return _this._startDrag(1, ev.clientY, ev.clientX); } }; })(this)); }; CropMarksUI.prototype._drag = function(top, left) { var height, minCrop, offsetLeft, offsetTop, width; if (this._dragging === null) { return; } ContentSelect.Range.unselectAll(); offsetTop = top - this._draggingOrigin[1]; offsetLeft = left - this._draggingOrigin[0]; height = this._bounds[1]; left = 0; top = 0; width = this._bounds[0]; minCrop = Math.min(Math.min(ContentTools.MIN_CROP, height), width); if (this._dragging === 0) { height = parseInt(this._domHandles[1].style.top) - minCrop; width = parseInt(this._domHandles[1].style.left) - minCrop; } else { left = parseInt(this._domHandles[0].style.left) + minCrop; top = parseInt(this._domHandles[0].style.top) + minCrop; } offsetTop = Math.min(Math.max(top, offsetTop), height); offsetLeft = Math.min(Math.max(left, offsetLeft), width); this._domHandles[this._dragging].style.top = "" + offsetTop + "px"; this._domHandles[this._dragging].style.left = "" + offsetLeft + "px"; this._domRulers[this._dragging].style.top = "" + offsetTop + "px"; return this._domRulers[this._dragging].style.left = "" + offsetLeft + "px"; }; CropMarksUI.prototype._fit = function(domParent) { var height, heightScale, left, ratio, rect, top, width, widthScale; rect = domParent.getBoundingClientRect(); widthScale = rect.width / this._imageSize[0]; heightScale = rect.height / this._imageSize[1]; ratio = Math.min(widthScale, heightScale); width = ratio * this._imageSize[0]; height = ratio * this._imageSize[1]; left = (rect.width - width) / 2; top = (rect.height - height) / 2; this._domElement.style.width = "" + width + "px"; this._domElement.style.height = "" + height + "px"; this._domElement.style.top = "" + top + "px"; this._domElement.style.left = "" + left + "px"; this._domHandles[0].style.top = '0px'; this._domHandles[0].style.left = '0px'; this._domHandles[1].style.top = "" + height + "px"; this._domHandles[1].style.left = "" + width + "px"; this._domRulers[0].style.top = '0px'; this._domRulers[0].style.left = '0px'; this._domRulers[1].style.top = "" + height + "px"; this._domRulers[1].style.left = "" + width + "px"; return this._bounds = [width, height]; }; CropMarksUI.prototype._startDrag = function(handleIndex, top, left) { var domHandle; domHandle = this._domHandles[handleIndex]; this._dragging = handleIndex; this._draggingOrigin = [left - parseInt(domHandle.style.left), top - parseInt(domHandle.style.top)]; this._onMouseMove = (function(_this) { return function(ev) { return _this._drag(ev.clientY, ev.clientX); }; })(this); document.addEventListener('mousemove', this._onMouseMove); this._onMouseUp = (function(_this) { return function(ev) { return _this._stopDrag(); }; })(this); return document.addEventListener('mouseup', this._onMouseUp); }; CropMarksUI.prototype._stopDrag = function() { document.removeEventListener('mousemove', this._onMouseMove); document.removeEventListener('mouseup', this._onMouseUp); this._dragging = null; return this._draggingOrigin = null; }; return CropMarksUI; })(ContentTools.AnchoredComponentUI); ContentTools.LinkDialog = (function(_super) { var NEW_WINDOW_TARGET; __extends(LinkDialog, _super); NEW_WINDOW_TARGET = '_blank'; function LinkDialog(href, target) { if (href == null) { href = ''; } if (target == null) { target = ''; } LinkDialog.__super__.constructor.call(this); this._href = href; this._target = target; } LinkDialog.prototype.mount = function() { LinkDialog.__super__.mount.call(this); this._domInput = document.createElement('input'); this._domInput.setAttribute('class', 'ct-anchored-dialog__input'); this._domInput.setAttribute('name', 'href'); this._domInput.setAttribute('placeholder', ContentEdit._('Enter a link') + '...'); this._domInput.setAttribute('type', 'text'); this._domInput.setAttribute('value', this._href); this._domElement.appendChild(this._domInput); this._domTargetButton = this.constructor.createDiv(['ct-anchored-dialog__target-button']); this._domElement.appendChild(this._domTargetButton); if (this._target === NEW_WINDOW_TARGET) { ContentEdit.addCSSClass(this._domTargetButton, 'ct-anchored-dialog__target-button--active'); } this._domButton = this.constructor.createDiv(['ct-anchored-dialog__button']); this._domElement.appendChild(this._domButton); return this._addDOMEventListeners(); }; LinkDialog.prototype.save = function() { var detail; if (!this.isMounted()) { this.dispatchEvent(this.createEvent('save')); return; } detail = { href: this._domInput.value.trim() }; if (this._target) { detail.target = this._target; } return this.dispatchEvent(this.createEvent('save', detail)); }; LinkDialog.prototype.show = function() { LinkDialog.__super__.show.call(this); this._domInput.focus(); if (this._href) { return this._domInput.select(); } }; LinkDialog.prototype.unmount = function() { if (this.isMounted()) { this._domInput.blur(); } LinkDialog.__super__.unmount.call(this); this._domButton = null; return this._domInput = null; }; LinkDialog.prototype._addDOMEventListeners = function() { this._domInput.addEventListener('keypress', (function(_this) { return function(ev) { if (ev.keyCode === 13) { return _this.save(); } }; })(this)); this._domTargetButton.addEventListener('click', (function(_this) { return function(ev) { ev.preventDefault(); if (_this._target === NEW_WINDOW_TARGET) { _this._target = ''; return ContentEdit.removeCSSClass(_this._domTargetButton, 'ct-anchored-dialog__target-button--active'); } else { _this._target = NEW_WINDOW_TARGET; return ContentEdit.addCSSClass(_this._domTargetButton, 'ct-anchored-dialog__target-button--active'); } }; })(this)); return this._domButton.addEventListener('click', (function(_this) { return function(ev) { ev.preventDefault(); return _this.save(); }; })(this)); }; return LinkDialog; })(ContentTools.AnchoredDialogUI); ContentTools.PropertiesDialog = (function(_super) { __extends(PropertiesDialog, _super); function PropertiesDialog(element) { var _ref; this.element = element; PropertiesDialog.__super__.constructor.call(this, 'Properties'); this._attributeUIs = []; this._focusedAttributeUI = null; this._styleUIs = []; this._supportsCoding = this.element.content; if ((_ref = this.element.type()) === 'ListItem' || _ref === 'TableCell') { this._supportsCoding = true; } } PropertiesDialog.prototype.caption = function(caption) { if (caption === void 0) { return this._caption; } this._caption = caption; return this._domCaption.textContent = ContentEdit._(caption) + (": " + (this.element.tagName())); }; PropertiesDialog.prototype.changedAttributes = function() { var attributeUI, attributes, changedAttributes, name, restricted, value, _i, _len, _ref, _ref1; attributes = {}; changedAttributes = {}; _ref = this._attributeUIs; for (_i = 0, _len = _ref.length; _i < _len; _i++) { attributeUI = _ref[_i]; name = attributeUI.name(); value = attributeUI.value(); if (name === '') { continue; } attributes[name.toLowerCase()] = true; if (this.element.attr(name) !== value) { changedAttributes[name] = value; } } restricted = ContentTools.getRestrictedAtributes(this.element.tagName()); _ref1 = this.element.attributes(); for (name in _ref1) { value = _ref1[name]; if (restricted && restricted.indexOf(name.toLowerCase()) !== -1) { continue; } if (attributes[name] === void 0) { changedAttributes[name] = null; } } return changedAttributes; }; PropertiesDialog.prototype.changedStyles = function() { var cssClass, styleUI, styles, _i, _len, _ref; styles = {}; _ref = this._styleUIs; for (_i = 0, _len = _ref.length; _i < _len; _i++) { styleUI = _ref[_i]; cssClass = styleUI.style.cssClass(); if (this.element.hasCSSClass(cssClass) !== styleUI.applied()) { styles[cssClass] = styleUI.applied(); } } return styles; }; PropertiesDialog.prototype.getElementInnerHTML = function() { if (!this._supportsCoding) { return null; } if (this.element.content) { return this.element.content.html(); } return this.element.children[0].content.html(); }; PropertiesDialog.prototype.mount = function() { var attributeNames, attributes, domActions, domTabs, lastTab, name, restricted, style, styleUI, value, _i, _j, _len, _len1, _ref; PropertiesDialog.__super__.mount.call(this); ContentEdit.addCSSClass(this._domElement, 'ct-properties-dialog'); ContentEdit.addCSSClass(this._domView, 'ct-properties-dialog__view'); this._domStyles = this.constructor.createDiv(['ct-properties-dialog__styles']); this._domStyles.setAttribute('data-ct-empty', ContentEdit._('No styles available for this tag')); this._domView.appendChild(this._domStyles); _ref = ContentTools.StylePalette.styles(this.element); for (_i = 0, _len = _ref.length; _i < _len; _i++) { style = _ref[_i]; styleUI = new StyleUI(style, this.element.hasCSSClass(style.cssClass())); this._styleUIs.push(styleUI); styleUI.mount(this._domStyles); } this._domAttributes = this.constructor.createDiv(['ct-properties-dialog__attributes']); this._domView.appendChild(this._domAttributes); restricted = ContentTools.getRestrictedAtributes(this.element.tagName()); attributes = this.element.attributes(); attributeNames = []; for (name in attributes) { value = attributes[name]; if (restricted && restricted.indexOf(name.toLowerCase()) !== -1) { continue; } attributeNames.push(name); } attributeNames.sort(); for (_j = 0, _len1 = attributeNames.length; _j < _len1; _j++) { name = attributeNames[_j]; value = attributes[name]; this._addAttributeUI(name, value); } this._addAttributeUI('', ''); this._domCode = this.constructor.createDiv(['ct-properties-dialog__code']); this._domView.appendChild(this._domCode); this._domInnerHTML = document.createElement('textarea'); this._domInnerHTML.setAttribute('class', 'ct-properties-dialog__inner-html'); this._domInnerHTML.setAttribute('name', 'code'); this._domInnerHTML.value = this.getElementInnerHTML(); this._domCode.appendChild(this._domInnerHTML); domTabs = this.constructor.createDiv(['ct-control-group', 'ct-control-group--left']); this._domControls.appendChild(domTabs); this._domStylesTab = this.constructor.createDiv(['ct-control', 'ct-control--icon', 'ct-control--styles']); this._domStylesTab.setAttribute('data-ct-tooltip', ContentEdit._('Styles')); domTabs.appendChild(this._domStylesTab); this._domAttributesTab = this.constructor.createDiv(['ct-control', 'ct-control--icon', 'ct-control--attributes']); this._domAttributesTab.setAttribute('data-ct-tooltip', ContentEdit._('Attributes')); domTabs.appendChild(this._domAttributesTab); this._domCodeTab = this.constructor.createDiv(['ct-control', 'ct-control--icon', 'ct-control--code']); this._domCodeTab.setAttribute('data-ct-tooltip', ContentEdit._('Code')); domTabs.appendChild(this._domCodeTab); if (!this._supportsCoding) { ContentEdit.addCSSClass(this._domCodeTab, 'ct-control--muted'); } this._domRemoveAttribute = this.constructor.createDiv(['ct-control', 'ct-control--icon', 'ct-control--remove', 'ct-control--muted']); this._domRemoveAttribute.setAttribute('data-ct-tooltip', ContentEdit._('Remove')); domTabs.appendChild(this._domRemoveAttribute); domActions = this.constructor.createDiv(['ct-control-group', 'ct-control-group--right']); this._domControls.appendChild(domActions); this._domApply = this.constructor.createDiv(['ct-control', 'ct-control--text', 'ct-control--apply']); this._domApply.textContent = ContentEdit._('Apply'); domActions.appendChild(this._domApply); lastTab = window.localStorage.getItem('ct-properties-dialog-tab'); if (lastTab === 'attributes') { ContentEdit.addCSSClass(this._domElement, 'ct-properties-dialog--attributes'); ContentEdit.addCSSClass(this._domAttributesTab, 'ct-control--active'); } else if (lastTab === 'code' && this._supportsCoding) { ContentEdit.addCSSClass(this._domElement, 'ct-properties-dialog--code'); ContentEdit.addCSSClass(this._domCodeTab, 'ct-control--active'); } else { ContentEdit.addCSSClass(this._domElement, 'ct-properties-dialog--styles'); ContentEdit.addCSSClass(this._domStylesTab, 'ct-control--active'); } return this._addDOMEventListeners(); }; PropertiesDialog.prototype.save = function() { var detail, innerHTML; innerHTML = null; if (this._supportsCoding) { innerHTML = this._domInnerHTML.value; } detail = { changedAttributes: this.changedAttributes(), changedStyles: this.changedStyles(), innerHTML: innerHTML }; return this.dispatchEvent(this.createEvent('save', detail)); }; PropertiesDialog.prototype._addAttributeUI = function(name, value) { var attributeUI, dialog; dialog = this; attributeUI = new AttributeUI(name, value); this._attributeUIs.push(attributeUI); attributeUI.addEventListener('blur', function(ev) { var index, lastAttributeUI, length; dialog._focusedAttributeUI = null; ContentEdit.addCSSClass(dialog._domRemoveAttribute, 'ct-control--muted'); index = dialog._attributeUIs.indexOf(this); length = dialog._attributeUIs.length; if (this.name() === '' && index < (length - 1)) { this.unmount(); dialog._attributeUIs.splice(index, 1); } lastAttributeUI = dialog._attributeUIs[length - 1]; if (lastAttributeUI) { if (lastAttributeUI.name() && lastAttributeUI.value()) { return dialog._addAttributeUI('', ''); } } }); attributeUI.addEventListener('focus', function(ev) { dialog._focusedAttributeUI = this; return ContentEdit.removeCSSClass(dialog._domRemoveAttribute, 'ct-control--muted'); }); attributeUI.addEventListener('namechange', function(ev) { var element, otherAttributeUI, restricted, valid, _i, _len, _ref; element = dialog.element; name = this.name().toLowerCase(); restricted = ContentTools.getRestrictedAtributes(element.tagName()); valid = true; if (restricted && restricted.indexOf(name) !== -1) { valid = false; } _ref = dialog._attributeUIs; for (_i = 0, _len = _ref.length; _i < _len; _i++) { otherAttributeUI = _ref[_i]; if (name === '') { continue; } if (otherAttributeUI === this) { continue; } if (otherAttributeUI.name().toLowerCase() !== name) { continue; } valid = false; } this.valid(valid); if (valid) { return ContentEdit.removeCSSClass(dialog._domApply, 'ct-control--muted'); } else { return ContentEdit.addCSSClass(dialog._domApply, 'ct-control--muted'); } }); attributeUI.mount(this._domAttributes); return attributeUI; }; PropertiesDialog.prototype._addDOMEventListeners = function() { var selectTab, validateCode; PropertiesDialog.__super__._addDOMEventListeners.call(this); selectTab = (function(_this) { return function(selected) { var selectedCap, tab, tabCap, tabs, _i, _len; tabs = ['attributes', 'code', 'styles']; for (_i = 0, _len = tabs.length; _i < _len; _i++) { tab = tabs[_i]; if (tab === selected) { continue; } tabCap = tab.charAt(0).toUpperCase() + tab.slice(1); ContentEdit.removeCSSClass(_this._domElement, "ct-properties-dialog--" + tab); ContentEdit.removeCSSClass(_this["_dom" + tabCap + "Tab"], 'ct-control--active'); } selectedCap = selected.charAt(0).toUpperCase() + selected.slice(1); ContentEdit.addCSSClass(_this._domElement, "ct-properties-dialog--" + selected); ContentEdit.addCSSClass(_this["_dom" + selectedCap + "Tab"], 'ct-control--active'); return window.localStorage.setItem('ct-properties-dialog-tab', selected); }; })(this); this._domStylesTab.addEventListener('mousedown', (function(_this) { return function() { return selectTab('styles'); }; })(this)); this._domAttributesTab.addEventListener('mousedown', (function(_this) { return function() { return selectTab('attributes'); }; })(this)); if (this._supportsCoding) { this._domCodeTab.addEventListener('mousedown', (function(_this) { return function() { return selectTab('code'); }; })(this)); } this._domRemoveAttribute.addEventListener('mousedown', (function(_this) { return function(ev) { var index, last; ev.preventDefault(); if (_this._focusedAttributeUI) { index = _this._attributeUIs.indexOf(_this._focusedAttributeUI); last = index === (_this._attributeUIs.length - 1); _this._focusedAttributeUI.unmount(); _this._attributeUIs.splice(index, 1); if (last) { return _this._addAttributeUI('', ''); } } }; })(this)); validateCode = (function(_this) { return function(ev) { var content; try { content = new HTMLString.String(_this._domInnerHTML.value); ContentEdit.removeCSSClass(_this._domInnerHTML, 'ct-properties-dialog__inner-html--invalid'); return ContentEdit.removeCSSClass(_this._domApply, 'ct-control--muted'); } catch (_error) { ContentEdit.addCSSClass(_this._domInnerHTML, 'ct-properties-dialog__inner-html--invalid'); return ContentEdit.addCSSClass(_this._domApply, 'ct-control--muted'); } }; })(this); this._domInnerHTML.addEventListener('input', validateCode); this._domInnerHTML.addEventListener('propertychange', validateCode); return this._domApply.addEventListener('click', (function(_this) { return function(ev) { var cssClass; ev.preventDefault(); cssClass = _this._domApply.getAttribute('class'); if (cssClass.indexOf('ct-control--muted') === -1) { return _this.save(); } }; })(this)); }; return PropertiesDialog; })(ContentTools.DialogUI); StyleUI = (function(_super) { __extends(StyleUI, _super); function StyleUI(style, applied) { this.style = style; StyleUI.__super__.constructor.call(this); this._applied = applied; } StyleUI.prototype.applied = function(applied) { if (applied === void 0) { return this._applied; } if (this._applied === applied) { return; } this._applied = applied; if (this._applied) { return ContentEdit.addCSSClass(this._domElement, 'ct-section--applied'); } else { return ContentEdit.removeCSSClass(this._domElement, 'ct-section--applied'); } }; StyleUI.prototype.mount = function(domParent, before) { var label; if (before == null) { before = null; } this._domElement = this.constructor.createDiv(['ct-section']); if (this._applied) { ContentEdit.addCSSClass(this._domElement, 'ct-section--applied'); } label = this.constructor.createDiv(['ct-section__label']); label.textContent = this.style.name(); this._domElement.appendChild(label); this._domElement.appendChild(this.constructor.createDiv(['ct-section__switch'])); return StyleUI.__super__.mount.call(this, domParent, before); }; StyleUI.prototype._addDOMEventListeners = function() { var toggleSection; toggleSection = (function(_this) { return function(ev) { ev.preventDefault(); if (_this.applied()) { return _this.applied(false); } else { return _this.applied(true); } }; })(this); return this._domElement.addEventListener('click', toggleSection); }; return StyleUI; })(ContentTools.AnchoredComponentUI); AttributeUI = (function(_super) { __extends(AttributeUI, _super); function AttributeUI(name, value) { AttributeUI.__super__.constructor.call(this); this._initialName = name; this._initialValue = value; } AttributeUI.prototype.name = function() { return this._domName.value.trim(); }; AttributeUI.prototype.value = function() { return this._domValue.value.trim(); }; AttributeUI.prototype.mount = function(domParent, before) { if (before == null) { before = null; } this._domElement = this.constructor.createDiv(['ct-attribute']); this._domName = document.createElement('input'); this._domName.setAttribute('class', 'ct-attribute__name'); this._domName.setAttribute('name', 'name'); this._domName.setAttribute('placeholder', ContentEdit._('Name')); this._domName.setAttribute('type', 'text'); this._domName.setAttribute('value', this._initialName); this._domElement.appendChild(this._domName); this._domValue = document.createElement('input'); this._domValue.setAttribute('class', 'ct-attribute__value'); this._domValue.setAttribute('name', 'value'); this._domValue.setAttribute('placeholder', ContentEdit._('Value')); this._domValue.setAttribute('type', 'text'); this._domValue.setAttribute('value', this._initialValue); this._domElement.appendChild(this._domValue); return AttributeUI.__super__.mount.call(this, domParent, before); }; AttributeUI.prototype.valid = function(valid) { if (valid) { return ContentEdit.removeCSSClass(this._domName, 'ct-attribute__name--invalid'); } else { return ContentEdit.addCSSClass(this._domName, 'ct-attribute__name--invalid'); } }; AttributeUI.prototype._addDOMEventListeners = function() { this._domName.addEventListener('blur', (function(_this) { return function() { var name, nextDomAttribute, nextNameDom; name = _this.name(); nextDomAttribute = _this._domElement.nextSibling; _this.dispatchEvent(_this.createEvent('blur')); if (name === '' && nextDomAttribute) { nextNameDom = nextDomAttribute.querySelector('.ct-attribute__name'); return nextNameDom.focus(); } }; })(this)); this._domName.addEventListener('focus', (function(_this) { return function() { return _this.dispatchEvent(_this.createEvent('focus')); }; })(this)); this._domName.addEventListener('input', (function(_this) { return function() { return _this.dispatchEvent(_this.createEvent('namechange')); }; })(this)); this._domName.addEventListener('keydown', (function(_this) { return function(ev) { if (ev.keyCode === 13) { return _this._domValue.focus(); } }; })(this)); this._domValue.addEventListener('blur', (function(_this) { return function() { return _this.dispatchEvent(_this.createEvent('blur')); }; })(this)); this._domValue.addEventListener('focus', (function(_this) { return function() { return _this.dispatchEvent(_this.createEvent('focus')); }; })(this)); return this._domValue.addEventListener('keydown', (function(_this) { return function(ev) { var nextDomAttribute, nextNameDom; if (ev.keyCode !== 13 && (ev.keyCode !== 9 || ev.shiftKey)) { return; } ev.preventDefault(); nextDomAttribute = _this._domElement.nextSibling; if (!nextDomAttribute) { _this._domValue.blur(); nextDomAttribute = _this._domElement.nextSibling; } if (nextDomAttribute) { nextNameDom = nextDomAttribute.querySelector('.ct-attribute__name'); return nextNameDom.focus(); } }; })(this)); }; return AttributeUI; })(ContentTools.AnchoredComponentUI); ContentTools.TableDialog = (function(_super) { __extends(TableDialog, _super); function TableDialog(table) { this.table = table; if (this.table) { TableDialog.__super__.constructor.call(this, 'Update table'); } else { TableDialog.__super__.constructor.call(this, 'Insert table'); } } TableDialog.prototype.mount = function() { var cfg, domBodyLabel, domControlGroup, domFootLabel, domHeadLabel, footCSSClasses, headCSSClasses; TableDialog.__super__.mount.call(this); cfg = { columns: 3, foot: false, head: true }; if (this.table) { cfg = { columns: this.table.firstSection().children[0].children.length, foot: this.table.tfoot(), head: this.table.thead() }; } ContentEdit.addCSSClass(this._domElement, 'ct-table-dialog'); ContentEdit.addCSSClass(this._domView, 'ct-table-dialog__view'); headCSSClasses = ['ct-section']; if (cfg.head) { headCSSClasses.push('ct-section--applied'); } this._domHeadSection = this.constructor.createDiv(headCSSClasses); this._domView.appendChild(this._domHeadSection); domHeadLabel = this.constructor.createDiv(['ct-section__label']); domHeadLabel.textContent = ContentEdit._('Table head'); this._domHeadSection.appendChild(domHeadLabel); this._domHeadSwitch = this.constructor.createDiv(['ct-section__switch']); this._domHeadSection.appendChild(this._domHeadSwitch); this._domBodySection = this.constructor.createDiv(['ct-section', 'ct-section--applied', 'ct-section--contains-input']); this._domView.appendChild(this._domBodySection); domBodyLabel = this.constructor.createDiv(['ct-section__label']); domBodyLabel.textContent = ContentEdit._('Table body (columns)'); this._domBodySection.appendChild(domBodyLabel); this._domBodyInput = document.createElement('input'); this._domBodyInput.setAttribute('class', 'ct-section__input'); this._domBodyInput.setAttribute('maxlength', '2'); this._domBodyInput.setAttribute('name', 'columns'); this._domBodyInput.setAttribute('type', 'text'); this._domBodyInput.setAttribute('value', cfg.columns); this._domBodySection.appendChild(this._domBodyInput); footCSSClasses = ['ct-section']; if (cfg.foot) { footCSSClasses.push('ct-section--applied'); } this._domFootSection = this.constructor.createDiv(footCSSClasses); this._domView.appendChild(this._domFootSection); domFootLabel = this.constructor.createDiv(['ct-section__label']); domFootLabel.textContent = ContentEdit._('Table foot'); this._domFootSection.appendChild(domFootLabel); this._domFootSwitch = this.constructor.createDiv(['ct-section__switch']); this._domFootSection.appendChild(this._domFootSwitch); domControlGroup = this.constructor.createDiv(['ct-control-group', 'ct-control-group--right']); this._domControls.appendChild(domControlGroup); this._domApply = this.constructor.createDiv(['ct-control', 'ct-control--text', 'ct-control--apply']); this._domApply.textContent = 'Apply'; domControlGroup.appendChild(this._domApply); return this._addDOMEventListeners(); }; TableDialog.prototype.save = function() { var detail, footCSSClass, headCSSClass; footCSSClass = this._domFootSection.getAttribute('class'); headCSSClass = this._domHeadSection.getAttribute('class'); detail = { columns: parseInt(this._domBodyInput.value), foot: footCSSClass.indexOf('ct-section--applied') > -1, head: headCSSClass.indexOf('ct-section--applied') > -1 }; return this.dispatchEvent(this.createEvent('save', detail)); }; TableDialog.prototype.unmount = function() { TableDialog.__super__.unmount.call(this); this._domBodyInput = null; this._domBodySection = null; this._domApply = null; this._domHeadSection = null; this._domHeadSwitch = null; this._domFootSection = null; return this._domFootSwitch = null; }; TableDialog.prototype._addDOMEventListeners = function() { var toggleSection; TableDialog.__super__._addDOMEventListeners.call(this); toggleSection = function(ev) { ev.preventDefault(); if (this.getAttribute('class').indexOf('ct-section--applied') > -1) { return ContentEdit.removeCSSClass(this, 'ct-section--applied'); } else { return ContentEdit.addCSSClass(this, 'ct-section--applied'); } }; this._domHeadSection.addEventListener('click', toggleSection); this._domFootSection.addEventListener('click', toggleSection); this._domBodySection.addEventListener('click', (function(_this) { return function(ev) { return _this._domBodyInput.focus(); }; })(this)); this._domBodyInput.addEventListener('input', (function(_this) { return function(ev) { var valid; valid = /^[1-9]\d{0,1}$/.test(ev.target.value); if (valid) { ContentEdit.removeCSSClass(_this._domBodyInput, 'ct-section__input--invalid'); return ContentEdit.removeCSSClass(_this._domApply, 'ct-control--muted'); } else { ContentEdit.addCSSClass(_this._domBodyInput, 'ct-section__input--invalid'); return ContentEdit.addCSSClass(_this._domApply, 'ct-control--muted'); } }; })(this)); return this._domApply.addEventListener('click', (function(_this) { return function(ev) { var cssClass; ev.preventDefault(); cssClass = _this._domApply.getAttribute('class'); if (cssClass.indexOf('ct-control--muted') === -1) { return _this.save(); } }; })(this)); }; return TableDialog; })(ContentTools.DialogUI); ContentTools.VideoDialog = (function(_super) { __extends(VideoDialog, _super); function VideoDialog() { VideoDialog.__super__.constructor.call(this, 'Insert video'); } VideoDialog.prototype.clearPreview = function() { if (this._domPreview) { this._domPreview.parentNode.removeChild(this._domPreview); return this._domPreview = void 0; } }; VideoDialog.prototype.mount = function() { var domControlGroup; VideoDialog.__super__.mount.call(this); ContentEdit.addCSSClass(this._domElement, 'ct-video-dialog'); ContentEdit.addCSSClass(this._domView, 'ct-video-dialog__preview'); domControlGroup = this.constructor.createDiv(['ct-control-group']); this._domControls.appendChild(domControlGroup); this._domInput = document.createElement('input'); this._domInput.setAttribute('class', 'ct-video-dialog__input'); this._domInput.setAttribute('name', 'url'); this._domInput.setAttribute('placeholder', ContentEdit._('Paste YouTube or Vimeo URL') + '...'); this._domInput.setAttribute('type', 'text'); domControlGroup.appendChild(this._domInput); this._domButton = this.constructor.createDiv(['ct-control', 'ct-control--text', 'ct-control--insert', 'ct-control--muted']); this._domButton.textContent = ContentEdit._('Insert'); domControlGroup.appendChild(this._domButton); return this._addDOMEventListeners(); }; VideoDialog.prototype.preview = function(url) { this.clearPreview(); this._domPreview = document.createElement('iframe'); this._domPreview.setAttribute('frameborder', '0'); this._domPreview.setAttribute('height', '100%'); this._domPreview.setAttribute('src', url); this._domPreview.setAttribute('width', '100%'); return this._domView.appendChild(this._domPreview); }; VideoDialog.prototype.save = function() { var embedURL, videoURL; videoURL = this._domInput.value.trim(); embedURL = ContentTools.getEmbedVideoURL(videoURL); if (embedURL) { return this.dispatchEvent(this.createEvent('save', { 'url': embedURL })); } else { return this.dispatchEvent(this.createEvent('save', { 'url': videoURL })); } }; VideoDialog.prototype.show = function() { VideoDialog.__super__.show.call(this); return this._domInput.focus(); }; VideoDialog.prototype.unmount = function() { if (this.isMounted()) { this._domInput.blur(); } VideoDialog.__super__.unmount.call(this); this._domButton = null; this._domInput = null; return this._domPreview = null; }; VideoDialog.prototype._addDOMEventListeners = function() { VideoDialog.__super__._addDOMEventListeners.call(this); this._domInput.addEventListener('input', (function(_this) { return function(ev) { var updatePreview; if (ev.target.value) { ContentEdit.removeCSSClass(_this._domButton, 'ct-control--muted'); } else { ContentEdit.addCSSClass(_this._domButton, 'ct-control--muted'); } if (_this._updatePreviewTimeout) { clearTimeout(_this._updatePreviewTimeout); } updatePreview = function() { var embedURL, videoURL; videoURL = _this._domInput.value.trim(); embedURL = ContentTools.getEmbedVideoURL(videoURL); if (embedURL) { return _this.preview(embedURL); } else { return _this.clearPreview(); } }; return _this._updatePreviewTimeout = setTimeout(updatePreview, 500); }; })(this)); this._domInput.addEventListener('keypress', (function(_this) { return function(ev) { if (ev.keyCode === 13) { return _this.save(); } }; })(this)); return this._domButton.addEventListener('click', (function(_this) { return function(ev) { var cssClass; ev.preventDefault(); cssClass = _this._domButton.getAttribute('class'); if (cssClass.indexOf('ct-control--muted') === -1) { return _this.save(); } }; })(this)); }; return VideoDialog; })(ContentTools.DialogUI); _EditorApp = (function(_super) { __extends(_EditorApp, _super); function _EditorApp() { } _EditorApp.prototype.init = function(queryOrDOMElements) { var allDataName = document.querySelectorAll(queryOrDOMElements);//根据参数检索全文中带有参数的属性的元素 for (var i = 0; i < allDataName.length; i++) {//遍历所有元素,监听每个元素的click事件 allDataName[i].addEventListener('click', (function (i) { return function () { var dataName=allDataName[i].getAttribute('data-name');//获取点击元素的data-name值 } })(i)); } }; return _EditorApp; })(ContentTools.ComponentUI); ContentTools.EditorApp = (function() { var instance; function EditorApp() {} instance = null; EditorApp.get = function() { var cls; cls = ContentTools.EditorApp.getCls(); return instance != null ? instance : instance = new cls(); }; EditorApp.getCls = function() { return _EditorApp; }; return EditorApp; })(); ContentTools.History = (function() { function History(regions) { this._lastSnapshotTaken = null; this._regions = {}; this.replaceRegions(regions); this._snapshotIndex = -1; this._snapshots = []; this._store(); } History.prototype.canRedo = function() { return this._snapshotIndex < this._snapshots.length - 1; }; History.prototype.canUndo = function() { return this._snapshotIndex > 0; }; History.prototype.index = function() { return this._snapshotIndex; }; History.prototype.length = function() { return this._snapshots.length; }; History.prototype.snapshot = function() { return this._snapshots[this._snapshotIndex]; }; History.prototype.goTo = function(index) { this._snapshotIndex = Math.min(this._snapshots.length - 1, Math.max(0, index)); return this.snapshot(); }; History.prototype.redo = function() { return this.goTo(this._snapshotIndex + 1); }; History.prototype.replaceRegions = function(regions) { var k, v, _results; this._regions = {}; _results = []; for (k in regions) { v = regions[k]; _results.push(this._regions[k] = v); } return _results; }; History.prototype.restoreSelection = function(snapshot) { var element, region; if (!snapshot.selected) { return; } region = this._regions[snapshot.selected.region]; element = region.descendants()[snapshot.selected.element]; element.focus(); if (element.selection && snapshot.selected.selection) { return element.selection(snapshot.selected.selection); } }; History.prototype.stopWatching = function() { if (this._watchInterval) { clearInterval(this._watchInterval); } if (this._delayedStoreTimeout) { return clearTimeout(this._delayedStoreTimeout); } }; History.prototype.undo = function() { return this.goTo(this._snapshotIndex - 1); }; History.prototype.watch = function() { var watch; this._lastSnapshotTaken = Date.now(); watch = (function(_this) { return function() { var delayedStore, lastModified; lastModified = ContentEdit.Root.get().lastModified(); if (lastModified === null) { return; } if (lastModified > _this._lastSnapshotTaken) { if (_this._delayedStoreRequested === lastModified) { return; } if (_this._delayedStoreTimeout) { clearTimeout(_this._delayedStoreTimeout); } delayedStore = function() { _this._lastSnapshotTaken = lastModified; return _this._store(); }; _this._delayedStoreRequested = lastModified; return _this._delayedStoreTimeout = setTimeout(delayedStore, 500); } }; })(this); return this._watchInterval = setInterval(watch, 50); }; History.prototype._store = function() { var element, name, other_region, region, snapshot, _ref, _ref1; snapshot = { regions: {}, selected: null }; _ref = this._regions; for (name in _ref) { region = _ref[name]; snapshot.regions[name] = region.html(); } element = ContentEdit.Root.get().focused(); if (element) { snapshot.selected = {}; region = element.closest(function(node) { return node.type() === 'Region' || node.type() === 'Fixture'; }); if (!region) { return; } _ref1 = this._regions; for (name in _ref1) { other_region = _ref1[name]; if (region === other_region) { snapshot.selected.region = name; break; } } snapshot.selected.element = region.descendants().indexOf(element); if (element.selection) { snapshot.selected.selection = element.selection(); } } if (this._snapshotIndex < (this._snapshots.length - 1)) { this._snapshots = this._snapshots.slice(0, this._snapshotIndex + 1); } this._snapshotIndex++; return this._snapshots.splice(this._snapshotIndex, 0, snapshot); }; return History; })(); ContentTools.StylePalette = (function() { function StylePalette() {} StylePalette._styles = []; StylePalette.add = function(styles) { return this._styles = this._styles.concat(styles); }; StylePalette.styles = function(element) { var tagName; tagName = element.tagName(); if (element === void 0) { return this._styles.slice(); } return this._styles.filter(function(style) { if (!style._applicableTo) { return true; } return style._applicableTo.indexOf(tagName) !== -1; }); }; return StylePalette; })(); ContentTools.Style = (function() { function Style(name, cssClass, applicableTo) { this._name = name; this._cssClass = cssClass; if (applicableTo) { this._applicableTo = applicableTo; } else { this._applicableTo = null; } } Style.prototype.applicableTo = function() { return this._applicableTo; }; Style.prototype.cssClass = function() { return this._cssClass; }; Style.prototype.name = function() { return this._name; }; return Style; })(); ContentTools.ToolShelf = (function() { function ToolShelf() {} ToolShelf._tools = {}; ToolShelf.stow = function(cls, name) { return this._tools[name] = cls; }; ToolShelf.fetch = function(name) { if (!this._tools[name]) { throw new Error("`" + name + "` has not been stowed on the tool shelf"); } return this._tools[name]; }; return ToolShelf; })(); ContentTools.Tool = (function() { function Tool() {} Tool.label = 'Tool'; Tool.icon = 'tool'; Tool.requiresElement = true; Tool.canApply = function(element, selection) { return false; }; Tool.isApplied = function(element, selection) { return false; }; Tool.apply = function(element, selection, callback) { throw new Error('Not implemented'); }; Tool._insertAt = function(element) { var insertIndex, insertNode; insertNode = element; if (insertNode.parent().type() !== 'Region') { insertNode = element.closest(function(node) { return node.parent().type() === 'Region'; }); } insertIndex = insertNode.parent().children.indexOf(insertNode) + 1; return [insertNode, insertIndex]; }; return Tool; })(); ContentTools.Tools.Bold = (function(_super) { __extends(Bold, _super); function Bold() { return Bold.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Bold, 'bold'); Bold.label = 'Bold'; Bold.icon = 'bold'; Bold.tagName = 'b'; Bold.canApply = function(element, selection) { if (!element.content) { return false; } return selection && !selection.isCollapsed(); }; Bold.isApplied = function(element, selection) { var from, to, _ref; if (element.content === void 0 || !element.content.length()) { return false; } _ref = selection.get(), from = _ref[0], to = _ref[1]; if (from === to) { to += 1; } return element.content.slice(from, to).hasTags(this.tagName, true); }; Bold.apply = function(element, selection, callback) { var from, to, _ref; element.storeState(); _ref = selection.get(), from = _ref[0], to = _ref[1]; if (this.isApplied(element, selection)) { element.content = element.content.unformat(from, to, new HTMLString.Tag(this.tagName)); } else { element.content = element.content.format(from, to, new HTMLString.Tag(this.tagName)); } element.content.optimize(); element.updateInnerHTML(); element.taint(); element.restoreState(); return callback(true); }; return Bold; })(ContentTools.Tool); ContentTools.Tools.Italic = (function(_super) { __extends(Italic, _super); function Italic() { return Italic.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Italic, 'italic'); Italic.label = 'Italic'; Italic.icon = 'italic'; Italic.tagName = 'i'; return Italic; })(ContentTools.Tools.Bold); ContentTools.Tools.Link = (function(_super) { __extends(Link, _super); function Link() { return Link.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Link, 'link'); Link.label = 'Link'; Link.icon = 'link'; Link.tagName = 'a'; Link.getAttr = function(attrName, element, selection) { var c, from, selectedContent, tag, to, _i, _j, _len, _len1, _ref, _ref1, _ref2; if (element.type() === 'Image') { if (element.a) { return element.a[attrName]; } } else { _ref = selection.get(), from = _ref[0], to = _ref[1]; selectedContent = element.content.slice(from, to); _ref1 = selectedContent.characters; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { c = _ref1[_i]; if (!c.hasTags('a')) { continue; } _ref2 = c.tags(); for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { tag = _ref2[_j]; if (tag.name() === 'a') { return tag.attr(attrName); } } } } return ''; }; Link.canApply = function(element, selection) { var character; if (element.type() === 'Image') { return true; } else { if (!element.content) { return false; } if (!selection) { return false; } if (selection.isCollapsed()) { character = element.content.characters[selection.get()[0]]; if (!character || !character.hasTags('a')) { return false; } } return true; } }; Link.isApplied = function(element, selection) { if (element.type() === 'Image') { return element.a; } else { return Link.__super__.constructor.isApplied.call(this, element, selection); } }; Link.apply = function(element, selection, callback) { var allowScrolling, app, applied, characters, dialog, domElement, ends, from, measureSpan, modal, rect, scrollX, scrollY, selectTag, starts, to, transparent, _ref, _ref1; applied = false; if (element.type() === 'Image') { rect = element.domElement().getBoundingClientRect(); } else { if (selection.isCollapsed()) { characters = element.content.characters; starts = selection.get(0)[0]; ends = starts; while (starts > 0 && characters[starts - 1].hasTags('a')) { starts -= 1; } while (ends < characters.length && characters[ends].hasTags('a')) { ends += 1; } selection = new ContentSelect.Range(starts, ends); selection.select(element.domElement()); } element.storeState(); selectTag = new HTMLString.Tag('span', { 'class': 'ct--puesdo-select' }); _ref = selection.get(), from = _ref[0], to = _ref[1]; element.content = element.content.format(from, to, selectTag); element.updateInnerHTML(); domElement = element.domElement(); measureSpan = domElement.getElementsByClassName('ct--puesdo-select'); rect = measureSpan[0].getBoundingClientRect(); } app = ContentTools.EditorApp.get(); modal = new ContentTools.ModalUI(transparent = true, allowScrolling = true); modal.addEventListener('click', function() { this.unmount(); dialog.hide(); if (element.content) { element.content = element.content.unformat(from, to, selectTag); element.updateInnerHTML(); element.restoreState(); } return callback(applied); }); dialog = new ContentTools.LinkDialog(this.getAttr('href', element, selection), this.getAttr('target', element, selection)); _ref1 = ContentTools.getScrollPosition(), scrollX = _ref1[0], scrollY = _ref1[1]; dialog.position([rect.left + (rect.width / 2) + scrollX, rect.top + (rect.height / 2) + scrollY]); dialog.addEventListener('save', function(ev) { var a, alignmentClassNames, className, detail, linkClasses, _i, _j, _len, _len1; detail = ev.detail(); applied = true; if (element.type() === 'Image') { alignmentClassNames = ['align-center', 'align-left', 'align-right']; if (detail.href) { element.a = { href: detail.href }; if (element.a) { element.a["class"] = element.a['class']; } if (detail.target) { element.a.target = detail.target; } for (_i = 0, _len = alignmentClassNames.length; _i < _len; _i++) { className = alignmentClassNames[_i]; if (element.hasCSSClass(className)) { element.removeCSSClass(className); element.a['class'] = className; break; } } } else { linkClasses = []; if (element.a['class']) { linkClasses = element.a['class'].split(' '); } for (_j = 0, _len1 = alignmentClassNames.length; _j < _len1; _j++) { className = alignmentClassNames[_j]; if (linkClasses.indexOf(className) > -1) { element.addCSSClass(className); break; } } element.a = null; } element.unmount(); element.mount(); } else { element.content = element.content.unformat(from, to, 'a'); if (detail.href) { a = new HTMLString.Tag('a', detail); element.content = element.content.format(from, to, a); element.content.optimize(); } element.updateInnerHTML(); } element.taint(); return modal.dispatchEvent(modal.createEvent('click')); }); app.attach(modal); app.attach(dialog); modal.show(); return dialog.show(); }; return Link; })(ContentTools.Tools.Bold); ContentTools.Tools.Heading = (function(_super) { __extends(Heading, _super); function Heading() { return Heading.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Heading, 'heading'); Heading.label = 'Heading'; Heading.icon = 'heading'; Heading.tagName = 'h1'; Heading.canApply = function(element, selection) { if (element.isFixed()) { return false; } return element.content !== void 0 && ['Text', 'PreText'].indexOf(element.type()) !== -1; }; Heading.isApplied = function(element, selection) { if (!element.content) { return false; } if (['Text', 'PreText'].indexOf(element.type()) === -1) { return false; } return element.tagName() === this.tagName; }; Heading.apply = function(element, selection, callback) { var content, insertAt, parent, textElement; element.storeState(); if (element.type() === 'PreText') { content = element.content.html().replace(/&nbsp;/g, ' '); textElement = new ContentEdit.Text(this.tagName, {}, content); parent = element.parent(); insertAt = parent.children.indexOf(element); parent.detach(element); parent.attach(textElement, insertAt); element.blur(); textElement.focus(); textElement.selection(selection); } else { element.removeAttr('class'); if (element.tagName() === this.tagName) { element.tagName('p'); } else { element.tagName(this.tagName); } element.restoreState(); } return callback(true); }; return Heading; })(ContentTools.Tool); ContentTools.Tools.Subheading = (function(_super) { __extends(Subheading, _super); function Subheading() { return Subheading.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Subheading, 'subheading'); Subheading.label = 'Subheading'; Subheading.icon = 'subheading'; Subheading.tagName = 'h2'; return Subheading; })(ContentTools.Tools.Heading); ContentTools.Tools.Paragraph = (function(_super) { __extends(Paragraph, _super); function Paragraph() { return Paragraph.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Paragraph, 'paragraph'); Paragraph.label = 'Paragraph'; Paragraph.icon = 'paragraph'; Paragraph.tagName = 'p'; Paragraph.canApply = function(element, selection) { if (element.isFixed()) { return false; } return element !== void 0; }; Paragraph.apply = function(element, selection, callback) { var app, forceAdd, paragraph, region; app = ContentTools.EditorApp.get(); forceAdd = app.ctrlDown(); if (ContentTools.Tools.Heading.canApply(element) && !forceAdd) { return Paragraph.__super__.constructor.apply.call(this, element, selection, callback); } else { if (element.parent().type() !== 'Region') { element = element.closest(function(node) { return node.parent().type() === 'Region'; }); } region = element.parent(); paragraph = new ContentEdit.Text('p'); region.attach(paragraph, region.children.indexOf(element) + 1); paragraph.focus(); return callback(true); } }; return Paragraph; })(ContentTools.Tools.Heading); ContentTools.Tools.Preformatted = (function(_super) { __extends(Preformatted, _super); function Preformatted() { return Preformatted.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Preformatted, 'preformatted'); Preformatted.label = 'Preformatted'; Preformatted.icon = 'preformatted'; Preformatted.tagName = 'pre'; Preformatted.apply = function(element, selection, callback) { var insertAt, parent, preText, text; if (element.type() === 'PreText') { ContentTools.Tools.Paragraph.apply(element, selection, callback); return; } text = element.content.text(); preText = new ContentEdit.PreText('pre', {}, HTMLString.String.encode(text)); parent = element.parent(); insertAt = parent.children.indexOf(element); parent.detach(element); parent.attach(preText, insertAt); element.blur(); preText.focus(); preText.selection(selection); return callback(true); }; return Preformatted; })(ContentTools.Tools.Heading); ContentTools.Tools.AlignLeft = (function(_super) { __extends(AlignLeft, _super); function AlignLeft() { return AlignLeft.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(AlignLeft, 'align-left'); AlignLeft.label = 'Align left'; AlignLeft.icon = 'align-left'; AlignLeft.className = 'text-left'; AlignLeft.canApply = function(element, selection) { return element.content !== void 0; }; AlignLeft.isApplied = function(element, selection) { var _ref; if (!this.canApply(element)) { return false; } if ((_ref = element.type()) === 'ListItemText' || _ref === 'TableCellText') { element = element.parent(); } return element.hasCSSClass(this.className); }; AlignLeft.apply = function(element, selection, callback) { var alignmentClassNames, className, _i, _len, _ref; if ((_ref = element.type()) === 'ListItemText' || _ref === 'TableCellText') { element = element.parent(); } alignmentClassNames = [ContentTools.Tools.AlignLeft.className, ContentTools.Tools.AlignCenter.className, ContentTools.Tools.AlignRight.className]; for (_i = 0, _len = alignmentClassNames.length; _i < _len; _i++) { className = alignmentClassNames[_i]; if (element.hasCSSClass(className)) { element.removeCSSClass(className); if (className === this.className) { return callback(true); } } } element.addCSSClass(this.className); return callback(true); }; return AlignLeft; })(ContentTools.Tool); ContentTools.Tools.AlignCenter = (function(_super) { __extends(AlignCenter, _super); function AlignCenter() { return AlignCenter.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(AlignCenter, 'align-center'); AlignCenter.label = 'Align center'; AlignCenter.icon = 'align-center'; AlignCenter.className = 'text-center'; return AlignCenter; })(ContentTools.Tools.AlignLeft); ContentTools.Tools.AlignRight = (function(_super) { __extends(AlignRight, _super); function AlignRight() { return AlignRight.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(AlignRight, 'align-right'); AlignRight.label = 'Align right'; AlignRight.icon = 'align-right'; AlignRight.className = 'text-right'; return AlignRight; })(ContentTools.Tools.AlignLeft); //hodo ContentTools.Tools.Color=(function (_super) { __extends(Color, _super); function Color() { return Color.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Color, 'color'); Color.label='color'; Color.icon='color'; Color.className='color'; Color.canApply = function(element, selection) { return element.content !== void 0; }; Color.apply = function(element, selection, callback) { var alignmentClassNames, className, _i, _len, _ref,elements; if ((_ref = element.type()) === 'ListItemText' || _ref === 'TableCellText') { element = element.parent(); } alignmentClassNames = [ContentTools.Tools.AlignLeft.className, ContentTools.Tools.AlignCenter.className, ContentTools.Tools.AlignRight.className]; for (_i = 0, _len = alignmentClassNames.length; _i < _len; _i++) { className = alignmentClassNames[_i]; if (element.hasCSSClass(className)) { element.removeCSSClass(className); if (className === this.className) { return callback(true); } } } ContentTools.hex.show(); ColorPicker( document.getElementsByClassName('cp-default')[0], function(hex, hsv, rgb) { element.attr('style',"background-color:"+ContentTools.bgcolor+';'+"color:"+hex); ContentTools.color=hex; } ); return callback(true); }; return Color; })(ContentTools.Tool); //背景颜色 ContentTools.Tools.BackgroundColor=(function (_super) { __extends(BackgroundColor, _super); function BackgroundColor() { return BackgroundColor.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(BackgroundColor, 'bgcolor'); BackgroundColor.label='bgcolor'; BackgroundColor.icon='bgcolor'; BackgroundColor.className='bgcolor'; BackgroundColor.canApply = function(element, selection) { return element.content !== void 0; }; BackgroundColor.apply = function(element, selection, callback) { var alignmentClassNames, className, _i, _len, _ref,elements; if ((_ref = element.type()) === 'ListItemText' || _ref === 'TableCellText') { element = element.parent(); } alignmentClassNames = [ContentTools.Tools.AlignLeft.className, ContentTools.Tools.AlignCenter.className, ContentTools.Tools.AlignRight.className]; for (_i = 0, _len = alignmentClassNames.length; _i < _len; _i++) { className = alignmentClassNames[_i]; if (element.hasCSSClass(className)) { element.removeCSSClass(className); if (className === this.className) { return callback(true); } } } ContentTools.hex.show(); ColorPicker( document.getElementsByClassName('cp-default')[0], function(hex, hsv, rgb) { element.attr('style',"background-color:"+hex+';'+"color:"+ContentTools.color); ContentTools.bgcolor=hex; } ); return callback(true); }; return BackgroundColor; })(ContentTools.Tools.Color); /* ContentTools.Tools.Red=(function (_super) { __extends(Red, _super); function Red() { return Red.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Red, 'red'); Red.label='red'; Red.icon='red'; Red.className='red'; return Red; })(ContentTools.Tools.Green); ContentTools.Tools.Yellow=(function (_super) { __extends(Yellow, _super); function Yellow() { return Yellow.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Yellow, 'yellow'); Yellow.label='yellow'; Yellow.icon='yellow'; Yellow.className='yellow'; return Yellow; })(ContentTools.Tools.Green); ContentTools.Tools.Pink=(function (_super) { __extends(Pink, _super); function Pink() { return Pink.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Pink, 'pink'); Pink.label='pink'; Pink.icon='pink'; Pink.className='pink'; return Pink; })(ContentTools.Tools.Green); ContentTools.Tools.Gray=(function (_super) { __extends(Gray, _super); function Gray() { return Gray.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Gray, 'gray'); Gray.label='gray'; Gray.icon='gray'; Gray.className='gray'; return Gray; })(ContentTools.Tools.Green);*/ ContentTools.Tools.UnorderedList = (function(_super) { __extends(UnorderedList, _super); function UnorderedList() { return UnorderedList.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(UnorderedList, 'unordered-list'); UnorderedList.label = 'Bullet list'; UnorderedList.icon = 'unordered-list'; UnorderedList.listTag = 'ul'; UnorderedList.canApply = function(element, selection) { var _ref; if (element.isFixed()) { return false; } return element.content !== void 0 && ((_ref = element.parent().type()) === 'Region' || _ref === 'ListItem'); }; UnorderedList.apply = function(element, selection, callback) { var insertAt, list, listItem, listItemText, parent; if (element.parent().type() === 'ListItem') { element.storeState(); list = element.closest(function(node) { return node.type() === 'List'; }); list.tagName(this.listTag); element.restoreState(); } else { listItemText = new ContentEdit.ListItemText(element.content.copy()); listItem = new ContentEdit.ListItem(); listItem.attach(listItemText); list = new ContentEdit.List(this.listTag, {}); list.attach(listItem); parent = element.parent(); insertAt = parent.children.indexOf(element); parent.detach(element); parent.attach(list, insertAt); listItemText.focus(); listItemText.selection(selection); } return callback(true); }; return UnorderedList; })(ContentTools.Tool); ContentTools.Tools.OrderedList = (function(_super) { __extends(OrderedList, _super); function OrderedList() { return OrderedList.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(OrderedList, 'ordered-list'); OrderedList.label = 'Numbers list'; OrderedList.icon = 'ordered-list'; OrderedList.listTag = 'ol'; return OrderedList; })(ContentTools.Tools.UnorderedList); ContentTools.Tools.Table = (function(_super) { __extends(Table, _super); function Table() { return Table.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Table, 'table'); Table.label = 'Table'; Table.icon = 'table'; Table.canApply = function(element, selection) { if (element.isFixed()) { return false; } return element !== void 0; }; Table.apply = function(element, selection, callback) { var app, dialog, modal, table; if (element.storeState) { element.storeState(); } app = ContentTools.EditorApp.get(); modal = new ContentTools.ModalUI(); table = element.closest(function(node) { return node && node.type() === 'Table'; }); dialog = new ContentTools.TableDialog(table); dialog.addEventListener('cancel', (function(_this) { return function() { modal.hide(); dialog.hide(); if (element.restoreState) { element.restoreState(); } return callback(false); }; })(this)); dialog.addEventListener('save', (function(_this) { return function(ev) { var index, keepFocus, node, tableCfg, _ref; tableCfg = ev.detail(); keepFocus = true; if (table) { _this._updateTable(tableCfg, table); keepFocus = element.closest(function(node) { return node && node.type() === 'Table'; }); } else { table = _this._createTable(tableCfg); _ref = _this._insertAt(element), node = _ref[0], index = _ref[1]; node.parent().attach(table, index); keepFocus = false; } if (keepFocus) { element.restoreState(); } else { table.firstSection().children[0].children[0].children[0].focus(); } modal.hide(); dialog.hide(); return callback(true); }; })(this)); app.attach(modal); app.attach(dialog); modal.show(); return dialog.show(); }; Table._adjustColumns = function(section, columns) { var cell, cellTag, cellText, currentColumns, diff, i, row, _i, _len, _ref, _results; _ref = section.children; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { row = _ref[_i]; cellTag = row.children[0].tagName(); currentColumns = row.children.length; diff = columns - currentColumns; if (diff < 0) { _results.push((function() { var _j, _results1; _results1 = []; for (i = _j = diff; diff <= 0 ? _j < 0 : _j > 0; i = diff <= 0 ? ++_j : --_j) { cell = row.children[row.children.length - 1]; _results1.push(row.detach(cell)); } return _results1; })()); } else if (diff > 0) { _results.push((function() { var _j, _results1; _results1 = []; for (i = _j = 0; 0 <= diff ? _j < diff : _j > diff; i = 0 <= diff ? ++_j : --_j) { cell = new ContentEdit.TableCell(cellTag); row.attach(cell); cellText = new ContentEdit.TableCellText(''); _results1.push(cell.attach(cellText)); } return _results1; })()); } else { _results.push(void 0); } } return _results; }; Table._createTable = function(tableCfg) { var body, foot, head, table; table = new ContentEdit.Table(); if (tableCfg.head) { head = this._createTableSection('thead', 'th', tableCfg.columns); table.attach(head); } body = this._createTableSection('tbody', 'td', tableCfg.columns); table.attach(body); if (tableCfg.foot) { foot = this._createTableSection('tfoot', 'td', tableCfg.columns); table.attach(foot); } return table; }; Table._createTableSection = function(sectionTag, cellTag, columns) { var cell, cellText, i, row, section, _i; section = new ContentEdit.TableSection(sectionTag); row = new ContentEdit.TableRow(); section.attach(row); for (i = _i = 0; 0 <= columns ? _i < columns : _i > columns; i = 0 <= columns ? ++_i : --_i) { cell = new ContentEdit.TableCell(cellTag); row.attach(cell); cellText = new ContentEdit.TableCellText(''); cell.attach(cellText); } return section; }; Table._updateTable = function(tableCfg, table) { var columns, foot, head, section, _i, _len, _ref; if (!tableCfg.head && table.thead()) { table.detach(table.thead()); } if (!tableCfg.foot && table.tfoot()) { table.detach(table.tfoot()); } columns = table.firstSection().children[0].children.length; if (tableCfg.columns !== columns) { _ref = table.children; for (_i = 0, _len = _ref.length; _i < _len; _i++) { section = _ref[_i]; this._adjustColumns(section, tableCfg.columns); } } if (tableCfg.head && !table.thead()) { head = this._createTableSection('thead', 'th', tableCfg.columns); table.attach(head); } if (tableCfg.foot && !table.tfoot()) { foot = this._createTableSection('tfoot', 'td', tableCfg.columns); return table.attach(foot); } }; return Table; })(ContentTools.Tool); ContentTools.Tools.Indent = (function(_super) { __extends(Indent, _super); function Indent() { return Indent.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Indent, 'indent'); Indent.label = 'Indent'; Indent.icon = 'indent'; Indent.canApply = function(element, selection) { return element.parent().type() === 'ListItem' && element.parent().parent().children.indexOf(element.parent()) > 0; }; Indent.apply = function(element, selection, callback) { element.parent().indent(); return callback(true); }; return Indent; })(ContentTools.Tool); ContentTools.Tools.Unindent = (function(_super) { __extends(Unindent, _super); function Unindent() { return Unindent.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Unindent, 'unindent'); Unindent.label = 'Unindent'; Unindent.icon = 'unindent'; Unindent.canApply = function(element, selection) { return element.parent().type() === 'ListItem'; }; Unindent.apply = function(element, selection, callback) { element.parent().unindent(); return callback(true); }; return Unindent; })(ContentTools.Tool); ContentTools.Tools.LineBreak = (function(_super) { __extends(LineBreak, _super); function LineBreak() { return LineBreak.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(LineBreak, 'line-break'); LineBreak.label = 'Line break'; LineBreak.icon = 'line-break'; LineBreak.canApply = function(element, selection) { return element.content; }; LineBreak.apply = function(element, selection, callback) { var br, cursor, tail, tip; cursor = selection.get()[0] + 1; tip = element.content.substring(0, selection.get()[0]); tail = element.content.substring(selection.get()[1]); br = new HTMLString.String('<br>', element.content.preserveWhitespace()); element.content = tip.concat(br, tail); element.updateInnerHTML(); element.taint(); selection.set(cursor, cursor); element.selection(selection); return callback(true); }; return LineBreak; })(ContentTools.Tool); ContentTools.Tools.Image = (function(_super) { __extends(Image, _super); function Image() { return Image.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Image, 'image'); Image.label = 'Image'; Image.icon = 'image'; Image.canApply = function(element, selection) { return !element.isFixed(); }; Image.apply = function(element, selection, callback) { var app, dialog, modal; if (element.storeState) { element.storeState(); } app = ContentTools.EditorApp.get(); modal = new ContentTools.ModalUI(); dialog = new ContentTools.ImageDialog(); dialog.addEventListener('cancel', (function(_this) { return function() { modal.hide(); dialog.hide(); if (element.restoreState) { element.restoreState(); } return callback(false); }; })(this)); dialog.addEventListener('save', (function(_this) { return function(ev) { var detail, image, imageAttrs, imageSize, imageURL, index, node, _ref; detail = ev.detail(); imageURL = detail.imageURL; imageSize = detail.imageSize; imageAttrs = detail.imageAttrs; if (!imageAttrs) { imageAttrs = {}; } imageAttrs.height = imageSize[1]; imageAttrs.src = imageURL; imageAttrs.width = imageSize[0]; image = new ContentEdit.Image(imageAttrs); _ref = _this._insertAt(element), node = _ref[0], index = _ref[1]; node.parent().attach(image, index); image.focus(); modal.hide(); dialog.hide(); return callback(true); }; })(this)); app.attach(modal); app.attach(dialog); modal.show(); return dialog.show(); }; return Image; })(ContentTools.Tool); ContentTools.Tools.Video = (function(_super) { __extends(Video, _super); function Video() { return Video.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Video, 'video'); Video.label = 'Video'; Video.icon = 'video'; Video.canApply = function(element, selection) { return !element.isFixed(); }; Video.apply = function(element, selection, callback) { var app, dialog, modal; if (element.storeState) { element.storeState(); } app = ContentTools.EditorApp.get(); modal = new ContentTools.ModalUI(); dialog = new ContentTools.VideoDialog(); dialog.addEventListener('cancel', (function(_this) { return function() { modal.hide(); dialog.hide(); if (element.restoreState) { element.restoreState(); } return callback(false); }; })(this)); dialog.addEventListener('save', (function(_this) { return function(ev) { var index, node, url, video, _ref; url = ev.detail().url; if (url) { video = new ContentEdit.Video('iframe', { 'frameborder': 0, 'height': ContentTools.DEFAULT_VIDEO_HEIGHT, 'src': url, 'width': ContentTools.DEFAULT_VIDEO_WIDTH }); _ref = _this._insertAt(element), node = _ref[0], index = _ref[1]; node.parent().attach(video, index); video.focus(); } else { if (element.restoreState) { element.restoreState(); } } modal.hide(); dialog.hide(); return callback(url !== ''); }; })(this)); app.attach(modal); app.attach(dialog); modal.show(); return dialog.show(); }; return Video; })(ContentTools.Tool); ContentTools.Tools.Undo = (function(_super) { __extends(Undo, _super); function Undo() { return Undo.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Undo, 'undo'); Undo.label = 'Undo'; Undo.icon = 'undo'; Undo.requiresElement = false; Undo.canApply = function(element, selection) { var app; app = ContentTools.EditorApp.get(); return app.history && app.history.canUndo(); }; Undo.apply = function(element, selection, callback) { var app, snapshot; app = ContentTools.EditorApp.get(); app.history.stopWatching(); snapshot = app.history.undo(); app.revertToSnapshot(snapshot); return app.history.watch(); }; return Undo; })(ContentTools.Tool); ContentTools.Tools.Redo = (function(_super) { __extends(Redo, _super); function Redo() { return Redo.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Redo, 'redo'); Redo.label = 'Redo'; Redo.icon = 'redo'; Redo.requiresElement = false; Redo.canApply = function(element, selection) { var app; app = ContentTools.EditorApp.get(); return app.history && app.history.canRedo(); }; Redo.apply = function(element, selection, callback) { var app, snapshot; app = ContentTools.EditorApp.get(); app.history.stopWatching(); snapshot = app.history.redo(); app.revertToSnapshot(snapshot); return app.history.watch(); }; return Redo; })(ContentTools.Tool); ContentTools.Tools.Remove = (function(_super) { __extends(Remove, _super); function Remove() { return Remove.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(Remove, 'remove'); Remove.label = 'Remove'; Remove.icon = 'remove'; Remove.canApply = function(element, selection) { return !element.isFixed(); }; Remove.apply = function(element, selection, callback) { var app, list, row, table; app = ContentTools.EditorApp.get(); element.blur(); if (element.nextContent()) { element.nextContent().focus(); } else if (element.previousContent()) { element.previousContent().focus(); } if (!element.isMounted()) { callback(true); return; } switch (element.type()) { case 'ListItemText': if (app.ctrlDown()) { list = element.closest(function(node) { return node.parent().type() === 'Region'; }); list.parent().detach(list); } else { element.parent().parent().detach(element.parent()); } break; case 'TableCellText': if (app.ctrlDown()) { table = element.closest(function(node) { return node.type() === 'Table'; }); table.parent().detach(table); } else { row = element.parent().parent(); row.parent().detach(row); } break; default: element.parent().detach(element); break; } return callback(true); }; return Remove; })(ContentTools.Tool); TimeTool = (function(_super) { __extends(TimeTool, _super); function TimeTool() { return TimeTool.__super__.constructor.apply(this, arguments); } ContentTools.ToolShelf.stow(TimeTool, 'time'); TimeTool.label = 'Time'; TimeTool.icon = 'time'; TimeTool.tagName = 'time'; TimeTool.apply = function(element, selection, callback) { var allowScrolling, app, dialog, domElement, from, measureSpan, modal, rect, selectTag, to, transparent, _ref; element.storeState(); selectTag = new HTMLString.Tag('span', { 'class': 'ct--puesdo-select' }); _ref = selection.get(), from = _ref[0], to = _ref[1]; element.content = element.content.format(from, to, selectTag); element.updateInnerHTML(); app = ContentTools.EditorApp.get(); modal = new ContentTools.ModalUI(transparent = true, allowScrolling = true); modal.addEventListener('click', function() { this.unmount(); dialog.hide(); element.content = element.content.unformat(from, to, selectTag); element.updateInnerHTML(); element.restoreState(); return callback(false); }); domElement = element.domElement(); measureSpan = domElement.getElementsByClassName('ct--puesdo-select'); rect = measureSpan[0].getBoundingClientRect(); dialog = new TimeDialog(this.getDatetime(element, selection)); dialog.position([rect.left + (rect.width / 2) + window.scrollX, rect.top + (rect.height / 2) + window.scrollY]); dialog.addEventListener('save', function(ev) { var datetime, time; datetime = ev.detail().datetime; element.content = element.content.unformat(from, to, 'time'); if (datetime) { time = new HTMLString.Tag('time', { datetime: datetime }); element.content = element.content.format(from, to, time); } element.updateInnerHTML(); element.taint(); modal.unmount(); dialog.hide(); element.content = element.content.unformat(from, to, selectTag); element.updateInnerHTML(); element.restoreState(); return callback(true); }); app.attach(modal); app.attach(dialog); modal.show(); return dialog.show(); }; TimeTool.getDatetime = function(element, selection) { var c, from, selectedContent, tag, to, _i, _j, _len, _len1, _ref, _ref1, _ref2; _ref = selection.get(), from = _ref[0], to = _ref[1]; selectedContent = element.content.slice(from, to); _ref1 = selectedContent.characters; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { c = _ref1[_i]; if (!c.hasTags('time')) { continue; } _ref2 = c.tags(); for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { tag = _ref2[_j]; if (tag.name() === 'a') { return tag.attr('href'); } } return ''; } }; return TimeTool; })(ContentTools.Tools.Bold); TimeDialog = (function(_super) { __extends(TimeDialog, _super); function TimeDialog() { return TimeDialog.__super__.constructor.apply(this, arguments); } TimeDialog.prototype.mount = function() { TimeDialog.__super__.mount.call(this); this._domInput.setAttribute('name', 'time'); this._domInput.setAttribute('placeholder', 'Enter a date/time/duration...'); return this._domElement.removeChild(this._domTargetButton); }; TimeDialog.prototype.save = function() { var detail; detail = { datetime: this._domInput.value.trim() }; return this.dispatchEvent(this.createEvent('save', detail)); }; return TimeDialog; })(ContentTools.LinkDialog); ContentTools.DEFAULT_TOOLS[3].push('time'); }).call(this);
let cards = [ { image: "https://static.wikia.nocookie.net/holy-world-war-fan-fiction-series/images/a/a1/Itachi_Uchiha.png/revision/latest/scale-to-width-down/250? cb=20171115205823" , //Itachi Uchiha value: 1, status: "closed" }, { image: "https://static.wikia.nocookie.net/holy-world-war-fan-fiction-series/images/a/a1/Itachi_Uchiha.png/revision/latest/scale-to-width-down/250? cb=20171115205823", //Itachi Uchiha value: 1, status: "closed" }, { image: "https://static.wikia.nocookie.net/naruto/images/2/21/Sasuke_Part_1.png/revision/latest/scale-to-width-down/300?cb=20170716092103", // Sasuke Uchiha value: 2, status: "closed" }, { image: "https://static.wikia.nocookie.net/naruto/images/2/21/Sasuke_Part_1.png/revision/latest/scale-to-width-down/300?cb=20170716092103", //Sasuke Uchiha value: 2, status: "closed" }, { image: "https://preview.redd.it/k6vvk45s5ml31.jpg?width=640&crop=smart&auto=webp&s=2656a19becd9388185bd8814eb1ae6269bd675e8", // Obito value: 3, status: "closed" }, { image: "https://preview.redd.it/k6vvk45s5ml31.jpg?width=640&crop=smart&auto=webp&s=2656a19becd9388185bd8814eb1ae6269bd675e8", // Obito value: 3, status: "closed" }, { image: "https://static.wikia.nocookie.net/naruto/images/4/4c/Shisui_Uchiha.png/revision/latest?cb=20140418091747", // Shishui value: 4, status: "closed" }, { image: "https://static.wikia.nocookie.net/naruto/images/4/4c/Shisui_Uchiha.png/revision/latest?cb=20140418091747", // Shishui value: 4, status: "closed" }, { image: "https://static.wikia.nocookie.net/naruto/images/b/b3/Madara%27s_Rinnegan.png/revision/latest?cb=20130725131804", // Madara value: 5, status: "closed" }, { image: "https://static.wikia.nocookie.net/naruto/images/b/b3/Madara%27s_Rinnegan.png/revision/latest?cb=20130725131804", // Madara value: 5, status: "closed" } ] // Shuffling algorithm. for (let i=cards.length-1; i>=0; i--){ let j = Math.floor(Math.random()*(i+1)); let temp = cards[i]; cards[i] = cards[j]; cards[j] = temp; } // console.log(cards); // Making the cards appear on the screen. displayCards = (cards) => { let img_tag = ""; for (let i=0; i<cards.length; i++) { img_tag += `<div class="card" style="background-image: url('${cards[i].image}')"> <div class="overlay ${cards[i].status}" onclick="open_cards(${i});"></div> </div>\n` } document.getElementById("cards").innerHTML = img_tag; } displayCards(cards); // Game Logic let flag=0, val1=null, val2=null, score = 0; open_cards = (index) => { cards[index].status = "opened"; // card[index]; displayCards(cards); if (flag === 0){ val1 = cards[index].value; flag = 1; } else if (flag === 1){ val2 = cards[index].value; if (val1 === val2){ score++; document.getElementById("score").innerText = score; // alert("You WIN!!"); val1 = val2 = null; flag = 0; } else { alert("Game Over!!"); location.reload(); } } }
import React, { useState, useLayoutEffect } from 'react'; const HEIGHT_RATIO = 3.375; const getImage = (locale = 'en-us', code = locale) => { return { ios: `https://linkmaker.itunes.apple.com/images/badges/${locale}/badge_appstore-lrg.svg`, android: `https://raw.github.com/yjb94/google-play-badge-svg/master/img/${code}_get.svg?sanitize=true` } } const ReactStoreBadges = ({ url, defaultLocale = 'en-us', platform, locale = (typeof navigator !== 'undefined' && navigator.language || defaultLocale), width = 135, height = width / HEIGHT_RATIO, target = "_self" }) => { let shortCode = locale = locale.toLowerCase() const expeptionLocale = ["zh-cn", "zh-tw"]; if (expeptionLocale.indexOf(locale) === -1) { shortCode = locale.split(/[_-]/)[0]; } const [image, setImage] = useState(getImage(locale, shortCode)) const setDefaultImage = () => { setImage(getImage(defaultLocale, shortCode)) } useLayoutEffect(() => { setImage(getImage(locale, shortCode)) }, [locale]) return ( <a style={{ display: 'inline-block', height: height, width: width, }} href={url} target={target} > <img src={image[platform]} style={{ width: '100%', height: '100%' }} onError={setDefaultImage} /> </a> ); } export default ReactStoreBadges
events = {}; events.afterInit = function() { var doc = this; var Class = doc.constructor; if(!doc._isNew) { return; } // Find a class on which the behavior had been set. var classBehavior = Class.getBehavior('slug'); var options = classBehavior.options; // Find the definition of the field. var field = classBehavior.definition.fields[options.slugFieldName]; if(_.has(field, 'default')) { return } var value = doc[options.slugFieldName]; if(value === null) { Class.getBehavior('slug').generateSlug(doc); } }; events.beforeSave = function() { var doc = this; var Class = doc.constructor; // Find a class on which the behavior had been set. var classBehavior = Class.getBehavior('slug'); var options = classBehavior.options; // Check if a field from which we want to create a slug has been // modified. var modified = doc.getModified(); if (!_.has(modified, options.fieldName)) { return; } Class.getBehavior('slug').generateSlug(doc); };
const resolve = { data: { avatarUpload: { filename: "some.png", mimetype: "", encoding: "", url: "@/assets/logo.png", } } } export default resolve
import { width, height, radius, padding } from './config' export const layouts = [ [ [width / 8, height / 2, 1, 'database'], [width / 4, height / 2, 2, 'model'], [width / 4, height * (3 /8), 3, 'view'], [width * (3 / 8), height * (7 / 16), 4, 'controller'], [width * (5 / 8), height * (7 / 16), 5, 'client'] ], [ [width / 8, height / 2, 1, 'database'], [width / 4, height / 2, 2, 'knex'], [width * (3 / 8), height / 2, 4, 'JSON API'], [width * (13 / 16), height / 2, 3,'react'] ], [ [width / 8, height / 2, 1, 'database'], [width / 4, height / 2, 2, 'knex'], [width * (3 / 8), height / 2, 4, 'JSON API'], [width * (13 / 16), height / 2, 3, 'react'], [width * (10 / 16), height / 2, 6, 'actions'], [width * (10 / 16), height * (6 / 16), 7, 'reducer'], [width * (13 / 16), height * (6 / 16), 8, 'state'] ], [ [width / 8, height / 2, 1, 'database'], [width / 4, height / 2, 2, 'knex'], [width * (3 / 8), height / 2, 4, 'JSON API'], [width * (13 / 16), height / 2, 3, 'react'], [width * (10 / 16), height / 2, 6, 'actions'], [width * (10 / 16), height * (6 / 16), 7, 'reducer'], [width * (13 / 16), height * (6 / 16), 8, 'state'], [width * (13 / 16), height * (7 / 16), 9, 'react-redux'], [width * (10 / 16), height * (5 / 16), 10, 'react-router'], [width * (10 / 16), height * (4 / 16), 11, 'assets'], [width * (3 / 8), height * (4 / 16), 12, 'static-server'] ], [ [width / 8, height / 2, 1, 'database'], [width / 4, height / 2, 2, 'knex'], [width * (3 / 8), height / 2, 4, 'JSON API'], [width * (13 / 16), height / 2, 3, 'react'], [width * (10 / 16), height / 2, 6, 'actions'], [width * (10 / 16), height * (6 / 16), 7, 'reducer'], [width * (13 / 16), height * (6 / 16), 8, 'state'], [width * (13 / 16), height * (7 / 16), 9, 'react-redux'], [width * (10 / 16), height * (5 / 16), 10, 'react-router'], [width * (10 / 16), height * (4 / 16), 11, 'assets'], [width * (3 / 8), height * (4 / 16), 12, 'static-server'] ] ] export const links = [ [ [0, 1], [3, 1], [3, 2], [4, 3] ], [ [0, 1], [2, 1], [3, 2], ], [ [0, 1], [2, 1], [4, 2], [4, 5], [5, 6], [6, 3], [3, 4], ], [ [0, 1], [2, 1], [4, 2], [4, 5], [5, 6], [6, 3], [3, 4], [9, 10] ] ] export const diagramTitles = [ 'THEY WERE SIMPLER TIMES', 'NOW SERVING JSON', 'CLIENT-SIDE STATE', 'CHALLENGE #3: The modern stack' ] const hour = width / 7 const start = 0 const y = height / 4 const h = 50 export const timelineData = [ { x1: start, y1: y, x2: start + hour, y2: y, stroke: 'black', id: 1, label: 'intro', time: '9am' }, { x1: start + hour, y1: y, x2: start + (2 * hour), y2: y, stroke: 'black', id: 2, label: 'toy app', time: '10am' }, { x1: start + (2 * hour), y1: y, x2: start + (3.5 * hour), y2: y, stroke: 'black', id: 3, label: 'challenge', time: '11am' }, { x1: start + (5 * hour), y1: y, x2: start + (6 * hour), y2: y, stroke: 'black', label: 'mob', time: '2pm' }, { x1: start + (6 * hour), y1: y, x2: start + (7 * hour), y2: y, stroke: 'black', label: 'challenge', time: '3pm' }, { x1: start, y1: y + (h * 2), x2: start + (hour/ 2), y2: y + (h * 2), stroke: 'black', id: 5, label: 'recap' } ]
// Assignment code here // Get references to the #generate element //variables of password var lowerCaseCharacters = ['a', 'b', 'c', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; var upperCaseCharacters = ['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']; var num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; var specialCharacters = [' ', '!', '"', '#', '$', '%', "'", '(', ')', '*', '+', "'", "-", "/", ":", ".", ";", "<", ">", "?", "@", "[", ']', '|', '^', "_", '~', '`', '{', '}']; var length = ""; var hasSpecialCharacters; var hasLowerCaseChar; var hasUpperCaseChar; var hasNumericCharacter; //generate button slection var generateBtn = document.querySelector("#generate"); //Get password information from user function getPasswordOptions() { //Varaible to store length of password from user input var length = parseInt( prompt("How many character would you like your password to contain?") ); //Conditional statement to check if password length is a number. Prompts end if this evaluates false if(Number.isNaN(length)) { alert("Password length must be provided as a number"); return null; } //conditional statement to check if password length is 8 characters long. Prompts end if this evaluates false if(length < 8){ alert("Password length must be at least 8 characters."); return null; } //conditional statement to check if password length is 128 characters, prompts end if this evaluates false if(length > 128) { alert("Password length must be less than 129 characters."); return null; } //variable to store boolean regarding the inclusion of special characters var hasSpecialCharacters = confirm( "Click OK to confirm including special characters." ); //Variable to store boolean regarding the inclusion of numeric characters var hasNumericCharacter = confirm( "Click OK to confirm including numeric characters." ); //Variable to store lowercase letters var hasLowerCaseChar = confirm( "Click OK to confirm including lower case characters. " ); //Variable to store Upper case letters var hasUpperCaseChar = confirm( "Click OK to confirm including upper case characters." ); //Conditional statement to check if user does not include any types of characters if(hasUpperCaseChar === false && hasLowerCaseChar === false && hasNumericCharacter === false && hasSpecialCharacters ===false){ alert("Must choose at least one variable for password.") return null; } }; //create password from user var writePassword = function () { var password = getPasswordOptions(); // Write password to the #password input var passwordText = document.querySelector("#password"); var passwordLetters = "" if(hasNumericCharacter === true && hasLowerCaseChar === true && hasSpecialCharacters === true && hasUpperCaseChar === true) { passwordLetters = passwordLetters.concat(num + upperCaseCharacters + specialCharacters + lowerCaseCharacters); console.log(passwordLetters); } if(hasSpecialCharacters===true && hasUpperCaseChar === true && hasLowerCaseChar == true && hasNumericCharacter === false){ passwordLetters = passwordLetters.concat(specialCharacters + upperCaseCharacters + lowerCaseCharacters); } if(hasSpecialCharacters===true && hasUpperCaseChar === false && hasLowerCaseChar == true && hasNumericCharacter === true){ passwordLetters = passwordLetters.concat(specialCharacters + lowerCaseCharacters + num); } if(hasSpecialCharacters===false && hasUpperCaseChar === true && hasLowerCaseChar == true && hasNumericCharacter === true){ passwordLetters = passwordLetters.concat(lowerCaseCharacters + upperCaseCharacters + num); } if(hasSpecialCharacters===true && hasUpperCaseChar === false && hasLowerCaseChar == true && hasNumericCharacter === true){ passwordLetters = passwordLetters.concat(lowerCaseCharacters + specialCharacters + num) } if(hasSpecialCharacters===false && hasUpperCaseChar === false && hasLowerCaseChar == true && hasNumericCharacter === true){ passwordLetters = passwordLetters.concat(lowerCaseCharacters + num); } if(hasSpecialCharacters===false && hasUpperCaseChar === false && hasLowerCaseChar == false && hasNumericCharacter === true){ passwordLetters = passwordLetters.concat(num); } if(hasSpecialCharacters===false && hasUpperCaseChar === true && hasLowerCaseChar == false && hasNumericCharacter === false){ passwordLetters = passwordLetters.concat(upperCaseCharacters); } if(hasSpecialCharacters===true && hasUpperCaseChar === false && hasLowerCaseChar == false && hasNumericCharacter === false){ passwordLetters = passwordLetters.concat(specialCharacters); } if(hasSpecialCharacters===false && hasUpperCaseChar === false && hasLowerCaseChar == true && hasNumericCharacter === false){ passwordLetters = passwordLetters.concat(lowerCaseCharacters); } console.log(passwordLetters) //randomize password order var randomPassword = "" for (var i = 0; i < length; i++) { randomPassword = randomPassword + passwordLetters[Math.floor(Math.random() * passwordLetters.length)]; console.log(randomPassword); } console.log(randomPassword); passwordText.value = password; console.log(passwordText); } // Add event listener to generate button generateBtn.addEventListener("click", writePassword);
import React, { Component, Fragment } from 'react'; import { Row, Col } from 'react-bootstrap'; import { Input } from '@material-ui/core'; import './AadhaarCardForm.scss'; export class AadhaarCardForm extends Component { constructor(props) { super(props); this.state = this.getInitialState(); this.handleChange = this.handleChange.bind(this); } getInitialState() { const initialState = {}; for (let i = 0; i < 12; i++) { initialState[`aadhaarInput${i}`] = this.props.setValue ? this.props.setValue[i] : ''; } initialState.inputsArray = this.getInputsArray(); initialState.focusId = initialState.inputsArray[0].id; return initialState; } componentDidUpdate() { const { focusId } = this.state; } getRandomID() { return ( '_' + Math.random() .toString(36) .substr(2, 9) ); } getInputsArray() { const inputs = []; for (let i = 0; i < 12; i++) { inputs.push({ id: this.getRandomID(), name: `aadhaarInput${i}` }); } return inputs; } handleChange(e, inputIndex) { let key = e.keyCode || e.charCode; const { inputsArray } = this.state; const { name } = e.target; let focusId = inputsArray[inputIndex].id; let value = e; console.log(e.keyCode); if (key === 8 || key === 46) { if (this.state[`aadhaarInput${inputIndex}`] === '') { const prevInputIndex = inputIndex - 1; if (prevInputIndex >= 0) { focusId = inputsArray[prevInputIndex].id; } document.getElementById(focusId).focus(); let aadhaarString = ''; for (let i = 0; i < inputsArray.length; i += 1) { aadhaarString += this.state[`aadhaarInput${i}`]; } this.props.sendAadhaarNumber(aadhaarString); } else { this.setState( { [name]: '', focusId }, () => { document.getElementById(focusId).focus(); let aadhaarString = ''; const { inputsArray } = this.state; for (let i = 0; i < inputsArray.length; i += 1) { aadhaarString += this.state[`aadhaarInput${i}`]; } this.props.sendAadhaarNumber(aadhaarString); } ); } } else if (key >= 48 && key <= 57 && this.state[`aadhaarInput${inputIndex}`] === '') { let char = String.fromCharCode(key); console.log(char, key); const nextInputIndex = inputIndex + 1; if (nextInputIndex < inputsArray.length) { focusId = inputsArray[nextInputIndex].id; } this.setState( { [name]: char, focusId }, () => { document.getElementById(focusId).focus(); let aadhaarString = ''; for (let i = 0; i < inputsArray.length; i += 1) { aadhaarString += this.state[`aadhaarInput${i}`]; } this.props.sendAadhaarNumber(aadhaarString); } ); } } render() { const { inputsArray } = this.state; const form = inputsArray.map((input, index) => { if (index === 4 || index === 8) { return ( <Fragment key={input.id}> <div className='aadhaar-input'> <span>/</span> </div> <div className='aadhaar-input'> <Input type='number' onKeyDown={e => this.handleChange(e, index)} name={input.name} id={input.id} value={this.state[`aadhaarInput${index}`]} maxLength='1' /> </div> </Fragment> ); } else { return ( <div key={input.id} className='aadhaar-input'> <Input type='number' onKeyDown={e => this.handleChange(e, index)} name={input.name} id={input.id} value={this.state[`aadhaarInput${index}`]} maxLength='1' /> </div> ); } }); return <div id='inputs-container'>{form}</div>; } } export default AadhaarCardForm;
import React from 'react' import { SRLWrapper } from "simple-react-lightbox"; import image1 from '../assests/portfolio/image1.jpg' import image2 from '../assests/portfolio/image2.jpg' import image3 from '../assests/portfolio/image3.jpg' import image4 from '../assests/portfolio/image4.jpg' import image5 from '../assests/portfolio/image5.jpg' import image6 from '../assests/portfolio/image6.jpg' import image7 from '../assests/portfolio/image7.jpg' import image8 from '../assests/portfolio/image8.jpg' import image9 from '../assests/portfolio/image9.jpg' function Photography() { return ( <div className='photography-container'> <div id='photography' className='photography-image'> <div className='photography-header'> <h1>PHOTOGRAPHY</h1> </div> </div> <div className='photography-contents'> <p>Bro ipsum dolor sit amet reverse camber park rat air poaching skid lid, north shore schwag air free ride ski bum ollie frozen chicken heads. Taco DH wheelie drop smear greasy frozen chicken heads avie bomb hole gondy hurl carcass tele. Wheels bro grab back country couloir air. Shreddin ripper dope huckfest afterbang brain bucket fatty ski bum punter gaper hurl carcass flow face shots greasy cork. McTwist lid yard sale washboard shred. Free ride derailleur rail, road rash lid smear huck gorby. White room wheelie booter, air sharkbite schwag cornice first tracks air gapers freshies caballerial endo.</p> <SRLWrapper> <div className='image-showcase'> <div className='row-1'> <img src={image1} alt='img1' /> <img src={image2} alt='img2' /> <img src={image3} alt='img3' /> </div> <div className='row-2'> <img src={image4} alt='img4' /> <img src={image5} alt='img5' /> <img src={image6} alt='img6' /> </div> <div className='row-3'> <img src={image7} alt='img7' /> <img src={image8} alt='img8' /> <img src={image9} alt='img9' /> </div> </div> </SRLWrapper> </div> </div> ) } export default Photography
import React from 'react' import ToDoDoneGroup from './ToDoDoneGroup' function ToDoDoneList() { return ( <div> <h1>Todo Done List</h1> <ToDoDoneGroup/> </div> ) } export default ToDoDoneList
/* eslint-disable no-unused-vars */ import { Signup, SignIn, AllUsers } from '../../controllers/user' import passportStrategy from '../../services/passportStrategy' import passport from 'passport' const requireSignIn = passport.authenticate('local', { session: false }) const requireAuth = passport.authenticate('jwt', { session: false }) const userRoutes = (app) => { // index route app.get('/api/users/', requireAuth, AllUsers) app.post('/api/user/signin', requireSignIn, SignIn) app.post('/api/user/signup', Signup) } export default userRoutes
var assert = require('assert') var curl = require('.') var tests = require('straight-to-curly-quotes') // Replace quotation marks with text descriptions for easy comparison by eye. function asciify(string) { return string .replace(/"/g, '{Straight Double}') .replace(/'/g, '{Straight Single}') .replace(/“/g, '{Left Double}') .replace(/”/g, '{Right Double}') .replace(/‘/g, '{Left Single}') .replace(/’/g, '{Right Single}') } function error(string) { process.stderr.write(string + '\n') } // For each of the straight-to-curly-quotes tests... tests.forEach(function(test) { try { assert.equal(curl(test.straight), test.curly) } catch (e) { error('Actual: ' + asciify(curl(test.straight))) error('Expected: ' + asciify(test.curly)) process.exit(1) } }) process.stdout.write('Passed ' + tests.length + ' tests.\n') process.exit(0)
const delate = (event) => { $(event.target).parent().parent().parent().remove(); }; module.exports = delate;
import React, { useState, useEffect } from "react"; import Axios from "axios"; import ls from "local-storage"; function Login(props) { // state const [authData, setauthData] = useState(); // handler function const handleChange = event => { event.preventDefault(); // const {name, value} = event.target; setauthData({ ...authData, [event.target.name]: event.target.value }); }; const handleSubmit = event => { event.preventDefault(); console.log(authData); Axios.post(`/api/login`, authData).then(result => { console.log(result.data); // ls.set(("user", result.data.user.phone)); localStorage.setItem("phone", result.data.user.phone); localStorage.setItem("id", result.data.user._id); // set the browser storage with the token // if (typeof result.data === Object) { props.history.push(`/products`); // } else { // console.log(result.data); // props.history.push(`/login`); // } }); }; console.log(authData); return ( <div className="login-wrapper"> <div className="form-wrapper"> <h1>Login</h1> <form onSubmit={handleSubmit}> <div className="email"> <label htmlFor="email">Email</label> <input type="email" onChange={handleChange} placeholder="Email Account" name="email" /> </div> <div className="password"> <label htmlFor="phone">Password</label> <input type="password" className="" onChange={handleChange} placeholder="Password" name="password" /> </div> </form> <button onClick={handleSubmit}>Log In</button> <a href="#!"> <small>Forgot Password?</small> </a> </div> </div> ); } export default Login;
$(".input").on('input', function(){ var number1 = document.getElementById('num1').value; number1 = parseFloat(number1); var number2 = document.getElementById('num2').value; number2 = parseFloat(number2); document.getElementById('result').value = number1 * number2; });
const bcrypt = require('bcrypt') const LocalStrategy = require('passport-local').Strategy const users = require('../models/users') function initializePassport(passport) { passport.use(new LocalStrategy({ usernameField: 'email' }, async function (username, password, done) { username = username.toLowerCase() const user = await users.findOne({ mail: username }) if (user == null) { return done(null, false, { errorMsg: 'Email is not found' }) } try { const isValidPass = await bcrypt.compare(password, user.password) if (isValidPass) { return done(null, user) } else { return done(null, false, { errorMsg: 'Email or password is not right' }) } } catch (e) { done(e) } })) passport.serializeUser(function (user, done) { done(null, user.id) }) passport.deserializeUser(function (id, done) { users.findById(id, function (err, user) { done(err, user) }) }) } module.exports = initializePassport
const express = require("express"); const router = express.Router(); const { createGlamping, deleteGlamping, getGlampings, updateGlamping, } = require("../controllers/glampingController"); router.post("/create", createGlamping); router.delete("/delete/:id", deleteGlamping); router.get("/glampings", getGlampings); router.patch("/update/:id", updateGlamping); module.exports = router;
document.addEventListener('DOMContentLoaded', () => { // ELEMENT: Navbar burger menu on mobile // Get all "navbar-burger" elements const $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0); // Check if there are any navbar burgers if ($navbarBurgers.length > 0) { // Add a click event on each of them $navbarBurgers.forEach( el => { el.addEventListener('click', () => { // Get the target from the "data-target" attribute const target = el.dataset.target; const $target = document.getElementById(target); // Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu" el.classList.toggle('is-active'); $target.classList.toggle('is-active'); }); }); } // ELEMENT: close notifications pressing the X (document.querySelectorAll('.notification .delete') || []).forEach(($delete) => { var $notification = $delete.parentNode; $delete.addEventListener('click', () => { $notification.parentNode.removeChild($notification); }); }); // ELEMENT: cycle through tabs let tabs = (document.querySelectorAll('.tabs li') || []) let tabs_targets = (document.querySelectorAll('.tab-target') || []) tabs.forEach((tab) => { let target = document.getElementById(tab.dataset.target); tab.addEventListener('click', () => { if (tab.classList.contains('is-active')) return; tabs.forEach(toggle_tab => { toggle_tab.classList.remove('is-active'); tab.classList.add('is-active'); }) tabs_targets.forEach(toggle_target => { toggle_target.classList.add('is-hidden'); target.classList.remove('is-hidden'); }) }) }); // ELEMENT: open/close modals (document.querySelectorAll('.modal-trigger') || []).forEach((modalTrigger) => { let target = document.getElementById(modalTrigger.dataset.target); let html = document.querySelector('html'); modalTrigger.addEventListener('click', e => { target.classList.add('is-active'); html.classList.add('is-clipped'); }) target.addEventListener('click', e => { if (e.target.classList.contains('modal-background') || e.target.classList.contains('modal-close') || e.target.classList.contains('modal-button-close')) { target.classList.remove('is-active'); html.classList.remove('is-clipped'); } }); }); });
$(document).ready(function(){ // 訂位桌RWD winchange(); $(window).resize(function(){ winchange(); }); function winchange(){ let screen = $('html').width(); // screen = 螢幕寬 if( screen < 769){ let bookingheight = screen * 12 / 7 ; $('.result').addClass('-open'); $('.bookwindow').css('height',bookingheight); } } // 寬小於700後 直立呈現 // /訂位桌RWD // 資訊總整方塊 $('.btn_drawer').click(function(){ $('.result').toggleClass('-open'); }); // /資訊總整方塊 // 資訊總整 $('input').change(function(){ let from = $(this).attr('id'); let text = $(this).val(); $(`.${from}`).text(text); }); $('#time').change(function(){ let date=$("#time :selected").text(); $('.time').text(date); }); $('.bookwindow button').on('click',function(){ if($(this).attr('id').length == 1 ){ let NOid = $(this).attr('id'); $(`.${NOid} button`).toggleClass('selected'); }else{ $(this).toggleClass('selected'); } // let from = $(this).attr('id'); let picking = $('.x.selected').length; $('.mans').text(picking); if (picking>0){ let desk = new Array; for ( i=0 ; i<picking ; i+=1){ let from = $(`.x.selected:nth(${i})`).attr('id'); desk[i] = from; $('.tables').text(desk); let long = desk.join(''); //暫時不破版 $('.tables').closest('p').css({ width: '300px', overflowX: 'auto', }); // /暫時不破版 } }else{ desk = []; $('.tables').text(desk); } }); // /資訊總整 // 資訊傳送 $('.bookingbutton').click(function(){ let R1 = $('.date').text(); let R2 = $('.time').text(); let R3 = $('.tables').text(); let R4 = $('.mans').text(); let R5 = $('.name').text(); let R6 = $('.phone').text(); $(this).closest('a').attr('href',`./Bookmeal.html?${R1}&${R2}&${R3}&${R4}&${R5}&${R6}`); }); // /資訊傳送 });
const mongoose = require('mongoose'); const Joi = require('@hapi/joi'); const mongoose_fuzzy_searching = require('mongoose-fuzzy-searching'); Joi.objectId = require('joi-objectid')(Joi); const countrySchema = new mongoose.Schema({ country: { type: String, maxlength: 40 }, }); countrySchema.plugin(mongoose_fuzzy_searching, { fields: ["country"] }); const Country = mongoose.model('countries', countrySchema); function validateCountry(country) { const schema = { country: Joi.string().min(2).max(60).required(), _id: Joi.objectId(), }; return Joi.validate(country, schema); } exports.Country = Country; exports.validate = validateCountry;
import React, { useState } from 'react'; import './Products.css' import 'bootstrap/dist/css/bootstrap.min.css'; import { Link } from 'react-router-dom'; const Products = (props) => { const pd = props.pd; return ( <div className="col-md-4" > <div className="card" > <img src={pd.images} className="card-img-top" alt="..." /> <div className="card-body"> <h5 className="card-title">{pd.name}</h5> <p className="card-text">{pd.price}</p> <button onClick={()=>{props.handleBuyProduct(pd)}} className="btn btn-primary"><Link to={'/checkout/'+pd._id}>Buy Now</Link></button> </div> </div> </div> ) }; export default Products;
function Lobby(){ this.game_index = $('.game_index'); this.user_list = $('.user_list'); this.syncGames(); this.syncUsers(); }; Lobby.prototype={ constructor: Lobby, renderGames:function(data){ console.log("renderGames--this=", this); this.game_index.html(data); }, renderUsers:function(data){ console.log("renderUsers--this=", this); this.user_list.html(data); }, syncGames:function(){ var self = this; $.get("/games/active", function(response) { self.renderGames(response); setTimeout(function() { self.syncGames.apply(self); }, 5000); }); }, syncUsers: function(){ var self = this; $.get('/users/active', function(response) { self.renderUsers(response); setTimeout(function() { self.syncUsers.apply(self); }, 3000); }); } };
jQuery(document).ready(function(){ logout(); }); function logout() { if(jQuery('#logout').length > 0){ jQuery('#logout').on('click', function(e){ e.preventDefault(); var $this = jQuery(this); jQuery.getJSON($this.attr('href'), function (result) { console.log(result.success); if(result.success){ window.location = pathRoot + 'views/index.php'; }else{ } }); }); } }
var isFlying = false; (function () { birdClick(); })(); function getNewPosition() { var h = $(window).height() - 150; var w = $(window).width() - 150; var nh = Math.floor(Math.random() * h); var nw = Math.floor(Math.random() * w); return [nh, nw]; } function getPositionOutsideScreen() { var h = $(window).height() - 150; var w = $(window).width() - 150; var nh = Math.floor(Math.random() * h); var nw = Math.floor(Math.random() * w); var side = (Math.floor(Math.random() * 4)); side = 3; switch (side) { case 0: {//top nh = -150; break; } case 1: {//bottom nh = $(window).height(); break; } case 2: {//right nw = $(window).width() ; break; } case 3: {//left nw = -150; break; } } return [nh, nw]; } function animateBird(fun) { let newPosition = fun; $('.bird').animate({ top: newPosition[0], left: newPosition[1], }, 1000, function () { $('.bird').removeClass('flying').addClass('standing'); }); } function moveBird(fun) { let newPosition = fun; $('.bird').css({ top: newPosition[0], left: newPosition[1] }); } $('.bird').click(function () { birdClick() }); function birdClick() { moveBird(getPositionOutsideScreen()); $('.bird').removeClass('standing').addClass('flying'); setTimeout(function () { animateBird(getNewPosition()); }, Math.random() * 3000 + 6000); }
import React, { Component } from 'react' import classes from './Header.module.scss' export default class Header extends Component { render() { return ( <header className={classes.Header}> <div className={classes.Logo}> <img src={this.props.img} /> </div> <div className={classes.Username}> {this.props.username} </div> <div className={classes.Signout} onClick={this.props.signout}> Sign Out </div> </header> ) } }
function vowelCount(str) { // variable pour les voyelles de l'alphabet var vowels = 'aeiouy'; // Je dois parcourir la string str // Pour chaque boucle je dois verifier pour chaque char si mon char est egal a une voyelle // Si mon char est egal, j'incremente un compteur // Sinon je fais rien // return mon compteur var count = 0 for (var i = 0; i < str.length; i++) { if (vowels.includes(str[i])) { count = count + 1 } } return count } // afficher le resultat console.log(vowelCount('aeiouy')) /*var vowelCount = function(str){ var count = 0; for(var i = 0; i < str.length; i++){ if(str[i].toLowerCase() == 'a' || str[i].toLowerCase() == 'i' || str[i].toLowerCase() == 'o' ||str[i].toLowerCase() == 'e' ||str[i].toLowerCase() == 'u'){ s } } return count; } console.log(vowelCount('aide')) */
const Array = require('./array'); function main() { Array.SIZE_RATIO = 3; // Create an instance of the Array class let arr = new Array(); // Add an item to the array arr.push(3); arr.push(5); arr.push(15); arr.push(19); arr.push(45); arr.push(10); // Remove last items from array arr.pop(); arr.pop(); arr.pop(); if (arr.length) { for (let i = 0; i = arr.length; i++) { arr.remove(0); console.log(arr.length); } } arr.push('tauhida'); //trying to console.log 'tauhida' results in NaN. // console.log(arr.get(0)); console.log(arr); } // main(); //2. // What is the length, capacity and memory address of your array? // Array { length: 1, _capacity: 3, ptr: 0 } // What is the length, capacity and memory address of your array? // Explain the result of your program after adding the new lines of code. // Array { length: 6, _capacity: 12, ptr: 3 } // The result of the program was that 6 new values were pushed in to memory blocks to create an array. // The length of the array is 6 and the capacity has increased to 12 because our program has allocated extra memory blocks using the resize function in array.js, // For the initial push 3 memory blocks were allocated (length of array=0, plus 1, times the Array.Size_Ratio(3)). // This allowed the first three values to be added to the array as there was space for them. // When the program went to push the 4th value- the resize function was triggered as there was no more capacity. // Therefore a total of 12 memory blocks were then allocated in the resize (length of array=3, plus 1 , times Array.size_Ratio(3)). // Lastly, the pointer is at position 3 because the first time through the resize, the pointer is set as memory.allocate(3)- // which actually returns the start point (this.head in memory) of 0; simultaneously though it changes the head value to 3 for future changes. // However, the second time through the resize the pointer is set to a value of memory.allocate(12). // Prior to the this.head in memory being set to a value of 12, the start value of 3 (from previously) is returned. // So the pointer value that we are left with is 3. //3. // What is the length, capacity, and address of your array? // Explain the result of your program after adding the new lines of code. // Array { length: 3, _capacity: 12, ptr: 3 } // When the pop method ran three times it decreased the length of the array by three. // However, it did not change the memory blocks allotted for the array so the capacity is still at 12. // It also did not change the position of the pointer, leaving it at 3. //4. // We use "arr.get(0)" and get "3". // Print this 1 item that you just added. What is the result? Can you explain your result? // Array { length: 1, _capacity: 12, ptr: 3 } // There is only 1 item, but capacity and ptr still the same. // Even when we remove from the array, allotted memory blocks don't change it. //However, when we try to console.log(arr.get(0)) we receive NAN. This is because // 'tauhida' is a string but it is conflicting with how we defined the memory class // to be a new Float64Array which would only take numbers. // What is the purpose of the _resize() function in your Array class? // The resize function helps to allot more memory blocks to allow the array to be resized or changed. // It is given an argument of size which is determined by the array length and the Array.SIZE_RATIO. // The resize function first makes note of the old starting point of the array (oldPtr). // Then it will look in memory to see if it can allocate new space. It looks at the head in the memory. // Which is the first free spot in the memory and makes sure it has enough room to allocate the right amount of memory blocks. // If so, it will return the 'head' or start point for the array which is then set to the value of this.ptr. // From there it uses the memory function of copy to copy from the old starting point to the new starting point and copies the length of the array into the new memory blocks. // The final steps are freeing the memory based on where the old pointer was. // And then sets the capacity to the size of the new block of memory. // function urlIFY(string) { let array = string.split(' '); let answer = array.join('%20'); return answer; } // console.log(urlIFY('www.thinkful.com /tauh ida parv een')); // the big O of the above algorithm is O(n) linear. function filtering(array) { for (let i = 0; i < array.length; i++) { if (array[i] < 5) { array.splice(i, 1); i--; } } return array; } // console.log(filtering([-1, 1, 1, 2, 2, 3, 4, 5, 6, 7])); // the big O of the above algorithm is O(n^2) polynomial because we loop through // the array based on the length, and then again when we use the splice method //we iterate over the array every time it is called to copy the elements into each previous index. //alternate solution function filteringTwo(array) { const newArray = []; for (let i = 0; i < array.length; i++) { if (array[i] >= 5) { newArray.push(array[i]); } } return newArray; } // console.log(filteringTwo([-1, 1, 1, 2, 2, 3, 4, 5, 6, 7])); //this solution would be big O(n) linear based on the size of the array. It iterates over // the array once in a for loop. function maxSum(array) { let max = array[0]; let sum = array[0]; for (let i = 1; i < array.length; i++) { sum += array[i]; if (sum > max) { max = sum; } } return max; } // console.log(maxSum([4, 6, -3, 5, -2, 1])); // the big O of the above algorithm is O(n) linear. function mergeArrays(arr1, arr2) { for (let i = 0; i < arr2.length; i++) { arr1.push(arr2[i]); } arr1.sort((a, b) => a - b); return arr1; } // console.log(mergeArrays([1, 3, 6, 8, 11], [2, 3, 5, 8, 9, 10])); // the big O of the above algorithm is O(n^2) polynomial. function removeChar(string, chars) { for (let i = 0; i < chars.length; i++) { for (let j = 0; j < string.length; j++) { if (string[j] === chars[i]) { string = string.replace(chars[i], ''); } } } return string; } // console.log(removeChar('Battle of the Vowels: Hawaii vs. Grozny', 'aeiou')); // the big O of the above algorithm is O(n^2) polynomial. function products(arr) { let result = 1; let total = []; for (let i = 0; i < arr.length; i++) { result = result * arr[i] } for (let j = 0; j < arr.length; j++) { total.push(result / arr[j]) } return total; } // console.log(products([1, 3, 9, 4])); // the big O of the above algorithm is 0(n^2) polynomial. function twoD(arr) { let newarr = []; for (let x = 0; x < arr.length; x++) { newarr.push([...arr[x]]) } // x = row for (let x = 0; x < arr.length; x++) { // y = column for (let y = 0; y < arr[x].length; y++) { if (arr[x][y] === 0) { for (let z = 0; z < arr[x].length; z++) { newarr[x][z] = 0; } for (let m = 0; m < arr.length; m++) { newarr[m][y] = 0; } } } } return newarr; } // console.log(twoD( // [[1,0,1,1,0], // [0,1,1,1,0], // [1,1,1,1,1], // [1,0,1,1,1], // [1,1,1,1,1]] // )); // the big O of the above algorithm is o(n^4) polynomial. function rotation(str1, str2) { for (let i = 0; i < str1.length; i++) { let newstr = str2[i] + str2.slice(i + 1) + str2.slice(0, i); if (newstr === str1) { return true; } } return false; } // console.log(rotation('amazon', 'azonam')); // the big O of the above algorithm is 0(n) linear.
import React from "react"; import { storiesOf } from "@storybook/react"; import { action } from "@storybook/addon-actions"; import { withInfo } from "@storybook/addon-info"; import { withKnobs, select, number, text } from "@storybook/addon-knobs"; import { Row, Column, Panel } from "../../src/index"; import { colors, sizes } from "../../src/theme"; const stories = storiesOf("Panel", module); stories.addDecorator(withKnobs); stories.add( "Default", withInfo("Panel usage")(() => { let type = select("type", Object.keys(colors)); let margin = number("margin", undefined); let padding = number("padding", undefined); let heading = text("heading", undefined); return ( <Panel type={type} margin={margin} padding={padding} heading={heading}> <Row> <Column> <p>Panel text</p> </Column> </Row> </Panel> ); }) );
// JavaScript Document var params = {}; var currentRealTimeSenderId; var currentRealTimeMessageId; var startRealTimeChat; $(document).ready(function(e) { // var inFoSliderWidth = $('#infoSlider').width(); // var inFoSliderHeight = $('#infoSlider').height(); // $('#infoSlider').bjqs({ // animtype : 'slide', // showcontrols : false, // responsive : true, // width:inFoSliderWidth, // height:inFoSliderHeight, // showcontrols:true, // showmarkers : false, // usecaptions : false, // hoverpause : true // }); // $('.tool').tipTip({ // // // // }); /* Home Page Script Begins */ // $(".touchslider").touchSlider({ // // autoplay:true // // }); /*Login Script Begins */ var receiverId; var albumId; var friendId; var userAlbumId; var curentAlbumName; var friendAlbumClickTimes = 0; var userAlbumClickTimes = 0; var userVideoClickTimes = 0; var userFriendClickTimes = 0; var friendNotificationClickTimes = 0; var friendMessagesClickTimes = 0; var currentFriendMessageId; var currentfriendId; $('#pwd').keypress(function(event){ var keycode = (event.keyCode ? event.keyCode : event.which); if(keycode == '13'){ $('#loginForm').submit(); } }); /*Login Script Begins */ /**/ /**/ var icons = { header: "ui-icon-circle-arrow-e", activeHeader: "ui-icon-circle-arrow-s" }; $('#notificationsAccordion').accordion({ icons:icons }); /**/ /* Check Email Validity Script Begins */ var status = "true"; var checkemailajax ="false"; $('#email').blur(function(){ if($('#email').val().trim().length != 0){ status = "true"; $('#checkEmail').css("display", "inline"); $('#checkEmail').attr("src", "resources/images/282.gif"); var email = $('#email').val(); if(!validateEmail(email)){ $('#checkEmail').attr("src", "resources/images/wrong.png"); //status ="falseemailregex"; } else{ $.ajax({ url:'UserInfo/checkEmail', type:'post', data:{ email:email } }).success(function(msg){ if (msg == false){ $('#checkEmail').attr("src", "resources/images/correct.gif"); checkemailajax ="true"; } else{ $('#checkEmail').attr("src", "resources/images/wrong.png"); status = "falseemail"; checkemailajax ="true"; } }); } } }); /* Check Email Validity Script Ends */ /**/ $('#repeatPassword').blur(function(){ var password = $('#password').val(); var conpassword = $('#repeatPassword').val(); $('#checkPassword').css("display","inline"); if(conpassword.length != 0){ if(password == conpassword ){ $('#checkPassword').attr("src","images/correct.gif"); } else{ $('#checkPassword').attr("src","images/wrong.png"); //$('#checkPassword').css("display","inline"); } } }); /**/ /*Birthday DatePicker Script Begins */ $('#birthday').datepicker({ changeMonth: true, changeYear: true, showOn: "button", buttonImage: "images/calendar.gif", buttonImageOnly: true, yearRange: "1980:2012", showAnim: "explode", duration: "normal", dateFormat: "dd-mm-yy", }); $('#birthday').focus(function(){ $('#birthday').datepicker({ changeMonth: true, changeYear: true, showOn: "button", buttonImage: "images/calendar.gif", buttonImageOnly: true }); }); $('#birthday').click(function(){ $('#birthday').datepicker({ changeMonth: true, changeYear: true, showOn: "button", buttonImage: "images/calendar.gif", buttonImageOnly: true }); }); /*Birthday DatePicker Script Ends*/ /* Sign Up Button Script Begins */ $('#signUpButton').click(function(e){ e.preventDefault(); var firstName; var lastName; var email; var password; var conpassword; var gender; var birthday; if(status != 'falseemail'){ status = "true"; } firstName = $('#firstName').val(); lastName = $('#lastName').val(); email = $('#email').val(); password = $('#password').val(); conpassword = $('#repeatPassword').val(); gender = $('#gender').val(); birthday = $('#birthday').val(); /*alert(firstName+lastName+email+password+gender+birthday);*/ $('#signup').find('input[type="text"]').each(function(){ if($(this).val().trim() == ""){ status = "falsem"; //alert(status); } }); $('#signup').find('input[type="password"]').each(function(){ if($(this).val().trim() == ""){ status = "falsem"; //alert("pass"); } }); if(status != 'falsem'){ if(password != conpassword){ status = "falsep"; } } if($('#email').val().trim().length != 0){ if(!validateEmail(email)){ $('#checkEmail').attr("src", "images/wrong.png"); status ="falseemailregex"; } } /*$('#signup').find('input[type="password"]').each(function(){ if($(this).val().trim().length < 7){ status = "falsel"; //alert("pass"); } });*/ if(status == 'true' && checkemailajax =='false'){ var formData = $('#signUpForm').serialize(); $('#dialog').html('Signing Up Please Wait').dialog({ modal:true, draggable:false, resizable:false, title:"Please Wait ......", show: { effect: "fold", duration: 500 }, hide: { effect: "fold", duration: 1000 }, buttons:{ } }); $.ajax({ url:'UserInfo/addUser', type:'post', data:formData }).success(function(msg){ var email = $('#email').val(); $('#signup').find('input[type="password"]').each(function(){ $(this).val(""); }); $('#signup').find('input[type="text"]').each(function(){ $(this).val(""); }); $('#signup').find('input[type="email"]').each(function(){ $(this).val(""); }); $('#checkEmail').css("display", "none"); $('#checkPassword').css("display", "none"); $.ajax({ url:'SendEmail', type:'post', data:{ recipient:email, subject:'Hii', messageBody:'Hii' } }); $('#dialog').html('Please Check Ur Email To Activate Your Account').dialog({ modal:true, buttons: [ { text: "Ok", click: function() { $(this).dialog("close"); $('#emailId').focus(); $('#emailId').css("background-color","yellow"); } } ], draggable:false , resizable:false , title:"Thanx A Ton :) " , show: { effect: "fold", duration: 1000 }, hide: { effect: "fold", duration: 1000 } }); }).error(function(){ alert('error'); }); } else if(status == "falsem"){ showNotification('Oops ! Some Fields Are Missing :('); } else if(status == "falseemail"){ showNotification('That Email Has Already Been Registered :('); } else if( status == "falsep"){ showNotification('Oops ! Password Didn\'t match :('); } else if(status == 'falsel'){ showNotification('Password lenght must be more than 7 characters'); } else if(status == "falseemailregex"){ showNotification("Please Enter Valid Email Address"); } }); /* Sign Up Button Script Ends */ /* Home Page Script Ends */ /*Log Out*/ /**/ /* Adding School Script Begins*/ $('#addSchoolButton').click(function(){ $('#addSchool').dialog({ modal:true, title:'Add New School', resizable:false, height:'250', width:'400', show: { effect: "drop", duration: 1000 }, hide: { effect: "drop", duration: 1000 }, draggable:false, buttons:[ { text:'Add', click:function(){ $('#addSchool').dialog("close"); $('#dialog').html("Adding School Please Wait .....").dialog({ modal:true, title:'Please Wait ...', show: { effect: "fade", duration: 500 }, hide: { effect: "fade", duration: 1000 }, buttons:{ } }); var userId = $('#userId').val(); var schoolName = $('#schoolName').val(); var place = $('#place').val(); var yearSchoolAttended = $('#yearSchoolAttended').val(); $.ajax({ url:'AddSchool', type:'post', data:{ userId:userId, schoolName:schoolName, place:place, yearSchoolAttended:yearSchoolAttended } }).success(function(){ $('#dialog').dialog("close"); }).error(function(){ alert("error"); }); }, },{ text:'Cancel', click:function(){ $(this).dialog("close"); } } ] }); /* Adding School Script Ends*/ }).next().button({ text: 'false', icons: { primary: "ui-icon-gear" } }); /*Adding College Script Begins*/ $('#addCollegeButton').click(function(){ $('#addCollege').dialog({ modal:true, title:'Add New College', height:'250', width:'400', resizable:false, draggable:false, buttons:[{ text:'Add', click:function(){ $('#addCollege').dialog("close"); $('#dialog').html("Adding College Please Wait .....").dialog({ modal:true, title:'Please Wait ...', show: { effect: "fade", duration: 500 }, hide: { effect: "fade", duration: 1000 }, buttons:{ } }); var userId = $('#userId').val(); var collegeName = $('#collegeName').val(); var stream = $('#stream').val(); var yearCollegeAttended = $('#yearCollegeAttended').val(); $.ajax({ url:'AddCollege', type:'post', data:{ userId:userId, collegeName:collegeName, stream:stream, yearCollegeAttended:yearCollegeAttended } }).success(function(){ $('#dialog').dialog("close"); $('#addCollege').dialog("close"); }).error(function(){ alert("error"); }); }, },{ text:'Cancel', click:function(){ $(this).dialog("close"); } } ] }); }); /*Adding College Script Ends*/ /*Accordion Script Ends*/ $('.logo').click(function(){ $('#dialog').html('Welcome To Slambook').dialog({ modal:true, resizable:false, draggable:false, title:'Welcome !', show: { effect: "fold", duration: 1000 }, hide: { effect: "fold", duration: 1000 }, buttons: { "Close": function() { $(this).dialog("close"); } } }); }); if(($.browser.mozilla) || ($.browser.opera)){ $('#magazine').booklet({ width:'84%', height:'580', easing:'easeInCubic', shadows: true, hoverWidth: 25, hash: true, arrows:true, cursor: "pointer", pageNumbers:false, keyboard:true, start: function(event, data) { $('#pageFlipSound').get(0).play(); } }); $('fieldset').css('height', '200px') } else{ var counter = 0; $('#magazine').booklet({ width:'84%', height:'580', easing:'easeInCubic', shadows: true, hoverWidth:25, hash: true, arrows:true, cursor: "pointer", pageNumbers:false, keyboard:false, closed: false, covers:false, autoCenter: true, create: function(event, data) { if(data.index == 0){ // $('#magazine').booklet("option", {arrows: false}); // $('#magazine').css('left','8%'); // $('#magazine').booklet("option", {hoverWidth:250}); //$('.b-next').css('display','none'); } else{ // $('#magazine').booklet("option", {arrows: true}); // $('#magazine').css('left','0%'); document.title = "SlamBook - "+data.pages[0].getAttribute("alt"); // $('#magazine').booklet("option", {hoverWidth:25}); //$('.b-next').css('display','inline'); } }, start: function(event, data) { $('#pageFlipSound').get(0).play(); document.title = "SlamBook - "+data.pages[0].getAttribute("alt"); if(data.index != 0){ } else{ //$('#magazine').css('box-shadow',''); } }, change: function(event, data) { if(data.index == 0){ // $('#magazine').booklet("option", {arrows: false}); //$('#magazine').css('left','8%'); //$('.b-next').css('display','none'); document.title = "Slambook - Home"; //$('#magazine').css('box-shadow','0'); // $('#magazine').booklet("option", {hoverWidth:250}); } else{ //$('.b-next').css('display','inline'); // $('#magazine').booklet("option", {arrows: true}); //$('#magazine').css('left','0'); //$('#magazine').css('box-shadow','0 0 6px 6px #FFF'); document.title = "SlamBook - "+data.pages[0].getAttribute("alt"); //$('#magazine').booklet("option", {hoverWidth:25}); } } }); } $('#uploadImagesToAlbumForm').click(function(){ $('#editAlbumMenu').slideUp(500); $('#selectUserAlbums').dialog({ width:'450', height:'150', modal:true, title:'Add Images To Album', draggable:'false', resizable:'false', show: { effect: "drop", duration: 1000 }, hide: { effect: "drop", duration: 1000 } }); }); $('#loadMoreUserAlbums').live('click',function(){ var userId = $('#userId').val(); userAlbumClickTimes++; $('#loadMoreUserAlbums').text("Loading ...."); $.ajax({ url:'album/LoadMoreUserAlbums/'+userId+"/"+userAlbumClickTimes, type:'post', data:{ userId:userId, clickTimes:userAlbumClickTimes } }).success(function(data){ $('#userAlbums').append(data); $('#loadMoreUserAlbums').text("Load More..."); }); }); $('#loadMoreFriendAlbums').live('click',function(){ friendAlbumClickTimes++; $('#loadMoreFriendAlbums').text("Loading ...."); $.ajax({ url:'LoadMoreFriendsAlbums', type:'post', data:{ userId:currentfriendId, clickTimes:friendAlbumClickTimes } }).success(function(data){ $('.friendsAlbums').append(data); $('#loadMoreFriendAlbums').text("Load More..."); }); }); $('#loadMoreFriendsNotifications').live('click',function(){ var userId = $('#userId').val(); friendNotificationClickTimes++; $('#loadMoreFriendsNotifications').text("Loading ...."); $.ajax({ url:'LoadMoreFriendsNewsFeed', type:'post', data:{ userId:userId, clickTimes:friendNotificationClickTimes } }).success(function(data){ $('.friendsNotifications').append(data); $('#loadMoreFriendsNotifications').text("Load More..."); }); }); $('#loadMoreUserVideos').live('click',function(){ var userId = $('#userId').val(); userVideoClickTimes++; $('#loadMoreUserVideos').text("Loading ...."); $.ajax({ url:'Videos/LoadMoreUserVideos/'+userId+"/"+userVideoClickTimes, type:'post', data:{ userId:userId, clickTimes:userVideoClickTimes } }).success(function(data){ $('#userVideos').append(data); $('#loadMoreUserVideos').text("Load More..."); }); }); $('#loadMoreFriendsVideos').live('click',function(){ userFriendClickTimes++; $('#loadMoreFriendsVideos').text("Loading ...."); $.ajax({ url:'LoadMoreFriendsVideos', type:'post', data:{ userId:currentfriendId, clickTimes:userFriendClickTimes } }).success(function(data){ $('.friendsVideos').append(data); if(data != null){ $('#loadMoreFriendsVideos').text("Load More..."); } else{ $('#loadMoreFriendsVideos').text("No More..."); } }); }); $(".getImages").live({ mouseenter: function() { $(this).find('span[class="deleteUserAlbum"]').show(500); }, mouseleave: function() { $(this).find('span[class="deleteUserAlbum"]').hide(500); } } ); $(".videosDiv").live({ mouseenter: function() { $(this).find('span[class="deleteUserVideo"]').show(500); }, mouseleave: function() { $(this).find('span[class="deleteUserVideo"]').hide(500); } } ); $(".deleteUserAlbum").live({ mouseenter: function() { $(this).parent().removeClass('getImages'); }, mouseleave: function() { $(this).parent().addClass('getImages'); } } ); $(".imagesDiv").live({ mouseenter: function() { //$(this).find('span[class="deleteUserAlbumImage"]').show(100); }, mouseleave: function() { //$(this).find('span[class="deleteUserAlbumImage"]').hide(100); } } ); $('.deleteUserAlbumImage').live('click',function(){ $(this).hide(500); var imageId = $(this).attr("imageId"); var albumId = $(this).attr("albumId"); $(this).parent().addClass('currentAlbumImageToBeDeleted'); $('#dialog').html("Are You Sure You Want To Delete This Image ?").dialog({ width:'auto', modal:true, title:'Confirmation ..', show: { effect: "drop", duration: 500 }, hide: { effect: "drop", duration: 500 }, buttons:[ { text: "Yes", click: function() { $('#dialog').dialog('close'); $('#dialog').html('Deleting Image Please Wait ..').dialog({ modal:true, width:'auto', title:'Please Wait', draggable:false, show: { effect: "drop", duration: 300 }, hide: { effect: "drop", duration: 100 }, resizable:false, buttons:{} }); $.ajax({ url:"DeleteUserAlbumImage", type:'post', data:{ imageId:imageId, albumId:albumId } }).success(function(data){ $('#dialog').dialog('close'); $('#dialog').html('Image Deleted Successfully :(').dialog({ modal:true, width:'auto', title:'Success :)', draggable:false, show: { effect: "drop", duration: 300 }, hide: { effect: "drop", duration: 100 }, resizable:false, buttons:[{ text:"Ok", click:function(){ $('#dialog').dialog('close'); $('div.currentAlbumImageToBeDeleted').hide(1000); } }] }); }).error(function(data){ alert("OE"+data); }); } }, { text: "No", click: function() { $(this).dialog('close'); } } ] }); }); $('.deleteUserVideo').live('click',function(){ $(this).hide(500); var videoId = $(this).attr("videoId"); $(this).parent().addClass('currentVideoToBeDeleted'); $('#dialog').html("Are You Sure You Want To Delete This Video ?").dialog({ width:'auto', modal:true, title:'Confirmation ..', show: { effect: "drop", duration: 500 }, hide: { effect: "drop", duration: 500 }, buttons:[ { text: "Yes", click: function() { $('#dialog').dialog('close'); $('#dialog').html('Deleting Video Please Wait ..').dialog({ modal:true, width:'auto', title:'Please Wait', draggable:false, show: { effect: "drop", duration: 300 }, hide: { effect: "drop", duration: 100 }, resizable:false, buttons:{} }); $.ajax({ url:"DeleteUserVideo", type:'post', data:{ videoId:videoId } }).success(function(data){ $('#dialog').dialog('close'); $('#dialog').html('Video Deleted Successfully :(').dialog({ modal:true, width:'auto', title:'Success :)', draggable:false, show: { effect: "drop", duration: 300 }, hide: { effect: "drop", duration: 100 }, resizable:false, buttons:[{ text:"Ok", click:function(){ $('#dialog').dialog('close'); $('div.currentVideoToBeDeleted').hide(2000); } }] }); }).error(function(){ alert("OE"); }); } }, { text: "No", click: function() { $(this).dialog('close'); } } ] }); }); $('.deleteUserAlbum').live('click',function(){ $(this).hide(500); var albumId = $(this).attr("albumId"); $(this).parent().addClass('currentAlbumToBeDeleted'); $('#dialog').html("Are You Sure You Want To Delete This Album ?").dialog({ width:'auto', modal:true, title:'Confirmation ..', show: { effect: "drop", duration: 500 }, hide: { effect: "drop", duration: 500 }, buttons:[ { text: "Yes", click: function() { $('#dialog').dialog('close'); $('#dialog').html('Deleting Album Please Wait ..').dialog({ modal:true, width:'auto', title:'Please Wait', draggable:false, show: { effect: "drop", duration: 300 }, hide: { effect: "drop", duration: 100 }, resizable:false, buttons:{} }); $.ajax({ url:"DeleteUserAlbum", type:'post', data:{ albumId:albumId } }).success(function(data){ $('#dialog').dialog('close'); $('#dialog').html('Album Deleted Successfully :(').dialog({ modal:true, width:'auto', title:'Success :)', draggable:false, show: { effect: "drop", duration: 300 }, hide: { effect: "drop", duration: 100 }, resizable:false, buttons:[{ text:"Ok", click:function(){ $('#dialog').dialog('close'); $('div.currentAlbumToBeDeleted').hide(1000); } }] }); }).error(function(){ alert("OE"); }); } }, { text: "No", click: function() { $(this).dialog('close'); } } ] }); }); $('.getImages').live('click',function(e) { $('#dialog').html('<div><img src="resources/images/143.gif" style="margin-left: auto; margin-right: auto;text-align:center;width:100%;"/></div>Please Wait While The Images Loads').dialog({ width:'auto', title:'Please Wait ....', show: { effect: "drop", duration: 300 }, hide: { effect: "drop", duration: 100 }, buttons:{ } }); albumId = $(this).attr("albumId"); var userId = $("#userId").val(); $.ajax({ url:"Images/getImages/"+albumId+"/"+userId, type:'post', }).success(function(data){ $('#dialog').dialog('close'); $('#images_div').html('<div style="position:absolute; bottom:0px; width: 100%; text-align: center"><button style="padding:1%" class="closeImagesDiv">Close</button></div>'); $('#images_div').prepend(data).slideDown(1000); }); }); $('.closeImagesDiv').live('click',function(){ $('#images_div').slideUp(1000); }); $('.closefriendsalbumImagesDiv').live('click',function(){ $('#images_div_friendsalbumImages').slideUp(1000); }) $('.currentViewAlbumHide').live('click',function(){ $('#images_div').slideUp(1000,function(){ $('#images_div').html(""); }); }); $('#account').click(function(e) { $('#dialog').html('Are You Sure You want to Log Out !').dialog({ modal:true, width:'auto', title:'Confirm Log Out', draggable:'false', resizable:'false', show: { effect: "fade", duration: 500 }, hide: { effect: "fade", duration: 1000 }, buttons: [ { text: "Yes", click: function() { $('#dialog').dialog('close'); $('#dialog').html('Logging Off Please Wait ..').dialog({ modal:true, width:'auto', title:'Confirm Log Out', draggable:'false', resizable:'false' }); $.ajax({ url:'logOutUser', type:'post' }).success(function(){ location.href="http://localhost:8084/SlamBook/logOutInfo.jsp"; }); } }, { text: "Cancel", click: function() { $(this).dialog('close'); } } ] }); }); $('#friends').click(function(e) { $('#friends_div').slideDown(1000); }); $('.closeFriendsDiv').click(function(){ $('#friends_div').slideUp(1000); }); var i = 0; $(".fancybox").fancybox({ padding : 0, title:'', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, beforeLoad :function(){ if(i == 0){ //$('#magazine').booklet("option", {keyboard: false}); } i++; }, afterClose:function(){ i = 0; //$('#magazine').booklet("option", {keyboard: true}); }, helpers : { thumbs : { width : 75, height : 75 }, buttons : { tpl: '<div id="fancybox-buttons"><ul style="width:132px"><li><a class="btnPrev" title="Previous" href="javascript:;"></a></li><li><a class="btnPlay" title="Start slideshow" href="javascript:;"></a></li><li><a class="btnNext" title="Next" href="javascript:;"></a></li><li><a class="btnClose" title="Close" href="javascript:jQuery.fancybox.close();"></a></li></ul></div>', type : 'inside' }, overlay : { css : { 'background' : 'rgba(0,0,0,0.85)' } } }, afterLoad : function() { this.title = 'Image ' + (this.index + 1) + ' of ' + this.group.length + (this.title ? ' - ' + this.title : ''); } }); $(".videofancybox").fancybox({ padding : 0, title:'', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, helpers : { overlay : { css : { 'background' : 'rgba(0,0,0,0.85)' } } }, }); $(".imageCommentsfancybox").fancybox({ padding : 0, title:'', openEffect : 'elastic', openSpeed : 150, showNavArrows: false, closeEffect : 'elastic', closeSpeed : 150, type:'iframe', autoSize:true, onComplete:function(){ alert('H'); $('.fancybox-nav').css('display','none!important'); }, helpers : { overlay : { css : { 'background' : 'rgba(0,0,0,0.85)' } } } }); $(".imageLikesfancybox").fancybox({ padding : 0, width:250, height:300, title:'', openEffect : 'elastic', openSpeed : 150, showNavArrows: false, closeEffect : 'elastic', closeSpeed : 150, type:'iframe', onComplete:function(){ alert('H'); $('.fancybox-nav').css('display','none!important'); }, helpers : { overlay : { css : { 'background' : 'rgba(0,0,0,0.85)' } } } }); // // $(window).resize(function(){ // // if(($.browser.webkit)){ // // alert("Hii"); // $('#magazine').booklet({ // width:'88%', // height:'100%', // easing:'easeInCubic', // // shadows: true, // hoverWidth: 100, // hash: true, // cursor: "pointer", // pageNumbers:false, // arrows:true // }); // // } // // // }); // if(($.browser.mozilla) || ($.browser.opera)){ // // $(window).resize(function() { // // // // if(($.browser.opera) || ($.browser.mozilla)){ // // $('#magazine').booklet({ // width:'88%', // height:'100%', // easing:'easeInCubic', // // shadows: true, // hoverWidth: 100, // hash: true, // cursor: "pointer", // pageNumbers:false, // arrows:true // }); // /*alert('ggh'); //*/ } // else{ // // $('#magazine').booklet({ // width:'88%', // height:'100%', // easing:'easeInCubic', // // shadows: true, // hoverWidth: 100, // hash: true, // cursor: "pointer", // pageNumbers:false, // arrows:true // }); // // // } // // }); // // } /*editprofile.jsp script begins*/ $('#showEditProfileMenu').click(function(){ $('#editProfileMenu').slideToggle(1000); }); $('#showEditAlbumMenu').click(function(){ $('#editAlbumMenu').slideToggle(1000); }); $('#albumDate').datepicker({ changeMonth: true, changeYear: true, showOn: "button", buttonImage: "/resources/images/calendar.gif", buttonImageOnly: true, yearRange: "1980:2012", duration: "normal", dateFormat: "dd-mm-yy", }); /*Delete Album Script Begins*/ $('.albumsDiv').draggable({ revert: "invalid", scroll: true, grid: [ 100,100 ], scrollSensitivity: 100 , scrollspeed:100 }); $( "#deleteAlbumsDroppable" ).droppable({ activeClass: "ui-state-hover", hoverClass: "ui-state-active", drop: function( event, ui ) { alert('dropped'); } }); /**/ $('#editAlbumButtonClick').click(function(){ $('#editAlbumMenu').slideToggle(1000); $('#addAlbumsDiv').dialog({ width:'auto', modal:true, title:'Create New Album', draggable:'false', resizable:'false', show: { effect: "drop", duration: 1000 }, hide: { effect: "drop", duration: 1000 }, buttons: { "Create Album": function() { var albumName; var albumSummary; var albumDate; albumName = $('#albumName').val(); albumSummary = $('#albumSummary').val(); albumDate = $('#albumDate').val(); $.ajax({ url:'album/addAlbum', type:'post', data:{ albumName:albumName, albumSummary:albumSummary, albumDate:albumDate } }).success(function(msg){ userAlbumId = msg; $('#albumImagesUploadId').attr('value', userAlbumId); //$('#imagesalbumId').attr('value', msg); $('#addAlbumsDiv').dialog("close"); $('#uploadImagesForm').dialog({ width:'450', height:'450', modal:true, title:'Add Images To Album', draggable:'false', resizable:'false', show: { effect: "drop", duration: 1000 }, hide: { effect: "drop", duration: 1000 }, buttons:{ "Add Images":function(){ alert("Hi"); } } }); }); } } }); }); $('#selectUserAlbumsId').change(function(){ var albumId = $('#selectUserAlbumsId').val(); $('#albumImagesUploadId').attr('value', albumId); $('#uploadImagesForm').dialog({ width:'450', height:'380', modal:true, title:'Add Images To Album', draggable:'false', resizable:'false', show: { effect: "drop", duration: 1000 }, hide: { effect: "drop", duration: 1000 } }); }); /*******************Upload Album Image Script Begins *********************/ // var input = document.getElementById("images"), // formdata = false; // // // // if (window.FormData) { // // } // // input.addEventListener("change", function (evt) { // formdata = new FormData(); // $('#addImagesDiv').dialog("close"); // $('#dialog').html('<img src="images/142.gif" style="margin-left: auto; margin-right: auto"/></br>Changing Profile Pic Please Wait').dialog({ // // modal:true, // width:'auto', // title:'Please Wait' // // }); // //document.getElementById("response").innerHTML = "Uploading . . ." // var i = 0, len = this.files.length, img, reader, file; // // for ( ; i < len; i++ ) { // file = this.files[i]; // // if (!!file.type.match(/image.*/)) { // if ( window.FileReader ) { // reader = new FileReader(); // reader.onloadend = function (e) { // //showUploadedItem(e.target.result, file.fileName); // }; // reader.readAsDataURL(file); // } // if (formdata) { // formdata.append("images", file); // } // } // } // // if (formdata) { // $.ajax({ // url: "Upload", // type: "POST", // data: formdata, // processData: false, // contentType:false, // success: function (res) { // //document.getElementById("response").innerHTML = res; // //alert(res); //// var id=$('#userId').val(); //// $.ajax({ //// //// url:'users/'+id+'/profilepic/'+res+'.jpg', //// type:'post', //// success:function(){ //// //// $('#profilePic').attr('src','users/'+id+'/profilepic/'+res+'.jpg'); //// $('#dialog').dialog("close"); //// //// } //// //// }); //// //// $('#profilePic').attr('src','users/'+id+'/profilepic/'+res+'.jpg'); //// $('#dialog').dialog("close"); // alert("Success"+res); // }, // error:function(){ // // //document.getElementById("response").innerHTML = "Error"; // } // }); // } // }, false); /*****************Upload Album Image Script Ends ***********************/ /*Send Message Scrpit Begins*/ $('#messageStreamButton').click(function(){ $('#InsidefriendsConversationMessages').html(""); var userId = $('#userId').val(); $('#dialog').html("Loading Messages Plesae Wait .....").dialog({ modal:true, width:'auto', title:'Please Wait ...', show: { effect: "fade", duration: 500 }, hide: { effect: "fade", duration: 500 }, buttons:{ } }); $.ajax({ url:'message/getTop10Messages', type:'post', data:{userId:userId} }).success(function(data){ $('#dialog').dialog("close"); $('#InsidefriendsConversationMessages').html(data) $('#friendsConversationMessages').slideToggle(1000); }); }); $('.closeFriendsMessages').click(function(){ $('#friendsConversationMessages').slideToggle(1000); }); $('.viewMessageConversation').live('click',function(){ $('#InsidefriendsConversationMessagesThread').html(""); $('#dialog').html("Loading Messages Plesae Wait .....").dialog({ modal:true, width:'auto', title:'Please Wait ...', show: { effect: "fade", duration: 500 }, hide: { effect: "fade", duration: 500 }, buttons:{ } }); receiverId = $(this).attr('senderId'); var senderId = $(this).attr('senderId'); currentFriendMessageId = $(this).attr('senderId'); currentRealTimeSenderId = senderId; friendMessagesClickTimes = 0; $.ajax({ url:'message/getMessages', type:'post', data:{senderId:senderId,clickTimes:0} }).success(function(data){ $('#dialog').dialog('close'); $('#InsidefriendsConversationMessagesThread').append(data); $('#friendsConversationMessagesThread').slideToggle(1000); $('#InsidefriendsConversationMessagesThread').find($('.messageBox')).each(function(){ currentRealTimeMessageId = $(this).attr("messageId"); }); startRealTimeChat = setInterval(getRealTimeMessageId,5000,currentRealTimeSenderId,currentRealTimeMessageId); }); }); $('.closeFriendsConversationMessagesThread').click(function(){ $('#friendsConversationMessagesThread').slideToggle(1000); clearInterval(startRealTimeChat); }); $('.loadMoreFriendsMessages').live('click',function(){ friendMessagesClickTimes++; $.ajax({ url:'message/getMessages', type:'post', data:{senderId:currentFriendMessageId,clickTimes:friendMessagesClickTimes} }).success(function(data){ $('#InsidefriendsConversationMessagesThread').prepend(data); }); }); $('.replyToMessageTextarea').live('keyup',function(e){ if(e.keyCode == 13){ $('.replyToMessageTextarea').attr('disabled','disabled'); var senderId = $('#userId').val(); var message = $(this).val(); $.ajax({ url:'sendMessage', type:'post', data:{ message:message, senderId:senderId, receiverId:receiverId } }).success(function(msg){ $('.replyToMessageTextarea').removeAttr('disabled'); $('.replyToMessageTextarea').val(); $('#InsidefriendsConversationMessagesThread').append('<div style="width:100%;display: block;float:left;margin-top: 1%; padding-bottom: 1%" ><div style="float:right;width:60px; height: 60px;margin-right: 3%;"> <img style="width:inherit;height:inherit" src="users/'+senderId+'/profilepic/thumbs/'+$('#currentProfilePic').val()+'.jpg"/> </div> <div class="bubbleright"><p style="position:relative;left:6%">'+$('#currentUserName').val()+'&nbsp;said:'+message+'</p></div></div>'); }).error(function(msg){ alert('error'+msg); }); } }); $('.sendEmail').click(function(){ var senderId = $('#userId').val(); var receiverId = $(this).attr("receiverId"); var receiverName = $(this).attr('receiverName'); $('#sendMessageDiv').dialog({ modal:true, title:'Send Message To '+receiverName, width:'auto', show: { effect: "drop", duration: 1000 }, hide: { effect: "drop", duration: 1000 }, buttons:{ "Send Message":function(){ var message = $('#messageText').val(); $.ajax({ url:'message/addMessage', type:'post', data:{ message:message, senderId:senderId, userReceiverId:receiverId } }).success(function(msg){ $('#sendMessageDiv').dialog("close"); showHomeNotification("Message Sent Successfully Thanks !") }).error(function(msg){ alert('error'+msg); }); } } }); }); /*Send Message Scrpit Ends*/ /**/ $('.acceptRequestPreview').click(function(){ var friendId = $(this).attr('friendId'); var userId = $('#userId').val(); //alert(friendId+userId); $.ajax({ url:'PreviewAnswers', type:'post', data:{ userId:userId, friendId:friendId } }).success(function(data){ $('#previewRequestSlidesDiv').html(data).slideDown(1000); }); }); $('#cancelRequest').live('click',function(){ var friendId = $(this).attr('friendId'); var userId = $('#userId').val(); //alert(friendId+userId); $.ajax({ url:'CancelRequest', type:'post', data:{ userId:userId, friendId:friendId } }).success(function(data){ $('#previewRequestSlidesDiv').slideUp(2000); }); }); /**/ $('#showEditVideoMenu').click(function(){ $('#editVideoMenu').slideToggle(1000); }); $('#editVideoButtonClick').click(function(){ $('#editVideoMenu').slideToggle(1000); $('#addVideosDiv').dialog({ width:'auto', modal:true, show: { effect: "drop", duration: 1000 }, hide: { effect: "drop", duration: 1000 }, title:'Add New Video', draggable:'false', resizable:'false', buttons:{ "Add Video":function(){ var videoUrl = $('#videoUrl').val(); var videoDescription = $('#videoDescription').val(); $.ajax({ url:'Videos/addVideo', type:'post', data:{ videoUrl:videoUrl, videoDescription:videoDescription } }).success(function(msg){ var userId = $('#userId').val(); $.ajax({ url:'Videos/LoadMoreUserVideos/'+userId+"/"+0, type:'post', data:{ userId:userId, clickTimes:'0' } }).success(function(data){ $('#userVideos').html(data); }); $('#addVideosDiv').dialog('close'); $('#dialog').html('Your Video has been added to the playlist Thanx :)').dialog({ width:'40%', modal:true, title:'Video Added', draggable:'false', resizable:'false', show: { effect: "fade", duration: 500 }, hide: { effect: "fade", duration: 1000 }, buttons:{ "Ok":function(){ $('#dialog').dialog('close'); } } }); }); } } }); }); $('.changeVideo').live('click',function(){ $('.videoPlayer').attr('src',$(this).attr('videoUrl')); }); $('#changeProfilePicButton').click(function(){ $('#editProfileMenu').slideUp('2000'); $('#changeProfilePicDiv').dialog({ modal:true, width:400, title:'Change Profile Image', show: { effect: "drop", duration: 1000 }, hide: { effect: "drop", duration: 1000 } }); }); $('#editProfileButtonClick').click(function(){ $('#editProfileMenu').slideUp('2000'); $('#editProfileSlideDiv').slideDown(2000); $.ajax({ url:'UserInfo/editUser', type:'post' }).success(function(data){ $('#editProfileSlideDiv').html(data); $('#editbirthday').datepicker({ changeMonth: true, changeYear: true, showOn: "button", buttonImage: "images/calendar.gif", buttonImageOnly: true, yearRange: "1980:2012", duration: "normal", dateFormat: "dd-mm-yy", }); }); }); $('.viewProfileLink').click(function(){ var friendId = $(this).attr('friendId'); $.ajax({ url:'ViewProfile', type:'post', data:{ friendId:friendId } }).success(function(data){ $('#viewProfileSlidesDiv').html(data).slideDown(2000); }); }); $('#editProfileButton').live('click',function(){ var tagline = $('#edittagline').val(); var introduction = $('#editintroduction').val(); var braggingRights = $('#editbraggingRights').val(); var placesLived = $('#editplacesLived').val(); var lookingFor = $('#editlookingFor').val(); var email = $('#editemail').val(); var gender = $('#editgender').val(); var birthday = $('#editbirthday').val(); var school = $('#editschool').val(); var college = $('#editcollege').val(); var relationshipStatus = $('#editrelationshipStatus').val(); var occupation = $('#editoccupation').val(); var website = $('#editwebsite').val(); $('#dialog').html("Updating Profile Please Wait .....").dialog({ modal:true, title:'Please Wait ...', show: { effect: "fade", duration: 500 }, hide: { effect: "fade", duration: 1000 }, buttons:{ } }); $.ajax({ url:'UserInfo/updateUser', type:'post', data:{ tagline:tagline, introduction:introduction, braggingRights:braggingRights, placesLived:placesLived, lookingFor:lookingFor, email:email, gender:gender, birthday:birthday, school:school, college:college, relationshipStatus:relationshipStatus, occupation:occupation, website:website } }).success(function(data){ $('.profileIntroTagline').html(tagline); $('.profileIntroIntroduction').html(introduction); $('.profileIntroBraggingRights').html(braggingRights); $('.profileIntroPlacesLived').html(placesLived); $('.profileIntroLookingFor').html(lookingFor); $('.profileIntroEmail').html(email); $('.profileIntroGender').html(gender); $('.profileIntroBirthday').html(birthday); $('.profileIntroSchool').html(school); $('.profileIntroCollege').html(college); $('.profileIntroRelationshipStatus').html(relationshipStatus); $('.profileIntroOccupation').html(occupation); $('.profileIntroWebsite').html(website); $('#dialog').html('Your Profile Has Updated !! ').dialog({ modal:true, show: { effect: "fade", duration: 500 }, hide: { effect: "fade", duration: 1000 }, buttons: [ { text: "Ok", click: function() { $(this).dialog("close"); $('#editProfileSlideDiv').html("").slideUp(1000); } } ], draggable:false , resizable:false , title:"Profile Updated" }); }).error(function(){ alert("Error"); }); }); /*Search Friend Script Begins*/ $('.search').focus(function(){ //$('#selectSearchOption').slideDown(500); var friendName = $('.search').val(); if(friendName.length > 3){ $('#searchFriends').css('display','block'); } }); $('.search').blur(function(){ //$('#selectSearchOption').slideUp(1000); //$('#searchFriends').css('display','none'); }); $('.search').keyup(function(){ var friendName = $('.search').val(); if(friendName.length > 3){ $.ajax({ url:'Friends/searchFriendsByName/'+friendName, type:'post', }).success(function(data){ $('#searchFriends').html(data).css('display','block'); }); } else{ $('#searchFriends').css('display','none'); } }); /*Search Friend Script Ends*/ /*editprofile.jsp script ends*/ /**/ $('.addToSlambookButton').live('click',function(){ $('#dialog').html('<div style="width:100%;text-align:center"><img src="resources/images/143.gif" style="margin-left: auto; margin-right: auto"/></div>Please Wait...').dialog({ width:'auto', show: { effect: "fade", duration: 500 }, hide: { effect: "fade", duration: 1000 }, buttons:{ } }); $('#searchFriends').hide(100); receiverId = $(this).attr('userId'); $.ajax({ url:'Friends/addFriend', type:'get' }).success(function(data){ $('#addToSlambookSlidesDiv').html(data).slideDown(2000); $('#dialog').dialog('close'); }); }); $('#addToSlambookButtonConfirm').live('click',function(){ $('#dialog').html('<img src="images/143.gif" style="margin-left: auto; margin-right: auto"/></br>Adding To Slambook Please Wait ..').dialog({ modal:true, width:"auto", title:'Please Wait', show: { effect: "fade", duration: 500 }, hide: { effect: "fade", duration: 1000 }, buttons:{ } }); var senderId = $('#userId').val(); var ans1 = $('#ans1').val(); var ans2 = $('#ans2').val(); var ans3 = $('#ans3').val(); var ans4 = $('#ans4').val(); var ans5 = $('#ans5').val(); var ans6 = $('#ans6').val(); var ans7 = $('#ans7').val(); var ans8 = $('#ans8').val(); var ans9 = $('#ans9').val(); var ans10 = $('#ans10').val(); var ans11 = $('#ans11').val(); var ans12 = $('#ans12').val(); var ans13 = $('#ans13').val(); $.ajax({ url:'SlamBookAnswers/addAnswers', type:'post', data:{ senderId:senderId, receiverId:receiverId, ans1:ans1, ans2:ans2, ans3:ans3, ans4:ans4, ans5:ans5, ans6:ans6, ans7:ans7, ans8:ans8, ans9:ans9, ans10:ans10, ans11:ans11, ans12:ans12, ans13:ans13 } }).success(function(data){ $('#dialog').dialog('close'); $('#dialog').html('A request has been sent to your friend for approval Thanx').dialog({ modal:true, width:'400', title:'Thanx !!', show: { effect: "fade", duration: 500 }, hide: { effect: "fade", duration: 1000 }, buttons: [ { text: "Ok", click: function() { $('#dialog').dialog("close"); $('#addToSlambookSlidesDiv').html("").slideUp(1000); } } ] }); }); }); /**/ $('.friendsAlbumsButton').click(function(){ $('.closefriendsAlbums').hide(100); currentfriendId = $(this).attr("friendId"); friendId = $(this).attr("friendId"); var clickTimes = 1; $.ajax({ url:'album/getUserFriendsAlbums/'+friendId+"/"+clickTimes, type:'get', }).success(function(data){ $('#dialog').dialog('close'); $('#images_div').html('<div style="position:absolute; bottom:0px; width: 100%; text-align: center"><button style="padding:1%" class="closeImagesDiv">Close</button></div>'); $('#images_div').prepend(data).slideDown(1000); }); }); $('.closefriendsAlbums').live('click',function(){ $('.closefriendsAlbums').hide(100); $('#friendsAlbums').slideUp(1000); }); $('.getFriendsAlbum').live("click",function(){ if($(this).attr("friendId") != null){ friendId = $(this).attr("friendId"); } var albumId = $(this).attr("albumId"); $.ajax({ url:"Images/getFriendsImages/"+albumId+"/"+friendId, type:"post", data:{ } }).success(function(data){ $('#dialog').dialog('close'); $('#images_div_friendsalbumImages').html('<div style="position:absolute; bottom:0px; width: 100%; text-align: center"><button style="padding:1%" class="closefriendsalbumImagesDiv">Close</button></div>'); $('#images_div_friendsalbumImages').prepend(data).slideDown(1000); }); }); $('.closefriendsAlbumsImages').live('click',function(){ $('#friendsAlbumImages').slideUp(1000); }); $('.closefriendsVideos').live('click',function(){ $('#friendsVideos').slideUp(1000); }); $('.friendsVideosButton').click(function(){ var friendVideoId = $(this).attr('friendId'); currentfriendId = $(this).attr('friendId'); userFriendClickTimes = 0; $.ajax({ url:"Videos/getFriendsVideos/"+friendVideoId+"/"+1, type:"post", data:{ } }).success(function(data){ $('#images_div').html('<div style="position:absolute; bottom:0px; width: 100%; text-align: center"><button style="padding:1%" class="closeImagesDiv">Close</button></div>'); $('#images_div').prepend(data).slideDown(1000); }); }); $('.changeFriendVideo').live("click",function(){ $('.friendvideoPlayer').attr('src',$(this).attr('videoUrl')); }); /**/ /*******************Upload Change PRofile Script Begins *********************/ var input = document.getElementById("imagefile"), formdata = false; if (window.FormData) { } input.addEventListener("change", function (evt) { formdata = new FormData(); $('#changeProfilePicDiv').dialog("close"); $('#dialog').html('<img src="images/143.gif" style="margin-left: auto; margin-right: auto"/></br>Changing Profile Pic Please Wait').dialog({ modal:true, width:'auto', title:'Please Wait', show: { effect: "fade", duration: 500 }, hide: { effect: "fade", duration: 1000 }, buttons:{ } }); //document.getElementById("response").innerHTML = "Uploading . . ." var i = 0, len = this.files.length, img, reader, file; for ( ; i < len; i++ ) { file = this.files[i]; if (!!file.type.match(/image.*/)) { if ( window.FileReader ) { reader = new FileReader(); reader.onloadend = function (e) { //showUploadedItem(e.target.result, file.fileName); }; reader.readAsDataURL(file); } if (formdata) { formdata.append("imagefile", file); } } } if (formdata) { $.ajax({ url: "profilepic/changeprofilepic", type: "POST", data: formdata, processData: false, contentType: false, success: function (res) { //document.getElementById("response").innerHTML = res; //alert(res); var id=$('#userId').val(); $.ajax({ url:'resources/users/'+id+'/profilepic/thumbs/'+res+'.jpg', type:'get', success:function(){ $('#profilePic').attr('src','resources/users/'+id+'/profilepic/thumbs/'+res+'.jpg'); $('#dialog').dialog("close"); } }); // $('#profilePic').attr('src','users/'+id+'/profilepic/'+res+'.jpg'); // $('#dialog').dialog("close"); }, error:function(){ //document.getElementById("response").innerHTML = "Error"; } }); } }, false); /*****************Upload Change PRofile Script Ends ***********************/ /**/ /**/ /*Video Likes*/ $('.addVideoLikes').live('click',function(){ var userId = $('#userId').val(); var videoId = $(this).attr('videoId'); $(this).next().addClass('current'); $(this).addClass('removeVideoLikes'); $(this).removeClass('addVideoLikes'); $(this).html('UnLike'); $.ajax({ url:'VideoLikes/addVideoLike', type:'post', data:{ videoId:videoId, userId:userId } }).success(function(data){ var likeNumber = data.toString(); $('.current').html(likeNumber+" Likes"); $('.current').removeClass('current'); showHomeNotification("Liked SuceesFully"); }).error(function(data){ alert("error"+userId+videoId); }); }); $('.removeVideoLikes').live('click',function(){ var userId = $('#userId').val(); var videoId = $(this).attr('videoId'); $(this).next().addClass('current'); $(this).removeClass('removeVideoLikes'); $(this).addClass('addVideoLikes'); $(this).html('Like'); $.ajax({ url:'VideoLikes/removeVideoLike', type:'post', data:{ videoId:videoId, userId:userId } }).success(function(data){ $('.current').html(data+" Likes"); $('.current').removeClass('current'); showHomeNotification("Unliked SuceesFully"); }).error(function(data){ alert("error"+userId+videoId); }); }); /*Video Likes*/ /*Image Likes*/ $('.addImageLikesInfo').live('click',function(){ var imageId = $(this).attr("imageId"); }); $('.addImageLikes').live('click',function(){ var userId = $('#userId').val(); var imageId = $(this).attr('imageId'); var albumId = $(this).attr('albumId'); $(this).next().addClass('current'); $(this).addClass('removeImageLikes'); $(this).removeClass('addImageLikes'); $(this).html('UnLike'); $.ajax({ url:'ImageLikes/addLike', type:'post', data:{ imageId:imageId, albumId:albumId, userId:userId } }).success(function(data){ var likeNumber = data.toString(); $('.current').html(likeNumber+" Likes"); $('.current').removeClass('current'); showHomeNotification("Liked SuceesFully"); }).error(function(data){ alert("error"+userId+imageId); }); }); $('.removeImageLikes').live('click',function(){ var userId = $('#userId').val(); var imageId = $(this).attr('imageId'); var albumId = $(this).attr('albumId'); $(this).next().addClass('current'); $(this).removeClass('removeImageLikes'); $(this).addClass('addImageLikes'); $(this).html('Like'); $.ajax({ url:'ImageLikes/removeLike', type:'post', data:{ imageId:imageId, albumId:albumId, userId:userId } }).success(function(data){ $('.current').html(data+" Likes"); $('.current').removeClass('current'); showHomeNotification("Unliked SuceesFully"); }).error(function(data){ alert("error"+userId+imageId); }); }); /* Image Likes*/ /*User Design Settings*/ $('#userSettingsButton').click(function(){ $('#settingsDiv').append('<div style="position:absolute; bottom:0px; width: 100%; text-align: center"><button style="padding:1%" class="closeSettingsDiv">Close</button></div>'); $('#settingsDiv').slideDown(1000); }); $('.closeSettingsDiv').live('click',function(){ $('#settingsDiv').slideUp(1000); }); $('#userDesignAccordion').accordion(); $('#insideUserDesignAccordion').accordion(); /* Slambook Pages Background Texture*/ $('.slambookPagesBackgroundTexture').hover(function(){ var textureId = $(this).attr("textureId"); $('div .b-wrap-right').toggleClass("slambookPagesBackgroundTexture"+textureId); $('div .b-wrap-left').toggleClass("slambookPagesBackgroundTexture"+textureId) }); /* Slambook Pages Background Texture*/ /* Slambook Background Texture*/ $('.slambookBackgroundTexture').hover(function(){ var textureId = $(this).attr("textureId"); $('body').toggleClass('backgroundTextture'+textureId); }); /* Slambook Background Texture*/ /*User Design Settings*/ /*News Feed*/ $('#newsStreamButton').click(function(){ var userId = $('#userId').val(); $('.innerfriendsNotificationsDiv').html(""); $('.yourNotificationsDiv').html(""); $('#dialog').html("Loading Notifications Plesae Wait .....").dialog({ modal:true, title:'Please Wait ...', show: { effect: "fade", duration: 500 }, hide: { effect: "fade", duration: 1000 }, buttons:{ } }); $.ajax({ url:'GetFriendsNotifications', type:'post', data:{userId:userId} }).success(function(data){ $('.innerfriendsNotificationsDiv').append(data); }); $.ajax({ url:'GetUserNotifications', type:'post', data:{userId:userId} }).success(function(data){ $('#notificationsSlidesDiv').slideDown(1000); $('#dialog').dialog("close"); $('.yourNotificationsDiv').prepend(data); }); }); $('.closeNotificationsSlidesDiv').click(function(){ $('#notificationsSlidesDiv').slideUp(1000); }); $('#closeNewsStream').click(function(){ $('#newsStream').animate({ width: "toggle" },1000); }); /**/ }); function showNotification(msg){ $('#message').html(msg); $('#notifications').slideDown(1000).delay(3000).slideUp(1000); } function showHomeNotification(msg){ $('#Homemessage').html(msg); $('#Homenotifications').slideDown(1000).delay(3000).slideUp(1000); } function validateEmail(sEmail) { var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; if (filter.test(sEmail)) { return true; } else { return false; } } function youtube_parser(url){ var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/; var match = url.match(regExp); if (match&&match[7].length==11){ return match[7]; }else{ return"failed"; } } function getEmail(){ var prmstr = window.location.search.substr(1); var prmarr = prmstr.split ("&"); for ( var i = 0; i < prmarr.length; i++) { var tmparr = prmarr[i].split("="); params[tmparr[0]] = tmparr[1]; } return params.email; } function getRealTimeMessageId(senderId,messageId){ $.ajax({ url:'message/getRealTimeMessageId', type:'post', data:{ senderId:senderId, messageId:messageId } }).success(function(data){ console.log("current ="+currentRealTimeMessageId+" Data = "+data); if(data > currentRealTimeMessageId){ retrieveMessage(currentRealTimeSenderId,currentRealTimeMessageId); currentRealTimeMessageId = data; } else{ } }); } function retrieveMessage(senderId,messageId){ $.ajax({ url:'message/getRealTimeMessages', type:'post', data:{senderId:senderId,messageId:messageId} }).success(function(data){ $('#InsidefriendsConversationMessagesThread').append(data); }); }
const works = [ { author: "Micheal Jackson",lifetime:"1022-1055",tips: "Human", photos: ["human1.jpg","human2.jpg","human3.jpg"] }, { author: "Maria JK",lifetime:"1920-2001", tips: "Classical", photos: ["classical1.jpg","classical2.jpg"] }, { author: "John Herry UY", lifetime:"1894-1928",tips: "Abstract", photos: ["abstract1.jpg","abstract2.jpg","abstract3.jpg","abstract4.jpg","abstract5.jpg"] }, { author: "Coco",lifetime:"1777-1799", tips: "Beauty", photos: ["beauty1.jpg","beauty2.jpg"] } ]; let item1 = document.createElement("div"); item1.className = "item"; document.getElementsByClassName("justify")[0].appendChild(item1); let tips = document.createElement("h4"); let tipContent = document.createTextNode("Genre :"+" " +works[0].tips); tips.appendChild(tipContent); item1.appendChild(tips); let innerBox1 = document.createElement("div"); innerBox1.className = "inner-box"; item1.appendChild(innerBox1); let author = document.createElement("h3"); author.innerHTML = works[0].author; innerBox1.appendChild(author); author.style.display = "inline"; let lifeTime = document.createElement("h5"); lifeTime.innerHTML = "lifetime:" + works[0].lifetime; innerBox1.appendChild(lifeTime); lifeTime.style.display = "inline"; lifeTime.style.marginLeft = "1em"; let innerBox2 = innerBox1.cloneNode(true); let content = document.createTextNode("Popular Photos"); innerBox2.firstChild.replaceChild(content,innerBox2.firstChild.firstChild); innerBox2.removeChild(innerBox2.childNodes[1]); item1.appendChild(innerBox2); addPhotos(innerBox2,0); function addPhotos(innerBox,j) { let div = document.createElement("div"); innerBox.appendChild(div); function addPhoto(node,str) { let photo = document.createElement("img"); photo.src = str; photo.className = "photo"; node.appendChild(photo); } for (let i = 0; i < works[j].photos.length; i++) { addPhoto(div,works[j].photos[i]) } } let button1 = document.createElement("button"); button1.innerHTML = "Visit"; item1.appendChild(button1); function cloneItem(j) { let item2 = item1.cloneNode(true); item2.childNodes[0].replaceChild(document.createTextNode("Genre :"+" " +works[j].tips),item2.childNodes[0].firstChild); item2.childNodes[1].firstChild.replaceChild(document.createTextNode(works[j].author),item2.childNodes[1].firstChild.firstChild); item2.childNodes[2].removeChild(item2.childNodes[2].childNodes[1]);//div移掉 addPhotos(item2.childNodes[2],j); document.getElementsByClassName("flex-container justify")[0].appendChild(item2); } cloneItem(1); cloneItem(2); cloneItem(3);
const {add,mul} = require("./mathUtil.js"); console.log(add(20,30)); console.log(mul(20,30)); import {name,age,height} from "./info"; console.log(name); console.log(age); console.log(height);
//Actividad 2 (filter) const ciudades = ["Madrid","Valencia","Murcia","Malaga"] const filtrarArreglo = ciudades.filter(function(ciudades){ return total= ciudades.startsWith("M"); }); console.log("Ciudades que empiezan por M: "+filtrarArreglo);
'use strict'; function listenShortcutReloadExtensionOnDemand() { chrome.commands.onCommand.addListener(function (command) { switch (command) { case 'restartext': chrome.runtime.reload(); break; } }); } function getLocation(href) { var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)(\/[^?#]*)(\?[^#]*|)(#.*|)$/); return match && { protocol: match[1], host: match[2], hostname: match[3], port: match[4], pathname: match[5], search: match[6], hash: match[7] }; } function injectJSFile(tabId, match) { // attempt to execute default js chrome.tabs.executeScript(tabId, { file: 'chromedotfiles/default.js' }, function (res) { if (chrome.runtime.lastError) { // file not found, fail silently return; } }); if (match) { // attempt to execute domain specific js let filenames = generatePossibleFilenamesFromHostname(match.hostname) for (let filename of filenames) { let curl = 'chromedotfiles/' + filename + '.js' chrome.tabs.executeScript(tabId, { file: curl, }, function (res) { if (chrome.runtime.lastError) { // file not found, fail silently return; } }); } } } function injectJS(tabId, match) { // attempt to execute default js chrome.tabs.executeScript(tabId, { file: 'chromedotfiles/default.js' }, function (res) { if (chrome.runtime.lastError) { // file not found, fail silently return; } }); if (match) { // attempt to execute domain specific js let filenames = generatePossibleFilenamesFromHostname(match.hostname) for (let filename of filenames) { let url = `chrome-extension://${chrome.runtime.id}/chromedotfiles/${filename}.js` console.log(url) fetch(url) .catch(function () { }) .then(response => response && response.ok && response.text()) .then(data => { if (!data) return; chrome.tabs.executeScript(tabId, { code: data }, function (res) { // TODO(hbt) ENHANCE consider adding a code to check response and retry. e.g add "injected-timestamp" at end of script then check the response and reinject // Note(hbt) check pogdesign example // console.log(res) }) }) } } } function generatePossibleFilenamesFromHostname(hostname) { console.log(hostname) let filenames = [] let parts = hostname.split(".") parts = parts.reverse() let nfile = "" for (let p of parts) { nfile = p + "." + nfile if (nfile.endsWith(".")) { nfile = nfile.substring(0, nfile.length - 1) } filenames.push(nfile) } filenames = filenames.reverse() filenames = _.unique(filenames) return filenames } function injectCSSFile(tabId, filename) { let filenames = generatePossibleFilenamesFromHostname(filename) for (let filename of filenames) { let curl = chrome.runtime.getURL(`chromedotfiles/${filename}.css`) try { $.ajax({ url: curl }).done(function (data) { if (data) { chrome.tabs.insertCSS( tabId, { code: data, runAt: "document_start", allFrames: true }, function (res) { } ); } }).error(function () { }); } catch (e) { } } } function injectCSS(tabId, match) { injectCSSFile(tabId, 'default') if (match) { injectCSSFile(tabId, match.hostname) } } function injectCSS2(tabId, match) { injectCSSFile(tabId, 'vdark') } // TODO(hbt) NEXT fix manivest v3 and use chrome removeCSS // https://gist.github.com/hbt/e2e445e69fb97e423567e342e03f6cdb function main() { listenShortcutReloadExtensionOnDemand() chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) { if(!tab || !tab.url) return; if (tab.url && tab.url.startsWith('chrome')) { return; } var match = getLocation(tab.url); if (changeInfo.status === 'loading') { // injectCSS(tabId, match); injectCSS2(tabId, match); } if (changeInfo.status === 'complete') { injectCSS(tabId, match) // Note(hbt) issues with injectJSFile not always injecting in latest chrome. Using injectJS with code instead of file. injectJS(tabId, match); } }); } // TODO(hbt) NEXT fix this to use code insertion instead of file insertion like injectJS function. reuse injectJS and remove dup code. /** * simulates loading JS files in order passed in array and in sync mode instead of async * * @param tabId * @param files * @param callbackFunctionName */ function loadJSFile(tabId, files, callbackFunctionName) { var port = chrome.tabs.connect(tabId, {}); if (files.length === 0) { port.postMessage({ action: callbackFunctionName }); // exit recursion return; } var nfiles = files; var filename = nfiles.shift(); chrome.tabs.executeScript(tabId, { file: 'chromedotfiles/' + filename }, res => { if (chrome.runtime.lastError) { port.postMessage({ action: 'console.error', args: chrome.runtime.lastError }); } loadJSFile(tabId, nfiles, callbackFunctionName); }); } function loadJSFiles(filepath, callbackFunctionName, tab) { var files = filepath; if (!(filepath instanceof Array)) { files = [filepath]; } loadJSFile(tab.id, files, callbackFunctionName); } main()