text
stringlengths
7
3.69M
import React from 'react'; import '../css/activity.css'; // Images import Followers from '../images/icons/Followers@2x.png'; import Events from '../images/icons/Events@2x.png'; import Assignments from '../images/icons/Assignments@2x.png'; function Activity() { return ( <section className="activity"> <h1 className="section-title line"><span>Activity</span></h1> <details className="activity-item"> <summary> <img className="thumbnail" src={ Followers } alt="" /> You have 5 new followers including <strong>Kathryn Crawford</strong> and <strong>Piper Shaw</strong> </summary> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus id dolor sed leo luctus aliquet. Integer ut volutpat lorem. Quisque sed neque dui. Integer tempus sagittis rhoncus. Fusce ac tempus enim. Morbi elementum urna hendrerit, tempor est vitae, consectetur mauris. Praesent pellentesque turpis fringilla nulla sollicitudin, sed feugiat tortor ultrices.</p> </details> <details className="activity-item"> <summary> <img className="thumbnail" src={ Events } alt="" /> 3 new events were added to your calendar </summary> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus id dolor sed leo luctus aliquet. Integer ut volutpat lorem. Quisque sed neque dui. Integer tempus sagittis rhoncus. Fusce ac tempus enim. Morbi elementum urna hendrerit, tempor est vitae, consectetur mauris. Praesent pellentesque turpis fringilla nulla sollicitudin, sed feugiat tortor ultrices.</p> </details> <details className="activity-item"> <summary> <img className="thumbnail" src={ Assignments } alt="" /> You have 3 pending readings to complete </summary> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus id dolor sed leo luctus aliquet. Integer ut volutpat lorem. Quisque sed neque dui. Integer tempus sagittis rhoncus. Fusce ac tempus enim. Morbi elementum urna hendrerit, tempor est vitae, consectetur mauris. Praesent pellentesque turpis fringilla nulla sollicitudin, sed feugiat tortor ultrices.</p> </details> </section> ); } export default Activity;
import Vue from "vue"; import App from "./App.vue"; import VueRouter from "vue-router"; import Home from "@/components/Home"; import Hello from "@/components/Hello" import Bye from "@/components/Bye" Vue.config.productionTip = false; Vue.use(VueRouter); let router = new VueRouter({ mode: 'history', routes: [ { name: 'home', component: Home, path: '/' }, { name: 'hello', component: Hello, path: '/hello' }, { name: 'bye', component: Bye, path: '/bye' }, ] }) new Vue({ router, render: h => h(App) }).$mount("#app");
/****************************************************************************** * Setup the webserver. * Using the express webframework, and ejs templating. * I am trying to follow the MVC pattern. */ var express = require('express'), app = module.exports = express(), templateContainer = require('./libs/templateContainer.js'); // Configuration app.configure(function(){ app.enable("jsonp callback"); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.static(__dirname + '/public')); app.use(app.router); // load the express-partials middleware // app.use(partials()); templateContainer.setDirname(__dirname); }); app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function(){ app.use(express.errorHandler()); }); /****************************************************************************** * Route Section */ // Base Route app.get('/', function(req, res){ res.send('Welcome to Site Robot'); }); app.get('/demo', function(req, res){ res.render("twoColumn.ejs", templateContainer.setDemo()); }); app.get('/debug', function(req, res){ var controller = require('./controllers/debugController.js'); controller.loadModel(req, function(model) { res.render(model.bodyTemplate, model); }); }); app.post('/debug', function(req, res){ var controller = require('./controllers/debugController.js'); controller.loadModel(req, function(model) { res.render(model.bodyTemplate, model); }); }); app.get('/robot', function(req, res){ var controller = require('./controllers/robotController.js'); controller.loadPassModel(req, function(model) { res.render(model.bodyTemplate, model); }); }); app.get('/robot/fail', function(req, res){ var controller = require('./controllers/robotController.js'); controller.loadFailModel(req, function(model) { res.render(model.bodyTemplate, model); }); }); app.get('/robot/pass', function(req, res){ var controller = require('./controllers/robotController.js'); controller.loadPassModel(req, function(model) { res.render(model.bodyTemplate, model); }); }); app.get('/robot/test-run', function(req, res){ var controller = require('./controllers/robotController.js'); controller.loadTestRunModel(req, function(model) { res.render(model.bodyTemplate, model); }); }); app.get('/robot/i', function(req, res){ var controller = require('./controllers/robotController.js'); controller.loadIModel(req, function(model) { res.render(model.bodyTemplate, model); }); }); app.get('/test-results', function(req, res) { var controller = require('./controllers/testResultsController.js'); var template = templateContainer.load(); controller.loadTestResults(true, template, req, function(resultTemplate) { res.render(resultTemplate.page.bodyTemplate, resultTemplate); }); }); app.get('/test-results/iron', function(req, res) { var controller = require('./controllers/testResultsController.js'); var template = templateContainer.load(); controller.loadTestResults(false, template, req, function(resultTemplate) { res.render(resultTemplate.page.bodyTemplate, resultTemplate); }); }) app.get('/check/create', function(req, res) { var controller = require('./controllers/checkController.js'); var template = templateContainer.load(); controller.create(template, req, function(resultTemplate) { res.render(resultTemplate.page.bodyTemplate, resultTemplate); }); }); app.post('/check/update', function(req, res) { var controller = require('./controllers/checkController.js'); var template = templateContainer.load(); controller.update(template, req, function(resultTemplate) { res.render(resultTemplate.page.bodyTemplate, resultTemplate); }); }); app.get('/check/update', function(req, res) { var controller = require('./controllers/checkController.js'); var template = templateContainer.load(); controller.update(template, req, function(resultTemplate) { res.render(resultTemplate.page.bodyTemplate, resultTemplate); }); }); app.get('/check/delete', function(req, res) { }); app.get('/check', function(req, res) { var controller = require('./controllers/checkController.js'); var template = templateContainer.load(); controller.index(template, req, function(resultTemplate) { res.render(resultTemplate.page.bodyTemplate, resultTemplate); }); }); /* app.get('/editor/create', function(req, res) { var controller = require('./controllers/editorController.js'); var template = templateContainer.load(); controller.create(template, req, function(resultTemplate) { res.render(resultTemplate.page.bodyTemplate, resultTemplate); }); }); app.get('/editor/update', function(req, res) { var controller = require('./controllers/editorController.js'); var template = templateContainer.load(); controller.create(template, req, function(resultTemplate) { res.render(resultTemplate.page.bodyTemplate, resultTemplate); }); }); app.get('/test-list', function(req, res) { var controller = require('./controllers/testListController.js'); var template = templateContainer.load(); controller.list(template, req, function(resultTemplate) { res.render(resultTemplate.page.bodyTemplate, resultTemplate); }); }); app.get('/test-list/create', function(req, res) { var controller = require('./controllers/testListController.js'); var template = templateContainer.load(); controller.create(template, req, function(resultTemplate) { res.render(resultTemplate.page.bodyTemplate, resultTemplate); }); }); app.post('/test-list/update', function(req, res) { var controller = require('./controllers/testListController.js'); var template = templateContainer.load(); controller.update(template, req, function(resultTemplate) { res.render(resultTemplate.page.bodyTemplate, resultTemplate); }); }); */ /****************************************************************************** * Start Web Server */ var port = process.env.PORT || 3000; app.listen(port); console.log("Express server listening on: " + port);
function clock() { function getTimeFromSeconds(seconds) { const date = new Date(seconds * 1000); return date.toLocaleTimeString('pt-BR', { hour12: false, timeZone: 'GMT' }); } const clock = document.querySelector('.clock'); const btnStart = document.querySelector('.start'); const btnStop = document.querySelector('.pause'); const btnReset = document.querySelector('.reset'); let seconds = 0; let timer; function startClock() { timer = setInterval(function() { seconds++; clock.innerHTML = getTimeFromSeconds(seconds); }, 1000); } document.addEventListener('click', (e) => { const element = e.target; if(element.classList.contains('start')) { clock.classList.remove('paused'); clearInterval(timer); startClock(); } if(element.classList.contains('pause')) { clock.classList.add('paused'); clearInterval(timer); } if(element.classList.contains('reset')) { clock.classList.remove('paused'); clearInterval(timer); clock.innerHTML = `00:00:00`; seconds = 0; } }); } clock(); /* btnStart.addEventListener('click', (e) => { clock.classList.remove('paused'); clearInterval(timer); startClock(); }); btnStop.addEventListener('click', (e) => { clock.classList.add('paused'); clearInterval(timer); }); */ /* btnReset.addEventListener('click', (e) => { clearInterval(timer); clock.innerHTML = `00:00:00`; seconds = 0; }); */
import React from "react"; import PropTypes from "prop-types"; import useResizeDetector from "use-resize-observer/polyfilled"; import debounce from "lodash.debounce"; import { ShirtSizes } from "@paprika/helpers"; import * as sc from "./ResizeDetector.styles"; const propTypes = { /** The width at which the size will change from the default (medium) to large. 0 or null value will disable. */ breakpointLarge: PropTypes.number, /** The width at which the size will change from small to the default (medium). 0 or null value will disable. */ breakpointSmall: PropTypes.number, /** Content to be wrapped which will be provided with live dimensions and (tshirt) size values. */ children: PropTypes.node, /** The ms delay before firing resize events / making live updates. */ debounceDelay: PropTypes.number, /** If the container will match its parent's width like a block level element (width: 100%). */ isFullWidth: PropTypes.bool, /** If the container will match its parent's height (height: 100%). */ isFullHeight: PropTypes.bool, /** Callback that fires when the size change crosses a breakpoint threshold (returns new size value). */ onBreak: PropTypes.func, /** Callback that fires when the size changes (returns new width + height values). */ onResize: PropTypes.func, }; const defaultProps = { breakpointLarge: 768, breakpointSmall: 360, children: null, debounceDelay: 30, isFullWidth: true, isFullHeight: false, onBreak: () => {}, onResize: () => {}, }; const MAX_WAIT = 1000; const ResizeContext = React.createContext(); export function useDimensions() { const { width, height } = React.useContext(ResizeContext); return { width, height }; } export function useBreakpoints() { const { size } = React.useContext(ResizeContext); return { size }; } function getSize(width, breakpointSmall, breakpointLarge) { let size = ShirtSizes.MEDIUM; if (breakpointSmall && width < breakpointSmall) { size = ShirtSizes.SMALL; } else if (breakpointLarge && width >= breakpointLarge) { size = ShirtSizes.LARGE; } return size; } function ResizeDetector(props) { const { breakpointSmall, breakpointLarge, children, debounceDelay, onBreak, onResize, ...moreProps } = props; const refContainer = React.useRef(null); const [{ width, height }, setDimensions] = React.useState({}); const [size, setSize] = React.useState(null); function handleResize({ width, height }) { setDimensions({ width, height }); onResize({ width, height }); const newSize = getSize(width, breakpointSmall, breakpointLarge); if (newSize !== size) { setSize(newSize); onBreak(newSize); } } useResizeDetector({ ref: refContainer, onResize: debounce(handleResize, debounceDelay, { maxWait: MAX_WAIT }), }); React.useLayoutEffect(() => { const { width, height } = refContainer.current.getBoundingClientRect(); setDimensions({ width, height }); setSize(getSize(width, breakpointSmall, breakpointLarge)); }, [breakpointSmall, breakpointLarge]); return ( <sc.ResizeDetector data-pka-anchor="resize-observer" {...moreProps} ref={refContainer}> <ResizeContext.Provider value={{ width, height, size }}>{children}</ResizeContext.Provider> </sc.ResizeDetector> ); } ResizeDetector.displayName = "ResizeDetector"; ResizeDetector.propTypes = propTypes; ResizeDetector.defaultProps = defaultProps; export default ResizeDetector;
function Decoder(bytes, port) { // Decode an uplink message from a buffer // (array) of bytes to an object of fields. // every field is the name of the field to be returned followed by the number of bits it is in the payload. In the order it would be send. var fields = [['value 1', 2],['value 2', 2],['value 3', 2],['timestamp', 4],['voltage', 2],[],[]]; //port = 3; var available_fields = port.toString(2); available_fields = available_fields.split("").reverse().join(""); available_fields = available_fields + "0000000".substr(available_fields.length); var payloadByteNext = 0; var output = {}; for(var i = 0; i < available_fields.length; i++){ if(available_fields.charAt(i) == "1"){ value = bytes[payloadByteNext] ; for(var j = 1; j < fields[i][1]; j++){ value |= (bytes[payloadByteNext + j] << (8 * j)); } name_field = fields[i][0]; output[name_field] = value; payloadByteNext += fields[i][1]; } } return output }
/* NAVIFATION PANEL =================================================================*/ const NAV_HEADER = document.querySelector('.nav_bar'); window.addEventListener('scroll', () => { // при проматывании страници, обработчик добавляет класс, с прилигающими к нему стилями, к секции навигации. if (pageYOffset > 100) { NAV_HEADER.id = 'window-scroll'; } else { NAV_HEADER.id = ''; } }) /* REVIEW WINDOW ==========================================================================*/ const ADD_TABLE = document.querySelector('.add_table'); const OVERLAY_ADD_TABLE = document.querySelector('.overlay'); const ADD_BUTTON = document.querySelector('.add_button'); const ESC_BUTTON = document.querySelector('.esc_button'); ADD_BUTTON.addEventListener('click', () => { // обработчик делает видимым секцию с формой для отзыва ADD_TABLE.classList.add('add_table-active'); }) OVERLAY_ADD_TABLE.addEventListener('click', () => { ADD_TABLE.classList.remove('add_table-active'); }) ESC_BUTTON.addEventListener('click', () => { // обработчик скрывает секцию с формой для отзыва ADD_TABLE.classList.remove('add_table-active'); }) // NEWS SLIDER LOGIC //====================================================== const CONTAINER_NEWS = document.querySelectorAll('.container_news'); const ARRAY_NEWS = Array.from(CONTAINER_NEWS); var index_news = 0; function move_news() { ARRAY_NEWS[index_news].classList.remove('active-news'); if (index_news++ == ARRAY_NEWS.length - 1) { index_news = 0 }; ARRAY_NEWS[index_news].classList.add('active-news'); } window.onload = setInterval(() => move_news(), 7000); // PERSONNEL SLIDER LOGIC //====================================================== const SLIDER_BUTTONS = document.querySelectorAll('.personnel_slider_buttons'); const CONTAINER_PERSONNEL = document.querySelector('.container_personnel_slides'); const PERSONNEL_MAIN = document.querySelector('.main_personnel_slides'); const PERSONNEL_LENGTH = document.querySelectorAll('.personnel').length; const WIDTH_PERSONNEL = Math.ceil(PERSONNEL_LENGTH / 3) * 100; const LAST_CHILD = PERSONNEL_LENGTH - 3; var count_personnel = 0; var timerId = setTimeout(() => move_direction_slides("right"), 5000); PERSONNEL_MAIN.previousElementSibling.innerHTML += `<style type="text/css"> .main_personnel_slides {width: ${WIDTH_PERSONNEL}%;} .personnel {width: ${((CONTAINER_PERSONNEL.offsetWidth / 3) - 20)}px;} </style>`; SLIDER_BUTTONS.forEach(item => { // кнопки ручного переключения слайдов item.addEventListener("click", () => { clearTimeout(timerId); move_direction_slides(`${item.value}`); }); }); function move_direction_slides(move_direction) { //выбор направления переключения слайдов switch(move_direction) { case("right"): count_personnel++; break; case("left"): count_personnel--; break; }; if (count_personnel < 0) { count_personnel = LAST_CHILD;} //проверка на минимум слайдов if (count_personnel > LAST_CHILD) { count_personnel = 0;} //проверка на максимум слайдов PERSONNEL_MAIN.style = `margin-left: -${count_personnel * 33.3333}%`//сдвиг окна слайдеров timerId = setTimeout(() => move_direction_slides("right"), 5000); }; // function auto_switch_slides(move_direction) { // засцикливание авто преключение слайдов // timerId = setTimeout(() => move_direction_slides(move_direction), 5000); // }
import React, {Component} from 'react' import { Link } from 'react-router' class TabLink extends Component { render(){ const { router } = this.context const isActive = router.isActive(this.props.to, this.props.params, this.props.query) const className = isActive ? 'active' : ''; return( <li className={className}> <Link {...this.props} /> </li> ) } } TabLink.contextTypes = { router: React.PropTypes.object.isRequired } export default TabLink
import request from './network.js' // 将首页获取的数据独立封装 export function getMultiData(){ return request({ url: '/home/multidata', }) } /************获取首页中的 流行 新款 精选等数据************* */ export function getProductData(type,page){ return request({ url: '/home/data', data:{ type, page } }) }
const express = require('express') const router = express.Router() const Food = require('../control/foodController') const multer = require('multer') const upload=multer({}) //查询接口(分页查询 分类查询 关键字查询) router.get('/getFoods',(req,res)=>{ let page=Number(req.query.page)||1 let pageSize=Number(req.query.pageSize)||2 Food.get(page,pageSize) .then((data)=>{ res.send({err:0,msg:'查询ok',list:data}) }) .catch((err)=>{ console.log(err) res.send({err:-1,msg:'查询失败'})}) }) // 分类查询 router.get('/getFoodsByType',(req,res)=>{ let {foodType} = req.query let page=Number(req.query.page)||1 let pageSize = Number(req.query.pageSize)||2 Food.getByType(foodType,page,pageSize) .then((data)=>{ res.send({err:0,msg:'查询ok',list:data}) }) }) // 关键字查询 router.get('/getFoodsByKw',(req,res)=>{ let page=Number(req.query.page)||1 let pageSize = Number(req.query.pageSize)||2 let kw = req.query.kw Food.getByKw(kw,page,pageSize) .then((data)=>{ res.send({err:0,msg:'ok',list:data}) }) }) //id查询 router.get('/getByID',(req,res)=>{ let _id = req.query._id Food.getByID(_id) .then((data)=>{ res.send({err:0,msg:'ok',list:data}) }) }) //删除接口 router.get('/delFood',(req,res)=>{ let {foodId}=req.query Food.del(foodId) .then((data)=>{ res.send({err:0,msg:'del ok'}) }) .catch((err)=>{ res.send({err:-1,msg:'del nook'}) }) }) //添加数据 router.post('/addFood',(req,res)=>{ let {goods_name,goods_price,goods_number,goods_weight,goods_state,add_time,old_time,is_promote,goods_img} = req.body Food.add(goods_name,goods_price,goods_number,goods_weight,goods_state,add_time,old_time,is_promote,goods_img) .then((data)=>{res.send({err:0,msg:'添加ok'})}) .catch((err)=>{ console.log(err) res.send({err:-1,msg:'添加失败'})}) }) //修改 router.get('/updateFood',(req,res)=>{ let {_id,goods_name,goods_price,goods_number,goods_weight,goods_state,add_time,old_time,is_promote,goods_img} = req.query Food.update(_id,goods_name,goods_price,goods_number,goods_weight,goods_state,add_time,old_time,is_promote,goods_img) .then((data)=>{res.send({err:0,msg:'修改ok'})}) .catch((data)=>{res.send({err:-1,msg:'修改失败'})}) }) //上传图片 router.post('/upfile',upload.single('hh'),(req,res)=>{ console.log(req.file) res.send(req.file) }) module.exports = router
const cds = require("@sap/cds"); const { retrieveJwt } = require("@sap-cloud-sdk/core"); /* const createFilter = xs => { const andFilters = xs.map(x => new FilterList([ Suppliers.SUPPLIER.equals(x.businessPartner), ])) return new FilterList(undefined, andFilters).flatten() } function SELECT (columns) { return { from(a){ const b = {} for (let p in a) if (p in columns) b[p] = a[p] return b }} } */ function getJWT(req) { if (typeof req._ !== "undefined") { return retrieveJwt(req._.req); } else { return ""; } } module.exports = async function () { const { Suppliers: sdkSuppliers, } = require("./odata-client/EPM_REF_APPS_PROD_MAN_SRV"); const { BusinessPartner: sdkBusinessPartner, } = require("./odata-client/business-partner-service"); const { FilterList, serializeEntity, retrieveJwt, } = require("@sap-cloud-sdk/core"); const sepmraProdService = await cds.connect.to("SEPMRA_PROD_MAN"); const externalService = await cds.connect.to("EPM_REF_APPS_PROD_MAN_SRV"); const es5Service = await cds.connect.to("ZPDCDS_SRV"); const { Products: externalProducts, Suppliers: externalSuppliers } = externalService.entities; const destinationName = "ES5"; const destinationS4Name = "APIBusinessHub"; /* this.before('READ', 'Orders', async (req) => { const { SELECT } = req.query SELECT.columns = SELECT.columns.filter(c => !(c.expand && c.ref[0] === 'EPMBusinessPartner')) }) this.after('READ', 'Orders', async (results, req) => { const { EPMBusinessPartners } = this.entities const $expand = req._.odataReq.getQueryOptions() && req._.odataReq.getQueryOptions().$expand || '' const result = results[0] || {} const entityRE = new RegExp(/([a-zA-Z]+)(?=(\(|$))/g) if ($expand){ if($expand.match(entityRE).includes('EPMBusinessPartner')) { if('businessPartner' in result) { var jwt = getJWT(req) try{ debugger; const epmSuppliers = await Suppliers .requestBuilder() .getAll() .filter(createFilter(results)) .execute({ destinationName: destinationName, jwt: jwt}) .then(Suppliers => Suppliers.map(bp => serializeEntity(bp, Suppliers))) results.forEach(order => order.EPMBusinessPartner = SELECT (EPMBusinessPartners.elements) .from (epmSuppliers.find( Suppliers => order.businessPartner === Suppliers.BpId ))) } catch (e) { debugger; console.log("Error: " + e.message) console.log("Stack: " + e.stack) } } } } }) */ this.on("READ", "sdkBusinessPartner", async (req, next) => { var jwt = getJWT(req); try { // Read API Key from Envoronment const apikey = JSON.parse(process.env.destinations).filter( (destination) => destination.name === "APIBusinessHub" )[0].apikey; const businessPartners = await sdkBusinessPartner .requestBuilder() .getAll() .top(2) .withCustomHeaders({ apikey: apikey, }) .execute({ destinationName: destinationS4Name, jwt: jwt }); // console.log("epmSuppliers: " + JSON.stringify(epmSuppliers)) let mappedBusinessPartners = await businessPartners.map((bp) => serializeEntity(bp, sdkBusinessPartner) ); // console.log("mappedSuppliers: " + JSON.stringify(mappedSuppliers)) return mappedBusinessPartners; } catch (e) { console.error("Error: " + e.message); console.log("Stack: " + e.stack); var msgError = { code: "SY002", message: e.message, numericSeverity: 4, }; req.error(msgError); return {}; } }); this.on("READ", "sdkSuppliers", async (req) => { var jwt = getJWT(req); try { const epmSuppliers = await sdkSuppliers .requestBuilder() .getAll() .execute({ destinationName: destinationName, jwt: jwt }); // console.log("epmSuppliers: " + JSON.stringify(epmSuppliers)) let mappedSuppliers = await epmSuppliers.map((bp) => serializeEntity(bp, sdkSuppliers) ); // console.log("mappedSuppliers: " + JSON.stringify(mappedSuppliers)) return mappedSuppliers; } catch (e) { debugger; console.error("Error: " + e.message); console.log("Stack: " + e.stack); } }); this.on("READ", "Suppliers", async (req) => { const tx = externalService.transaction(req); // const cqn = getCQNforREAD(externalSuppliers, req) // const cqn = req.query.SELECT try { let result = await tx.run(req.query); return result; } catch (error) { console.error(error.message); } }); this.on("READ", "Products", async (req) => { const tx = externalService.transaction(req); try { // let result = await tx.run(cqn) console.info(req.query); let result = await tx.run(req.query); return result; } catch (error) { console.error(error.message); if (error.request && error.request._header) { console.error(error.request._header); } req.error(error.message); } }); this.on("READ", "SEPMRA_I_Product_E", async (req) => { const tx = es5Service.transaction(req); try { // let result = await tx.run(cqn) console.info(req.query); let result = await tx.run(req.query); return result; } catch (error) { console.error(error.message); console.error(error.request._header); req.error(error.message); } }); this.on("*", "SEPMRA_C_PD_Product", async (req) => { return sepmraProdService.run(req.query); }); };
//aside selector const aside = document.querySelector('[data-sticky="true"]'), //varibles startScroll = 0; var endScroll = window.innerHeight - aside.offsetHeight -500, currPos = window.scrollY, screenHeight = window.innerHeight, asideHeight = aside.offsetHeight; aside.style.top = startScroll + 'px'; //check height screen and aside on resize window.addEventListener('resize', ()=>{ screenHeight = window.innerHeight; asideHeight = aside.offsetHeight; }); //main function document.addEventListener('scroll', () => { endScroll = window.innerHeight - aside.offsetHeight; let asideTop = parseInt(aside.style.top.replace('px;', '')); if(asideHeight>screenHeight){ if (window.scrollY < currPos) { //scroll up if (asideTop < startScroll) { aside.style.top = (asideTop + currPos - window.scrollY) + 'px'; } else if (asideTop >= startScroll && asideTop != startScroll) { aside.style.top = startScroll + 'px'; } } else { //scroll down if (asideTop > endScroll) { aside.style.top = (asideTop + currPos - window.scrollY) + 'px'; } else if (asideTop < (endScroll) && asideTop != endScroll) { aside.style.top = endScroll + 'px'; } } }else{ aside.style.top = startScroll + 'px'; } currPos = window.scrollY; }, { capture: true, passive: true }); const links = document.querySelectorAll(".nav-link"); links.forEach(link => { link.addEventListener("click",()=>{ links.forEach(link=>{ link.classList.remove("active"); }) link.classList.add("active"); console.log(link.textContent); }); }) const hamMenu = document.querySelector("#ham-menu"); hamMenu.addEventListener('click',()=>{ document.querySelector("nav ul").classList.toggle("active"); });
class Ressource { // Constructor constructor(level, display_name, count, base_cost, current_cost, unlocked) { this.level = level; this.display_name = display_name; this.count = count; this.base_cost = base_cost; this.current_cost = current_cost; this.multiplier = new Multiplier(1, 10000, 10000); this.autobuyer = null; this.unlocked = unlocked; } compute_next_cost() { this.current_cost = Math.floor(this.base_cost * Math.pow(1.5, this.count)); } } class Multiplier { constructor(value, base_cost, current_cost) { this.value = value; this.base_cost = base_cost; this.current_cost = current_cost; } compute_next_cost() { this.current_cost = Math.floor(this.base_cost * Math.pow(100, this.value)); } } class Autobuyer { constructor(count, base_cost, current_cost) { this.count = count; this.base_cost = base_cost; this.current_cost = current_cost; this.multiplier = 1; } compute_next_cost() { this.current_cost = Math.floor(this.base_cost * Math.pow(1.5, this.count)); } } class Engine { constructor(interval) { this.interval = interval; this.ress = []; this.nb_units = 10; console.log("Engine created"); } init() { _this.ress.push(new Ressource(1, "cursors", 0, 10, 10, true)); _this.ress.push(new Ressource(2, "meta_cursors", 0, 100, 100, false)); _this.ress.push(new Ressource(3, "meta_meta_cursors", 0, 1000, 1000, false)); } set_names(names) { // -1 because units are not in ress if (names.length - 1 == _this.ress.length) { for (let i = 0; i < names.length; i++) { if (i == 0) { document.getElementById("lvl_" + String(i)).innerHTML = names[i]; } else { _this.ress[i - 1].display_name = names[i]; document.getElementById("lvl_" + String(i)).innerHTML = names[i]; } } } } add_unit(number_to_add) { _this.nb_units += number_to_add; document.getElementById("lvl_0_count").innerHTML = String(Math.floor(_this.nb_units)); } //TODO: add number_to_add as parameter (check cost etc.) buy(type) { let obj = _this.ress.find(obj => "lvl_" + obj.level === type); if (_this.nb_units >= obj.current_cost) { _this.nb_units -= obj.current_cost; obj.count += 1; document.getElementById("lvl_0_count").innerHTML = String(Math.floor(_this.nb_units)); document.getElementById(type + "_count").innerHTML = String(Math.floor(obj.count)); obj.compute_next_cost(); document.getElementById(type + "_cost").innerHTML = String(Math.floor(obj.current_cost)); } } create(type, number_to_create) { let obj = _this.ress.find(obj => "lvl_" + obj.level === type); obj.count += number_to_create; obj.compute_next_cost(); document.getElementById(type + "_count").innerHTML = String(Math.floor(obj.count)); } check_unlocked() { for (let i = 1; i < _this.ress.length; i++) { if (_this.ress[i].unlocked === false && _this.ress[i - 1].count >= 10) { _this.ress[i].unlocked = true; document.getElementById("lvl_" + _this.ress[i].level + "_row").style.display = 'inline'; } } } update_display() { _this.check_unlocked(); document.getElementById("lvl_0_count").innerHTML = String(Math.floor(_this.nb_units)); for (let obj of _this.ress) { if (obj.unlocked) { document.getElementById("lvl_" + String(obj.level) + "_count").innerHTML = String(Math.floor(obj.count)); document.getElementById("lvl_" + String(obj.level) + "_cost").innerHTML = String(Math.floor(obj.current_cost)); } } } update() { let lvl_1_ref = _this.ress.find(obj => obj.level === 1); _this.add_unit(lvl_1_ref.count * (_this.interval / 1000) * lvl_1_ref.multiplier.value); for (let i = 1; i < _this.ress.length; i++) { _this.create("lvl_" + String(i), _this.ress[i].count * (_this.interval / 1000) * _this.ress[i].multiplier.value); } _this.update_display(); } run() { window.setInterval(_this.update, _this.interval); } } let basic_names = ["units", "cursors", "meta-cursors", "meta-meta-cursors"]; let memory_names = ["bits leaked", "faulty pointer", "un-dereferenced pointers", "out-of-bounds index"]; let eng = new Engine(50); let _this = eng; eng.init(); eng.set_names(memory_names); eng.run();
import React, { useContext } from "react"; import styled from "styled-components"; import context from "../context"; const StyledBackdrop = styled.div` content: ""; z-index: 1; position: fixed; top: 0; bottom: 0; left: 0; right: 0; background-color: rgba(0, 0, 0, 0.5); `; const Backdrop = () => { const { dispatch } = useContext(context); return ( <StyledBackdrop onClick={() => { dispatch({ type: "RESET_POST" }); }} /> ); }; export default Backdrop;
import React, { Component } from 'react'; import { StyleSheet, View, Text, Image, TouchableOpacity, } from 'react-native'; import moment from 'moment'; import CommonStyles from '../common/Styles'; import math from '../config/math'; export default class WMOrderLotterInfo extends Component { static defaultProps = { orderData: { }, wrapStyle: {}, }; // 开奖算法 gotoLotteryAlgorithm = () => { const { orderData, navigation } = this.props; const param = { thirdWinningTime: orderData.thirdWinningTime, thirdWinningNo: orderData.thirdWinningNo, thirdWinningNumber: orderData.thirdWinningNumber, termNumber: orderData.termNumber, userBuyRecord: orderData.maxStake || 0, // 本期参与人次 lotteryNumber: orderData.lotteryNumber, // 中奖编号 }; navigation.navigate('WMLotteryAlgorithm', { lotteryData: param }); } render() { const { orderData, wrapStyle } = this.props; const gzDataList = [ { label: '中奖号码:', value: orderData.lotteryNumber || '暂无', }, { label: '中奖时间:', value: orderData.lotteryTime ? moment(orderData.lotteryTime * 1000).format('YYYY-MM-DD HH:mm') : moment().format('YYYY-MM-DD HH:mm'), }, { label: '时时彩开奖时间:', value: orderData.thirdWinningTime ? moment((orderData.thirdWinningTime) * 1000).format('YYYY-MM-DD HH:mm') : moment().format('YYYY-MM-DD HH:mm'), }, { label: '时时彩开奖期数:', value: orderData.thirdWinningNo || 0, }, { label: '时时彩开奖号码:', value: orderData.thirdWinningNumber || 0, }, ]; return ( <React.Fragment> <View style={[styles.gzWrpa, wrapStyle]}> { gzDataList.map((item, index) => { const bottomBorder = index === gzDataList.length ? null : styles.borderBottom; if (index === 0) { return ( // eslint-disable-next-line react/no-array-index-key <View style={[CommonStyles.flex_start, { paddingTop: 15, paddingBottom: 7.5 }]} key={index}> <Text style={[styles.btmLabel, { width: 112 }]}>{item.label}</Text> <View style={[CommonStyles.flex_between, CommonStyles.flex_1]}> <Text style={[styles.btmLabel, styles.itemValueStyle]}>{item.value}</Text> <TouchableOpacity style={styles.btnWrap} activeOpacity={0.65} onPress={() => { this.gotoLotteryAlgorithm(); }}> <Text style={styles.btnText}>开奖算法</Text> </TouchableOpacity> </View> </View> ); } return ( // eslint-disable-next-line react/no-array-index-key <View style={[CommonStyles.flex_start, { paddingVertical: 7.5 }, (index === gzDataList.length - 1) ? { paddingBottom: 15 } : null]} key={index}> <Text style={[styles.btmLabel, { width: 112 }]}>{item.label}</Text> <Text style={[styles.btmLabel, styles.itemValueStyle]}>{item.value}</Text> </View> ); }) } </View> </React.Fragment> ); } } const styles = StyleSheet.create({ gzWrpa: { backgroundColor: '#fff', margin: 10, marginBottom: 0, borderRadius: 8, paddingHorizontal: 15, }, borderBottom: { borderBottomWidth: 1, borderBottomColor: '#F1F1F1', }, btmLabel: { fontSize: 14, color: '#777', width: 70, }, itemValueStyle: { fontSize: 14, color: '#222', flex: 1, paddingLeft: 10, }, btnWrap: { width: 70, height: 20, borderRadius: 12, borderWidth: 1, borderColor: CommonStyles.globalHeaderColor, backgroundColor: '#fff', }, btnText: { fontSize: 12, textAlign: 'center', color: CommonStyles.globalHeaderColor, lineHeight: 18, }, });
module.exports = (themeVariablesDef, currentVariables) => { const inheritanceMap = Object.entries(themeVariablesDef).reduce((acu, [varName, varDef]) => { if (varDef.extends != null) { acu[varDef.extends] = acu[varDef.extends] || [] acu[varDef.extends].push(varName) } return acu }, {}) const variables = Object.assign({}, currentVariables) Object.entries(inheritanceMap).map(([genericName, vars]) => { vars.forEach((varName) => { if (variables[varName] == null) { variables[varName] = variables[genericName] } }) }) return variables }
const axios = require('axios'); const chalk = require('chalk'); const log = console.log; const baseUrl = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1"; console.log('Random Quotes'); axios.get(baseUrl) .then(x=>{ var content = x.data[0].content; content = content.replace(/(<([^>]+)>)/, " "); log(chalk.blue(content)); }) .catch(function() { console.log('¯\\_(ツ)_/¯'); });
import {List, Map} from 'immutable'; export function setInitialState(){ let state = { rooms: Map() }; return state; }
/*global JSAV, document */ $(document).ready(function() { "use strict"; // TODO: This block can be removed if/when a fixstate function is created // window.JSAV_EXERCISE_OPTIONS.fixmode = "undo"; // ODSA.UTILS.parseURLParams(); JSAV._types.ds.BinaryTree.prototype.insert = function(value) { // helper function to recursively insert var ins = function (node, insval) { var val = node.value(); if (!val || val === "jsavnull") { // no value in node node.value(insval); } else if (val - insval >= 0) { // go left if (node.left()) { ins(node.left(), insval); } else { node.left(insval); } } else { // go right if (node.right()) { ins(node.right(), insval); } else { node.right(insval); } } }; if ($.isArray(value)) { // array of values for (var i = 0, l = value.length; i < l; i++) { ins(this.root(), value[i]); } } else { ins(this.root(), value); } return this; }; var oldfx; function turnAnimationOff() { //save the state of fx.off var oldfx = $.fx.off || false; //turn off the jQuery animations $.fx.off = true; } function restoreAnimationState() { $.fx.off = oldfx; } var bst = {}; bst.turnAnimationOff = turnAnimationOff; bst.restoreAnimationState = restoreAnimationState; window.BST = bst; });
import { AuthService } from "./auth-service/auth-service"; import { FeedService } from "./feed-service/feed-service"; import { ImageService } from "./image-service/image-service"; import { Firebase } from "./firebase/firebase"; export { AuthService, FeedService, ImageService, Firebase }; export const PROVIDERS = [ AuthService, FeedService, ImageService, Firebase, ];
/******************************************************************************* * Project MCMS, all source code and data files except images, * Copyright 2008-2015 Grit-Innovation Software Pvt. Ltd., India * * Permission is granted to Magma Fin Corp. to use and modify as they see fit. *******************************************************************************/ /** * */ function resetCommonCheckBox(){ var elements = document.getElementsByName("selectAll"); var len = elements.length; for(var i=0;i<len;i++) { elements[i].checked = false; } } function resetCheckBoxByName(ch_name){ var elements = document.getElementsByName(ch_name); if(elements!=null){ var len = elements.length; for(var i=0;i<len;i++) { elements[i].checked = false; } } } //on role drop change function displayLocation(){ var roleId=document.getElementById("roleId"); document.getElementById("mutilpleBuckets").style.display="none"; document.getElementById("mutilpleDivisions").style.display="none"; resetCommonCheckBox(); resetCheckBoxByName("branchCode"); resetCheckBoxByName("bucketCode"); resetCheckBoxByName("divCode"); var branchCode = userBranch; var multiselectbr = document.getElementById("isMultiBranchUser"); if(ismultiuser==true){ branchCode = document.getElementById("branchCode").value; } if(userRole=="Branch Administrator" || userRole=="RH" || userRole=="BM 0-90" || userRole=="TM 0-90" || userRole=="SCM 0-90" || userRole=="RBM 0-90"){ if(ismultiuser==true){ loadBranches(); } /*document.getElementById("zoneMultiDiv").style.display="none"; document.getElementById("zoneSingleDiv").style.display="none"; */ if(roleId!=null && roleId.value!="" && roleId.value != 1 && roleId.value != 2 && roleId.value != 33 && roleId.value != 9 && roleId.value != 12 && roleId.value != 13 && roleId.value != 46){ if(roleId.value==7 || roleId.value==5){ document.getElementById("zoneSingleDiv").style.display="block"; document.getElementById("zoneMultiDiv").style.display="none"; document.getElementById("branchMultiDiv").style.display="none"; document.getElementById("branchDiv").style.display="block"; }else{ document.getElementById("zoneSingleDiv").style.display="none"; document.getElementById("zoneMultiDiv").style.display="block"; document.getElementById("branchMultiDiv").style.display="block"; document.getElementById("branchDiv").style.display="none"; } }else{ document.getElementById("zoneSingleDiv").style.display="none"; document.getElementById("zoneMultiDiv").style.display="none"; document.getElementById("branchMultiDiv").style.display="none"; document.getElementById("branchDiv").style.display="none"; } if(roleId!=null && roleId.value!="" && (roleId.value==34 || roleId.value==4 || roleId.value==38 || roleId.value==40 || roleId.value==63)){ if(roleId.value !=4) document.getElementById("mutilpleBuckets").style.display="block"; document.getElementById("mutilpleDivisions").style.display="block"; if(!ismultiuser) DWRUtil.getLocationsByBranch(branchCode,multipleLocationsCallback); } else if(roleId.value!=null && roleId.value!="" && (roleId.value==7 || roleId.value==16 || roleId.value==23 || roleId.value==26 || roleId.value==27 || roleId.value==28 || roleId.value==29 || roleId.value==30 || roleId.value==31 || roleId.value==35 || roleId.value==36 || roleId.value==37 || roleId.value==42 || roleId.value==45 || roleId.value==67)){ if(roleId.value!=7 && roleId.value!=42){ document.getElementById("mutilpleBuckets").style.display="block"; } else{ document.getElementById("mutilpleBuckets").style.display="none"; } document.getElementById("mutilpleDivisions").style.display="none"; if(roleId.value==7 || roleId.value==30 || roleId.value==35){ if(!ismultiuser) DWRUtil.getLocationsByBranch(branchCode,locationCallback); document.getElementById("mutilplelocLocation").style.display="none"; } else{ document.getElementById("priLocDiv").style.display="none"; document.getElementById("mutilplelocLocation").style.display="none"; } } else{ document.getElementById("mutilpleBuckets").style.display="none"; document.getElementById("mutilpleDivisions").style.display="none"; document.getElementById("mutilplelocLocation").style.display="none"; } document.getElementById("priLocDiv").style.display="none"; document.getElementById("catchmentDiv").style.display="none"; document.getElementById("districtDiv").style.display="none"; document.getElementById("subDistrictDiv").style.display="none"; document.getElementById("pincodeDiv").style.display="none"; document.getElementById("localityDiv").style.display="none"; } else if(userRole=="Zonal Administrator" || userRole=="POC Support" || userRole=="Zonal Accountant Admin" ){ document.getElementById("zoneMultiDiv").style.display="none"; if(ismultizoneuser){ document.getElementById("zoneSingleDiv").style.display="block"; }else{ document.getElementById("zoneSingleDiv").style.display="none"; loadBranches(); } if(roleId!=null && roleId.value!="" && (roleId.value==34 || roleId.value==4 || roleId.value==33 || roleId.value==16 || roleId.value==23 || roleId.value==26 || roleId.value==27 || roleId.value==28 || roleId.value==29 || roleId.value==30 || roleId.value==31 || roleId.value==35 || roleId.value==36 || roleId.value==37 || roleId.value==38|| roleId.value==42 || roleId.value==45 || roleId.value==39 || roleId.value==40 || roleId.value==41 || roleId.value==48 || roleId.value==52 || roleId.value==50 ||roleId.value==49 ||roleId.value==51 || roleId.value==58 || roleId.value==60 || roleId.value==57 || roleId.value==59 || roleId.value==63 || roleId.value==65 || roleId.value==67 || roleId.value==68 || roleId.value==69 || roleId.value==74)){ if(roleId.value!=42){ document.getElementById("mutilpleBuckets").style.display="block"; /*if(roleId.value==58 || roleId.value==60){ document.getElementById("mutilpleBuckets").style.display="none"; }*/ } if(roleId.value==34 || roleId.value==4 || roleId.value==33 || roleId.value==38 || roleId.value==39 || roleId.value==40 || roleId.value==41 || roleId.value==48 || roleId.value==58 || roleId.value==60 || roleId.value==63 || roleId.value==65 || roleId.value==68 || roleId.value==69 || roleId.value==74){ document.getElementById("mutilpleDivisions").style.display="block"; } else{ document.getElementById("mutilpleDivisions").style.display="none"; } if(roleId.value!=33 && roleId.value!=65){ if(!ismultizoneuser) loadBranches(); } else{ /*document.getElementById("branchMultiDiv").style.display="none"; document.getElementById("branchDiv").style.display="none";*/ document.getElementById("mutilplelocLocation").style.display="none"; document.getElementById("priLocDiv").style.display="none"; document.getElementById("catchmentDiv").style.display="none"; document.getElementById("districtDiv").style.display="none"; document.getElementById("subDistrictDiv").style.display="none"; document.getElementById("pincodeDiv").style.display="none"; document.getElementById("localityDiv").style.display="none"; } } else{ /*document.getElementById("branchMultiDiv").style.display="none"; document.getElementById("branchDiv").style.display="none";*/ document.getElementById("mutilpleBuckets").style.display="none"; document.getElementById("mutilpleDivisions").style.display="none"; document.getElementById("mutilplelocLocation").style.display="none"; if(roleId.value==64){ document.getElementById("mutilpleBuckets").style.display="block"; } if(!ismultizoneuser) loadBranches(); } if(roleId!=null && roleId.value!="" && roleId.value != 1 && roleId.value != 2 && roleId.value != 33 && roleId.value != 46 && roleId.value != 52 && roleId.value != 60 && roleId.value != 61 && roleId.value != 62 && roleId.value!=65 && roleId.value!=66 && roleId.value!=73){ if(roleId.value==7 || roleId.value==5){ document.getElementById("zoneSingleDiv").style.display="block"; document.getElementById("zoneMultiDiv").style.display="none"; document.getElementById("branchMultiDiv").style.display="none"; document.getElementById("branchDiv").style.display="block"; document.getElementById("regionMultiDiv").style.display="none"; }else{ document.getElementById("zoneSingleDiv").style.display="none"; document.getElementById("zoneMultiDiv").style.display="block"; document.getElementById("branchMultiDiv").style.display="block"; document.getElementById("branchDiv").style.display="none"; if(roleId.value == 70 || roleId.value == 71 || roleId.value == 72){ resetCheckBoxByName("zoneCode"); document.getElementById("regionMultiDiv").style.display="none"; document.getElementById("branchMultiDiv").style.display="none"; } } }else{ document.getElementById("zoneSingleDiv").style.display="none"; document.getElementById("zoneMultiDiv").style.display="none"; document.getElementById("branchMultiDiv").style.display="none"; document.getElementById("branchDiv").style.display="none"; document.getElementById("regionMultiDiv").style.display="none"; } } else if(userRole=="TL F&F" || userRole=="Regional F&F" || userRole=="Zonal F&F" || userRole=="National F&F" ){ if(roleId!=null && roleId.value!="" && ( roleId.value==49 || roleId.value==50 || roleId.value==51 || roleId.value==35 || roleId.value==36 || roleId.value==37 || roleId.value==67 )){ document.getElementById("mutilpleBuckets").style.display="block"; document.getElementById("zoneSingleDiv").style.display="none"; document.getElementById("zoneMultiDiv").style.display="block"; document.getElementById("branchMultiDiv").style.display="block"; document.getElementById("branchDiv").style.display="none"; document.getElementById("priLocDiv").style.display="none"; } else { document.getElementById("zoneSingleDiv").style.display="none"; document.getElementById("zoneMultiDiv").style.display="none"; document.getElementById("branchMultiDiv").style.display="none"; document.getElementById("branchDiv").style.display="none"; } if(roleId!=null && roleId.value!="" && ( roleId.value==38 )){ document.getElementById("mutilpleBuckets").style.display="block"; document.getElementById("zoneMultiDiv").style.display="block"; document.getElementById("branchMultiDiv").style.display="block"; document.getElementById("mutilpleDivisions").style.display="block"; } if(roleId!=null && roleId.value!="" && ( roleId.value==7 )){ document.getElementById("zoneSingleDiv").style.display="block"; document.getElementById("branchDiv").style.display="block"; document.getElementById("zoneCode").value = ''; document.getElementById("branchCode").value = ''; } document.getElementById("priLocDiv").style.display="none"; document.getElementById("catchmentDiv").style.display="none"; document.getElementById("districtDiv").style.display="none"; document.getElementById("subDistrictDiv").style.display="none"; document.getElementById("pincodeDiv").style.display="none"; document.getElementById("localityDiv").style.display="none"; } else{ if(roleId!=null && roleId.value!="" && (roleId.value==33 || roleId.value==52 || roleId.value==65)){ document.getElementById("mutilpleBuckets").style.display="block"; document.getElementById("mutilpleDivisions").style.display="block"; /*document.getElementById("zoneMultiDiv").style.display="none"; document.getElementById("zoneSingleDiv").style.display="none";*/ } else if(roleId!=null && roleId.value!="" && (roleId.value==13 ||roleId.value==46 || roleId.value==12 || roleId.value==9 ||roleId.value==61 || roleId.value==62 || roleId.value==66 || roleId.value==73)){ /*document.getElementById("zoneMultiDiv").style.display="none"; document.getElementById("zoneSingleDiv").style.display="none";*/ document.getElementById("mutilpleBuckets").style.display="none"; document.getElementById("mutilpleDivisions").style.display="none"; }else if(roleId!=null && roleId.value==60){ document.getElementById("mutilpleDivisions").style.display="block"; } else if(roleId!=null && roleId.value!="" && (roleId.value==3 || roleId.value==47 || roleId.value==8 || roleId.value==10 || roleId.value==51 || roleId.value==59 || roleId.value==64)){ var zoneCode = document.getElementById("zoneCode").value; if(zoneCode!=null) { var elements = document.forms[0].elements; checkedItemCount=0; for(var i=0;i<elements.length;i++) { if(elements[i].type=="checkbox") { elements[i].checked=false; } } } mygrid3.clearAll(); mygrid3.parse(myData,"jsarray"); if(roleId.value==3 || roleId.value==51 || roleId.value==64){ document.getElementById("mutilpleBuckets").style.display="block"; document.getElementById("mutilpleDivisions").style.display="block"; }else if(roleId!=null && roleId.value==59){ document.getElementById("mutilpleDivisions").style.display="block"; } } else{ document.getElementById('zoneCode').getElementsByTagName('option')[0].selected = 'selected'; document.getElementById("zoneMultiDiv").style.display="block"; document.getElementById("zoneSingleDiv").style.display="none"; if(roleId!=null && roleId.value!="" && (roleId.value==4 || roleId.value==48|| roleId.value==34 || roleId.value==38 || roleId.value==39 || roleId.value==40 || roleId.value==41 || roleId.value==50 || roleId.value==63 || roleId.value==68 || roleId.value==69 || roleId.value==74)){ document.getElementById("mutilpleBuckets").style.display="block"; document.getElementById("mutilpleDivisions").style.display="block"; } else if(roleId!=null && roleId.value!="" && (roleId.value==16 || roleId.value==23 || roleId.value==26 || roleId.value==27 || roleId.value==28 || roleId.value==29 || roleId.value==30 || roleId.value==31 || roleId.value==35 || roleId.value==36 || roleId.value==37 || roleId.value==45 || roleId.value==49 || roleId.value==67)){ document.getElementById("mutilpleBuckets").style.display="block"; }else if(roleId!=null && roleId.value==58){ document.getElementById("mutilpleDivisions").style.display="block"; } } if(roleId.selectedIndex==0){ document.getElementById("zoneSingleDiv").style.display="none"; } if(roleId!=null && roleId.value!="" && roleId.value != 1 && roleId.value != 2 && roleId.value != 9 && roleId.value != 12 && roleId.value != 13 && roleId.value != 33 && roleId.value != 46 && roleId.value != 52 && roleId.value != 53 && roleId.value != 60 && roleId.value != 61 && roleId.value!=62 && roleId.value!=65 && roleId.value!=66 && roleId.value!=73){ if(roleId.value==7 || roleId.value==5){ document.getElementById("zoneSingleDiv").style.display="block"; document.getElementById("zoneMultiDiv").style.display="none"; document.getElementById("branchMultiDiv").style.display="none"; document.getElementById("branchDiv").style.display="block"; document.getElementById("regionMultiDiv").style.display="none"; }else{ document.getElementById("zoneSingleDiv").style.display="none"; document.getElementById("zoneMultiDiv").style.display="block"; document.getElementById("branchMultiDiv").style.display="block"; document.getElementById("branchDiv").style.display="none"; if(roleId.value == 70 || roleId.value == 71 || roleId.value == 72){ resetCheckBoxByName("zoneCode"); document.getElementById("regionMultiDiv").style.display="none"; document.getElementById("branchMultiDiv").style.display="none"; } } }else{ document.getElementById("zoneSingleDiv").style.display="none"; document.getElementById("zoneMultiDiv").style.display="none"; document.getElementById("branchMultiDiv").style.display="none"; document.getElementById("branchDiv").style.display="none"; document.getElementById("regionMultiDiv").style.display="none"; } if(roleId!=null && roleId.value!="" && (roleId.value==57 || roleId.value==58 || roleId.value==59 || roleId.value==60)){ document.getElementById("mutilpleBuckets").style.display="block"; } if(roleId!=null && roleId.value!="" && (roleId.value == 70 || roleId.value == 71 || roleId.value == 72)){ if(formMode == 'NEW'){ document.getElementById("branchMultiDiv").style.display="none"; document.getElementById("branchDiv").style.display="none"; } } document.getElementById("mutilplelocLocation").style.display="none"; // document.getElementById("locDiv").style.display="none"; document.getElementById("priLocDiv").style.display="none"; document.getElementById("catchmentDiv").style.display="none"; document.getElementById("districtDiv").style.display="none"; document.getElementById("subDistrictDiv").style.display="none"; document.getElementById("pincodeDiv").style.display="none"; document.getElementById("localityDiv").style.display="none"; } if(roleId!=null && (roleId.value=='49' || roleId.value=='50' || roleId.value=='51' || roleId.value=='52')){ document.getElementById("mutilpleDivisions").style.display="none"; } } // on zone change function loadBranches(){ var roleId=document.getElementById("roleId"); var zoneCodeId=document.getElementById("zoneCode"); resetCommonCheckBox(); if(userRole!=null && userRole!="" && (userRole=="Zonal Administrator" || userRole=="Zonal Accountant Admin")){ var zoneCode=userZone; if(ismultizoneuser){ zoneCode = document.getElementById("zoneCode").value; } /*if(roleId!=null && roleId.value!="" && (roleId.value==5 || roleId.value==7 || roleId.value==30 || roleId.value==34)){ document.getElementById("branchMultiDiv").style.display="none"; document.getElementById("branchDiv").style.display="block"; DWRUtil.getBranchesByZone(zoneCode,branchCallback); } else if(roleId!=null && roleId.value!="" && (roleId.value==3 || roleId.value==4 || roleId.value==48 || roleId.value==11 || roleId.value==14|| roleId.value==35 || roleId.value==38 || roleId.value==16 || roleId.value==23 || roleId.value==26 || roleId.value==27 || roleId.value==28 || roleId.value==29 || roleId.value==31 || roleId.value==36 || roleId.value==37 || roleId.value==42 || roleId.value==45 || roleId.value==39 || roleId.value==40 || roleId.value==41 )){ document.getElementById("branchMultiDiv").style.display="block"; document.getElementById("branchDiv").style.display="none"; DWRUtil.getBranchesByZone(zoneCode,branchGridCallback); }*/ if(roleId!=null && roleId.value!="" && roleId.value != 1 && roleId.value != 2 && roleId.value != 9 && roleId.value != 12 && roleId.value != 13 && roleId.value != 33 && roleId.value != 46){ if(roleId.value==7 || roleId.value==5){ document.getElementById("branchMultiDiv").style.display="none"; document.getElementById("branchDiv").style.display="block"; DWRUtil.getBranchesByZone(zoneCode,branchCallback); }else{ document.getElementById("branchMultiDiv").style.display="block"; document.getElementById("branchDiv").style.display="none"; DWRUtil.getBranchesByZone(zoneCode,branchGridCallback); } }else{ document.getElementById("branchMultiDiv").style.display="none"; document.getElementById("branchDiv").style.display="none"; } }else if(userRole=="Branch Administrator" || userRole=="BM 0-90" || userRole=="TM 0-90" || userRole=="SCM 0-90" || userRole=="RBM 0-90" || userRole=="RH"){ if(roleId!=null && roleId.value!="" && (roleId.value==35 || roleId.value==27 || roleId.value==28)) { var div = document.getElementById("multiBranch"); if(div!=null){ document.getElementById("multiBranch").style.display="block"; } document.getElementById("branchMultiDiv").style.display="block"; document.getElementById("branchDiv").style.display="none"; loadUserBranches(); }else{ document.getElementById("branchMultiDiv").style.display="none"; document.getElementById("branchDiv").style.display="block"; var zoneCode=document.getElementById("zoneCode").value; if(roleId.value==7){ DWRUtil.getBranchesByZone(zoneCode,branchCallback); } } } else{ var zoneCode=document.getElementById("zoneCode").value; if(roleId!=null && roleId.value!="" && (roleId.value==5 || roleId.value==7 || roleId.value==30 || roleId.value==34 )){ if(zoneCodeId.selectedIndex==0) { document.getElementById("branchMultiDiv").style.display="none"; document.getElementById("branchDiv").style.display="none"; } else { document.getElementById("branchMultiDiv").style.display="none"; document.getElementById("branchDiv").style.display="block"; DWRUtil.getBranchesByZone(zoneCode,branchCallback); } } else if(roleId!=null && roleId.value!="" && (roleId.value==3 || roleId.value==35|| roleId.value==38 || roleId.value==4|| roleId.value==48 || roleId.value==11 || roleId.value==14 || roleId.value==16 || roleId.value==23 || roleId.value==26 || roleId.value==27 || roleId.value==28 || roleId.value==29 || roleId.value==31 || roleId.value==36 || roleId.value==37 || roleId.value==42 || roleId.value==45|| roleId.value==39 || roleId.value==40 || roleId.value==41 || roleId.value==49 || roleId.value==50 || roleId.value==51 || roleId.value==52 || roleId.value==67 || roleId.value==68 || roleId.value==69)){ if(zoneCodeId.selectedIndex==0) { document.getElementById("branchMultiDiv").style.display="none"; document.getElementById("branchDiv").style.display="none"; } else { document.getElementById("branchMultiDiv").style.display="block"; document.getElementById("branchDiv").style.display="none"; DWRUtil.getBranchesByZone(zoneCode,branchGridCallback); } } } document.getElementById("mutilplelocLocation").style.display="none"; document.getElementById("priLocDiv").style.display="none"; document.getElementById("catchmentDiv").style.display="none"; document.getElementById("districtDiv").style.display="none"; document.getElementById("subDistrictDiv").style.display="none"; document.getElementById("pincodeDiv").style.display="none"; document.getElementById("localityDiv").style.display="none"; loadLocations(); } function loadUserBranches(){ mygrid4.clearAll(); mygrid4.parse(userbranchFormulti,"jsarray"); } function doSelectZone(zone_id){ var roleId=document.getElementById("roleId"); var elements = document.getElementsByName("zoneCode"); var zones=""; var len = elements.length; for(var i=0;i<len;i++){ if(elements[i].checked){ if(elements[i].value!=null && elements[i].value!='') zones = zones + elements[i].value+','; } } if(roleId.value!=7 && roleId.value!=1 && roleId.value!=2 && roleId.value!=9 && roleId.value!=12 && roleId.value!=13 && roleId.value!=46 && roleId.value!=5){ if(roleId.value == 70 || roleId.value == 71 || roleId.value == 72){ if(zones != ""){ document.getElementById("regionMultiDiv").style.display="block"; }else{ resetCommonCheckBox(); document.getElementById("regionMultiDiv").style.display="none"; document.getElementById("branchMultiDiv").style.display="none"; } DWRUtil.getRegionsByMultipleZones(zones,regionGridCallback); }else{ document.getElementById("branchMultiDiv").style.display="block"; DWRUtil.getBranchesByMultipleZones(zones,branchGridCallback); } }else{ document.getElementById("branchMultiDiv").style.display="none"; } } function branchCallback(data) { if(data!=null) { var branches = document.getElementById("branchCode"); var len = data.length; branches.options.length = 0; branches.options[0]= new Option("Select Branch",""); for(var i=0;i<len;i++) { branches.options[branches.options.length]= new Option(data[i].substr(data[i].indexOf("$")+1),data[i].substr(0,data[i].indexOf("$"))); } } } function branchGridCallback(data) { if(data!=null) { // Get all the branches at the instance and filter only the checked ones var branch_div = document.getElementsByName("branchCode"); var no_of_branches = branch_div.length; var checked_branches = new Array(); for(var i=0;i<no_of_branches;i++){ if(branch_div[i].checked){ if(branch_div[i].value!=null && branch_div[i].value!=''){ checked_branches.push(branch_div[i].value.trim()); } } } // check the branches, if they are already checked. var len = data.length; var myData = new Array(); var j=0; for(var i=0;i<len;i++){ myData[j]=new Array(); var valid_branch_code = data[i].substr(0,data[i].indexOf("$")); if (checked_branches.indexOf(valid_branch_code) > -1) { myData[j][0]='<INPUT TYPE="checkbox" NAME="branchCode" onclick="doSelectBranch(this)" id="branchCode" value="'+data[i].substr(0,data[i].indexOf("$"))+'" checked>'; } else { myData[j][0]='<INPUT TYPE="checkbox" NAME="branchCode" onclick="doSelectBranch(this)" id="branchCode" value="'+data[i].substr(0,data[i].indexOf("$"))+'">'; } myData[j][1]=data[i].substr(data[i].indexOf("$")+1); j++; } mygrid4.clearAll(); mygrid4.parse(myData,"jsarray"); } } function loadlocfrommultiBranch(branches){ var roleId=document.getElementById("roleId"); document.getElementById("priLocDiv").style.display="none"; document.getElementById("mutilplelocLocation").style.display="none"; document.getElementById("catchmentDiv").style.display="none"; document.getElementById("districtDiv").style.display="none"; document.getElementById("subDistrictDiv").style.display="none"; document.getElementById("pincodeDiv").style.display="none"; document.getElementById("localityDiv").style.display="none"; resetCommonCheckBox(); DWRUtil.getLocationsByBranch(branches,locationCallback); } function loadlocfrommultiBranchTC(branches){ var roleId=document.getElementById("roleId"); document.getElementById("priLocDiv").style.display="none"; document.getElementById("mutilplelocLocation").style.display="none"; document.getElementById("catchmentDiv").style.display="none"; document.getElementById("districtDiv").style.display="none"; document.getElementById("subDistrictDiv").style.display="none"; document.getElementById("pincodeDiv").style.display="none"; document.getElementById("localityDiv").style.display="none"; //resetCommonCheckBox(); DWRUtil.getLocationsByBranch(branches,locationCallback); } var locationData; function locationCallback(data) { if(data!=null) { locationData = data; var roleId=document.getElementById("roleId"); if(roleId!=null && roleId.value!="" && (roleId.value==5 || roleId.value==7 || roleId.value==30 || roleId.value==35|| roleId.value==55)) { document.getElementById("priLocDiv").style.display="block"; } var locations = document.getElementById("primaryLocCode"); var len = data.length; locations.options.length = 0; locations.options[0]= new Option("Select Location",""); for(var i=0;i<len;i++) { locations.options[locations.options.length]= new Option(data[i].substr(data[i].indexOf("$")+1),data[i].substr(0,data[i].indexOf("$"))); } } } function multipleLocationsCallback(data) { var roleId = document.getElementById("roleId"); if(roleId.value==54) document.getElementById("priLocDiv").style.display="block"; if(data!=null) { var locations = document.getElementById("primaryLocCode"); document.getElementById("mutilplelocLocation").style.display="block"; if(roleId.value==54) document.getElementById("span_text").innerHTML="Deposit To Locations"; else document.getElementById("span_text").innerHTML="Locations"; var len = data.length; var j=0; var myData = new Array(); for(var i=0;i<len;i++) { if(locations!=data[i].substr(0,data[i].indexOf("$"))) { myData[j]=new Array(); myData[j][0]='<INPUT TYPE="checkbox" NAME="locCode" id="locCode" value="'+data[i].substr(0,data[i].indexOf("$"))+'">'; myData[j][1]=data[i].substr(data[i].indexOf("$")+1); j++; } } mygrid5.clearAll(); mygrid5.parse(myData,"jsarray"); } } //primary location change function loadDepositLocations() { var selectedPrimaryLoc = document.getElementById("primaryLocCode").value; var roleId=document.getElementById("roleId"); if(locationData!=null) { if(roleId!=null && roleId.value!="" && (roleId.value==5 || roleId.value==6)) { var locations = document.getElementById("primaryLocCode"); if(locations.selectedIndex==0) { document.getElementById("mutilplelocLocation").style.display="none"; } else { document.getElementById("mutilplelocLocation").style.display="block"; document.getElementById("span_text").innerHTML="Deposit To Locations" var len = locationData.length; var myData = new Array(); var j=0; for(var i=0;i<len;i++) { if(selectedPrimaryLoc!=locationData[i].substr(0,locationData[i].indexOf("$"))) { myData[j]=new Array(); myData[j][0]='<INPUT TYPE="checkbox" NAME="locCode" id="locCode" value="'+locationData[i].substr(0,locationData[i].indexOf("$"))+'">'; myData[j][1]=locationData[i].substr(locationData[i].indexOf("$")+1); j++; } } mygrid5.clearAll(); mygrid5.parse(myData,"jsarray"); } } else if(roleId!=null && roleId.value!="" && roleId.value==7) { var locations = document.getElementById("primaryLocCode"); if(locations.selectedIndex==0) { document.getElementById("catchmentDiv").style.display="none"; document.getElementById("districtDiv").style.display="none"; document.getElementById("subDistrictDiv").style.display="none"; document.getElementById("pincodeDiv").style.display="none"; document.getElementById("localityDiv").style.display="none"; } else { loadCatchementAreas(); loadDistricts(); } } } else if(selectedPrimaryLoc!=null && selectedPrimaryLoc!="" && roleId!=null && roleId.value!="" && roleId.value==7) { loadCatchementAreas(); loadDistricts(); } } function loadCatchementAreas() { var roleId=document.getElementById("roleId"); if(roleId!=null && roleId.value!="" && roleId.value==7) { var locCode = document.getElementById("primaryLocCode").value; DWRUtil.getCatchmentAreasByLocation(locCode,caCallback); } } function caCallback(data) { if(data!=null) { document.getElementById("catchmentDiv").style.display="block"; document.getElementById("catchment").checked=false; var len = data.length; var myData = new Array(); for(var i=0;i<len;i++) { myData[i]=new Array(); myData[i][0]='<INPUT TYPE="checkbox" NAME="caCode" id="caCode" value="'+data[i].substr(0,data[i].indexOf("$"))+'">'; myData[i][1]=data[i].substr(data[i].indexOf("$")+1); } mygrid2.clearAll(); mygrid2.parse(myData,"jsarray"); } } function loadDistricts() { document.getElementById("subDistrictDiv").style.display="none"; document.getElementById("pincodeDiv").style.display="none"; document.getElementById("localityDiv").style.display="none"; document.getElementById("districtDiv").style.display="none"; var roleId=document.getElementById("roleId"); if(roleId!=null && roleId.value!="" && roleId.value==7) { var locCode = document.getElementById("primaryLocCode").value; DWRUtil.getMultipleDistrictsByLocation(locCode,districtCallback); } } function districtCallback(data) { document.getElementById("subDistrictDiv").style.display="none"; document.getElementById("pincodeDiv").style.display="none"; document.getElementById("localityDiv").style.display="none"; document.getElementById("districtDiv").style.display="block"; document.getElementById("district").checked=false; if(data!=null) { document.getElementById("districtDiv").style.display="block"; var len = data.length; var myData = new Array(); for(var i=0;i<len;i++) { var district = data[i].substr(0,data[i].indexOf("$")); myData[i]=new Array(); myData[i][0]='<INPUT TYPE="checkbox" NAME="dataObject.districtCode" id="dataObject.districtCode" onclick="doSelectDistrict(this)" value="' +district+ '" > '; myData[i][1]=data[i].substr(data[i].indexOf("$")+1); } mygrid11.clearAll();//clear districts mygrid11.parse(myData,"jsarray"); } } function doSelectBranch(){ var roleId=document.getElementById("roleId"); var elements = document.getElementsByName("branchCode"); var branches=""; //resetCommonCheckBox(); loadLocations(); var len = elements.length; for(var i=0;i<len;i++) { if(elements[i].checked){ if(elements[i].value!=null && elements[i].value!=''){ branches=branches + elements[i].value+','; } } } if(roleId.value==35 || roleId.value==55){ if(branches=="" || branches==null){ document.getElementById("priLocDiv").style.display="none"; }else{ document.getElementById("priLocDiv").style.display="block"; loadlocfrommultiBranch(branches); } } else if(branches=="" || branches==null){ document.getElementById("mutilplelocLocation").style.display="none"; } else if(roleId.value==4|| roleId.value==48 || roleId.value==39 ||roleId.value==42 || roleId.value==40 || roleId.value==41 || roleId.value==58 || roleId.value==63){ DWRUtil.getLocationsByMultipleBranchs(branches,multipleLocationsCallback); } else if(roleId.value==54) { DWRUtil.getLocationsByMultipleBranchs(branches,multipleLocationsCallback); document.getElementById("priLocDiv").style.display="block"; loadlocfrommultiBranch(branches); } } //on branch change function loadLocations() { var roleId=document.getElementById("roleId"); document.getElementById("priLocDiv").style.display="none"; document.getElementById("mutilplelocLocation").style.display="none"; document.getElementById("catchmentDiv").style.display="none"; document.getElementById("districtDiv").style.display="none"; document.getElementById("subDistrictDiv").style.display="none"; document.getElementById("pincodeDiv").style.display="none"; document.getElementById("localityDiv").style.display="none"; var branchCodeId=document.getElementById("branchCode"); if(branchCodeId.selectedIndex==0) { document.getElementById("priLocDiv").style.display="none"; document.getElementById("mutilplelocLocation").style.display="none"; } else { if(roleId!=null && roleId.value!="" && (roleId.value==5 || roleId.value==7 || roleId.value==30 || roleId.value==35)) { var branchCode = document.getElementById("branchCode").value; DWRUtil.getLocationsByBranch(branchCode,locationCallback); } else if(roleId!=null && roleId.value!="" && (roleId.value==34)){ var branchCode = document.getElementById("branchCode").value; DWRUtil.getLocationsByBranch(branchCode,multipleLocationsCallback); } } } function doSave(){ try{ var fORMSUBMITFLAG = false; var roleId=document.getElementById("roleId"); var caCodeId=document.getElementById("caCode"); var userStatId=document.getElementById("userStatusId"); var branchCodeId=document.getElementById("branchCode"); var primaryLocCode=document.getElementById("primaryLocCode"); var locCodeId=document.getElementById("locCode"); var zoneCodeId=document.getElementById("zoneCode"); var districtId = document.getElementById("dataObject.districtCode"); var subDistrictId=document.getElementById("dataObject.subDistrictCode"); var pincodeId=document.getElementById("dataObject.pincode"); var localityCodeId=document.getElementById("dataObject.localityCode"); if(roleId.selectedIndex!=0){ if(userRole=="Branch Administrator"|| userRole=="RH" || userRole=="TM 0-90" || userRole=="SCM 0-90" || userRole=="RBM 0-90"){ if(roleId!=null && roleId.value!="" && (roleId.value==42 || roleId.value==34 || roleId.value==38 || roleId.value==40)){ if(checkCheckBoxs("locCode")){ alert("Location is mandatory"); fORMSUBMITFLAG=false; return false; } else if(checkCheckBoxs("bucketCode")){ alert("Module Type is mandatory"); fORMSUBMITFLAG=false; return false; } else if(checkCheckBoxs("divCode")){ alert("Division is mandatory"); fORMSUBMITFLAG=false; return false; } } else if(roleId!=null && roleId.value!="" && (roleId.value==16 || roleId.value==23 || roleId.value==26 || roleId.value==27 || roleId.value==28 || roleId.value==29 || roleId.value==30 || roleId.value==31 || roleId.value==35 || roleId.value==36 || roleId.value==37 || roleId.value==45 || roleId.value==67)){ if(checkCheckBoxs("bucketCode")){ alert("Module Type is mandatory"); fORMSUBMITFLAG=false; return false; } if(ismultiuser && roleId.value==35){ if(checkCheckBoxs("branchCode")){ alert("Branch Code mandatory"); fORMSUBMITFLAG=false; return false; } } // if(checkCheckBoxs("branchCode")){ alert("Territory is mandatory"); FORMSUBMITFLAG=false; return false; } // } else if(roleId!=null && roleId.value!="" && (roleId.value==7)){ if(zoneCodeId.selectedIndex==0){ zoneCodeId.style.backgroundColor='#FFD9D9'; zoneCodeId.focus(); fORMSUBMITFLAG=false; return false; } if(branchCodeId.selectedIndex==0){ branchCodeId.style.backgroundColor='#FFD9D9'; branchCodeId.focus(); fORMSUBMITFLAG=false; return false; } if(primaryLocCode) { if(primaryLocCode.selectedIndex==0 ||primaryLocCode.selectedIndex==-1) { primaryLocCode.style.backgroundColor='#FFD9D9'; primaryLocCode.focus(); fORMSUBMITFLAG=false; return false; } } if(checkCheckBoxs("caCode")){ caCodeId.style.backgroundColor='#FFD9D9'; caCodeId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.districtCode")){ districtId.style.backgroundColor='#FFD9D9'; districtId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.subDistrictCode")) { subDistrictId.style.backgroundColor='#FFD9D9'; subDistrictId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.pincode")) { pincodeId.style.backgroundColor='#FFD9D9'; pincodeId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.localityCode")) { localityCodeId.style.backgroundColor='#FFD9D9'; localityCodeId.focus(); fORMSUBMITFLAG=false; return false; } } else if((roleId!=null && roleId.value!="") && (roleId.value==63)){ if(checkCheckBoxs("zoneCode")){ alert("Zone is mandatory"); fORMSUBMITFLAG=false; return false; } else if(checkCheckBoxs("branchCode")){ alert("Territory is mandatory"); FORMCONFIRMFLAG=false; return false; } else if(checkCheckBoxs("divCode")){ alert("Division is mandatory"); fORMSUBMITFLAG=false; return false; } else if(checkCheckBoxs("bucketCode")){ alert("Module Type is mandatory"); fORMSUBMITFLAG=false; return false; } } } else if(userRole=="POC Support" || userRole=="HO Administrator" || userRole=="Zonal Administrator" || userRole=="Zonal Accountant Admin" || userRole=="Super Administrator" || userRole=="National Head"){ if(roleId!=null && roleId.value!="" && (roleId.value==3 || roleId.value==4 || roleId.value==48|| roleId.value==34 || roleId.value==38 || roleId.value==39 || roleId.value==40 || roleId.value==41 || roleId.value==68 || roleId.value==69 || roleId.value==74)){ if(checkCheckBoxs("branchCode")){ alert("Territory is mandatory"); FORMCONFIRMFLAG=false; return false; } else if(checkCheckBoxs("divCode")){ alert("Division is mandatory"); fORMSUBMITFLAG=false; return false; } else if(checkCheckBoxs("bucketCode")){ alert("Module Type is mandatory"); fORMSUBMITFLAG=false; return false; } } if(roleId!=null && roleId.value!="" && (roleId.value==16 || roleId.value==23 || roleId.value==26 || roleId.value==27 || roleId.value==28 || roleId.value==29 || roleId.value==30 || roleId.value==31 || roleId.value==35 || roleId.value==36 || roleId.value==37 || roleId.value==45 || roleId.value==49 || roleId.value==50 || roleId.value==51 || roleId.value==52 || roleId.value==67)){ if(checkCheckBoxs("bucketCode")){ alert("Module Type is mandatory"); fORMSUBMITFLAG=false; return false; } } if(roleId!=null && roleId.value!="" && (roleId.value==8 || roleId.value==10 || roleId.value==3 || roleId.value==47 || roleId.value==51) && userRole!="HO Administrator" && userRole!="Super Administrator" && userRole!="Zonal Administrator" && userRole!="POC Support"){ if(checkCheckBoxs("zoneCode")){ alert("Zone is mandatory"); fORMSUBMITFLAG=false; return false; } } if(roleId!=null && roleId.value!="" && userRole!="HO Administrator" && userRole!="Super Administrator" && userRole!="Zonal Administrator" && userRole!="Zonal Accountant Admin" && userRole!="POC Support" && (roleId.value==4 || roleId.value==5 || roleId.value==7 || roleId.value==11 || roleId.value==14 || roleId.value==16 || roleId.value==23 || roleId.value==26 || roleId.value==27 || roleId.value==28 || roleId.value==29 || roleId.value==30 || roleId.value==31 || roleId.value==34 || roleId.value==35 || roleId.value==36 || roleId.value==37 || roleId.value==38 || roleId.value==39 || roleId.value==40 || roleId.value==41 || roleId.value==42 || roleId.value==45 || roleId.value==48 || roleId.value==49 || roleId.value==50 || roleId.value==67)){ if(zoneCodeId) { if(zoneCodeId.selectedIndex==0 ||zoneCodeId.selectedIndex==-1) { zoneCodeId.style.backgroundColor='#FFD9D9'; zoneCodeId.focus(); fORMSUBMITFLAG=false; return false; } } } if(roleId!=null && roleId.value!="" && (roleId.value==4 || roleId.value==54 || roleId.value==48 || roleId.value==3 || roleId.value==11 || roleId.value==14 || roleId.value==35 || roleId.value==16 || roleId.value==23 || roleId.value==26 || roleId.value==27 || roleId.value==28 || roleId.value==29 || roleId.value==31 || roleId.value==36 || roleId.value==37 || roleId.value==38 || roleId.value==39 || roleId.value==40 || roleId.value==41 || roleId.value==42 || roleId.value==45 || roleId.value==49 || roleId.value==50 || roleId.value==51 || roleId.value==67 || roleId.value==68 || roleId.value==69)){ if(checkCheckBoxs("branchCode")){ alert("Territory is mandatory"); fORMSUBMITFLAG=false; return false; } } if(roleId!=null && roleId.value!="" && (roleId.value==5 || roleId.value==7 || roleId.value==30 || roleId.value==34)){ if(branchCodeId) { if(branchCodeId.selectedIndex==0 ||branchCodeId.selectedIndex==-1) { branchCodeId.style.backgroundColor='#FFD9D9'; branchCodeId.focus(); fORMSUBMITFLAG=false; return false; } } } if(roleId!=null && roleId.value!="" && (roleId.value==5 || roleId.value==7 || roleId.value==30 || roleId.value==35)){ if(primaryLocCode) { if(primaryLocCode.selectedIndex==0 ||primaryLocCode.selectedIndex==-1) { primaryLocCode.style.backgroundColor='#FFD9D9'; primaryLocCode.focus(); fORMSUBMITFLAG=false; return false; } } } if(roleId!=null && roleId.value!="" && (roleId.value==34|| roleId.value==38 || roleId.value==42 || roleId.value==68 || roleId.value==69)){ if(checkCheckBoxs("locCode")){ alert("Location is mandatory"); fORMSUBMITFLAG=false; return false; } } if(roleId.value==7) { if(checkCheckBoxs("caCode")){ caCodeId.style.backgroundColor='#FFD9D9'; caCodeId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.districtCode")){ districtId.style.backgroundColor='#FFD9D9'; districtId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.subDistrictCode")) { subDistrictId.style.backgroundColor='#FFD9D9'; subDistrictId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.pincode")) { pincodeId.style.backgroundColor='#FFD9D9'; pincodeId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.localityCode")) { localityCodeId.style.backgroundColor='#FFD9D9'; localityCodeId.focus(); fORMSUBMITFLAG=false; return false; } } if((roleId != null) && (roleId.value==56 || roleId.value==55 || roleId.value==57 || roleId.value==58 || roleId.value==59 || roleId.value==60)){ if((checkCheckBoxs("zoneCode")) && (roleId.value==56 || roleId.value==55 || roleId.value==57 || roleId.value==58 || roleId.value==59)){ alert("Zone is mandatory"); FORMCONFIRMFLAG=false; return false; } if((checkCheckBoxs("branchCode")) && (roleId.value==56 || roleId.value==55 || roleId.value==57 || roleId.value==58 || roleId.value==59)){ alert("Territory is mandatory"); FORMCONFIRMFLAG=false; return false; } if(roleId.value==55 && primaryLocCode) { if(primaryLocCode.selectedIndex==0 ||primaryLocCode.selectedIndex==-1) { primaryLocCode.style.backgroundColor='#FFD9D9'; primaryLocCode.focus(); fORMSUBMITFLAG=false; return false; } } if((roleId.value==58) && (checkCheckBoxs("locCode"))){ alert("Location is mandatory"); fORMSUBMITFLAG=false; return false; } if((checkCheckBoxs("divCode")) && ((roleId.value==58 || roleId.value==59 || roleId.value==60) && (userRole=="HO Administrator"))){ alert("Division is mandatory"); fORMSUBMITFLAG=false; return false; } if((checkCheckBoxs("divCode")) && ((roleId.value==58 || roleId.value==60) && (userRole=="POC Support"))){ alert("Division is mandatory"); fORMSUBMITFLAG=false; return false; } if((checkCheckBoxs("bucketCode")) && (roleId.value==57 || roleId.value==58 || roleId.value==59 || roleId.value==60)){ alert("Module Type is mandatory"); fORMSUBMITFLAG=false; return false; } } if((roleId!=null && roleId.value!="")&&(roleId.value==63 || roleId.value==64 || roleId.value==65)){ if((checkCheckBoxs("zoneCode")) && (roleId.value!=65)){ alert("Zone is mandatory"); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("branchCode") && (roleId.value!=65)){ alert("Territory is mandatory"); FORMCONFIRMFLAG=false; return false; } if((checkCheckBoxs("locCode"))&&(roleId.value==63)){ alert("Location is mandatory"); fORMSUBMITFLAG=false; return false; } if((checkCheckBoxs("divCode")) && ((userRole=="POC Support") && (roleId.value!=64)) ){ alert("Division is mandatory"); fORMSUBMITFLAG=false; return false; }else{ if((checkCheckBoxs("divCode")) && (userRole=="HO Administrator" || userRole=="Zonal Administrator" || userRole=="National Head")){ alert("Division is mandatory"); fORMSUBMITFLAG=false; return false; } } if(checkCheckBoxs("bucketCode")){ alert("Module Type is mandatory"); fORMSUBMITFLAG=false; return false; } } if((roleId!=null && roleId.value!="")&&(roleId.value==70 || roleId.value==71 || roleId.value==72)){ if(checkCheckBoxs("zoneCode")){ alert("Zone is mandatory"); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("regionCode")){ alert("Region is mandatory"); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("branchCode")){ alert("Territory is mandatory"); fORMSUBMITFLAG=false; return false; } } } if(userRole=="TL F&F" || userRole=="Regional F&F" || userRole=="Zonal F&F" || userRole=="National F&F" ){ if(roleId!=null && roleId.value!="" && ( roleId.value==49 || roleId.value==50 || roleId.value==51 || roleId.value==35 || roleId.value==36 || roleId.value==37 || roleId.value==38 || roleId.value==67)){ if(checkCheckBoxs("zoneCode")){ alert("Zone is mandatory"); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("branchCode")){ alert("Territory is mandatory"); fORMSUBMITFLAG=false; return false; } if(roleId.value==38 && checkCheckBoxs("divCode")){ alert("Division is mandatory"); fORMSUBMITFLAG=false; return false; } if(roleId.value==35 && primaryLocCode){ if(primaryLocCode.selectedIndex==0 ||primaryLocCode.selectedIndex==-1) { primaryLocCode.style.backgroundColor='#FFD9D9'; primaryLocCode.focus(); fORMSUBMITFLAG=false; return false; } } if(checkCheckBoxs("bucketCode")){ alert("Module Type is mandatory"); fORMSUBMITFLAG=false; return false; } } if(roleId.value==7) { if(zoneCodeId) { if(zoneCodeId.selectedIndex==0 ||zoneCodeId.selectedIndex==-1) { zoneCodeId.style.backgroundColor='#FFD9D9'; zoneCodeId.focus(); fORMSUBMITFLAG=false; return false; } } if(branchCodeId) { if(branchCodeId.selectedIndex==0 ||branchCodeId.selectedIndex==-1) { branchCodeId.style.backgroundColor='#FFD9D9'; branchCodeId.focus(); fORMSUBMITFLAG=false; return false; } } if(primaryLocCode) { if(primaryLocCode.selectedIndex==0 ||primaryLocCode.selectedIndex==-1) { primaryLocCode.style.backgroundColor='#FFD9D9'; primaryLocCode.focus(); fORMSUBMITFLAG=false; return false; } } if(checkCheckBoxs("caCode")){ caCodeId.style.backgroundColor='#FFD9D9'; caCodeId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.districtCode")){ districtId.style.backgroundColor='#FFD9D9'; districtId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.subDistrictCode")) { subDistrictId.style.backgroundColor='#FFD9D9'; subDistrictId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.pincode")) { pincodeId.style.backgroundColor='#FFD9D9'; pincodeId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.localityCode")) { localityCodeId.style.backgroundColor='#FFD9D9'; localityCodeId.focus(); fORMSUBMITFLAG=false; return false; } } } if(userStatId && userRole=="Zonal Administrator" && userRole=="POC Support") { if(userStatId.selectedIndex!=0) { fORMSUBMITFLAG=true; } else { userStatId.style.backgroundColor='#FFD9D9'; userStatId.focus(); fORMSUBMITFLAG=false; return false; } } else{ fORMSUBMITFLAG=true; } } else{ roleId.style.backgroundColor='#FFD9D9'; roleId.focus(); fORMSUBMITFLAG=false; return false; } if(fORMSUBMITFLAG!=false){ document.forms[0].formAction.value="SAVE"; document.forms[0].method="POST"; document.forms[0].action="userMaintenanceFormController.htm"; document.forms[0].submit(); } }catch(ex){ //console.error("outer", ex.message); alert(ex.message); } } function checkCheckBoxs(id) { var elements = document.getElementsByName(id); var len = elements.length; var check; for(var i=0;i<len;i++) { if(!elements[i].checked){ //if none checked then hide pincodes check =1; } else { check=0; break; } } return check; } function doSelectAllCatchments(obj) { var elements = document.getElementsByName("caCode"); var len = elements.length; if(obj.checked) { for(var i=0;i<len;i++) { elements[i].checked = true; } } else { for(var i=0;i<len;i++) { elements[i].checked = false; } } } function doSelectAllLocations(obj) { var elements = document.getElementsByName("locCode"); var len = elements.length; if(obj.checked) { for(var i=0;i<len;i++) { elements[i].checked = true; } } else { for(var i=0;i<len;i++) { elements[i].checked = false; } } } function doSelectAllBucket(obj) { var elements = document.getElementsByName("bucketCode"); var len = elements.length; if(obj.checked) { for(var i=0;i<len;i++) { elements[i].checked = true; } } else { for(var i=0;i<len;i++) { elements[i].checked = false; } } } function doSelectAllDivisions(obj) { var elements = document.getElementsByName("divCode"); var len = elements.length; if(obj.checked) { for(var i=0;i<len;i++) { elements[i].checked = true; } } else { for(var i=0;i<len;i++) { elements[i].checked = false; } } } function doSelectAllZones(obj) { var roleId=document.getElementById("roleId"); var zones=""; var elements = document.getElementsByName("zoneCode"); var len = elements.length; if(obj.checked) { for(var i=1;i<len;i++) { elements[i].checked = true; if(elements[i].value!=null && elements[i].value!='') zones=zones + elements[i].value+','; } if(roleId.value!=null && (roleId.value!=7 && roleId.value!=1 && roleId.value!=2 && roleId.value!=46 && roleId.value!=5 && roleId.value!=12 && roleId.value!=13 && roleId.value!=9 && roleId.value!=33 && roleId.value!=52)){ if(roleId.value == 70 || roleId.value == 71 || roleId.value == 72){ document.getElementById("regionMultiDiv").style.display="block"; DWRUtil.getRegionsByMultipleZones(zones,regionGridCallback); }else{ document.getElementById("branchMultiDiv").style.display="block"; DWRUtil.getBranchesByMultipleZones(zones,branchGridCallback); } } } else { for(var i=0;i<len;i++) { elements[i].checked = false; } resetCheckBoxByName("branchCode"); mygrid4.clearAll(); resetCommonCheckBox(); if(document.getElementById("priLocDiv")!=null) document.getElementById("priLocDiv").style.display="none"; document.getElementById("mutilplelocLocation").style.display="none"; if(roleId.value == 70 || roleId.value == 71 || roleId.value == 72){ mygrid12.clearAll(); document.getElementById("regionMultiDiv").style.display="none"; document.getElementById("branchMultiDiv").style.display="none"; } } } function doSelectAllBranches(obj) { var roleId=document.getElementById("roleId"); var elements = document.getElementsByName("branchCode"); var branches=""; var len = elements.length; if(checkCheckBoxs("zoneCode")) len = elements.length-1; if(obj.checked) { for(var i=1;i<len;i++) { elements[i].checked = true; if(elements[i].value!=null && elements[i].value!='') branches=branches + elements[i].value+','; } if(roleId.value==35 || roleId.value==55){ if(branches=="" || branches==null){ document.getElementById("priLocDiv").style.display="none"; }else{ document.getElementById("priLocDiv").style.display="block"; loadlocfrommultiBranchTC(branches); } } else if(branches=="" || branches==null){ document.getElementById("mutilplelocLocation").style.display="none"; } else if(roleId.value==4|| roleId.value==48 || roleId.value==39 ||roleId.value==42 || roleId.value==40 || roleId.value==41 || roleId.value==58 || roleId.value==63){ DWRUtil.getLocationsByMultipleBranchs(branches,multipleLocationsCallback); } else if(roleId.value==54) { DWRUtil.getLocationsByMultipleBranchs(branches,multipleLocationsCallback); document.getElementById("priLocDiv").style.display="block"; loadlocfrommultiBranchTC(branches); } } else { for(var i=0;i<len;i++) { elements[i].checked = false; } mygrid5.clearAll(); if(document.getElementById("priLocDiv")!=null) document.getElementById("priLocDiv").style.display="none"; document.getElementById("mutilplelocLocation").style.display="none"; } } function doSelectDistrict(obj){ document.getElementById("pincodeDiv").style.display="none"; document.getElementById("localityDiv").style.display="none"; var districts =""; var elements = document.getElementsByName("dataObject.districtCode"); var len = elements.length; var loadSubDistrictsFlag=false;//Flag to load Sub-districts if(obj.checked) { loadSubDistrictsFlag=true; }else { var flag =0; for(var i=0;i<len;i++) { if(!elements[i].checked){ //if none checked then hide pincodes flag =1; } else { flag=0; break; } } if(flag) { document.getElementById("subDistrictDiv").style.display="none"; document.getElementById("pincodeDiv").style.display="none"; document.getElementById("localityDiv").style.display="none"; }else{ loadSubDistrictsFlag=true; } } if(loadSubDistrictsFlag){ for(var i=0;i<len;i++) { if(elements[i].checked){ if(elements[i].value!=null && elements[i].value!='') districts=districts + elements[i].value+','; } } document.getElementById("districtDiv").style.display="block"; districts = districts.substring(0, districts.length-1); mygrid10.clearAll();//clear subdistricts mygrid9.clearAll();//clear pincodes mygrid8.clearAll();//clear locality codes //DWRUtil.getSubDistrictByMultipleDistricts(districts,multiSubDistrictCallback); DWRUtil.getAllSubDistrictsForChosenDistricts(districts,multiSubDistrictCallback); } } function doSelectAllDistrict(obj) { var districts =""; var elements = document.getElementsByName("dataObject.districtCode"); var len = elements.length; if(obj.checked) { for(var i=0;i<len;i++) { elements[i].checked = true; } } else { for(var i=0;i<len;i++) { elements[i].checked = false; } } doSelectDistrict(obj); } function multiSubDistrictCallback(data) { if(data!=null) { document.getElementById("subDistrictDiv").style.display="block"; document.getElementById("subdistrict").checked = false; var len = data.length; var myData = new Array(); for(var i=0;i<len;i++) { var subdistrict = data[i].substr(0,data[i].indexOf("$")); myData[i]=new Array(); myData[i][0]='<INPUT TYPE="checkbox" NAME="dataObject.subDistrictCode" id="dataObject.subDistrictCode" onclick="doSelectSubDistrict(this)" value="' +subdistrict+ '" > '; myData[i][1]=data[i].substr(data[i].indexOf("$")+1); } mygrid8.clearAll();//clear subdistricts mygrid8.parse(myData,"jsarray"); } } function doSelectAllSubDistricts(obj) { var subDistricts =""; var elements = document.getElementsByName("dataObject.subDistrictCode"); var len = elements.length; if(obj.checked) { for(var i=0;i<len;i++) { elements[i].checked = true; } } else { for(var i=0;i<len;i++) { elements[i].checked = false; } } doSelectSubDistrict(obj); } function doSelectSubDistrict(obj){ document.getElementById("localityDiv").style.display="none"; var subDistricts =""; var elements = document.getElementsByName("dataObject.subDistrictCode"); var len = elements.length; var loadPinsFlag=false;//Flag to load Pincodes if(obj.checked) { loadPinsFlag=true; }else { var flag =0; for(var i=0;i<len;i++) { if(!elements[i].checked){ //if none checked then hide pincodes flag =1; } else { flag=0; break; } } if(flag) { document.getElementById("pincodeDiv").style.display="none"; document.getElementById("localityDiv").style.display="none"; }else{ loadPinsFlag=true; } } if(loadPinsFlag){ for(var i=0;i<len;i++) { if(elements[i].checked){ if(elements[i].value!=null && elements[i].value!='') subDistricts=subDistricts + elements[i].value+','; } } document.getElementById("subDistrictDiv").style.display="block"; subDistricts = subDistricts.substring(0, subDistricts.length-1); mygrid9.clearAll();//clear pincodes mygrid10.clearAll();//clear locality codes DWRUtil.getPincodeByMultipleSubDistricts(subDistricts,multiPincodeCallback); } } function multiPincodeCallback(data) { if(data!=null) { document.getElementById("pincodeDiv").style.display="block"; document.getElementById("pincode").checked = false; var len = data.length; var myData = new Array(); for(var i=0;i<len;i++) { myData[i]=new Array(); myData[i][0]='<INPUT TYPE="checkbox" NAME="dataObject.pincode" id="dataObject.pincode" onclick="doSelectPincodes(this)" value="'+data[i].substr(0,data[i].indexOf("-"))+'" >'; myData[i][1]=data[i].substr(data[i].indexOf(",")+1); } mygrid9.clearAll(); //clear pins mygrid9.parse(myData,"jsarray"); } } function doSelectAllPincodes(obj) { var elements = document.getElementsByName("dataObject.pincode"); var len = elements.length; if(obj.checked) { for(var i=0;i<len;i++) { elements[i].checked = true; } } else { for(var i=0;i<len;i++) { elements[i].checked = false; } } doSelectPincodes(obj); } function doSelectPincodes(obj){ var pincodes =""; var elements = document.getElementsByName("dataObject.pincode"); var len = elements.length; document.getElementById("localityDiv").style.display="none"; var loadLocalitiesFlag=false;//Flag to load Localities if(obj.checked) { loadLocalitiesFlag=true; }else { var flag =0; for(var i=0;i<len;i++) { if(!elements[i].checked){ //if none checked then hide localitycodes flag =1; } else { flag=0; break; } } if(flag) { document.getElementById("localityDiv").style.display="none"; }else{ loadLocalitiesFlag=true; } } if(loadLocalitiesFlag){ for(var i=0;i<len;i++) { if(elements[i].checked){ if(elements[i].value!=null && elements[i].value!=''){ pincodes=pincodes + elements[i].value+','; } } } pincodes = pincodes.substring(0, pincodes.length-1); mygrid10.clearAll(); DWRUtil.getLocalityByMultiplePincodes(pincodes,multiLocalityCallback); } } function multiLocalityCallback(data) { if(data!=null) { document.getElementById("localityDiv").style.display="block"; document.getElementById("locality").checked = false; var len = data.length; var myData = new Array(); for(var i=0;i<len;i++) { myData[i]=new Array(); myData[i][0]='<INPUT TYPE="checkbox" NAME="dataObject.localityCode" id="dataObject.localityCode" onclick="doSelectLocality(this)" value="'+data[i].substr(0,data[i].indexOf("$"))+'">'; myData[i][1]=data[i].substr(data[i].indexOf("$")+1); } mygrid10.clearAll(); mygrid10.parse(myData,"jsarray"); } } function doSelectLocality(obj){ var localities =""; var elements = document.getElementsByName("dataObject.localityCode"); var len = elements.length; if(obj.checked) { for(var i=0;i<len;i++) { if(elements[i].checked){ if(elements[i].value!=null && elements[i].value!='') localities=localities + elements[i].value+','; } } localities = localities.substring(0, localities.length-1); } else { for(var i=0;i<len;i++) { elements[i].checked = false; } } } function doSelectAllLocality(obj) { var elements = document.getElementsByName("dataObject.localityCode"); var len = elements.length; if(obj.checked) { for(var i=0;i<len;i++) { elements[i].checked = true; } } else { for(var i=0;i<len;i++) { elements[i].checked = false; } } doSelectLocality(obj); } function doConfirm() { var FORMCONFIRMFLAG=false; var roleId=document.getElementById("roleId"); var caCodeId=document.getElementById("caCode"); var userStatId=document.getElementById("userStatusId"); var branchCodeId=document.getElementById("branchCode"); var primaryLocCode=document.getElementById("primaryLocCode"); var locCodeId=document.getElementById("locCode"); var zoneCodeId=document.getElementById("zoneCode"); var chkResetPwd = document.getElementById("chkResetPwd"); var txtpassword = document.getElementById("password"); var districtId = document.getElementById("dataObject.districtCode"); var subDistrictId=document.getElementById("dataObject.subDistrictCode"); var pincodeId=document.getElementById("dataObject.pincode"); var localityCodeId=document.getElementById("dataObject.localityCode"); if(roleId.selectedIndex!=0){ if(userRole=="Branch Administrator" || userRole=="RH"|| userRole=="TM 0-90" ||userRole=="SCM 0-90" || userRole=="RBM 0-90"){ if(roleId!=null && roleId.value!="" && (roleId.value==34 || roleId.value==35 || roleId.value==38 || roleId.value==40 || roleId.value==42)){ if(checkCheckBoxs("locCode") && roleId.value!=38 && roleId.value!=35){ alert("Location is mandatory"); FORMCONFIRMFLAG=false; return false; } if(checkCheckBoxs("branchCode")){ alert("Territory is mandatory"); FORMCONFIRMFLAG=false; return false; } else if(checkCheckBoxs("bucketCode")){ alert("Module Type is mandatory"); FORMCONFIRMFLAG=false; return false; } else if(checkCheckBoxs("divCode") && (roleId.value!=35)){ alert("Division is mandatory"); FORMCONFIRMFLAG=false; return false; } } else if(roleId!=null && roleId.value!="" && (roleId.value==16 || roleId.value==23 || roleId.value==26 || roleId.value==27 || roleId.value==28 || roleId.value==29 || roleId.value==30 || roleId.value==31 || roleId.value==35 || roleId.value==36 || roleId.value==37 || roleId.value==45 || roleId.value==67)){ if(checkCheckBoxs("zoneCode")){ alert("Zone is mandatory"); FORMCONFIRMFLAG=false; return false; } if(checkCheckBoxs("branchCode")){ alert("Territory is mandatory"); FORMCONFIRMFLAG=false; return false; } if(checkCheckBoxs("bucketCode")){ alert("Module Type is mandatory"); fORMSUBMITFLAG=false; return false; } } else if(roleId!=null && roleId.value!="" && (roleId.value==7)){ if(zoneCodeId.selectedIndex==0){ zoneCodeId.style.backgroundColor='#FFD9D9'; zoneCodeId.focus(); fORMSUBMITFLAG=false; return false; } if(branchCodeId.selectedIndex==0){ branchCodeId.style.backgroundColor='#FFD9D9'; branchCodeId.focus(); fORMSUBMITFLAG=false; return false; } if(primaryLocCode) { if(primaryLocCode.selectedIndex==0 ||primaryLocCode.selectedIndex==-1) { primaryLocCode.style.backgroundColor='#FFD9D9'; primaryLocCode.focus(); fORMSUBMITFLAG=false; return false; } } if(checkCheckBoxs("caCode")){ caCodeId.style.backgroundColor='#FFD9D9'; caCodeId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.districtCode")){ districtId.style.backgroundColor='#FFD9D9'; districtId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.subDistrictCode")) { subDistrictId.style.backgroundColor='#FFD9D9'; subDistrictId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.pincode")) { pincodeId.style.backgroundColor='#FFD9D9'; pincodeId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.localityCode")) { localityCodeId.style.backgroundColor='#FFD9D9'; localityCodeId.focus(); fORMSUBMITFLAG=false; return false; } } else if((roleId!=null && roleId.value!="") && (roleId.value==63)){ if(checkCheckBoxs("zoneCode")){ alert("Zone is mandatory"); fORMSUBMITFLAG=false; return false; } else if(checkCheckBoxs("branchCode")){ alert("Territory is mandatory"); FORMCONFIRMFLAG=false; return false; } else if(checkCheckBoxs("divCode")){ alert("Division is mandatory"); fORMSUBMITFLAG=false; return false; } else if(checkCheckBoxs("bucketCode")){ alert("Module Type is mandatory"); fORMSUBMITFLAG=false; return false; } } } else if(userRole=="Super Administrator" || userRole=="HO Administrator" || userRole=="Zonal Administrator" || userRole=="Zonal Accountant Admin" || userRole=="National Head" || userRole=="POC Support"){ if(roleId!=null && roleId.value!="" && (roleId.value==33 || roleId.value==48 || roleId.value==3 || roleId.value==4 || roleId.value==34 || roleId.value==38 || roleId.value==39 || roleId.value==40 || roleId.value==41 ||roleId.value==68 || roleId.value==69 || roleId.value==74)){ if((getValuesFromDropdown("branchCode")==null || getValuesFromDropdown("branchCode")=="") && roleId.value != 33 ){ alert("Territory is mandatory"); FORMCONFIRMFLAG=false; return false; } if(checkCheckBoxs("bucketCode")){ alert("Module Type is mandatory"); FORMCONFIRMFLAG=false; return false; } else if(checkCheckBoxs("divCode")){ alert("Division is mandatory"); return false; } }if(roleId!=null && roleId.value!="" && (roleId.value==37 || roleId.value==67)){ if(getValuesFromDropdown("zoneCode")==null || getValuesFromDropdown("zoneCode")==""){ alert("Zone is mandatory"); FORMCONFIRMFLAG=false; return false; } if(getValuesFromDropdown("branchCode")==null || getValuesFromDropdown("branchCode")==""){ alert("Territory is mandatory"); FORMCONFIRMFLAG=false; return false; } if(checkCheckBoxs("bucketCode")){ alert("Module Type is mandatory"); FORMCONFIRMFLAG=false; return false; } } if(roleId!=null && roleId.value!="" && (roleId.value==16 || roleId.value==23 || roleId.value==26 || roleId.value==27 || roleId.value==28 || roleId.value==29 || roleId.value==30 || roleId.value==31 || roleId.value==35 || roleId.value==36 || roleId.value==37 || roleId.value==45 || roleId.value==49 || roleId.value==50 || roleId.value==51 || roleId.value==52 || roleId.value==67)){ if(checkCheckBoxs("bucketCode")){ alert("Module Type is mandatory"); fORMSUBMITFLAG=false; return false; } } if(roleId!=null && roleId.value!="" && userRole!="HO Administrator" && userRole!="Super Administrator" && userRole!="Zonal Administrator" && userRole!="POC Support" && userRole!="Zonal Accountant Admin" && (roleId.value==8 || roleId.value==10 || roleId.value==3 || roleId.value==47 || roleId.value==51)){ if(getValuesFromDropdown("zoneCode")==null || getValuesFromDropdown("zoneCode")==""){ alert("Zone is mandatory"); FORMCONFIRMFLAG=false; return false; } } if(roleId!=null && roleId.value!="" && userRole!="HO Administrator" && userRole!="Super Administrator" && userRole!="Zonal Administrator" && userRole!="Zonal Accountant Admin" && userRole!="POC Support" && (roleId.value==4 || roleId.value==48 || roleId.value==5 || roleId.value==7 || roleId.value==11 || roleId.value==14 || roleId.value==16 || roleId.value==23 || roleId.value==26 || roleId.value==27 || roleId.value==28 || roleId.value==29 || roleId.value==31 || roleId.value==34 || roleId.value==35 || roleId.value==36 || roleId.value==37 || roleId.value==38 || roleId.value==39 || roleId.value==40 || roleId.value==41 || roleId.value==42 || roleId.value==45 || roleId.value==49 || roleId.value==50 || roleId.value==67)){ if(zoneCodeId) { if(zoneCodeId.selectedIndex==0 ||zoneCodeId.selectedIndex==-1) { zoneCodeId.style.backgroundColor='#FFD9D9'; zoneCodeId.focus(); FORMCONFIRMFLAG=false; return false; } } } if(roleId!=null && roleId.value!="" && (roleId.value==4 || roleId.value==3 || roleId.value==54 || roleId.value==11 || roleId.value==14 || roleId.value==35|| roleId.value==48 || roleId.value==16 || roleId.value==23 || roleId.value==38 || roleId.value==26 || roleId.value==27 || roleId.value==28 || roleId.value==29 || roleId.value==31 || roleId.value==36 || roleId.value==37 || roleId.value==39 || roleId.value==40 || roleId.value==41 || roleId.value==42 || roleId.value==45 || roleId.value==49 || roleId.value==50 || roleId.value==51 || roleId.value==67)){ if(getValuesFromDropdown("branchCode")==null || getValuesFromDropdown("branchCode")==""){ alert("Territory is mandatory"); FORMCONFIRMFLAG=false; return false; } } if(roleId!=null && roleId.value!="" && (roleId.value==5 || roleId.value==7 || roleId.value==30 || roleId.value==34)){ if(branchCodeId) { if(branchCodeId.selectedIndex==0 ||branchCodeId.selectedIndex==-1) { branchCodeId.style.backgroundColor='#FFD9D9'; branchCodeId.focus(); FORMCONFIRMFLAG=false; return false; } } } if(roleId!=null && roleId.value!="" && (roleId.value==5 || roleId.value==7 || roleId.value==30 || roleId.value==35)){ if(primaryLocCode) { if(primaryLocCode.selectedIndex==0 ||primaryLocCode.selectedIndex==-1) { primaryLocCode.style.backgroundColor='#FFD9D9'; primaryLocCode.focus(); FORMCONFIRMFLAG=false; return false; } } } if(roleId!=null && roleId.value!="" && (roleId.value==34 || roleId.value==42)){ if(checkCheckBoxs("locCode")){ alert("Location is mandatory"); FORMCONFIRMFLAG=false; return false; } } if(roleId.value==7) { if(checkCheckBoxs("caCode")){ caCodeId.style.backgroundColor='#FFD9D9'; caCodeId.focus(); FORMCONFIRMFLAG=false; return false; } if(checkCheckBoxs("dataObject.districtCode")){ districtId.style.backgroundColor='#FFD9D9'; districtId.focus(); FORMCONFIRMFLAG=false; return false; } if(checkCheckBoxs("dataObject.subDistrictCode")) { subDistrictId.style.backgroundColor='#FFD9D9'; subDistrictId.focus(); FORMCONFIRMFLAG=false; return false; } if(checkCheckBoxs("dataObject.pincode")) { pincodeId.style.backgroundColor='#FFD9D9'; pincodeId.focus(); FORMCONFIRMFLAG=false; return false; } if(checkCheckBoxs("dataObject.localityCode")) { localityCodeId.style.backgroundColor='#FFD9D9'; localityCodeId.focus(); FORMCONFIRMFLAG=false; return false; } } if((roleId != null) && (roleId.value==56 || roleId.value==55 || roleId.value==57 || roleId.value==58 || roleId.value==59 || roleId.value==60)){ if((checkCheckBoxs("zoneCode")) && (roleId.value==56 || roleId.value==55 || roleId.value==57 || roleId.value==58 || roleId.value==59)){ alert("Zone is mandatory"); FORMCONFIRMFLAG=false; return false; } if((checkCheckBoxs("branchCode")) && (roleId.value==56 || roleId.value==55 || roleId.value==57 || roleId.value==58 || roleId.value==59)){ alert("Territory is mandatory"); FORMCONFIRMFLAG=false; return false; } if(roleId.value==55 && primaryLocCode) { if(primaryLocCode.selectedIndex==0 ||primaryLocCode.selectedIndex==-1) { primaryLocCode.style.backgroundColor='#FFD9D9'; primaryLocCode.focus(); fORMSUBMITFLAG=false; return false; } } if((roleId.value==58) && (checkCheckBoxs("locCode"))){ alert("Location is mandatory"); fORMSUBMITFLAG=false; return false; } if((checkCheckBoxs("divCode")) && ((roleId.value==58 || roleId.value==59 || roleId.value==60) && (userRole=="HO Administrator"))){ alert("Division is mandatory"); fORMSUBMITFLAG=false; return false; } if((checkCheckBoxs("divCode")) && ((roleId.value==60 || roleId.value==58 ) && (userRole=="POC Support"))){ alert("Division is mandatory"); fORMSUBMITFLAG=false; return false; } if((checkCheckBoxs("bucketCode")) && (roleId.value==57 || roleId.value==58 || roleId.value==59 || roleId.value==60)){ alert("Module Type is mandatory"); fORMSUBMITFLAG=false; return false; } } if((roleId!=null && roleId.value!="")&&(roleId.value==63 || roleId.value==64 || roleId.value==65)){ if((checkCheckBoxs("zoneCode")) && (roleId.value!=65)){ alert("Zone is mandatory"); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("branchCode") && (roleId.value!=65)){ alert("Territory is mandatory"); FORMCONFIRMFLAG=false; return false; } if((checkCheckBoxs("locCode"))&&(roleId.value==63)){ alert("Location is mandatory"); fORMSUBMITFLAG=false; return false; } if((checkCheckBoxs("divCode")) && ((userRole=="POC Support") && (roleId.value!=64)) ){ alert("Division is mandatory"); fORMSUBMITFLAG=false; return false; }else{ if((checkCheckBoxs("divCode")) && (userRole=="HO Administrator" || userRole=="Zonal Administrator" || userRole=="National Head")){ alert("Division is mandatory"); fORMSUBMITFLAG=false; return false; } } if(checkCheckBoxs("bucketCode")){ alert("Module Type is mandatory"); fORMSUBMITFLAG=false; return false; } } if((roleId!=null && roleId.value!="")&&(roleId.value==70 || roleId.value==71 || roleId.value==72)){ if(checkCheckBoxs("zoneCode")){ alert("Zone is mandatory"); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("regionCode")){ alert("Region is mandatory"); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("branchCode")){ alert("Territory is mandatory"); fORMSUBMITFLAG=false; return false; } } } else if(userRole=="TL F&F" || userRole=="Regional F&F" || userRole=="Zonal F&F" || userRole=="National F&F" ){ if(roleId!=null && roleId.value!="" && ( roleId.value==49 || roleId.value==50 || roleId.value==51 || roleId.value==37 || roleId.value==38 || roleId.value==67)){ if(getValuesFromDropdown("zoneCode")==null || getValuesFromDropdown("zoneCode")==""){ alert("Zone is mandatory"); fORMSUBMITFLAG=false; return false; } if(getValuesFromDropdown("branchCode")==null || getValuesFromDropdown("branchCode")==""){ alert("Territory is mandatory"); fORMSUBMITFLAG=false; return false; } if((checkCheckBoxs("divCode")) && roleId.value==38){ alert("Division is mandatory"); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("bucketCode")){ alert("Module Type is mandatory"); fORMSUBMITFLAG=false; return false; } } if(roleId!=null && roleId.value!="" && roleId.value==7) { if(zoneCodeId) { if(zoneCodeId.selectedIndex==0 ||zoneCodeId.selectedIndex==-1) { zoneCodeId.style.backgroundColor='#FFD9D9'; zoneCodeId.focus(); FORMCONFIRMFLAG=false; return false; } } if(branchCodeId) { if(branchCodeId.selectedIndex==0 ||branchCodeId.selectedIndex==-1) { branchCodeId.style.backgroundColor='#FFD9D9'; branchCodeId.focus(); FORMCONFIRMFLAG=false; return false; } } if(primaryLocCode) { if(primaryLocCode.selectedIndex==0 ||primaryLocCode.selectedIndex==-1) { primaryLocCode.style.backgroundColor='#FFD9D9'; primaryLocCode.focus(); FORMCONFIRMFLAG=false; return false; } } if(checkCheckBoxs("caCode")){ caCodeId.style.backgroundColor='#FFD9D9'; caCodeId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.districtCode")){ districtId.style.backgroundColor='#FFD9D9'; districtId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.subDistrictCode")) { subDistrictId.style.backgroundColor='#FFD9D9'; subDistrictId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.pincode")) { pincodeId.style.backgroundColor='#FFD9D9'; pincodeId.focus(); fORMSUBMITFLAG=false; return false; } if(checkCheckBoxs("dataObject.localityCode")) { localityCodeId.style.backgroundColor='#FFD9D9'; localityCodeId.focus(); fORMSUBMITFLAG=false; return false; } } } if(chkResetPwd.checked) { var pattern = /^(?=.*?[a-z])(?=.*?[0-9])[a-zA-Z0-9]{6,}$/; if(trim(txtpassword.value).length==0 || trim(txtpassword.value).length<6) { txtpassword.style.backgroundColor='#FFD9D9'; txtpassword.focus(); FORMCONFIRMFLAG=false; return false; } if(pattern.test(txtpassword.value)==false && roleId.value!=7){ alert("Password should contain alphanumerics only"); FORMCONFIRMFLAG=false; return false; } } if(userStatId) { if(userStatId.selectedIndex!=0 && userStatId.value!=original_status) { if(userStatId.value!=7 && userStatId.value!=6){ FORMCONFIRMFLAG=true; } else{ userStatId.style.backgroundColor='#FFD9D9'; userStatId.focus(); FORMCONFIRMFLAG=false; return false; } } else if(userStatId.selectedIndex!=0 && userStatId.value==original_status){ FORMCONFIRMFLAG=true; } else { userStatId.style.backgroundColor='#FFD9D9'; userStatId.focus(); FORMCONFIRMFLAG=false; return false; } } document.getElementById("zoneSelected").value = getValuesFromDropdown("zoneCode"); document.getElementById("branchSelected").value = getValuesFromDropdown("branchCode"); } else{ roleId.style.backgroundColor='#FFD9D9'; roleId.focus(); FORMCONFIRMFLAG=false; return false; } if(FORMCONFIRMFLAG!=false){ document.forms[0].formAction.value="CONFIRM"; document.forms[0].method="POST"; document.forms[0].action="userMaintenanceFormController.htm"; document.forms[0].submit(); } } function getValuesFromDropdown(id){ var roleId=document.getElementById("roleId"); if(roleId.value!=7 && roleId.value!=5){ var elements = document.getElementsByName(id); if(elements!=null){ var len = elements.length; var selectedValue = ""; if(len>1){ for(var i=0;i<len;i++) { if(elements[i].checked){ if(i!=0){ selectedValue = selectedValue+","; } selectedValue = selectedValue+elements[i].value; } } }else{ selectedValue = elements[0].value; } return selectedValue; } }else{ return document.getElementById(id).value; } } function onClickReset(){ var chkResetPwd = document.getElementById("chkResetPwd"); var txtpassword = document.getElementById("password"); if(chkResetPwd.checked) { if(trim(txtpassword.value).length==0 || trim(txtpassword.value).length<6) { txtpassword.style.backgroundColor='#FFD9D9'; txtpassword.focus(); return false; } else{ location.reload(); } } else location.reload(); } function showPassword(chkElement) { if(chkElement.checked) document.getElementById("passwordDiv").style.display="block"; else document.getElementById("passwordDiv").style.display="none"; } function regionGridCallback(data) { if(data!=null) { // Get all the regions at the instance and filter only the checked once var branch_div = document.getElementsByName("regionCode"); var no_of_branches = branch_div.length; var checked_branches = new Array(); for(var i=0;i<no_of_branches;i++){ if(branch_div[i].checked){ if(branch_div[i].value!=null && branch_div[i].value!=''){ checked_branches.push(branch_div[i].value.trim()); } } } // check the branches, if they are already checked. var len = data.length; var myData = new Array(); var j=0; for(var i=0;i<len;i++){ myData[j]=new Array(); var valid_branch_code = data[i].substr(0,data[i].indexOf("$")); if (checked_branches.indexOf(valid_branch_code) > -1) { myData[j][0]='<INPUT TYPE="checkbox" NAME="regionCode" onclick="doSelectRegion(this)" id="regionCode" value="'+data[i].substr(0,data[i].indexOf("$"))+'" checked>'; } else { myData[j][0]='<INPUT TYPE="checkbox" NAME="regionCode" onclick="doSelectRegion(this)" id="regionCode" value="'+data[i].substr(0,data[i].indexOf("$"))+'">'; } myData[j][0]='<INPUT TYPE="checkbox" NAME="regionCode" onclick="doSelectRegion(this)" id="regionCode" value="'+data[i].substr(0,data[i].indexOf("$"))+'">'; myData[j][1]=data[i].substr(data[i].indexOf("$")+1); j++; } mygrid12.clearAll(); mygrid12.parse(myData,"jsarray"); } } function doSelectAllRegions(obj){ var roleId=document.getElementById("roleId"); var regions=""; var elements = document.getElementsByName("regionCode"); var len = elements.length; if(obj.checked) { for(var i=0;i<len;i++) { elements[i].checked = true; if(elements[i].value!=null && elements[i].value!='') regions=regions + elements[i].value+','; } if((roleId.value!=null) && (roleId.value == 70 || roleId.value == 71 || roleId.value == 72)){ document.getElementById("branchMultiDiv").style.display="block"; DWRUtil.getBranchesByMultipleRegions(regions,branchGridCallback) } } else{ if((roleId.value!=null) && (roleId.value == 70 || roleId.value == 71 || roleId.value == 72)){ resetCheckBoxByName("regionCode"); // resetCommonCheckBox(); mygrid4.clearAll(); document.getElementById("branchMultiDiv").style.display="none"; } } } function doSelectRegion(obj){ var roleId=document.getElementById("roleId"); var regions=""; var elements = document.getElementsByName("regionCode"); var len = elements.length; for(var i=0;i<len;i++) { if(elements[i].checked){ if(elements[i].value!=null && elements[i].value!='') regions=regions + elements[i].value+','; } } if((roleId.value!=null) && (roleId.value == 70 || roleId.value == 71 || roleId.value == 72)){ if(regions != ""){ document.getElementById("branchMultiDiv").style.display="block"; }else{ document.getElementById("branchMultiDiv").style.display="none"; } DWRUtil.getBranchesByMultipleRegions(regions,branchGridCallback) } }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { withStyles, Typography } from '@material-ui/core'; const styles = theme => ({ switchWrapper: { border: '3px solid #f06c0d', borderRadius: '30px', padding: '4px 10px', position: 'relative', display: 'flex', justifyContent: 'space-between', alignItems: 'center', height: '30px', width: '140px' }, bubble: { position: 'absolute', height: '95%', borderRadius: '30px', top: 1, backgroundColor: '#f06c0d', zIndex: 0, transition: 'all .2s linear' }, top:{ zIndex: 10, transition: 'all .2s linear' }, white: { color: 'white' }, grey: { color: '#cccbcb' }, monthly: { left: 1, width: 92 }, yearly: { left: 92, width: 67 } }) export class ToggleSwitch extends Component { render() { const { classes, opt1, opt2, monthly, toggle } = this.props; return ( <div className={classes.switchWrapper} onClick={toggle}> <Typography className={`${classes.top} ${monthly ? classes.white : classes.grey}`} variant="body2" color="default">{opt1}</Typography> <Typography className={`${classes.top} ${monthly ? classes.grey : classes.white}`} variant="body2" color="default">{opt2}</Typography> <div className={`${classes.bubble} ${monthly ? classes.monthly : classes.yearly }`}></div> </div> ) } } ToggleSwitch.propTypes = { // theme: PropTypes.string, enabled: PropTypes.oneOfType([ PropTypes.bool, PropTypes.func ]), onStateChanged: PropTypes.func } export default withStyles(styles, { withTheme: true })(ToggleSwitch);
import React from 'react'; import { connect } from 'react-redux'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { addTab } from '../layout/uilayout-actions'; import { setSidePanel } from '../layout/uilayout-actions'; class NetworkBrowser extends React.Component{ static icon = "sitemap"; static label = "Network Browser"; constructor(props){ super(props); this.showNetworkTree = this.showNetworkTree.bind(this) } launchEntityTab = (options) => (e) => { e.preventDefault(); let tabId = options.entity + "Tab"; this.props.dispatch(addTab(tabId, 'ElementBrowser', { entity: options.entity, title: options.title, endpoint: '/api/network/live/' + options.endpoit })); } showNetworkTree(){ this.props.dispatch(setSidePanel('NetworkTree')); } render(){ return ( <div> <h3><FontAwesomeIcon icon={NetworkBrowser.icon}/> Network Browser</h3> <div className="card mb-2"> <div className="card-body p-3"> <a href="#" className="launch-network-tree" onClick={this.showNetworkTree}><FontAwesomeIcon icon="arrow-right"/> View network tree</a> </div> </div> </div> ); } } export default connect()(NetworkBrowser)
import React from "react"; import PropTypes from "prop-types"; import Button from "../Button"; import styles from "./channelForm.css"; import Spinner from "../Spinner"; const ButtonContent = ({ isPushing }) => isPushing ? <Spinner /> : <React.Fragment>Create Channel</React.Fragment>; const ErrorMsg = ({ isInvalid, errorMsg }) => isInvalid ? <span className={styles.errorMsg}>{errorMsg}</span> : null; const UserInput = ({ isInvalid, value, errorMsg, ...attr }) => { const classNames = isInvalid ? `${styles.input} ${styles.hasError}` : styles.input; return ( <label htmlFor="channel-form-name-field" className={styles.channelInput}> Name <ErrorMsg isInvalid={isInvalid} errorMsg={errorMsg} /> <input type="text" placeholder="e.g. l33t club" value={value} id="channel-form-name-field" className={classNames} {...attr} /> </label> ); }; function ChannelForm({ value, onCreateBtnClick, isInvalid, errorMsg, isPushing, ...attr }) { const buttonClassNames = isInvalid ? [styles.btn] : [`${styles.btn} ${styles.isValid}`]; return ( <div className={styles.formContainer}> <h1 className={styles.title}>Create a Channel</h1> <form> <UserInput isInvalid={isInvalid} value={value} {...attr} errorMsg={errorMsg} /> <Button classNames={buttonClassNames} onClick={onCreateBtnClick} disabled={isInvalid} > <ButtonContent isPushing={isPushing} /> </Button> </form> </div> ); } ChannelForm.defaultProps = { isPushing: false, isInvalid: false, errorMsg: "", value: "" }; ChannelForm.propTypes = { isInvalid: PropTypes.bool, isPushing: PropTypes.bool, errorMsg: PropTypes.string, value: PropTypes.string, onCreateBtnClick: PropTypes.func.isRequired }; export default ChannelForm;
'use strict'; var React = require('react/addons'); var indicator = React.createClass({ displayName: 'indicator', propTypes: { levels: React.PropTypes.number.isRequired, level: React.PropTypes.number.isRequired }, render: function () { var items = []; var i; var className; var len = this.props.levels; var bar = String.fromCharCode(9604); for (i = 0; i < len; i++) { className = i < this.props.level ? 'bar active' : 'bar'; items.push(React.DOM.span({ className: className, key: i }, bar)); } return ( React.DOM.div({ className: 'indicator' }, items) ); } }); module.exports = React.createClass({ displayName: 'round-trip-rate', propTypes: { steps: React.PropTypes.number, label: React.PropTypes.string, cssClass: React.PropTypes.string, onChange: React.PropTypes.func }, getDefaultProps: function () { return { steps: 3, label: '' }; }, getInitialState: function () { return { rating: 0 }; }, render: function () { var cssClassNames = []; if (this.props.cssClass) { cssClassNames.push(this.props.cssClass); } cssClassNames.push('rating-' + this.state.rating); return ( React.DOM.button({ onClick: this.incrementRating, className: cssClassNames.join(' ') }, React.createElement(indicator, { level: this.state.rating, levels: this.props.steps }), React.DOM.span(null, this.props.label) ) ); }, incrementRating: function () { var rating = this.state.rating; if (++rating === (this.props.steps + 1)) { rating = 0; } this.setState({ rating: rating }); if (this.props.onChange) { this.props.onChange(this.props.label, rating); } } });
describe('Home page', () => { it ('successfully loads home page', () => { cy.visit('/'); // Check website title cy.get('.navbar-brand').should('have.text', 'OpenWorker'); }); it ('logs in and out', () => { cy.visit('/'); // Go to login page cy.get('#accountDropdown').click() .get('[routerlink="/auth/login"]').click() .url().should('include', '/auth/login') // Login as matt .get('#login').type('matt') .get('#password').type('matt') .get('#btnSearch').click() // Check username in nav bar .get('#accountDropdown2') .should('include.text', 'matt') .click() // Disconnect .get('#accountDropdownMenu2 > :nth-child(2)').click() // Check there's no username in nav bar .get('#accountDropdown') .should('not.have.text', 'matt'); }); it ('fails to log with bad credentials', () => { cy.visit('/'); // Log as moutt cy.get('#accountDropdown').click() .get('[routerlink="/auth/login"]').click() .url().should('include', '/auth/login') .get('#login').type('moutt') .get('#password').type('mitt') .get('#btnSearch').click() // Check error message .get('#msg').should('contain.text', "Il n'y a pas d'utilisateur avec l'identifiant moutt.") }); });
'use strict'; module.exports = connector => handlers => ({ js: (event, context, cb) => { const handler = handlers[`${event.handler}`]; if (!handler) { const handlerName = context.functionName.split('-').pop().split("'")[0]; const error = new Error(`[404] Event-handler '${event.handler}' not found in function-handler '${handlerName}'`); return cb(error); } const promisesArray = typeof(handler) === 'function' ? [handler] : handler; try { return connector.apply(null, promisesArray)(event, context, cb); } catch (err) { return cb(err); } } });
let autoUnblock = setInterval(function() { window.scrollBy(0, window.innerHeight); document.querySelectorAll('[aria-label^="Blocked"]').forEach(function(account) { account.click() }); }, 1000);
class APIHandler { constructor (baseUrl) { this.BASE_URL = baseUrl; } getFullList () { $.ajax({ url: "http://ih-api.herokuapp.com/characters", method: "GET", success: function (response) { printFullList(response); }, error: function (err) { console.log(err); }, }); } getOneRegister (id) { $.ajax({ url: "http://ih-api.herokuapp.com/characters/"+id, method: "GET", success: function (response) { printCharacter(response); }, error: function (err) { console.log(err); }, }); } createOneRegister () { let name = $('#name-new').val(); let occupacy = $('#occupation-new').val(); let debt = $('#debt-new').prop("checked"); let weapon = $('#weapon-new').val(); const characterInfo = { name: name, occupation: occupacy, debt: debt, weapon: weapon } $.ajax({ type: 'POST', url: 'http://ih-api.herokuapp.com/characters', data: characterInfo, success: function (response) { showCreation(response); }, error: function (err){ console.log(err); } }); } updateOneRegister () { let name = $('#name-new').val(); let occupacy = $('#occupation-new').val(); let debt = $('#debt-new').prop("checked"); let weapon = $('#weapon-new').val(); const characterInfo = { name: name, occupation: occupacy, debt: debt, weapon: weapon } $.ajax({ type: 'PATCH', url: 'http://ih-api.herokuapp.com/characters', data: characterInfo, success: function (response) { showUpdate(response); }, error: function (err){ console.log(err); } }); } deleteOneRegister () { } }
export default { register: '/user/register', login: 'user/login', userINFO: 'user/info', updateUserInfo: 'user/update' }
const getModelUrl = jest.fn(); getModelUrl.mockReturnValue(''); module.exports = { getModelUrl };
// merage all json file to single one module.exports = () => { return { users: require('./users.json'), posts: require('./posts.json') } }
import startApp from '../helpers/start-app'; import Resolver from '../helpers/resolver'; import Ember from 'ember'; var App; module('Acceptance: Topics', { setup: function() { var topic = Resolver.resolve('model:topic'); topic.reopenClass({ FIXTURES: [ { "id": "1751295897__Berlin", "label": "Berlin", "volume": 165, "type": "topic", "sentiment": { "negative": 3, "neutral": 133, "positive": 29 }, "sentimentScore": 65 }, { "id": "1751295897__Hammered", "label": "Hammered", "volume": 48, "type": "topic", "sentiment": { "neutral": 18, "negative": 30 }, "sentimentScore": 20 }, { "id": "1751295897__Barcelona", "label": "Barcelona", "volume": 7, "type": "topic", "sentiment": { "neutral": 7 }, "sentimentScore": 50 } ]}); App = startApp(); }, teardown: function() { Ember.run(App, 'destroy'); } }); function exists(selector) { return !!window.find(selector).length; } test('should visiting /topics', function() { visit('/'); andThen(function() { equal(currentPath(), 'topics.index'); }); }); test('should render', function() { expect(5); visit('/'); andThen(function() { ok(exists('#div-header')); ok(exists('#div-word-cloud')); ok(exists('#div-topic-details')); ok(exists('#word-cloud-topics')); ok(exists('#table-topic-details')); }); }); test('should show all words', function() { visit('/'); andThen(function() { equal(find('#word-cloud-topics').children(":first").find(':nth-child(1)').text(), 'Berlin'); equal(find('#word-cloud-topics').children(":first").find(':nth-child(2)').text(),'Barcelona'); equal(find('#word-cloud-topics').children(":first").find(':nth-child(3)').text(),'Hammered'); }); }); test('should click on a word', function() { visit('/'); andThen(function() { click('#word-cloud-topics :first :nth-child(1)').then(function(){ ok( true, "word was clicked!" ); }); }); }); test('word should have green color', function() { visit('/'); andThen(function() { equal(find('#word-cloud-topics').children(":first").find(':nth-child(1)').css("fill"), 'rgb(0, 128, 0)'); }); }); test('word should have gray color', function() { visit('/'); andThen(function() { equal(find('#word-cloud-topics').children(":first").find(':nth-child(2)').css("fill"), 'rgb(128, 128, 128)'); }); }); test('word should have red color', function() { visit('/'); andThen(function() { equal(find('#word-cloud-topics').children(":first").find(':nth-child(3)').css("fill"), 'rgb(255, 0, 0)'); }); });
function words(str) { var result = {}; var array = str.split(/\t|\n|\s*\s+/g); console.log(array); for (var i = 0; i < array.length; i++) { //continue skips that iteration and moves on to the next iteration if(array[i] === '') continue; if (!result[array[i]]) { result[array[i]] = 1; } else if (array[i] === 'toString') { result[array[i]] = 1; } else { result[array[i]]++; } } return result; } module.exports = words;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.conf = Object.freeze({ port: Number(process.env.SERVER_PORT) || 3000, cors: process.env.CORS || '*', ttl: 15 * 3600 * 24 * 1000 });
const {exec} = require('child_process'); const child = require('child'); const config = require('../config/config.js'); const GEKKO = __dirname + '/../../gekko'; const GEKKO_API = __dirname + '/../../web/server'; const NODE = 'node'; const CONFIG_ARG = '--config=./reactive-trader/config/tmp-config.js'; const Options = { IMPORT: [GEKKO, '--import', CONFIG_ARG], SERVER: [GEKKO_API, CONFIG_ARG], TRADE: [GEKKO, CONFIG_ARG] }; class GekkoManager { constructor() { this.server = null; this.trader = null; } static getInstance() { if (!this.instance_) { this.instance_ = new GekkoManager(); } return this.instance_; } async importData() { console.log('Importing data'); return new Promise((resolve, reject) => { const importer = child({command: NODE, args: Options.IMPORT, cbStdout: data => { console.log('' + data); if (data.indexOf('Done importing!') >= 0) { importer.stop(); resolve(); } }, cbStderr: data => console.log('' + data), cbClose: exitCode => { resolve(); }, }); importer.start(); }); } async runServer() { if (this.server != null) { await this.stopServer(); } console.log('Running server'); return new Promise((resolve, reject) => { this.server = child({command: NODE, args: Options.SERVER, cbStdout: data => {}, cbStderr: data => console.log('' + data), cbClose: exitCode => { console.log('Server quit unexpectedly', exitCode) this.stopServer().then(() => reject(exitCode)); }, }); this.server.start(); // TODO: Check stdout for when its up and running properly setTimeout(resolve, 4000); }); } stopServer() { console.log('Stopping server'); return new Promise((resolve, reject) => { if (this.server != null) { this.server.stop(resolve); this.server = null; } else { console.log('Stop failed: No server found'); resolve(); } }); } async runTrader() { if (this.trader) { await this.stopTrader(); } return new Promise((resolve, reject) => { this.trader = child({command: NODE, args: Options.TRADE, cbStdout: data => console.log('out ' + data), cbStderr: data => console.log('err ' + data) }); this.trader.start(); // TODO: Check stdout for when its up and running properly setTimeout(resolve, 4000); }); } stopTrader() { console.log('Stopping trader'); return new Promise((resolve, reject) => { if (this.trader != null) { this.trader.stop(resolve); this.trader = null; } else { console.log('Stop failed: No trader found'); resolve(); } }); } } module.exports = GekkoManager;
import styled from 'styled-components'; export const PrimaryText = styled.Text` color: ${props => props.theme.primaryColor}; `; export const SecondaryText = styled.Text` color: ${props => props.theme.secondaryColor}; `;
/** * 公用配置文件 */ define(function() { var C = { /*api地址*/ API_PATH: "http://192.168.1.116:8000/xiaodongdong/api/", /*项目根路径*/ ROOT_PATH: "http://192.168.1.116:90/web/", IMG_PATH: "http://192.168.1.116:8000/xiaodongdong/", /*ajax请求类型*/ DATA_TYPE: "JSON", /*ajax方法类型*/ DATA_METHOD: "post", /*成功code值*/ SUCCESS_CODE:"10000" }; /*后台总权限控制api*/ C.AUTH_API_PATH = C.API_PATH + "sys/login/checkAuth"; /*退出登录*/ C.LOGOUT_PATH = C.API_PATH + "sys/login/logout"; window.C = C; return C; });
import React from 'react'; import Head from 'next/head'; import Layout from 'components/Layout'; import Link from 'next/link'; import BreadcrumbsArrow from 'components/svg/breadcrumbsArrow'; const Index = () => ( <Layout> <Head> <title>Shop | Booma Израиль</title> </Head> <div className="container panel"> <div className="row justify-content-lg-start justify-content-md-start justify-content-sm-center"> <div className="col-md-12"> <h2 className="tabs-content__title">Shop RU</h2> </div> </div> </div> <section className="section about"> <div className="container"> <div className="row"> <div className="col-lg-11 col-12 offset-lg-1 offset-0"> <div className="breadcrumbs"> <ul className="breadcrumbs__list"> <li className="breadcrumbs__item"> <Link href="/ru"> <a className="breadcrumbs__link">Главная RU</a> </Link> <BreadcrumbsArrow /> </li> <li className="breadcrumbs__item"> <Link href="/ru/home"> <a className="breadcrumbs__link">Для дома</a> </Link> <BreadcrumbsArrow /> </li> </ul> </div> </div> </div> </div> <style jsx>{` .breadcrumbs__list { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; padding: 0 0 40px 0; } .breadcrumbs__item { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; margin: 0 7px 0 0; } .breadcrumbs__item svg { margin: 0 0 0 7px; } .breadcrumbs__link { color: #8b8b8b; font-weight: normal; font-size: 14px; line-height: 17px; -webkit-transition: all 0.2s linear; transition: all 0.2s linear; } .breadcrumbs__link:hover { text-decoration: underline; -webkit-transition: all 0.2s linear; transition: all 0.2s linear; } `}</style> <style jsx global>{` .about { padding: 40px 0 60px 0; } `}</style> </section> </Layout> ); export default Index;
export const VIOLET_DARK = '#2D1440'; export const PURPLE = '#AE44C8'; export const PURPLE_BRIGHT = '#9E58DC'; export const SOFT_BLUE = '#785EDD'; export const BLUE_VIOLET = '#8657DB'; export const INPUT_DARK_PURPLE = '#1D0D28'; export const HEADER_PURPLE = '#1D0D28'; export const TEXT_COLOR = '#ECF6F6'; export const COLOR_SILVER = '#bdc3c7'; export const DRAWER_BACKGROUND = '#525659';
// note: this is not intended to be used directly - only through Combobox, or other var proto = require('proto') var Gem = require('gem') var Style = require('gem/Style') // emits a 'change' event when its 'selected' value changes module.exports = proto(Gem, function(superclass) { // staic members this.name = 'Option' this.defaultStyle = Style({ display: 'block', cursor: 'pointer' }) // instance members this.init = function(/*[label,] value*/) { this.domNode = document.createElement("option") // do this before calling the superclass constructor so that an extra useless domNode isn't created inside it superclass.init.call(this) // superclass constructor this._selected = false if(arguments.length===1) { this.val = arguments[0] } else { // 2 this.label = arguments[0] this.val = arguments[1] } } Object.defineProperty(this, 'val', { // returns the value of the Option get: function() { return this._value }, // sets the value of the Option set: function(value) { if(this.parent !== undefined) { if(this.parent.mainGem.options[value] !== undefined) { throw new Error("Can't give an Option the same value as another in the Select or MultiSelect (value: "+JSON.stringify(value)+")") } if(this.val !== null) { delete this.parent.mainGem.options[this.val] } this.parent.mainGem.options[value] = this } this._value = value } }) Object.defineProperty(this, 'selected', { // returns whether or not the option is selected get: function() { return this._selected }, // sets the selected state of the option to the passed value (true for selected) set: function(value) { var booleanValue = value === true if(this._selected === booleanValue) return false; // ignore if there's no change if(this.parent !== undefined) this.parent.mainGem.prepareForValueChange([this.val]) this.setSelectedQuiet(booleanValue) if(this.parent !== undefined) { this.parent.mainGem.changeValue(this.val) this.parent.mainGem.emit('change') } } }) // private // does everything for setting the selected state except emit the parent's change event this.setSelectedQuiet = function(booleanValue) { if(this.selected === booleanValue) return; // ignore if there's no change this._selected = booleanValue this.emit('change') } })
jQuery(document).ready(function() { wow = new WOW( { boxClass: 'wow', animateClass: 'animated', offset: 0, mobile: false, live: true } ) wow.init(); jQuery('.wrapper-logo button.navbar-toggler').click(function() { jQuery('.main-menu-desktop').addClass('show'); jQuery('.overlay').addClass('show'); jQuery('body').addClass('show-menu'); }); jQuery('.main-header .overlay').click(function() { jQuery('.main-menu-desktop').removeClass('show'); jQuery('.overlay').removeClass('show'); jQuery('body').removeClass('show-menu'); }); if($('.contact-us').length) jQuery('.enquiry').click(function(){ $('html, body').animate({ scrollTop:$(".contact-us").offset().top-40 },1000) }); // jQuery('.main-menu-desktop .wrapper-nav-menu .navbar-menu .navbar-nav .dropdown a').click(function(){ // if($(this).parent().hasClass('show')){ // $(this).parents().find('.bg-menu').removeClass('show'); // }else{ // $(this).parents().find('.bg-menu').addClass('show'); // } // }); if ($(window).width() < 992) { jQuery('.sub-header').slick({ dots: false, arrows: false, slidesToShow: 1, slidesToScroll: 1, auto: true, }); } // Search link if ($(window).width() > 992) { $('.nav-link.search-link').click(function(e){ e.preventDefault(); if($('.header-search').hasClass('d-none')){ $('.header-search').removeClass('d-none'); } }); $('.close-search').click(function(e){ if(!$('.header-search').hasClass('d-none')){ $('.header-search').addClass('d-none'); } }); } if ($(window).width() < 992) { $('.menu-mobile .nav-link.search-link').click(function(e){ e.preventDefault(); if($('.header-search-mb').hasClass('d-none')){ $('.header-search-mb').removeClass('d-none'); } }); $('.close-search').click(function(e){ if(!$('.header-search-mb').hasClass('d-none')){ $('.header-search-mb').addClass('d-none'); } }); $('.main-menu-desktop .nav-link.search-link').click(function(e){ e.preventDefault(); }); } jQuery('.section-top-seller .row').slick({ dots: false, arrows: true, slidesToShow: 5, slidesToScroll: 1, auto: true, looop: true, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 4, } }, { breakpoint: 992, settings: { slidesToShow: 3, } }, { breakpoint: 767, settings: { slidesToShow: 2, } }, { breakpoint: 576, settings: { slidesToShow: 1, } } ] }); // var userFeed = new Instafeed({ // get: 'user', // userId: '1417323441', // accessToken: '1417323441.1677ed0.e34f1660a24949de9ecf5c9afd888816', // resolution: 'standard_resolution', // useHttp: "true", // template: '<div class="col-instagram"><a href="{{link}}" target="_blank" id="{{id}}"><div class="drop"><i class="fa fa-instagram"></i></div><div style="background: url({{image}}); background-position: center; padding-top: 100%;"></div></a></div>', // sortBy: 'most-recent', // limit: 6, // target: 'instafeed' // }); // userFeed.run(); jQuery('select.js').each(function() { var $this = jQuery(this), numberOfOptions = jQuery(this).children('option').length; var val = $(this).val(); $this.addClass('select-hidden') $this.wrap('<div class="select"></div>') $this.after('<div class="select-styled"></div>') var $styledSelect = $this.next('div.select-styled'); var $list = jQuery('<ul />', { 'class': 'select-options' }).insertAfter($styledSelect) for (var i = 0; i < numberOfOptions; i++) { var html = $this.children('option').eq(i).text(); if (val == $this.children('option').eq(i).val()) { $styledSelect.text($this.children('option').eq(i).text()); } jQuery('<li />', { html: html, rel: $this.children('option').eq(i).val(), class: (val == $this.children('option').eq(i).val()) ? 'active' : '', }).appendTo($list) } var $listItems = $list.children('li') $styledSelect.click(function(e) { e.stopPropagation() jQuery('div.select-styled.active').not(this).each(function() { jQuery(this).removeClass('active').next('ul.select-options').hide() }) jQuery(this).toggleClass('active').next('ul.select-options').toggle() }) $listItems.click(function(e) { e.stopPropagation(); $styledSelect.text($(this).text()).removeClass('active'); if ((val != $(this).attr('rel') || $(this).attr('rel') == '') && !$(this).hasClass('active')) { $list.children('li').removeClass('active'); $(this).addClass('active'); $this.val($(this).attr('rel')); $this.trigger('change'); } $list.hide() }) jQuery(document).click(function() { $styledSelect.removeClass('active') $list.hide() }) }); $('.section-banner-post').slick({ slidesToShow: 1, slidesToScroll: 1, dots:false, arrows: true, }); $('.list-fabric-main').slick({ slidesToShow: 1, slidesToScroll: 1, arrows: false, fade: true, asNavFor: '.list-img-fabric' }) $('.slider .img-slider').slick({ infinite: true, slidesToShow: 4, slidesToScroll: 1, prevArrow: $('.prev'), nextArrow: $('.next'), responsive: [{ breakpoint: 1200, settings: { slidesToShow: 3, slidesToScroll: 1, } }, { breakpoint: 992, settings: { slidesToShow: 4, slidesToScroll: 1, } }, { breakpoint: 767, settings: { slidesToShow: 3, slidesToScroll: 1, } } ] }); $('.slider .img-slider1').slick({ infinite: true, slidesToShow: 4, slidesToScroll: 2, prevArrow: $('.prev1'), nextArrow: $('.next1'), responsive: [{ breakpoint: 1200, settings: { slidesToShow: 3, slidesToScroll: 1, } }, { breakpoint: 992, settings: { slidesToShow: 4, slidesToScroll: 1, } }, { breakpoint: 767, settings: { slidesToShow: 3, slidesToScroll: 1, } } ] }); $('.slider .img-slider2').slick({ infinite: true, slidesToShow: 4, slidesToScroll: 2, prevArrow: $('.prev2'), nextArrow: $('.next2'), responsive: [{ breakpoint: 1200, settings: { slidesToShow: 3, slidesToScroll: 1, } }, { breakpoint: 992, settings: { slidesToShow: 4, slidesToScroll: 1, } }, { breakpoint: 767, settings: { slidesToShow: 3, slidesToScroll: 1, } } ] }); changePositionElement(); $(window).resize(function() { changePositionElement(); }); function changePositionElement() { let productRange = $('.lampshades-main-content .product-range') if (productRange.length && $(window).width() <= 991) { let listItem = productRange.find('.row'); listItem.map(function(index, item, listItem) { if ($(item).find('.col-lg-4.col-sm-12 img').length) { $(item).find('.info').after($(item).find('.col-lg-4.col-sm-12 img')); } }) } else if (productRange.length && $(window).width() > 991) { let listItem = productRange.find('.row'); listItem.map(function(index, item, listItem) { if ($(item).find('.col-slider > .img-fluid').length) { $(item).find('.col-lg-4.col-sm-12').append($(item).find('.col-slider > .img-fluid')); } }) } } $('.modal-reg-wholesale .btn-close').click(function(){ $('.modal-reg-wholesale').removeClass('show'); }); // Submit // $('#wholesaleSignUp').submit(function(e){ // e.preventDefault(); // $('.nactivity').addClass('open'); // var form = $('#wholesaleSignUp'); // var business = form.find('input[type="checkbox"]'); // var dataBusiness = ''; // business.each(function(index){ // if($(this).is(':checked') == true){ // dataBusiness += $(this).val() + ';'; // } // }); // var customer= { // "Customer": [ // { // "EmailAddress":form.find('input[name="reg_email"]').val(), // "Password":"123456", // "UserGroup":"Wholesale", // "ABN":form.find('input[name="reg_email"]').val(), // "WebsiteURL":form.find('input[name="reg_email"]').val(), // "UserCustom1":dataBusiness, // "UserCustom2":form.find('input[name="reg_mobile_phone"]').val(), // "BillingAddress": { // "BillFirstName":form.find('input[name="reg_first_name"]').val(), // "BillLastName":form.find('input[name="reg_last_name"]').val(), // "BillCompany":form.find('input[name="reg_company"]').val(), // "BillStreetLine1":form.find('input[name="reg_address1"]').val(), // "BillStreetLine2":form.find('input[name="reg_address2"]').val(), // "BillCity":form.find('input[name="reg_suburb"]').val(), // "BillState":form.find('input[name="reg_state"]').val(), // "BillPostCode":form.find('input[name="reg_postcode"]').val(), // "BillCountry":form.find('select[name="reg_bill_country"]').val(), // "BillPhone":form.find('input[name="reg_phone_number"]').val() // } // } // ] // }; // $.ajax({ // async: true, // crossDomain: true, // url: 'https://mayfield.neto.com.au/do/WS/NetoAPI', // headers: { // 'accept': 'application/json', // 'netoapi_action':'AddCustomer', // 'netoapi_key':'1gtxBpHMY89nGu0PnEfDuWnOa65qJFyd', // 'content-type': 'application/json', // 'cache-control': 'no-cache' // }, // method: 'POST', // dataType: 'json', // processData: false, // data: JSON.stringify(customer), // success: function(response){ // $('.nactivity').removeClass('open'); // if(response.Ack != 'Error'){ // $('.p-status').html(''); // $('.modal-reg-wholesale .content-modal').append('<h3>Thank you.</h3><p>We&#39;ll be in touch shortly to confirm your registration.</p><button class="btn btn-close">Done</button>'); // $('.modal-reg-wholesale').addClass('show'); // } else { // $('.p-status').html('<p>'+response.Messages.Error.Message+'</p>'); // } // } // }); // }); $('#wholesaleSignUpMail').find('input[type="checkbox"]').each(function(index){ $(this).on('click',function () { if ($(this).is(':checked')) { $('input[name="inp-business'+index+'"]').val($(this).val()); } else { $('input[name="inp-business'+index+'"]').val(''); } }); }); $('.new-style-popup .npopup-body').bind("DOMSubtreeModified", function() { if ($('.new-style-popup .successaddmessageclear').length) { $('.noverlay').addClass('active'); } else { $('.noverlay').removeClass('active'); } }); $('#zoomProIn').click(zoomProIn_click); $('#zoomProOut').click(zoomProOut_click); move_image(); $('.lampshades-main-content .product-range .list-row-lampshades > .row').each(function(index) { $(this).find('.img-slider').slick({ infinite: true, slidesToShow: 4, slidesToScroll: 1, arrows: true, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 3, slidesToScroll: 1, } }, { breakpoint: 992, settings: { slidesToShow: 4, slidesToScroll: 1, } }, { breakpoint: 767, settings: { slidesToShow: 2, slidesToScroll: 1, } }, { breakpoint: 576, settings: { slidesToShow: 1, slidesToScroll: 1, } } ] }); }); if($('.list-fabric-main').length) { $('.list-fabric-main .fabric-item').each(function(index) { callApiLampShades($(this).data('sku')); }); } selectSlick(); $('.project-gallery-item img').click(function() { getPjGallery($(this).parent('div').data('sku')); }); $('#modalMF .close').click(function() { $('#modalMF').removeClass('open'); $('#modalMF .modal-mf-content .modal-mf-body').html(''); $('#modalMF .modal-mf-content .modal-mf-header h4').remove(); }); }); function getPjGallery(sku){ $('.nactivity').addClass('open'); var data = { "Filter":{ "SKU": sku, "OutputSelector": ["Name","Images","Description"] } }; $.ajax({ async: true, crossDomain: true, url: 'https://mayfield.neto.com.au/do/WS/NetoAPI', headers: { 'accept': 'application/json', 'netoapi_action':'GetItem', 'netoapi_key':'1gtxBpHMY89nGu0PnEfDuWnOa65qJFyd', 'content-type': 'application/json', 'cache-control': 'no-cache' }, method: 'POST', dataType: 'json', processData: false, data: JSON.stringify(data), success: function(response){ $('#modalMF .modal-mf-content .modal-mf-header').append('<h4 class="modal-title">'+response.Item[0].Name+'</h4>') $('#modalMF .modal-mf-content .modal-mf-body').append('<div class="row"><div class="col-xl-8 col-lg-12 col-md-12 col-sm-12"><div class="content-slide-img"></div></div><div class="col-xl-4 col-lg-12 col-md-12 col-sm-12"><div class="content-des"></div></div></div>'); response.Item[0].Images.forEach(item => { $('#modalMF .modal-mf-content .content-slide-img').append('<img class="img-fluid" src="'+item.URL+'"/>'); }); $('#modalMF .modal-mf-content .content-des').append(response.Item[0].Description); $('#modalMF .modal-mf-content .content-des').append('<a href="#">Enquire</a>'); $('.nactivity').removeClass('open'); $('#modalMF').addClass('open'); $('#modalMF .modal-mf-content .content-slide-img').slick({ dots: false, arrows: true, loop: false, slidesToShow: 1, slidesToScroll: 1, auto: false, }); } }); } function callApiLampShades(sku){ var data = { "Filter":{ "SKU": sku, "OutputSelector": ["Name","Description"] } }; $.ajax({ async: true, crossDomain: true, url: 'https://mayfield.neto.com.au/do/WS/NetoAPI', headers: { 'accept': 'application/json', 'netoapi_action':'GetItem', 'netoapi_key':'1gtxBpHMY89nGu0PnEfDuWnOa65qJFyd', 'content-type': 'application/json', 'cache-control': 'no-cache' }, method: 'POST', dataType: 'json', processData: false, data: JSON.stringify(data), success: function(response){ $('.list-fabric-main #fabric' + sku + ' .content-des').append(response.Item[0].Description); } }); } function openModal(id) { if (!jQuery(id).hasClass('open')) { jQuery(id).addClass('open'); jQuery('.modal-pendant.open .content-slide-img').slick({ dots: false, arrows: true, loop: false, slidesToShow: 1, slidesToScroll: 1, auto: false, }); } } function closeModal(id) { if (jQuery(id).hasClass('open')) { jQuery(id).removeClass('open'); } } function loadThumbProduct(data) { $('#contentProAjax').empty(); if (data.Item.length > 0) { data.Item.forEach(element => { var article = document.createElement('article'); cardProduct = document.createElement('div'); $(cardProduct).addClass('card-product').attr('itemscope', '').attr('itemtype', 'http://schema.org/Product'); $(cardProduct).append('<meta itemprop="mpn" content="' + element.SKU + '"/>'); imgProduct = document.createElement('a'); $(imgProduct).addClass('thumbnail-image').attr('href', '#'); if (element.Images[0].URL) imgProSrc = element.Images[0].URL; else imgProSrc = 'https://cdn.neto.com.au/assets/neto-cdn/images/default_product.gif'; $(imgProduct).append('<img src="' + imgProSrc + '" itemprop="image" class="product-image img-fluid">'); $(imgProduct).appendTo(cardProduct); titleProduct = document.createElement('p'); $(titleProduct).addClass('card-title').attr('itemprop', 'name'); $(titleProduct).append('<a href="[@URL@]">' + element.Name + '</a>'); $(titleProduct).appendTo(cardProduct); priceProduct = document.createElement('p'); $(priceProduct).addClass('price'); $(priceProduct).append('<span itemprop="price" content="' + element.DefaultPrice + '">' + element.DefaultPrice + '</span>'); $(priceProduct).append('<meta itemprop="priceCurrency" content="AUD">'); $(priceProduct).appendTo(cardProduct); formBuy = document.createElement('form'); $(formBuy).addClass('form-inline buying-options'); $(formBuy).append('<input type="hidden" id="sku' + element.SKU + '" name="sku' + element.SKU + '" value="' + element.SKU + '">'); $(formBuy).append('<input type="hidden" id="modal' + element.SKU + '" name="modal' + element.SKU + '" value="' + element.Model + '">'); $(formBuy).append('<input type="hidden" id="thumb' + element.SKU + '" name="thumb' + element.SKU + '" value="' + imgProduct + '">'); $(formBuy).append('<input type="hidden" id="qty' + element.SKU + '" name="qty' + element.SKU + '" value="1" class="input-tiny">'); $(formBuy).append('<button type="button" class="addtocart btn btn-block btn-loads" rel="' + element.SKU + '">Add to Cart</button>'); $(formBuy).children('button').attr("data-loading-text", "<i class='fa fa-spinner fa-spin' style='font-size: 14px'></i>"); $(formBuy).append('<span class="product-wishlist"><a class="wishlist_toggle" rel="' + element.SKU + '"><span class="add heart-icon" rel="wishlist_text' + element.SKU + '"></span></a></span>'); $(formBuy).appendTo(cardProduct); $(article).append(cardProduct); $('#contentProAjax').append(article); }); } else { $('#contentProAjax').append('Not found product!'); } } function openModalFabric(id) { $('#modalFabric .modal-fabric-body').html('<div class="row"><div class="col-md-6 col-img"></div><div class="col-md-6 col-description"><div class="container-description"></div></div></div></div>'); $('#contentPro article').each(function(index) { $('#modalFabric .modal-fabric-body .col-img').append('<div class="content-image"><img class="img-fluid" width="264px" src="'+$(this).children().data('thumb')+'"></div>'); $('#modalFabric .modal-fabric-body .container-description').append('<div class="content-description">'+$(this).children().data('description')+'</div>'); }); $('#modalFabric').addClass('open'); var mainSlide = $(id).parent('article').data('stt'); $('#modalFabric .modal-fabric-body .col-img').slick({ slidesToShow: 1, slidesToScroll: 1, arrows: true, dots: false, fade: true, initialSlide: mainSlide, asNavFor: '#modalFabric .modal-fabric-body .container-description' }); $('#modalFabric .modal-fabric-body .container-description').slick({ slidesToShow: 1, slidesToScroll: 1, arrows: false, dots: false, fade: true, asNavFor: '#modalFabric .modal-fabric-body .col-img' }); $('#modalFabric .modal-fabric-body .col-description').append('<a href="#">Enquire</a>'); } function closeModalFabric(){ $('#modalFabric').removeClass('open'); $('#modalFabric .modal-fabric-body').html(''); } var zoom = 0; function zoomProIn_click(){ if(zoom == 0){ $('#main-image').css('transform','scale(1.2)'); zoom ++; return; } if(zoom == 1){ $('#main-image').css('transform','scale(1.4)'); zoom ++; return; } if(zoom == 2){ $('#main-image').css('transform','scale(1.6)'); zoom ++; return; } } function zoomProOut_click(){ if(zoom == 3){ $('#main-image').css('transform','scale(1.4)'); zoom --; return; } if(zoom == 2){ $('#main-image').css('transform','scale(1.2)'); zoom --; return; } if(zoom == 1){ $('#main-image').css('transform','scale(1.0)'); zoom --; return; } } function move_image(){ var x=0; var y=0; var tx=0; var ty=0; var click=false; $('#main-image').mousedown(function(event){ x = event.pageX; y = event.pageY; click = true; }); $('#main-image').mousemove(function(event){ if(click == false) return; let cy = event.pageY,cx = event.pageX; $('#main-image').css('top',(cy-y+ty)); $('#main-image').css('left',(cx-x+tx)); }); $('#main-image').mouseup(function(event){ let cy = event.pageY,cx = event.pageX; tx += cx-x; ty +=cy-y; $('#main-image').css('top',ty); $('#main-image').css('left',tx); //$('#main-image').css('transform','translate(0px, 0px)'); click=false; }); } function selectSlick(){ var countElements = $(".list-img-fabric .fabric-item").length; if (countElements > 10) { $('.list-img-fabric').slick({ slidesToShow: 11, slidesToScroll: 1, asNavFor: '.list-fabric-main', centerMode:false, focusOnSelect: true, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 8, slidesToScroll: 1, } }, { breakpoint: 992, settings: { slidesToShow: 6, slidesToScroll: 1, } }, { breakpoint: 767, settings: { slidesToShow: 3, slidesToScroll: 1, } } ] }); } else { $('.list-img-fabric').slick({ slidesToShow: countElements, slidesToScroll: 1, asNavFor: '.list-fabric-main', centerMode:false, focusOnSelect: true }); } }; function findStockists() { var postCode = $('#postcode').val(); var kmSelected = Number($('#kilometerSelect').val()); var countResult = 0; if(postCode) { $('.list-result').html(''); $('.found-location-status').removeClass('active'); $('.wrapper-submit-find .load-ajax').addClass('load'); geocoder.geocode( { 'address': postCode, region: 'AU'}, function(results, status) { if (status == 'OK') { try { let marker0 = new google.maps.Marker(); marker0.setMap(null); map.setCenter(results[0].geometry.location); // let marker = new google.maps.Marker({ // map: map, // position: results[0].geometry.location // }); var locationPostCode = results[0].geometry.location; glatlngPostCode = new google.maps.LatLng({lat: locationPostCode.lat(), lng: locationPostCode.lng()}); $('#listStloc>li').each(function(index) { $(this).removeClass('result'); let latItem = parseFloat($(this).data('lat')); let lngItem = parseFloat($(this).data('lng')); let glatlngItem = new google.maps.LatLng({lat: latItem, lng: lngItem}); let kmdistance = (google.maps.geometry.spherical.computeDistanceBetween(glatlngPostCode, glatlngItem)*0.001).toFixed(3); if (kmdistance <= kmSelected){ $(this).addClass('result'); $(this).data('km', kmdistance); let marker = new google.maps.Marker({ position: glatlngItem, map: map }); countResult++; } }); if(countResult > 0) { $('.found-location-status').addClass('active'); $('.found-location-status').text(countResult + ' results found'); $('.wrapper-submit-find .load-ajax').removeClass('load'); $('#listStloc>li').each(function(index) { if($(this).hasClass('result')) { $('.list-result').append('<p class="location-details"><b>'+$(this).data('name')+' ('+$(this).data('km')+'km from location)</b><br>'+$(this).data('address')+'<br>'+$(this).data('phone')+'</p>'); } }); } else { $('.wrapper-submit-find .load-ajax').removeClass('load'); $('.found-location-status').addClass('active'); $('.found-location-status').text('Not found!'); } } catch (error) { $('.wrapper-submit-find .load-ajax').removeClass('load'); $('.found-location-status').addClass('active'); $('.found-location-status').text('Error: ' + error); } } else { $('.wrapper-submit-find .load-ajax').removeClass('load'); $('.found-location-status').addClass('active'); $('.found-location-status').text('Not found your location!'); } }); } }
var nameVar=`Andrew`; var nameVar=`mike`; console.log(`nameVar`,nameVar); let nameLet='jen'; nameLet='julie'; console.log('nameLet',nameLet); const nameConst='frank'; console.log('nameConst',nameConst); var fullName=`agha moraddar`; if(fullName){ let firstName=fullName.split(' ')[0]; console.log(firstName); } console.log(firstName);
import Reflux from 'reflux'; import reqwest from 'reqwest'; import Config from 'config'; const SigninActions = Reflux.createActions([ 'signin', 'getUser', 'getEnt' ]); const SigninStore = Reflux.createStore({ listenables: [SigninActions], user:null, ent:{"appid" : "ca52bf40-8a65-11e7-a0b9-1d87294b8940", "entid" : "ent_20170808220894", "entname" : "test"}, onSingnin:function(name, password){ var self = this; reqwest({ url:'', type:'POST', data:{name:name, password:password}, success: function (data, status) { var result = { user:{mobile:'',entid:'',icon:''}, ent:{entid:'', appid:''} }; self.user = result.user; self.ent = result.ent; self.trigger('results', data); }, error: function (reason) { console.log('error',reason); } }) }, onGetUser:function () { var self = this; self.trigger('results', data); }, onGetEnt:function(){ var self = this; self.trigger('getEnt', self.ent); } }); exports.SigninActions = SigninActions; exports.SigninStore = SigninStore;
function runTest() { FBTest.openNewTab(basePath + "dom/3122/issue3122.html", function(win) { FBTest.openFirebug(function() { FBTest.enableScriptPanel(function() { // Wait for break in debugger. var chrome = FW.Firebug.chrome; FBTest.waitForBreakInDebugger(chrome, 36, false, function(sourceRow) { FW.Firebug.chrome.selectSidePanel("watches"); var row = FBTest.getWatchExpressionRow(null, "err"); FBTest.ok(row, "The 'err' expression must be in the watch panel."); // Resume debugger, test done. FBTest.clickContinueButton(); FBTest.testDone(); }); FBTest.click(win.document.getElementById("testButton")); }); }); }); }
const Loading = () => { return ( <div className="loading-wrapper"> <div className="header"> <h1>Microsoft</h1> </div> <div className="center"> <img src="/static/images/window95_logo.png" className="logo" /> <div className="title"> <p className="top">Microsoft</p> <h1>Windows</h1> <span>95</span> <p className="bottom">Microsoft Internet Exporler</p> </div> </div> <div className="progress"> <div className="color-anime" /> </div> </div> ) } export default Loading
module.exports = { add2: (n) => { return n + 2; } }
/** * @param {number[]} nums * @return {number[][]} */ var subsetsWithDup = function(nums) { if(!nums || nums.length ===0) return []; var res = []; var out = []; nums.sort((a, b) => a-b); getSubsets(nums, 0, out, res); return res; }; function getSubsets(nums, pos, out, res1) { res1.push(out.slice()); for (var i = pos; i<nums.length; i++) { out.push(nums[i]); getSubsets(nums, i+1, out, res1); out.pop(); while(i+1 < nums.length && nums[i] === nums[i+1]) i++; } } console.log(subsetsWithDup([1,2,2]))
import "./ability.scss" import "@babel/polyfill" import NumResolver from "@class/resolver/NumericResolver" export default { template: `<div class="paper"> <canvas class="ability" ref="paper" :width="xoffset" :height="yoffset"> 최신 브라우저를 사용해주세요.. </canvas> <!--<div class="dimension"> <div class="tag" v-for="(keyword,idx) in keywords" :style="{ top:top(idx), left:left(idx) }"> {{ keyword }} </div> </div>--> </div>`, data(){ return { paper: null, division: 0, limit: 150, asset: this.asset } }, props: { xoffset:{ default: 250 }, yoffset:{ default: 250 }, phase:{ default: 5, }, asset:{ required: true }, keywords:{ default: ()=>["a","b","c","d","e"] } }, computed:{ x_center(){ return this.xoffset/2 }, y_center(){ return this.yoffset/2 }, vertax(){ return this.asset.length }, radius(){ return (this.xoffset<=this.yoffset)?this.xoffset/2*0.8:this.yoffset/2*0.8 }, radius_a(){ return (this.xoffset<=this.yoffset)?this.xoffset/2*0.9:this.yoffset/2*0.9 }, angle(){ return Math.PI*2/this.asset.length }, top(){ return function(idx){ return Math.sin(this.radius*idx)*this.radius/this.radius*100/2+"%" } }, left(){ return function(idx){ return Math.cos(this.radius*idx)*this.radius/this.radius*100/2+"%" } }, middle(){ let middle_list = [] if(this.keywords.length%2==0){ middle_list.push(this.keywords.length/2-1) middle_list.push(this.keywords.length/2) }else{ middle_list.push(Math.floor(this.keywords.length/2)) middle_list.push(Math.floor(this.keywords.length/2)+1) } return middle_list } }, methods:{ apply(styles){ this.paper.save() Object.entries(styles).forEach(([key,value])=>{ this.paper[key] = value }) }, polygon(radius,styles){ this.apply(styles) this.paper.translate(this.x_center,this.y_center) this.paper.beginPath() this.paper.moveTo(0, -radius) for(let i = 0; i < this.vertax; i++){ this.paper.rotate(this.angle) this.paper.lineTo(0, -radius) } this.paper.closePath() this.paper.stroke() this.paper.restore() }, linear(styles){ this.apply(styles) this.paper.translate(this.x_center,this.y_center) for(let i = 0; i < this.vertax; i++){ this.paper.rotate(this.angle) this.paper.beginPath() this.paper.moveTo(0,0) this.paper.lineTo(0,-this.radius) this.paper.closePath() this.paper.stroke() } this.paper.restore() }, text(styles){ this.apply(styles) this.paper.translate(this.x_center,this.y_center) let width = 0 let offset= 10 for(let i = 0; i < this.vertax; i++){ // console.log(Math.cos(this.radius_a*i-Math.PI*0.50)*this.radius_a*-1, // Math.sin(this.radius_a*i-Math.PI*0.50)*this.radius_a) width = this.length(NumResolver.to_num(styles.font.split(" ")[0]), this.keywords[i]) this.paper.fillText(this.keywords[i], (i < Math.ceil(this.keywords.length/2)) ?(i>0) ?Math.cos(this.radius_a*i-Math.PI*0.55)*this.radius_a*-1 :Math.cos(this.radius_a*i-Math.PI*0.55)*this.radius_a*-1-width*0.9 :Math.cos(this.radius_a*i-Math.PI*0.55)*this.radius_a*-1-width, (this.middle.some(mid=>(mid==i)?true:false)) ?Math.sin(this.radius_a*i-Math.PI*0.55)*this.radius_a+offset :Math.sin(this.radius_a*i-Math.PI*0.55)*this.radius_a) } this.paper.restore() }, length(size,word){ size = (typeof size == 'string')?Number.parseInt(size):size let length = 0 Array.from(word).forEach(char=>(/\S/.test(char)?length+=size:length+=size*0.5)) return length }, set_ability(ability,styles){ this.apply(styles) this.paper.translate(this.x_center,this.y_center) this.paper.beginPath() this.paper.moveTo(0,-ability[0]/100*this.radius) for(let i = 1; i < this.vertax; i++){ this.paper.rotate(this.angle) this.paper.lineTo(0,-ability[i]/100*this.radius) } this.paper.closePath() this.paper.fill() this.paper.stroke() this.paper.restore() this.paper.save() this.paper.translate(this.x_center,this.y_center) this.paper.moveTo(0,-ability[0]/100*this.radius) for(let i = 0; i < this.vertax; i++){ let size = 3 this.paper.save() this.paper.fillStyle = '#FA7253' this.paper.beginPath() this.paper.arc(0, -ability[i]/100*this.radius, size, 0, Math.PI*2) this.paper.fill() //사각형 포인트용 // this.paper.fillRect(size*-1,-ability[i]/100*this.radius-(size*1), size*2,size*2) // this.paper.fillStyle = '#FBE1DB' // this.paper.clearRect(size*-0.5,-ability[i]/100*this.radius-(size*0.5), size,size) // this.paper.fillRect(size*-0.5,-ability[i]/100*this.radius-(size*0.5), size,size) this.paper.restore() this.paper.rotate(this.angle) } this.paper.restore() }, draw(init,growthes,limit){ if(this.division<limit){ this.paper.clearRect(0,0,this.xoffset,this.yoffset) this.paper.save() let styles = { lineWidth: '2', strokeStyle: '#ededed' } for(let i = 0; i < this.phase; i++){ this.polygon(this.radius/this.phase*(i+1), styles) } this.linear(styles) this.paper.save() if(this.division==0){ setTimeout(()=>{ this.set_ability(init,{ lineWidth: '2', strokeStyle: '#FA7253', fillStyle: 'rgba(251, 225, 219, 0.5)'}) this.text({ font: "18px noto_san" , fillStyle: "#666" }) init = init.map((atom,idx)=>atom+growthes[idx]) this.division += 1 setTimeout(()=>this.draw(init,growthes,limit),0.01) },1000) }else{ this.set_ability(init,{ lineWidth: '2', strokeStyle: '#FA7253', fillStyle: 'rgba(251, 225, 219, 0.5)'}) this.text({ font: "18px noto_san" , fillStyle: "#666" }) init = init.map((atom,idx)=>atom+growthes[idx]) this.division += 1 setTimeout(()=>this.draw(init,growthes,limit),0.01) } }else{ return } } }, mounted(){ this.paper = this.$refs.paper.getContext('2d') this.asset = this.asset.map(num=>(num<=10) ?100/this.phase :(Math.round(num*this.phase*0.1)-Math.round(num*this.phase*0.1)%100/this.phase)*10/this.phase) let init = this.asset.map(()=>0), growthes = this.asset.map(ag=>ag/this.limit) this.draw(init,growthes,this.limit) } }
angular .module('altairApp') .controller("holderCtrl", [ '$scope', '$rootScope', '$state', 'lptypes', 'role_data', function ($scope, $rootScope, $state, lptypes, role_data) { $scope.domain = "com.peace.users.model.mram.SubLegalpersons."; $scope.pmenuGrid = { dataSource: { transport: { read: { url: "/user/angular/SubLegalpersons", contentType: "application/json; charset=UTF-8", type: "POST" }, update: { url: "/user/service/editing/update/" + $scope.domain + "", contentType: "application/json; charset=UTF-8", type: "POST", complete: function (e) { $("#notificationUpdate").trigger('click'); } }, destroy: { url: "/user/service/editing/delete/" + $scope.domain + "", contentType: "application/json; charset=UTF-8", type: "POST", complete: function (e) { $("#notificationDestroy").trigger('click'); } }, create: { url: "/user/service/editing/create/" + $scope.domain + "", contentType: "application/json; charset=UTF-8", type: "POST", complete: function (e) { $("#notificationSuccess").trigger('click'); $(".k-grid").data("kendoGrid").dataSource.read(); } }, parameterMap: function (options) { return JSON.stringify(options); } }, schema: { data: "data", total: "total", model: { id: "id" } }, pageSize: 15, serverPaging: true, serverFiltering: true, serverSorting: true }, filterable: { mode: "row" }, sortable: { mode: "multiple", allowUnsort: true }, resizable: true, toolbar: ["excel"], excel: { allPages: true, fileName: "Export.xlsx", filterable: true }, height: function () { return $(window).height() - 175; }, reorderable: true, pageable: { refresh: true, pageSizes: true, buttonCount: 5 }, columns: [ {title: "#", template: "<span class='row-number'></span>", width: "60px"}, {field: "lpReg", title: "<span data-translate='Reg.number'></span>", width: 150}, {field: "lpName", title: "<span data-translate='Company name'></span>", width: 250}, {field: "givName", title: "<span data-translate='Firstname /Mon/'></span>", width: 150}, {field: "phone", title: "<span data-translate='Phone'></span>", width: 150}, {field: "street", title: "<span data-translate='Хаяг'></span>", width: 350}, {field: "GENGINEER", title: "<span data-translate='Ерөнхий инженерийн нэр'></span>", width: 350}, {field: "GENGINEERPHONE", title: "<span data-translate='Утас'></span>", width: 150}, {field: "GENGINEERMAIL", title: "<span data-translate='И-мэйл'></span>", width: 150}, {field: "minehead", title: "<span data-translate='Уурхайн даргын нэр'></span>", width: 350}, {field: "minephone", title: "<span data-translate='Утас'></span>", width: 150}, {field: "mineemail", title: "<span data-translate='И-мэйл'></span>", width: 150}, {field: "ACCOUNTANT", title: "<span data-translate='Нягтлан бодогчийн нэр'></span>", width: 350}, {field: "ACCOUNTANTPHONE", title: "<span data-translate='Утас'></span>", width: 150}, {field: "ACCOUNTANTEMAIL", title: "<span data-translate='И-мэйл'></span>", width: 150}, {field: "ECONOMIST", title: "<span data-translate='Эдийн засагчийн нэр'></span>", width: 350}, {field: "ECONOMISTPHONE", title: "<span data-translate='Утас'></span>", width: 150}, {field: "ECONOMISTEMAIL", title: "<span data-translate='И-мэйл'></span>", width: 150}, {field: "KEYMAN", title: "<span data-translate='Тайлан хариуцсан хүний нэр'></span>", width: 350}, {field: "KEYMANPHONE", title: "<span data-translate='Утас'></span>", width: 150}, {field: "KEYMANEMAIL", title: "<span data-translate='И-мэйл'></span>", width: 150} ], dataBound: function () { var rows = this.items(); $(rows).each(function () { var index = $(this).index() + 1 + ($(".k-grid").data("kendoGrid").dataSource.pageSize() * ($(".k-grid").data("kendoGrid").dataSource.page() - 1)); ; var rowLabel = $(this).find(".row-number"); $(rowLabel).html(index); }); }, } }] )
import React from 'react'; import { NavLink } from 'react-router-dom'; import s from './UsersPageMenu.module.css'; function UsersPageMenu(props) { return ( <div className={s.usersPageMenuWrapper}> <div className={s.navLinkWrapper}> <NavLink to='/users/my_friends' className={s.link} activeClassName={s.activeNavLink}>My Friends</NavLink> </div> <div className={s.navLinkWrapper}> <NavLink to='/users/search_people' className={s.link} activeClassName={s.activeNavLink}>Search People</NavLink> </div> </div> ); } export default UsersPageMenu;
import React, { Component } from 'react' import { BrowserRouter as Router, Route, Switch } from 'react-router-dom' import Login from './features' import Home from './features/home' import Playground from './features/playground' import Lesson from './features/lesson' import EditUser from './features/editUser' import EditLessonList from './features/editLessonList' import EditLesson from './features/editLesson' import Logout from './features/logout' import ComingSoon from './features/notices/ComingSoon' import NotFound from './features/notices/NotFound' class App extends Component { render() { return ( <Router> <Switch> <Route path="/" exact component={Login} /> <Route path="/home" exact component={Home} /> <Route path="/playground" exact component={Playground} /> <Route path="/lesson" exact component={Lesson} /> <Route path="/editUser" exact component={EditUser} /> <Route path="/editLessonList" exact component={EditLessonList} /> <Route path="/editLesson/:index" exact component={EditLesson} /> <Route path="/logout" exact component={Logout} /> <Route path="/comingsoon" exact component={ComingSoon} /> <Route component={NotFound} /> </Switch> </Router> ) } } export default App
import mongoose from "mongoose"; const ChatGroupSchema = new mongoose.Schema({ name: { type: String, }, lastMessageAt: { type: mongoose.Schema.Types.Date, default: Date.now, }, createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "User", }, createdAt: { type: mongoose.Schema.Types.Date, default: Date.now, }, }); export default mongoose.model("ChatGroup", ChatGroupSchema);
import React from 'react' import { BrowserRouter as Router, Route } from 'react-router-dom' import { Container } from 'react-bootstrap' import HomeView from './views/HomeView' import LoginView from './views/LoginView' import RegisterView from './views/RegisterView' import ProductView from './views/ProductView' import CartView from './views/CartView' import ProfileView from './views/ProfileView' import ShippingView from './views/ShippingView' import PaymentView from './views/PaymentView' import PlaceOrderView from './views/PlaceOrderView' import OrderView from './views/OrderView' import Header from './components/Header' import Footer from './components/Footer' function App() { return ( <Router> <Header /> <div className="content py-3"> <Container> <Route path='/' exact component={HomeView}/> <Route path='/search/:keyword' component={HomeView}/> <Route path='/products/:id' exact component={ProductView}/> <Route path='/cart/:id?' exact component={CartView}/> <Route path='/login' component={LoginView}/> <Route path='/register' component={RegisterView}/> <Route path='/profile' component={ProfileView}/> <Route path='/shipping' component={ShippingView}/> <Route path='/payment' component={PaymentView}/> <Route path='/placeorder' component={PlaceOrderView}/> <Route path='/order/:id' component={OrderView}/> </Container> </div> <Footer /> </Router> ); } export default App;
Gabscape = function() { SB.Game.call(this); } goog.inherits(Gabscape, SB.Game); Gabscape.prototype.initialize = function(param) { if (!param) param = {}; if (!param.displayStats) param.displayStats = Gabscape.default_display_stats; this.twitterInfo = param.info; SB.Game.prototype.initialize.call(this, param); this.initEntities(); } Gabscape.prototype.initEntities = function() { this.root = new SB.Entity; // var grid = new SB.Grid({size:64}); // this.root.addComponent(grid); var g1 = new Gabber({name: "Gabber1" }); g1.transform.position.set(15, 0, -20); /* var g2 = new Gabber({name: "Gabber2" }); g2.transform.position.set(-25, 0, -33); var g3 = new Gabber({name: "Gabber3" }); g3.transform.position.set(0, 0, -15); */ var viewer = SB.Prefabs.FPSController({ active : true, headlight : true, cameraPosition : new THREE.Vector3(0, 0, 5) }); this.gabatar = new Gabatar({ info : this.twitterInfo }); this.gabatar.transform.position.set(0, -2.5, 0); viewer.addChild(this.gabatar); viewer.transform.position.set(0, 2.5, 0); this.gabbers = [g1]; // , g2, g3]; this.activeGabber = null; this.root.addChild(g1); // this.root.addChild(g2); // this.root.addChild(g3); this.root.addChild(viewer); this.addEntity(this.root); this.root.realize(); } Gabscape.prototype.getTwitterData = function() { var that = this; Gabulous.getTimeline(function(result, text) { that.timelineCallback(result, text); }); } Gabscape.prototype.timelineCallback = function(result, responseText) { var foo = result; var statusInfo = this.getStatusInfo(result); this.updateStatus(statusInfo); var that = this; Gabulous.getFriends(this.twitterInfo.screen_name, function(result, text) { that.friendsCallback(result, text); }); } Gabscape.prototype.friendsCallback = function(result, responseText) { var foo = result; var friendsInfo = this.getFriendsInfo(result); this.updateFriends(friendsInfo); var that = this; Gabulous.getPublicTimeline(function(result, text) { that.publicTimelineCallback(result, text); }); } Gabscape.prototype.publicTimelineCallback = function(result, responseText) { var foo = result; var statusInfo = this.getStatusInfo(result); this.updatePublicTimeline(statusInfo); } Gabscape.prototype.updateStatus = function(message) { // document.getElementById("status").innerHTML = message; } Gabscape.prototype.getStatusInfo = function(status) { var info = ""; var i, len = status.length; for (i = 0; i < len; i++) { var stat = status[i]; info += ( "<img src='" + stat.user.profile_image_url + "'>" + "<b>" + stat.user.name +"</b>" + " @" + stat.user.screen_name + "<br/>" + stat.text + "<br/>" ); } return info; } Gabscape.prototype.updateFriends = function(message) { // document.getElementById("friends").innerHTML = message; } Gabscape.prototype.getFriendsInfo = function(friends) { var info = ""; var i, len = friends.length; for (i = 0; i < len; i++) { var friend = friends[i][0]; info += ( "<img src='" + friend.profile_image_url + "'>" + "<b>" + friend.name +"</b>" + " @" + friend.screen_name + "<br/>" + friend.status.text + "<br/>" ); } return info; } Gabscape.prototype.updatePublicTimeline = function(message) { // document.getElementById("public").innerHTML = message; } Gabscape.prototype.onKeyDown = function(keyCode, charCode) { this.whichKeyDown = keyCode; if (this.activeGabber) this.activeGabber.onKeyDown(keyCode, charCode); else SB.Game.prototype.onKeyDown.call(this, keyCode, charCode) } Gabscape.prototype.onKeyUp = function(keyCode, charCode) { var mi; var handled = false; switch (String.fromCharCode(keyCode)) { case 'H' : this.help(); handled = true; break; case '1' : mi = 1; break; case '2' : mi = 2; break; case '3' : mi = 3; break; default : break; } if (!handled && this.activeGabber) { this.activeGabber.onKeyUp(keyCode, charCode); } if (mi) { var gabber = this.gabbers[mi-1]; this.setActiveGabber(gabber); } if (!handled) SB.Game.prototype.onKeyUp.call(this, keyCode, charCode) } Gabscape.prototype.onKeyPress = function(keyCode, charCode) { SB.Game.prototype.onKeyPress.call(this, keyCode, charCode) } Gabscape.prototype.onTimeChanged = function(t) { return; if (!this.activeGabber) { var handled = false; switch (this.whichKeyDown) { case SB.Keyboard.KEY_LEFT : this.turn(+1); handled = true; break; case SB.Keyboard.KEY_UP : this.move(-1); handled = true; break; case SB.Keyboard.KEY_RIGHT : this.turn(-1); handled = true; break; case SB.Keyboard.KEY_DOWN : this.move(+1); handled = true; break; } if (!handled) { switch (String.fromCharCode(this.whichKeyDown)) { case 'A' : this.turn(+1); handled = true; break; case 'W' : this.move(-1); handled = true; break; case 'D' : this.turn(-1); handled = true; break; case 'S' : this.move(+1); handled = true; break; default : break; } } } } Gabscape.prototype.onTimeFractionChanged = function(fraction) { this.turnFraction = fraction; } Gabscape.prototype.setActiveGabber = function(gabber) { if (this.activeGabber) { this.activeGabber.setActive(false); } gabber.setActive(true); this.activeGabber = gabber; } Gabscape.prototype.help = function() { if (!this.helpScreen) { this.helpScreen = new GabscapeHelp(); } this.helpScreen.show(); } Gabscape.default_display_stats = false;
import _ from "lodash" import { GET_BY_ID_AND_START_EXAMLOG_DATA, GET_BY_ID_AND_START_EXAMLOG_SUCCESS, GET_BY_ID_AND_START_EXAMLOG_FAILURE, SET_QUESTION_ANSWERS_EXAMLOG_DATA, SET_QUESTION_ANSWERS_EXAMLOG_SUCCESS, SET_QUESTION_ANSWERS_EXAMLOG_FAILURE, SET_QUESTION_ISMARKED_EXAMLOG_DATA, SET_QUESTION_ISMARKED_EXAMLOG_SUCCESS, SET_QUESTION_ISMARKED_EXAMLOG_FAILURE } from "./actions" const initialState = { payload: { questions: [{ title: "", answer: { list: [], selectedIds: [], } }], exam: { passingGrade: 0 }, result:{ pass: 0, failed: 0 }, isStart: false, isSubmit: false, endTime: "0" }, isLoading: false, error: {}, } export default (state = initialState, action) => { switch (action.type) { case GET_BY_ID_AND_START_EXAMLOG_DATA: return { ...state, isLoading: true } case GET_BY_ID_AND_START_EXAMLOG_SUCCESS: return { ...state, isLoading: false, payload: action.payload } case GET_BY_ID_AND_START_EXAMLOG_FAILURE: return { ...state, isLoading: false, error: action.error } case SET_QUESTION_ANSWERS_EXAMLOG_DATA: let index = _.findIndex(state.payload.questions, { id: action.questionId } ) state.payload.questions[index].answer.tempSelectedIds = state.payload.questions[index].answer.selectedIds state.payload.questions[index].answer.selectedIds = [action.answerId] return { ...state } case SET_QUESTION_ANSWERS_EXAMLOG_SUCCESS: index = _.findIndex(state.payload.questions, { id: action.questionId } ) state.payload.questions[index].answer.tempSelectedIds = state.payload.questions[index].answer.selectedIds return { ...state } case SET_QUESTION_ANSWERS_EXAMLOG_FAILURE: index = _.findIndex(state.payload.questions, { id: action.questionId } ) state.payload.questions[index].answer.selectedIds = state.payload.questions[index].answer.tempSelectedIds return { ...state } case SET_QUESTION_ISMARKED_EXAMLOG_DATA: index = _.findIndex(state.payload.questions, { id: action.questionId } ) state.payload.questions[index].tempIsMarked = state.payload.questions[index].isMarked state.payload.questions[index].isMarked = action.isMarked return { ...state } case SET_QUESTION_ISMARKED_EXAMLOG_SUCCESS: index = _.findIndex(state.payload.questions, { id: action.questionId } ) state.payload.questions[index].tempIsMarked = state.payload.questions[index].isMarked return { ...state } case SET_QUESTION_ISMARKED_EXAMLOG_FAILURE: index = _.findIndex(state.payload.questions, { id: action.questionId } ) state.payload.questions[index].isMarked = state.payload.questions[index].tempIsMarked return { ...state } default: return state } }
const init = require('./new') const start = require('./start') const build = require('./build') exports.init = init exports.build = build exports.start = start
export { default as Products } from './products'; export { default as fetchProducts } from './products.mock';
angular.module('recommend.route', [ ]) .config([ '$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider .state('tab.recommend', { url: '/recommend', views: { 'tab-recommend': { templateUrl: './areas/recommend/recommend.html', controller: 'recommendController' } } }) } ]);
import _ from 'underscore'; import BaseModel from '../../../base/model/base'; export default class PlaydayModel extends BaseModel { constructor (options) { super(options); } url () { return _.getApiUrl('playday'); } }
function shellSort(numbers) { var length = numbers.length; var h = 1; // 3x + 1 increment sequence while (h < length / 3) { h = 3 * h + 1; } while (h >= 1) { // h-sort the array for (var i = h; i < length; i++) { for (var j = i; j >= h && numbers[j] < numbers[j - h]; j -= h) { var temp = numbers[j]; numbers[j] = numbers[j - h]; numbers[j - h] = temp; } } h = Math.floor(h / 3); } } exports.shellSort = shellSort;
import './accounts.js'; import './data.js';
import React, { Component } from "react"; import firebaseConfig from "./firebaseconfig"; export default class Forgotpassword extends Component { constructor() { super(); this.state = { email: null, error: false }; this.emailCatch = this.emailCatch.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } emailCatch(e) { let email = e.target.value; this.setState({ email: email }) console.log(this.state); } handleSubmit(e) { e.preventDefault(); firebaseConfig.auth().sendPasswordResetEmail( this.state.email, null) .catch( (error) => { this.setState({ error: true }) console.log(error) }); } render() { return ( <div className='loginsigninext'> <div className='loginsigninint'> <form> <h3>Olvidaste tu contraseña?</h3> { this.state.error && <h4 className="errorMessage"> Por favor comprueba tu e-mail y trata otra vez </h4> } <div className='form-group'> <label>Email</label> <input type="email" className="form-control" placeholder="Enter email" onChange={this.emailCatch}/> <button type="submit" className="btn btn-primary btn-block" onClick={this.handleSubmit}>Reestablecer contraseña</button> </div> </form> </div> </div> ) } }
import React from "react"; import { Route } from "react-router-dom"; import Home from "./Home"; import SignupForm from "./SignupForm"; import Navbar from "./Navbar"; import Grid from "@material-ui/core/Grid"; import "./styles/App.css"; function App() { return ( <div className='App'> <Navbar /> <Grid container justify='space-around'> <Grid item xs={12} s={6} md={4}> <Route exact path='/' component={Home} /> <Route exact path='/signup' component={SignupForm} /> </Grid> </Grid> </div> ); } export default App;
function ajaxQuote() { $.ajax({ url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1', success: function(data) { var post = data.shift(); // The data is an array of posts. Grab the first one. $("#text-quote").empty().append(post.content); $("#author-quote").empty().append(post.title); }, cache: false }); }; $(document).ready(ajaxQuote); $("#new-quote").on("click", ajaxQuote); $("#share-twitter").click(function() { var textTweet = $("#text-quote p").text() + " - " + $("#author-quote").text(); var tweetLink = 'https://twitter.com/intent/tweet?text=' + encodeURIComponent(textTweet); window.open(tweetLink, '_blank'); });
const getRegValues = require('./reg'); const PAC_RE = /(https?:\/\/[\x20-\x7e]+)/g; const PAC_SUFFIX = /\.pac(?:\?|$)/i; const SETTINGS_PATH = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Connections'; const SETTINGS_KEY = 'DefaultConnectionSettings'; let timer; let pacUrl; const toString = (value) => { const result = []; for (let i = 0, len = value.length; i < len;) { const code = parseInt(value.substring(i, i += 2), 16); result.push(String.fromCharCode(code)); } return result.join(''); }; const parsePacUrl = (value) => { value = toString(value).match(PAC_RE); if (!value) { return ''; } const len = value.length; for (let i = 0; i < len; i++) { const url = value[i]; if (PAC_SUFFIX.test(url)) { return url; } } return value[len - 1]; }; const loadPacUrl = (init) => { clearTimeout(timer); const result = getRegValues(SETTINGS_PATH).then((list) => { const { value } = list.find(item => item.name === SETTINGS_KEY); pacUrl = result; timer = setTimeout(loadPacUrl, 10000); return parsePacUrl(value); }, (err) => { if (init) { pacUrl = null; } timer = setTimeout(loadPacUrl, 1000); throw err; }); pacUrl = pacUrl || result; return result; }; module.exports = () => { pacUrl = pacUrl || loadPacUrl(true); return pacUrl; };
import gql from 'graphql-tag'; // Logout Mutation export const mLogout = gql ` mutation{ logout{ id email } }` // Login Mutation export const mLogin = gql ` mutation loginUser($email : String, $password : String){ login(email:$email, password : $password){ id email } }` // SignUp Mutation export const mSignUp = gql ` mutation SignUp($email : String, $password : String){ signup(email:$email, password : $password){ id email } }` // Adding Poem to User export const mAddPoem2user = gql` mutation addPoem2user($title: String, $userId:ID){ addPoemToUser(title:$title, userId:$userId){ id email poems{ id title } } } `
const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function(app) { // const wsProxy = createProxyMiddleware('/ws', { // target: 'ws://parseapi.back4app.com', // pathRewrite: { // '^/ws' : '/', // rewrite path. // '^/parse-api' : '' // remove path. // }, // changeOrigin: true, // for vhosted sites, changes host header to match to target's host // ws: true, // enable websocket proxy // logLevel: 'debug' // }); app.use( '/bass-api', createProxyMiddleware({ // target: 'https://api.parse.com', // target host target: 'https://zkicsetztdaigfpjfeor.supabase.co', changeOrigin: true, // needed for virtual hosted sites ws: true, // proxy websockets pathRewrite: { '^/bass-api': '/', // rewrite path }, logLevel: 'debug', }), ); // app.use( // '/nada-disso', // createProxyMiddleware({ // target: 'https://parseapi.back4app.com', // pathRewrite: { // '^/nada-disso': '/', // rewrite path // }, // changeOrigin: true, // for vhosted sites, changes host header to match to target's host // ws: true, // enable websocket proxy // logLevel: 'debug' // }) // ); };
export default { appCurrency(value) { if (!value) return ''; return `R$ ${String(value.toFixed(2)).replace(/,/g, '^').replace(/\./g, ',').replace(/\^/g, '.')}`; }, appStatus(value) { if (!value) return ''; let statuses = { AVAILABLE: 'Disponível', RENTED: 'Alugado', MAINTENANCE: 'Em Manutenção', FOR_SALE: 'À Venda', SOLD: 'Vendido', UNAVAILABLE: 'Indisponível' }; return statuses[value] || value; }, appCategory(value) { if (!value) return ''; let categories = { SMALL: 'Pequeno', HATCH: 'Hatch', SEDAN: 'Sedã', SUV: 'SUV', LUXURY: 'Luxo', SPORTING: 'Esportivo', }; return categories[value] || value; } }
import React, { useContext } from 'react' import UserAvatar from './UserAvatar' import { UserContext} from '../App' function Nav() { const user = useContext(UserContext) return ( <div className='nav'> <UserAvatar user={user}/> </div> ) } export default Nav
import React, { useState, useEffect } from 'react'; import { Map } from '../Map/Map.jsx'; import { Animal } from '../Animal/Animal'; import { Modal } from '../Modal/Modal.jsx'; import zebra from '../Animal/Gallery/Africa/zebra.svg'; import panda from '../Animal//Gallery/Asia/panda.svg'; import kangaroo from '../Animal//Gallery/Australia/kangaroo.svg'; import europeanBeaver from '../Animal//Gallery/Europe/europeanBeaver.svg'; import lamaAlpaca from '../Animal//Gallery/SouthAmerica/lamaAlpaca.svg'; import americanBison from '../Animal//Gallery/NorthAmerica/americanBison.svg'; import useSound from 'use-sound'; import success from '../../audio/success.mp3'; import fail from '../../audio/fail.mp3'; export const Game = ({ onMoveToResult, onCounter, onNumberOfAnimals }) => { const [move, setMove] = useState(null); const [index, setIndex] = useState(null); const [result, setResult] = useState(null); const [closeModal, setCloseModal] = useState(null); const [reloadMap, setReloadMap] = useState(true); const [counter, setCounter] = useState(0); const [animals, setAnimals] = useState([ { img: zebra, name: 'zebra stepní', area: 'AF', text: 'Jsem známá svým pruhováním, kterým se odlišuji od svých příbuzných.', visible: true, }, { img: panda, name: 'panda velká', area: 'AS', text: 'Moje zbarvení je nápadně černobílé a živím se převážně bambusovými výhonky', visible: true, }, { img: kangaroo, name: 'klokan velký', area: 'OC', text: 'Můj ocas je tak silný, že mi slouží jako opora těla.', visible: true, }, { img: europeanBeaver, name: 'bobr evropský', area: 'EU', text: 'Pomocí svých mohutných zubů buduji na řekách hráze.', visible: true, }, { img: lamaAlpaca, name: 'lama alpaka', area: 'SA', text: 'Říkají mi horský velbloud a mám velmi jemnou srst', visible: true, }, { img: americanBison, name: 'bizon americký', area: 'NA', text: 'Možná vypadám těžkopádně, ale dokážu běžet rychlostí až 50 km/h', visible: true, }, ]); const [availableAnimals, setAvailableAnimals] = useState(animals); const [chosenAnimals, setChosenAnimals] = useState([]); const [moveToResult, setMoveToResult] = useState(true); const handleMove = (item, reload) => { setMove(item); setReloadMap(reload); setCounter(counter + 1); }; const handleClick = () => { setCloseModal(true); setAnimals(availableAnimals); setIndex(round(availableAnimals.length)); setReloadMap(true); setResult(false); if (availableAnimals.length === 0) { onMoveToResult(moveToResult); onCounter(counter); } }; const round = (animalsCount) => { let randomNumber = Math.floor(Math.random() * animalsCount); return randomNumber; }; const shuffle = (array) => { var currentIndex = array.length, randomIndex; while (0 !== currentIndex) { randomIndex = Math.ceil(Math.random() * currentIndex); currentIndex--; [array[currentIndex], array[randomIndex]] = [ array[randomIndex], array[currentIndex], ]; } return array; }; useEffect(() => { const newArray = shuffle(animals).slice(0, 3); setChosenAnimals(newArray); setIndex(round(animals.length)); }, []); const [playSuccess] = useSound(success); const [playFail] = useSound(fail); useEffect(() => { if (index !== null) { setResult(move === animals[index].area), move === animals[index].area ? playSuccess() : playFail(); setCloseModal(false); } }, [counter]); const [correctAnswers, setCorrectAnswers] = useState(0); useEffect(() => { if (result === true) { availableAnimals[index].visible = false; setAvailableAnimals( chosenAnimals.filter((animal) => animal.visible === true), ); setCorrectAnswers(correctAnswers + 1); } }, [result]); useEffect(() => { onNumberOfAnimals(correctAnswers); }); return ( <> <Map onMove={handleMove} reloadMap={reloadMap} /> {index === null ? ( 'načítám' ) : ( <Animal key={animals[index].name} img={animals[index].img} name={animals[index].name} /> )}{' '} {result === null || closeModal ? undefined : result ? ( <Modal onCloseModal={handleClick} text={animals[index].text} modal=" modal-container--true" /> ) : ( <Modal onCloseModal={handleClick} text="Bohužel. Tady není můj domov." modal=" modal-container--false" /> )} </> ); };
/* * Class to handle leads */ //const Model = require('../models/lead.js'); const path = require('path'); const fs = require('fs'); const util = require('util'); var readFile = util.promisify(fs.readFile); var writeFile = util.promisify(fs.writeFile); class Lead { constructor(filename) { this.filename = path.join(__dirname, '../data/leads.json'); } static now() { return Math.floor(new Date() / 1000); } async create(lead) { // will insert into mongoose later // but for now will be inserting into local file var all = await this.all(); all.unshift(lead); // add to front of array await writeFile(this.filename, JSON.stringify(all.sort((a,b) => b.datetime - a.datetime))); return {success: "Lead has been successfully inserted!"}; /* var user = new Model(); user.name = lead.name; user.email = lead.email; user.phone = lead.phone; user.datetime = lead.datetime; return await user.save(); */ } async all() { // will grab from mongoose later // for now, read from file var data = await readFile(this.filename, 'utf8'); if ( ! data) return []; return JSON.parse(data); } async read(id) { // will grab from mongoose later // for now, read from file var all = this.all(); Object.keys(all).forEach((key) => { if (all[key].id === id){ return all[key]; } }); return []; // unable to find } update(id,data) { } delete(id) { } } module.exports = Lead;
'use strict'; module.exports = function (sequelize, DataTypes) { var OutfitMember = sequelize.define('OutfitMember', { characterId: { type: DataTypes.BIGINT.UNSIGNED, field: 'character_id', primaryKey: true }, outfitId: { type: DataTypes.BIGINT.UNSIGNED, field: 'outfit_id' }, memberSinceDate: { type: DataTypes.DATE, field: 'member_since_date' }, rank: { type: DataTypes.STRING, field: 'rank' }, rankOrdinal: { type: DataTypes.INTEGER, field: 'rank_ordinal' } }, { tableName: 'outfit_member', classMethods: { associate: function (models) { OutfitMember.belongsTo(models.Character, { foreignKey: 'characterId', onDelete: 'CASCADE', onUpdate: 'NO ACTION' }); OutfitMember.belongsTo(models.Outfit, { foreignKey: 'outfitId', onDelete: 'CASCADE', onUpdate: 'NO ACTION' }); } } }); return OutfitMember; };
/** host: devcenter.heroku.com */ window.bsdpower.ready(function() { jQuery(function($) { alert(2); $(document.body).focus(); }); });
import React from "react"; import { Link } from "react-router-dom"; import "../styles/NewMovies.css"; const newMovies = (props) => { const newMovies = props.newMovies.map((movie, i) => { let imageLink = "https://image.tmdb.org/t/p/w300" + movie.poster_path; let link = "/movie/" + movie.id; return ( <Link to={link} key={i}> <div className="movie"> <img src={imageLink} alt="movie poster"/> </div> </Link> ); }); return ( <div className="movies"> {newMovies} </div> ); } export default newMovies;
class Orientation { static ORIENTATIONS = { TOP: "TOP", RIGHT: "RIGHT", BOTTOM: "BOTTOM", LEFT: "LEFT" }; constructor(orientation) { this.currentOrientation = orientation; } getOpposite() { switch (this.currentOrientation) { case "LEFT": { return "RIGHT" } case "RIGHT": { return "LEFT" } case "TOP": { return "BOTTOM" } case "BOTTOM": { return "TOP" } } } } class Shape { static SHAPES = { INNER: "INNER", OUTER: "OUTER", FLAT: "FLAT" }; constructor(shape) { this.shape = shape; } getOpposite() { switch (this.shape) { case "LEFT": { return "RIGHT" } case "RIGHT": { return "LEFT" } default: return null; } } } class Puzzle { constructor(pieces, size) { this.pieces = []; this.piece = [ [] ]; this.size = size; } setEdgeInSolution(pieces, edge, row, column, orientation) { let piece = edge.getParentPiece(); } } class Piece { constructor(edgeList) { } rotateEdgesBy(numberOfRotations) {} isCorner() {} isBorder() {} } class Edge { constructor(shape, parentShape) { this.shape = shape; this.parent = parentShape } fitsWith(edge) {} } function solve() { let cornerPieces = []; let borderPieces = []; let insidePieces = []; groupPieces(cornerPieces, borderPieces, insidePieces); solution = new Piece[size][size]; for (let row = 0; row < size; row++) { for (let column = 0; column < size; column++) { piecesToSearch = getPieceListToSearch(cornerPieces, borderPieces, insidePieces, row, column); if (!fitNextEdge(piecesToSearch, row, column)) { return false; } } } return true; } function fitNextEdge(piecesToSearch, row, column) { if( row === 0 && column === 0){ let p = piecesToSearch.remove(); orientTopLeftCorner(p); solution[0][0] = p; }else{ let pieceToMatch = column === 0 ? solution[row - 1][0] : solution[row][column - 1]; let orientationToMatch = column === 0 ? Orientation.ORIENTATIONS.BOTTOM : Orientation.ORIENTATIONS.TOP; let edgeToMatch = pieceToMatch.getEdgeWithOrientation(orientationToMatch); let edge = getMatchingEdge(edgeToMatch, piecesToSearch); if( edge === null){ return false; } orientation = orientationToMatch.getOpposite(); setEdgeInSolution(piecesToSearch,edge,row,column,orientation); } return true; }
//Asynchronous Programming const f1 = (word) => { let count = 0; let handle = setInterval(() => { console.log(word) count++; if(count>10){ clearInterval(handle); } }, 500); } f1("Hello"); f1("Hai");
import flatten from './flatten' import camelCase from './camelCase' import dataSchema from './dataSchema' import {OrderedSet, List, Repeat, Map} from 'immutable' import { CharacterMetadata, ContentBlock, ContentState, genKey, } from 'draft-js' /** * Compiler */ function compiler (ast, config = {}) { /** * Create an empty ContentState object */ let entityContentState = ContentState.createFromText('') /** * Called for each node in the abstract syntax tree (AST) that makes up the * state contained in the store. We identify the node by `type` * * @param {Array} Array representing a single node from the AST * @param {Boolean} first Is the first item in the AST? * @param {Boolean} last Is the last item in the AST? * * @return {Array} Result of the visit/render */ function visit (node, opts) { const type = node[0] const content = node[1] const visitMethod = 'visit' + camelCase(type, true) return destinations[visitMethod](content, opts) } /** * A reference object so we can call our dynamic functions in `visit` * @type {Object} */ const destinations = { /** * Called for each node that identifies as a 'block'. Identifies the block * _type_ function from the `renderers` * * @param {Array} Array representing a single block node from the AST * @param {Boolean} first Is the first item in the AST? * @param {Boolean} last Is the last item in the AST? * * @return {Function} Result of the relevant `renderers.block[type]` * function */ visitBlock (node, opts) { const childBlocks = [] let depth = opts.depth || 0 const type = node[dataSchema.block.type] const children = node[dataSchema.block.children] const data = Map(node[dataSchema.block.data]) // Build up block content let text = '' let characterList = List() children.forEach((child) => { const type = child[0] const childData = visit(child, {depth: depth + 1}) // Nested blocks will be added to the `blocks` array // when visited if (type === 'block') { childBlocks.push(childData) } else { // Combine the text and the character list text = text + childData.text characterList = characterList.concat(childData.characterList) } }) const contentBlock = new ContentBlock({ key: genKey(), text, type, characterList, depth, data, }) return [contentBlock, childBlocks] }, /** * Called for each node that identifies as a 'entity'. Identifies the * entity _type_ function from the `renderers` * * @param {Array} Array representing a single entity node from the AST * @param {Boolean} first Is the first item in the AST? * @param {Boolean} last Is the last item in the AST? * * @return {Function} Result of the relevant `renderers.entity[type]` * function */ visitEntity (node) { const type = node[dataSchema.entity.type] const mutability = node[dataSchema.entity.mutability] const data = node[dataSchema.entity.data] const children = node[dataSchema.entity.children] // Create the entity and note its key // run over all the children and aggregate them into the // format we need for the final parent block entityContentState = entityContentState.createEntity( type, mutability, data ) const entityKey = entityContentState.getLastCreatedEntityKey() let text = '' let characterList = List() children.forEach((child) => { const childData = visit(child, {entityKey}) // Combine the text and the character list text = text + childData.text characterList = characterList.concat(childData.characterList) }) return { text, characterList, } }, /** * Called for each node that identifies as a 'inline'. Identifies the * entity _type_ function from the `renderers` * * @param {Array} Array representing a single inline node from the AST * @param {Boolean} first Is the first item in the AST? * @param {Boolean} last Is the last item in the AST? * * @return {Function} Result of the relevant `renderers.inline[type]` * function */ visitInline (node, opts = {}) { const styles = node[dataSchema.inline.styles] const text = node[dataSchema.inline.text] // Convert the styles into an OrderedSet const style = OrderedSet( styles.map((style) => style) ) // Create a List that has the style values for each character let charMetadata = CharacterMetadata.create({ style, entity: opts.entityKey || null, }) // We want the styles to apply to the entire range of `text` let characterMeta = Repeat(charMetadata, text.length) const characterList = characterMeta.toList() return { text, characterList, } }, } if (ast.length > 0) { // Procedurally visit each node const blocks = flatten(ast.map(visit)) // Build a valid ContentState that combines the blocks and the entity map // from the entityContentState return ContentState.createFromBlockArray(blocks, entityContentState.getEntityMap()) } else { return ContentState.createFromText('') } } export default compiler
var a = 10; var b = 22.22; var sum = a+ b; console.log('输出相加的结果:'+sum);
// Array.prototype.mid = function (v) { // const midIndex = Math.round(this.length / 2); // const removedElements = this.splice(midIndex, (this.length - midIndex), v); // const expectedArray = this.concat(removedElements); // this.splice(0, this.length, ...expectedArray); // return v // }; // // // Primitive Data Type // // /* // // 1. string type // // 2. number type // // 3. boolean type // // 4. undefined // // 5. null // // 6. NaN // // */ // // // Data type conversion: implicit and explicit conversion // // //explicit conversion: In this fact, Programmer must do the conversion. e.g. // // // + operator er kaj dui rokom. ekta hochche addition, arekta hochche concatenation // // var num = 15 // // console.log(String(num)) // '15' // // var string = '20' // // var calc = Number(string) + 10 // explicit conversion // // console.log(calc) // // console.log(Number(true) + 15) // true = 1 // // console.log(Number(false) + 10) // false = 0 // // console.log(Boolean(0)) // undefined, null, 0, NaN, '' // // // implicit conversion: auto conversion done by JS Engine // // console.log('A' + 'B') // // console.log(10 + 5) // arithmetic operation // // console.log('10' + 5) // '10' + String(5) = '105' // // console.log('20' - '5') // Number("20") - 5 = 15 // // // triple eual/ strict equal / double equal/ loose equal // // console.log(false === 0) // // console.log(false == 0) // Number(false) == 0 --> 0 == 0 // // // false == Boolean(0) --> false == false // // console.log([] == 0) // Number([]) == 0 --> 0 == 0 // // console.log([20] - 13) // Number([20]) - 13 --> 20 - 13 // // console.log([20] + 13) // String([20]) + 13 --> "20" + 13 // // console.log(NaN == NaN) // false // // console.log(Boolean(NaN) == Boolean(NaN)) // false // // // isNaN always checks if the given data/ value is character string. if it is, isNaN will return true, otherwise false // // var str = 'bogra' // // //console.log(Number(str)) // // console.log(isNaN(str)) // isNaN(Number(str)) // // // isNaN --> is it character? // // // !isNaN --> is it number? // // if(!isNaN(str)) { // !isNaN --> is a number? // // //console.log('it works') // // }; // // var value = 10 // // //console.log(typeof value) // "string", "number" // // if(typeof value === 'string') { // // console.log('This is string') // // } // // console.log(Number(false) === 0) // Number(false) === 0 // // console.log(false == '0') // // // lexicographical ordered operation / alphabetical order // // // all capital letters are smaller than small letters // // console.log('c' < 'ac') // // console.log("69" > "59") // // console.log(15456451351 < 'A') // always false // // console.log('A' > '=') // // console.log(Boolean(undefined) === Boolean(null)) // // console.log(undefined == null) // true // // console.log(NaN === NaN) // // console.log(undefined === undefined) // // console.log(null === null) // // console.log([] == 0) // // console.log([] === []) // // console.log({a:5} === {a:5}) // // // reference data type // // var a = 5 // // var b = a // // a = 10 // // console.log(b) // // var obj = { // // x: 15 // // } // // var obj1 = obj // // obj.x = 20 // // console.log(obj1) // // console.log('************************************') // // /* // // আপনাকে এমন একটি function তৈরী করতে হবে যা input হিসেবে একটি number নিবে এবং সেই number এর প্রতিটি digit কে বর্গ করে তাকে concatenate করে একটি নতুন number output হিসেবে পাঠাবে। function-টিতে অবশ্যই return statement ব্যবহার করতে হবে। // // উদাহরণস্বরূপ, আমরা যদি function-টির মাধ্যমে 9119 input দেই তবে output হিসেবে আসবে 811181, কারণ 9^2 -> 81 এবং 1^1 -> 1 // // */ // // /* // // 9 -> 9^2 = 81 // // 1 -> 1^ 2 = 1 // // 1 -> 1^2 = 1 // // 9 -> 9^2 = 81 // // '81' + '1' + '1' + '81' = '811181' -> 811181 <- // // */ // // function test(num) { // // var string = String(num) // "9119" // // var result = '' // "811181" // // for(var i = 0; i < string.length; i++) { // // result = result + (string[i] * string[i]) // Math.pow(string[i], string[i]) // // } // // return result // // } // // //console.log(test(99)) // // function test(num) { // // var numArray = String(num).split('') // ["9", "1", "1", "9"] // // var newArray = numArray.map(e => e * e) // ["81", "1", "1", "81"] // // return newArray.join('') // // } // // //console.log(test(9119)) // // //////////////////////////////////////////////////////////////////////// // // // function findPosition(str) { // // // var letters = ' abcdefghijklmnopqrstuvwxyz' // // // var result = '' // // // for(var i = 0; i < str.length; i++) { // // // for(var j = 1; j < letters.length; j++) { // // // if(str[i] === letters[j]) { // // // result = result + j // // // } // // // } // // // } // // // return result // // // } // // // console.log(findPosition('zahid')) // "261894" // // function findPosition(str) { // // var letters = ' abcdefghijklmnopqrstuvwxyz' // // var result = '' // // for(var i = 0; i < str.length; i++) { // // result = result + letters.indexOf(str[i]) // // } // // return result // // } // // //console.log(findPosition('zahid')) // // function sqrt(num){ // // var numArr = String(num).split(""); // // var arr = [] // // for(var i = 0; i < numArr.length ; i++){ // // var a = numArr[i] * numArr[i]; // // arr.push(a) // // } // // return arr.join('') // // } // // //console.log(sqrt(99)) // // // একটি অ্যার দেওয়া আছে, // // // let array = ['mango', 'zahidul islam', 'tomato', 'zohurul islam']; // // // এমন একটি ফাংশন তৈরি করতে হবে যেনো শুধু মাত্র ওই অ্যারে থেকে মানুষের নাম গুলোই বের করে। ebong ta ekti notun array-te rekhe sei array-k return korte hobe. // // var array = ['a', 'b', 5, 'a', 'bogra', 'b', 5, 20, 10, 'a'] // // //console.log(array.indexOf(array[3])) // // function booleanAdding(arr){ // // var count = 0; // // for( var i = 0; i < arr.length; i++){ // // if(arr[i] === 'mango') { // // count++ // // } // // } // // return count // // } // // console.log(booleanAdding(["anarosh", "kola", "mango", "mango", "tomato", "lebu", "mango"])) // // //["anarosh", "kola", "mango", "mango", "tomato", "lebu", "mango"] // // // implicit conversion -- jokhon JS engine nije theke kono kichu convert kore // // //explicit conversion -- jokhon programmer JS engine-k diye conversion koriye ney // // console.log(Number(true) + 2) // explicit conversion // // console.log(true + 4) // implicit conversion // // console.log(Number(null) === Number(false)) // // console.log(false == 0) // // // reference data type // // function largestSwap(num) { // // var numToStr = String(num); // "27" // // // var numToStr1 = num.toString(); // // var changeNum = numToStr[1] + numToStr[0]; // "72" // // if(num >= Number(changeNum)){ // 27 >= 72 // // return true; // // }else{ // // return false; // // } // // } // // //console.log(largestSwap(32)); // 23 // // /* 2. Find the Smallest and Biggest Numbers // // Description: Create a function that takes an array of numbers and return both the minimum and maximum numbers, in that order. // // function minMax(arr) { // // // code here // // } // // Examples // // minMax([1, 2, 3, 4, 5]) ➞ [1, 5] // // minMax([2334454, 5]) ➞ [5, 2334454] // // minMax([1]) ➞ [1, 1] */ // // function minMax(arr) { // // var largest = -Infinity; // // var smallest = Infinity; // // var minMaxArr = [] // // for(var i = 0; i < arr.length; i++) { // // if(largest < arr[i]) { // // largest = arr[i]; // // } // // if(smallest > arr[i]) { // // smallest = arr[i] // // } // // } // // minMaxArr.push(largest) // // minMaxArr.push(smallest) // // return minMaxArr // // } // // //console.log(minMax([1, 5, 8, 100, 2, 3, 4,-5, 5])) // // ASCII --> Americal Standard Code Information Interchange // function findLength(string) { // var result = 0; // for (var i = 0; i < string.length; i++) { // if (string[0] === string[0].toUpperCase()) { // if (string[i] === string[i].toUpperCase()) { // result++; // } // } // if (string[0] >= "a" && string[0] <= "z") { // if (string[i] >= "a" && string[i] <= "z") { // result++; // } // } // } // return result; // } // //console.log(findLength("BanGladesH")); // //console.log(findLength("jaVaScripT")); // // Reference data type // var a = 5; // var b = a; // a = 10; // //console.log(b) // primitive type data // var arr = [2, 6]; // var arr2 = arr; // arr.push(10); // //console.log(arr) // it is called reference type data // var arr3 = [2, 6, 10]; // //console.log(arr3 === arr2) // //console.log(arr === arr2) // var x = [2, 3]; // var y = [2, 3]; // //console.log(x === y) // // stack memory, heap memory // // stack memory is resposible to store Primitive data type // // heap memory is resposible to store reference data type // // Primitive data type // /* // 1. String // 2. Number // 3. Boolean // 4. undefined // 5. null // 6. NaN // */ // // Reference data type // /* // 1. Array // 2. Object // 3. function // */ // // sort method // var myArray = [1, 10, 100, 20, 2000, 49, 5, 8]; // // [1, 10, 20, 100, 49, 5, 8, 2000] // // [1, 10, 20, 49, 5, 8, 100, 2000] // // [1, 10, 20, 5, 8, 49, 100, 2000] // // [1. 10, 5, 8, 20, 49, 100, 2000] // // [1, 5, 8, 10, 20, 49, 100, 2000] // // "Zb", "za", // var sortedArray = myArray.sort(function (a, b) { // return b - a; // }); // lexicographical order // //console.log(sortedArray) // // sort method takes an callback function. this function has two parameters // var names = ["zahidul", "mursalin", "minhaz", "jinius", "zahidul", "redwan"]; // // bubble sorting // // merge sorting // // quick sorting -- what is the concept or how it works // // selection sorting // var sortedNames = names.sort(function (a, b) { // //console.log(a < b) // if (a > b) { // return 1; // --> > 0 // } else if (a < b) { // return -1; // --> < 0 // } else { // return 0; // --> === 0 // } // }); // lexicographical order // //console.log(sortedNames) // /* // টাইটেল: Array থেকে ডুপ্লিকেট এলিমেন্ট বাদ দেয়া // এমন একটি ফাঙ্কশন বানাতে হবে যা প্যারামিটার হিসেবে নিবে একটি array এবং আউটপুট দিবে এমন একটি array যেখানে কোনো ডুপ্লিকেট এলিমেন্ট থাকবে না। // Examples: // removeDuplicate (["red", "green", "blue", "red", "brown", "green", "orange", "orange", "violet", "red" ]) --> ["red", "green", "blue", "brown", "orange", "violet" ] // removeDuplicate(["mursalin", "jinius", "minhaz", "redwan", "farjana "]) --> ["mursalin", "jinius", "minhaz", "redwan", "farjana "] // */ // // ["red", "green", "blue", "red", "brown", "green", "orange", "orange", "violet", "red" ] // // ["red", "green", "blue", "brown", "green", "orange", "orange", "violet"] // // ["red", "green", "blue", "brown", "orange", "orange", "violet"] // // ["red", "green", "blue", "brown", "orange", "violet"] // var array = [ // "red", // "green", // "blue", // "red", // "brown", // "green", // "orange", // "orange", // "violet", // "red", // ]; // // splice method takes 3 parameters // // first parameter is the index - starting position to delete element(s) // // second parameter is a number- how many elements you want to delete // // third parameter is a value - if you want to replace with // // only index parameter is mendatory // // splice method changes the original array // // splice method returns array with deleted value // array.splice(4, 1, ["a", 10]); // //console.log(array) // function removeDuplicate(array) { // for (var i = 0; i < array.length; i++) { // for (var j = i + 1; j < array.length; j++) { // if (array[i] === array[j]) { // array.splice(j, 1); // } // } // } // return array; // } // console.log( // removeDuplicate([ // "red", // "green", // "blue", // "red", // "brown", // "green", // "orange", // "orange", // "violet", // "red", // ]) // ); // // function removeDuplicate(array) { // // var uniqueArray = [...new Set(array)] // // return uniqueArray // // } // console.log( // removeDuplicate([ // "red", // "green", // "blue", // "red", // "brown", // "green", // "orange", // "orange", // "violet", // "red", // ]) // ); // var myArr = [ // "red", // "green", // "blue", // "red", // "brown", // "green", // "orange", // "orange", // "violet", // "red", // ]; // var mySet = new Set(myArr); // mySet.add('Zahidul') // mySet.add('bogra') // mySet.add('sylhet') // mySet.add('bogra') // mySet.add('bogra') // <...> <-- this is called spread operator // var myAnotherSet = [...mySet]; // console.log(myAnotherSet); // console.log(mySet.size); // //ES6 mySet[i] // for (var value of mySet) { // console.log(value); // } // console.log(mySet); // /* // 3. Check if One Array can be Nested in Another // Description: Create a function that returns true if the first array can be nested inside the second. // function canNest(arr1, arr2) { // // code here // } // arr1 can be nested inside arr2 if: // arr1's min value is greater than arr2's min value. // Examples // canNest([1, 2, 3, 4], [0, 6]) ➞ true // canNest([3, 1], [4, 0]) ➞ true // canNest([9, 9, 8], [8, 9]) ➞ false // canNest([1, 2, 3, 4], [2, 3]) ➞ false // */ // //ES6 // // function canNest(arr1, arr2) { // // return Math.min(...arr1) > Math.min(...arr2) // // } // // a + b // // console.log(canNest([9, 9, 8], [8, 9])) // // Infinity is a variable attached to global object // // positive Infinity is greater than any other number // // negative Infinity is smaller than any other number // // var x = 999999999999999 // // var myInfinity = x + 1 // // console.log(myInfinity > x) // //console.log(-Infinity < -10) // function canNest(arr1, arr2) { // var largeLen = arr1.length > arr2.length ? arr1.length : arr2.length; // var minValueOfArr1 = Infinity; // 1 // var minValueOfArr2 = Infinity; // 0 // for (var i = 0; i < largeLen; i++) { // if (arr1[i] < minValueOfArr1) { // minValueOfArr1 = arr1[i]; // } // if (arr2[i] < minValueOfArr2) { // minValueOfArr2 = arr2[i]; // } // } // return minValueOfArr1 > minValueOfArr2; // // if(minValueOfArr1 > minValueOfArr2) { // // return true // // }else { // // return false // } // //console.log(canNest([1, 2, 3, 4], [1, 5, 9, 20, 0, 6])); ////////////////////////////////////////////////////////////// // let arr = [2, 5, 7, 9, 0, 20]; // arr.mid('hi') // console.log(arr) // let myArr = ['red', 'green', 'blue', 'gray', 'sky', 'orange', 'lightgreen'] // myArr.mid('pink') // console.log(myArr) /////////////////////////////////////////////////////////////// /* মনে করো তোমার ক্লায়েন্ট তোমাকে বললো, "আমার অনলাইন নিউজপেপারে ডেট এবং সময় প্রকাশ হয় ইংরেজিতে। যেহেতু আমার নিউজপেপারের রিডার সবাই বাঙালি, সেহেতু আমি চাচ্ছি যে ডেট এবং সময় যেন বাংলায় দেখায়।" এখন তোমার জন্য চ্যালেঞ্জ হয়ে দাঁড়ালো যে ইংরেজি ডিজিটকে বাংলায় কনভার্ট করা। এই প্রোগ্রামটি তৈরী করতে পারলেই, ক্লায়েন্ট যা চাচ্ছে তা তুমি করে দিতে পারবে। উপরের ঘটনাকে বিবেচনা করে এমন এনকি function create করো যা কিনা ইংরেজি নাম্বারকে বাংলায় রূপান্তর করবে। Example : converToBanglaNumber(2021) --> ২০২১ converToBanglaNumber(10999) --> ১০৯৯৯ নোট : Let's take this challenge and accomplish */ // function onverToBanglaNumber(num) { // var str = "০১২৩৪৫৬৭৮৯"; // num = String(num); // var result = ""; // for (var i = 0; i < num.length; i++) { // result = result + str[Number(num[i])]; // num[i] = 1, 2, 3, 4, 5 --> str[1] --> // } // return result; // } // you can't pass 0 in first place //console.log(onverToBanglaNumber(2021)); // 2. for...of - ES6 // var a = ["orange", "banana", "apple"]; // for (var element of a) { // console.log(element); // } // 3. for...in - ES6 // var obj = { // name: "zahidul", // address: "bogra", // }; // var myName = "name"; // console.log(obj[myName]); // var emptyArr = []; // for in loop is used to travers through object keys // var xy = [5, 6]; // for (var i in xy) { // console.log(xy[i]); // } // for (var key in obj) { // emptyArr.push([key, obj[key]]); // } // console.log(emptyArr); // 4. Object.entries - ES6 // var object = { // x: 5, // y: "zahid", // }; // console.log(Object.entries(object)); // 5. spread operator - ES6 // ... // var obj = { // a: 5, // b: 10, // name: 'zahidul' // } //var myArray = [[], []] // console.log(Object.entries(obj)) // var str = '2561794' // console.log(Math.max(...str)) // "2", "5", "6", "1", "7", "9", "4" // var arr = ['red', 'green', 'blue'] // var arr2 = ['sky', 'lightgreen'] // var anotherArray = [...arr, 'zahidul', ...arr2] // console.log(anotherArray) // var numStr = '123' // function add(x, y, z) { // return Number(x) + Number(y) + Number(z) // } // console.log(add(...numStr)) // rest operator/ rest parameter - ES6 // you have to mention the rest parameter always at the end // function test(x, ...args) { // console.log(args) // } // test(10, 50, 'zahidul', 'red') // 6. concat arrays // var str = 'zahidul' // var str2 = ' islam' // var newStr = str.concat(str2) // console.log(newStr) // var newArray = arr.concat(arr2) // console.log(newArray) // 7. type of functions - pure/ impure // 8. break statement within for...loop // break statement breaks a for...loop // 9. continue statement in for..loop // continue skips the steps of for...loop // 10. includes method of array // 1. slice method /* এমন একটি function তৈরী করো যা argument হিসেবে একটি string array নেবে এবং চেক করে দেখবে যে array এর element string এর সাথে কোনো নাম্বার আছে কিনা। যদি থাকে তবে সেই element গুলো আরেকটা array এর মধ্যে নিয়ে return করতে হবে। যেমন - numInStr(["1a", "a", "2b", "b"]) ➞ ["1a", "2b"], এখানে array এর প্রথম element "1a" তে নাম্বার আছে এবং "2b" তে নাম্বার আছে। তাই রিটার্ন হয়েছে ["1a", "2b"], আরো উদাহরণ - numInStr(["abc", "abc10"]) ➞ ["abc10"], numInStr(["abc", "ab10c", "a10bc", "bcd"]) ➞ ["ab10c", "a10bc"], numInStr(["this is a test", "test1"]) ➞ ["test1"] বি.দ্র: অরিজিনাল array কে change করা যাবে না। */ // ["abc", "ab10c", "a10bc", "bcd"] //console.log(!isNaN(' ')) // break statement // continue statement // var str = 'my country is Bangladesh' // for(var j = 0; j < str.length; j++) { // if(str[j] === ' ') continue; // // console.log(str[j]) // } // function numInStr(arr) { // var result = [] // for(var i = 0; i < arr.length; i++) { // for(j = 0; j < arr[i].length; j++) { // if(arr[i][j] === ' ') continue; // if(!isNaN(arr[i][j])) { // result.push(arr[i]) // break; // } // } // } // return result // } //console.log(numInStr(['my country is Bangladesh', "abc", "ab01c", "a10bc", "b3cd25"])) // isAllDigitPresent (981423568910) // includes method of array // includes methid always returns Boolean value (true/ false) // includes method takes a parameter value which you want to check // parameter value is mendatory // var arr = [0, 3, 4, 5, 7, 8, 9, 'zahidul'] // console.log(arr.includes('zahidul')) // for(var i = 0; i < arr.length; i++) { // if(arr[i] === 'zahidul') { // console.log(true) // } // } // function isAllDigitsPresent(num) { // var strNum = num.toString() // "891204356789" // var arrayToCompare = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] // 8 === "8" // for(var value of strNum) { // if(arrayToCompare.includes(Number(value))) { // "8" --> 8 // //arrayToCompare.splice(Number(value), 1, true) // "9" --> 9 // delete arrayToCompare[Number(value)] // } // } // console.log(arrayToCompare) // // var newArray = arrayToCompare.filter(function(value) { // this is called callback function // // return typeof value === 'number' // // }) // var newArray = [] // for(var value of arrayToCompare) { // if(typeof value === 'number') { // newArray.push(value) // } // } // console.log(newArray) // return newArray.length === 0 ? true : false // } // console.log(isAllDigitsPresent (8912435607891)) ///////////////////////////////////////////////////// // var colors = ['red', 'green', 'blue'] // for(var color of colors) { // console.log(color) // } // colors.splice(1, 1, true) // console.log(colors) // filter function // filter method takes a function as argument and that function takes // filter method always returns an arrau // var mixed = [2, 5, 'red', 'zahidul', true, 4, false] // var filteredArray = mixed.filter(function (value, index, array) { // return index > 2 // }) // console.log(filteredArray) // // function expression // var x = function () { // console.log('function x is called') // } // x() // function randomWord(str){ // var randomNum = Math.floor(Math.random() * 5) // var getRandomWord = str[randomNum]; // return getRandomWord // } // console.log(randomWord(["red", "green", "blue", " teal", "oranged"])) // reverse method of array // var arr = [1,2,3,4] // console.log(arr.join('')) // "1,2,3,4" // function reverseString(str) { // //return str.split('').reverse().join('') // var result = '' // for(var i = 0; i < str.length; i++) { // result = str[i] + result // } // return result // } // console.log(reverseString('bangladesh')) // function findLongestWord(str) { // var strArray = str.split(' ') // //console.log(strArray) // var longestWord = '' // "activity // for(var i = 0; i < strArray.length; i++) { // if(strArray[i].length > longestWord.length) { // longestWord = strArray[i] // } // //console.log(strArray[i].length) // } // return longestWord // } // console.log(findLongestWord('we have to be genius by our activity')) // function findLongestWord(str) { // var strArray = str.split(' ') // var longestWord = strArray.sort(function(a, b) { // return b.length - a.length // }) // return longestWord[0] // } // console.log(findLongestWord('we have to be genius by our activity')) //create a function that takes an argument as string and returns the character which appears the most. // [["b", 1], ["a", 1], ["n", 1]....] // ["b", 1], ["a", 1], ["n", 1].... // function mostAppearingChar(str) { // var obj = {} // {"t": 2, "i": 1, "k": 2, "o": 1} // for(var i = 0; i < str.length; i++) { // if(obj[str[i]]) { // obj[str[i]] = obj[str[i]] + 1 // }else { // obj[str[i]] = 1 // } // } // // to get max value // var maxValue = -Infinity // var targetedKey = '' // for(var key in obj) { // if(obj[key] > maxValue) { // maxValue = obj[key] // targetedKey = key // } // } // return `${targetedKey} appears ${maxValue} times` // } //console.log(mostAppearingChar('bangladesh')) // --> "a appears 2 times" //console.log(mostAppearingChar('beautiful')) // --> "u appears 2 times" //console.log(mostAppearingChar('tiktok')) // --> "t appears 2 times" // slice method // slice method takes two parameter values // first parameter value is the array index which is starting point to slice // the end point where we want to stop slicing is the next index of that end point index // slice method does not change the original array // parameter value is not mendatory // var alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'] // // 0 3 // var slicedArray = alphabets.slice(0, 3) // console.log(slicedArray) // console.log(alphabets) // splice method // splice method removes array of element(s) // splice method changes the original array // splice method takes three parameter values // first parameter value is the index where we want to start removing // second parameter value (number) is how many element(s) we want to remove // third parameter value is any type of value (it can be string, number, array, object etc) which we want to replace with the removed element(s). We can push multiple values as well. // first parameter value is mendatory // splice method returns array with removed element(s) // var colors = ['red', 'green', 'yellow', 'pink'] // var splicedArray = colors.splice(1, 2, [10, 25], 'zahidul', {a: 5}) // console.log(splicedArray) // console.log(colors) // delete method // delete method removes element but keeps that index of removed element with undefined value // var countries = ['Bangladesh', 'India', 'Pakistan', 'Srilanka'] // delete countries[1] // delete countries[3] // console.log(countries) //The slice() method // The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument. //splice() method //The splice() method adds/removes items to/from an array, and returns the removed item(s). //delete method // The delete keyword deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. /* getString([ [1, 3, 2, 'a', 7, 9, 4, 6, 8], [4, 9, 8, 2, 6, 1, 'b', 7, 5], ['c', 'h', 6, 3, 8, 4, 2, 1, 9], [6, 4, 3, 1, 'd', 8, 7, 9, 2], [5, 2, 'e', 7, 9, 3, 8, 4, 6], [9, 8, 7, 4, 2, 'f', 5, 3, 1], [2, 1, 4, 9, 3, 5, 6, 8, 'g'], [3, 'h', 5, 8, 1, 7, 9, 2, 4], [8, 7, 9, 6, 4, 2, 1, 'i', 3] ]) function doneOrNot(board) { //your code goes here } Tomader kaj hochche array gulo theke shudhu matro string gulo niye notun ekti array return korte hobe. result should be like this ----> ["a", "b", "c", " h", "d", "e", "f", "g", "h", "i"] বি.দ্রঃ splice method ব্যবহার করা বাধ্যতামূলক। */ // Jinius, Minhaz, Redwan, Mursalin, Farjana-- all elements we will get inside temp array // // includes method always returns Boolean value // var cities = ['Dhaka', 'Chittagong', 'Bogra', 'Dhaka', 'Sylhet', 'Kushtia', 'Faridpur', 'Bogra', 'Chittagong', 'Dinajpur', 'Faridpur'] // // ['Dhaka', 'Chittagong', 'Bogra', 'Sylhet', 'Kushtia', 'Faridpur', 'Dinajpur'] // // ['Chittagong', 'Sylhet', 'Faridpur'] // var temp = [] // [Dinajpur'] // var city // var uniqueArray = [] // ["Dhaka", "Chittagong", "Bogra", "Sylhet", "Kushtia", "Faridpur", "Dinajpur"] // for(var i = 0; i < cities.length; i++) { // if(uniqueArray.includes(cities[i])) { // console.log(cities[i]) // }else { // uniqueArray.push(cities[i]) // } // //temp = cities.splice(i, 1, true) // //temp = [...temp, ...cities.splice(i, 1)] // temp = [Dinajpur'] // //temp = temp.concat(cities.splice(i, 1, true)) // } // console.log(uniqueArray) // console.log(city) // console.log(cities) // console.log(temp) // largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]) // [5, 27, 39, 1001] // var a = [1, 2, 3] // var b = [4, 5, 6] // a = a.concat(b) // console.log(a) // function spliceMethod(array) { // var newArray = [] // for(var i = 0; i < array.length; i++) { // newArray = newArray.concat(array.splice(i, 1)) // i = i - 1 // } // return newArray // } //console.log(spliceMethod(['Farjana', 'Mursalin', 'Jinius', 'Minhaz', 'Redwan', 'Zahidul'])) // var string = 'zahidul' // console.log(string.split('l')) // var arr = ['red', 'green', ''] // console.log(arr[arr.length - 1] === '') // function endingCheck(str, target) { // str = str.split(target) // ["He has to give me a new ", ""] // console.log(str) // if(str[str.length - 1] === '') { // return true // }else { // return false // } // } // console.log(endingCheck("Bastain", "an")); //console.log(endingCheck("Walking on water and developing software from a specification are easy if both are frozen", "specification")) //console.log(endingCheck("He has to give me a new name", "name")) //console.log(endingCheck("Open sesame", "sage")) //console.log(endingCheck("Open sesame", "game")) // function confirmEnding(str, target) { // if(str.lastIndexOf(target) == (str.length-target.length)){ // return true; // } else { // return false; // } // } //console.log(confirmEnding("Open sesame", "same")); // consecutive = ধারাবাহিক --> 1, 2. 3 // 2, 5, 6, 7, 8, 10 // function check(first, second) { // var array = [] // for(var i = 0; i < first.length; i++) { // console.log(first[i], i) // for(var j = 0; j < second.length; j++) { // if(second.length === 1 && first[i] === second[j]) { // return true // } // if(first[i] === second[j]) { // array.push(i) // } // } // } // for(var i = 0; i < array.length; i++) { // } // for(var j = array.length - 1; j >= 0; j--) { // console.log(array[j]) // } // } // console.log(check('bangladesh', 'glas')) // expected result = true // 1, 3, 4, 5, 8 // 8, 5, 4, 3, 1 //--------------- // 9, 8, 8, 8, 9 // if a function receives another function as argument, that (another function) is called callback function. // who receives a callback function is called higher order function // function a(callback) { // return callback() // } // function c() { // return 'I am Zahidul' // } // var b = a(c) // console.log(b) //map, filter, sort, forEach, reduce, every, some, find, findIndex // all the above methods use callback function as their parameter value // var arr = [1, 2, 3] // arr.map(function(value) { // console.log(value) // }) // var obj = { // a: 5, // b: function() { // console.log('I am a method of object (obj)') // } // } // obj.b() // timing function // there are two timing functions in JS, they are:- 1) setTimeout, 2) setInterval // concept of synchronization and asynchronization // 1) setTimeout function calls itself within a certain time. // setTimeout function takes two parameter values. first parameter is a function and second parameter is millisecond // setTimeout function calls itself only one time // 1000 millisecond = 1 second // setInterval function calls itself continuously based on delay time // every setInterval or setTimeout function returns an ID. this ID is used to stop the timing function. // to stop a timing function, clearInterval or clearTimeout is used // DOM - Document Object Module // how to get html element(s) // In JS every element of html is called node //var h1Tag = document.getElementsByTagName('h1') //var jsTag = document.getElementById('js') //var h1Tag = document.getElementsByClassName('demo') //var h1Tag = document.querySelector('.demo') // var h1Tag = document.querySelector('.demo') // h1Tag.innerHTML = 'Zahidul' // //text.style.color = 'red' // // how to add class or remove class by JS // h1Tag.style.backgroundColor = 'red' // //var id = setInterval(timing, 1000); // var i = 1 // 1 // function timing() { // console.log(i) // 1, 2, 3, 4, 5, 1 // i = i % 5 // i = 0 // i++ // i = 1 // } // function nestedArray(array, num){ // var result = [] // var x = 0 // for(var i = 0; i < array.length; i = i + (array.length / num)) { // result[x] = array.slice(i, i + (array.length / num)) // x++ // } // return result // } // console.log(nestedArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 6)) // var numArray = [] // numArray[0] = 1 // numArray[2] = 2 // numArray[4] = 3 // console.log(numArray) // function replaceInAlphabeticalOrder(str) { // let arr = str.split(''); // [c, b, d] // let temp = ''; // for (let i = 0; i < str.length; i++){ // arr[i] = c // for (let j = i + 1; j < str.length; j++){ // arr[j] = b // if (arr[i] > arr[j]) { // arr = [b, c, d] // temp = arr[i] // temp = c // arr[i] = arr[j]; // arr[i] = b // arr[j] = temp; // arr[j] = c // } // } // console.log(arr) // } // return arr.join(''); // } //console.log(replaceInAlphabeticalOrder('zahidul')); // adhiluz //var myArray = [5, 10] // var temp // if(myArray[0] > myArray[1]) { // temp = myArray[0] // myArray[0] = myArray[1] // myArray[1] = temp // } //console.log(myArray) // function replaceInAlphabeticalOrder(str) { // // code here // var myStr = '' // var mainStr = 'abcdefghijklmnopqrstuvwxyz' // for (var i = 0; i < mainStr.length; i++) { // if (str.includes(mainStr[i])) { // myStr = myStr + mainStr[i] // } // } // return myStr // } //console.log(replaceInAlphabeticalOrder('zahidul')) /////////////////////////////////////////////////////////// // function titleCase(str) { // str = str.toLowerCase() // let newStr = '' // for (let i = 0; i < str.length; i++) { // if(i === 0) { // newStr = str[i].toUpperCase() // } // if(i > 0) { // if(str[i] === ' ') { // newStr = newStr + ' ' + str[i + 1].toUpperCase() // i = i + 1 // }else { // newStr = newStr + str[i] // } // } // } // return newStr; // } //console.log(titleCase("I'm a little tea pot")) //console.log(titleCase("sHoRt AnD sToUt")) //////////////////////////////////////////////////////////////////// //let result = [] // function printArray(arr) { // for (var i = 0; i < arr.length; i++) // if (Array.isArray(arr[i])) { // printArray(arr[i]) // }else { // result.push(arr[i]) // } // return result // } // var numAray = [ // [1, 5, [11, 22, [33, 44]], ['a', 'b'] ], // [[[[7, 4]]]] // ]; // console.log(printArray(numAray)) // function printArray1(arr) { // let result = [] // for (var i = 0; i < arr.length; i++) { // for(var j = 0; j < arr[i].length; j++) { // if (Array.isArray(arr[i][j])) { // arr[i] = arr[i][j] // j = -1 // }else { // result.push(arr[i][j]) // } // } // } // return result // } // console.log(printArray1(numAray)) // function myFun(str) { // var newStr = str.toLowerCase() // var result = ""; // for (var i = 0; i < newStr.length; i++) { // if (i === 0) { // result = newStr[i].toUpperCase() // } // if (i > 0) { // if (newStr[i] === ' ' && newStr[i + 1] < 'A' || newStr[i + 1] > 'z') { // result = result + ' ' + '' + newStr[i + 2].toUpperCase() // i = i + 2 // } else if (newStr[i] !== '.' && newStr[i] < 'A' || newStr[i] > 'z') { // result = result + ' ' + newStr[i + 1].toUpperCase() // i = i + 1; // } else { // result = result + newStr[i] // } // } // } // return result; // } // console.log(myFun("bangladeSH is a~beauTiful Country./WE*love {our$COUNTRY")) // ASCII -> American Standard Code for Information & Interchange // ACII code usees 7 bits numbers // ASCII code produce always string // (48 - 57) -> ("0" - "9") // (65 - 90) -> ("A" - "Z") // (97 - 122) -> ("a" - "z") // var str = 'zahid' // console.log(str.charAt(3)) // "gap" -> what is the binary Number // "g" -> 103 -> 1100111 // 64 + 32 + 4 + 2 + 1 = 103 // 64 32 16 8 4 2 1 --> 64 + 32 + 4 + 2 + 1 = 103 // 1 1 0 0 1 1 1 // "a" -> 97 // "p" -> 112 // 64 32 16 8 4 2 1 --> 64 + 16 + 4 + 2 = 86 --> "V" (Capital) // "V" (Capital) --> 1010110 // 1 0 1 0 1 1 0 -> example-1 of a 7 bits binary number // 1111111 -> example-2 of a 7 bits binary number // 0000000 -> example-3 of a 7 bits binary number // Lower-case G //console.log("g".charCodeAt()) // function myFun(str) { // var newStr = str.toLowerCase() // var result = ""; // for (var i = 0; i < newStr.length; i++) { // if (i === 0) { // result = newStr[i].toUpperCase() // } // if (i > 0) { // if (newStr[i] === ' ' && newStr[i + 1] < 'A' || newStr[i + 1] > 'z') { // result = result + ' ' + '' + newStr[i + 2].toUpperCase() // i = i + 2 // } else if (newStr[i] !== '.' && newStr[i] < 'A' || newStr[i] > 'z') { // result = result + ' ' + newStr[i + 1].toUpperCase() // i = i + 1; // } else { // result = result + newStr[i] // } // } // } // return result; // } // console.log(myFun("bangladeSH is a~beauTiful Country./WE*love {our$COUNTRY")) // function frankenSplice(arr1, arr2, n) { // } //frankenSplice([1, 2, 3], ['red', 'green', 'yellow', 'pink'], 2); // the condition is:- you have to return a new array. arr1 and arr2 must not be changed // [4, 1, 2, 3, 5, 6] // [4, 5, 6, 1, 2, 3] // ['red', 'green', 1, 2, 3, 'yellow', 'pink'] // var, let, const // function frankenSplice(arr1, arr2, num) { // var result = arr2.slice() // var temp = result.splice(num) // console.log(result) // console.log(temp) // result = result.concat(arr1, temp) // return result // } //console.log(frankenSplice([1, 2, 3], [4, 5, 6], 0)) //console.log(frankenSplice([1, 2, 3], //['red', 'green', 'yellow', 'pink'], 2)) // function frankenSplice(arr1, arr2, n) { // var x = arr1.slice() // console.log(x) // "1,2,3" // x.splice(n, 0, ...arr1) // console.log(x) // } // //frankenSplice([1, 2, 3], ['red', 'green', 'yellow', 'pink'], 2) // function frankenSplice(arr1, arr2, n) { // var result = [...arr2] // result.splice(n, 0, ...arr1) // console.log(result) // } // frankenSplice([1, 2, 3], ['red', 'green', 'yellow', 'pink'], 2) // var elements = document.getElementsByClassName('demo') // var h2 = document.querySelector('#h2') //elements[1].style.color = 'green' //h2.classList.add('zahidul') // var x = 0 // var id = setInterval(myFunc, 1000) // h2.classList.add('zahid') // console.log(h2.classList.contains('zahid')) // function myFunc() { // x++ // if(h2.classList.contains('zahid')) { // h2.classList.remove('zahid') // }else { // h2.classList.add('zahid') // } // // if(x >= 10) { // // clearInterval(id) // // } // } // var, let, const // var <-- keyword // let <-- keyword // const <-- keyword // let greeting = "say Hi"; // let times = 4; // if (times > 3) { // let greeting = "say hello"; // } // let num1 = 10; // const num = 10; // console.log(greeting); // function findLCM(arr) { // if (arr.length === 1) { // return arr[0]; // } // let maxValue = Math.max(arr[0], arr[1]); // let minValue = Math.min(arr[0], arr[1]); // let i; // for (i = maxValue; i % minValue !== 0; i = i + maxValue) {} // if (arr.length > 2) { // arr.splice(0, 2) // arr.push(i) // arr = [5, 6] // return findLCM(arr) // } // return i; // } // console.log(findLCM([24, 36, 54, 72, 96])); // for of loop // for of loop is to use to avoid traditional for...loop // let colors = ['red', 'green', 'blue'] // for(let color of colors) { // console.log(color) // } // for(let index in colors) { // console.log(colors[index]) // } // let obj = { // color: 'blue', // age: 21, // address: 'Bangladesh', // age: 15 // } // for(let key in obj) { // let values = obj[key] // console.log(key) // console.log(values) // } // for (let i = 0; i < Object.entries(obj).length; i++) { // let keys = Object.entries(obj)[i][0] // let values = Object.entries(obj)[i][1] // console.log(keys) // console.log(values) // } // for in loop // if we try to traverse the keys of an Object, we will use for in loop // 1, 20 othoba 3, 12 :- duita number-er ekta jodi 1 hoy othoba duita number-er borotake jodi chotota diye nisheshe bivajjo hoy tobe GCF hobe choto number-ti. function getGCF(a, b) { let ln = a > b ? a : b let sn = ln === a ? b : a let gcf let remainder = ln % sn // remainder = 10 if(remainder === 0) { gcf = sn }else { for(let i = 0; i < Infinity; i++) { ln = sn sn = remainder remainder = ln % sn if(remainder === 0) { gcf = sn break; } } } return gcf } console.log(getGCF(8, 30)) function gcd_two_numbers(x, y) { while (y) { // 6 var i = y; // i = 2 y = x % y; // y = 0 x = i; // x = 2 } return x; } console.log(gcd_two_numbers(8, 30)); ////////////////////////////////////////////////// function findLCM(arr) { if (arr.length === 1) { return arr[0] } let maxValue = arr[0] > arr[1] ? arr[0] : arr[1] let minValue = maxValue === arr[0] ? arr[1] : arr[0] let GCF let remainder = maxValue % minValue if (remainder === 0) { GCF = minValue } else { for (let i = 0; i < Infinity; i++) { if (maxValue % minValue !== 0) { maxValue = minValue minValue = remainder remainder = maxValue % minValue if (remainder === 0) { GCF = minValue break; } } } } var LCM = (arr[0] * arr[1]) / GCF if (arr.length > 2) { arr.splice(0, 2) arr.push(LCM) return findLCM(arr) } return LCM; } console.log(findLCM([2, 3, 4, 5, 6]))
import React, { Component } from 'react'; import { Helmet } from 'react-helmet'; class App extends Component { render() { return ( <div> <Helmet titleTemplate='%s - ReactJS Starter' defaultTitle='ReactJS Starter'> <meta name='description' content='A easy and fastest way to start of ReactJS project with Webpack.' /> </Helmet> <div> <p>Welcome to ReactJS App! <span aria-label='dizzy' role='img'>💫</span></p> </div> </div> ); } } export default App;
import React from 'react' import { connect } from 'react-redux' import action from '../../redux/users/action'; import HocHeader from '@/components/HOC/HocHeader' import Input from '@/components/HOC/input/input'; import HocInput from '@/components/HOC/input/HocInput'; import Count from '@/components/count'; const NumberInput = HocInput('amount', { roles: { reg: /^[0-9]*$/, required: true, msg: '请输入数字', err: '数字格式不正确', } })(Input) const TelInput = HocInput('tel', { roles: { reg: /^1[34578]\d{9}$/, required: true, msg: '请输入电话号码', err: '号码格式不正确', } })(Input) @connect( state => state.counter, { ...action } ) @HocHeader(['baidu', 'go', 'back']) class Page3 extends React.Component{ constructor(){ super() this.state={ userVal:{}, list:[ { id:1, count:0, name:'辣条' },{ id:2, count:0, name:'锅巴' },{ id:3, count:0, name:'面包' },{ id:4, count:0, name:'酸奶' }, ] } } handleChange = (obj) => { let { userVal } = this.state this.setState({userVal:{...userVal, ...obj}}) console.log('我是数字:', obj) } handleSubmit = (event) => { alert('A name was submitted: ' + this.state.userVal.amount); event.preventDefault(); } click(){ this.props.loginState() const promise = new Promise((resolve,reject) =>{ resolve('success1'); reject('error') resolve('success2'); }) promise.then((res) => { console.log('then',res) }).catch((err)=>{ console.log('error',err) }) } handleClick = ( itm ) => { let { list } = this.state; console.log(list) list.map( item => { if(item.id === itm.id){ item.count = itm.count; this.setState({list}) } }) } render(){ let { list } = this.state; return( <div> <button onClick={()=>this.click()}>123123</button> <form onSubmit={this.handleSubmit}> <NumberInput handleChange={this.handleChange}/> <TelInput handleChange={this.handleChange}/> <input type="submit"/> </form> <div style = {{display:'flex' }}> { list.map((item,index) =>( <Count key={index} {...item} handleClick={this.handleClick} /> )) } </div> </div> ) } } export default Page3
import React from 'react'; import { storiesOf } from '@storybook/react'; import DepthChart from './DepthChart'; import DepthChart2 from './DepthChart2'; const lastOrders = [ { pairId: 1, price: 0.000012, amount: 20, side: 'buy', }, { pairId: 1, price: 0.000015, amount: 50, side: 'buy', }, { pairId: 1, price: 0.000016, amount: 100, side: 'buy', }, { pairId: 1, price: 0.000017, amount: 110, side: 'buy', }, { pairId: 1, price: 0.000011, amount: 80, side: 'sell', }, { pairId: 1, price: 0.000014, amount: 40, side: 'sell', }, { pairId: 1, price: 0.000016, amount: 90, side: 'sell', }, { pairId: 1, price: 0.000019, amount: 80, side: 'sell', }, ]; storiesOf('DepthChart', module) .add('DepthChart', () => <DepthChart orders={lastOrders} />) .add('DepthChart2', () => <DepthChart2 orders={lastOrders} />);
'use strict'; // Declare app level module which depends on views, and components angular.module('myApp', [ //'ngRoute', 'myApp.services', 'myApp.controllers' ]) .config(function($interpolateProvider) { $interpolateProvider.startSymbol('{[{'); $interpolateProvider.endSymbol('}]}'); }); // .config(['$routeProvider', function($routeProvider) { // $routeProvider.otherwise({redirectTo: '/'}); // }]). // config(function ($httpProvider) { // $httpProvider.interceptors.push('AuthInterceptor'); // }) ;
let Sequelize = require("sequelize"); let Model = Sequelize.Model; let { sequelize } = require("../DB/mysql"); class Trip extends Model { } Trip.init({ id: { type: Sequelize.INTEGER, allowNull: false, autoIncrement: true, primaryKey: true }, from_location: { type: Sequelize.STRING, allowNull: false }, to_location: { type: Sequelize.STRING, allowNull: false }, start_time: { type: Sequelize.TIME, allowNull: false }, end_time: { type: Sequelize.TIME, allowNull: false }, user_id: { type: Sequelize.STRING, allowNull: false }, driver_id: { type: Sequelize.INTEGER, allowNull: false }, status_id: { type: Sequelize.INTEGER, allowNull: false }, car_id: { type: Sequelize.STRING, allowNull: false }, date: { type: Sequelize.DATE, allowNull: false }, distance: { type: Sequelize.DECIMAL, allowNull: false } }, { sequelize, underscored: true, tableName: "trip" }); module.exports.Trip = Trip;
export * from "./Logger"; export * from "./TemplateRenderer"; export * from "./SymbolLinks"; export * from "./template-plugins/RelationsPlugin";
/** * clipboard.js - HumanInput Clipboard Plugin: Adds support for cut, copy, paste, select, and input events to HumanInput * Copyright (c) 2016, Dan McDougall * @link https://github.com/liftoff/HumanInput/src/clipboard.js * @license plublic domain */ import { handlePreventDefault } from './utils'; import HumanInput from './humaninput'; HumanInput.defaultListenEvents = HumanInput.defaultListenEvents.concat(['cut', 'copy', 'paste', 'select']); export class ClipboardPlugin { constructor(HI) { // HI == current instance of HumanInput this.HI = HI; HI._clipboard = this._clipboard.bind(HI); this._paste = this._clipboard; this._copy = this._clipboard; this._cut = this._clipboard; HI._select = this._select.bind(HI); this._input = this._select; } init(HI) { return this; // So it gets logged as being initialized } _clipboard(e) { var data; var event = e.type + ':"'; if (this.filter(e)) { if (window.clipboardData) { // IE data = window.clipboardData.getData('Text'); } else if (e.clipboardData) { // Standards-based browsers data = e.clipboardData.getData('text/plain'); } if (!data && (e.type == 'copy' || e.type == 'cut')) { data = this.getSelText(); } if (data) { // First trigger a generic event so folks can just grab the copied/cut/pasted data let results = this._triggerWithSelectors(e.type, [e, data]); // Now trigger a more specific event that folks can match against results = results.concat(this._triggerWithSelectors(event + data + '"', [e])); handlePreventDefault(e, results); } } } _select(e) { // Handles triggering 'select' *and* 'input' events (since they're so similar) var event = e.type + ':"'; if (e.type == 'select') { var data = this.getSelText(); } else if (e.type == 'input') { var data = e.data || e.target.value; } if (this.filter(e)) { let results = this._triggerWithSelectors(e.type, [e, data]); if (data) { results = results.concat(this._triggerWithSelectors(event + data + '"', [e])); handlePreventDefault(e, results); } } } } HumanInput.plugins.push(ClipboardPlugin);
var cfgs = { "app_name": "车务通" , "logo": "" , "domain": "/cwt/" , "loginPage": "login.html" , "mainPage": "index.html" , "debug": false , "output": { "debug": false, "info": true, "warn": true, "error": true } /* 系统模块定义 */ , "parts": { /*车辆列表*/ "tree": { "parent": "#treeContainer", "url": "views/parts/tree.html" }, /*通知栏*/ "notify": { "parent": ".nav-bar-plugins", "url": "views/parts/inbox.html", "complated": "App.notify.init()" }, "setting-menu": { "parent": "#setting-menu", "url": "views/parts/settings.html", "complated": "App.theme.init()" } } , "modules": { "1": { "parent": "-", "name": "基本功能" } // , "100": { "parent": "000", "icon": "icon-speedometer", "name": "监控中心" } // , "102": { "theme": "bg-green", "name": "多窗口监控", "url": "#", "complated": "" } , "300": { "parent": "000", "icon": "icon-bar-chart", "name": "统计中心" } , "301": { "theme": "#ECA877", "iconImage": "定位统计.png", "name": "定位统计", "url": "views/common-statistic.html", "complated": "App.plugins.statistics.location" } , "302": { "theme": "#F1AC08", "iconImage": "里程统计.png", "name": "里程统计", "url": "views/common-statistic.html", "complated": "App.plugins.statistics.mileage" } , "303": { "theme": "#8455DB", "iconImage": "油耗统计.png", "name": "油耗统计", "url": "views/common-statistic.html", "complated": "App.plugins.statistics.fuelquery" } , "304": { "theme": "#7FC822", "iconImage": "告警统计.png", "name": "告警统计", "url": "views/statistics/report-statistic.html", "complated": "App.plugins.statistics.alarm" } , "305": { "theme": "#ECA877", "iconImage": "离线统计.png", "name": "离线统计", "url": "views/common-statistic.html", "complated": "App.plugins.statistics.offline" } , "306": { "theme": "#38B2F1", "iconImage": "告警查询.png", "name": "告警查询", "url": "views/statistics/report-statistic.html", "complated": "App.plugins.searchs.alarm" } , "307": { "theme": "#7FC822", "iconImage": "停车统计.png", "name": "停车查询", "url": "views/common-statistic.html", "complated": "App.plugins.statistics.park" } , "308": { "theme": "#F2B588", "iconImage": "终端查询.png", "name": "终端查询", "url": "views/statistics/terminal-search.html", "complated": "App.plugins.statistics.terminalquery" } , "309": { "theme": "#DD64B1", "iconImage": "轨迹查询.png", "name": "轨迹查询", "url": "views/common-statistic.html", "complated": "App.plugins.statistics.trajectoryquery" } , "310": { "theme": "#139B79", "iconImage": "指令查询.png", "name": "指令查询", "url": "views/searchs/command-search.html", "complated": "App.plugins.searchs.command" } , "311": { "theme": "#3A3FB2", "iconImage": "日志查询.png", "name": "日志查询", "url": "views/statistics/log-search.html", "complated": "App.plugins.statistics.logquery", "icon": "fa fa-bar-chart-o" } , "400": { "parent": "000", "icon": "icon-settings", "name": "设置中心" } , "401": { "theme": "#F2B588", "iconImage": "定位设置.png", "name": "定位设置", "url": "views/setup/location.html", "complated": "setuplocation" } , "402": { "theme": "#F7DB53", "iconImage": "电子围栏.png", "name": "电子围栏", "url": "views/setup/electric-fence.html", "complated": "App.plugins.setup.electricFence" } , "403": { "theme": "#7FC822", "iconImage": "偏航告警.png", "name": "偏航告警", "url": "#", "complated": "" } , "404": { "theme": "#3D43A9", "iconImage": "超速告警.png", "name": "超速告警", "url": "#", "complated": "" } , "405": { "theme": "#018FE9", "iconImage": "兴趣图形.png", "name": "兴趣图形", "url": "views/setup/graphical.html", "complated": "" } , "406": { "theme": "#F2B588", "iconImage": "告警设置.png", "name": "离线告警", "url": "#", "complated": "" } , "407": { "theme": "#018FE9", "iconImage": "分组管理.png", "name": "分组管理", "url": "views/manager/group-list.html", "complated": "App.plugins.manager.groupmanager" } , "408": { "theme": "#DD123D", "iconImage": "角色管理.png", "name": "角色管理", "complated": "App.plugins.manager.rolemanager" } , "409": { "theme": "#DD123D", "iconImage": "操作员管理.png", "name": "操作员管理", "complated": "App.plugins.manager.operatormanager" } , "411": { "theme": "#F1AC08", "iconImage": "车辆管理.png", "name": "车辆管理", "complated": "App.plugins.manager.carmanager" } , "412": { "theme": "#3A3FB2", "iconImage": "人员管理.png", "name": "人员管理", "url": "#", "complated": "" } , "413": { "theme": "#7FC822", "iconImage": "驾驶员管理.png", "name": "驾驶员管理", "url": "#", "complated": "" } , "800": { "parent": "000", "icon": "fa fa-cab", "name": "调度中心" } , "801": { "theme": '#F19B13', "iconImage": "新-用车申请.png", "name": "用车申请", "url": "views/dispatch/01.request.html", "complated": "App.plugins.dispatch.request.init" } , "802": { "theme": '#ee9B79', "iconImage": "新-用车审批.png", "name": "用车审批", "url": "views/dispatch/02.approval.html", "complated": "App.plugins.dispatch.approval.init" } , "803": { "theme": '#ab0569', "iconImage": "新-车辆调度.png", "name": "车辆调度", "url": "views/dispatch/03.dispatch.html", "complated": "App.plugins.dispatch.dispatch.init" } , "804": { "theme": '#D50569', "iconImage": "新-派车单管理.png", "name": "派车单管理", "url": "views/dispatch/04.order.html", "complated": "App.plugins.dispatch.order.init" } , "805": { "theme": '#703F93', "iconImage": "新-车辆归队.png", "name": "车辆归队", "url": "views/dispatch/05.rejoin.html", "complated": "App.plugins.dispatch.rejoin.init" } } }; var server = "http://cwt.jsadc.com/CWTCSServer/"; if (cfgs.debug) { server = "http://localhost:8080/cwt/api.jsp?api="; } /* 业务逻辑参数 */ var bus_cfgs = { "cache": {} , "options": {} , "login": { "token_cookie": "ecr_user_token" , "token_json_cookie": "ecr_user_json" /* API:请求验证码 */ , "captchaapi": server + "getCaptcha" /* API:请求登录 */ , "loginapi": server + "login" } , "carservice": { /* API:请求目标列表 */ "targetlistapi": server + "queryTargetList" /* API:请求定位 */ , "trackapi": server + "getTrack" /* API:请求最后轨迹 */ , "lasttrackapi": server + "queryLastTrack" /* API:请求实时轨迹 */ , "realtrackapi": server + "getTrack" /* API:请求订阅 */ , "Subscribeapi": server + ((cfgs.debug) ? "addSubscribe&iType=P,R,M" : "addSubscribe?iType=P,R,M") } /* 监控中心模块 */ , "monitor": { "getTrackTimeapi": server + "getTrackTime" , "tarckPlayapi": server + "tarckPlay"//sid={0}&startUtc={1}&endUtc={2}&timeInterval={3} } /* 设置中心模块 */ , "setting": { /* PAGE:车辆信息设置修改页面 */ "requesteditpage": "views/newsletter/setuo_vehicleinfo_update.html", /* API:车辆信息设置查询*/ "vehicleListapi": server + "vehicleList", /* API:操作员列表查询*/ "operatorlistapi": server + "operatorList" } /* 调度中心模块 */ , "dispatch": { /* PAGE:用车申请编辑页面 */ "requesteditpage": "views/dispatch/edit.html" /* PAGE:用车详情页面 */ , "detailspage": "views/dispatch/details.html" /* PAGE:审批界面*/ , "approvalpage": "views/dispatch/approval.html" /* PAGE:驳回界面*/ , "rejectpage": "views/dispatch/reject.html" /* PAGE:调度界面*/ , "dispatchpage": "views/dispatch/dispatch.html" /* PAGE:归队界面*/ , "rejoinpage": "views/dispatch/rejoin.html" /* API:用车申请列表查询*/ , "requestlistapi": server + "applyQuery" /* API:用车申请详情查询*/ , "detailsapi": server + "applyDetail" /* API:用车申请取消 */ , "requestdeleteapi": server + "applyCancel" /* API:新增用车申请*/ , "applyAddapi": server + "applyAdd" /* API:审批提交*/ , "applySumbitapi": server + "applySumbit" /* API:用车审批详情查询*/ , "approvalQueryapi": server + "approveQuery" /* API:审批通过提交调度*/ , "applyApproveapi": server + "applyApprove" /* API:车辆归队列表查询*/ , "rejoinlistapi": server + "guidui_query" /* API:车辆调度列表查询*/ , "dispatchlistapi": server + "carDispatchQuery" /* API:派车单列表查询*/ , "orderlistapi": server + "paichedan_query" /* API:车辆信息列表查询(调度)*/ , "carlistapi": server + "vehicleListPcd" /* API:驾驶员信息列表查询(调度)*/ , "driverlistapi": server + "driverListPcd" /* API:派车单信息列表(可多个)*/ , "dispatchapi": server + "carDispatch" /* API:调度驳回*/ , "dispatchRejectapi": server + "dispatchReject" /* API:调度完结*/ , "dispatchOverapi": server + "dispatchOver" /* API:作废派车单*/ , "orderCancelapi": server + "paichedan_dele" /* API:车辆归队*/ , "orderRejoinapi": server + "car_guidui_update" } /*统计中心模块*/ , "reportStatistics": { /*API:定位统计*/ "locationapi": server + "locationStat"//"http://localhost:8080/cwt/api.jsp?api=locationStat"// /*告警统计*/ , "requestlistapi": server + "reportCountStat" /*里程统计*/ , "mileageStatapi": server + "mileageStat" /*油耗统计*/ , "oilCostStatapi": server + "oilCostStat" /*指令统计*/ , "commandStatapi": server + "commandStat" /*定位统计*/ , "locationStatapi": server + "locationStat" /*终端查询*/ , "terminalStatapi": server + "terminalStat" /*照片查询*/ , "photoStatapi": server + "photoStat" /*日志统计*/ , "logStatapi": server + "logStat" /*轨迹查询*/ , "trackStatapi": server + "trackStat" /*停车查询*/ , "parkStatapi": server + "parkStat", /** 告警查询 */ "reportStatapi": server + "reportStat", } /*设置中心-车辆管理模块*/ , "carmanager": { /*API:车辆分页列表*/ "datas": server + "vehicleList" /*API:更新车辆信息*/ , "update": server + "updaterole" , "listpage": "views/manager/car-list.html" , "editpage": "views/manager/car-edit.html" } /*设置中心-分组管理模块*/ , "groupmanager": { /*API:分组分页列表*/ "datas": server + "getTargetGroupingList" /*API:更新车辆信息*/ , "update": server + "updaterole" } /*设置中心-操作员管理模块*/ , "operatormanager": { /*API:操作员分页列表*/ "datas": server + "operatorList" , "listpage": "views/manager/operator-list.html" , "editpage": "views/manager/operator-edit.html" } /*设置中心-角色管理模块*/ , "rolemanager": { /*API:分组分页列表*/ "datas": server + "operatorRoleList" , "listpage": "views/manager/role-list.html" , "editpage": "views/manager/role-edit.html" } }; /* 各项内容模板设置 */ bus_cfgs.templates = { "cell": "<td class='center'/>" }; /* 各项数据默认值设置 */ bus_cfgs.options.defaults = { "dateformatsort": "YYYY-MM-DD" , "dateformatsort2": "yyyy-MM-dd HH:mm" , "dateformat": "yyyy-MM-dd HH:mm:ss" }; /* 数据字典相关设置 */ bus_cfgs.dict = { "sex": { "0": "男", "1": "女" } , "color": { "": "未设置", "ff0000": "红色", "ffffff": "白色", "000000": "黑色" } , "LOGINMODE": { "A": "LBS人员定位", "E": "GPS车辆定位(APN)", "F": "GPS车辆定位(CMNET)" } //申请状态 , "SQZT": { "": "全部", "1": "未提交", "2": "审核中", "3": "审核通过", "4": "已驳回" } , "DDZT": { "": "全部", "1": "未调度", "2": "调度中", "3": "调度完成", "4": "调度驳回" } , "YCFW": { "": "全部", "1": "市内", "2": "省内", "3": "省外" } //客服类型 , "KEFU": { "": "全部", "1": "投诉", "2": "需求建议" } //是否 , "SF": { "": "全部", "1": "是", "2": "否" } //告警类型 , "GJLX": { "": "所有告警类型", "1": "速度异常告警", "2": "区域告警", "3": "非法开门告警", "4": "紧急告警", "5": "邮箱开盖告警", "6": "主电源断电告警" } //出车状态 , "CCZT": { "": "全部", "1": "出车中", "2": "已归队" } //处理状态 , "CLZT": { "": "全部", "1": "待办", "2": "已办" } //车辆类型 , "CLLX": { "": "全部", "1": "小型客车", "2": "中型客车", "3": "大型客车" } //调度身份 , "DDSF": { "": "全部", "1": "申请人", "2": "审核员", "3": "调度员" } //驾驶员状态 , "JSTZT": { "0": "正常在岗", "1": "离岗", "2": "其他" } /** 指令类型 */ , "ZLLX": { "": "全部", "GC.TC.CALL": "点名动作", "GC.TST.MILE": "里程设置动作", "GC.TST.CALL_NO_LIST": "呼入呼出下发", "GC.TC.DOOR": "开关门动作", "GC.TC.OIL": "油路开关动作", "GC.EC.TAKE_PHOTO": "拍照动作", "GC.RTST.REGION_ENTER": "进区域告警下发", "GC.RTST.REGION_OUT": "出区域告警下发", "GC.RTST.SPEED": "速度告警下发", } }; /*异常字典定义*/ bus_cfgs.dict.errorCode = { "9999": "系统错误" , "8888": "JSON格式错误" , "1001": "账号不存在" , "1002": "密码错误" }; /* 日期选择控件参数设置 */ bus_cfgs.options.datepicker = { format: "yyyy-mm-dd", autoclose: true, todayBtn: true, language: "zh-CN", startDate: "2010-01-01", minView: "month", pickerPosition: "bottom-left" } bus_cfgs.options.datetimepicker = { format: "yyyy-mm-dd hh:ii:ss", autoclose: true, todayBtn: true, language: "zh-CN", startDate: "2010-01-01 00:00:00", pickerPosition: "bottom-left"//, //minuteStep: 6, // minView: 1 } /* 文本相关参数设置 */ bus_cfgs.options.texts = { "btn_delete": " <i class=\"fa fa-trash-o\"></i> 删除 " , "btn_add": "<i class=\"fa fa-plus\"></i> 新增" , "btn_details": " <i class=\"fa fa-info\"></i> 详情 " , "btn_back": "<i class=\"fa fa-arrow-circle-left\"></i> 返回" , "btn_export": "<i class=\"fa fa-share-square-o\"></i> 导出" , "btn_search": "<i class=\"fa fa-search\"></i> 查询" , "btn_refresh": "<i class=\"fa fa-refresh\"></i> 刷新" , "btn_save": " 保存 <i class=\"fa fa-arrow-circle-right\"></i>" , "btn_cancel": "<i class=\"fa fa-arrow-circle-left\"></i> 取消 " , "btn_ok": " 确定 <i class=\"fa fa-arrow-circle-right\"></i> " , "btn_submit": " <i class=\"icon-share-alt\"></i> 提交 " , "btn_reset": " <i class=\"icon-refresh\"></i> 重置 " , "btn_close": "<i class=\"glyphicon glyphicon-remove\"></i> 关闭 " , "btn_reject": "<i class=\"fa fa-arrow-circle-left\"></i> 驳回 " , "btn_createPCD": "<i class=\"fa fa-arrow-circle-right\"></i> 生成派车单 " , "btn_rejoin": "<i class=\"fa fa-arrow-circle-right\"></i> 归队 " , "btn_edit": "<i class=\"fa fa-pencil\"></i> 编辑 " , "btn_select": " <i class=\"fa fa-check-square-o\"></i> 选择 " , "btn_carback": " <i class=\"fa fa-check-square-o\"></i> 车辆归队 " , "btn_tonext": "<i class=\"fa fa-arrow-circle-right\"></i> 提交审批 " , "btn_todispatch": "<i class=\"fa fa-arrow-circle-right\"></i> 提交调度 " , "btn_dispatch": "<i class=\"fa fa-arrow-circle-right\"></i> 调度 " , "btn_nodispatch": "<i class=\"fa fa-arrow-circle-right\"></i> 无单调度 " , "btn_dispatchfinish": "<i class=\"fa fa-arrow-circle-right\"></i> 调度完结 " , "btn_supplement": "<i class=\"fa fa-arrow-circle-right\"></i> 补单 " , "btn_start": " <i class=\"fa fa-arrow-circle-right\"></i> 开始 " , "btn_pause": " <i class=\"icon-share-alt\"></i> 暂停 " , "btn_stop": " <i class=\"icon-refresh\"></i> 停止 " }; /* 样式相关参数设置 */ bus_cfgs.options.styles = { "default": "btn btn-default" }; /* 页面相关参数设置 */ bus_cfgs.options.page = { "size": 8, "texts": { "first": "<i class=\"icon-control-start\"></i> 首页" , "priv": "<i class=\"icon-control-rewind\"></i> 上一页" , "next": "下一页 <i class=\" icon-control-forward\"></i>" , "last": "末页 <i class=\"icon-control-end\"></i>" } }; /* 请求相关参数设置 */ bus_cfgs.options.request = { /* 设置AJAX请求超时时间:单位毫秒*/ "timeout": 120000 , "monitor": 60000 }; /* 下拉列表选项 */ bus_cfgs.options.select2 = { allowClear: true, language: "zh-CN" }; /*-----------------------------------------------------------------------------------*/ /* 当前页面选项 /*-----------------------------------------------------------------------------------*/ var pageOptions = { menus: [] , items: [] , currentmenu: null /* 当前选中的菜单 */ , requestOptions: {} /* 最后一次分页数据请求 */ , buffer: {} /* 最后一次请求分页数据 */ , fromCache: false /* 是否读取缓存数据 */ }; /* /// <summary>表示请求验证码的服务地址</summary> public const string QueryCaptcha = "{serverurl}getCaptcha"; /// <summary>表示请求用户登录的服务地址</summary> public const string QueryLogin = "{serverurl}login?sessionId={0}&u={1}&p={2}&captcha={3}&netType={4}"; /// <summary>表示请求目标列表的服务地址</summary> public const string QueryTargetList = "{serverurl}queryTargetList?sessionId={sessionid}&operId={operateid}"; /// <summary>表示请求订阅的服务地址</summary> public const string QuerySubscribe = "{serverurl}addSubscribe?sessionId={sessionid}&tid={0}&iType={1}"; /// <summary>表示请求最后轨迹的服务地址</summary> public const string QueryLastTrack = "{serverurl}queryLastTrack?sessionId={sessionid}&sids={0}"; /// <summary>表示请求实时轨迹的服务地址</summary> public const string QueryTrack = "{serverurl}getTrack?sessionId={sessionid}"; /// <summary>表示请求车辆详细信息的服务地址</summary> public const string QueryVehicleTargetDetail = "{serverurl}queryVehicleTargetDetail?sessionId={sessionid}&targetId={0}"; /// <summary>表示人员定位的服务地址</summary> public const string BatchCall = "{serverurl}batchCall?sessionId={sessionid}&sIds={0}"; /// <summary>表示人员详细信息服务地址</summary> public const string QueryPersonTargetDetail = "{serverurl}queryPersonTargetDetail?sessionId={sessionid}&targetId={0}"; /// <summary>表示定位统计服务地址</summary> public const string LocationStat = "{serverurl}locationStat?sessionId={sessionid}&startTime={0}&endTime={1}&sIds={2}&start={3}&limit={4}"; /// <summary>表示停车统计服务地址</summary> public const string ParkStat = "{serverurl}parkStat?sessionId={sessionid}&startTime={0}&endTime={1}&sIds={2}&start={3}&limit={4}&times={5}"; /// <summary>表示停车统计服务地址2</summary> public const string OldParkStat = "{serverurl}oldParkStat?sessionId={sessionid}&startTime={0}&endTime={1}&sIds={2}&start={3}&limit={4}&times={5}"; /// <summary>表示里程统计服务地址</summary> public const string MileageStat = "{serverurl}mileageStat?sessionId={sessionid}&startTime={0}&endTime={1}&sIds={2}&start={3}&limit={4}"; /// <summary>表示离线统计服务地址</summary> public const string OffLineStat = "{serverurl}offLineReportStat?sessionId={sessionid}&day={0}&sIds={1}&start={2}&limit={3}"; /// <summary>表示油耗统计服务地址</summary> public const string OilCostStat = "{serverurl}oilCostStat?sessionId={sessionid}&startTime={0}&endTime={1}&sIds={2}&start={3}&limit={4}"; /// <summary>表示终端统计服务地址</summary> public const string TerminalStat = "{serverurl}terminalStat?sessionId={sessionid}&sIds={0}&start={1}&limit={2}&groupId={3}&targetName={4}&sim={5}&planName={6}&isPlan={7}"; /// <summary>表示日志统计服务地址</summary> public const string LogStat = "{serverurl}logStat?sessionId={sessionid}&startTime={0}&endTime={1}&content={2}&start={3}&limit={4}"; /// <summary>表示指令统计服务地址</summary> public const string CommandStat = "{serverurl}commandStat?sessionId={sessionid}&startTime={0}&endTime={1}&sIds={2}&start={3}&limit={4}&cmdName={5}&operName={6}"; /// <summary>表示告警查询服务地址</summary> public const string ReportStat = "{serverurl}reportStat?sessionId={sessionid}&rType={0}&startTime={1}&endTime={2}&sIds={3}&start={4}&limit={5}"; /// <summary>表示告警统计服务地址</summary> public const string AlarmCountStat = "{serverurl}reportCountStat?sessionId={sessionid}&rType={0}&startTime={1}&endTime={2}&sIds={3}&start={4}&limit={5}"; /// <summary>表示轨迹统计服务地址</summary> public const string TrackStat = "{serverurl}trackStat?sessionId={sessionid}&startTime={0}&endTime={1}&sIds={2}&start={3}&limit={4}&sHour={5}&eHour={6}&type={7}"; /// <summary>表示照片统计服务地址</summary> public const string PhotoStat = "{serverurl}photoStat?sessionId={sessionid}&startTime={0}&endTime={1}&sIds={2}&start={3}&limit={4}"; /// <summary>表示里程重置服务地址</summary> public const string MileageReset = "{serverurl}mileReset?sessionId={sessionid}&sIds={0}&mile={1}"; /// <summary>表示立即拍照服务地址</summary> public const string OncePhoto = "{serverurl}oncePhoto?sessionId={sessionid}&sIds={0}"; /// <summary>表示油路控制服务地址</summary> public const string OilControl = "{serverurl}oilControl?sessionId={sessionid}&sIds={0}&c={1}"; /// <summary>表示远程开关门服务地址</summary> public const string OnOffDoor = "{serverurl}onOffDoor?sessionId={sessionid}&sIds={0}&d={1}"; /// <summary>表示终端密码验证服务地址</summary> public const string PwCheckURL = "{serverurl}pswCheck?sessionId={sessionid}&targetId={0}&psw={1}"; /// <summary>表示查询车辆信息服务地址</summary> public const string VehicleList = "{serverurl}vehicleList?sessionId={sessionid}&gName={0}&driver={1}&vName={2}&sim={3}&start={4}&limit={5}"; /// <summary>表示查询车辆信息服务地址(调度)</summary> public const string VehicleListDiaodu = "{serverurl}vehicleListPcd?sessionId={sessionid}&gName={0}&driver={1}&vName={2}&sim={3}&start={4}&limit={5}"; /// <summary>表示查询驾驶员信息服务地址(调度)</summary> public const string DriverListDiaodu = "{serverurl}driverListPcd?sessionId={sessionid}&vName={0}&sex={1}&dName={2}&dNum={3}&vType={4}&start={5}&limit={6}"; /// <summary>表示新增车辆类型服务地址</summary> public const string VehicleTypeAdd = "{serverurl}vehicleTypeAdd?sessionId={sessionid}&name={0}&desc={1}&remark={2}"; /// <summary>表示车辆类型服务地址</summary> public const string VehicleTypeQuery = "{serverurl}vehicleTypeQuery?sessionId={sessionid}"; /// <summary>表示查询驾驶员信息服务地址</summary> public const string DriverList = "{serverurl}driverList?sessionId={sessionid}&vName={0}&sex={1}&dName={2}&dNum={3}&vType={4}&start={5}&limit={6}"; /// <summary>表示查询目标分组信息服务地址</summary> public const string TargetGroupingList = "{serverurl}getTargetGroupingList?sessionId={sessionid}&gName={0}&gRuel={1}&start={2}&limit={3}"; public const string Upload = "{serverurl}upload?sessionId={sessionid}"; public const string DriverAdd = "{serverurl}driverAdd?sessionId={sessionid}&dName={0}&vName={1}&dNum={2}&sex={3}&date={4}&iCard={5}&address={6}&phone={7}&tel={8}&vType={9}&photo={10}&remark={11}"; public const string DriverUpdate = "{serverurl}driverUpdate?sessionId={sessionid}&dName={0}&vName={1}&dNum={2}&sex={3}&date={4}&iCard={5}&address={6}&phone={7}&tel={8}&vType={9}&photo={10}&remark={11}&driverId={12}"; public const string VehicleUpdate = "{serverurl}vehicleUpdate?sessionId={sessionid}&id={0}&vName={1}&simCode={2}&vType={3}&vColor={4}&vCharacter={5}&oilConsume={6}&vOwner={7}&phone={8}&password={9}&frameCode={10}&engineCode={11}&drivingLicence={12}&drivingLicenseDate={13}&runDate={14}&businessCode={15}&money={16}&buyDate={17}&registerDate={18}&saleMerchant={19}&invoiceCode={20}&subjoinMoneyCode={21}&photo={22}&remark={23}&areaCode={24}&qryType={25}&qryNum={26}"; public const string QryVehicleDriver = "{serverurl}qryVehicle_driver?sessionId={sessionid}&vName={0}&sim={1}&active={2}&gName={3}&start={4}&limit={5}"; public const string DriverDel = "{serverurl}driverDel?sessionId={sessionid}&driverId={0}"; public const string PersonUpdate = "{serverurl}personUpdate?sessionId={sessionid}&pId={0}&pName={1}&position={2}&sex={3}&sim={4}&idCard={5}&officeTel={6}&homeTel={7}&address={8}&department={9}&photo={10}"; public const string PersonDel = "{serverurl}personDel?sessionId={sessionid}&pId={0}"; public const string Img = "{serverurl}getImg?f={0}"; /// <summary>表示人员信息列表服务地址</summary> public const string PersonList = "{serverurl}personList?sessionId={sessionid}&gName={0}&sim={1}&pName={2}&openStat={3}&sex={4}&rzStat={5}&birth={6}&start={7}&limit={8}"; /// <summary>表示定位计划服务地址</summary> public const string LocatePlanList = "{serverurl}locatePlanList?sessionId={sessionid}&start={0}&limit={1}"; /// <summary>表示新增定位计划服务地址</summary> public const string LocatePlanAdd = "{serverurl}locatePlanAdd?sessionId={sessionid}&name={0}&sDate={1}&eDate={2}&locateInterval={3}&num={4}&type={5}"; /// <summary>表示删除定位计划服务地址</summary> public const string LocatePlanDel = "{serverurl}locatePlanDel?sessionId={sessionid}&id={0}&type={1}"; /// <summary>表示绑定关系定位计划服务地址</summary> public const string LocatePlanBound = "{serverurl}locatePlanBound?sessionId={sessionid}&pId={0}&tmnId={1}&pName={2}&tName={3}"; /// <summary>表示普通超速告警设置服务地址</summary> public const string SpeedAlarmSetting1 = "{serverurl}speedReportSetup?sessionId={sessionid}&type=1&speedType={0}&speed={1}&priority={2}&interval={3}&needConfirm={4}&onNow={5}&sids={6}"; /// <summary>表示时间段超速告警设置地址</summary> public const string SpeedAlarmSetting2 = "{serverurl}speedReportSetup?sessionId={sessionid}&sDate={0}&eDate={1}&speed={2}&interval={3}&sIds={4}"; /// <summary>表示离线车辆列表地址</summary> public const string OffLineReportList = "{serverurl}offLineReportList?sessionId={sessionid}&start={0}&limit={1}"; /// <summary>表示离线告警设置地址</summary> public const string OffLineUpdate = "{serverurl}offLineUpdate?sessionId={sessionid}&frequency={0}&type={1}&num={2}&sendOp={3}&id={4}"; /// <summary>表示离线告警详情地址</summary> public const string OffLineReportDetail = "{serverurl}offLineReportDetail?sessionId={sessionid}&id={abc}"; /// <summary>表示操作员信息管理查询地址</summary> public const string OperatorList = "{serverurl}operatorList?sessionId={sessionid}&userName={0}&loginName={1}&telphone={2}&state={3}&dispatch_identity={4}&start={5}&limit={6}"; /// <summary>表示操作员信息管理查询地址</summary> public const string OperatorDetail = "{serverurl}operatorDetail?sessionId={sessionid}&id={0}"; /// <summary>表示操作员信息管理查询地址</summary> public const string OperatorUpdate = "{serverurl}operatorUpdate?sessionId={sessionid}&id={0}&userName={1}&telphone={2}&email={3}&dispatch_identity={4}&remark={5}"; /// <summary>表示显示操作员已绑定的目标组查询地址</summary> public const string ShowTarGroup = "{serverurl}showTarGroup?sessionId={sessionid}&operId={0}"; /// <summary>表示分配目标组地址</summary> public const string MatchOperTmnGroup = "{serverurl}matchOperTmnGroup?sessionId={sessionid}&operId={0}&targetGroups={1}"; /// <summary>表示分配目标组地址</summary> public const string OperatorRoleMatching = "{serverurl}operatorRoleMatching?sessionId={sessionid}&operId={0}&roleIds={1}"; /// <summary>表示目标组新增地址</summary> public const string TargetGroupingAdd = "{serverurl}targetGroupingAdd?sessionId={sessionid}&gName={0}&gParentId={1}&groupType={2}&intro={3}&remark={4}&ruleId={5}"; /// <summary>表示目标组新增地址</summary> public const string TargetGroupingUpdate = "{serverurl}targetGroupingUpdate?sessionId={sessionid}&gName={0}&gParentId={1}&groupType={2}&intro={3}&remark={4}&ruleId={5}&gId={6}"; /// <summary>表示目标组删除地址</summary> public const string TargetGroupingDel = "{serverurl}targetGroupingDel?sessionId={sessionid}&gId={0}"; /// <summary>表示目标组删除地址</summary> public const string AddTargetMacting = "{serverurl}addTargetMacting?sessionId={sessionid}&groupId={0}&targetIds={1}"; /// <summary>表示目标组删除地址</summary> public const string RemoveTargetMacting = "{serverurl}removeTargetMacting?sessionId={sessionid}&groupId={0}&targetIds={1}"; /// <summary>表示查询操作员角色列表地址</summary> public const string OperatorRoleList = "{serverurl}operatorRoleList?sessionId={sessionid}&op_id={0}&name={1}&remark={2}&start={3}&limit={4}"; /// <summary>表示新增操作员角色信息地址</summary> public const string OperatorRoleAdd = "{serverurl}operatorRoleAdd?sessionId={sessionid}&name={0}&remark={1}&intro={2}&isOperator=1&isAdmin=2"; /// <summary>表示新增操作员角色信息地址</summary> public const string OperatorRoleUpdate = "{serverurl}operatorRoleUpdate?sessionId={sessionid}&name={0}&remark={1}&intro={2}&isOperator=1&isAdmin=2&id={3}"; /// <summary>表示删除操作员角色信息地址</summary> public const string OperatorRoleDel = "{serverurl}operatorRoleDel?sessionId={sessionid}&operIds={0}"; /// <summary>表示查询客服进度列表地址</summary> public const string CustomerServiceList = "{serverurl}customerServiceList?sessionId={sessionid}&type={0}&startTime={1}&endTime={2}&start={3}&limit={4}"; /// <summary>表示查询轨迹时间段列表地址</summary> public const string TrackTime = "{serverurl}getTrackTime?sessionId={sessionid}&startTime={0}&endTime={1}&sim={2}"; /// <summary>表示查询轨迹回放数据地址</summary> public const string TrackPlay = "{serverurl}tarckPlay?sessionId={sessionid}&sid={0}&startUtc={1}&endUtc={2}&timeInterval={3}"; /// <summary>PositionNoneCenter</summary> public const string PositionNoneCenter = "{serverurl}requestLocationDesc?sessionId={sessionid}&lon={0}&lat={1}&uuid={guid}"; */
// Used to set, get and check for cookie consent function checkForCookies(name) { return !!getCookie(name); } function getCookie(name) { let cookieArray = document.cookie.split(';'); return cookieArray.find(cookieCrumb => cookieCrumb.substring(name.length, 0) === name); } function setCookie(name, value, options) { if (typeof options === 'undefined') { options = {} } var cookieString = name + '=' + value + '; path=/' if (options.days) { var date = new Date() date.setTime(date.getTime() + (options.days * 24 * 60 * 60 * 1000)) cookieString = cookieString + '; expires=' + date.toGMTString() } if (document.location.protocol === 'https:') { cookieString = cookieString + '; Secure' } document.cookie = cookieString } function updateBanner() { document.getElementById("cookie-actions-container").style.display = "none"; document.getElementById("cookie-confirmation").style.display = "block"; } function unhideBanner() { document.getElementById("app-cookie-banner").style.display = "block"; } function hideBanner() { document.getElementById("app-cookie-banner").style.display = "none"; } function acceptAllCookies() { setCookie("ghre_allow_cookies", true, { days: 365 }); updateBanner(); } export { setCookie, getCookie, checkForCookies, acceptAllCookies, hideBanner, unhideBanner };
'use strict' const assert = require('assert') let fakeStream = new (require('stream').Writable)() fakeStream.buff = '' fakeStream._write = function (chunk, enc, next) { this.buff += chunk.toString() next() } let testOutput = ` TAP version 13 1..14 ok 1 foo example 1 not ok 2 foo example 2 --- stack: this is a stack ... ok 3 foo example 3 # SKIP ok 4 foo example 4 not ok 5 foo example 5 --- message: rejected string ... not ok 6 foo example 6 --- stack: this is a stack that is thrown ... ok 7 foo example 7 ok 8 foo example 8 not ok 9 foo example 9 --- name: Error stack: fake stack ... ok 10 foo example 10 ok 11 foo example 11 not ok 12 foo example 12 --- name: Error stack: fake stack ... not ok 13 foo example 13 --- name: Error stack: fake stack ... ok 14 foo example 14 # SKIP # tests 14 # pass 6 # fail 6 # skip 2 ` module.exports = function (cb) { let test = require('../index')({ outputStream: fakeStream, done: function (code) { try { console.log(fakeStream.buff.trim()) // console.log(require('util').inspect(fakeStream.buff.trim())) // console.log(require('util').inspect(testOutput.trim())) assert.equal(code, 1) assert.equal(fakeStream.buff.trim(), testOutput.trim()) cb() } catch (e) { console.error(e.stack) process.exit(1) } } }) test('foo example 1', function () { return Promise.resolve() }) test('foo example 2', function () { return Promise.reject({stack: 'this is a stack'}) }) test.skip('foo example 3', function () { return Promise.resolve() }) test('foo example 4', Promise.resolve()) test `foo example 5`(Promise.reject('rejected string')) test('foo example 6', function () { let err = {stack: 'this is a stack that is thrown'} throw err }) test('foo example 7', function () { return Promise.resolve() }) let err = Error() err.stack = 'fake stack' test('foo example 8', function () {}) test('foo example 9', function () { throw err }) test('foo example 10', function (cb) { cb() }) test('foo example 11', function (cb) { setImmediate(cb) }) test('foo example 12', function (cb) { cb(err) }) test('foo example 13', function (cb) { setImmediate(function () { cb(err) }) }) test('foo example 14') console.log('#\n# test most things\n#') test() }
import {Suite, assertThat, assertThrows, assertTrue, assertFalse} from "test/TestUtil.js" import {codeDistanceToPipeSize} from "src/braid/CodeDistance.js" let suite = new Suite("CodeDistance"); suite.test('codeDistanceToPipeSize', () => { assertThat(codeDistanceToPipeSize(1)).isEqualTo({w: 1, h: 1}); assertThat(codeDistanceToPipeSize(2)).isEqualTo({w: 1, h: 1}); assertThat(codeDistanceToPipeSize(3)).isEqualTo({w: 1, h: 1}); assertThat(codeDistanceToPipeSize(4)).isEqualTo({w: 1, h: 1}); assertThat(codeDistanceToPipeSize(5)).isEqualTo({w: 3, h: 1}); assertThat(codeDistanceToPipeSize(6)).isEqualTo({w: 3, h: 1}); assertThat(codeDistanceToPipeSize(7)).isEqualTo({w: 3, h: 3}); assertThat(codeDistanceToPipeSize(8)).isEqualTo({w: 3, h: 3}); assertThat(codeDistanceToPipeSize(9)).isEqualTo({w: 5, h: 3}); assertThat(codeDistanceToPipeSize(10)).isEqualTo({w: 5, h: 3}); assertThat(codeDistanceToPipeSize(11)).isEqualTo({w: 5, h: 5}); });
const customName = document.getElementById("customname"); const randomize = document.querySelector(".randomize"); const story = document.querySelector(".story"); const insertX = [ "Willy the Goblin", "Big Daddy", "Father Christmas" ]; const insertY = [ "the soup kitchen", "Disneyland", "the White House" ]; const insertZ = [ "spontaneously combusted", "melted into a puddle on the sidewalk", "turned into a slug and crawled away" ]; function randomValueFromArray(array){ const random = Math.floor(Math.random()*array.length); return array[random]; } randomize.addEventListener("click", result); function result() { let newStory, name, weight, temperature, xItem, yItem, zItem; /* Name */ name = "Bob"; // Default if(customName.value !== "") { // If specified name = customName.value; } /* Weight and Temperature */ // Default: US temperature = Math.round(94) + " fahrenheit"; weight = Math.round(300) + " pounds"; // UK if(document.getElementById("uk").checked) { temperature = Math.round(34) + " centigrade"; weight = Math.round(21) + " stones"; } /* Inserting Item */ xItem = randomValueFromArray(insertX); yItem = randomValueFromArray(insertY); zItem = randomValueFromArray(insertZ); /* Story */ newStory = `It was ${ temperature } outside, so ${ xItem } went for a walk. \ When they got to ${ yItem }, they stared in horror for a few moments, then ${ zItem }. \ ${ name } saw the whole thing, but was not surprised — ${ xItem } weighs ${ weight }, and it was a hot day.`; /* Data Update */ story.textContent = newStory; story.style.visibility = "visible"; }
const HtmlWebpackPlugin = require('html-webpack-plugin') const ProvidePlugin = require('webpack/lib/ProvidePlugin') var DedupePlugin = require('webpack/lib/optimize/DedupePlugin') module.exports = { entry: { app: [ './app/index.jsx' ] }, output: { path: './build', filename: 'bundle.js' }, resolve: { extensions: ['', '.js', '.jsx', '.coffee'], alias: { underscore: 'lodash' } }, plugins: [ new DedupePlugin(), new ProvidePlugin( { jQuery: 'jquery' } ), new HtmlWebpackPlugin( { template: 'app/index.html', inject: 'body' } ) ], module: { preLoaders: [ {test: /\.jsx?$/, loader: 'eslint-loader', exclude: /node_modules/} ], loaders: [ { test: /\.scss$/, loader: 'style!css!sass' }, { test: /\.jsx?$/, loader: 'babel', exclude: /node_modules/, // babel 6.x, pending: https://phabricator.babeljs.io/T2645 //query: {presets: ['es2015', 'stage-0', 'react']} query: {stage: 0} }, { test: /\.css$/, loader: 'style!css' }, { test: /\.png$/, loader: 'url-loader?mimetype=image/png' }, { test: /\.jpg$/, loader: 'url-loader?mimetype=image/jpg' }, { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=10000&minetype=application/font-woff' }, { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader' } ] }, eslint: { test: /\.jsx?$/, loaders: ['eslint'], exclude: /node_modules/ //configFile: './.eslintrc' } }
(function () { 'use strict'; angular .module('myapp.tracking') .config(configure); configure.$inject = [ 'c8yComponentsProvider', 'gettext' ]; function configure( c8yComponentsProvider, gettext ) { c8yComponentsProvider.add({ // adds a menu item to the widget menu list with ... name: 'Tracking Map', // ... the name *"Icon Map"* nameDisplay: gettext('Tracking Map'), // ... the displayed name *"Icon Map"* description: gettext('可追蹤設備位置的Plugin'), // ... a description templateUrl: ':::PLUGIN_PATH:::/views/tracking.html', // ... displaying *"charts.main.html"* when added to the dashboard options: { noDeviceTarget: false } }); } }());
const APP_VERSION = '0.3.2' function makeCsvRow (csvContent, tmp, rowDelimiter = `\r\n`, fieldSeperator = ';', idName = 'id') { // TBD Make alphbetical order? if (!csvContent) { csvContent += idName // set id as first columns for (let k1 in tmp) { if (tmp.hasOwnProperty(k1) && k1 !== idName) { // set id as first columns let text = k1.replace(/;/g, ' ') text = text.replace(/([A-Z])/g, ' $1') text = text.charAt(0).toUpperCase() + text.slice(1) // capitalize the first letter - as an example. csvContent += ';' + text } } csvContent += rowDelimiter } csvContent += `${tmp[idName]}` for (let k2 in tmp) { if (tmp.hasOwnProperty(k2) && k2 !== idName) { let value = '' if (typeof tmp[k2] === 'undefined' || !tmp[k2]) { // do nothing } else if (typeof tmp[k2] === 'string') { value = tmp[k2] } else if (Array.isArray(tmp[k2])) { value = JSON.stringify(tmp[k2]) } else if (typeof tmp[k2] === 'object') { value = JSON.stringify(tmp[k2]) } else { try { value = tmp[k2].toString() } catch (e) { } } csvContent += ';' + value.replace(/;/g, ' ') } } csvContent += rowDelimiter return csvContent } // to be removed function exportCsv (csvContent, filename) { let encodedUri = encodeURI('data:text/csv;charset=utf-8,' + csvContent) let link = document.createElement('a') link.setAttribute('href', encodedUri) link.setAttribute('download', filename) document.body.appendChild(link) // Required for FF link.click() } // to be removed function exportJson (jsonContent, filename) { if (typeof jsonContent !== 'string') jsonContent = JSON.stringify(jsonContent) let encodedUri = encodeURI('data:text/json;charset=utf-8,' + jsonContent) let link = document.createElement('a') link.setAttribute('href', encodedUri) link.setAttribute('download', filename) document.body.appendChild(link) // Required for FF link.click() } // improved download function function downloadData (content, filename, type = 'text/csv;charset=utf-8;') { const blob = new Blob([content], { type }) // IE11 & Edge if (navigator.msSaveBlob) { // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx navigator.msSaveBlob(blob, filename) } else { // In FF link must be added to DOM to be clicked const link = document.createElement('a') link.href = window.URL.createObjectURL(blob) link.setAttribute('download', filename) document.body.appendChild(link) link.click() // IE: "Access is denied"; see: https://connect.microsoft.com/IE/feedback/details/797361/ie-10-treats-blob-url-as-cross-origin-and-denies-access document.body.removeChild(link) } } export { APP_VERSION, makeCsvRow, exportCsv, exportJson, downloadData }
import React, { Component } from 'react' import './css/singleAD.css' import { connect } from 'react-redux' import { loadAd } from '../actions/actions' class SingleAD extends Component { componentDidMount(){ const id = this.props.match.params.id console.log('ID', id) this.props.loadAd(id) } render() { if(!this.props.ads) return 'Loading...' return ( <div className="card-wrapper"> <div className="single-card"> <img src={this.props.ads.picture} alt=""/> <h1>{this.props.ads.title}</h1> <p className="price">${this.props.ads.price}</p> <p>{this.props.ads.description}</p> <p>Email: {this.props.ads.email}</p> <p>Phone: {this.props.ads.phone}</p> <p><button>Add to your WishList</button></p> </div> </div> ) } } const mapStateToProps = (state) => { return { ads: state.advertisements } } export default connect(mapStateToProps, {loadAd})(SingleAD)
import React from 'react'; import Component from './App.component'; import './App.css'; import * as BooksAPI from './BooksAPI'; class App extends React.Component { constructor(props) { super(props) this.onOpenSearch = this.onOpenSearch.bind(this) this.onCloseSearch = this.onCloseSearch.bind(this) this.onChangeShelf = this.onChangeShelf.bind(this) this.onSearch = this.onSearch.bind(this) this.state = { showSearchPage: false, books: null } } componentDidMount() { BooksAPI.getAll() .then(bks => this.setState({ books: bks })) .catch(err => this.setState({ books: [] })) } onCloseSearch(e) { BooksAPI.getAll() .then(bks => this.setState({ books: bks, showSearchPage: false })) .catch(err => this.setState({ books: [] })) } onOpenSearch(e) { this.setState({ showSearchPage: true, books: null }) } onChangeShelf(e, book) { const shelf = e.target.value BooksAPI.update(book, shelf) .then(() => BooksAPI.getAll()) .then((bks) => this.setState({ books: bks })) .catch(err => this.setState({ books: [] })) } onSearch(e) { e.preventDefault() const query = e.target.value if (query && query.length > 2) { BooksAPI.search(query) .then((bks) => this.setState({ books: bks || [] })) .catch(err => this.setState({ books: [] })) } } render() { return ( <Component {...this.props} {...this.state} handleChange={this.handleChange} onCloseSearch={this.onCloseSearch} onOpenSearch={this.onOpenSearch} onChangeShelf={this.onChangeShelf} onSearch={this.onSearch} /> ); } } export default App;
var searchData= [ ['utility_2ecpp_96',['utility.cpp',['../utility_8cpp.html',1,'']]], ['utility_2ehpp_97',['utility.hpp',['../utility_8hpp.html',1,'']]] ];
import { Link } from "react-router-dom"; import "./returnHome.css"; function ReturnHome() { return ( <div className="returnHome"> <Link to="/game">Home</Link> </div> ); } export default ReturnHome;
import Vue from 'vue' import Router from 'vue-router' // import Index from '../components/PageIndex' // import TopicDetail from '../components/TopicDetail' // import User from '../components/PageUser' // import UserIndex from '../components/UserIndex' // import Collections from '../components/PageCollections' const Index = () => import(/* webpackChunkName: "index" */ '../components/PageIndex'); const TopicDetail = () => import(/* webpackChunkName: "topic-detail" */ '../components/TopicDetail'); const User = () => import(/* webpackChunkName: "user" */ '../components/PageUser'); const UserIndex = () => import(/* webpackChunkName: "user-index" */ '../components/UserIndex'); const Collections = () => import(/* webpackChunkName: "collections" */ '../components/PageCollections'); Vue.use(Router); export default new Router({ routes: [ { path: '/', redirect: {path: '/topics'} }, { path: '/topics', redirect: {path: '/topics/all', query: {page: 1}} }, { path: '/topics/:tab', name: 'Topics', component: Index }, { path: '/topic/:id', name: 'TopicDetail', component: TopicDetail }, { path: '/user/:loginname', component: User, children:[ { path:'', name:'UserIndex', component:UserIndex }, { path:'collections', name:'Collections', component:Collections } ] } ] })