text
stringlengths
7
3.69M
import React, { Component } from "react"; import { submitSignUp } from "../../actions/eventActions"; import { connect } from "react-redux"; import { attendanceType } from "../../utils/enums"; import Button from "@material-ui/core/Button"; import TextField from "@material-ui/core/TextField"; import Typography from "@material-ui/core/Typography"; import FormControl from "@material-ui/core/FormControl"; import { MenuItem, Grid } from "@material-ui/core"; class SignUpForm extends Component { constructor() { super(); this.state = { signup: "No" }; } updateSignUp(event) { console.log(event.target.value); this.setState({ signup: event.target.value }); } submitSignUp() { this.props.dispatch( submitSignUp(this.props.eventItemID, this.props.username, { attendance: this.state.signup }) ); this.setState({ signup: "No" }); } render() { const classes = this.props; console.log(this.props.eventItemID); return ( <Grid container spacing={2} justify="space-between"> <Grid item xs={12}> <Typography component="h1" variant="h5"> Sign Up For Event </Typography> </Grid> <Grid item xs={12}> <FormControl margin="normal" required fullWidth> <TextField select id="signup" value={this.state.signup} onChange={this.updateSignUp.bind(this)} > {attendanceType.map(option => ( <MenuItem key={option} value={option}> {option} </MenuItem> ))} </TextField> </FormControl> </Grid> <Grid item xs={12}> <Button fullWidth variant="contained" color="primary" onClick={this.submitSignUp.bind(this)} > Submit </Button> </Grid> </Grid> ); } } const mapStateToProps = state => { return { username: state.auth.username }; }; export default connect(mapStateToProps)(SignUpForm);
import React, { useState, useEffect } from "react"; import { Link } from "react-router-dom"; import { useGlobalContext } from "../../../context"; import listMeal from "../ListMeal"; import "./lunchlist.css"; import "../../../grid.css"; // Components import NavbarEating from "../NavbarEating"; import FooterTop from "../../tours/FooterTop"; import FooterBottom from "../FooterBottom"; import img from "../../../img/Eating/lunch/com tam suon (5)____horizontal-730x456.jpg"; const MealNo5 = () => { const [filterMeal, setFilterMeal] = useState(listMeal); const [showRequire, setShowRequire] = useState(false); const [mealQuantity, setMealQuantity] = useState(1); const [showPickDay, setShowPickDay] = useState(false); const { listCart, setListCart } = useGlobalContext(); useEffect(() => { const mealChoose = filterMeal.find((meal) => meal.to === "bua-trua-dac-sac-sai-gon-standard"); setFilterMeal(mealChoose); // eslint-disable-next-line }, []); useEffect(() => { if (showRequire) { document.body.style.overflowY = "hidden"; } else { document.body.style.overflowY = "unset"; } }, [showRequire]); useEffect(() => { if (showPickDay) { document.body.style.overflowY = "hidden"; } else { document.body.style.overflowY = "unset"; } }, [showPickDay]); const decreaseMeal = () => { if (mealQuantity <= 1) { setMealQuantity(1); } else { setMealQuantity(mealQuantity - 1); } }; const increaseMeal = () => { if (mealQuantity >= 100) { setMealQuantity(100); } else { setMealQuantity(mealQuantity + 1); } }; const addCart = (id) => { const addedItem = listCart.find((x) => x.id === id); if (addedItem) { setListCart((y) => (y.id === id ? { ...addedItem, quantity: addedItem.quantity + 1 } : y)); } else { setListCart([...listCart, { ...filterMeal, quantity: 1 }]); } }; const { id, mealName, rating, description, chefImg, chefName, price, to } = filterMeal; return ( <> <NavbarEating /> <div className='lunchlist-container'> <div className='grid wide'> <div className='row'> {/* Breadcrumbs */} <nav className='col l-12 m-12 c-12'> <ul className='lunchlist-navbar'> <li className='lunchlist-item'> <Link className='lunchlist-link' to='/an-uong'> <span>Trang chủ</span> </Link> </li> <li className='lunchlist-item'> <Link className='lunchlist-link' to='/an-uong'> <span>Combo bữa trưa</span> </Link> </li> <li className='lunchlist-item'> <Link className='lunchlist-choose' to={`${to}`}> <span>{mealName}</span> </Link> </li> </ul> </nav> {/* Name */} <div className='col l-12 m-12 c-12'> <h2 className='lunchlist-name'>{mealName}</h2> </div> <div className='col l-8 m-12 c-12'> {/* Rating and Price */} <div className='lunchlist-ratingprice'> {rating !== undefined ? ( <p className='lunchlist-rating'> {rating.map((desc, index) => ( <span key={index}>{desc}</span> ))} </p> ) : ( "" )} <p> {price !== undefined ? <span>{price.toLocaleString()}</span> : ""} <span> đ/tuần</span> </p> </div> </div> {/* Info */} <div className='col l-8 m-12 c-12'> {/* Image and Description */} <div className='lunchlist-imgdesc'> {description && <span>{description}</span>} <img src={img} alt={mealName} className='lunchlist-img' /> </div> {/* Introduce */} <div className='lunchlist-introduce'> <div className='row'> <div className='col l-6 m-12 c-12'> <div className='lunchlist-whychoose'> <h3>Tại sao bạn nên chọn gói này?</h3> <p> Dù là người mới đến hay quá thân thuộc với đất Sài Thành, bạn cũng không bao giờ hết ấn tượng với thiên đường ẩm thực nơi đây. Để “ấm lòng”, bạn có thể gọi một tô bún mắm dậy mùi thơm nức của các loại mắm, ăn kèm miếng mực giòn sực, chả dai thơm và các loại rau cực ngon. Khi cần no bụng, cơm tấm Sài Gòn thơm nức mũi chắc chắn đủ làm bạn hài lòng, hoặc thưởng thức ngay một tô hủ tiếu khô, mì quảng để bữa trưa thật nhiều thi vị nhé!. Hãy thử nhé! </p> </div> </div> <div className='col l-6 m-12 c-12'> <div className='lunchlist-designed'> <h3>Thực đơn được thiết kế bởi</h3> <div className='lunchlist-chefinfo'> <img src={chefImg} alt={chefName} className='chef-img' /> <p>Bộ sưu tập món ngon iVIVU đề cử</p> </div> </div> </div> </div> </div> {/* Menu Week */} <div className='lunchlist-menuweek'> <div className='menuweek'> <h3> Thực đơn tuần <span> 15.02 <i className='fas fa-arrow-right'></i> 19.02 </span> </h3> <button onClick={() => setShowPickDay(true)}>Thay đổi</button> </div> {showPickDay && ( <div className={`modal-overlay ${showPickDay ? "show-modal" : ""}`}> <div className='lunchlist-pickdayform'> <i onClick={() => setShowPickDay(false)} className='fas fa-times'></i> <h3>Bỏ bớt ngày không phù hợp</h3> <p>Thứ 2, 15.02 → Thứ 6, 19.02</p> <div> <input id='monday' type='checkbox' /> <label htmlFor='monday'> <p>Thứ 2 · Nui xào bò</p> </label> </div> <div> <input id='tuesday' type='checkbox' /> <label htmlFor='tuesday'> <p>Thứ 3 · Bún mọc</p> </label> </div> <div> <input id='wednesday' type='checkbox' /> <label htmlFor='wednesday'> <p>Thứ 4 · Cơm chiên dương châu</p> </label> </div> <div> <input id='thursday' type='checkbox' /> <label htmlFor='thursday'> <p>Thứ 5 · Mì phúc kiến xào</p> </label> </div> <div> <input id='friday' type='checkbox' /> <label htmlFor='friday'> <p>Thứ 6 · Bún gà nướng sả</p> </label> </div> <div className='lunchlist-pickdayformtotal'> <p>Tổng cộng</p> <p> <span>{price.toLocaleString()}</span> <span> đ/tuần</span> </p> </div> <div className='lunchlist-pickdayformbtn'> <button onClick={() => setShowPickDay(false)}>Huỷ</button> <button>Xác nhận</button> </div> </div> </div> )} <div className='row'> <div className={`col l-2-4 m-2-4 c-12`}> <div className='lunchlist-menudetail'> <div className='lunchlist-dayinweek'> <span>Thứ 2 15.02</span> </div> <h5>Nui xào bò</h5> ..... <div className='lunchlist-ricedesert'> <p>Spice Viet Sai Gon</p> </div> </div> </div> <div className='col l-2-4 m-2-4 c-12'> <div className='lunchlist-menudetail'> <div className='lunchlist-dayinweek'> <span>Thứ 3 16.02</span> </div> <h5>Bún mọc</h5> ..... <div className='lunchlist-ricedesert'> <p>Spice Viet Sai Gon</p> </div> </div> </div> <div className='col l-2-4 m-2-4 c-12'> <div className='lunchlist-menudetail'> <div className='lunchlist-dayinweek'> <span>Thứ 4 17.02</span> </div> <h5> Cơm chiên <br /> dương châu </h5> ..... <div className='lunchlist-ricedesert'> <p>Spice Viet Sai Gon</p> </div> </div> </div> <div className='col l-2-4 m-2-4 c-12'> <div className='lunchlist-menudetail'> <div className='lunchlist-dayinweek'> <span>Thứ 5 18.02</span> </div> <h5> Mì phúc <br /> kiến xào </h5> ..... <div className='lunchlist-ricedesert'> <p>Spice Viet Sai Gon</p> </div> </div> </div> <div className='col l-2-4 m-2-4 c-12'> <div className='lunchlist-menudetail'> <div className='lunchlist-dayinweek'> <span>Thứ 6 19.02</span> </div> <h5> Bún gà <br /> nướng sả </h5> ..... <div className='lunchlist-ricedesert'> <p>Spice Viet Sai Gon</p> </div> </div> </div> </div> </div> {/* Delivery */} <div className='lunchlist-delivery'> <h3>Phương thức giao hàng</h3> <p>Bữa trưa được đóng gói trong khay nhựa thực phẩm ngay trước khi giao</p> <p>Giao hàng miễn phí từ 11h15 đến 12h00 hàng ngày tại các khu vực:</p> <p> <b>Hồ Chí Minh</b>: Quận 1, Quận 10, Quận 11, Quận 2, Quận 3, Quận 4, Quận 5, Quận 6, Quận 7, Quận 8, Quận Bình Thạnh, Quận Gò Vấp, Quận Phú Nhuận, Quận Tân Bình, Quận Tân Phú. </p> <p> Quý khách ngoài khu vực trên vui lòng để lại thông tin liên lạc, iVIVU sẽ cố gắng hỗ trợ Quý khách trong thời gian sớm nhất. </p> <p onClick={() => setShowRequire(true)}> Yêu cầu giao khu vực khác <i className='fas fa-angle-right'></i> </p> </div> {showRequire && ( <div className={`modal-overlay ${showRequire ? "show-modal" : ""}`}> <div className='lunchlist-sendrequire'> <i onClick={() => setShowRequire(false)} className='fas fa-times'></i> <h3>Yêu cầu giao khu vực khác</h3> <div> <label htmlFor=''>Tên đầy đủ *</label> <input type='text' /> </div> <div> <label htmlFor=''>Số di động</label> <input type='text' /> </div> <div> <label htmlFor=''>Email</label> <input type='email' /> </div> <div> <label htmlFor=''>Địa chỉ giao hàng</label> <input type='text' /> </div> <button>Gửi yêu cầu</button> </div> </div> )} </div> {/* Price Table */} <div className='col l-4 m-12 c-12'> <div className='lunchlist-pricetable'> <div className='lunchlist-firsttable'> <h4> Thực đơn tuần thứ 2, 15.02 <i className='fas fa-arrow-right'></i> thứ 6, 19.02 </h4> <div> <div className='lunchlist-quantity'> <button onClick={decreaseMeal}>-</button> <span className='lunchlist-quantitypart'>{mealQuantity}</span> <button onClick={increaseMeal}>+</button> <span className='lunchlist-part'>Phần</span> </div> <div className='lunchlist-tools'> <div className='lunchlist-morerice'> <div> <input type='checkbox' id='morerice' /> <label htmlFor='morerice'>Cơm thêm</label> </div> <div> <span>+ 2.000 </span> <span>đ/ngày</span> </div> </div> <div className='lunchlist-spoonchopstick'> <div> <input type='checkbox' id='spoonchopstick' /> <label htmlFor='spoonchopstick'>Muỗng đũa</label> </div> <div> <span>+ 2.000 </span> <span>đ/ngày</span> </div> </div> </div> </div> </div> <div className='lunchlist-secondtable'> <p>Nước uống dùng kèm</p> <div className='lunchlist-blackcoffee'> <div> <input type='checkbox' id='blackcoffee' /> <label htmlFor='blackcoffee'>Cafe đen</label> </div> <div> <span>+ 10.000 </span> <span>đ/ngày</span> </div> </div> <div className='lunchlist-lemontea'> <div> <input type='checkbox' id='lemontea' /> <label htmlFor='lemontea'>Trà chanh</label> </div> <div> <span>+ 10.000 </span> <span>đ/ngày</span> </div> </div> <div className='lunchlist-milkcoffee'> <div> <input type='checkbox' id='milkcoffee' /> <label htmlFor='milkcoffee'>Cafe sữa</label> </div> <div> <span>+ 15.000 </span> <span>đ/ngày</span> </div> </div> </div> <div className='lunchlist-thirdtable'> <div className='lunchlist-totalprice'> <span>Tổng cộng</span> <p> {price !== undefined ? <span className='lunchlist-total'>{price.toLocaleString()}</span> : ""} <span> đ/tuần</span> </p> </div> <div className='lunchlist-btnaddorder'> <button className='lunchlist-btnadd' onClick={() => addCart(id)}> Thêm vào giỏ hàng </button> <button className='lunchlist-btnorder'>Đặt ngay</button> </div> </div> </div> </div> </div> </div> </div> <div style={{ backgroundColor: "#f9f9f9", padding: "0 8px" }}> <FooterTop /> <FooterBottom /> </div> </> ); }; export default MealNo5;
define(['knockout', 'webApiClient', 'messageBox', 'page', 'baseList'], function (ko, webApiClient, messageBox, page, baseList) { "use strict"; var setupViewModel = { tableViewModel: new baseList.ListViewModel({ columns: [ { name: "Name", value: "Name", sortDescending: false }, { name: "Type", value: "Type" }, ], sortable: true, filterMode: 'search', pageSize: 10, emptyRowMessage: "No Sites found", url: "/setup/sites/", successCallback: function (model) { messageBox.Hide(); }, errorCallback: function (errorResponse) { messageBox.ShowError("Error retrieving Sites"); } }, null), UploadSites: function (file) { var self = this; messageBox.Hide(); webApiClient.ajaxUploadCsv("/setup/sites", file, function(model) { messageBox.ShowSuccess(file.name + " uploaded sucessfully"); }, function(errorResponse) { messageBox.ShowErrors("Upload Failed. ", errorResponse); }); }, SyncSummaries: function () { var self = this; messageBox.Hide(); webApiClient.ajaxPut("/setup/", "/syncProjectSummaries", null, function (model) { messageBox.ShowSuccess("Sync Details Requested Successfully"); }, function (errorResponse) { messageBox.ShowErrors("Error requesting details:", errorResponse); }); }, SyncFields: function () { var self = this; messageBox.Hide(); webApiClient.ajaxPut("/setup/", "/syncFields", null, function (model) { messageBox.ShowSuccess("Sync Fields Completed Successfully"); }, function (errorResponse) { messageBox.ShowErrors("Error requesting fields:", errorResponse); }); }, Initialise: function () { var self = this; ko.applyBindings(self, $("#setupActions")[0]); } }; return setupViewModel; });
export var defaultGetTextAndFormatDate = () => ({ text: "", formatDate: "" }); export var defaultGetSingleAppointment = () => ({});
require('./config/config') const express = require('express'); const app = express(); // Using Node.js `require()` const mongoose = require('mongoose'); const path = require('path'); //Este paquete (bodyParser) serializa en un objeto json la información //enviada en un POST: const bodyParser = require('body-parser'); //Son midelware's, se ejecutarán c/vez que pase por aquí en c/petición //parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })); // parse application/json app.use(bodyParser.json()); //habilitar la carpet public para que pueda ser accedida desde cualquier lugar app.use(express.static(path.resolve(__dirname, '../public'))); //Config. global de rutas app.use(require('./routes/index')); mongoose.connect(process.env.URLDB, (err, res) => { if (err) throw err; console.log('BD On-line'); }); app.listen(process.env.PORT, () => { console.log(`Escuchando puerto ${process.env.PORT}`); });
/** * Deals with browser storage */ import store from './store'; import events from 'enketo-core/src/js/event'; import settings from './settings'; import connection from './connection'; import $ from 'jquery'; import assign from 'lodash/assign'; let hash; function init( survey ) { return store.init() .then( () => get( survey ) ) .then( _removeQueryString ) .then( result => { if ( result ) { return result; } else { return set( survey ); } } ) .then( _processDynamicData ) .then( _setUpdateIntervals ) .then( _setResetListener ); } function get( survey ) { return store.survey.get( survey.enketoId ); } function set( survey ) { return connection.getFormParts( survey ) .then( _swapMediaSrc ) .then( _addBinaryDefaultsAndUpdateModel ) .then( store.survey.set ); } function remove( survey ) { return store.survey.remove( survey.enketoId ); } function _removeQueryString( survey ) { const bareUrl = window.location.pathname + window.location.hash; history.replaceState( null, '', bareUrl ); return survey; } function _processDynamicData( survey ) { // TODO: In the future this method could perhaps be used to also store // dynamic defaults. However, the issue would be to figure out how to clear // those defaults. if ( !survey ) { return survey; } return store.dynamicData.get( survey.enketoId ) .then( data => { const newData = { enketoId: survey.enketoId }; assign( newData, data ); // Carefully compare settings data with stored data to determine what to update. // submissionParameter if ( settings.submissionParameter.name ) { if ( settings.submissionParameter.value ) { // use the settings value newData.submissionParameter = settings.submissionParameter; } else if ( settings.submissionParameter.value === '' ) { // delete value delete newData.submissionParameter; } else if ( data && data.submissionParameter && data.submissionParameter.value ) { // use the stored value settings.submissionParameter.value = data.submissionParameter.value; } } else { delete newData.submissionParameter; } // parentWindowOrigin if ( typeof settings.parentWindowOrigin !== 'undefined' ) { if ( settings.parentWindowOrigin ) { // use the settings value newData.parentWindowOrigin = settings.parentWindowOrigin; } else if ( settings.parentWindowOrigin === '' ) { // delete value delete newData.parentWindowOrigin; } else if ( data && data.parentWindowOrigin ) { // use the stored value settings.parentWindowOrigin = data.parentWindowOrigin; } } else { delete newData.parentWindowOrigin; } return store.dynamicData.update( newData ); } ) .then( () => survey ); } function _setUpdateIntervals( survey ) { hash = survey.hash; // Check for form update upon loading. // Note that for large Xforms where the XSL transformation takes more than 30 seconds, // the first update make take 20 minutes to propagate to the browser of the very first user(s) // that open the form right after the XForm update. setTimeout( () => { _updateCache( survey ); }, 3 * 1000 ); // check for form update every 20 minutes setInterval( () => { _updateCache( survey ); }, 20 * 60 * 1000 ); return Promise.resolve( survey ); } /** * Form resets require reloading the form media. * This makes form resets slower, but it makes initial form loads faster. * * @param {*} survey [description] */ function _setResetListener( survey ) { $( document ).on( 'formreset', function( event ) { if ( event.target.nodeName.toLowerCase() === 'form' ) { survey.$form = $( this ); updateMedia( survey ); } } ); return Promise.resolve( survey ); } /** * Handles loading form media for newly added repeats. * * @param {*} survey [description] */ function _setRepeatListener( survey ) { //Instantiate only once, after loadMedia has been completed (once) survey.$form[ 0 ].addEventListener( events.AddRepeat().type, event => { _loadMedia( survey, $( event.target ) ); } ); return Promise.resolve( survey ); } /** * Changes src attributes in view to data-offline-src to facilate loading those resources * from the browser storage. * @param {*} survey */ function _swapMediaSrc( survey ) { survey.form = survey.form.replace( /(src="[^"]*")/g, 'data-offline-$1 src=""' ); return survey; } /** * Loads all default binary files and adds them to the survey object. It removes the src * attributes from model nodes with default binary files. * @param {*} survey */ function _addBinaryDefaultsAndUpdateModel( survey ) { // The mechanism for default binary files is as follows: // 1. They are stored as binaryDefaults in the resources table with the key being comprised of the VALUE (i.e. jr:// url) // 2. Filemanager.getFileUrl will determine whether to load from (survey) resources of (record) files const model = new DOMParser().parseFromString( survey.model, 'text/xml' ); const binaryDefaultElements = [ ...model.querySelectorAll( 'instance:first-child > * *[src]' ) ]; const tasks = []; survey.binaryDefaults = []; binaryDefaultElements.forEach( el => { tasks.push( connection.getMediaFile( el.getAttribute( 'src' ) ) .then( result => { // Overwrite the url to use the jr://images/img.png value. This makes the magic happen. // It causes a jr:// value to be treated the same as a filename.ext value. result.url = el.textContent; survey.binaryDefaults.push( result ); // Now the src attribute should be removed because the filemanager.js can return the blob for // the jr://images/... key (as if it is a file). el.removeAttribute( 'src' ); } ) .catch( e => { // let files fail quietly. Rely on Enketo Core to show error. console.error( e ); } ) ); } ); return Promise.all( tasks ) .then( () => { survey.model = new XMLSerializer().serializeToString( model ); return survey; } ); } /** * Updates maximum submission size if this hasn't been defined yet. * The first time this function is called is when the user is online. * If the form/data server updates their max size setting, this value * will be updated the next time the cache is refreshed. * * @param {*} survey [description] * @return {*} [description] */ function updateMaxSubmissionSize( survey ) { if ( !survey.maxSize ) { return connection.getMaximumSubmissionSize() .then( maxSize => { if ( maxSize ) { survey.maxSize = maxSize; // Ignore resources. These should not be updated. delete survey.resources; delete survey.binaryDefaults; return store.survey.update( survey ); } return survey; } ); } else { return Promise.resolve( survey ); } } /** * Loads survey resources either from the store or via HTTP (and stores them). * * @param {*} survey [description] * @return {Promise} [description] */ function updateMedia( survey ) { const requests = []; // if survey.resources exists, the resources are available in the store if ( survey.resources ) { return _loadMedia( survey ) .then( _setRepeatListener ); } survey.resources = []; _getElementsGroupedBySrc( survey.$form.add( $( '.form-header' ) ) ).forEach( elements => { const src = elements[ 0 ].dataset.offlineSrc; requests.push( connection.getMediaFile( src ) ); } ); return Promise.all( requests.map( _reflect ) ) .then( resources => { // Filter out the failed requests (undefined) resources = resources.filter( resource => !!resource ); survey.resources = resources; return survey; } ) // Store any resources that were successful .then( store.survey.update ) .then( _loadMedia ) .then( _setRepeatListener ) .catch( error => { console.error( 'loadMedia failed', error ); // Let the flow continue. return survey; } ); } /** * To be used with Promise.all if you want the results to be returned even if some * have failed. Failed tasks will return undefined. * * @param {Promise} task [description] * @return {*} [description] */ function _reflect( task ) { return task .then( response => response, error => { console.error( error ); return; } ); } function _loadMedia( survey, $target ) { let resourceUrl; const URL = window.URL || window.webkitURL; $target = $target || survey.$form.add( $( '.form-header' ) ); _getElementsGroupedBySrc( $target ).forEach( elements => { const src = elements[ 0 ].dataset.offlineSrc; store.survey.resource.get( survey.enketoId, src ) .then( resource => { if ( !resource || !resource.item ) { console.error( 'resource not found or not complete', src ); return; } // create a resourceURL resourceUrl = URL.createObjectURL( resource.item ); // add this resourceURL as the src for all elements in the group elements.forEach( element => { element.src = resourceUrl; } ); } ); } ); // TODO: revoke objectURL if not inside a repeat // add eventhandler to last element in a group? // $( element ).one( 'load', function() { // console.log( 'revoking object URL to free up memory' ); // URL.revokeObjectURL( resourceUrl ); // } ); return Promise.resolve( survey ); } function _getElementsGroupedBySrc( $target ) { const groupedElements = []; const urls = {}; let $els = $target.find( '[data-offline-src]' ); $els.each( function() { if ( !urls[ this.dataset.offlineSrc ] ) { const src = this.dataset.offlineSrc; const $group = $els.filter( function() { if ( this.dataset.offlineSrc === src ) { // remove from $els to improve performance $els = $els.not( `[data-offline-src="${src}"]` ); return true; } } ); urls[ src ] = true; groupedElements.push( $.makeArray( $group ) ); } } ); return groupedElements; } function _updateCache( survey ) { console.log( 'Checking for survey update...' ); connection.getFormPartsHash( survey ) .then( version => { if ( hash === version ) { console.log( 'Cached survey is up to date!', hash ); } else { console.log( 'Cached survey is outdated! old:', hash, 'new:', version ); return connection.getFormParts( survey ) .then( formParts => { // media will be updated next time the form is loaded if resources is undefined formParts.resources = undefined; return formParts; } ) .then( _swapMediaSrc ) .then( _addBinaryDefaultsAndUpdateModel ) .then( store.survey.update ) .then( result => { // set the hash so that subsequent update checks won't redownload the form hash = result.hash; console.log( 'Survey is now updated in the store. Need to refresh.' ); $( document ).trigger( 'formupdated' ); } ); } } ) .catch( error => { // if the form has been de-activated or removed from the server if ( error.status === 404 || error.status === 401 ) { // remove it from the store remove( survey ) .then( () => { // TODO notify user to refresh or trigger event on form console.log( `survey ${survey.enketoId} removed from storage`, error.status ); } ) .catch( e => { console.error( 'an error occurred when attempting to remove the survey from storage', e ); } ); } else { console.log( 'Could not obtain latest survey or hash from server or failed to save it. Probably offline.', error.stack ); } } ); } /** * Completely flush the form cache (not the data storage) * * @return {Promise} [description] */ function flush() { return store.survey.removeAll() .then( () => { console.log( 'Done! The form cache is empty now. (Records have not been removed)' ); return; } ); } export default { init, get, updateMaxSubmissionSize, updateMedia, remove, flush };
function greet(whatToSay) { return function(name) { console.log(whatToSay + " " + name); } } //greet("Hi")("Lars"); var sayHi = greet("Hi"); /* equals: var whatToSay = "Hi"; var sayHi = function(name) { consnole.log(whatToSay + " " + name); } */ sayHi("Lars");
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Image } from 'react-native'; import Dimensions from 'Dimensions'; var width = Dimensions.get('window').width; var height = Dimensions.get('window').height; var Main = require('./main.js'); var Launch =React.createClass({ getInitialState:function(){ return { sec:3, } }, componentDidMount:function(){ var sec = this.state.sec; var that = this; this.timer = setInterval(function(){ sec--; that.setState({ sec:sec }); if (sec == 0) { clearInterval(that.timer); that.props.navigator.replace({ component:Main, title:"main" }) } },1000); }, render:function(){ return ( <View> <Text style={{alignSelf:'flex-end'}}>{this.state.sec}秒后自动跳转</Text> <Image source={require('../../images/launch.png')} style={{width:width,height:height}}/> </View> ); } }) module.exports = Launch;
import React from 'react'; import { View, Dimensions } from 'react-native'; import { Input, Button, Image, Text } from 'react-native-elements'; import ImagePicker from 'react-native-image-crop-picker'; import axios from 'axios'; import { connect } from 'react-redux'; import Modal from 'react-native-modal'; import { createPost } from '../../store/actions/post'; import addPostImg from '../../../assets/images/add_image.png'; class CreatePost extends React.Component { constructor(props) { super(props); this.state = { control: { body: '' }, image: null, modalVisible: false }; } static navigationOptions = ({ navigation }) => { return { title: 'New post', headerRight: ( <Button title="share" type="solid" buttonStyle={{backgroundColor: 'rgba(0,0,0,0)'}} titleStyle={{textTransform: 'capitalize', fontSize: 20, color: '#53B8E9'}} onPress={navigation.getParam('save')} /> ) }; }; _toggleModalVisibility = () => { this.setState(state => ({ ...state.control, modalVisible: !state.modalVisible })); }; _launchImagePicker = () => { ImagePicker.openPicker({ width: 300, height: 400, cropping: true }) .then(image => { console.log(image); this.setState(state => ({ image })); }) .catch(err => console.log(err)); }; _launchCamera = () => { ImagePicker.openCamera({ width: 300, height: 400, cropping: true }) .then(image => { console.log(image); this.setState({ ...this.state, image }); }) .catch(err => console.log(err)); }; postBodyHandler = val => { this.setState(state => { return { ...state, control: { ...state.control, body: val } }; }); }; handleUploadData = async () => { let image = { uri: this.state.image.path, type: 'image/jpeg', name: 'example' }; let data = new FormData(); data.append('image', image); data.append('user_id', 1); data.append('body', this.state.control.body); await this.props.createPost(data); this.setState(state => ({ ...state, control: { ...state.control, image: null } })); }; componentDidMount() { this.props.navigation.setParams({ save: this.handleUploadData.bind(this) }) } render() { const { width, height } = Dimensions.get('window'); return ( <View> <Modal isVisible={this.state.modalVisible} animationIn="zoomIn" animationOut="zoomOut" animationInTiming={500} animationOutTiming={500} onBackdropPress={this._toggleModalVisibility} style={{ alignItems: 'center' }} > <View style={{ backgroundColor: '#FFF', borderRadius: 5, width: width * 0.6, height: '40%', flexDirection: 'column' }} > <View style={{ paddingHorizontal: 15, paddingTop: 15, flex: 1, flexDirection: 'row', justifyContent: 'center' }} > <Text h4>select image</Text> </View> <View style={{ flexDirection: 'column' }}> <Button type="clear" title="capture image with camera" onPress={this._launchCamera} /> <Button type="clear" title="pick image from gallery" onPress={this._launchImagePicker} /> <Button type="clear" title="cancel" buttonStyle={{ borderTopWidth: 0.7, borderColor: '#999' }} onPress={this._toggleModalVisibility} /> </View> </View> </Modal> <View style={{ flexDirection: 'row' }}> <View style={{ flexDirection: 'column', width: '32%' }}> <Image containerStyle={{ width: '100%', height: height * 0.2 }} style={{ alignSelf: 'stretch', flex: 1, width: undefined, height: undefined }} resizeMode="cover" source={ this.state.image !== null ? { uri: this.state.image.path } : addPostImg } /> <Button title="select image" type="outline" onPress={this._toggleModalVisibility} /> </View> <View style={{ width: '68%' }}> <Input textAlignVertical="top" multiline={true} inputContainerStyle={{ height: height * 0.2 }} inputStyle={{ height: height * 0.2 }} placeholder="enter a caption" value={this.state.control.body} onChangeText={this.postBodyHandler} /> </View> </View> </View> ); } } export default connect( null, { createPost } )(CreatePost);
// Module: https://github.com/learnboost/socket.io/ // Documentation: http://socket.io/#how-to-use exports.initialize = function(application) { var socket = require('socket.io') , io = socket.listen(application) , utilities = require('./utilities-0.0.3') , applicationConfigurationModule = require('./configuration/application-0.2.5') , redisStore = require('socket.io/lib/stores/redis') , mongoDB = require('./mongodb-0.0.1') , redisDB = require('./redis-0.0.1') , topPlaylists = require('./top_playlists-0.0.1') , jamendoApiModule = require('./jamendo_api-0.0.1'); var applicationConfiguration = applicationConfigurationModule.getApplicationConfiguration(); var socketIOOptions = { 'transports': ['websocket'], 'browser client minification': true, 'browser client etag': true, 'browser client gzip': true }; io.set(socketIOOptions); utilities.log('[SOCKET_IO] redisDB pubClient', 'info'); redisDB.getClient(false, function(error, pubClient) { if (error) { utilities.log('socket io initialize get redis pubClient failed: ' + error); } utilities.log('[SOCKET_IO] redisDB subClient', 'info'); redisDB.getClient(false, function(error, subClient) { if (error) { utilities.log('socket io initialize get redis subClient failed: ' + error); } utilities.log('[SOCKET_IO] redisDB redisClient', 'info'); redisDB.getClient(false, function(error, redisClient) { if (error) { utilities.log('socket io initialize get redisClient failed: ' + error); } var redis = redisDB.getModule(); io.set('store', new redisStore({ redis: redis, redisPub: pubClient, redisSub: subClient, redisClient: redisClient }) ); }); }); }); /** * * @param {type} param1 * @param {type} param2 */ io.sockets.on('connection', function(socket) { // use the socket id as user id var userId = socket.id; utilities.log('[SOCKET_IO] server opened new websocket connection for client with id: ' + userId, 'info'); socket.on('loginRequest', function() { utilities.log('[SOCKET_IO] loginRequest', 'info'); var path = 'https://api.jamendo.com/v3.0/oauth/authorize'; var method = 'GET'; var parameters = {}; var callbackFunction = ''; jamendoApiModule.makeJamendoApiRequest(path, method, parameters, callbackFunction); response.error = false; response.userId = userId; socket.emit('loginResponse', response); }); /** * if client needs a refresh of the top playlists world data */ socket.on('requestTopPlaylists', function(data) { utilities.log('[SOCKET_IO] requestTopPlaylists', 'info'); // TODO: right now whole world coordinates get send alltogether, we // could improve this by sending only the coordinates of the world // that is visible by the client, this would decrease the response // size but increase the requests frequency topPlaylists.getTopPlaylists(function(error, topPlaylists) { if (error) { utilities.log(error); socket.emit('responseTopPlaylists', ''); } socket.emit('responseTopPlaylists', topPlaylists); }); }); /** * */ socket.on('joinJamendoWorldLobby', function(data) { utilities.log('[SOCKET_IO] user with id "' + userId + '" and username "' + data.username + '" has entered the lobby'); // save username to socket.io session storage socket.set('username', data.username); // join the lobby room socket.join('lobby'); }); /** * */ socket.on('joinRoom', function(data) { utilities.log('[SOCKET_IO] joinRoom, data.newRoomId: ' + data.newRoomId, 'info'); // join the room socket.join(data.newRoomId); // get access log db index from configuration var collectionName = applicationConfiguration.mongoDB.playlistAccessLog.collections; // inform the users in the room that new user has joined io.sockets.in(data.newRoomId).emit('userJoined', data.user); mongoDB.getCollection(null, null, null, collectionName, true, function(error, mongoDBCollection, mongoDBClient) { if (error) { utilities.log('[SOCKET_IO] joinRoom getCollection failed: ' + error); } else { var songsQueueQuery = { playlistId: data.newRoomId }; var songsQueueFields = {}; mongoDB.mongoDBSingleRead(mongoDBCollection, songsQueueQuery, songsQueueFields, function(error, songsQueue) { if (error) { utilities.log('[SOCKET_IO] joinRoom mongoDBRead: ' + error); } socket.emit('setSongsQueue', songsQueue); }); // add a hit in the access log var accessLogEntry = { username: socket.get('username'), playlistId: data.newRoomId, timestamp: new Date().getTime() } mongoDB.mongoDBWrite(mongoDBCollection, accessLogEntry, safeOption, function(error) { if (error) { utilities.log('[SOCKET_IO] joinRoom access log update failed: ' + error); } }); } }); }); socket.on('leaveRoom', function(data) { utilities.log('[SOCKET_IO] leaveRoom, data.previousRoomId: ' + data.previousRoomId, 'info'); // disconnect user from room and inform users of that room that // user has left if (typeof(data.previousRoomId) !== 'undefined') { socket.leave(data.previousRoomId); io.sockets.in(data.previousRoomId).emit('userLeft', data.user); } }); socket.on('getRoomUserCount', function(roomId) { utilities.log('[SOCKET_IO] getRoomUserCount, roomId: ' + roomId, 'info'); var clients = io.sockets.clients(roomId); io.sockets.in(roomId).emit('setRoomUserCount', clients.length); }); socket.on('recommendSong', function(data) { utilities.log('[SOCKET_IO] recommendSong', 'info'); }); socket.on('starPlaylist', function(data) { utilities.log('[SOCKET_IO] starPlaylist', 'info'); }); /** * */ socket.on('broadCastMessage', function(data) { utilities.log('[SOCKET_IO] broadCastMessage', 'info'); // https://github.com/LearnBoost/socket.io/wiki/Rooms io.sockets.in(data.roomId).emit('broadCastMessage', {message: data.message, author: data.author}); }); /** * */ socket.on('disconnect', function() { utilities.log('[SOCKET_IO] disconnect', 'info'); }); }); }; exports.sendToPlaylistsToClient = function(topPlaylistsObject) { utilities.log('[SOCKET_IO] sendToPlaylistsToClient', 'info'); // send world coordinates to user that requested them io.sockets.socket(userId).emit('topPlaylistsObject', topPlaylistsObject); };
import React, { Component } from 'react' import {connect} from 'react-redux' class Mine extends Component{ constructor(){ super() this.tosetting=this.tosetting.bind(this) } render(){ return <div id='mine'> <div> <p> <span className="iconfont icon-wxbgongju" onClick={this.tosetting}></span> <span>我的717商城</span> </p> <dl> <dt> <img src={require('../../static/img/nav4.jpg')} alt=""/> </dt> <dd> <p>{123}</p> <p>{456}</p> </dd> </dl> </div> </div> } tosetting(){ this.props.history.push('/setting') } } export default Mine
import ReactDOM from 'react-dom'; import React from 'react'; import Card from './Card.jsx'; const dom = ( <Card> <Card.Body> <Card.Title>Title</Card.Title> <Card.Text>Text</Card.Text> </Card.Body> </Card> ); ReactDOM.render( dom, document.getElementById('container'), );
const Archive = require('../models/Archive') const ErrorResponse = require('../util/errorResponse') const asyncHandler = require('../middleware/async') // @desc Get all archives // @route GET /api/archives // @access private exports.getArchives = asyncHandler (async(req, res, next) => { const archives = await Archive.find(); // res.status(200).json({data: archives}); res.status(200).json(archives); }); // @desc Get single archive // @route GET /api/archives/:id // @access private exports.getArchive =asyncHandler(async(req, res, next) => { const archive = await Archive.findById(req.params.id); if(!archive){ next(new ErrorResponse(`Archive not found with id ${req.params.id}`, 404)); } res.status(200).json(archive); }); // @desc Post newarchive // @route POST /api/archives/:id // @access private exports.createArchive = asyncHandler(async(req, res, next) => { const archive = await Archive.create(req.body); res.status(200).json({ data: archive }); }); // @desc Update single archive // @route PUT /api/archives/:id // @access private exports.updateArchive =asyncHandler(async(req, res, next) => { const archive = await Archive.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true }); if(!archive){ return next(new ErrorResponse(`Archive not found with id ${req.params.id}`, 404)); } res.status(200).json({ data: archive}); }); // @desc Delete single archive // @route DELETE /api/archives/:id // @access private exports.deleteArchive = asyncHandler(async(req, res, next) => { const archive = await Archive.findByIdAndDelete(req.params.id); if(!archive){ next(new ErrorResponse(`Archive not found with id ${req.params.id}`, 404)); } res.status(200).json({ data: []}); });
class UrlDateValidator { constructor() { } validate(value) { return { isValid: /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(value.trim()), message: 'Must consist of the following format: YYYY-MM-DD.' }; } } export default (new UrlDateValidator());
import React, { useState } from 'react'; import Modal from './Modal'; import ModalPortal from './ModalPortal'; const App = () => { const [clicks, setClicks] = useState(0); const handleClick = () => { setClicks(prev => prev + 1); } return ( <div onClick={handleClick}> <p>Number of clicks: {clicks}</p> <p> Open up the browser DevTools to observe that the button is not a child of the div with the onClick handler. </p> <ModalPortal> <Modal /> </ModalPortal> </div> ); } export default App;
export configureStore from './store/configureStore' export createReducer from './utils/createReducer' export i18n from './i18n' export App from './app'
import { connect } from "react-redux"; import withStyles from "@material-ui/core/styles/withStyles"; import ProductStocksComponent from "../../views/Products/Stock/stock"; import { postProductStockDetails, fetchProductStocks, } from "../../actions/actions_product_stock"; import { fetchProducts } from "../../actions/actions_product"; const ProductStocksStyle = { cardCategoryWhite: { "&,& a,& a:hover,& a:focus": { color: "white", margin: "0", fontSize: "14px", marginTop: "0", marginBottom: "0", }, "& a,& a:hover,& a:focus": { color: "#FFFFFF", }, }, cardTitleWhite: { color: "#FFFFFF", marginTop: "0px", minHeight: "auto", fontWeight: "300", fontFamily: "'Roboto', 'Helvetica', 'Arial', sans-serif", marginBottom: "3px", textDecoration: "none", "& small": { color: "#777", fontSize: "65%", fontWeight: "400", lineHeight: "1", }, }, }; const mapStateToProps = state => ({ productStock: state.productStock, }); const mapDispatchToProps = (dispatch) => { const dispatchObject = { postProductStockDetails: (productStockDetails) => { dispatch(postProductStockDetails(productStockDetails)); }, fetchProductStocks: () => { dispatch(fetchProductStocks()); }, fetchProducts: () => { dispatch(fetchProducts()); }, }; return dispatchObject; }; const ProductStocks = connect( mapStateToProps, mapDispatchToProps, )(ProductStocksComponent); export default withStyles(ProductStocksStyle)(ProductStocks);
import React, { Component } from 'react' import {Container, Row, Col} from 'react-bootstrap' import Member from './components/Member' import Filter from './components/Filter' import Calendar from './components/Calendar' import SearchBar from './components/SearchBar' import JanjiJanji from './components/JanjiJanji'; import './style.css' export default class Content extends Component { render() { return ( <Container> <Row> <SearchBar/> </Row> <Row> <Col md={12}> <JanjiJanji /> </Col> </Row> <br/><br/><br/> </Container> ) } }
import React from 'react'; import User from './User'; class SelectedUsers extends React.Component { mapUsers(users) { return users.map((user, index) => { return <User user={user} key={index} toggleUser={this.props.toggleUser.bind(this)} router={this.props.router}/> }); } componentDidMount() { console.log("ComponentDidMount SelectedUsers"); } componentWillMount() { console.log("ComponentWillMount SelectedUsers"); } componentWillUnmount() { console.log("componentWillUnmount SelectedUsers"); } componentWillReceiveProps() { console.log("ComponentWillReceiveProps SelectedUsers"); } render() { var selectedUsers = this.props.selectedUsers; if (!_.isEmpty(selectedUsers)) { return <div className="row" style={{backgroundColor: "azure", textAlign: "center"}}> <h2>Selected users for cropping</h2> <div className="col-sm-8"> {this.mapUsers(selectedUsers)} </div> <div className="col-sm-4"> <button type="button" className="btn btn-block btn-primary" style={{marginTop: "150px"}} onClick={this.props.toggleCropper.bind(this)}>Enable cropper</button> </div> </div> } else { return <div className="row"/> } } } ; SelectedUsers.propTypes = { router: React.PropTypes.func.isRequired, selectedUsers: React.PropTypes.array.isRequired, toggleUser: React.PropTypes.func.isRequired, toggleCropper: React.PropTypes.func.isRequired }; export default SelectedUsers;
const data = [ { album_name: "Baahubali", album_image: require("../assets/baahubali.jpg"), songs: [ { song_name: "Bale Bale Bale", artist_name: "SPB", song: "", song_id: 1 }, { song_name: "Orey Oru Ooril", artist_name: "SPB", song: "", song_id: 2 }, { song_name: "Kanna Nee Thoongadaa", artist_name: "SPB", song: "", song_id: 3 }, { song_name: "Vandhaai Ayya", artist_name: "SPB", song: "", song_id: 4 } ] } ]; export default data;
export const PRODUCT_LIST_REQUEST = "PRODUCT_LIST_REQUEST"; export const PRODUCT_LIST_SUCCESS = "PRODUCT_LIST_SUCCESS"; export const PRODUCT_LIST_FAIL = "PRODUCT_LIST_FAIL"; export const PRODUCT_PAGINATION_PAGE = "PRODUCT_PAGINATION_PAGE"; export const PRODUCT_PAGINATION_PAGES = "PRODUCT_PAGINATION_PAGES"; export const PRODUCT_PAGINATION_COUNT = "PRODUCT_PAGINATION_COUNT"; export const PRODUCT_FILTERS_RESPONSE = "PRODUCT_FILTERS_RESPONSE";
export default { state: { currentLocation: {}, //获取的当前位置 parkItems: [], //停车位数据 phone: '', //登录的电话号码 isphone: null, exclude: [], //需要清除缓存的组件 appId: 'wxe44228e45ce071dc', //微信公众服务号appID|测试 // appId:'wx42a91e33c4b3a97b', //微信公众服务号appID|正式 map: null, //高德地图 //当前系列 orderId: '', //当前订单号 estateName: '', //当前小区名 startTime: '', //停车开始时间 plateNo: '', // 车牌号 createTime: '', //订单|预约创建时间 createFmTime: '', //格式化后的订单|预约创建时间 endTime: '', // 最晚入场时间 address: '', //当前地址 orgX: '', //出发点的经度 orgY: '', //出发点的维度 desX: '', //目的地的经度 desY: '', //目的地的维度 lngcenter: '', // 定位坐标经度 latcenter: '', // 定位坐标纬度 AMap: null, // 地图 AMguide: null, // 驾车路径规划 } }
/* 443. String Compression Given an array of characters chars, compress it using the following algorithm: Begin with an empty string s. For each group of consecutive repeating characters in chars: If the group's length is 1, append the character to s. Otherwise, append the character followed by the group's length. Example 1: Input: chars = ["a","a","b","b","c","c","c"] Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3". Example 2: Input: chars = ["a"] Output: Return 1, and the first character of the input array should be: ["a"] Explanation: The only group is "a", which remains uncompressed since it's a single character. Example 3: Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"] Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"]. Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12". Example 4: Input: chars = ["a","a","a","b","b","a","a"] Output: Return 6, and the first 6 characters of the input array should be: ["a","3","b","2","a","2"]. Explanation: The groups are "aaa", "bb", and "aa". This compresses to "a3b2a2". Note that each group is independent even if two groups have the same character. */ chars = ["a", "a", "b", "b", "c", "c", "c"]; output = 6 function strCompress(chars) { let count = 1 //let str = "" for(let i = 0; i < chars.length; i++) { if(chars[i] == chars[i+1]) { count++; } else { chars[i] = count count = 1 } } console.log(chars) } strCompress(chars);
import React from "react"; import * as actions from '../../action/Issues'; class IssueRecordingForm extends React.Component{ constructor(props) { super(props); this.state = { title: '', description: '' }; this.formOnChange = this.formOnChange.bind(this); } formOnChange(event){ const {name,value} = event.target; this.setState({[name] : value}); } render() { return( <div> <label htmlFor={"title"} >Title</label> <input type={"text"} id={"title"} name={"title"} value={this.state.title} onChange={this.formOnChange}/> <br/> <label htmlFor={"description"}>Description</label> <input type={"text"} id={"description"} name={"description"} value={this.state.description} onChange={this.formOnChange}/> <br/> <button onClick={()=> actions.recordTask(this.state)}>Submit</button> </div> ); } } export default IssueRecordingForm;
const { spawn } = require('child_process'); const dtlpath = "server/"; const CSV_PATH = "bigdata/csv/"; const DTL_PATH = "bigdata/dtl/"; const BAT_NAME = "dtl_par.bat"; const CSV_NAME = "20190108"; let fs = require('fs'); const con = require('./connection'); /* const csv_arr = [ "20190110", "20190108", "20190104", "20190103" ]; */ const csvFiles = fs.readdirSync(CSV_PATH); const csvs = csvFiles.filter((file) => file.includes('.csv')) .map((f) => f.slice(0, -4)); //console.log(csvs); //const csv_arr = csvs.slice(-5); const csv_arr = csvs; console.log(csv_arr); let csv = require('fast-csv'); const csvPath = (csv_path, csv_name) => csv_path + csv_name + ".csv"; let sequence = Promise.resolve(); const allData =[]; // csv parsing chaining try { csv_arr.forEach(function(filename, i, arr){ sequence = sequence.then(function(){ return getDataFromCSV(filename); }) .then(function(alldt){ console.log(i + " : " + arr.length); console.log("Final success BD state = "+ con.state); if (i === arr.length - 1) { con.end(); } }); }); } catch(e) { console.log(e.message); } finally { ; // con.end(); we can perform in last forEach action } /* * * -------------------------------------------------------- */ const ROWS_ARRAY = [`dt`, `Q_39`, `T_41`, `T_42`, `P_19`, `P_18`, `P_36`, `T_10`, `T_6`, `T_7`, `T_4`, `W_38`]; function getDuplicateUpadateString(rec, rows){ const keyupdate = (acc, key, index, arr) => { const coma = index < arr.length -1 ? `,` : ``; return acc + ` ${key} = VALUES(${key})` + coma; } const noDate = rows; noDate.shift(); const ins = "INSERT INTO `hr3` (`dt`, `Q_39`, `T_41`, `T_42`, `P_19`, `P_18`, `P_36`, `T_10`, `T_6`, `T_7`, `T_4`, `W_38`) VALUES ? " const str = " ON DUPLICATE KEY UPDATE"; //ON DUPLICATE KEY UPDATE name = VALUES(name), rank = VALUES(rank) const dupStr = noDate.reduce(keyupdate, str); return ins + dupStr; } /* * -------------------------------------------------------- */ function putRecordsInMySQL(records){ return new Promise( function(resolve,reject){ function performQuery(){ const sql = getDuplicateUpadateString(records, ROWS_ARRAY ); let query = con.query(sql, [values], function (err, result, fields) { if (err) { console.log(err.message); //con.end(); reject(err); //throw err; } else { console.log("Success. BD state = "+ con.state); //con.end(); resolve(result); } }); } const values = records; if (con.state === 'disconnected'){ con.connect(function(err) { if (err){ console.log('BD connect error: ' + err.message); con.end(); //throw err; } else { performQuery(); console.log("RE-Connected! BD state = "+ con.state); } }); } else { try { performQuery(); } catch(e) { console.log("SQL insert problem" + e.message ); } finally { ; } }; }); } con.on('error', function(err) { console.log('BD error: ' + err.message); console.log(" err BD state = "+ con.state); }); con.connect(function(err) { if (err){ console.log('BD connect error: ' + err.message); console.log(" err BD state = "+ con.state); con.end(); //throw err; } else { console.log("Connected! BD state = "+ con.state); } }); /** * * -------------------------------------------------------- */ function prepareRecord(arr){ const dt = arr[0].replace(/[\/]/g , "-" ) + " " + arr[1].slice(0,-5) + "00:00"; const record = arr.slice(2); record.unshift(dt); return record; } /** * * -------------------------------------------------------- */ function getDataFromCSV(filename){ return new Promise(function(resolve, reject){ let fs = require('fs'); const dataarr =[]; fs.createReadStream(csvPath(CSV_PATH, filename)) .pipe(csv()) .on('data', function(data){ if (!isNaN(parseFloat(data[3]))){ const rec = prepareRecord(data); dataarr.push(rec); } else { console.log(csvPath(CSV_PATH, filename)); } }) .on('end', function(data){ console.log(dataarr.length); console.log('read finished'); putRecordsInMySQL(dataarr) .then(function(result){ resolve(dataarr); console.log('OK ' + csvPath(CSV_PATH, filename)); } ) .catch(function(error){ console.log(error.message); }); }); }); };
import React, {Component} from 'react' import SelectField from 'material-ui-selectfield' import DatePicker from 'material-ui/DatePicker' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' import * as filterActions from '../../Actions/FilterActions' import * as groupActions from '../../Actions/GroupActions' import * as repoActions from '../../Actions/RepoActions' import * as toolActions from '../../Actions/ToolActions' import * as tagActions from '../../Actions/TagActions' import * as findingActions from '../../Actions/FindingActions' import {Button} from 'react-bootstrap'; import {BootstrapTable} from 'react-bootstrap-table' import {underlineFocusStyle, floatingLabelFocusStyle, selectContainerStyle,} from '../CSSModules' import {connect} from 'react-redux' import {bindActionCreators} from 'redux' import {fetchDropdownOptions, selectionsRenderer,} from '../Common' import {toastr} from 'react-redux-toastr' import {severityBadgeStyle} from '../CSSModules' class FilterList extends Component { constructor(props) { super(props); this.state = { currentScanTypeId: null, currentOwnerTypeId: null, offset: 0, sizePerPage: 10, page: 1, totalSize: 0, orderBy: "name", sortDirection: 'ASC', searchTerm: null, selectedFindings: {}, falsePositiveBtn: true, notExploitableBtn: true, checkedAll: false } this.fetchData = this .fetchData .bind(this); this.handlePageChange = this .handlePageChange .bind(this); this.handleSizePerPageChange = this .handleSizePerPageChange .bind(this); this.viewFinding = this .viewFinding .bind(this) this.fetchFilterValues = this .fetchFilterValues .bind(this); this.handleSubmit = this .handleSubmit .bind(this); this.selectAll = this .selectAll .bind(this); this.selectOne = this .selectOne .bind(this); this.changeFindingStatus = this .changeFindingStatus .bind(this); } handleTagChange = (tags, name) => this.setState({tags}) handleStatusChange = (status, name) => this.setState({status}); handleRepoChange = (repos, name) => this.setState({repos}) handleVulChange = (vulnerabilities, name) => this.setState({vulnerabilities}); handleGroupChange = (groups, name) => this.setState({groups}) handleSeverityChange = (severity, name) => this.setState({severity}); handleAgingChange = (aging, name) => this.setState({aging}); handleToolChange = (tools, name) => this.setState({tools}); handleFromDateChange = (event, fromDate) => this.setState({fromDate}); handleToDateChange = (event, toDate) => this.setState({toDate}); static contextTypes = { router: React.PropTypes.object } renderTags(filterValues) { if (filterValues === null) return null; return ( <SelectField name='tags' hintText='' value={this.state.tags} floatingLabel='Tag' onChange={this.handleTagChange} fullWidth={true} maxHeight={200} floatingLabelFocusStyle={floatingLabelFocusStyle} underlineFocusStyle={underlineFocusStyle} multiple={true} checkPosition='right' style={selectContainerStyle} selectionsRenderer={(values, hintText) => selectionsRenderer(values, hintText)}> {fetchDropdownOptions(filterValues.tags)} </SelectField> ); } renderStatues() { var statues = [ { id: "Open", name: "Open" }, { id: "Closed", name: "Closed" }, { id: "Deferred", name: "Deferred" }, { id: "Fix in progress", name: "Fix in progress" }, ]; return ( <SelectField name='status' hintText='' value={this.state.status} floatingLabel='Status' onChange={this.handleStatusChange} fullWidth={true} maxHeight={200} floatingLabelFocusStyle={floatingLabelFocusStyle} underlineFocusStyle={underlineFocusStyle} checkPosition='right' style={selectContainerStyle} selectionsRenderer={(values, hintText) => selectionsRenderer(values, hintText)}> {fetchDropdownOptions(statues)} </SelectField> ); } renderRepos(filterValues) { if (filterValues === null) return null; return ( <SelectField name='repos' hintText='' value={this.state.repos} floatingLabel='Repo' onChange={this.handleRepoChange} fullWidth={true} maxHeight={200} floatingLabelFocusStyle={floatingLabelFocusStyle} underlineFocusStyle={underlineFocusStyle} multiple={true} checkPosition='right' style={selectContainerStyle} selectionsRenderer={(values, hintText) => selectionsRenderer(values, hintText)}> {fetchDropdownOptions(filterValues.repos)} </SelectField> ); } renderGroups(filterValues) { if (filterValues === null) return filterValues; return ( <SelectField name='groups' hintText='' value={this.state.groups} floatingLabel='Group' onChange={this.handleGroupChange} fullWidth={true} maxHeight={200} floatingLabelFocusStyle={floatingLabelFocusStyle} underlineFocusStyle={underlineFocusStyle} multiple={true} checkPosition='right' style={selectContainerStyle} selectionsRenderer={(values, hintText) => selectionsRenderer(values, hintText)}> {fetchDropdownOptions(filterValues.groups)} </SelectField> ); } renderSeverity() { var severities = [ { id: "Critical", name: "Critical" }, { id: "High", name: "High" }, { id: "Medium", name: "Medium" }, { id: "Low", name: "Low" }, { id: "Info", name: "Info" }, ]; return ( <SelectField name='severity' hintText='' value={this.state.severity} floatingLabel='Severity' onChange={this.handleSeverityChange} fullWidth={true} maxHeight={200} floatingLabelFocusStyle={floatingLabelFocusStyle} underlineFocusStyle={underlineFocusStyle} checkPosition='right' style={selectContainerStyle} selectionsRenderer={(values, hintText) => selectionsRenderer(values, hintText)}> {fetchDropdownOptions(severities)} </SelectField> ); } renderVulnerabilties(filterValues) { if (filterValues === null) return filterValues; var vulnerableTypes = []; filterValues .vulnerableTypes .map(function(type) { vulnerableTypes.push({id: type.name, name: type.name,}); }); return ( <SelectField name='vulnerabilities' hintText='' value={this.state.vulnerabilities} floatingLabel='Vulnerable Type' onChange={this.handleVulChange} fullWidth={true} maxHeight={200} floatingLabelFocusStyle={floatingLabelFocusStyle} underlineFocusStyle={underlineFocusStyle} multiple={true} checkPosition='right' style={selectContainerStyle} selectionsRenderer={(values, hintText) => selectionsRenderer(values, hintText)}> {fetchDropdownOptions(vulnerableTypes)} </SelectField> ); } renderAging() { var aging = [ { id: 7, name: '1 month ago', }, { id: 30, name: '1 month ago', }, { id: 90, name: '3 months ago', }, { id: 180, name: '6 months ago', }, { id: 365, name: '1 year ago', }, ]; return ( <SelectField name='aging' hintText='' value={this.state.aging} floatingLabel='Aging' onChange={this.handleAgingChange} fullWidth={true} maxHeight={200} floatingLabelFocusStyle={floatingLabelFocusStyle} underlineFocusStyle={underlineFocusStyle} checkPosition='right' style={selectContainerStyle} selectionsRenderer={(values, hintText) => selectionsRenderer(values, hintText)}> {fetchDropdownOptions(aging)} </SelectField> ); } renderTools(filterValues) { if (filterValues === null) return filterValues; var tools = []; filterValues .tools .map(function(tool) { tools.push({id: tool.name, name: tool.name,}); }); return ( <SelectField name='tools' hintText='' value={this.state.tools} floatingLabel='Tool' onChange={this.handleToolChange} fullWidth={true} maxHeight={200} floatingLabelFocusStyle={floatingLabelFocusStyle} underlineFocusStyle={underlineFocusStyle} multiple={true} checkPosition='right' style={selectContainerStyle} selectionsRenderer={(values, hintText) => selectionsRenderer(values, hintText)}> {fetchDropdownOptions(tools)} </SelectField> ); } selectCheckBoxRender = (cell, row) => { return (<input id={cell} type="checkbox" value={false} checked={this.state.selectedFindings[cell]} onChange={this.selectOne}/>); } selectAll() { var selectedFindings = {} var needToDisableBtns = true; if (!this.state.checkedAll) { for (var findingId in this.state.selectedFindings) { selectedFindings[findingId] = true; needToDisableBtns = false; } } else { for (var findingId in this.state.selectedFindings) { selectedFindings[findingId] = false; } } this.setState({ selectedFindings: selectedFindings, checkedAll: !this.state.checkedAll, notExploitableBtn: needToDisableBtns, falsePositiveBtn: needToDisableBtns, }); } selectOne(event) { var selectedFindings = this.state.selectedFindings; if (!this.state.selectedFindings[event.target.id]) { selectedFindings[event.target.id] = true; } else { selectedFindings[event.target.id] = false; } var selectedAtLeastOne = false; for (var findingId in this.state.selectedFindings) { if (selectedFindings[findingId]) { selectedAtLeastOne = true; break; } } this.setState({ selectedFindings: selectedFindings, notExploitableBtn: !selectedAtLeastOne, falsePositiveBtn: !selectedAtLeastOne }); } componentDidMount() { var {ownerType, scanType,} = this.props; if (this.props.severity) { var payload = { limit: 10, ownerTypeId: ownerType, orderBy: 'name', sortDirection: 'asc', severity: this.props.severity }; this .props .actions .fetchAllFilterResults(payload); this.setState({ severity: { label: this.props.severity, value: this.props.severity } }) } if (this.props.vulnerableType) { var payload = { limit: 10, ownerTypeId: ownerType, orderBy: 'name', sortDirection: 'asc', vulnerabilities: [this.props.vulnerableType] }; this .props .actions .fetchAllFilterResults(payload); this.setState({ vulnerabilities: [ { label: this.props.vulnerableType, value: this.props.vulnerableType } ] }) } this.fetchFilterValues(ownerType, scanType); } fetchFilterValues(ownerType, scanType) { this.setState({currentScanTypeId: scanType, currentOwnerTypeId: ownerType}) var payload = { limit: -1, ownerTypeId: ownerType, scanTypeId: scanType }; this .props .actions .fetchFilterValues(payload); } changeFindingStatus(event) { var status = event.target.name; var payload = { bulkUpdate: true } var ids = []; for (var findingId in this.state.selectedFindings) { if (this.state.selectedFindings[findingId]) ids.push(parseInt(findingId)); } if (status === 'falsePositive') { payload['isFalsePositive'] = true; } if (status === 'notExploitable') { payload['notExploitable'] = true; } payload['ids'] = ids; this .props .actions .updateFilterFinding(payload, 0); } handleSubmit(event) { event.preventDefault(); var payload = { limit: 10, ownerTypeId: this.state.currentOwnerTypeId, scanTypeId: this.state.currentScanTypeId, orderBy: 'name', sortDirection: 'asc' }; var payloadDetails = this.getPayload(payload); payload = payloadDetails[0]; var anyOneSelected = payloadDetails[1]; if (anyOneSelected) { this .props .actions .fetchAllFilterResults(payload); } else { toastr.error('Please selecte at least one criteria'); } } getPayload(payload) { var anyOneSelected = false; if (this.state.tags) { anyOneSelected = true; payload['tagIds'] = this .state .tags .map((tag) => tag.value); } if (this.state.repos) { anyOneSelected = true; payload['repoIds'] = this .state .repos .map((repo) => repo.value); } if (this.state.groups) { anyOneSelected = true; payload['groupIds'] = this .state .groups .map((group) => group.value); } if (this.state.tools) { anyOneSelected = true; payload['toolNames'] = this .state .tools .map((tool) => tool.value); } if (this.state.vulnerabilities) { anyOneSelected = true; payload['vulnerabilities'] = this .state .vulnerabilities .map((vulnerability) => vulnerability.value); } if (this.state.status) { anyOneSelected = true; payload['status'] = this.state.status.value; } if (this.state.severity) { anyOneSelected = true; payload['severity'] = this.state.severity.value; } if (this.state.aging) { anyOneSelected = true; payload['aging'] = this.state.aging.value; } if (this.state.fromDate) { anyOneSelected = true; payload['fromDate'] = this.state.fromDate; } if (this.state.toDate) { anyOneSelected = true; payload['toDate'] = this.state.toDate; } return [payload, anyOneSelected,] } renderFlasePositiveBtn(findingsUpdateAllowed) { if (findingsUpdateAllowed) { return ( <Button name="falsePositive" class='btn btn-danger' disabled={this.state.falsePositiveBtn} onClick={this.changeFindingStatus}> <i class="fa fa-check" aria-hidden="true"></i> &nbsp;Mark False Positive </Button> ); } } renderNotExploitableBtn(findingsUpdateAllowed) { if (findingsUpdateAllowed) { return ( <Button name="notExploitable" class='btn btn-danger' disabled={this.state.notExploitableBtn} onClick={this.changeFindingStatus}> <i class="fa fa-check" aria-hidden="true"></i> &nbsp;Mark Not Exploitable </Button> ); } } filterResults(filterResults, options, totalSize, findingsUpdateAllowed) { if (filterResults.length === 0) return ( <h4 class='text-center'> Filters not applied / No Results </h4> ); return ( <div class="row"> <div class="col-xs-3"> {this.renderFlasePositiveBtn(findingsUpdateAllowed)} </div> <div class="col-xs-3"> {this.renderNotExploitableBtn(findingsUpdateAllowed)} </div> <div class='col-xs-12'> <BootstrapTable height="auto" data={filterResults} options={options} fetchInfo={{ dataTotalSize: totalSize }} search remote pagination striped hover bordered={false}> <TableHeaderColumn dataField="id" dataFormat={this.selectCheckBoxRender}> <input type="checkbox" checked={this.state.checkedAll} onChange={this.selectAll}/> &nbsp;Select All </TableHeaderColumn> <TableHeaderColumn dataField="severity" dataSort dataFormat={this.severityDataFormat}>Severity</TableHeaderColumn> <TableHeaderColumn dataField="name" isKey dataSort>Bug Type</TableHeaderColumn> <TableHeaderColumn dataField="description" dataSort>Description</TableHeaderColumn> <TableHeaderColumn dataField="toolName" dataSort>Tool Name</TableHeaderColumn> <TableHeaderColumn dataField="id" dataFormat={this.viewFindingDataFormat}>View Finding</TableHeaderColumn> </BootstrapTable> </div> </div> ); } fetchData(page = this.state.page, sizePerPage = this.state.sizePerPage, offset = this.state.offset, searchTerm = this.state.searchTerm, orderBy = this.state.orderBy, sortDirection = this.state.sortDirection) { offset = (page - 1) * sizePerPage; var payload = { offset: offset, limit: sizePerPage, orderBy: orderBy, sortDirection: sortDirection, searchTerm: searchTerm, ownerTypeId: this.state.currentOwnerTypeId, scanTypeId: this.state.currentScanTypeId } var payloadDetails = this.getPayload(payload); payload = payloadDetails[0]; this .props .actions .fetchAllFilterResults(payload); this.setState({ totalSize: this.props.totalSize, offset: offset, sizePerPage: sizePerPage, page: page, searchTerm: searchTerm, orderBy: orderBy ? orderBy : "name", sortDirection: sortDirection, }) } handlePageChange(page, sizePerPage) { this.fetchData(page, sizePerPage); } handleSizePerPageChange(sizePerPage) { // When changing the size per page always navigating to the first page this.fetchData(1, sizePerPage); } handleSearchChange = (searchText, colInfos, multiColumnSearch) => { if (searchText.length >= 3 || searchText.length == 0) { this.fetchData(1, this.state.sizePerPage, 0, searchText, this.state.orderBy, this.state.sortDirection); } } handleSortChange = (sortName, sortOrder) => { this.fetchData(1, this.state.sizePerPage, 0, this.state.searchTerm, sortName, sortOrder); } viewFindingDataFormat = (cell, row) => { return ( <a class="btn btn-sm btn-primary btn-scan-page" aria-label="Delete" onClick={this .viewFinding .bind(this, event, row)}> View Finding </a> ); } viewFinding(event, row) { this .context .router .history .push("/finding_detail/" + row.scanId + "/" + row.id, {state: 'state'}); } severityDataFormat = (cell, row) => { return ( <span class={'badge ' + cell.toLowerCase() + '-severity'} style={severityBadgeStyle}> {cell} </span> ); } componentWillReceiveProps(nextProps) { if (this.props.ownerType != nextProps.ownerType || this.props.scanType != nextProps.scanType) { this.fetchFilterValues(nextProps.ownerType, nextProps.scanType) } if (nextProps.fetchedResults && nextProps.fetchedResults.length > 0) { var selectedFindings = {} nextProps .fetchedResults .map(function(finding, index) { selectedFindings[finding.id] = false; }); this.setState({selectedFindings: selectedFindings}) } if (nextProps.updateResponse) { this.fetchData(); toastr.success('Selected findings status updated successfully'); } } render() { const {filterValues} = this.props; const options = { onPageChange: this.handlePageChange, onSizePerPageList: this.handleSizePerPageChange, page: this.state.page, sizePerPage: this.state.sizePerPage, prePage: 'Prev', // Previous page button text nextPage: 'Next', // Next page button text firstPage: 'First', // First page button text lastPage: 'Last', // Last page button text,,,, onSearchChange: this.handleSearchChange, onSortChange: this.handleSortChange, }; const {fetchedResults} = this.props; const {totalSize} = this.props; const {findingsUpdateAllowed} = this.props; return ( <section class="content"> <div class="card"> <div class="card-body"> <MuiThemeProvider> <form> <div class="row"> <div class="col-xs-6"> {this.renderTags(filterValues)} </div> <div class="col-xs-6"> {this.renderStatues()} </div> </div> <div class="row"> <div class="col-xs-6"> {this.renderRepos(filterValues)} </div> <div class="col-xs-6"> {this.renderVulnerabilties(filterValues)} </div> </div> <div class="row"> <div class="col-xs-6"> {this.renderGroups(filterValues)} </div> <div class="col-xs-6"> {this.renderSeverity()} </div> </div> <div class="row"> <div class="col-xs-6"> {this.renderAging()} </div> <div class="col-xs-6"> {this.renderTools(filterValues)} </div> </div> <div class="row"> <div class="col-xs-6"> <DatePicker hintText="From Date" fullWidth={true} style={{ paddingTop: 25 }} underlineFocusStyle={underlineFocusStyle} floatingLabelFocusStyle={floatingLabelFocusStyle} value={this.state.fromDate} onChange={this.handleFromDateChange}/> </div> <div class="col-xs-6"> <DatePicker hintText="To Date" fullWidth={true} style={{ paddingTop: 25 }} value={this.state.toDate} underlineFocusStyle={underlineFocusStyle} floatingLabelFocusStyle={floatingLabelFocusStyle} onChange={this.handleToDateChange}/> </div> </div> <div class="row"> <div class="col-xs-6"> <button class="btn btn-primary form-page-btn" onClick={this.handleSubmit}> Apply Filters </button> </div> </div> </form> </MuiThemeProvider> </div> </div> <div class="card"> <h4 class="card-title">Filter Results</h4> <div class="card-body"> {this.filterResults(fetchedResults, options, totalSize, findingsUpdateAllowed)} </div> </div> </section> ) } } const mapDispatchToProps = (dispatch) => ({ actions: bindActionCreators(Object.assign({}, filterActions, groupActions, repoActions, toolActions, tagActions, findingActions), dispatch) }); const mapStateToProps = (state) => ({ filterValues: state.filters.filterValues, fetchedResults: state.filters.fetchedResults, totalSize: state.filters.totalSize, findingsUpdateAllowed: state.filters.findingsUpdateAllowed, updateResponse: state.filters.updateFilterFindings, }); export default connect(mapStateToProps, mapDispatchToProps)(FilterList);
{ let listaProduseFavorite = JSON.parse(localStorage.getItem('ListaProduseFavorite')); // ----------- Verificare existenta listei in local storage if (listaProduseFavorite != null) { listaProduseFavorite = JSON.parse(localStorage.getItem('ListaProduseFavorite')); } else { listaProduseFavorite = [0]; localStorage.setItem('ListaProduse', JSON.stringify(listaProduse)); } // ----------------------Schimbare clasa pentru "activarea" iconului const numeToogle = "icon-like-active"; const numeClasa = "icon-like"; let produseFavorite = document.querySelectorAll(`.${numeToogle}`); let toateProdusele = document.querySelectorAll(`.${numeClasa}`); let numarProduseFavorite = produseFavorite.length; localStorage.setItem('ListaProduseFavorite', JSON.stringify(listaProduseFavorite)); for (let i in toateProdusele) { toateProdusele[i].onclick = function(e) { e.stopPropagation(); toateProdusele[i].classList.toggle(`${numeToogle}`); produseFavorite = document.querySelectorAll(`.${numeToogle}`); numarProduseFavorite = produseFavorite.length; listaProduseFavorite = [numarProduseFavorite]; localStorage.setItem('ListaProduseFavorite', JSON.stringify(listaProduseFavorite)); // ----------------- Update lista produse cu noua clasa let clasaProdus = toateProdusele[i].className; let listaProduse = JSON.parse(localStorage.getItem('ListaProduse')); listaProduse[i].activ = `${clasaProdus}`; localStorage.setItem('ListaProduse', JSON.stringify(listaProduse)); } } }
const core = require('../core'); /** * Get's a summary of Events in a given term or all terms * @param {int} sectionid Section ID * @param {int} termid Term ID (Optional) */ module.exports.getEventsSummary = async (sectionid, termid = -1) => { const parts = []; const out = await core.performQuery(`/ext/events/summary/?action=get&sectionid=${sectionid}&termid=${termid}`, parts); return out; }; /** * Get's structure & parameters of a given Events * @param {int} sectionid Section ID * @param {int} eventid Event ID */ module.exports.getEventStructure = async (sectionid, eventid) => { const parts = []; const out = await core.performQuery(`/ext/events/event/?action=getStructureForEvent&sectionid=${sectionid}&eventid=${eventid}`, parts); return out; }; /** * Get's attendance of a given Event * @param {int} sectionid Section ID * @param {int} eventid Event ID * @param {int} termid Term ID */ module.exports.getEventAttendance = async (sectionid, eventid, termid = -1) => { const parts = []; const out = await core.performQuery(`/ext/events/event/?action=getAttendance&eventid=${eventid}&sectionid=${sectionid}&termid=${termid}`, parts); return out; }; /** * Get's attachments of a given Event * @param {int} sectionid Section ID * @param {int} eventid Event ID */ module.exports.getEventAttachments = async (sectionid, eventid) => { const parts = []; const out = await core.performQuery(`/ext/uploads/events/?action=listAttachments&sectionid=${sectionid}&eventid=${eventid}`, parts); return out; }; /** * Get's a list of items (equipment) for an event * @param {int} sectionid Section ID * @param {int} eventid Event ID */ module.exports.getEventEquipment = async (sectionid, eventid) => { const parts = []; const out = await core.performQuery(`/ext/quartermaster/eventbookings/?action=loadListsForEvent&sectionid=${sectionid}&eventid=${eventid}`, parts); return out; };
import React, { Component } from "react"; import { NavLink } from "react-router-dom"; import { Link } from "react-router-dom"; import Logo from "./../../Assets/img/logo-v5.png"; import ShopCart from "./../../Assets/img/shopping-bag.svg"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faUser } from "@fortawesome/free-solid-svg-icons"; import { faHome } from "@fortawesome/free-solid-svg-icons"; import AuthContext from "./../auth/AuthContext"; import BtnSignout from "./../Utils/BtnSignout"; // import { faHeart } from "@fortawesome/free-solid-svg-icons"; // import navBurger from "./../../js/NavBurger"; export default class NavBurger extends Component { static contextType = AuthContext; state = { active: false, }; menuClose = () => { window.close(); } toggleClassName = () => { this.setState({ active: !this.state.active }); }; render() { const classActive = this.state.active ? "active" : ""; const classNavActive = this.state.active ? "nav-active" : ""; return ( <div className="header-nav-burger"> <div className={`bar-burger ${classActive}`} onClick={this.toggleClassName} > <span></span> </div> <div className="burger-nav-top"> <NavLink exact to="/" onClick={() => this.menuClose()}> <div className="logo"> <img src={Logo} alt="logo mali tijara" /> {/* <figcaption>MALI TIJARA</figcaption> */} </div> </NavLink> <Link to="/basketShop"> <figure className="basket-burger"> <img src={ShopCart} alt="panier" style={{ width: "50px" }} /> </figure> </Link> </div> <nav className={`nav-burger-container ${classNavActive}`}> <ul className="list-nav-burger"> <li> <NavLink to="/"> <FontAwesomeIcon icon={faHome} size="2x" color="var(--color-white)" /> </NavLink> </li> <li> <NavLink to="/signin" className="nav-link"> <span className="icon-user"> <FontAwesomeIcon icon={faUser} style={{ margin: "0 10px 0" }} size="lg" /> </span> </NavLink> </li> <li> {this.context.isSignedIn && ( <> {"\u00A0"} <BtnSignout /> </> )} </li> <li> <NavLink to="/our-products" className="nav-link link-drop-down"> Nos produits </NavLink> </li> <li> <NavLink to="/our-products/soins-naturels" className="nav-link link-drop-down" > Produits de soins naturels </NavLink> </li> <li> <NavLink to="/our-products/miels" className="nav-link link-drop-down" > Mièls </NavLink> </li> <li> {" "} <NavLink to="/our-products/plantes-locales" className="nav-link link-drop-down" > Plantes locales </NavLink> </li> <li> {" "} <NavLink to="/our-products/huiles-vegetales" className="nav-link link-drop-down" > Huiles végétales </NavLink> </li> <li className="nav-link"> <NavLink to="/contact">Contact</NavLink> </li> <li> {" "} <NavLink to="/dashboard" className="nav-link"> Tableau de bord </NavLink> </li> </ul> </nav> </div> ); } }
+function () { let oWait = $('.wait'); let oPs = $('.process-stage'); let oT = $('.t'); let oDownload = $('.download'); oDownload.addEventListener('click', () => { oDownload.style.transform = 'scale(0)'; Promise.resolve() .then(() => { oWait.classList.add('wait-mor') return Sleep(10000); }) .then(() => { oPs.style.animationIterationCount = 1; oWait.style.animationIterationCount = 1; oWait.classList.add('hidden'); oT.classList.add('show'); }) }) }(); function rem() { document.documentElement.style.fontSize = (document.documentElement.clientWidth || document.documentElement.clientWidth) + 'px'; }; rem(); window.addEventListener('resize', rem); function $(v,d) { d = d || document; return d.querySelector(v); } function $$(v,d) { d = d || document; return d.querySelectorAll(v); } function Sleep(timeout) { return new Promise(function(resolve) { setTimeout(function () { resolve(); },timeout); }); }
/* eslint-disable */ import React, { useState, useContext } from 'react'; import { Navigate } from 'react-router-dom'; import { Container, Grid, makeStyles, Button } from '@material-ui/core'; import { v4 as uuidv4 } from 'uuid'; import Page from 'src/components/Page'; import axios from 'axios'; import TicketDetailsForm from './TicketDetailsForm'; const useStyles = makeStyles((theme) => ({ root: { backgroundColor: theme.palette.background.dark, minHeight: '100%', paddingBottom: theme.spacing(3), paddingTop: theme.spacing(3) } })); const SettingsView = () => { const classes = useStyles(); const token = localStorage.getItem('token'); const [ticketDetails, setTicketDetails] = useState({ user: '', newuser: '', ticket: '', board: '', sellingprice: '', tickets: [{ id: uuidv4(), ticketNumber: '', ticketQty: 1, ticketDiasbled: true }] }); const handleSubmit = async (values) => { let data = { ticketprice: values.ticket, ticketboard: values.board, sellingprice: values.sellingprice, ticketnumbers: [] }; if (values.newuser) { data['newuser'] = values.newuser; } else { data['user'] = values.user; } values.tickets.map((ticket) => { for (let i = 0; i < ticket.ticketQty; i++) { data.ticketnumbers.push(ticket.ticketNumber); } }); await axios .post(`${process.env.REACT_APP_API}/purchaseticket`, data, { headers: { 'Bearer-Token': token } }) .then((response) => { window.location.reload(); }) .catch((err) => { console.log(err.response); }); }; return ( <Page className={classes.root} title="Purchase Ticket"> {token ? ( <Container maxWidth={false}> <TicketDetailsForm value={ticketDetails} setValue={setTicketDetails} handleTicketFormSubmit={handleSubmit} /> </Container> ) : ( <Navigate to="/login" /> )} </Page> ); }; export default SettingsView;
export const common = { login: 'Log In', register: 'Sign Up', logout: 'Log Out', password: 'password', passwordRule1: 'Enter password', passwordRule2: 'Password length not less than 6', repassword: 'Confrim password', countryRule: 'Select country', emailRule1: 'Enter email', emailRule2: 'Email format error,enter again', repasswordRule1: 'Enter confirm password', repasswordRule2: 'Two passwords not same!', sendCode: 'Send', second: 'second', name: 'name', or: 'or', coin: 'Coin', amount: 'Amount', price: 'Price', operate: 'Operate', buy: 'Buy', sell: 'Sell', country: 'country', alipay: 'alipay', wechat: 'wechat', unionPay: 'unionPay', deposit: 'deposit', extract: 'extract', recharge: 'recharge', withdraw: 'withdraw', status: 'status', type: 'type', completed: 'completed', cancelled: 'cancelled', ibuy: 'i want buy', isell: 'i want sell', memberName: 'business', qrcode: 'qrcode', tips: 'Tips', agreeTips: 'Please click agree', success: 'success', status_1:'Reviewing', status_2:'Transfering', status_3:'Failure', status_4:'Success', commission: 'fees', range: 'range', remark: 'remark', remarkRule: 'Enter remark', add: 'add', securityVerification: 'safety verification', phone: 'Tel', phoneCode: 'Tel code', getCode: 'click to get', email: 'email', emailCode: 'email code', save: 'save', delete: 'delete', saveFail: 'Failed to save!', saveSuccess: 'Saved successfully', reset: 'reset', loginPwd: 'login password', modify: 'modify', oldLoginPw: 'old login password', newLoginPw: 'new login password', newPwConfirm: 'confirm new password', priceW: 'fund password', setting: 'settings', oldPriceW: 'old fund password', newPriceW: 'new fund password', codeRule: 'Enter confirmation code', phoneRule: 'Enter phone number', passwordRule: 'Please enter no less than 6 passwords', oldPasswordRule: 'Please enter the old password', newPasswordRule: 'Please enter no less than 6 new passwords', priceWRule1: 'Please enter the correct fund password', confirm: 'confirm', nodata: 'No data', expect: 'Look forward to expectation!', pleaseSelect: 'Please select', logintip: 'please log in first' }; export const header = { index: 'INDEX', otc: 'OTC', exchange: 'EXCHANGE', asset: 'ASSET', identbusiness: 'IDENTBUSINESS', ucenter: 'ACCOUNT', service: 'SERVICE' }; export const sectionPage = { ptaqTitle: 'Platform Security', ptaqContent: "The hash algorithm is used to encrypt the world's leading security authentication", ptslTitle: 'Platform Strength', ptslContent: "The world's largest bitcoin trading platform", newsTitle: 'News Center', bannerTitle: 'A Truly Global Exchange', bannerSubTitle: 'The trusted world-class operation designed specifically for knowledgeable crypto-investors', assetType: 'Asset Type', transactionPair:'Transaction Pair', latestPrice: 'Latest Price', proportion24h: 'Proportion Today', highestPrice24h: 'Highest Price', minimumPrice24h: 'Minimum Price', volume24h: '24H Volume', latestNotice: 'Latest Announcement', platformProject: 'Platform Project', hotActivity: 'Popular Activity', btc: 'BTC', eth: 'ETH', ltc: 'LTC', usdt: 'USDT', bch: 'BCH', etc: 'ETC', eos: 'EOS', qtum: 'QTUM', neo: 'NEO', more: 'MORE', subPlatformTitle: 'Multi currency transactions guarantee transaction security ', subHotActivityTitle: 'Delivery of platform currency, exemption fee, registered airdrop', sPlatformCoin: 'Platform Currency', mServiceCharge: 'Exemption Fee', registerAirdrop: 'Registered Airdrop', sCoinDesc: 'From now on, the new user registration will send 10 platform currency, each invite a friend can get 2 platform currency.', mChargeDesc: 'The transaction volume of old customers is more than 20000, and the handling fee is reduced by half.', airdropDesc: 'The transaction volume of old customers is more than 20000, and the handling fee is reduced by half.', lookMore: 'Look at more', page4Title: 'Multi terminal APP, inch, enjoy easy transaction', page4SubTitle: 'Welcome to use mobile phone client to concentrate on palm trading experience.', download: 'download', platformMsg: 'Platform Message', }; export const nav = { ptjy: 'Platform Trading', ptaq: 'Platform Security', ptsl: 'Platform Strength', xwzx: 'News Center' }; export const footer = { gsmc: 'Na Bo Mdt InfoTech Ltd', gsjj: 'Notice', gywm: 'About Us', jrwm: 'Join Us', yqlj: 'Links', help: 'Help', xsjc: 'Novice Course', xsrm: 'Getting Started', czzn: 'Recharge Guide', jyzn: 'Trade Guide', ptsm: 'Explain', fysm: 'Fees', fwtk: 'Service Policy', fltk: 'Legal Policy', about: 'about', aboutus: 'About Us', gyjc: 'About Jiu Cai', szzcjs: 'Asset Tntroduction', clause: 'Clause', userPrivacy: 'User Privacy', ysLaw: 'Privacy Law', lawExplain: 'Law Explain', APPDownload: 'APP Download', problem: 'Problem', contact: 'Contact', industryInfor: 'Industry Information', contactus: 'Contact Us', }; export const financeNav = { wdzc: 'my assets' }; export const login = { leftTip: 'No Account?To Regist', rightTip: 'Welcome', user: 'Tel/Email', captchaShow: 'Loading verification code', captchaHide: 'Please finish verification first', findPwd: 'Forget password??', userRule: 'Please input tel or email', success: 'success' }; export const register = { leftTip: 'Have a Account?To Log In', user: 'Username', code: 'code', agree: 'I have read and agree', userprotocol: 'User Agreement', phoneRegister: 'Tel registration', emailRegister: 'Email registration', userRule1: 'Enter username', userRule2: 'Username length not less than 3,not more than15', codeRule: 'Enter sms verification code', passwordRule: 'Enter login password', emailRule: 'Enter email verification code', phoneRule1: 'Enter tel', phoneRule2: 'Tel format error,enter again', resetPhonePassword: "Reset phone password", resetEmailPassword: "Reset email password", newPasswordRule: 'Enter new password', modaltitle: 'Please verification', validatecodeload: 'Loading verification code', validatemsg: 'Please finish verification first' }; export const otc = { buySellTrade: 'Trading transactions', myAd: 'My Ad', myOrder: 'My Order', adCenter: 'Advertising', identbusiness: 'Apply for certification', transactions: 'Volume', payMode: 'Action', price: 'Price/Coin', publishAd: 'Post An Ad', myAdAlert: '【Tip】:When the minimum amount of advertising purchases plus the fee is greater than the remaining number of advertisements, the ad is automatically taken off the shelf.', adId: 'no', advertiseType: 'type', onlinePurchase: 'Online buy', onlineSale: 'Online sale', orderLimit: 'limit', remainAmount: 'remain amount', createTime: 'Time', offShelf: 'dropoff', onShelf: 'shelf', delete: 'delete', unpaid: 'Unpaid', paid: 'Paided', appealed: 'Appealing', handleSearch: 'Enter the order number', orderSn: 'OrderNo', unit: 'Coin', tradeType: 'Type', tradeName: 'tradeName', money: 'Money', commission: 'Fee', emailAuthorized: 'Email certified', emailUnauthorized: 'Email unauthorized', phoneAuthorized: 'Telno certified', phoneUnauthorized: 'Telno unauthorized', idCardAuthorized: 'IDCard certified', idCardUnauthorized: 'IDCard unauthorized', tradeLimit: 'Transaction limit', Location: 'location', tradeDeadline: 'Transaction period', min: 'min', enterMoney: 'Please enter the money', enterAmount: 'Please enter the amount', tellRequest: 'Tell him your request~', remarkMessage: 'Remarks information', tradeNotice: 'Trading Information', tradeNotice1: 'After you initiate the transaction request, the digital currency is locked in the hosting and protected by the platform. If you are a seller, after you initiate a transaction request, you can top up and wait for the buyer to pay. Buyers pay within the payment deadline. After you receive the payment, you should release the digital currency that is under your custody.', tradeNotice2: 'Read before trading《Platform Network Terms of Service》 and FAQs, trading guides and other help documentation.', tradeNotice3: 'Beware of liar!Before the transaction, please check the rating received by the user and pay more attention to the newly created account.', tradeNotice4: 'Please note,Rounding and price fluctuations may affect the amount of digital currency that is eventually traded.The fixed amount you enter determines the final amount, and the digital currency amount will be calculated from the instant exchange rate at the same time that the request is issued.', tradeNotice5: 'Hosting services protect both buyers and sellers of online transactions.In the event of a dispute, we will evaluate all the information provided and release the hosted digital currency to its legal owner.', confirmBuy: 'Confirm buy', confirmSell: 'Confirm sell', createAd: 'Create an ad deal', createAdTip1: 'If you often trade, you can create your own trading ad.If you only trade occasionally, we recommend that you search directly', tradeAd: 'Trading Advertising', createAdTip2: 'Create a trading ad is Free of charge', createAdTip3: 'If you want to directly edit the created ads, please check', iWant: 'I want', currency: 'Coin', openFixedPrice: "Open fixed price", open: 'Open', close: 'Close', fixedTip: 'When enabled, your currency price will not fluctuate with the market and the price will not change.', premisePrice: 'Premium', premisePriceTip1: 'Please set your premium', fixedPrice: 'fixed price', fixedPriceTip: 'Please enter your exchange price', cankao: 'Market reference price', premisePriceTip2: 'Premium refers to what percentage is higher than the current market price', tradePrice: 'Exchange price', valuationFormula: 'Pricing formula', enterRequest: 'Please enter what you want', sAmount: 'num', timeLimitTip1: 'Please enter your trading deadline', timeLimitTip2: 'How much time the buyer can accept transactions, please enter an integer', addPayMode: '【Tip】Can be bound to personal center/Add payment method', minLimit: 'minimum transaction amount', minLimitTip: 'Please enter your minimum transaction amount', maxLimit: 'maximum transaction amount', maxLimitTip: 'Please enter your maximum transaction amount', remarkMessageTip: 'You can fill in your special requirements in the remarks information, such as: the buyer\'s requirements, online time and so on.', openAutoReply: 'Open autoreply', openAutoReplyTip: 'When enabled, when the user initiates a transaction to you through this ad, the system automatically sends the auto reply phrase you selected to the other party.', autoReply: 'AutoReply', autoReplyTip: 'After receiving the order, the information is automatically returned to the buyer, for example: payment method, collection account number, etc.', priceWTip: 'Please enter your funds password', submit: 'Submit', premisePriceValidate: 'The overflow value is 0-20 and cannot be 0', fixedPriceValidate: 'Please enter the correct fixed price', numberValidate: 'Please enter the correct number, and the maximum number of transactions does not exceed 100', timeLimitValidate: 'Please enter the correct trading deadline', payModeValidate: 'Please select transaction method', priceWValidate: 'Please enter funds password', language: 'Language:Chinese', registerTime: 'Registration time:', totalTransactions: 'Accumulated transactions:', tradeInformation: 'Trading Information', publishTime: 'Release time', seller: 'Seller', buyer: 'Buyer', tradeMoney: 'Exchange amount', operationTips: 'Operate tip', operationTipBuy1_1: 'Please complete the payment in accordance with the account given by the other party within the time limit and click on this page.“', paymentCompleted: 'payment completed', operationTipBuy1_2: 'Please note in the comments when you transfer the good payment reference number.', operationTipBuy2: 'After receiving the payment, the seller will confirm the payment on the website. The system will automatically send the digital assets you have purchased to your account. Please note that.', notice: 'Note', noticeTip: 'Please do not use other chat software to communicate with each other, and do not accept any documents, email attachments, etc. sent to you by the direction. All communication links are completed in the chat window on this page', operationTipSell1_1: 'The digital assets that you have sold have been submitted to the platform for hosting and freezing. ou have confirmed your payment, click“', confirmRelease: 'Confirm release', operationTipSell1_2: 'Pay digital assets!', operationTipSell2: 'Please do not believe any reason for urging the currency to be released, confirm the receipt of the money and release the digital assets to avoid loss!', operationTipSell3: 'After receiving the account short message, please be sure to log in to online banking or mobile banking to confirm whether the payment is accounted for, to avoid the false release of digital assets due to receiving fraudulent messages!', orderStatus: 'Order status', cancelTrade: 'cancel the deal', orderAppeal: 'Order appeal', order: 'Order', and: 'and', sTrade: 'exchange', tradeAmount: 'Trading price', noBankCardTip: 'The user has not added the bank card number yet', noAlipayTip: 'The user has not added the Alipay account for the time being', noWechatTip: 'The user has not added the WeChat account yet', confirmPaidTip: 'Are you sure you have paid?', confirmCancelTip1: 'Payments are not refundable! Are you sure to cancel your order?', confirmCancelTip2: '【Repeat】:Payments are not refundable!Are you sure to cancel your order?', complaintType: 'Complaint type', paidMonenyNoReceived: 'Paid, not received', paidCoinNoReceived: 'Already paid, not received', complaintNote: 'Tip', iWantComplain: 'I want to complain', whetherConfirmRelease: 'Please enter the funds password and click confirm to make the loan', waitPaid: 'waiting for payment', waitRelease: 'Waiting for release', appealing: 'Appealing', orderStatus1: 'The buyer did not pay and waited for the buyer to pay!', orderStatus2: 'The buyer has paid and waits for the seller to release!', orderStatus3: 'Order completed transaction!', orderStatus4: 'Order is being appealed!', orderStatus0: 'Order cancelled!', loadMore: 'Load more', warning: 'Anti-fraud alerts: In the recent past, fraudsters have repeatedly used bank transfer remittance information and fake remittance credentials for fraud, so please be sure to check your own payment account number. Ensure the safety of remittance funds and avoid the risk of bank cards being frozen!', sendTips: 'Please enter chat content Enter key to send', sendTipsRule: 'Message cannot be empty' }; export const exchange = { market: 'Market', rose: 'Rose', high: 'High', low: 'Low', vol: 'Vol', limited: 'limited price', marketed: 'market price', fees: 'fee rate', toTrade: 'Trade Now!', available: 'Available', buyPrice: 'Buy Price', sellPrice: 'Sell Price', buyAmount: 'Buy Amount', sellAmount: 'Sell Amount', turnover: 'turnover', marketBuyTips: 'Buy at the best price in the market', marketSellTips: 'Sell at the best price in the market', lastPrice: 'Lastest', currentOrder: 'Delegate', historyOrder: 'History Delegate', realtimeTrade: 'Market Trades', buyAmountRule1: 'enter buy amount', buyAmountRule2: 'buy amount not more', turnoverRule1: 'enter trading volume', turnoverRule2: 'Trading volume not higher than', sellAmountRule1: 'enter sell amount', sellAmountRule2: 'sell amount not more', sellPriceRule: 'enter sell price', tradeSuccess: 'submit success!', confrimCancel: 'Confirm Undo?', collect: 'Marked', direction: 'Direction', time: 'Time', gear: 'Stall', total: 'Total', tradedAmount: 'Done', cancel: 'Canceled', entrust: 'Delegate Amount', marketPrice: 'Market Price', volume: 'Volume', open: 'Open price', dayRose: 'Day rose', trend: 'Trend', goTrade: 'Go to trade', do_favorite: 'Collected', cancel_favorite: 'Cancel Collected', realtime: 'realtime' }; export const finance = { finance: 'Finance center', financeIndex: 'Personal assets', financeRecord: 'Bill detail', coinType: 'Coin', balance: 'Balance', frozenBalance: 'Frozen Balance', depositAddress: 'Recharge Address', copy: 'Copy', ewm: 'QRCode', rechargeTip1: 'Do not recharge any non-currency assets to the above address, otherwise the assets will not be recovered.', rechargeTip2: 'After you recharge to the above address, you need to confirm the entire network node, after 2 network confirmations arrive, after 6 network confirmation can be extracted.', rechargeTip3: 'Minimum recharge amount: 0.01 currency, recharge less than the minimum amount will not be accounted.', rechargeTip4: 'Your top-up address will not change frequently and you can repeat the recharge; if there is any change, we will try to notify you via website announcement or email.', rechargeTip5: 'Please be sure to confirm the security of your computer and browser to prevent information from being tampered with or leaked.', rechargeRecord: 'Recording', copySuccess: 'Success!', copyFail: 'Failure!Please copy it manually', createTime: 'Arrival time', rechargeAddress: 'Recharge Address', rechargeAmount: 'Recharge Amount', extractAddressManage: 'Address management', extractAddress: 'Address', availableBalance: 'Available Balance', extractAmountTip1: 'Enter up to 6 decimal places and the minimum value is', extractAmountTip2: 'The maximum value is', accountAmount: 'The number of arrivals', withdrawTip1: 'The minimum number of coins is', withdrawTip2: 'currency.', withdrawTip3: 'In order to ensure the security of funds, when your account security policy changes, passwords are changed, and you use the new address to withdraw coins, we will conduct a manual audit of the coins. Please be patient and wait for the staff to call or email.', withdrawTip4: 'Please be sure to confirm the security of your computer and browser to prevent information from being tampered with or leaked.', withdrawRecord: 'Withdrawals record', coinTypeTip: 'Please select a currency', withdrawAdressTip: 'Please fill in the address', withdrawAmountTip1: 'Please fill in the correct number of coins, the minimum value is', withdrawAmountTip2: 'Coinage amount must not be less than processing fee', withdrawFeeTip1: 'The minimum fee is ', withdrawFeeTip2: 'The maximum value is', withdrawTime: 'Withdrawal time', withdrawAdress: 'Address', withdrawAmount: 'Amount', addressList: 'Address List', phoneRule: 'Incorrect phone number', codeRule: 'Incorrect verification code', emailRule: 'Incorrect email', startTime: 'Start-End', to: 'To', operateType: 'Action Type', search: 'Search', tradeTime: 'transaction Time', transaccount: 'Transfer', exchange: 'Exchange', otcbuy: 'OTC-Buy', otcsell: 'OTC-Sell', activityaward: 'Activity Award', promotionaward: 'Promotion Award', dividend: 'Dividend', vote: 'Vote', handrecharge: 'Artificial recharge' }; export const uc = { safeCenter: 'Security center', safeSetting: 'Security setting', accountSetting: 'Account setting', safeLevelLow: 'Security Level: Low', safeLevelHigh: 'Security Level: High', safeLevelMiddle: 'Security Level: Medium', realnameAuthentication: 'Verified', noRealname: 'To protect your account security, please complete real-name certification before you can trade operations!', bound: 'Binded', auditing: 'Review', bind: 'Bind', realName: 'Actual name', idCard: 'ID Card', imgPreview: 'Upload photo ID front', imgNext: 'Upload ID card reverse photo', imgLast: 'Upload handheld ID photos', imgPreviewRule: 'Please upload the photo ID card front', imgNextRule: 'Please upload the photo ID card reverse', imgLastRule: 'Please upload handheld ID photos', upload: 'Upload', bindEmail: 'Bind email', bindPhone: 'Bind phone', loginPwdTip: 'Use when logging in to the platform', priceWTip: 'When account funds change, you need to verify the funds password first', newLoginPwRule: 'Please enter no less than 6 new login passwords', newPwConfirmRule1: 'New login password is inconsistent', newPwConfirmRule2: 'New login password twice is inconsistent!', oldPriceWRule: 'Please enter no less than 6 passwords', newPriceWRule1: 'Inconsistent password', newPriceWRule2: 'Inconsistent twice password!', realNameRule: 'Please enter your real name', idCardRule: 'Please enter the ID number', bindPhoneRule: 'Please bind your phone first!', resetPriceW: 'Reset funds password', bindRealNameAccount: 'Bind real name account', AccountTip: 'Please set your payment method, please be sure to use my real name account', bankCardNo: 'Bank account', bankCardNoTip: 'Personal bank card information is not bound', bankName: 'Bank account', bankBranch: 'Bank branch', bankNo: 'Bank number', bankNoConfirm: 'Confirm card number', alipayNo: 'Alipay account', alipayNoTip: 'Personal Alipay account is not bound', wechatNo: 'Wechat account', wechatNoTip: 'Personal Wechat account is not bound', bankNoRule1: 'Please enter the correct bank card number', bankNoRule2: 'The bank card number entered twice is inconsistent!', realRule: 'Please perform real name authentication first', bankNameRule: 'Please select your bank', bankBranchRule: 'Please enter account branch', alipayNoRule: 'Please enter Alipay account', wechatNoRule: 'Please enter WeChat account', identity: { apply: 'Apply for certification business', seat: 'Exclusive booth', service: 'One-to-one service', lowfee: 'Lower fees', mailboxleft: 'Please send the following materials by mail to', mailboxcenter: 'email.com,', mailboxright: 'We will review your application as soon as possible.', phone: 'Phone', balance: 'Personal assets', cardphoto: 'Positive and negative ID photos', wx: 'Wechat', exchange: 'Whether to engage in off-exchange trading of digital assets', handphoto: 'User holding ID photo', qq: 'QQ', ploy: 'Whether there is a corresponding risk control strategy', agreement: 'I have read《Certified Merchant Agreement》', applyfor: 'Apply', sendcode: 'Send', confirm: 'Confirm', prepare: 'Prepare materials', review: 'Submit review', passed: 'Review passed', approve: 'Please agree to the certification merchant agreement', benefits: 'After successful certification, you can enjoy more benefits' }, safe:{ safelevel_low:'Security Level: Low', safelevel_high:'Security Level: High', safelevel_medium:'Security Level: Medium', nickname:'Nickname', bind: 'Bind', binded:'Binded', binding:'Bindind', binderr:'Failure', verified:'Verified', verifiedtip:'To protect your account security, please complete real-name certification before you can trade operations!', realname:'Actual name', idcard:'ID Card', upload:'Upload', upload_positive:'Upload photo ID front', upload_negative:'Upload ID card reverse photo', upload_hand:'Upload handheld ID photos', save:'Save', reset:'Reset', email:'Email', bindemail:'Bind email', loginpwd:'Login Password', emailcode:'Email verification code', clickget:'Click to get', second:'s', phone:'Telphone', bindphone:'Bind telphone', phonecode:'Telphone verification code', logintip:'Use when logging in to the platform', edit:'Modify', oldpwd:'Old login password', newpwd:'New login password', confirmnewpwd:'Confirm new password', fundpwd:'Fund password', fundtip:'When account funds change, you need to verify the funds password first', set:'Set', confirmpwd:'confirm password', oldfundpwd:'Old Fund password', newfundpwd:'New Fund password', newpwdmsg1:'Please enter no less than 6 new login passwords', newpwdmsg2:'New login password is inconsistent', pwdmsg1:'Please enter no less than 6 passwords', pwdmsg2:'Inconsistent password', emailtip:'Please enter email', codetip:'Please enter verification code', telnotip:'Please enter phone number', oldpwdtip:'Please enter the original password', realnametip:'Please enter your real name', idcardtip:'Please enter the ID number', bindphonetip:'Please bind your phone first!', resetfundpwd:'Reset funds password', upload_positivetip:'Please upload the photo ID card front', upload_negativetip:'Please upload the photo ID card reverse', upload_handtip:'Please upload handheld ID photos', save_success:'Success!', save_failure:'Failure!', imgtip:'Please upload your QRCode for receiver cash', }, imgtip: 'Please upload your payment code', }; export const cms = { noticecenter: 'Announcement Center', newshelp: 'New user helping', appdownload: 'Download App', faq: 'FAQ', notice: 'Announcement', servicecenter: 'Customer Center', about: 'About', joinus: 'Join us', aboutus: 'About us', exchangerule: 'Trading Rules', useprotocol: 'Use Agreement', feenote: 'Charge description', }; export const aboutus = { aboutus: 'About us', businessRage: 'Business Range', coreValues: 'Core Value', integrityRigour: 'Honest Rigorous', openInnovation: 'Open Innovative', cooperationEnterprise: 'Cooperative Progressive', ourAdvantages: 'Our Advantages', advantageBottomOne: 'World top security risk control system', advantageBottomTwo: 'Global localized professional operation team', advantageBottomThree: 'Global digital asset distribution and transaction service', advantageBottomFour: 'Professional block chain assets research estimation system', advantageItemOneOne: 'Building experience of Goldman Sachs’s top security risk control system', advantageItemOneTwo: 'Experience of digital assets risk control management for many years', advantageItemOneThree: 'Independent professional digital assets research estimation system', advantageItemOneFour: 'Ploughing digital assets service industry and providing authoritative neutral assets analysis', advantageItemOneFive: 'Professional distributed framework and anti-DDOS attack system', advantageItemTwoOne: 'Many global states and regions establish local transaction service centers', advantageItemTwoTwo: 'Global localized digital asset distribution and transaction service', advantageItemTwoThree: 'Global project expansion and operation management system', advantageItemTwoFour: 'Many kinds of legal currencies and digital assets point to point OTC transaction business', advantageItemThreeOne: '7*24 hours customer service digital assets platform', advantageItemThreeTwo: 'Global leading independent digital assets estimation system', advantageItemFourOne: 'Relying on accurate research of massive data', advantageItemFourTwo: 'Sticking objective, independent, rigorous and professional principle', advantageItemFourThree: 'With more than 100 professional researchers and relying on strong international platform, our research team is also good at overseas and cross-border research', modalOnePar: "Jiucai website is a global leading digital asset financial server. Jiucai funding team harbors prospect of promoting global new financial revolution", modalTwoPar: 'and takes “making finance more highly efficient, making fortune more free” as group’s mission, sticks to service conception of “user first”, strives for providing safe, professional, sincere and excellent service for global users.', modalThreePar: 'At present, Jiucai website has finished layout to states and regions, such as Singapore, America, Japan, Korea, Hong Kong and so forth.', weAreTitle: 'We are...', weAreDesc: 'Jiucai btc is affiliated in Taiwan Nabo Information Science and Technology Co., Ltd, it is one of the global leading digital asset transaction platforms, the platform faces to global and provide bitcoin, etheric workshop and litecoin, etheric classics and various digital asset transaction service, which is a safe, reliable digital assets transaction website. One-stop digital currency and block chain comprehensive platform launched by many large cross-border enterprise’s IT elites, digital currency sophisticated players, block chain technology elites and many internet continuous entrepreneurs. Sticking to user’s profit as core and taking openness, freedom and sharing as internet spirit to provide the most reliable and convenient digital asset service for global users.', businessDesc: 'Jiucai website’s business range covers global digital asset investment users, it has established independent transaction business or operation center in many states and regions, such as Singapore, America, Japan, Korea, Hong Kong and so forth.', coreValueOnePar: 'As a technological innovative enterprise, we focus on products development innovation of block chain front-edged technology field, currently, we have made prospective strategic layout in block chain technology field.', coreValueTwoPar: ' In the future we will further to configure various power of the same industry and absorb various helpful power of global block chain’s ecological system, promote industrial development business implementation in block chain field, strive for shaping an open, professional and highly efficient block chain exchange interaction platform and provide valuable', coreValueThreePar: 'and depth industrial resolution scheme for block chain market, promote development and expansion of Chinese block chain technology industry from multiple perspectives of technology, asset, resources and so forth, in order to occupy a position of the field.', adOnePar: 'Jiucai website is a global leading digital asset financial server. Jiucai website funding team has an extremely deep believe and sense of mission to block chain technology,', adTwoPar: 'Many years of industrial background and solid technological storage make us have an extreme advantage beyond the same industry in platform security and efficiency. Jiucai website takes “making finance more highly efficient, making fortune more free”,', adThreePar: 'Sticking to service conception of “user first” to strive for providing safe, professional, sincere and excellent service for global users.', }; export const law = { lawTitle: 'Legal declaration', firstArticle: 'First', secondArticle: 'Second', thirdArticle: 'Third', fourthArticle: 'Fourth', fifthArticle: 'Fifth', firstDesc: 'The purpose of this website is to provide professional international level trading platform and financial products to the global digital asset lovers and investors as far as possible without violating the relevant laws and regulations of the country. It is forbidden to use this website to engage in money laundering, smuggling, commercial bribery and so on. In case of such incidents, the station will freeze accounts and report to the authorities immediately.', secondDesc: 'When the competent authority shows the relevant investigation documents to require the station to cooperate with the designated user to investigate the designated user, or to seal, freeze or transfer the user account, the station will assist in providing the corresponding user data, or the corresponding operation according to the requirements of the authorized organ. Therefore, this site does not bear any responsibility for user privacy leakage, account inability to operate, and so on.', thirdDesc: 'As the user of this website violates the provisions of this statement, it has violated the relevant laws of the state. As a provider of the service, this station is obliged to improve the rules and services of the platform, but the station has no motives and facts to offend the relevant laws and regulations of the state, and does not bear any joint liability for the users behavior.', fourthDesc: 'Whoever enters the website in any way or directly or indirectly uses the service of this website shall be deemed to voluntarily accept the restriction of the statement of this website.', fifthDesc: 'This statement does not refer to the relevant laws and regulations of the state. When the statement conflicts with the relevant laws and regulations of the state, the relevant laws and regulations of the State shall prevail.', }; export const problem = { faq: 'Common Problem', problemOne: 'RMB recharge to buy money', problemTwo: 'Cash in RMB', problemThree: 'Novice must see', problemFour: 'Common problems of trading platform', problemFive: 'Rules of the currency exchange zone', }; export const joinus = { latestAnnouncement: 'Latest Announcement', industryInfor: 'Industry Information', contactUs: 'Contact Us', joinUs: 'Join Us', principle: 'The principle of long money is to use the director. You should give full play to your expertise, do what you like and do well. Our open recruitment does not necessarily have the right position for you, but if you are talented in the field that you are good at, please contact us and we should still be able to leave a position.', jobOne: 'Sale', jobDesc: 'Job Description', qualification: 'Qualification', jobTwo: 'Customer service', jobThree: 'Designer', jobApplication: 'Job Application', saleDescOne: 'To undertake the customer development and customer relationship maintenance in the corresponding industries of the company.', saleDescTwo: 'Complete the market and performance targets of the company and department.', saleDescThree: 'Assist the other departments of the company to carry out the implementation of the project.', saleDescFour: 'Maintain new and old customers and establish good relationship with customers.', saleQualificationOne: 'College degree or above, major in marketing management, IT finance, Internet related field is preferred; large industry customer sales or project management experience is preferred.', saleQualificationTwo: 'With strong interpersonal skills, good communication and language ability, strong pioneering spirit and good mental balance ability;', saleQualificationThree: 'With good professional ethics and integrity, open minded, honest, confident and good team spirit.', saleQualificationFour: 'The company arranges training staff to carry out professional training.', saleQualificationFive: 'Pay plus salary;', customerDescOne: 'Online customer service, processing users technical consultation and feedback to the product;', customerDescOne: 'Responsible for customer maintenance, guide customers to be familiar with the use and operation skills of the companys products, and answer common problems of customers.', customerDescTotal: 'The company provides you with a good career development platform training: from entering the company, there are specialized trainers from entering the company to provide you with professional training guidance, including sales skills training, product knowledge training, mental ability training, management ability training and so on.', customerQuaOne: 'College degree or above;', customerQuaTwo: 'The graduates of the boundary or the work experience of non customer service are all available.', customerQuaThree: 'Familiar with computer operation;', customerQuaFour: 'It can take the time of shift to work.', customerQuaFive: 'Be able to comply with the flexible work arrangement of the project group.', customerQuaSix: 'Because the work requires great patience and stability, good compression ability, basic communication skills and good customer service consciousness;', customerQuaSever: 'With strong self-learning and self management ability, can adapt to the continuous updating of knowledge;', desigerDescOne: 'According to the companys brand strategy planning, it is responsible for the graphic design and production of advertising, and the design, editing and beautification of logo, including the information and publicity of the enterprise promotion.', desigerDescTwo: 'According to the companys market strategy planning, it is responsible for the design of related plane publicity products in marketing system project promotion, such as marketing campaign publicity design, publicity design of large public relations activities, PPT production and optimization, etc.', desigerDescThree: 'Network promotion of graphic related creativity and design, such as website, WeChat, micro-blog and other new media picture design processing;', desigerDescFour: 'Publicity product packaging design and modification, optimization and so on;', desigerDescFive: 'Responsible for website related activities and online advertising design and production;', desigerDescSix: 'Optimize design to improve website usability, ease of use and applicability.', desigerQuaOne: 'Fine arts or design professional graduation, with good art foundation and aesthetic ability, proficient in web design, hope you love design, work experience is not limited, we pay more attention to your work;', desigerQuaTwo: 'Skillful operation design software ex: Photoshop、Flash、IIIustator、Dreamweaver、Div+css etc ', desigerQuaThree: 'Good at communicating with others, good team work spirit and sense of responsibility, able to withstand pressure;', desigerQuaFour: 'Please attach the work collection or work link to the resume.', jobApplicationTotal: 'If you want to apply for the above position, please send your resume and cover letter to hjkj@haihj.comPlease indicate the desired position in the email subject, and look forward to seeing you soon.', }; export const noviceCourse = { noviceCourse:'Novice Course', howBuyMoney:'How do you buy money?', currencyExchange:'Currency Exchange', iBuy:'I want to buy', confirmBuy:'CL-Buy', paymentCompleted:'Payment has been completed', clickEnter:'Click Enter', sure:'that will do', thatOk:"That's ok", courseStepOne:'1. Sign in https://www.jiucai.com find', courseStepTwoHand:'2. Enter the following page, select', courseStepTwofooter:'You can see a lot of BTC that are being sold. They have different prices and different payment methods. Find one that is in line with your own psychological price,choice', courseStepThree:'3. Choose a suitable price, click buy, will enter the following purchase page.', courseStepFourHand:'4. Enter the amount of money you want to buy, and then', courseStepFourfooter:'You can succeed in creating purchase orders', courseStepFiveHand:'5. Create order, play money in payment within the time limit provided by the seller to the Alipay / WeChat / bank account. When you transfer, try to remark the payment reference number shown below, so that the seller can easily see your payment and then click after payment.', courseStepSix:'6.The seller will confirm receipt after receiving the payment, and then the system will automatically call the digital assets to your account.', courseStepSever:'7. Congratulations, you have been successful in buying BTC. USDT purchase process is the same, in the same way, you can buy USDT.', reminder:'Warm tip: when contacting the seller, be sure to confirm that the seller is online, so that he can make a loan transaction. When payment is completed, he must click in time.', };
require('dotenv').config() const { google } = require('googleapis') const OAuth2 = google.auth.OAuth2 const oauth2Client = new OAuth2( process.env.CLIENT_ID, // ClientID process.env.CLIENT_SECRET, // Client Secret 'https://developers.google.com/oauthplayground' // Redirect URL ) oauth2Client.setCredentials({ refresh_token: process.env.REFRESH_TOKEN }) module.exports = { user: 'lukway.developer@gmail.com', clientId: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET, refreshToken: process.env.REFRESH_TOKEN, accessToken: oauth2Client.getAccessToken() }
const publicIp = require("public-ip"); const admin = require("firebase-admin"); const fetch = require("node-fetch"); const rcon = require("./rcon"); admin.initializeApp({ credential: admin.credential.applicationDefault(), }); let API_URL = "https://us-central1-csgo-stats-457a9.cloudfunctions.net/"; const args = process.argv.slice(2); if (args.includes("--local")) { API_URL = "http://localhost:5001/csgo-stats-457a9/us-central1/"; admin.firestore().settings({ ignoreUndefinedProperties: true, host: "localhost:8080", ssl: false, }); } else { admin.firestore().settings({ ignoreUndefinedProperties: true, }); } let db = admin.firestore(); const initServer = () => { const promises = []; //Update server status promises.push( publicIp.v4().then((ip) => { let docRef = db.collection("_config").doc("status"); docRef.set({ state: "ON", ip: ip, port: rcon.SERVER_PORT, }); }) ); //Update users status promises.push( db .collection("_users") .get() .then(function (querySnapshot) { querySnapshot.forEach(function (doc) { doc.ref.set({ online: false }, { merge: true }); }); }) ); return Promise.all(promises); }; const setUserOnline = (userId, value) => { let docRef = db.collection("_users").doc(userId); return docRef.set({ online: value }, { merge: true }); }; const sendMatch = (matchData) => { const url = new URL(API_URL + "addMatch"); return fetch(url, { method: "POST", body: JSON.stringify(matchData), }); }; const getCurrentConfig = () => { return db .collection("_config") .doc("config") .get() .then((doc) => doc.data()); }; module.exports = { sendMatch: sendMatch, initServer: initServer, setUserOnline: setUserOnline, getCurrentConfig: getCurrentConfig, };
import React from 'react'; import PokemonListItem from './PokemonListItem'; const PokemonList = ({ items, onClick }) => ( <div> {items.length && items.map(item => ( <PokemonListItem item={item} key={item.id} onClick={onClick} /> )) } </div> ); export default PokemonList;
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import LinearProgress from '@material-ui/core/LinearProgress'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; import ArrowBackIcon from '@material-ui/icons/ArrowBack'; import BookmarksIcon from '@material-ui/icons/Bookmarks'; import StarIcon from '@material-ui/icons/Star'; import StarBorderIcon from '@material-ui/icons/StarBorder'; import NextIcon from '@material-ui/icons/SkipNext'; import StopIcon from '@material-ui/icons/Stop'; import Drawer from '@material-ui/core/Drawer'; import { Link } from 'react-router-dom'; import List from '@material-ui/core/List'; import Divider from '@material-ui/core/Divider'; import ListItem from '@material-ui/core/ListItem'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import ListItemText from '@material-ui/core/ListItemText'; import File from '../../models/file'; import Layout from '../common/layout.jsx'; export const HIDE_STAR = 0; export const STAR = 1; export const STAR_BORDER = 2; const styles = (theme) => ({ list: { width: '200px' }, listItemLink: { textDecoration: 'none !important' }, stopButton: { marginLeft: theme.spacing.unit } }); class AppBase extends React.Component { constructor(props) { super(props); this.state = { drawerOpen: false }; } handleKey = (e) => { const { next_bookmark, isPlaying, } = this.props; switch(e.keyCode) { case 190: { // > if (isPlaying) { next_bookmark(); } break; } default: { // console.log(e.keyCode); } } } componentDidMount() { document.addEventListener('keydown', this.handleKey); } componentWillUnmount() { document.removeEventListener('keydown', this.handleKey); } renderHeaderLeft() { const { cd, current, next_bookmark, stop_play_bookmark, add_bookmark, remove_bookmark, isPlaying, classes, star } = this.props; const buttons = [ <IconButton key='back' color="inherit" disabled={current.id === ''} onClick={() => cd('directory', current.parentId)} > <ArrowBackIcon /> </IconButton>, <IconButton key='menu' color="inherit" onClick={this.toggleDrawer(true)} > <MenuIcon /> </IconButton> ]; switch (star) { case STAR: { buttons.push(( <IconButton key='bookmark' color="inherit" onClick={() => remove_bookmark(current.id)} > <StarIcon /> </IconButton> )); break; } case STAR_BORDER: { buttons.push(( <IconButton key='bookmark' color="inherit" onClick={() => add_bookmark(current.id)} > <StarBorderIcon /> </IconButton> )); break; } } if (isPlaying) { buttons.push( <IconButton key='next' color="inherit" onClick={next_bookmark} > <NextIcon /> </IconButton> ); buttons.push( <IconButton key='next' color="inherit" className={classes.stopButton} onClick={stop_play_bookmark} > <StopIcon /> </IconButton> ); } return buttons; } toggleDrawer = (open) => () => { this.setState({ drawerOpen: open }); } renderMenuLists () { const { classes, show_progress, buffered, current, max_pos } = this.props; return ( <div className={classes.list}> <List> <Link className={classes.listItemLink} to="/" > <ListItem button> <ListItemText primary="ホーム" /> </ListItem> </Link> </List> <List> <Link className={classes.listItemLink} to="/history" > <ListItem button> <ListItemText primary="履歴" /> </ListItem> </Link> </List> <List> <Link className={classes.listItemLink} to="/bookmark" > <ListItem button> <ListItemText primary="ブックマーク" /> </ListItem> </Link> </List> <Divider /> <List> <Link className={classes.listItemLink} to="/logout" > <ListItem button> <ListItemText className={classes.listItemText} primary="ログアウト" /> </ListItem> </Link> </List> </div> ); } render() { const { current, children, headerRight, current_pos, max_pos, show_appbar } = this.props; const title = max_pos > 0 && isFinite(current_pos) ? `${current.name} (${current_pos + 1} / ${max_pos})` : current.name; return ( <div> <Layout title={title} headerLeft={this.renderHeaderLeft()} headerRight={headerRight} show_appbar={show_appbar} > { children } </Layout> <Drawer open={this.state.drawerOpen} onClose={this.toggleDrawer(false)} > <div tabIndex={0} role="button" onClick={this.toggleDrawer(false)} onKeyDown={this.toggleDrawer(false)} > {this.renderMenuLists()} </div> </Drawer> </div> ); } } AppBase.propTypes = { classes: PropTypes.object.isRequired, match: PropTypes.object.isRequired, current: PropTypes.instanceOf(File), children: PropTypes.node, headerRight: PropTypes.node, isPlaying: PropTypes.bool.isRequired, current_pos: PropTypes.number, max_pos: PropTypes.number, show_appbar: PropTypes.bool, star: PropTypes.oneOf([ HIDE_STAR, STAR, STAR_BORDER ]).isRequired, cd: PropTypes.func.isRequired, next_bookmark: PropTypes.func.isRequired, stop_play_bookmark: PropTypes.func.isRequired, add_bookmark: PropTypes.func.isRequired, remove_bookmark: PropTypes.func.isRequired, }; AppBase.defaultProps = { current: 0, max_pos: 0, show_appbar: true }; export default withStyles(styles)(AppBase);
const { Artist } = require('../models'); exports.createArtist = (req, res) => { Artist.create(req.body).then(artist => res.status(201).json(artist)) }; exports.listArtists = (_, res) => { Artist.findAll({}).then(artists => res.status(200).json(artists)) }; exports.getArtistById = (req, res) => { const { id } = req.params; Artist.findByPk(id).then(artist => { if (!artist) { res.status(404).json({ error: 'The artist could not be found.' }); } else { res.status(200).json(artist); } }) .catch(err => console.log(err)) }; exports.updateArtist = (req, res) => { const { id } = req.params; Artist.update(req.body, { where: { id } }).then(([rowsUpdated]) => { if (!rowsUpdated) { res.status(404).json({ error: 'The artist could not be found.' }); } else { res.status(200).json(rowsUpdated); } }) .catch(err => console.log(err)) }; exports.removeArtist = (req, res) => { const { id } = req.params; Artist.destroy({ where: { id } }).then(rowsDeleted => { if (!rowsDeleted) { res.status(404).json({ error: 'The artist could not be found.' }); } else { res.status(204).json(rowsDeleted); } }) .catch(err => console.log(err)) };
import React, { Component } from "react" import PropTypes from "prop-types" import Helmet from "react-helmet" class PostTemplate extends Component { render() { const siteMetadata = this.props.data.site.siteMetadata const currentPost = this.props.data.wordpressPost return ( <div> <h1 dangerouslySetInnerHTML={{ __html: currentPost.title }} /> <div dangerouslySetInnerHTML={{ __html: currentPost.content }} /> <img src={currentPost.featured_media.source_url} /> </div> ) } } PostTemplate.propTypes = { data: PropTypes.object.isRequired, edges: PropTypes.array, } export default PostTemplate export const pageQuery = graphql` query currentPostQuery($id: String!) { wordpressPost(id: { eq: $id }) { featured_media { source_url } title content date(formatString: "MMMM DD, YYYY") } site { id siteMetadata { title subtitle } } } `
import React from 'react'; function NewTweet(props) { let tweet = { name: null, text: null } return ( <div> <div> username <input type="text" onChange={data => tweet.name = data.target.value} /> </div> <div> NewText <input type="text" onChange={data => tweet.text = data.target.value} /> </div> <button onClick={() => props.click(tweet)}> submit </button> </div> ) } export default NewTweet;
import { createSelector } from 'reselect'; import { initialState } from './reducer'; /** * Direct selector to the languageToggle state domain */ const selectLanguage = state => { // console.log(state, 'state123') return state.language; } /** * Select the language locale */ const makeSelectLocale = () => createSelector(selectLanguage, languageState => { // console.log(languageState, 'languageState') return languageState.locale }); export { selectLanguage, makeSelectLocale };
/*global LocalCache */ // should be initialized with: // a) lat + lng attributes // b) itemIds: possibly an array of item ids var Stores = Phoenix.Collections.Stores = Phoenix.PagedCollection.extend({ model: Phoenix.Models.Store, ttl: LocalCache.TTL.DAY, v1: true, initialize: function(models, attributes) { attributes = _.extend(this, _.defaults(attributes || {}, { lat: 0, lng: 0, radius: 50 })); Phoenix.Collection.prototype.initialize.call(this, models); }, url: function() { if (this.itemIds) { return '/m/j?service=StoreLocator&method=locateShippableByLatLong&p1=' + this.lat + '&p2=' + this.lng + '&p3=' + JSON.stringify(this.itemIds) + '&p4=' + this.radius + this.offsetParams(5); } else { return '/m/j?service=StoreLocator&method=locate&p1=' + this.lat + '&p2=' + this.lng + '&p3=' + this.radius + this.offsetParams(4); } }, attributes: function() { return { lat: this.lat, lng: this.lng, radius: this.radius }; }, hasMore: function() { return !this.noMorePages; }, parse: function(data) { var rtn = Phoenix.Collection.prototype.parse.call(this, data); // the data has not totalCount attribute if (rtn.length < this.pageSize) { this.noMorePages = true; } // Support this while we still have the one off paging logic in the checkout store locator // After that is killed off we can drop this var in favor of CachedPagedCollection this.totalCount = this.length + rtn.length; return rtn; }, getPhotoPickupTimes: function(ids, callback) { if (!callback) { callback = ids; ids = _.pluck(this.models, 'id'); } this.ajax({ secure: true, v1: true, url: '/m/j?service=Photo&method=getStorePickupTime', data: { p1: JSON.stringify(ids) }, success: callback }); } }); //get closest store, callback will only be called if a store is found (function() { function _getClosestStore(coords, callback, options) { var stores = new Phoenix.Collections.Stores(null, coords); stores.fetch(_.defaults({ success: function(stores) { callback(stores.at(0)); } }, options)); } // keep a cached value of the closest store when not querying location services var CACHED_CLOSEST_STORE = '_cachedClosestStore'; var cachedClosestStoreData = JSON.parse(LocalCache.get(CACHED_CLOSEST_STORE) || '{}'); if (cachedClosestStoreData.store) { // the model attributes were cached var attrs = cachedClosestStoreData.store; cachedClosestStoreData.store = new Phoenix.Models.Store(attrs); } function _cacheClosestStore(coords, store) { var data = { store: store, coords: coords }; LocalCache.store(CACHED_CLOSEST_STORE, JSON.stringify(data)); cachedClosestStoreData = data; } Stores.closest = function(callback, failback, options) { Phoenix.getLocation(function(coords) { var cachedCoords = cachedClosestStoreData.coords; if (!cachedCoords || !Phoenix.Util.isWithinRange(cachedCoords, coords)) { // location is out of date, get new store data _getClosestStore(coords, function(store) { _cacheClosestStore(coords, store); if (store) { callback(store); } else { failback && failback(); } }, options); } else { // the cached store location is still the same callback(cachedClosestStoreData.store); } }, failback, options && options.useCachedLocation); }; })();
import * as actions from '../constants'; const initialState = { loading: false, coords: null, weatherData: null, forecastData: null, hourlyData: null, error: null, searchListData: null, searchListLoading: false, activeSearchListElement: 0, }; const reducer = (state = initialState, action) => { switch (action.type) { case actions.FETCH_WEATHER_START: return { ...state, loading: true, error: null, }; case actions.FETCH_WEATHER_SUCCESS: return { ...state, loading: false, weatherData: action.payload, searchListData: null, }; case actions.FETCH_WEATHER_FAILURE: return { ...state, loading: false, error: { msg: action.payload, }, searchListData: null, }; case actions.FETCH_COORDS_SUCCESS: return { ...state, loading: false, coords: action.payload.coords, weatherData: action.payload.data, }; case actions.FETCH_FORECAST_SUCCESS: return { ...state, loading: false, forecastData: action.payload, searchListData: null, }; case actions.FETCH_FORECAST_FAILURE: return { ...state, loading: false, error: { msg: action.payload, }, searchListData: null, }; case actions.SET_ERROR: return { ...state, error: action.payload, }; case actions.FETCH_SEARCH_LIST_START: return { ...state, searchListLoading: true, }; case actions.FETCH_SEARCH_LIST_SUCCESS: return { ...state, searchListLoading: false, searchListData: action.payload, }; case actions.FETCH_SEARCH_LIST_FAILURE: return { ...state, searchListLoading: false, searchListData: null, }; case actions.FETCH_HOURLY_BY_NAME_SUCCESS: return { ...state, loading: false, error: null, hourlyData: action.payload, searchListData: null, }; case actions.FETCH_HOURLY_BY_NAME_FAILURE: return { ...state, loading: false, error: { msg: action.payload, }, searchListData: null, }; case actions.SET_ACTIVE_SEARCH_LIST_ELEMENT: return { ...state, activeSearchListElement: state.activeSearchListElement + action.payload, }; case actions.SET_ACTIVE_SEARCH_LIST_ELEMENT_BY_MOUSEOVER: return { ...state, activeSearchListElement: action.payload, }; default: { return { ...state, }; } } }; export default reducer;
export class Distortioncurve { amount:number; k:number; n_samples:number; curve: Float32Array; x:number; constructor(){ this.n_samples=44100; this.curve=new Float32Array(this.n_samples); } drawCurve(amount) { this.k=amount; for (var i=0; i<this.n_samples; i++) { this.x = i*2/this.n_samples-1; this.curve[i] = (3+this.k)*this.x/(3*(3+this.k*Math.abs(this.x))); } return this.curve; } }
import { useAuthState } from "react-firebase-hooks/auth"; import { auth, db } from "../firebase"; import moment from "moment"; function Message({ user, message }) { const [userLoggedIn] = useAuthState(auth); return ( <div> { user === userLoggedIn.email ? ( <p className=" text-right w-[fit-content] p-2 rounded-md m-2 min-w-[60px] pb-6 relative ml-auto bg-[#dcf8c6] "> {message.message} <span className="text-gray-500 p-2 text-[9px] absolute bottom-0 text-right right-0 "> {message.timestamp ? moment(message.timestamp).format("LT") : "..."} </span> </p> ) : ( <p className=" w-[fit-content] p-2 rounded-md m-2 min-w-[60px] pb-6 relative text-left bg-gray-100 "> {message.message} <span className="text-gray-500 p-2 text-[9px] absolute bottom-0 text-right right-0 "> {message.timestamp ? moment(message.timestamp).format("LT") : "..."} </span> </p> ) } </div> ) } export default Message
//singleVolume var bpapp = bpapp || {}; bpapp.singleVolume = Backbone.Model.extend({ defaults: { name: "default" }, urlRoot: "/volume", initialize: function(){ } });
//Constants export const SET_TOKEN_ACCESS = 'SET_TOKEN_ACCESS'; export const UPDATE_SEARCH_RESULTS = 'UPDATE_SEARCH_RESULTS'; export const UPDATE_PROFILE = 'UPDATE_PROFILE'; export const UPDATE_MEDIA = 'UPDATE_MEDIA'; export const APPEND_POSTS = 'APPEND_POSTS'; export const FETCHING_DATA = 'FETCHING_DATA'; //Places from where data can be fetched export const PROFILE = 'PROFILE'; export const SEARCH = 'SEARCH'; export const MEDIA = 'MEDIA';
import React, {useState, useEffect} from 'react' import { withRouter, Link } from 'react-router-dom' import { PopInformation } from '../PopInformation' import { getToken, getContract, getTermsAndConditions, getCustomerByMail, saveProposal, setRegistration, getRegistration, getProposal, getFinancialEducation, getAnalytics } from '../../../services/api.js' import cookie from 'react-cookies' import { BallBeat } from 'react-pure-loaders' import TagManager from 'react-gtm-module' import Axios from 'axios' const idProduct = 1 const BasicInfo = ({setCurrentStep, changeProposal, props}) => { const [data, setData] = useState({}) const [showPassword, setShowPassword] = useState(false) const [showRepeatPassword, setShowRepeatPassword] = useState(false) const [passError, setPassError] = useState(false) const [passRepeatError, setPassRepeatError] = useState(false) const [termsAccepted, setTermsAccepted] = useState(false) const [privacyAccepted, setPrivacyAccepted] = useState(false) const [financialAccepted, setFinancialAccepted] = useState(false) const [customer, setCustomer] = useState(null) const [customerInvalid, setCustomerInvalid] = useState(false) const [validEmail, setValidEmail] = useState(false) const [repeatPassword, setRepeatPassword] = useState(null) const [openContract, setOpenContract] = useState(false) const [openPrivacy, setOpenPrivacy] = useState(false) const [openFinancial, setOpenFinancial] = useState(false) const [contract, setContract] = useState(null) const [privacy, setPrivacy] = useState(null) const [financial, setFinancial] = useState(null) const [loadingForm, setLoadingForm] = useState(false) const [loading, setLoading] = useState(false) const [logged, setLogged] = useState(false) const [ip, setIp] = useState(null) // Error handling const [firstNameError, setFirstNameError] = useState(false) const [firstLastNameError, setFirstLastNameError] = useState(false) const [secondLastNameError, setSecondLastNameError] = useState(false) const [mobilePhoneError, setMobilePhoneError] = useState(false) const [homePhoneError, setHomePhoneError] = useState(false) const [serverError, setServerError] = useState(false) const [tokenError, setTokenError] = useState(false) useEffect(() => { if(firstNameError || firstLastNameError || secondLastNameError || mobilePhoneError || homePhoneError || serverError || tokenError){ window.scrollTo(0, 180) } }, [firstNameError, firstLastNameError, secondLastNameError, mobilePhoneError, homePhoneError, serverError, tokenError]) const handleData = e => { if(e.target.name === 'eMail') return setData({...data, [e.target.name]: e.target.value.toLowerCase()}) setData({...data, [e.target.name]: e.target.value}) } const checkPassword = pass => { if(logged) return true if(!data.password){ setPassError(true) return false } setPassError(false) if(!pass){ setPassRepeatError(true) return false } if(data.password !== pass){ setPassRepeatError(true) return false } setPassRepeatError(false) return true } // TAG MANAGER useEffect(() => { const tagManagerArgs = { dataLayer: { event: 'pageChange', page: { url: '/register', referrer: '/' } }, dataLayerName: 'dataLayer' } TagManager.dataLayer(tagManagerArgs) }, []) // TAG MANAGER END const submitData = async () => { if(data.eMail === 'demo@demo.com') return props.push('/registration/personal-details') if(!(termsAccepted && privacyAccepted && financialAccepted)) return if(!data.firstName) return setFirstNameError(true) else setFirstNameError(false) if(!data.firstLastName) return setFirstLastNameError(true) else setFirstLastNameError(false) if(!data.secondLastName) return setSecondLastNameError(true) else setSecondLastNameError(false) if(!data.mobilePhone) return setMobilePhoneError(true) else setMobilePhoneError(false) if(data.mobilePhone.length < 10) return setMobilePhoneError(true) else setMobilePhoneError(false) if (data.mobilePhone.match(/^[0-9]+$/) === null) return setMobilePhoneError(true) else setMobilePhoneError(false) if (data.mobilePhone.search(/[a-zA-Z]/) !== -1) return setMobilePhoneError(true) else setMobilePhoneError(false) if(data.mobilePhone === data.homePhone) return setHomePhoneError(true) else setHomePhoneError(false) if(!data.homePhone) return setHomePhoneError(true) else setHomePhoneError(false) if(data.homePhone.length < 10) return setHomePhoneError(true) else setHomePhoneError(false) if (data.homePhone.match(/^[0-9]+$/) === null) return setHomePhoneError(true) else setHomePhoneError(false) if (data.homePhone.search(/[a-zA-Z]/) !== -1) return setHomePhoneError(true) else setHomePhoneError(false) let repeatPass = await checkPassword(repeatPassword) if(!repeatPass) return if(!logged && (!data.password || data.password.length < 6)) return setPassError(true) else setPassError(false) setLoadingForm(true) let submittedData = { ...data, idProduct, secondName: '', termsAccepted, privacyAccepted, financialAccepted, utm: sessionStorage.getItem('utm') || '/', customerOrigin: document.URL, userAgent: navigator.userAgent, clientIP: sessionStorage.getItem('ip') || ip, additionalFields: [] } if(logged) submittedData.password = '' if(!logged) submittedData.idCustomer = 0 else submittedData.idCustomer = customer.customerId let validToken = cookie.load('token') if(!validToken){ let response = await getToken() if(!response.data) return props.push('/error') if(response.data) validToken = response.data.token } sessionStorage.setItem('data-step-registration', JSON.stringify(submittedData)) setRegistration(submittedData, validToken) .then(res => { if(res.status === 200){ setServerError(false) let proposal = JSON.parse(sessionStorage.getItem('proposal')) return getCustomerByMail(idProduct, data.eMail, validToken) .then(response => { sessionStorage.setItem('empty-customer', JSON.stringify(response.data)) if(response.status === 200){ return saveProposal(idProduct, response.data.customerId, proposal.monto, proposal.periodicidad, proposal.plazo, validToken) .then(res => { if(res.status === 200) { return props.push('/registration/personal-details') } }) .catch(err => setLoadingForm(false)) } }) .catch(err => { setServerError(false) setLoadingForm(false) }) } setServerError(true) setLoadingForm(false) }) .catch(err => setLoadingForm(false)) // Save slider } const checkUser = async () => { sessionStorage.removeItem('customer-register') sessionStorage.removeItem('empty-customer') sessionStorage.removeItem('data-step-registration') sessionStorage.removeItem('session-step') sessionStorage.removeItem('customer-logged') if(data.eMail === 'demo@demo.com') return setValidEmail(true) setLoading(true) let rex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if(!data.eMail || !rex.test(data.eMail.toLowerCase())) { setLoading(false) return setCustomerInvalid(true) } setCustomerInvalid(false) let validToken = cookie.load('token') if(!validToken){ let response = await getToken() if(!response.data) return props.push('/error') if(response.data) validToken = response.data.token } let response = await getCustomerByMail(idProduct, data.eMail, validToken) if(response.status === 200){ sessionStorage.setItem('customer-register', JSON.stringify(response.data)) return props.push('/login') } setValidEmail(true) setLoading(false) } const handlePassword = e => { if (e.target.value.length < 6) { return setPassError(true) } else if (e.target.value.length > 30) { return setPassError(true) } else if (e.target.value.search(/\d/) === -1) { return setPassError(true) } else if (e.target.value.search(/[a-zA-Z]/) === -1) { return setPassError(true) } else if (e.target.value.search(/[^a-zA-Z0-9!@#$%^&*()_+.,;:]/) !== -1) { return setPassError(true) } setPassError(false) } const loadEmptyCustomer = (idCustomer, eMail, validToken) => { getCustomerByMail(idProduct, eMail, validToken) .then(res => { setCustomer(res.data) setValidEmail(true) getRegistration(idProduct, idCustomer, eMail, validToken) .then(res => setData(res.data)) .catch(err => console.log(err)) getProposal(idProduct, idCustomer, validToken) .then(res => { if(res.status === 200){ let proposal = { monto: res.data.amount, periodicidad: res.data.opFrequency, plazo: res.data.term } changeProposal(proposal) let step = sessionStorage.getItem('session-step') // if(step === '0') return props.push('/registration') // if(step === '1') return props.push('/registration/personal-details') // if(step === '2') return props.push('/registration/employment-details') // if(step === '3') return props.push('/registration/nip-bureau') // if(step === '4') return props.push('/registration/identity') // if(step === '5') return props.push('/registration-complete') if(sessionStorage.getItem('session-step')) sessionStorage.setItem('session-step', 0) } }) .catch(err => console.log(err)) }) .catch(err => { console.log(err) }) } const loadCalculatorOnly = (idCustomer, step, token) => { getProposal(idProduct, idCustomer, token) .then(res => { if(res.status === 200){ let proposal = { monto: res.data.amount, periodicidad: res.data.opFrequency, plazo: res.data.term } changeProposal(proposal) if(step === 0) return props.push('/registration') if(step === 1) return props.push('/registration/personal-details') if(step === 2) return props.push('/registration/employment-details') if(step === 3) return props.push('/registration/nip-bureau') if(step === 4) return props.push('/registration/identity') if(step === 5) return props.push('/registration-complete') if(step === 6) return props.push('/registration/questionary') // setCurrentStep(step) } }) } const blockScroll = () => { document.getElementsByTagName('body')[0].style.overflowY = 'hidden' } const releaseScroll = () => { document.getElementsByTagName('body')[0].style.overflowY = 'auto' } useEffect(() => { const askToken = async () => { let validToken = cookie.load('token') if(!validToken){ let response = await getToken() if(!response.data) return if(response.data) validToken = response.data.token } let contRes = await getContract(idProduct, 0, validToken) let termRes = await getTermsAndConditions(idProduct, 0, validToken) let finRes = await getFinancialEducation(idProduct, 0, validToken) setContract({__html: contRes.data.htmlText}) setPrivacy({__html: termRes.data.htmlText}) setFinancial({__html: finRes.data.htmlText}) return } askToken() Axios.get('https://api.ipify.org') .then(res => setIp(res.data)) .catch(err => setIp('0.0.0.0')) }, []) useEffect(() => { const askLogged = async () => { let validToken = cookie.load('token') if(!validToken){ let response = await getToken() if(!response.data) return if(response.data) validToken = response.data.token } let currentStep = await sessionStorage.getItem('session-step') if(currentStep === '3') return props.push('/registration/nip-bureau') if(currentStep === '4') return props.push('/registration/identity') if(currentStep === '5') return props.push('/registration-complete') if(currentStep === '6') return props.push('/registration/questionary') // if(currentStep === '3' || currentStep === '4' || currentStep === '5') return setCurrentStep(parseInt(currentStep)) let directStep = await sessionStorage.getItem('customer-direct-step') if(directStep){ let emptyCustomer = await JSON.parse(sessionStorage.getItem('empty-customer')) if(emptyCustomer){ setLogged(true) return loadCalculatorOnly(emptyCustomer.customerId ? emptyCustomer.customerId : emptyCustomer.idCustomer, parseInt(directStep), validToken) } if(directStep === 0) return props.push('/registration') if(directStep === 1) return props.push('/registration/personal-details') if(directStep === 2) return props.push('/registration/employment-details') if(directStep === 3) return props.push('/registration/nip-bureau') if(directStep === 4) return props.push('/registration/identity') if(directStep === 5) return props.push('/registration-complete') if(directStep === 6) return props.push('/registration/questionary') // return setCurrentStep(parseInt(directStep)) } else{ let loggedUser = await JSON.parse(sessionStorage.getItem('loggedUser')) if(!loggedUser) { let emptyCustomer = await JSON.parse(sessionStorage.getItem('empty-customer')) if(emptyCustomer){ setLogged(true) return loadEmptyCustomer(emptyCustomer.customerId ? emptyCustomer.customerId : emptyCustomer.idCustomer, emptyCustomer.eMail, validToken) } return } setCustomerInvalid(false) setCustomer(loggedUser) setLogged(true) return loadEmptyCustomer(loggedUser.customerId, loggedUser.eMail, validToken) } } askLogged() }, []) let fillDemo = () => { sessionStorage.setItem('demoUser', JSON.stringify({ eMail: 'demo@demo.com', customerId: 12345, fullName: 'Demo', mobile: '5565829661' })) if(!data.eMail) return setData({eMail: 'demo@demo.com'}) setData({...data, firstName: 'Demo', firstLastName: 'FN', secondLastName: 'LN', homePhone: '5565829661', mobilePhone: '5544778899', password: 'parole1', }) setRepeatPassword('parole1') setTermsAccepted(true) setPrivacyAccepted(true) setFinancialAccepted(true) } return ( <> {!tokenError ? <div className='register-form-container'> {/* <div onClick={fillDemo} className="fill-demo">DEMO</div> */} <h1 style={{margin: '1rem 0 0 0', padding: 0, fontWeight: 'bold', fontSize: '3rem'}}>Registro</h1> <div style={{borderBottom: '5px solid black', width: '50px'}}></div> <div style={{marginBottom: '1rem'}}> <div className='register-questions'> <p>¿Ya eres cliente?</p><Link to='/login'>Por favor ingresa aquí</Link> </div> <small>Por favor llena todos los campos</small> </div> <div className={customerInvalid ? 'input-div input-error' : 'input-div'}> <p style={{fontWeight: 'bold'}}><strong>Correo electrónico</strong></p> <div className='validation-email-register'> <input style={{width: '250px', padding: '0.6rem', fontSize: '1rem'}} onChange={handleData} type='text' name='eMail' value={data.eMail}/> {validEmail || customer ? null : loading ? <div style={{backgroundColor: '#A3CD3A', padding: '0.5rem 1rem', margin: '0 1rem', color: 'white', fontWeight: '600', cursor: 'pointer', minWidth: '57px'}}><BallBeat loading color={'white'}/></div> : <small onClick={checkUser} style={{backgroundColor: '#A3CD3A', padding: '0.5rem 1rem', margin: '0 1rem', color: 'white', fontWeight: '600', cursor: 'pointer'}}>Verificar</small>} </div> {customerInvalid ? <><small style={{color: 'red', marginLeft: '1rem'}}>Correo electrónico incorrecto</small><br/></> : null} <small>Para mantenerte informado sobre el progreso de tu solicitud</small> </div> {validEmail || customer ? <> <div className={firstNameError ? 'input-div input-error' : 'input-div'}> <p style={{fontWeight: 'bold'}}><strong>Nombre</strong></p> <div> <input style={{width: '250px', padding: '0.6rem', fontSize: '1rem'}} onChange={handleData} type='text' name='firstName' maxlength="40" value={data.firstName}/> </div> </div> <div className={firstLastNameError ? 'input-div input-error' : 'input-div'}> <p style={{fontWeight: 'bold'}}><strong>Apellido Paterno</strong></p> <div> <input style={{width: '250px', padding: '0.6rem', fontSize: '1rem'}} onChange={handleData} type='text' name='firstLastName' maxlength="30" value={data.firstLastName}/> </div> </div> <div className={secondLastNameError ? 'input-div input-error' : 'input-div'}> <p style={{fontWeight: 'bold'}}><strong>Apellido Materno</strong></p> <div> <input style={{width: '250px', padding: '0.6rem', fontSize: '1rem'}} onChange={handleData} type='text' name='secondLastName' maxlength="30" value={data.secondLastName}/> </div> </div> <div className='register-subtitle'> <h5>Detalles de contacto</h5> <p>Esta información es confidencial y sólo será utilizada para corroborar tu identidad</p> </div> <div className={mobilePhoneError ? 'input-div input-error' : 'input-div'}> <p style={{fontWeight: 'bold'}}><strong>Celular</strong></p> <div> <input style={{width: '250px', padding: '0.6rem', fontSize: '1rem'}} onChange={handleData} type='text' name='mobilePhone' maxlength="10" value={data.mobilePhone}/> </div> <small>Ingresa tu teléfono a 10 dígitos incluyendo código de ciudad (ejemplo: 5511112222)</small> </div> <div className={homePhoneError ? 'input-div input-error' : 'input-div'}> <p style={{fontWeight: 'bold'}}><strong>Otro teléfono de contacto</strong></p> <div> <input style={{width: '250px', padding: '0.6rem', fontSize: '1rem'}} onChange={handleData} type='text' name='homePhone' maxlength="10" value={data.homePhone}/> </div> <small style={homePhoneError ? {color: 'red'} : null}>Requerimos de un número telefónico adicional donde podamos localizarte, este número debe ser diferente de tu teléfono celular y debe capturarse a 10 dígitos incluyendo código de ciudad</small> </div> {!logged ? <> <div className='register-subtitle'> <h5>Cuenta Online</h5> <p>Revisa tu estado de cuenta aquí</p> </div> <div className={passError ? 'input-div input-error' : 'input-div'}> <p style={{fontWeight: 'bold'}}><strong>Elegir una contraseña</strong></p> <div className={showPassword ? 'password-wrapper eye' : 'password-wrapper eye-hidden'}> <div className="input-wrapper"> <input onChange={e => {handleData(e); handlePassword(e)}} value={data.password} style={{width: '250px', padding: '0.6rem', fontSize: '1rem'}} type={showPassword ? 'text' : 'password'} className="form-control" name="password"/> </div> <p onClick={() => setShowPassword(!showPassword)} className="show-password">{showPassword ? 'Ocultar' : 'Mostrar'} contraseña</p> </div> {passError ? <div><small style={{color: 'red', fontSize: '0.9rem', marginTop: '1rem'}}>La contraseña es muy débil</small></div> : null} <small>La contraseña debe ser de al menos 6 caracteres y debe incluir al menos 1 número</small> </div> <div className={passError ? 'input-div input-error' : 'input-div'}> <p style={{fontWeight: 'bold'}}><strong>Repite tu contraseña</strong></p> <div className={showPassword ? 'password-wrapper eye' : 'password-wrapper eye-hidden'}> <div className="input-wrapper"> <input onChange={e => {setRepeatPassword(e.target.value); checkPassword(e.target.value)}} value={repeatPassword} style={{width: '250px', padding: '0.6rem', fontSize: '1rem'}} type={showRepeatPassword ? 'text' : 'password'} className="form-control" name="password"/> </div> <p onClick={() => setShowRepeatPassword(!showRepeatPassword)} className="show-password">{showRepeatPassword ? 'Ocultar' : 'Mostrar'} contraseña</p> </div> {passRepeatError ? <div><small style={{color: 'red', fontSize: '0.9rem', marginTop: '1rem'}}>Las contraseñas no coinciden</small></div> : null} </div> </> : null} <div className='register-subtitle'> <h5>Consentimiento legal</h5> <p>Por favor, abre, lee y acepta a Vivus.</p> </div> <div className='checkbox-div'> <div className='checkbox-top'> <label className="container"> <input onChange={() => {setOpenContract(true); blockScroll()}} checked={termsAccepted} type="checkbox"/> <span className="checkmark"></span> </label> <p style={{fontWeight: 'bold', margin: '0 2rem'}}><strong>Términos del contrato</strong></p> {termsAccepted ? <p style={{backgroundColor: 'lightgray', cursor: 'default'}} className='btn-register'>Aceptado</p> : <div onClick={contract ? () => {setOpenContract(true); blockScroll()} : null} className='btn-register'>{contract ? 'Por favor, lee y acepta' : <BallBeat loading color={'white'}/>}</div>} </div> </div> <div className='checkbox-div'> <div className='checkbox-top'> <label className="container"> <input onChange={() => {setOpenPrivacy(true); blockScroll()}} checked={privacyAccepted} type="checkbox"/> <span className="checkmark"></span> </label> <p style={{fontWeight: 'bold', margin: '0 2rem'}}><strong>Aviso de Privacidad</strong></p> {privacyAccepted ? <p style={{backgroundColor: 'lightgray', cursor: 'default'}} className='btn-register'>Aceptado</p> : <div onClick={privacy ? () => {setOpenPrivacy(true); blockScroll()} : null} className='btn-register'>{privacy ? 'Por favor, lee y acepta' : <BallBeat loading color={'white'}/>}</div>} </div> <small>Al proporcionar tu correo electrónico aceptas recibir por parte de Vivus noticias y comunicaciones promocionales. Podrás revocar dicho consentimiento en cualquier momento, para más detalles consulta nuestro Aviso de Privacidad</small> </div> <div className='checkbox-div'> <div className='checkbox-top'> <label className="container"> <input onChange={() => {setOpenFinancial(true); blockScroll()}} checked={financialAccepted} type="checkbox"/> <span className="checkmark"></span> </label> <p style={{fontWeight: 'bold', margin: '0 2rem'}}><strong>Educación Financiera</strong></p> {financialAccepted ? <p style={{backgroundColor: 'lightgray', cursor: 'default'}} className='btn-register'>Aceptado</p> : <div onClick={financial ? () => {setOpenFinancial(true); blockScroll()} : null} className='btn-register'>{financial ? 'Por favor, lee y acepta' : <BallBeat loading color={'white'}/>}</div>} </div> <small>Acepto recibir el servicio de Educación Financiera prestado por 4finance</small> </div> <div onClick={submitData} className={termsAccepted && privacyAccepted && financialAccepted ? 'btn-register' : 'btn-register-disabled'}>{loadingForm ? <BallBeat loading color={'white'}/> : 'Continuar'}</div> {serverError ? <div> <small>Ocurrió un error en el servidor, intenta nuevamente</small> </div> : null} </> : null} <PopInformation open={openContract} close={() => {setOpenContract(false); releaseScroll()}} data={contract} accept={setTermsAccepted}/> <PopInformation open={openPrivacy} close={() => {setOpenPrivacy(false); releaseScroll()}} data={privacy} accept={setPrivacyAccepted}/> <PopInformation open={openFinancial} close={() => {setOpenFinancial(false); releaseScroll()}} data={financial} accept={setFinancialAccepted}/> </div> : <div>Error en el servidor...</div>} </> ) } export default withRouter(BasicInfo)
console.log("TENNIS SCORE"); var btnPlayer1 = document.getElementById("btnplayer1"); var btnPlayer2 = document.getElementById("btnplayer2"); var gamescore1 = document.getElementById("gamescore1"); var gamescore2 = document.getElementById("gamescore2"); gamescore1.textContent = 0; gamescore2.textContent = 0; var currentScore1 = gamescore1.textContent; var currentScore2 = gamescore2.textContent; var currentSet = 1; var numberOfSetPlayer = [0, 0]; var players = [{ name: "Roger Federer" , name1: "Mr Federer" }, { name: "Rafael Nadal" , name1: "Mr Nadal" }]; function scoreUpdate1() { if (currentScore1 == "0") { currentScore1 = "15"; } else if (currentScore1 == "15") { currentScore1 = "30"; } else if (currentScore1 == "30") { currentScore1 = "40"; } else if (currentScore1 == "40" && currentScore2 == "40") { currentScore1 = "AD"; } else if (currentScore1 == "40" && currentScore2 == "AD") { currentScore1 = "40"; currentScore2 = "40"; } else if ((currentScore1 == "AD" && currentScore2 == "40") || (currentScore1 == "40" && currentScore2 != "40")) { currentScore1 = "0"; currentScore2 = "0"; document.getElementById("gametext").innerHTML = "GAME - " + players[0].name; console.log("GAME " + document.getElementById("player1").textContent); document.getElementById("gametext2").innerHTML = ""; updateCurrentSet(0); } gamescore1.textContent = currentScore1 gamescore2.textContent = currentScore2 console.log(currentScore1 + "/" + currentScore2); } function scoreUpdate2() { if (currentScore2 == "0") { currentScore2 = "15"; } else if (currentScore2 == "15") { currentScore2 = "30"; } else if (currentScore2 == "30") { currentScore2 = "40"; } else if (currentScore2 == "40" && currentScore1 == "40") { currentScore2 = "AD"; } else if (currentScore2 == "40" && currentScore1 == "AD") { currentScore1 = "40"; currentScore2 = "40"; } else if ((currentScore2 == "AD" && currentScore1 == "40") || (currentScore2 == "40" && currentScore1 != "40")) { currentScore2 = "0"; currentScore2 = "0"; document.getElementById("gametext").innerHTML = "GAME - " + players[1].name; console.log("GAME " + document.getElementById("player2").textContent); document.getElementById("gametext2").innerHTML = ""; updateCurrentSet(1); } gamescore1.textContent = currentScore1 gamescore2.textContent = currentScore2 console.log(currentScore1 + "/" + currentScore2); } function updateCurrentSet(gamePlayer) { var setPlayer1 = document.querySelectorAll("td.active")[gamePlayer]; setPlayer1.innerHTML = Number(setPlayer1.innerHTML) + 1; var setWon = checkSetWon(); if (setWon == 1) { numberOfSetPlayer[gamePlayer] = numberOfSetPlayer[gamePlayer] + 1; console.log("SETS - " + players[gamePlayer].name); document.getElementById("gametext2").innerHTML = "SETS - " + players[gamePlayer].name; if (numberOfSetPlayer[gamePlayer] < 3) { document.querySelector("td.active").classList.remove("active"); document.querySelector("td.active").classList.remove("active"); console.log("SET WON") currentSet = currentSet + 1; currentId = "#set" + currentSet; console.log(currentId); document.querySelectorAll(currentId)[0].classList.add("active"); document.querySelectorAll(currentId)[1].classList.add("active"); document.querySelectorAll(currentId)[0].innerHTML = 0; document.querySelectorAll(currentId)[1].innerHTML = 0; } else { console.log("MATCH - " + players[gamePlayer].name); document.getElementById("gametext3").innerHTML = "MATCH - " + players[gamePlayer].name; btnPlayer1.disabled = true; btnPlayer2.disabled = true; } } } function checkSetWon() { var setPlayer1 = Number(document.querySelectorAll("td.active")[0].innerHTML); var setPlayer2 = Number(document.querySelectorAll("td.active")[1].innerHTML); if (setPlayer1 == 7 || setPlayer2 == 7) { return 1; } else if (setPlayer1 == 6 && setPlayer2 < 5) { return 1; } else if (setPlayer1 < 5 && setPlayer2 == 6) { return 1; } else if (setPlayer1 >= 5 || setPlayer2 >= 5) { if (setPlayer1 == 6 && setPlayer2 == 6) { return 0; } else if ((setPlayer1 == 6 && setPlayer2 == 5) || (setPlayer1 == 5 && setPlayer2 == 6)) { return 2; } } else { return 2; } } btnPlayer1.addEventListener("click", scoreUpdate1); btnPlayer2.addEventListener("click", scoreUpdate2);
var mongoose = require("mongoose"); var Schema = mongoose.Schema, ObjectId = Schema.ObjectId; var taskModel = require("./tasks"); var AnswerSchema = new Schema({ answer: String, nameans: { type: ObjectId, ref: "tasks" } }); var Answer = mongoose.model('answer', AnswerSchema) module.exports = Answer;
/** * * App * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) */ import React from 'react' import PropTypes from 'prop-types' import { injectIntl } from 'react-intl' import { Helmet } from 'react-helmet' import { Layout } from 'antd' import utilsMsg from '../../utils/messages' class App extends React.PureComponent { componentDidMount () {} render () { const { formatMessage } = this.props.intl return ( <Layout> <Helmet titleTemplate={`%s -${formatMessage(utilsMsg.AppHelmetTitle)}`} defaultTitle={formatMessage(utilsMsg.AppHelmetTitle)} > <meta name="description" content={formatMessage(utilsMsg.AppHelmetTitle)} /> </Helmet> </Layout> ) } } App.propTypes = { intl: PropTypes.object } export default injectIntl(App)
import { useEffect, useState } from "react"; import { Link } from "react-router-dom"; import Book from "./Book"; import { getAll, update } from "./BooksAPI"; function Home() { const [books, setBooks] = useState([]); useEffect(() => { getAll() .then((books) => { setBooks(books); }) .catch(() => { alert("Something went wrong while fetching your books"); }); }, []); function updateBook(book, shelf) { update(book, shelf) .then((res) => { const slice = books.slice(); // update the updated book shelf in our local list on success slice.find(({ id }) => id === book.id).shelf = shelf; setBooks(slice); }) .catch(() => { alert("Something went wrong while updating the book"); }); } return ( <div className="list-books"> <div className="list-books-title"> <h1>MyReads</h1> </div> <div className="list-books-content"> <div> <div className="bookshelf"> <h2 className="bookshelf-title">Currently Reading</h2> <div className="bookshelf-books"> <ol className="books-grid"> {books .filter(({ shelf }) => shelf === "currentlyReading") .map((book) => { return ( <li key={book.id}> <Book book={book} onUpdateBook={updateBook} /> </li> ); })} </ol> </div> </div> <div className="bookshelf"> <h2 className="bookshelf-title">Want to Read</h2> <div className="bookshelf-books"> <ol className="books-grid"> {books .filter(({ shelf }) => shelf === "wantToRead") .map((book) => { return ( <li key={book.id}> <Book book={book} onUpdateBook={updateBook} /> </li> ); })} </ol> </div> </div> <div className="bookshelf"> <h2 className="bookshelf-title">Read</h2> <div className="bookshelf-books"> <ol className="books-grid"> {books .filter(({ shelf }) => shelf === "read") .map((book) => { return ( <li key={book.id}> <Book book={book} onUpdateBook={updateBook} /> </li> ); })} </ol> </div> </div> </div> </div> <div className="open-search"> <Link to="/search">Add a book</Link> </div> </div> ); } export default Home;
let Idade = 0 let Valor = 100 if (Idade<10) Valor += 80 if(Idade>=10 && Idade<=30) Valor += 50 if (Idade>30 && Idade<=60) Valor += 95 if (Idade>60) Valor += 130 console.log(Valor.toLocaleString('pt-BR', {style:'currency', currency:'BRL'}))
import React,{ useState } from "react"; import axios from "axios"; import MainCity from "./MainCity.js"; import NextDay from "./NextDay.js"; // import NextDay from "./NextDay.js"; export default function Search() { const [city, setCity] = useState(""); let [weatherInfo, setWeatherInfo] = useState({}); let apiKey = "6c4290abd5648abaf091c539d72478db"; let url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`; function showWeather(response) { let latitude = response.data.coord.lat; let longtitude = response.data.coord.lon; let forecastUrl = `https://api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longtitude}&units=metric&appid=${apiKey}`; axios.get(forecastUrl).then(function(forecastResponse) { setWeatherInfo({ coordinates: response.data.coord, temperature: response.data.main.temp, humidity: response.data.main.humidity, description: response.data.weather[0].description, wind: response.data.wind.speed, city: response.data.name, icon: response.data.weather[0].icon, forecast: forecastResponse.data.daily }); }) } function handleSubmit(event) { event.preventDefault(); axios.get(url).then(showWeather); } function showCity(event) { setCity(event.target.value); } return ( <div> <div className="row p-2 justify-content-center"> <div className="col col-md-4"> <form id="search-form" onSubmit={handleSubmit}> <input type="search" className="form-control" placeholder="Choose city..." onChange={showCity} /> </form> </div> </div> {weatherInfo.temperature ? <div><MainCity data={weatherInfo} /><NextDay data={weatherInfo.forecast} /></div> : <div className="row p-2 justify-content-center"><p>Choose city...</p></div>} </div> ); }
import React from 'react' import { Link } from 'react-router-dom' import { blogs } from '../utils' import Blog from './Blog' import Title from './Title' export default function Blogs() { return ( <div className='mt-5'> <div className='is-flex is-align-item-center is-justify-content-space-between is-flex-wrap-wrap px-6'> <Title title='Change Your Life' subtitle='Start Your Journey of Happiness and Health Today!' /> <Link to='/course' className='button is-primary has-text-white is-size-5 is-capitalized' > view all course </Link> </div> <div className='section'> <div className='columns'> {blogs.map((blog, index) => ( <Blog blog={blog} key={index} /> ))} </div> </div> </div> ) }
const express = require('express') const app = express() const port = 3000; const userRouter = require('./routes/user.route') app.set('view engine', 'pug') app.use(express.static('public')) app.use('/users',userRouter) app.get('/', (req,res) => { res.render('index') }) app.listen(port, () => console.log(`Server conecting to ${port}`))
const Discord = require('discord.js'); const fs = require("fs"); exports.run = (client, message, args) => { if(!message.member.hasPermission("MANAGE_MESSAGES")) return message.reply("> Nie możesz użyć tej komendy!"); let reason = args.slice(1).join(' '); let user = message.mentions.users.first(); if (message.mentions.users.size < 1) return message.reply('> Musisz wpisać nazwę aby nadać blacklist'); if (reason.length < 1) return message.reply('> Musisz wpisać powód...'); let dmsEmbed = new Discord.RichEmbed() .setTitle("Dodano do Blacklist!") .setColor("0xF1C40F") .setDescription(`Zostałeś dodany do blacklist permamętnie! \`${message.guild.name}\``) .addField("Dodał:", message.author.tag) .addField("Powód:", reason); user.send(dmsEmbed); message.delete(); let bean = new Discord.RichEmbed() .setTitle("Dodano Blacklist!") .setColor("0xF1C40F") .setDescription(`Zostałeś dodany do blacklist permamętnie! \`${message.guild.name}\``) .addField("Dodany", user, true) .addField("Dodał:", message.author.tag) .addField("Powód:", reason) message.channel.send(bean) message.member.addRole(role = "673572420904288318").catch(console.error); } exports.help = { name: 'blacklist' };
module.exports = (req, res, next) => { res.status(200).send({code: 1, message: "Bienvenido al Pokedex"}); };
/// <reference path="/Scripts/jquery-1.10.2-vsdoc.js"/> /// <reference path="/Scripts/General.js"/> /// <reference path="/Scripts/Conversiones.js"/> /// <reference path="/Scripts/Servicios.js"/> /// <reference path="/Scripts/InterfazGrafica.js"/> /// <reference path="/Scripts/DOM.js"/> function Inicializar() { GestionAutomatica = false; PausaGestion = true; Errores = []; Avisos = []; Asignaciones = {}; window.onerror = OnError; FastidiarPorCorreos = true; $(".EncSeccion").click(function () { $('#' + this.id.substr(1)).slideToggle(); OcultarAvisos(); }) PonerHora(); $('#Avisos').click(function () { if ($('#Avisos').css('left') == "-340px") { desp = '0px'; } else { desp = '-340px'; } $('#Avisos').animate({ left: desp }, 1000, function () { }); }); LlamarServicio(_Avisos_lst2, "Avisos_lst", { idAviso: $("#idAviso").val() }); setInterval("PonerHora()", 60000); TipoOperador = $("#TipoOperador").val(); $("input.fecha").datepicker($.datepicker.regional["es"]); LlamarServicio(_ActualizarGrafico, "ActualizarGrafico", { idOperador: idOpA() });//warning se cambió de idOp a idOpA LlamarServicio(_ActualizarGraficoSupervision, "ActualizarGraficoSupervision", { idOperador: idOpA() }); LlamarServicio(_ActualizarGraficoPorSemana, "ActualizarGraficoPorSemana", { idOperador: idOpA() }); LlamarServicio(_ActualizarIndicadores, "ActualizarIndicadores", { idOperador: idOpA() });//warning se cambió de idOp a idOpA LlamarServicio(_Operadores_Asignaciones_lst, "Operadores_Asignaciones_lst", { idOperador: idOpA() }); $("#pnlGestion").tabs({ show: { effect: "fade", duration: 100 }, hide: { effect: "fade", duration: 100 }, beforeActivate: function (event, ui) { if (ui.newPanel[0].id == "tabIndicadores") { LlamarServicio(_ActualizarGrafico, "ActualizarGrafico", { idOperador: idOp() }); LlamarServicio(_ActualizarIndicadores, "ActualizarIndicadores", { idOperador: idOp() }); } if (ui.newPanel[0].id == "tabGestion" && $('#idPersona').val() == "") { Mensaje({ mensaje: Recursos["msgNoPerSel"] }); //no ha seleccionado a una persona para gestionar return false; } if (ui.newPanel[0].id == "tabSupervision") { LlamarServicio(_ActualizarGraficoSupervision, "ActualizarGraficoSupervision", { idOperador: idOpA() }); LlamarServicio(_ActualizarGraficoPorSemana, "ActualizarGraficoPorSemana", { idOperador: idOpA() }); } } }); $("#tabsOtrasActividades").tabs({ show: { effect: "fade", duration: 100 }, hide: { effect: "fade", duration: 100 } }); LlamarServicio(_Status_lst, "Status_lst", { idOperador: idOpA() }); LlamarServicio(_OperadoresSupervisados_lst, "OperadoresSupervisadosConSupervisor_lst", { idOperador: idOpA() }); ActualizarSuplentes(); setInterval('Novedades();', 45000); window.onbeforeunload = function () { Salir(idOpL()); } setTimeout(InicioRetrasado, 5000); LimpiarAdjuntos(); } function OnError(message, location, line, colno, error) { $("#pnlErrores").show(); var Err = $("#nroErrores").text(); $("#nroErrores").text(Convert.ToInt32("0" + Err) + 1); Errores.push({ message: message, location: location, line: line, col: colno, callstack: error.stack }); return false; } function EnviarReporte() { LlamarServicio(_EnviarReporte, "EnviarReporte", { Errores: Errores, idOperador: idOpL() }); } function _EnviarReporte(msg) { $("#pnlErrores").hide(); Errores = []; } function InicioRetrasado() { RefrescarCorreos(); LlamarServicio(_Personas_Tocadas_lst, "Personas_Tocadas_lst", { idOperador: idOp() }); if ($("#idPersona").val() != "") { Persona_Mostrar($("#idPersona").val()); } else { // $("#pstIndicadores").click(); // $("#pstIndicadores").click(); } LlamarServicio(_Operador_Metas, "Operador_Metas", { idOperador: idOpA() }); if (!OperadorEs('SU', 'CO', 'GE', 'AD')) ActualizarCartera(); LlamarServicio(_ExclusionesMotivos_lst, "ExclusionesMotivos_lst", {}); } function _ExclusionesMotivos_lst(msg) { LlenarCombo({ Combo: "cboExclusionMotivo", Resultado: msg.d, CampoId: "id", CampoValor: "Nombre", TextoNull: "«Seleccione»", ValorNull: "" }); } function _Operadores_Asignaciones_lst(msg) { TiposCliente = msg.d.select("idTipoCliente").distinct(); Paises = msg.d.select("idPais").distinct(); } function _Operador_Metas(msg) { Tabla({ Contenedor: "pnlMetas", Resultado: msg.d, LimitarAltura: 200, Campos: [ { Titulo: "Name", Campo: "Nombre", Clase: "grdTexto", Ordenacion: false, Filtro: false }, { Titulo: "Facturas", Campo: "Facturas", Clase: "grdEntero", Ordenacion: false, Filtro: false, Resumen: 'TOTAL' }, { Titulo: "Collected", Campo: "FacturasCobradas", Clase: "grdEntero", Ordenacion: false, Filtro: false, Resumen: 'TOTAL' }, { Titulo: "Goal", Campo: "Meta", Post: "USD", Clase: "grdDecimal", Ordenacion: false, Filtro: false, Resumen: 'TOTAL' }, { Titulo: "Collected", Campo: "Real", Post: "USD", Clase: "grdDecimal", Ordenacion: false, Filtro: false, Resumen: 'TOTAL' }, { Titulo: "Effectiveness", Campo: "Porc", Clase: "grdDecimal", Post: "%", Ordenacion: false, Filtro: false } // { Titulo: "Adj", Campo: function(a){return a.TieneAdjuntos}, Campo2: "", Clase: "", Pre: "", Post: "", Ordenacion: true, Filtro: true, Combo: _combo_ } ], FuncSeleccionar: "AbrirMetas(«idMeta»,'«Fecha»'," + idOp() + ");" }); } function AbrirMetas(idMeta, Fecha, idOperador) { Emergente({ url: "/Emergentes/ctrlMetaDetalle.aspx?idMeta=" + idMeta + "&Fecha=" + Fecha + "&idOperador=" + idOperador }); } function ActualizarContrasena(CambiarAJuro) { setTimeout('Emergente({ url: "/Emergentes/ctrlOperador.aspx' + (CambiarAJuro ? "?Cambiar=1" : "") + '", width:300, height:300 })', 2000); } //----------------------------------------------------------------------------------------------------------Bandeja de Entrada function _Personas_Tocadas_lst(msg) { PersonasTocadas = msg.d; LlenarCombo({ Combo: "cboaPersona", Resultado: msg.d, CampoId: "idPersona", CampoValor: "Nombre", TextoNull: "<<Niguno>>" }); } function AsignarCorreosAPersona(CrearRegla) { var idPersona = $("#cboaPersona").val(); if (idPersona == "" || idPersona == null) { Mensaje({ mensaje: Recursos["msgMustSelectPerson"] }); return; } var CorreosSel = ObtenerSeleccionados("pnlCorreos").select("idCorreo"); if (CorreosSel.length == 0) { Mensaje({ mensaje: "Debe Seleccionar el/los correos Primero" }); return; } //Correos_Persona_ins(_Correos_Persona_ins, CorreosSel, idPersona, CrearRegla);RA LlamarServicio(_Correos_Persona_ins, "Correos_Persona_ins", { Correos: CorreosSel, idPersona: idPersona, CrearRegla: CrearRegla }); } function _Correos_Persona_ins(msg) { Mensaje({ mensaje: Recursos["msgMailAssigned"] }); RefrescarCorreos(); } function MarcarComoPersonal() { var Correos = ObtenerSeleccionados("pnlCorreos").select("idCorreo"); if (Correos.length == 0) { Mensaje({ mensaje: "Debe Seleccionar el/los correos Primero" }); return; } LlamarServicio(_Correos_MarcarPersonal_upd, "Correos_MarcarPersonal_upd", { Correos: Correos, TipoEspecial: 2 }); } function _Correos_MarcarPersonal_upd() { RefrescarCorreos(); } function idP() //Persona Actual { return $("#idPersona").val(); } function idOp() //Este es el Operador Supervisado { return $("#idOperador").val(); } function idOpA() // Este es el Operador Suplantado { return $("#idOperadorAct").val(); } function idOpL() //Este es el Operador Logueado { return $("#idOperadorLog").val(); } function AdministrarFiltros() { Emergente({ url: "/Emergentes/ctrlFiltros.aspx?idOperador=" + idOp() }); } //function ActualizarCorreos() //{ // Operador_Correos_nov(_Operador_Correos_nov, idOp(), $("#idCorreo").val()); //} function RefrescarCorreos() { //Operador_Correos_lst(_Operador_Correos_lst, idOp());RA LlamarServicio(_Operador_Correos_lst, "Operador_Correos_lst", { idOperador: idOp() }); //Operador_CorreosClasificadosNoLeidos_lst(_Operador_CorreosClasificadosNoLeidos_lst, idOp());RA LlamarServicio(_Operador_CorreosClasificadosNoLeidos_lst, "Operador_CorreosClasificadosNoLeidos_lst", { idOperador: idOp() }); } //function _Operador_Correos_nov(msg) //{ // if (msg.d === true) // { // RefrescarCorreos(); // //Mensaje({ mensaje: "Hay Correo Nuevo" }); // } //} function _Operador_Correos_lst(msg) { $("#idCorreo").val(msg.d.length == 0 ? 0 : msg.d[0].idCorreo); if (FastidiarPorCorreos) { if (msg.d.length > 10) Mensaje({ mensaje: "Tiene " + msg.d.length + " Correos sin Asignar, Recuerde que debe asignar estos correos." }); FastidiarPorCorreos = false; } $("#Cantidad").text(msg.d.length); Tabla({ Contenedor: "pnlCorreos", Resultado: msg.d, TodosSeleccionados: false, idSeleccion: "idCorreo", LimitarAltura: 200, Campos: [ { Titulo: "MailRead", Campo: function (a) { return "/Img/" + (a.Leido ? "CorreoLeido16.png" : "CorreoEntrante16.png"); }, Clase: "grdTexto", Ordenacion: false, Filtro: false, Imagen: true }, { Titulo: "MailFrom", Campo: "Remitente", Clase: "grdTexto", Ordenacion: true, Filtro: true }, { Titulo: "Subject", Campo: "Asunto", Clase: "grdTexto", Ordenacion: true, Filtro: true }, { Titulo: "Date", Campo: "Fecha", Clase: "grdFechaHora", Ordenacion: true, Filtro: true } // { Titulo: "Adj", Campo: function(a){return a.TieneAdjuntos}, Campo2: "", Clase: "", Pre: "", Post: "", Ordenacion: true, Filtro: true, Combo: _combo_ } ], FuncSeleccionar: "AbrirCorreo(«idCorreo»,'Correo',1);" }); } function _Operador_CorreosClasificadosNoLeidos_lst(msg) { $("#idCorreo").val(msg.d.length == 0 ? 0 : msg.d[0].idCorreo); if (FastidiarPorCorreos) { if (msg.d.length > 10) Mensaje({ mensaje: "Tiene " + msg.d.length + " Correos clasificados pero no leídos" }); FastidiarPorCorreos = false; } $("#Cantidad2").text(msg.d.length); Tabla({ Contenedor: "pnlCorreosClasificadosNoLeidos", Resultado: msg.d, TodosSeleccionados: false, idSeleccion: "idCorreo", LimitarAltura: 200, Campos: [ { Titulo: "MailRead", Campo: function (a) { return "\\Img\\" + (a.Leido ? "CorreoLeido16.png" : "CorreoEntrante16.png"); }, clase: "grdTexto", Ordenacion: false, Filtro: false, Imagen: true }, { Titulo: "MailFrom", Campo: "Remitente", Clase: "grdTexto", Ordenacion: true, Filtro: true }, { Titulo: "Subject", Campo: "Asunto", Clase: "grdTexto", Ordenacion: true, Filtro: true }, { Titulo: "Date", Campo: "Fecha", Clase: "grdFecha", Ordenacion: true, Filtro: true } // { Titulo: "Adj", Campo: function(a){return a.TieneAdjuntos}, Campo2: "", Clase: "", Pre: "", Post: "", Ordenacion: true, Filtro: true, Combo: _combo_ } ], FuncSeleccionar: "AbrirCorreo(«idCorreo»,'Correo',2);" //Filtros: FiltrosCNL, //OrdenadoPor: OrdenadoPorCNL }); } //----------------------------------------------------------------------------------------------------------Supervisión function Supervisar(idOperador) { LlamarServicio(Supervisar_Nombre, "Nombre", { idOperador: idOperador }); $("#idOperador").val(idOperador); $("#pnlCartera").html("Espere por favor..."); //Cartera_lst(_Cartera_lst, idOperador, idOpL() != idOp());RA ActualizarCartera(); //LlamarServicio(_Cartera_lst, "Cartera_lst", { idOperador: idOperador, Supervisado: idOpL() != idOp() }); //Personas_Tocadas_lst(_Personas_Tocadas_lst, idOperador);RA LlamarServicio(_Personas_Tocadas_lst, "Personas_Tocadas_lst", { idOperador: idOperador }); LlamarServicio(_Operador_Metas, "Operador_Metas", { idOperador: idOperador }); RefrescarCorreos(); $("#pstCartera").click(); $("#idPersona").val(""); $("#minipnlSupervision")[0].style.display = (idOpL() == idOperador) ? 'none' : ''; } function Supervisar_Nombre(msg) { $("#lblSupervisando").text(msg.d); } function Suplantar_Nombre(msg) { $("#lblSuplantando").text(msg.d); } function _ActualizarGraficoSupervision(msg) { var hora = new Date().getTime(); var Ruta = msg.d + "?hora=" + hora; $("#chrtGestionesSupervision").attr("src", Ruta); } function _ActualizarGraficoPorSemana(msg) { var hora = new Date().getTime(); var Ruta = msg.d + "?hora=" + hora; $("#chrtGestionesPorSemana").attr("src", Ruta); } //----------------------------------------------------------------------------------------------------------Gestion function btnEnviarNuevoCorreo_Click() { lstCuentas = window.parent.ObtenerSeleccionados("pnlPeCuentas").select("idCuenta"); Emergente({ url: "/Emergentes/ctrlEnvioCorreo.aspx?idPersona=" + $("#idPersona").val() + "&idOperador=" + idOpA(), modal: false }); } function _Status_lst(msg) { //Ver _Status_lst en ctrlReglas.aspx.js lstStatus = msg.d; } function SelecionGestion() { var Status = $("#cboGestStatus option:selected").html(); Mensaje({ mensaje: "Usted esta seguro de cerrar una gestion con el siguiente motivo: " + Status }); } function ActualizarComboStatus(idPais, idTipoCliente) { var Status = lstStatus.where(function (x) { return x.idPais == idPais && x.idTipoCliente == idTipoCliente }); $("#cboGestStatus").html(""); var papa = $("#cboGestStatus")[0]; var opcion = document.createElement("OPTION"); $(opcion).text("<<Seleccione>>"); $(opcion).val(0); papa.appendChild(opcion); var i; for (i = 0; i < Status.length; i++) { var opcion = document.createElement("OPTION"); $(opcion).text(Status[i].Nombre); $(opcion).val(Status[i].idStatus); switch (Status[i].Tipo) { case "Positivo": opcion.style.backgroundColor = Colores.Positivo; break; case "Neutral": opcion.style.backgroundColor = Colores.Neutral; break; case "Negativo": opcion.style.backgroundColor = Colores.Negativo; opcion.style.color = "#FFFFFF"; break; } papa.appendChild(opcion); } } function _Cuentas_Pagos_lst(msg) { var fecha = new Date(); var FechaT = Dos(fecha.getDate()) + "/" + Dos(fecha.getMonth() + 1) + "/" + fecha.getFullYear().toString(); $('#txtFechaNuevoPago')[0].value = FechaT; var FacturasPago = msg.d; $("#pnlPeFacturasPago").html(""); var pnl = $("#pnlPeFacturasPago")[0]; var tabla = CrearTabla("Tabla"); tabla.setAttribute("id", "tblPeFacturasPago"); pnl.appendChild(tabla); var fila = AgregarFila(tabla); AgregarHeader(fila, "Documento", "grdTexto", true, true).setAttribute("campo", "idCuenta"); AgregarHeader(fila, "Moneda", "grdTexto", true, true).setAttribute("campo", "Moneda"); AgregarHeader(fila, "Deuda USD", "grdDecimal", true, true); AgregarHeader(fila, "Tasa a USD", "grdTexto", true, true); AgregarHeader(fila, "Deuda Origen", "grdDecimal", false, false); AgregarHeader(fila, "Pago Origen", "grdDecimal", false, false).setAttribute("campo", "MontoPago"); AgregarHeader(fila, "Tasa a Local", "grdTexto", true, true); AgregarHeader(fila, "Deuda Local", "grdDecimal", true, true); var MontoPago = 0; var Monedas = Array(); for (i = 0; i < FacturasPago.length; i++) { if ($.inArray(FacturasPago[i].Moneda, Monedas) == -1) { Monedas.push(FacturasPago[i].Moneda); } fila = AgregarFila(tabla, "itmDeuda"); AgregarCelda(fila, FacturasPago[i].Documento, "grdTexto").setAttribute("idCuenta", FacturasPago[i].idCuenta); AgregarCelda(fila, FacturasPago[i].Moneda, "grdTexto") AgregarCelda(fila, FormatDecimal(FacturasPago[i].DeudaDolar) + "USD", "grdDecimal"); AgregarCelda(fila, FormatDecimal(FacturasPago[i].CambioDolar), "grdDecimal"); AgregarCelda(fila, FormatDecimal(FacturasPago[i].Deuda) + FacturasPago[i].Moneda, "grdDecimal"); //MontoPago = MontoPago + FacturasPago[i].Deuda; var txtPago = CrearInputBox(FormatDecimal(0), "text", "grdDecimal"); txtPago.setAttribute("MontoDeuda", FacturasPago[i].Deuda); txtPago.setAttribute("onblur", "ValidarSumaPagos(this);"); txtPago.setAttribute("onfocus", "return focusDec(this);"); txtPago.setAttribute("onkeydown", "return kdDec(event);"); txtPago.setAttribute("onkeypress", "return kpDec(event, this);"); AgregarCelda(fila, "", "grdDecimal").appendChild(txtPago); AgregarCelda(fila, FormatDecimal(FacturasPago[i].CambioLocal), "grdDecimal"); AgregarCelda(fila, FormatDecimal(FacturasPago[i].DeudaLocal) + FacturasPago[i].MonedaLocal, "grdDecimal"); } RedefinirAlternativo(tabla); $("#txtMontoPago").val(FormatDecimal(MontoPago)); $("#txtMontoRestante").val(FormatDecimal(0)); var cboMonedasPago = $("#cboMonedasPago"); for (i = 0; i < Monedas.length; i++) { cboMonedasPago.append($('<option>', { value: Monedas[i], text: Monedas[i] })); } ValidarMonedaCuentasPago(); } function _Gestion_ins(msg) { var resp = msg.d; if (resp == false) { Mensaje({ mensaje: Recursos["ErrorManagement"] }); } else { if (AvisosPropios.length > 0) { LlamarServicio(_Avisos_del, "Avisos_del", { Avisos: AvisosPropios, Comentario: $("#txtGestDescripcion").val() }); } //RefrescarPersona(); $("#txtGestDescripcion").val(""); $("#cboGestStatus option:first").attr('selected', 'selected'); // Mensaje({ mensaje: "La gestión se guardó correctamente" }); Preguntar({ mensaje: "La gestión se guardó correctamente, ¿Desea gestionar a otra persona?", funcion: FinalizarGestion }); //Cartera_lst(_Cartera_lst, idOp(), idOpL() != idOp()); /*Warning*/RA //LlamarServicio(_Cartera_lst, "Cartera_lst", { idOperador: idOp(), Supervisado: idOpL() != idOp() }); RefrescarGestiones() try { for (var i = 0; i < Cartera.length; i++) { var ItemCartera = Cartera[i].Personas.where(function (a) { return a.idPersona == idP(); })[0]; if (ItemCartera == undefined) break; ItemCartera.FechaUltimaGestion = (new Date()).ToString("JSON"); var Status = lstStatus.where(function (a) { return a.idStatus == idUltimoStatus; }); ItemCartera.StatusUltimaGestion = Status[0].Nombre; ItemCartera.TipoStatus = Status[0].Tipo; } _Cartera_lst({ d: Cartera }); } catch (e) { ActualizarCartera(); } LimpiarAdjuntos(); } } function _Avisos_del(msg) { Avisos_Actualizar(); } function RefrescarPersona() { var idPersona = $("#idPersona").val(); if (idPersona == "") return; Persona_Mostrar(idPersona); } function RefrescarGestiones() { var idPersona = $("#idPersona").val(); if (idPersona == "") return; LlamarServicio(_Personas_Gestiones_lst, "Personas_Gestiones_lst", { idPersona: idPersona, idOperador: idOp() }); } function FinalizarGestion() { LlamarServicio(_Personas_sel, "Personas_sel", { idPersona: 0, idOperador: idOp() }); } function _Personas_sel(msg) { var Persona = msg.d; if (Persona == null) { Mensaje({ mensaje: "Ya no hay más clientes para gestionar" }); $("#idPersona").val(""); $("#pstIndicadores").click(); return; } $("#idPersona").val(Persona.idPersona); $("#lblPeCodigo").text(Persona.Codigo); $("#lblPeRif").text(Persona.Rif); $("#lnkPeURL").attr("href", Persona.URL); $("#lnkPeURL").text(Persona.URL); $("#lblPeEmail").text(Persona.Email); $("#lblPeNombre").text(Persona.Nombre); $("#lblPeDireccion").text(Persona.DireccionFiscal); $("#lblPeDireccionEntrega").text(Persona.DireccionEntrega); $("#lblPeContacto").text(Persona.Contacto); $("#divPeDatos").html(""); if (Persona.Datos != null) { XMLDatos = XMLParse(Persona.Datos); var Nodos = XMLDatos.getElementsByTagName("Dato"); var TablaDatos = CrearTabla("Tabla"); $("#divPeDatos")[0].appendChild(TablaDatos); var tr = AgregarFila(TablaDatos); AgregarHeader(tr, "Dato", "grdTexto", false, false, ""); AgregarHeader(tr, "Valor", "grdTexto", false, false, ""); for (var i = 0; i < Nodos.length; i++) { var Clave = Nodos[i].getAttribute("Clave"); var Valor = Nodos[i].textContent; var tr = AgregarFila(TablaDatos); AgregarCelda(tr, Clave, "grdTexto"); AgregarCelda(tr, Valor, "grdTexto"); } } $("#idPais").val(Persona.ISO3); var pais = $("#lblPePais"); var papa = pais[0].parentNode; $(papa).html(""); var img = document.createElement("img"); img.src = "Img/Banderas/" + Persona.ISO3 + "24.png"; papa.appendChild(img); pais.text(Persona.Pais); papa.appendChild(pais[0]); ActualizarComboStatus(Persona.ISO3, Persona.idTipoCliente); //Avisos Propios AvisosPropios = []; if (Persona.AvisosPropios.length > 0) { Preguntar({ mensaje: "Hay avisos propios asociados a esta persona, ¿Desea Cancelar los avisos propios al Guardar una Gestión?", funcion: function () { AvisosPropios = Persona.AvisosPropios; } }); } //---Teléfonos var i; var lstTel = $("#lstPeTelefonos"); lstTel.html(""); lstTelefonos = []; indiceColaTelefonos = -1; for (i = 0; i < Persona.Telefonos.length; i++) { var Telefono = Persona.Telefonos[i]; if (Telefono == undefined) break; if (Telefono.idTelefono == undefined) break; InsertarTelefono(Telefono, lstTel[0]); } //---Soportes var i; var pnlSop = $("#pnlPeSoportes"); pnlSop.html(""); for (i = 0; i < Persona.Soportes.length; i++) { var a = document.createElement("a"); $(a).addClass("Soporte"); $(a).text(Persona.Soportes[i].Nombre); a.onclick = new Function('Emergente({url:"/Emergentes/ctrlSoportes.aspx?idSoporte=' + Persona.Soportes[i].idSoporte + '"});'); //Persona.Soportes[i].Ubicacion; a.target = "_blank"; pnlSop[0].appendChild(a); } //---Contactos var j; var lstPC = $("#lstPeContactos"); lstPC.html(""); for (i = 0; i < Persona.PersonasContacto.length; i++) { MostrarPersonaContacto(Persona.PersonasContacto[i]); //var div = document.createElement("div"); //$(div).addClass("Contacto"); //var div1 = document.createElement("div"); //$(div1).addClass("Nombre"); //$(div1).text(Persona.PersonasContacto[i].Nombre); //div.appendChild(div1); //var div2 = document.createElement("div"); //$(div2).addClass("Cargo"); //$(div2).text(Persona.PersonasContacto[i].Cargo); //div.appendChild(div2); //var div3 = document.createElement("div"); //$(div3).addClass("Correo"); //$(div3).text(Persona.PersonasContacto[i].Correo); //div.appendChild(div3); //var div4 = document.createElement("div"); //$(div4).addClass("Telefonos"); //for (j = 0; j < Persona.PersonasContacto[i].Telefonos.length; j++) { // var Telefono = Persona.PersonasContacto[i].Telefonos[j]; // if (Telefono == undefined) break; // InsertarTelefono(Telefono, div4); // // var div5 = document.createElement("div"); // // div5.className = "Telefono"; // // div5.title = (Telefono.CodigoArea || "") + Telefono.Telefono; // // div5.onclick = LlamarNumero; // // $(div5).text(formatear(Telefono)); // // div5.id = Telefono.idTelefono; // // div4.appendChild(div5); // // // var a = document.createElement("a"); // // $(a).addClass("Telefono"); // // $(a).text(Persona.PersonasContacto[i].Telefonos[j]); // // a.href = "sip:" + ObtenerNumeros(Persona.PersonasContacto[i].Telefonos[j]); // // div4.appendChild(a); //} //div.appendChild(div4); //var btn = document.createElement("input"); //btn.type = "Button"; //$(btn).addClass("btnEliminar32"); //btn.onclick = new Function("EliminarPersonasContacto(" + Persona.PersonasContacto[i].idPersonaContacto + ");"); //btn.title = "Eliminar Persona Contacto"; //div.appendChild(btn); //lstPC[0].appendChild(div); //lstPC[0].appendChild(document.createElement("HR")); } $("#pnlPeCuentas").html("Espere Por Favor..."); //Personas_Cuentas_lst(_Personas_Cuentas_lst, Persona.idPersona, idOp());RA LlamarServicio(_Personas_Cuentas_lst, "Personas_Cuentas_lst", { idPersona: Persona.idPersona, idOperador: idOp() }); $("#pnlPeGestiones").html("Espere Por Favor..."); //Personas_Gestiones_lst(_Personas_Gestiones_lst, Persona.idPersona, idOp());RA LlamarServicio(_Personas_Gestiones_lst, "Personas_Gestiones_lst", { idPersona: Persona.idPersona, idOperador: idOp() }); _Persona_Pagos_lst(Persona.Pagos) _Persona_Reclamos_lst(Persona.Reclamos) LlamarServicio(_Personas_Compromisos_lst, "Personas_Compromisos_lst", { idPersona: Persona.idPersona }); LlamarServicio(_Avisos_Persona_lst, "Avisos_Persona_lst", { idPersona: Persona.idPersona }); //Observaciones Tabla({ Contenedor: "pnlPeObservaciones", Resultado: Persona.Observaciones, Campos: [ { Titulo: "Date", Campo: "Fecha", Clase: "grdFecha", Ordenacion: true, Filtro: true }, { Titulo: "Description", Campo: "Descripcion", Clase: "grdTexto", Ordenacion: true, Filtro: true }, { Titulo: "Severity", Campo: "Severidad", Clase: "grdTexto", Ordenacion: true, Filtro: true } ] }); //Comentarios ActualizarComentario(Persona.Comentarios); //Reportes $("#pnlPeReportes").empty(); for (var i = 0; i < Persona.Reportes.length; i++) { var div = document.createElement("div"); div.className = "btnReporte"; $("#pnlPeReportes")[0].appendChild(div); $(div).text(Persona.Reportes[i].Nombre); div.onclick = new Function('Emergente({ url: "/Emergentes/ctrlReporte.aspx?idTipoReporte=' + Persona.Reportes[i].idTipoReporte + '&idPersona=' + $("#idPersona").val() + '"});'); } $("#pstGestion")[0].click(); $("#datosPersona").slideDown(); if (GestionAutomatica) { PlayGestion("Retrasada"); } } function EliminarPersonasContacto(idPersonaContacto) { Preguntar({ mensaje: "¿Está seguro de que desea eliminar este contacto?", funcion: new Function("LlamarServicio(_PersonasContacto_del,'PersonasContacto_del',{idPersonaContacto:" + idPersonaContacto + "});") }); } function _PersonasContacto_del(msg) { if (msg.d) { Mensaje({ mensaje: "La persona contacto ha sido eliminada satisfactoriamente" }); Persona_Mostrar($("#idPersona").val()); } } function EditarComentario() { Emergente({ url: "/Emergentes/ctrlComentario.aspx?idPersona=" + $("#idPersona").val(), width: 400, height: 300 }); } function ActualizarComentario(Comentario) { $("#lblPeComentarios").html((Comentario || "").replace(/\n/g, '<br/>')); } function RefrescarCompromisos() { LlamarServicio(_Personas_Compromisos_lst, "Personas_Compromisos_lst", { idPersona: $("#idPersona").val() }); } function _Personas_Compromisos_lst(msg) { Tabla({ Contenedor: "pnlPeCompromisos", Resultado: msg.d, Campos: [ { Titulo: "Document", Campo: "Documento", Clase: "grdTexto", Ordenacion: false, Filtro: false }, { Titulo: "Date", Campo: "Fecha", Clase: "grdFechaHora", Ordenacion: false, Filtro: false }, { Titulo: "Total", Campo: "Total", Clase: "grdDecimal", Ordenacion: false, Filtro: false }, { Titulo: "Creator", Campo: "Creador", Clase: "grdTexto", Ordenacion: false, Filtro: false } ] }); } function _Avisos_Persona_lst(msg) { Tabla({ Contenedor: "pnlPeAvisos", Resultado: msg.d, Campos: [ { Titulo: "Reminder", Campo: "Aviso", Clase: "grdTexto", Ordenacion: false, Filtro: false }, { Titulo: "Date", Campo: "FechaAviso", Clase: "grdFechaHora", Ordenacion: false, Filtro: false }, { Titulo: "Operator", Campo: "Operador", Clase: "grdTexto", Ordenacion: false, Filtro: false }, { Titulo: "Creator", Campo: "OperadorCrea", Clase: "grdTexto", Ordenacion: false, Filtro: false } ], FuncSeleccionar: "AbrirAviso(«idAviso»);" }); } function _Personas_Gestiones_lst(msg) { //---Gestiones Tabla({ Contenedor: "pnlPeGestiones", Resultado: msg.d, LimitarAltura: 400, Campos: [ { Titulo: " ", Campo: "Img", Clase: "grdImagen", Imagen: true }, { Titulo: "Date", Campo: "Fecha", Clase: "grdFechaHora", Ordenacion: true, Filtro: true }, { Titulo: "Operator", Campo: "Operador", Clase: "grdTexto", Ordenacion: true, Filtro: true }, // { Titulo: "Description", Campo: "Descripcion", Clase: "grdTexto", Tooltip: function (a) { return "Cuentas:\n" + a.Cuentas.join("\n"); }, Ordenacion: true, Filtro: true }, { Titulo: "Description", Campo: "Descripcion", Clase: "grdTexto", Tooltip: "Cuentas", Ordenacion: true, Filtro: true }, { Titulo: "Status", Campo: "Status", Clase: "grdTexto", Ordenacion: true, Filtro: true, Color: "Tipo" } ], FuncSeleccionar: "AbrirCorreo(«id»,'«Img»',0);" }); } function AbrirDocumento(idCuenta) { Emergente({ url: "/Emergentes/ctrlSoportes.aspx?idCuenta=" + idCuenta }); } function _Personas_Cuentas_lst(msg) { //---Cuentas if (msg.d.length > 0 && msg.d[0].idPersona != idP()) return; //Si se van a cargar cuentas que no son de la persona actual... no la cargues. Tabla({ Contenedor: "pnlPeCuentas", Resultado: msg.d, TodosSeleccionados: false, idSeleccion: "idCuenta", LimitarAltura: 400, Campos: [ { Titulo: "Document", Campo: "Documento", Clase: "grdTexto", Ordenacion: true, Filtro: true, OnClick: "AbrirDocumento(«idCuenta»);", Resumen: "CUENTA" }, { Titulo: "Date", Campo: "Fecha", Clase: "grdFecha", Ordenacion: true, Filtro: true }, { Titulo: "DeliveryDate", Campo: "FechaEntrega", Clase: "grdFecha", Ordenacion: true, Filtro: true }, { Titulo: "Overdue", Campo: "Antiguedad", Clase: "grdEntero", Ordenacion: true, Filtro: true, Resumen: "NINGUNO" }, { Titulo: "Client", Campo: "CodigoCliente", Clase: "grdTexto", Ordenacion: true, Filtro: true }, { Titulo: "Product", Campo: "Producto", Clase: "grdTexto", Ordenacion: true, Filtro: true }, { Titulo: "Total", Campo: "Total", Campo2: "Moneda", Clase: "grdTexto", Ordenacion: false, Filtro: false }, { Titulo: "Remaining", Campo: "Deuda", Campo2: "Moneda", Clase: "grdDecimal", Ordenacion: false, Filtro: false }, { Titulo: "TotalUSD", Campo: "TotalDolar", ToolTip: "CambioDolar", Clase: "grdDecimal", Post: "USD", Ordenacion: true, Filtro: true }, { Titulo: "RemainingUSD", Campo: "DeudaDolar", ToolTip: "CambioDolar", Clase: "grdDecimal", Post: "USD", Ordenacion: true, Filtro: true }, { Titulo: "TotalLocal", Campo: "TotalLocal", Campo2: "MonedaLocal", ToolTip: "CambioLocal", Clase: "grdDecimal", Ordenacion: true, Filtro: true }, { Titulo: "RemainingLocal", Campo: "DeudaLocal", Campo2: "MonedaLocal", ToolTip: "CambioLocal", Clase: "grdDecimal", Ordenacion: true, Filtro: true }, { Titulo: "Claim", Campo: "EnReclamo", Clase: "grdBooleano" }, { Titulo: "Status", Campo: "Status", Clase: "grdTexto", Ordenacion: true, Filtro: true }, { Titulo: "Goal", Campo: "EsMeta", Clase: "grdTexto", Ordenacion: true, Filtro: true } ], FuncSeleccionar: "AbrirCuenta(«idCuenta»);" }); } function AbrirCuenta(idCuenta) { Emergente({ url: "/Emergentes/ctrlCuenta.aspx?idCuenta=" + idCuenta }); } function _Persona_Pagos_lst(Pagos) { Tabla({ Contenedor: "pnlPePagos", Resultado: Pagos, LimitarAltura: 200, Campos: [ { Titulo: "Code", Campo: "Codigo", Campo2: "", Clase: "grdTexto" }, { Titulo: "Reference", Campo: "Referencia", Campo2: "", Clase: "grdTexto" }, { Titulo: "Type", Campo: "Tipo", Campo2: "", Clase: "grdTexto" }, { Titulo: "Date", Campo: "Fecha", Campo2: "", Clase: "grdFecha" }, { Titulo: "Amount", Campo: "Monto", Campo2: "Moneda", Clase: "grdDecimal" }, { Titulo: "Status", Campo: "Status", Clase: "grdTexto" }, { Titulo: "Result", Campo: "Resultado", Clase: "grdTexto" } ], FuncSeleccionar: "AbrirPago(«idPago»,«Aprobado»,«Confirmado»);" }); } function _Persona_Reclamos_lst(Reclamos) { Tabla({ Contenedor: "pnlPeReclamos", Resultado: Reclamos, LimitarAltura: 200, Campos: [ { Titulo: "Date", Campo: "Fecha", Clase: "grdFecha", Ordenacion: true, Filtro: true }, { Titulo: "Code", Campo: "Codigo", Clase: "grdTexto", Ordenacion: true, Filtro: true }, { Titulo: "Reason", Campo: "Motivo", Clase: "grdTexto", Ordenacion: true, Filtro: true }, { Titulo: "Amount", Campo: "MontoLocal", Campo2: "MonedaLocal", Clase: "grdDecimal", Ordenacion: true, Filtro: true }, { Titulo: "Status", Campo: "Status", Clase: "grdTexto", Ordenacion: true, Filtro: true }, { Titulo: "Department", Campo: "Departamento", Clase: "grdTexto", Ordenacion: true, Filtro: true }, { Titulo: "Result", Campo: "Resultado", Clase: "grdTexto", Ordenacion: true, Filtro: true } ], FuncSeleccionar: "AbrirReclamo(«idReclamo»);" }); } function Persona_Mostrar(idPersona, propio) { if (propio == undefined) propio = false; $("#idPersona").val(""); LlamarServicio(_Personas_sel, "Personas_sel", { idPersona: idPersona, idOperador: propio ? idOpA() : idOp() }); } function ConfirmarGestion() { var Status = $("#cboGestStatus option:selected").html(); Preguntar({ mensaje: "La gestión se guardara con el Status: " + Status + ", ¿Esta seguro?", funcion: GuardarGestion }); } function GuardarGestion() { var tablaCuenta = $("#pnlPeCuentas")[0].getElementsByTagName("table")[0]; var campos = obtenerCampos(tablaCuenta); var colIdCuenta = $.inArray("idCuenta", campos); var lstCuentas = Array(); elem = tablaCuenta.getElementsByTagName("tr"); for (i = 1; i < elem.length; i++) { try { var checkBox = elem[i].getElementsByTagName("td")[colIdCuenta].getElementsByTagName("input")[0]; if (checkBox.checked) { lstCuentas.push($(checkBox).val()); } } catch (ex) { } } var rtGestion = {}; rtGestion.idOperador = idOpL(); rtGestion.idPersona = $("#idPersona").val(); rtGestion.idStatus = $('#cboGestStatus').find(":selected").val(); idUltimoStatus = rtGestion.idStatus; rtGestion.Descripcion = $("#txtGestDescripcion").val(); rtGestion.Cuentas = lstCuentas; if (rtGestion.idStatus == 0) { Mensaje({ mensaje: "No ha seleccionado un status" }); return; } lstCuentas2 = ObtenerSeleccionados("pnlPeCuentas").select("idCuenta"); if (lstCuentas.length == 0 && elem.length > 2) { // Mensaje({ mensaje: "No hay facturas seleccionadas, ¿Desea continuar?", titulo: "Guardando gestión", buttons: { Aceptar: function () { Gestion_ins(_Gestion_ins, rtGestion); $(this).dialog("close"); }, Cancelar: function () { $(this).dialog("close"); } } }); Mensaje({ mensaje: "No ha seleccionado ninguna factura, No Puede Guardar la gestión", titulo: "Guardando gestión" }); return } //Gestion_ins(_Gestion_ins, rtGestion);RA LlamarServicio(_Gestion_ins, "Gestion_ins", { Gestion: rtGestion, Adjuntos: lstAdjuntos }); } function obtenerCuentasTabla(tablaCuenta) { var campos = obtenerCampos(tablaCuenta); var colIdCuenta = $.inArray("idCuenta", campos); var facturas = ""; elem = tablaCuenta.getElementsByTagName("tr"); for (i = 1; i < elem.length; i++) { try { var checkBox = elem[i].getElementsByTagName("td")[colIdCuenta].getElementsByTagName("input")[0]; if (checkBox.checked) { if (facturas == "") { facturas = $(checkBox).val(); } else { facturas = facturas + "," + $(checkBox).val(); } } } catch (ex) { } } return facturas; } function NuevoPago() { var tablaCuenta = $("#pnlPeCuentas")[0].getElementsByTagName("table")[0]; //Cuentas = obtenerCuentasTabla(tablaCuenta); Cuentas = ObtenerSeleccionados("pnlPeCuentas").select("idCuenta"); idPersona = $("#idPersona").val(); idOperadorSup = idOp(); idOperadorAct = idOpA(); idOperadorLog = idOpL(); // if (Cuentas == "") // if (Cuentas.length == 0) // { // Mensaje({ mensaje: "Debe seleccionar al menos una cuenta" }); // } // else // { // Emergente({ url: "/Emergentes/ctrlNuevoPago.aspx?cuentas=" + cuentas }); Emergente({ url: "/Emergentes/ctrlNuevoPago.aspx", modal: false }); // } } function NuevoCompromiso() { Cuentas = ObtenerSeleccionados("pnlPeCuentas").select("idCuenta"); idPersona = $("#idPersona").val(); idOperadorSup = idOp(); idOperadorAct = idOpA(); idOperadorLog = idOpL(); if (Cuentas.length == 0) { Mensaje({ mensaje: "Debe seleccionar al menos una cuenta" }); } else { Emergente({ url: "/Emergentes/ctrlCompromisos.aspx" }); } } function NuevoReclamo() { Cuentas = ObtenerSeleccionados("pnlPeCuentas").select("idCuenta"); idPersona = $("#idPersona").val(); idOperadorSup = idOp(); idOperadorAct = idOpA(); idOperadorLog = idOpL(); if (Cuentas.length == 0) { Mensaje({ mensaje: "Debe seleccionar al menos una cuenta" }); } else { Emergente({ url: "/Emergentes/ctrlNuevoReclamo.aspx?oper=Ins" }); } } function Pais() { return $("#idPais").val(); } //------------------------------------------------------------------------------------------------------------Generales; function AbrirCorreo(id, Tipo1, Tipo) { if (id == 0 || id == undefined) return; if (Tipo1.indexOf("Telefono") != -1) { location.href = "/Emergentes/Grabaciones.aspx?Grabacion=" + id + "&Tipo=id"; } else if (Tipo1.indexOf("Correo") != -1) { Emergente({ url: "/Emergentes/ctrlCorreo.aspx?idCorreo=" + id + "&idOperador=" + idOpA() + "&Tipo=" + Tipo, modal: false, close: function (event, ui) { RefrescarCorreos(); } }); } else if (Tipo1.indexOf("UsuarioAdjunto") != -1) { Emergente({ url: "/Emergentes/ctrlSoportes.aspx?idGestion=" + id, modal: false }); } } function AbrirPago(idPago, Aprobado, Confirmado) { // if (Confirmado == null || Confirmado == false) if (Aprobado == false || Confirmado == false) { idPersona = $("#idPersona").val(); idOperadorSup = idOp(); idOperadorAct = idOpA(); idOperadorLog = idOpL(); Emergente({ url: "/Emergentes/ctrlNuevoPago.aspx?idPago=" + idPago.toString() }); } else { Mensaje({ mensaje: "El Pago ya ha sido confirmado, no puede editarlo" }); } } function AbrirCompromiso(idCompromiso) { //Mensaje({ mensaje: "Todavía no implementado" }); } function AbrirReclamo(idReclamo) { Emergente({ url: "/Emergentes/ctrlReclamos.aspx?idReclamo=" + idReclamo.toString() }); //Mensaje({ mensaje: "Todavía no implementado" }); } //function Llamar() //{ // Emergente({ url: "/Emergentes/ctrlLlamada.aspx" }); //} //------------------------------------------------------------------------------------------------------------Cartera function _Cartera_lst(msg) { Cartera = msg.d; $("#pnlCartera").empty(); bandera = 0; var Panel = $("#pnlCartera")[0]; for (var i = 0; i < msg.d.length; i++) { Grupo = msg.d[i]; if (bandera == 0) { // var h3 = document.createElement("h3"); // $(h3).text(Grupo.Nombre); // Panel.appendChild(h3); var enc = document.createElement("div"); var img = document.createElement("img"); img.src = "Img/Soporte_16.png"; //img.onclick = function (e) { Cartera_Descargar(Grupo.idCampana); e.cancelBubble=true;}; img.onclick = new Function("Cartera_Descargar(" + Grupo.idCampana + "); event.cancelBubble=true;") var spn = document.createElement("span"); $(spn).text(Grupo.Nombre + "[" + Grupo.Personas.length + " Personas]"); enc.appendChild(spn); enc.appendChild(img); enc.id = "_pnlCartera" + i.toString(); enc.className = "EncSeccion"; Panel.appendChild(enc); $(enc).click(function () { $('#' + this.id.substr(1)).slideToggle(); OcultarAvisos(); }) var div = document.createElement("div"); div.id = "pnlCartera" + i.toString(); div.className = "Seccion"; Panel.appendChild(div); Tabla({ Contenedor: div.id, Resultado: Grupo.Personas, idSeleccion: (OperadorEs('SU', 'CO', 'GE', 'AD') ? "idPersona" : undefined), Campos: [ { Titulo: "Status", Campo: function (a) { return "/Img/" + a.TipoStatus + "24.png"; }, Clase: "grdTexto", Ordenacion: "TipoStatus", Tooltip: "StatusUltimaGestion", Filtro: false, Imagen: true }, { Titulo: "R", Campo: "TieneAviso", Clase: "grdBooleano", Ordenacion: true, Filtro: false }, { Titulo: "LastManagement", Campo: "FechaUltimaGestion", Clase: "grdFechaHora", Ordenacion: true, Filtro: true }, { Titulo: "LastOperator", Campo: "Operador", Clase: "grdTexto", Ordenacion: true, Filtro: true }, { Titulo: "AssignedOperator", Campo: "UltimoOperador", Clase: "grdTexto", Ordenacion: true, Filtro: true }, { Titulo: "Code", Campo: "Codigo", Clase: "grdTexto", Ordenacion: true, Filtro: true }, { Titulo: "Rif", Campo: "Rif", Clase: "grdTexto", Ordenacion: true, Filtro: true }, { Titulo: "Name", Campo: "Nombre", Clase: "grdTexto", Ordenacion: true, Filtro: true }, { Titulo: "TotalUSD", Campo: "TotalDolar", Clase: "grdDecimal", Post: "USD", Ordenacion: true, Filtro: true }, { Titulo: "RemainingUSD", Campo: "RestanteDolar", Clase: "grdDecimal", Post: "USD", Ordenacion: true, Filtro: true }, { Titulo: "TotalLocal", Campo: "TotalLocal", Campo2: "Moneda", Clase: "grdDecimal", Ordenacion: false, Filtro: false }, { Titulo: "RemainingLocal", Campo: "RestanteLocal", Campo2: "Moneda", Clase: "grdDecimal", Ordenacion: false, Filtro: false }, { Titulo: "Country", Campo: function (a) { return "/Img/Banderas/" + a.idPais + "24.png"; }, Clase: "grdTexto", Ordenacion: "Iso3", Filtro: false, Imagen: true }, ], FuncSeleccionar: "if (OperadorEs('SO','BO','SU','CO','GE','AD','SI')) Persona_Mostrar(«idPersona»);" }); if (Grupo.idCampana == -2) { bandera = 1; } } } } function _OperadoresSupervisados_lst(msg) { if (msg.d.length == 0) return; LlenarCombo({ Combo: "cboOperadorAviso", Resultado: msg.d, CampoId: "idOperador", CampoValor: "Nombre" }); $("#cboOperadorAviso").val(idOp()); var Op = msg.d; var papa = $("#pnlSupervision"); papa.html(""); papa = papa[0]; var jerarquia = ""; var tabla; var celdaAnterior = papa; for (var i = 0; i < Op.length; i++) { if (Op[i].Jerarquia == "-") continue; var JA = Op[i].Jerarquia.length; //Actual var JP = jerarquia.length; //Pasada if (JA > JP) { papa = celdaAnterior; tabla = CrearTabla(); papa.appendChild(tabla); } if (JA < JP) { for (var j = 0; j < (JP - JA) / 3; j++) { while ((papa = papa.parentNode).tagName.toLowerCase() != "td") { }; } tabla = papa.getElementsByTagName("table")[0]; } var fila = AgregarFila(tabla, "itmSeleccionable"); fila.onclick = new Function("Supervisar(" + Op[i].idOperador + ");"); var celda = AgregarHeader(fila, ""); var img = document.createElement("img"); img.src = "Img/usuario24.png"; celda.appendChild(img); AgregarHeader(fila, Op[i].Nombre).style.textAlign = "left"; fila = AgregarFila(tabla); AgregarCelda(fila, " "); celdaAnterior = AgregarCelda(fila, ""); jerarquia = Op[i].Jerarquia; } } //------------------------------------------------------------------------------------------------------------Indicadores function _ActualizarGrafico(msg) { var hora = new Date().getTime(); var Ruta = msg.d + "?hora=" + hora; $("#chrtGestiones").attr("src", Ruta); } function _ActualizarIndicadores(msg) { $("#lblMetaGestiones").text((msg.d.MetaGestiones)); $("#lblRealGestiones").text((msg.d.RealGestiones)); Colorear("barGestiones", "lblRealGestiones", msg.d.MetaGestiones, msg.d.RealGestiones); $("#lblMetaGestionesPersonas").text((msg.d.MetaGestionesPersonas)); $("#lblRealGestionesPersonas").text((msg.d.RealGestionesPersonas)); Colorear("barGestionesPersonas", "lblRealGestionesPersonas", msg.d.MetaGestionesPersonas, msg.d.RealGestionesPersonas); $("#lblMetaMonto").text(FormatDecimal(msg.d.MetaMonto)); $("#lblRealMonto").text(FormatDecimal(msg.d.RealMonto)); Colorear("barMonto", "lblRealMonto", msg.d.MetaMonto, msg.d.RealMonto); $("#lblMetaTiempo").text(Convert.ToTimeSpan(msg.d.MetaTiempo * 60)); $("#lblRealTiempo").text(Convert.ToTimeSpan(msg.d.RealTiempo * 60)); Colorear("barTiempo", "lblRealTiempo", msg.d.MetaTiempo, msg.d.RealTiempo); $("#lblMetaTiempoInactivo").text(Convert.ToTimeSpan(msg.d.MetaTiempoInactivo * 60)); $("#lblRealTiempoInactivo").text(Convert.ToTimeSpan(msg.d.RealTiempoInactivo * 60)); Colorear("barInactivo", "lblRealTiempoInactivo", msg.d.MetaTiempoInactivo, msg.d.RealTiempoInactivo, true); $("#lblMetaTMO").text(Convert.ToTimeSpan(Convert.ToInt32(msg.d.MetaTMO * 60))); $("#lblRealTMO").text(Convert.ToTimeSpan(Convert.ToInt32(msg.d.RealTMO * 60))); Colorear("barTMO", "lblRealTMO", msg.d.MetaTMO, msg.d.RealTMO, true); $("#lblCuentasAsignadas").text(msg.d.CuentasAsignadas); $("#lblPersonasAsignadas").text(msg.d.PersonasAsignadas); $("#lblTiempoEnLlamada").text(Convert.ToTimeSpan(msg.d.TiempoEnLlamada)); $("#lblLlamadasRealizadas").text(msg.d.LlamadasRealizadas); $("#lblLlamadasContestadas").text(msg.d.LlamadasContestadas); $("#lblLlamadasNoContestadas").text(msg.d.LlamadasNoContestadas); } function Colorear(barra, id, meta, real, maximo) { var Control = $("#" + id); var Barra = $("#" + barra); var Color; var Tamano; Barra.text(meta == 0 ? "0%" : FormatDecimal(real * 100.0 / meta) + "%"); if (maximo !== true) { Tamano = (meta == 0 || real / meta > 1.2 ? 120 : real * 100.0 / meta); if (real >= meta)//Excelente { Color = Colores.Positivo; } else if (real >= meta * .8)//Bastante Bien, casi cumpliendo la meta { Color = Colores.Neutral; } else // mal, lejos de la meta { Color = Colores.Negativo; } } else { Tamano = (meta == 0 || real / meta > 1.2 ? 120 : real * 100.0 / meta); if (real <= meta) //Excelente { Color = Colores.Positivo; } else if (real >= meta * 1.2) //mal, lejos de la meta { Color = Colores.Negativo; } else //Bastante Bien, casi cumpliendo la meta { Color = Colores.Neutral; } } Control.css("color", Color); Barra.css("background-color", Color); Barra.css("width", Tamano); if (Tamano == 120) { Barra.css("border-right", "1px dotted white"); } } //Warning function BuscarRNC() { var rif = $("#lblPeRif").text(); rif = rif.replace(/[-]/g, ""); Emergente({ url: "http://rncenlinea.snc.gob.ve/reportes/resultado_busqueda?p=1&rif=" + rif + "&search=RIF" }); } function BuscarGoogle() { var Nombre = $("#lblPeNombre").text(); Nombre = Nombre.replace(/[\s]/g, "+"); Nombre = Nombre.replace(/&/g, "%26"); window.open("https://www.google.co.ve/#q=" + Nombre, "_blank"); } function BuscarPAC() { var Nombre = $("#lblPeNombre").text(); Nombre = Nombre.replace(/[\s]/g, "+"); Nombre = Nombre.replace(/&/g, "%26"); window.open("http://www.pac.com.ve/index.php?option=com_jumi&fileid=9&Itemid=119&keyword=" + Nombre, "_blank"); } function CrearAviso() { var Aviso = {}; Aviso.idOperador = $("#cboOperadorAviso").val(); Aviso.idOperadorCrea = idOpL(); Aviso.idPersona = $("#idPersona").val(); Aviso.Prioritario = $("#chkAvisoPrioritario")[0].checked; if ($("#dtpFechaAviso").val() == "") { Mensaje({ mensaje: "Debe seleccionar una fecha válida para este aviso" }); return; } if ($("#txtNuevoAviso").val() == "") { Mensaje({ mensaje: "Debe seleccionar un Texto para este aviso" }); return; } Aviso.FechaAviso = Convert.ToDateTime($("#dtpFechaAviso").val() + " " + $("#cboHoraAviso").val() + ":" + $("#cboMinutoAviso").val()).ToString("JSON"); Aviso.Aviso = $("#txtNuevoAviso").val(); //Avisos_ins(_Avisos_ins, Aviso);RA LlamarServicio(_Avisos_ins, "Avisos_ins", { Aviso: Aviso }); } function _Avisos_ins(msg) { if (msg.d === true) { Mensaje({ mensaje: "Tu aviso ha sido creado exitosamente" }); $("#txtNuevoAviso").val(""); } } function Seniat() { Emergente({ url: "http://contribuyente.seniat.gob.ve/BuscaRif/BuscaRif.jsp" }); } function AgregarTelefono() { Emergente({ url: "/Emergentes/ctrlNuevoTelefono.aspx?idPersona=" + $("#idPersona").val(), width: 300, height: 200 }); } function EliminarTelefono() { Emergente({ url: "/Emergentes/ctrlEliminarTelefono.aspx?idPersona=" + $("#idPersona").val() + "&idOperador=" + idOp() }); } function AgregarContacto() { Emergente({ url: "/Emergentes/ctrlNuevoContacto.aspx?idPersona=" + $("#idPersona").val(), width: 300, height: 300 }); } function FiltrarPersona() { var filtro = $("#txtFiltroPersona").val().toUpperCase(); if (filtro == "") { LlenarCombo({ Combo: "cboaPersona", Resultado: PersonasTocadas, CampoId: "idPersona", CampoValor: "Nombre", TextoNull: "<<Niguno>>" }); } else { LlenarCombo({ Combo: "cboaPersona", Resultado: PersonasTocadas.where(function (a) { return a.Nombre.toUpperCase().indexOf(filtro) != -1; }), CampoId: "idPersona", CampoValor: "Nombre" }); } } function Cartera_Descargar(idCampana) { if (idCampana == undefined) { location.href = "/Descargas/Descargas.aspx?Reporte=Cartera&idOperador=" + idOp() + "&IncluyeAutomatico=" + ($("#chkIncluyeAutomatico")[0].checked ? "true" : "false" + "&Supervisor=" + (idOpL() != idOp() ? "true" : "false")); } else { location.href = "/Descargas/Descargas.aspx?Reporte=Cartera&idOperador=" + idOp() + "&IncluyeAutomatico=" + ($("#chkIncluyeAutomatico")[0].checked ? "true" : "false" + "&Supervisor=" + (idOpL() != idOp() ? "true" : "false") + "&idCampana=" + idCampana); } } function OcultarAvisos() { if ($('#Avisos').css('left') != "-340px") { $('#Avisos').animate({ left: "-340px" }, 1000, function () { }); } } function OperadorEs() { for (var i = 0; i < arguments.length; i++) { if (TipoOperador.indexOf(arguments[i]) != -1) return true; } return false; } function _Avisos_lst(msg) { Vencidos = 0; var i; for (i = 0; i < msg.d.length; i++) { Avisos_Cargar(msg.d[i]); } } function _Avisos_lst2(msg) { _Avisos_lst(msg) if (Vencidos > 0) { Mensaje({ mensaje: Recursos["msgExpiredReminders"].replace("#", Vencidos) }); } } function Avisos_Cargar(Aviso) { $("#idAviso").val(Aviso.idAviso); var tabla = document.getElementById("tblAvisos"); var tbody = tabla.getElementsByTagName("tbody")[0]; var fila = document.createElement("TR"); Aviso.FechaAviso = Convert.ToDateTime(Aviso.FechaAviso); AgregarCelda(fila, Aviso.FechaAviso.ToString(Regional.FormatoFechaHora)); fila.setAttribute("class", "itmAviso"); fila.onclick = new Function("AbrirAviso(" + Aviso.idAviso + ");"); AgregarCelda(fila, Aviso.Aviso); AgregarCelda(fila, Aviso.OperadorCrea); AgregarCelda(fila, Aviso.CodigoPersona); var filas = tbody.getElementsByTagName("TR"); var referencia = null; var i; for (i = 1; i < filas.length; i++) { var celdas = filas[i].getElementsByTagName("TD"); if (Convert.ToDateTime($(celdas[0]).text()) > Aviso.FechaAviso) { referencia = filas[i]; break; } } if (referencia == null) { tbody.appendChild(fila); } else { tbody.insertBefore(fila, referencia); } var tiempo = Aviso.FechaAviso - (new Date()); if (tiempo > 0) { if (tiempo < 24 * 60 * 60 * 1000) // si el tiempo es menor a 1 día. { Avisos.push({ Aviso: Aviso.idAviso, Handle: setTimeout("AbrirAviso(" + Aviso.idAviso + ");", tiempo) }); } } else { fila.setAttribute("class", "itmAvisoVencido"); Vencidos++; } } function Avisos_Actualizar() { var tabla = document.getElementById("tblAvisos"); var tbody = tabla.getElementsByTagName("tbody")[0]; var filas = tbody.getElementsByTagName("TR"); var i; for (i = filas.length - 1; i > 0; i--) { tbody.removeChild(filas[i]); } for (i = 0; i < Avisos.length; i++) { clearTimeout(Avisos[i].Handle); } Avisos = []; // $("#idAviso").val("0"); //Avisos_lst(_Avisos_lst, 0);RA LlamarServicio(_Avisos_lst, "Avisos_lst", { idAviso: 0 }); } function AbrirAviso(idAviso) { var iframe = $("#aviso iframe"); iframe[0].src = "/Emergentes/ctrlAviso.aspx?idAviso=" + idAviso; var argumentos = { modal: false, width: 450, height: 400, minWidth: 450, minHeight: 400 } argumentos.close = function (event, ui) { $("#aviso iframe")[0].src = "about:blank"; }; argumentos.hide = { effect: "fade", duration: 500 }; $("#aviso").dialog(argumentos); } function CerrarAviso() { $("#aviso").dialog("close"); } function _Operadores_Suplantar_lst(msg) { Tabla({ Contenedor: "pnlOperadoresYoSuplantar", Resultado: msg.d, Campos: [ { Titulo: "Operator", Campo: "Operador", Clase: "grdTexto" }, { Titulo: "StartDate", Campo: "FechaInicio", Clase: "grdFecha" }, { Titulo: "EndDate", Campo: "FechaFin", Clase: "grdFecha" }, { Titulo: "Dashboard", Campo: "Indicadores", Clase: "grdBooleano" }, { Titulo: "InBox", Campo: "Correo", Clase: "grdBooleano" }, { Titulo: "Portfolio", Campo: "Cartera", Clase: "grdBooleano" }, { Titulo: "Management", Campo: "Gestion", Clase: "grdBooleano" }, { Titulo: "Supervision", Campo: "Supervision", Clase: "grdBooleano" }, { Titulo: "Distribution", Campo: "Distribucion", Clase: "grdBooleano" }, { Titulo: "Reports", Campo: "Reportes", Clase: "grdBooleano" }, ], FuncSeleccionar: "Suplantar(«idOperador»);" }); } function _Operadores_Suplantarme_lst(msg) { Tabla({ Contenedor: "pnlOperadoresSuplantarme", Resultado: msg.d, Campos: [ { Titulo: "Suplente", Campo: "Operador", Clase: "grdTexto" }, { Titulo: "StartDate", Campo: "FechaInicio", Clase: "grdFecha" }, { Titulo: "EndDate", Campo: "FechaFin", Clase: "grdFecha" }, { Titulo: "Dashboard", Campo: "Indicadores", Clase: "grdBooleano" }, { Titulo: "InBox", Campo: "Correo", Clase: "grdBooleano" }, { Titulo: "Portfolio", Campo: "Cartera", Clase: "grdBooleano" }, { Titulo: "Management", Campo: "Gestion", Clase: "grdBooleano" }, { Titulo: "Supervision", Campo: "Supervision", Clase: "grdBooleano" }, { Titulo: "Distribution", Campo: "Distribucion", Clase: "grdBooleano" }, { Titulo: "Reports", Campo: "Reportes", Clase: "grdBooleano" }, ], FuncEliminar: "EliminarSuplantacion(«idSuplente»);" }); } function Suplantar(idOperador) { $("#pnlCartera").html("Espere por favor..."); $("#idPersona").val(""); $("#minipnlSuplantacion")[0].style.display = (idOpL() == idOperador) ? 'none' : ''; LlamarServicio(Suplantar_Nombre, "Nombre", { idOperador: idOperador }); $("#idOperador").val(idOperador); $("#idOperadorAct").val(idOperador); LlamarServicio(_Personas_Tocadas_lst, "Personas_Tocadas_lst", { idOperador: idOp() }); ActualizarCartera(); RefrescarCorreos(); $("#pstCartera").click(); LlamarServicio(_ActualizarGraficoSupervision, "ActualizarGraficoSupervision", { idOperador: idOperador }); LlamarServicio(_ActualizarGraficoPorSemana, "ActualizarGraficoPorSemana", { idOperador: idOperador }); LlamarServicio(_OperadoresSupervisados_lst, "OperadoresSupervisadosConSupervisor_lst", { idOperador: idOperador }); LlamarServicio(_ActualizarIndicadores, "ActualizarIndicadores", { idOperador: idOperador }); } function Revertir() { Suplantar(idOpL()); //Suplantar al Logueado } function Novedades() { if (llamadas != 0) return; var Hora = $("#Hora").val(); if (Hora == "") Hora = null; LlamarServicio(_Novedades, "Novedades", { idOperadorLog: idOpL(), idOperador: idOp(), idOperadorAct: idOpA(), Hora: Hora }); } function _Novedades(msg) { var Result = msg.d; if (Result.Reiniciar) { Emergente({ url: "/Default.aspx?RL=1" }); } if (Result.Avisos) { Avisos_Actualizar(); } if (Result.Correos == null) { $("#NoRecibeCorreos").show(); $("#pstBandejaEntrada").css({ color: "Red" }); } else { $("#NoRecibeCorreos").hide(); $("#pstBandejaEntrada").css({ color: "" }); } if (Result.Correos) { RefrescarCorreos(); } if (Result.Cartera) { //Cartera_lst(_Cartera_lst, idOp(), idOpL() != idOp());RA //LlamarServicio(_Cartera_lst, "Cartera_lst", { idOperador: idOp(), Supervisado: idOpL() != idOp() }); ActualizarCartera(); } if (Result.Colas) { ActualizarCartera(); } $("#Hora").val(Result.Hora); } function Importar(CodigoPersona, idOrigen, idPais) { LlamarServicio(_ImportarPersona_sel, "ImportarPersona_sel", { CodigoPersona: CodigoPersona, idOrigen: idOrigen, idPais: idPais }); } function _ImportarPersona_sel(msg) { if (msg.d == 0) { Mensaje({ mensaje: "No se pudo importar el cliente" }); return; } Persona_Mostrar(msg.d); } function ActualizarCartera() { LlamarServicio(_Cartera_lst, 'Cartera_lst', { idOperador: idOp(), Supervisado: idOpL() != idOp(), IncluyeAutomatico: $("#chkIncluyeAutomatico")[0].checked }); } function InsertarColas(posicion) { //modificar para crear un arreglo y enviar un solo objeto al servidor var x = document.getElementsByTagName("div").pnlCartera.children.length / 2; var valores = []; for (var i = 0; i < x; i++) { var nombre = "pnlCartera" + i; valores = valores.concat(ObtenerSeleccionados(nombre).select("idPersona")); } LlamarServicio(_Agregar_Cola_Sup, 'Agregar_Cola_Sup', { Valores: valores, Lugar: posicion }); //sacar este mensaje para que se reciba en el mensaje del servicio ActualizarCartera(); } function _Agregar_Cola_Sup(msg) { if (msg.d == 0) { Mensaje({ mensaje: "Cuenta procesada a la cola del operador correctamente" }); return; } } function setCookieCulture() { document.cookie = 'Culture=' + $('#ddlIdioma').val(); } //-------------------- function formatear(Telefono) { if (Telefono.CodigoArea == null) { var Tel = Telefono.Telefono.replace(/[-]/g, "").replace(/[\/]/g, ""); return "(" + Tel.substring(0, 4) + ") " + Tel.substring(4); } else { return "(" + Telefono.CodigoArea + ") " + Telefono.Telefono; } } function LlamarNumero() { Llamada({ url: '/Emergentes/ctrlLlamada.aspx?Numero=' + this.title + "&idTelefono=" + this.id + "&idPersona=" + idP() }); } function FinalizarLlamada() { try { CerrarLlamada(); } catch (e) { } LlamarServicio(_Personas_Gestiones_lst, "Personas_Gestiones_lst", { idPersona: idP() }); if (GestionAutomatica && !PausaGestion) { Preguntar({ mensaje: "Llamada Finalizada, ¿Intentar el siguiente Teléfono?", funcion: ColaDeLlamadas }); } } function InsertarTelefono(Telefono, contenedor) { if (contenedor == undefined) contenedor = $('#lstPeTelefonos')[0]; var div = document.createElement("div"); div.className = "Telefono"; div.title = (Telefono.CodigoArea || "") + (Telefono.Telefono || ""); div.onclick = LlamarNumero; $(div).text(formatear(Telefono)); div.id = Telefono.idTelefono; contenedor.appendChild(div); lstTelefonos.push(Telefono); } function ColaDeLlamadas() { try { if (PausaGestion) return; } catch (e) { } if (indiceColaTelefonos != -1) { try { $("#" + lstTelefonos[indiceColaTelefonos].idTelefono + ".Telefono").removeClass("TelefonoActivo"); } catch (e) { } } indiceColaTelefonos++; if (indiceColaTelefonos >= lstTelefonos.length) { Mensaje({ mensaje: "Ya no hay más teléfonos para llamar, por favor haga una gestión para continuar." }); } else { var Telefono = lstTelefonos[indiceColaTelefonos]; //setTimeout('FinalizarLlamada();', 5000); $("#" + lstTelefonos[indiceColaTelefonos].idTelefono).addClass("TelefonoActivo"); //Mensaje({ mensaje: "Llamando a :" + Telefono.Telefono }); Llamada({ url: '/Emergentes/ctrlLlamada.aspx?Numero=' + (Telefono.CodigoArea || "") + Telefono.Telefono + "&idTelefono=" + Telefono.idTelefono + "&idPersona=" + idP() }); } } function PlayGestion(Retrasada) { LlamarServicio(_Acciones_ins, "Acciones_ins", { Accion: "G>", idOperador: idOp() }); PausaGestion = false; GestionAutomatica = true; if (idP() > 0) { if (Retrasada == "Retrasada") { setTimeout("Retraso(20);", 1000); } else { ColaDeLlamadas(); } } else { FinalizarGestion(); } $("#btnPlay").hide(); $("#btnPause").show(); $("#btnStop").show(); } function PauseGestion() { LlamarServicio(_Acciones_ins, "Acciones_ins", { Accion: "G|", idOperador: idOp() }); PausaGestion = true; $("#btnPlay").show(); $("#btnPause").hide(); $("#btnStop").show(); } function StopGestion() { LlamarServicio(_Acciones_ins, "Acciones_ins", { Accion: "G*", idOperador: idOp() }); PausaGestion = true; GestionAutomatica = false; $("#btnPlay").show(); $("#btnPause").hide(); $("#btnStop").hide(); } function _Acciones_ins() { //Cuerpo. } function Retraso(n) { $("#Contador").text(n); if (n <= 0) { $("#Contador").text(""); ColaDeLlamadas(); } else { setTimeout("Retraso(" + (n - 1).toString() + ");", 1000); } } function EjecutarPruebas() { indicePrueba = 0; Prueba(); } function Prueba() { switch (indicePrueba) { case 0: //Tiempo de Respuesta tiempo = new Date(); LlamarServicio(_Prueba, "PruebasTransferencia", { Data: "-" }); break; case 1: //Prueba Subida tiempo = new Date(); var Data = ""; for (var i = 0; i < 5000; i++) { Data += "**********"; } LlamarServicio(_Prueba, "PruebasTransferencia", { Data: Data }); break; case 2: tiempo = new Date(); LlamarServicio(_Prueba, "PruebasTransferencia", { Data: "" }); break; case 3: tiempo = new Date(); LlamarServicio(_Prueba, "PruebasTransferencia", { Data: "B" }); break; case 4: LlamarServicio(_Prueba, "PruebasPing", {}); break; case 5: LlamarServicio(_Prueba, "Bloqueos"); break; default: break; } } function _Prueba(msg) { switch (indicePrueba) { case 0: //Tiempo de Respuesta var tiempo2 = new Date(); $("#SWTiempoRespuesta").text(((tiempo2 - tiempo) / 1000).toString() + " s"); break; case 1: //Prueba Subida var tiempo2 = new Date(); $("#SWTiempoSubida").text(((tiempo2 - tiempo) / 1000).toString() + " s"); break; case 2: //Prueba Bajada var tiempo2 = new Date(); $("#SWTiempoBajada").text(((tiempo2 - tiempo) / 1000).toString() + " s"); break; case 3: //Prueba Base de Datos var tiempo2 = new Date(); $("#BDTiempoTransporte").text(((tiempo2 - tiempo) / 1000).toString() + " s"); break; case 4: //Prueba Ping $("#BDPing").text(msg.d); break; case 5: //Bloqueos _Bloqueos(msg); break; default: break; } indicePrueba++; Prueba() } function EliminarSuplantacion(idSuplente) { LlamarServicio(_Suplentes_del, "Suplentes_del", { idSuplente: idSuplente }); } function _Suplentes_del(msg) { ActualizarSuplentes(); } function ActualizarSuplentes() { LlamarServicio(_Operadores_Suplantarme_lst, "Operadores_Suplantarme_lst"); LlamarServicio(_Operadores_Suplantar_lst, "Operadores_Suplantar_lst"); } function ConsultarBloqueos() { LlamarServicio(_Bloqueos, "Bloqueos"); } function _Bloqueos(msg) { Tabla({ Contenedor: "BDBloqueos", Resultado: msg.d, Campos: [ { Titulo: "P1", Campo: "p1", Clase: "grdEntero", Ordenacion: false, Filtro: false }, { Titulo: "P2", Campo: "p2", Clase: "grdEntero", Ordenacion: false, Filtro: false }, { Titulo: "Usuario Bloqueado", Campo: "UsuarioBloqueado", Clase: "grdTexto", Ordenacion: false, Filtro: false }, { Titulo: "Usuario Bloqueador", Campo: "UsuarioBloqueador", Clase: "grdTexto", Ordenacion: false, Filtro: false } ], FuncEliminar: "Matar(«p1»);" }); } function Matar(id) { LlamarServicio(_Matar, "Matar", { spid: id }); } function _Matar(msd) { ConsultarBloqueos(); Mensaje({ mensaje: "El proceso ha sido eliminado" }); } function EjecutarComando() { LlamarServicio(_EjecutarComando, "EjecutarComando", { Comando: $("#txtBDComando").val() }); } function _EjecutarComando(msg) { TablaDataSet(msg.d, 'pnlResultadoBDComando'); } function ExcluirMetasCuentas() { var Motivo = $("#cboExclusionMotivo").val(); if (Motivo == "") { Mensaje({ mensaje: "Debe Seleccionar un Motivo para Excluir" }); return; } Cuentas = ObtenerSeleccionados("pnlPeCuentas").select("idCuenta"); if (Cuentas.length == 0) { Mensaje({ mensaje: "Debe Seleccionar Cuentas Excluir" }); return; } LlamarServicio(_Exclusiones_ins, "Exclusiones_inss", { idOperador: idOp(), Cuentas: Cuentas, idMotivo: Motivo }); } function ExcluirMetasPersona() { var Motivo = $("#cboExclusionMotivo").val(); if (Motivo == "") { Mensaje({ mensaje: "Debe Seleccionar un Motivo para Excluir" }); return; } LlamarServicio(_Exclusiones_ins, "Exclusiones_ins", { idOperador: idOp(), idPersona: idP(), idMotivo: Motivo }); } function _Exclusiones_ins(msg) { Mensaje({ mensaje: msg.d }); } function CargarPersonaContacto(idPersonaContacto) { if (idPersonaContacto != 0) { LlamarServicio(_PersonaContacto_sel, "PersonaContacto_sel", { idPersonaContacto: idPersonaContacto }) } } function _PersonaContacto_sel(msg) { MostrarPersonaContacto(msg.d); } function MostrarPersonaContacto(PersonaContacto) { var lstPC = $("#lstPeContactos"); var div = document.createElement("div"); $(div).addClass("Contacto"); var div1 = document.createElement("div"); $(div1).addClass("Nombre"); $(div1).text(PersonaContacto.Nombre); div.appendChild(div1); var div2 = document.createElement("div"); $(div2).addClass("Cargo"); $(div2).text(PersonaContacto.Cargo); div.appendChild(div2); var div3 = document.createElement("div"); $(div3).addClass("Correo"); $(div3).text(PersonaContacto.Correo); div.appendChild(div3); var div4 = document.createElement("div"); $(div4).addClass("Telefonos"); for (j = 0; j < PersonaContacto.Telefonos.length; j++) { var Telefono = PersonaContacto.Telefonos[j]; if (Telefono == undefined) break; InsertarTelefono(Telefono, div4); } div.appendChild(div4); var btn = document.createElement("input"); btn.type = "Button"; $(btn).addClass("btnEliminar32"); btn.onclick = new Function("EliminarPersonasContacto(" + PersonaContacto.idPersonaContacto + ");"); btn.title = "Eliminar Persona Contacto"; div.appendChild(btn); lstPC[0].appendChild(div); lstPC[0].appendChild(document.createElement("HR")); } //Para actualizar la lista de telefenos una vez eliminado function RemoverTelefono(idTelefono) { var div = $("#" + idTelefono)[0]; div.parentNode.removeChild(div); var i = lstTelefonos.indexOf(lstTelefonos.where(function (a) { return a.idTelefono == idTelefono })[0]); lstTelefonos.splice(i, 1); } function Adjuntar() { Emergente({ url: "/Emergentes/ctrlSubirSoportes.aspx", width: 300, height: 200 }); } function AgregarAdjunto(Archivo) { var div = document.createElement("DIV"); div.onclick = function () { var Archivo = $(this).text(); this.parentNode.removeChild(this); for (var i = 0; i < lstAdjuntos.length; i++) { var Parte = lstAdjuntos[i].substr(pos + 1); if (Parte == Archivo) { a.splice(i); break; } } }; var pos = Archivo.indexOf("_"); $(div).text(Archivo.substr(pos + 1)); div.className = "Telefono"; lstAdjuntos.push(Archivo); $("#Adjuntos")[0].appendChild(div); } function LimpiarAdjuntos() { lstAdjuntos = []; $("#Adjuntos").html(""); } function Seleccionar(idPersona) { window.parent.Persona_Mostrar(idPersona); } function ConfirmarGestionGrupoEmpresa() { var Status = $("#cboGestStatus option:selected").html(); Preguntar({ mensaje: "La gestión se guardara con el Status: " + Status + ", ¿Esta seguro?", funcion: GuardarGestionGrupoEmpresa }); } function GuardarGestionGrupoEmpresa() { var tablaCuenta = $("#pnlPeCuentas")[0].getElementsByTagName("table")[0]; var campos = obtenerCampos(tablaCuenta); var colIdCuenta = $.inArray("idCuenta", campos); var lstCuentas = Array(); elem = tablaCuenta.getElementsByTagName("tr"); for (i = 1; i < elem.length; i++) { try { var checkBox = elem[i].getElementsByTagName("td")[colIdCuenta].getElementsByTagName("input")[0]; if (checkBox.checked) { lstCuentas.push($(checkBox).val()); } } catch (ex) { } } var rtGestion = {}; rtGestion.idOperador = idOpL(); rtGestion.idPersona = $("#idPersona").val(); rtGestion.idStatus = $('#cboGestStatus').find(":selected").val(); idUltimoStatus = rtGestion.idStatus; rtGestion.Descripcion = $("#txtGestDescripcion").val(); rtGestion.Cuentas = lstCuentas; if (rtGestion.idStatus == 0) { Mensaje({ mensaje: "No ha seleccionado un status" }); return; } lstCuentas2 = ObtenerSeleccionados("pnlPeCuentas").select("idCuenta"); if (lstCuentas.length == 0 && elem.length > 2) { // Mensaje({ mensaje: "No hay facturas seleccionadas, ¿Desea continuar?", titulo: "Guardando gestión", buttons: { Aceptar: function () { Gestion_ins(_Gestion_ins, rtGestion); $(this).dialog("close"); }, Cancelar: function () { $(this).dialog("close"); } } }); Mensaje({ mensaje: "No ha seleccionado ninguna factura, No Puede Guardar la gestión", titulo: "Guardando gestión" }); return } //Gestion_ins(_Gestion_ins, rtGestion);RA LlamarServicio(_GestionGupoEmpresa_ins, "GestionGupoEmpresa_ins", { Gestion: rtGestion, Adjuntos: lstAdjuntos }); } function _GestionGupoEmpresa_ins(msg) { var resp = msg.d; if (resp == false) { Mensaje({ mensaje: Recursos["ErrorManagement"] }); } else { if (AvisosPropios.length > 0) { LlamarServicio(_Avisos_del, "Avisos_del", { Avisos: AvisosPropios, Comentario: $("#txtGestDescripcion").val() }); } //RefrescarPersona(); $("#txtGestDescripcion").val(""); $("#cboGestStatus option:first").attr('selected', 'selected'); // Mensaje({ mensaje: "La gestión se guardó correctamente" }); Preguntar({ mensaje: "La gestión se guardó correctamente, ¿Desea gestionar a otra persona?", funcion: FinalizarGestion }); //Cartera_lst(_Cartera_lst, idOp(), idOpL() != idOp()); /*Warning*/RA //LlamarServicio(_Cartera_lst, "Cartera_lst", { idOperador: idOp(), Supervisado: idOpL() != idOp() }); RefrescarGestiones() try { for (var i = 0; i < Cartera.length; i++) { var ItemCartera = Cartera[i].Personas.where(function (a) { return a.idPersona == idP(); })[0]; if (ItemCartera == undefined) break; ItemCartera.FechaUltimaGestion = (new Date()).ToString("JSON"); var Status = lstStatus.where(function (a) { return a.idStatus == idUltimoStatus; }); ItemCartera.StatusUltimaGestion = Status[0].Nombre; ItemCartera.TipoStatus = Status[0].Tipo; } _Cartera_lst({ d: Cartera }); } catch (e) { ActualizarCartera(); } LimpiarAdjuntos(); } }
/** * Created by Chen Zhiqiang on 2015/9/28 * 瀑布流 * * 使用: * var f = new WaterFail(el, opt); * f.updateLayout(elements); * elements: 类型:Array * 需要插入的元素(html元素,不是jquery元素),; * f.reset(); 瀑布流重置,清空元素 * f.reLayout(); 重新排列已有元素 */ define(function (require, exports, module) { var checkScrollTimeId, waterFailLayoutTimeId, oBoxesHeights = []; /** * @param el 瀑布流容器,html元素,**必填 * @param opt 配置 * perWidth: 每列宽度,**必填 * knownHeight: 图片高度是否已知 * onScrollEnd: 滚到最底部的回调函数 * onComplete: 瀑布流执行结束的回调函数 * @constructor */ var WaterFail = function (el, opt) { this.el = el; this.options = opt; this.imgLoadingNum = 0; this.init(); return this; }; WaterFail.prototype.updateLayout = function (arr) { var self = this; self.loadingImgs = arr; self.imgLoadingNum = arr.length; this.removeScroll(); if (this.options.knownHeight) { this.layoutByKnownHeight(arr); } else { this.layoutByNoHeight(arr); } }; WaterFail.prototype.updateChildLayout = function(){ var _arr = this.el.childNodes; for (var i = 0; i < _arr.length; i++) { this.updateElementLayout(_arr[i]); } this.el.style.height = Math.max.apply(null, oBoxesHeights) + "px"; }; WaterFail.prototype.init = function () { this.initStyle(); this.addImageListener(); this.setupScroll(); this.initData(); }; WaterFail.prototype.initStyle = function () { this.el.className = this.el.className + " waterfail-container clearfix"; this.el.style.position = "relative"; this.el.style.overflow = "hidden"; }; WaterFail.prototype.initData = function () { var len = Math.floor(this.el.offsetWidth / this.options.perWidth); oBoxesHeights = []; for (var i = 0; i < len; i++) { oBoxesHeights.push(0); } this.imgLoadingNum = 0; this.loadingImgs = []; }; WaterFail.prototype.addImageListener = function () { var self = this; window.imgOnLoad = function () { self.imgLoadingNum--; if (self.imgLoadingNum == 0) { clearTimeout(waterFailLayoutTimeId); self.loadImgsComplete(); } }; window.imgOnError = function () { self.imgLoadingNum--; if (self.imgLoadingNum == 0) { clearTimeout(waterFailLayoutTimeId); self.loadImgsComplete(); } }; }; WaterFail.prototype.setupScroll = function () { var self = this; window.onscroll = function () { clearTimeout(checkScrollTimeId); checkScrollTimeId = setTimeout(function () { if (checkScrollSide(self.el)) { if (self.options.onScrollEnd) { self.options.onScrollEnd(); } } }, 500); }; }; WaterFail.prototype.removeScroll = function () { window.onscroll = null; }; WaterFail.prototype.layoutByKnownHeight = function (arr) { var self = this; for (var i = 0; i < arr.length; i++) { self.appendElement(arr[i]); } this.el.style.height = Math.max.apply(null, oBoxesHeights) + "px"; this.setupScroll(); this.options.onComplete && this.options.onComplete(); }; WaterFail.prototype.layoutByNoHeight = function (arr) { var self = this; for (var j = 0; j < arr.length; j++) { self.el.appendChild(arr[j]); var img = arr[j].getElementsByTagName("img")[0]; img.setAttribute("onload", "imgOnLoad()"); img.setAttribute("onerror", "imgOnError()"); } clearTimeout(waterFailLayoutTimeId); waterFailLayoutTimeId = setTimeout(function () { self.loadImgsComplete(); }, arr.length * 3 * 1000); }; WaterFail.prototype.loadImgsComplete = function () { for (var k = 0; k < this.loadingImgs.length; k++) { this.appendElement(this.loadingImgs[k]); } this.el.style.height = Math.max.apply(null, oBoxesHeights) + "px"; this.setupScroll(); this.options.onComplete && this.options.onComplete(); }; WaterFail.prototype.appendElement = function (ele) { var min = getMinByArray(oBoxesHeights); ele.style.float = "left"; ele.style.position = "absolute"; ele.style.left = this.options.perWidth * (min.index % oBoxesHeights.length) + "px"; ele.style.top = min.data + "px"; this.el.appendChild(ele); oBoxesHeights[min.index] += ele.offsetHeight; }; WaterFail.prototype.updateElementLayout = function(ele){ var min = getMinByArray(oBoxesHeights); ele.style.float = "left"; ele.style.position = "absolute"; ele.style.left = this.options.perWidth * (min.index % oBoxesHeights.length) + "px"; ele.style.top = min.data + "px"; oBoxesHeights[min.index] += ele.offsetHeight; }; WaterFail.prototype.reset = function(){ this.el.innerHTML = ""; this.el.style.height = "0px"; this.initData(); }; WaterFail.prototype.reLayout = function(){ this.initData(); this.updateChildLayout(); }; function getMinByArray(arr) { var idx = 0, temp = arr[0]; for (var i = 0; i < arr.length; i++) { if (temp > arr[i]) { temp = arr[i]; idx = i; } } return { index: idx, data: temp } } function checkScrollSide(ele) { var lastPinH = ele.offsetTop + Math.floor(ele.offsetHeight); var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; var documentH = document.documentElement.clientHeight; return (lastPinH < scrollTop + documentH + 100) ? true : false; } module.exports = WaterFail; });
import React from 'react'; import ArticuloForm from '../ArticuloForm'; class ArticulosEditPage extends React.Component { render() { return ( <div className="container"> <h1>Formulario editar articulo</h1> <hr /> <ArticuloForm form="update" /> </div> ); } } export default ArticulosEditPage;
//Make a pretty date time from a timestamp string export const processDateTime = (str) => { var date = new Date(str); return date.toLocaleString(); };
(function() { 'use strict'; function changeLogoLink() { const headerLogo = document.querySelector('div.Header-logoHolder>div>a'); const newUrl = 'https://library.depaul.edu/Pages/default.aspx'; if (headerLogo) { headerLogo.href = newUrl; headerLogo.addEventListener('click', function(e) { this.href = newUrl; e.stopPropagation(); }); } } // Move the collection browse button to just underneath the title document.addEventListener('cdm-collection-landing-page:ready', function(e){ var pageContainer = document.getElementsByClassName('CollectionLanding-maincontentLanding')[0]; var browseButton = document.getElementsByClassName('text-center')[0]; var pageTitle = document.getElementsByClassName('CollectionLanding-aboutCollection')[0]; pageContainer.insertBefore(browseButton,pageTitle.nextSibling); }); document.addEventListener('cdm-home-page:ready', changeLogoLink); document.addEventListener('cdm-about-page:ready', changeLogoLink); document.addEventListener('cdm-login-page:ready', changeLogoLink); document.addEventListener('cdm-search-page:ready', changeLogoLink); document.addEventListener('cdm-collection-page:ready', changeLogoLink); document.addEventListener('cdm-advanced-search-page:ready', changeLogoLink); document.addEventListener('cdm-item-page:ready', changeLogoLink); document.addEventListener('cdm-custom-page:ready', changeLogoLink); })();
function solve(fieldInput, bombInput){ let bombNumber = bombInput[0]; let bombPower = bombInput[1]; let field = fieldInput; let leftBombSideIndex = 0; for (let i = 0; i < field.length; i++) { if(isABomb(bombNumber, field, i)){ let indexOfBomb = field.indexOf(bombNumber); if(isInFieldFromLeftSide(indexOfBomb, bombPower)){ leftBombSideIndex = indexOfBomb - bombPower; } if(isInFieldFromRightSide(indexOfBomb, field, bombPower)){ if(!isInFieldFromLeftSide(indexOfBomb, bombPower)){ field.splice(leftBombSideIndex, bombPower + 1); }else{ field.splice(leftBombSideIndex, bombPower * 2 + 1, 0); } continue; } field.splice(leftBombSideIndex) } } console.log(sumNumbers(field)); function sumNumbers(arr){ let sum = 0; for (let i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } function isABomb(bombNumber, field, i){ return bombNumber === field[i]; } function isInFieldFromLeftSide(number, bombPower){ return number - bombPower >= 0; } function isInFieldFromRightSide(number, field, bombPower){ return number + bombPower < field.length - 1; } } solve([4, 3, 2, 2],[4, 2]);
var view = require("ui/core/view"); var viewModel = require("./mainViewModel"); var page; exports.pageLoaded = function (args){ page = args.object; page.bindingContext = viewModel; viewModel.asd(page.navigationContext.id, page.navigationContext.slika); var imeIPrezTextField = view.getViewById(page, "imeIPrez"); imeIPrezTextField.text = "Ime: " + page.navigationContext.ime + " " + page.navigationContext.prezime; var indexTextField = view.getViewById(page, "index"); indexTextField.text = "Indeks: " + page.navigationContext.index; } exports.navigatedTo = function (args){ //alert(JSON.stringify(context)); }
import axios from 'axios'; import Swal from 'sweetalert2'; import {actualizarAvance} from '../funciones/avance'; const factura = document.querySelector('.listado-facturas'); if(factura){ factura.addEventListener('click', e=>{ //console.log(e.target.classList); if(e.target.classList.contains('fa-check-circle') || e.target.classList.contains('fa-circle')){ const icono=e.target; const idFactura=icono.parentElement.parentElement.parentElement.dataset.factura; const url = `${location.origin}/administrador/ver-facturas/${idFactura}`; axios.patch(url,{ idFactura }) .then(function(respuesta){ if(respuesta.status===200){ icono.classList.toggle('pagado'); icono.classList.toggle('fa-circle') actualizarAvance(); } icono.classList.toggle('fa-check-circle') }) } if(e.target.classList.contains('fa-trash')){ const facturaHTML = e.target.parentElement.parentElement.parentElement, idFactura = facturaHTML.dataset.factura; Swal.fire({ title: '¿Estás seguro de eliminar esta factura?', text: "Si se elimina se pierde la factura", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Si', cancelButtonText: 'Cancelar', }).then((result) => { if (result.value) { const url = `${location.origin}/administrador/ver-facturas/${idFactura}`; axios.delete(url,{params:{idFactura}}) .then(function(respuesta){ if(respuesta.status===200){ facturaHTML.parentElement.removeChild(facturaHTML); console.log(facturaHTML); console.log("Entro"); Swal.fire( 'factura eliminada', respuesta.data, 'success' ); actualizarAvance(); } }) } }) } }); } export default factura;
function createPlanit() { historyUpdate(createPlanit, arguments); $.ajax({ url: '/types/planit_types', method: 'get' }).done(function(types) { appvars.planit_types = types.planit_types var data = { planit_types: appvars.planit_types, title: 'Create a planit (event)', states: appvars.states, startDate: formatDateInput(Date.now()), endDate: formatDateInput(Date.now()) }; displayTemplate('main', 'planitupdate', data); // addFormSubmitListener(); }); } function createPlanitPost(event) { if (event) event.preventDefault(); validatePlanitForm(function() { var formData = getFormData('form'); $.ajax({ url: '/planits', method: 'post', data: formData, xhrFields: { withCredentials: true } }).done(function(data) { // $('#errorMessage').hide(); viewPlanit(data.planits[0].id); }).fail(function(err) { // $('.error-message').text('Enter all fields.') // customAlert('All fields must be filled out in order to create a planit'); }); }); } function listPlanits(memberId) { var url = memberId ? '/members/' + memberId + '/planits' : '/planits'; historyUpdate(listPlanits, arguments); $.ajax({ url: url, method: 'get' }).done(function(data) { data.user = appvars.user; data.planits.forEach(function(planit) { planit.startDate = formatDateShort(planit.start_date); planit.endDate = formatDateShort(planit.end_date); }); displayTemplate('main', 'planits', data); }); } function viewPlanit(id) { historyUpdate(viewPlanit, arguments); $.ajax({ url: '/planits/' + id, method: 'get' }).done(function(planits) { appvars.planit = planits.planits[0]; appvars.planit.startDate = formatDateLong(appvars.planit.start_date); appvars.planit.endDate = formatDateLong(appvars.planit.end_date); planits.tasks.forEach(function(task) { task.formattedTime = formatDateTimeShort(task.start_time); }); data = { planit: appvars.planit, tasks: planits.tasks, user: appvars.user, editable: appvars.user && (appvars.user.id == planits.planits[0].member_id || appvars.user.role_name == 'admin'), deletable: appvars.user && (appvars.user.id == planits.planits[0].member_id || appvars.user.role_name !== 'normal'), formattedCurrency: formatCurrency(appvars.planit.budget) }; displayTemplate('main', 'planit', data); }); } function updatePlanit(id) { historyUpdate(updatePlanit, arguments); Promise.all([ $.ajax({ url: '/planits/' + id, method: 'get' }), $.ajax({ url: '/types/planit_types', method: 'get' }) ]).then(function(data) { appvars.planit_types = data[1].planit_types; var planit = data[0].planits[0]; var data = { planit: planit, planit_types: data[1].planit_types, title: 'planit Update', update: true, states: appvars.states, category: findBy(appvars.planit_types, 'id', planit.planit_type_id).name, startDate: formatDateInput(planit.start_date), endDate: formatDateInput(planit.end_date) }; displayTemplate('main', 'planitupdate', data); }); } function updatePlanitPut(event, id) { if (event) event.preventDefault(); validatePlanitForm(function() { var formData = getFormData('form'); // console.log(formData); $.ajax({ url: '/planits/' + id, method: 'put', data: formData, xhrFields: { withCredentials: true } }).done(function(data) { viewPlanit(id); }); }); } function deletePlanit(id) { customConfirm('Are you sure you want to delete this planit?', function() { $.ajax({ url: '/planits/' + id, method: 'delete', xhrFields: { withCredentials: true } }).done(function(data) { listPlanits(); }); }); } function selectState(id) { $('.planit-state').val(appvars.states[id]); $('.ben-will-murder-you-if-remove-this-class-state').html(appvars.states[id] + '<span class="caret"></span>'); } function selectPlanitType(id) { $('.planit-type').val(id); var planitType = findBy(appvars.planit_types, 'id', id).name; $('.ben-will-murder-you-if-remove-this-class-category').html(planitType + '<span class="caret"></span>'); }
import React, {Component} from 'react'; import { StyleSheet, Text, ImageBackground, Image, View } from 'react-native'; import Quote from "../components/Quote"; const quotes = require('../../quotes.json'); const bg = require('../../assets/images/bg.jpg'); import Swiper from 'react-native-swiper'; class QuoteScreen extends Component { render() { const quote = quotes['quotes'][2]; return ( <Swiper style={styles.container}> <View style={styles.slider}> <Quote text={quotes['quotes'][0].quoteText} author={quotes['quotes'][0].quoteAuthor}/> <Image source={bg} style={styles.backgroundContainer}/> </View> <View style={styles.slider}> <Image source={bg} style={styles.backgroundContainer}/> <Quote text={quotes['quotes'][1].quoteText} author={quotes['quotes'][1].quoteAuthor}/> </View> <View style={styles.slider}> <Image source={bg} style={styles.backgroundContainer}/> <Quote text={quotes['quotes'][2].quoteText} author={quotes['quotes'][2].quoteAuthor}/> </View> <View style={styles.slider}> <Image source={bg} style={styles.backgroundContainer}/> <Quote text={quotes['quotes'][3].quoteText} author={quotes['quotes'][3].quoteAuthor}/> </View> <View style={styles.slider}> <Image source={bg} style={styles.backgroundContainer}/> <Quote text={quotes['quotes'][4].quoteText} author={quotes['quotes'][4].quoteAuthor}/> </View> </Swiper> ) } } const styles = StyleSheet.create({ container: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, justifyContent: 'center', alignItems: 'center', }, slider: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#6dd4e5', }, backgroundContainer: { resizeMode: 'cover', width: undefined, height: undefined, }, }); export default QuoteScreen;
/** * Created by kimsungwoo on 2015. 10. 6.. */
//function* //итераторы предоставляют средства для доступа к элементам коллекций по одному за раз //генераторы работаю как фабрики итераторов //генераторы могут порождать множество значений //метод next() возращает след. элемент, //возращает объект со свойством value: и свойством done: //которое указывает ,что генератор уже отдал свое значение(true, false) 'use strict'; function* genMarkers() { yield 1; yield 2; yield 3; } const it = genMarkers(); console.log(it.next().value); //1 console.log(it.next().value); //2 console.log(it.next().value); //3 const number = { from: 1, to: 8, *[Symbol.iterator]() { //or [Symbol.iterator]: function*() for(let value = this.from; value <= this.to; value++) { yield value; } } }; console.log([...number]); function* generateNum() { yield 1; yield 2; yield 5; } let generatorF = generateNum(); for(let value of generatorF) { console.log(value); } //array let generatorS = [0,...generateNum()]; console.log(generatorS); 'use strict'; function* Blabla(start, end, delta) { let value = start; while(end > value) { value += delta; //if (value > end) return; // (проверка)done:false для 7-35, дальше value: undefined done:true yield value; } } const a = Blabla(0, 36, 7); const c1 = a.next(); const c2 = a.next(); const c3 = a.next(); const c4 = a.next(); const c5 = a.next(); const c6 = a.next(); const c7 = a.next(); //done:true итерирование закончилось console.log({a, c1, c2, c3, c4, c5, c6, c7}); //yield* // композиця генераторов - "встраивание" генераторов друг в друга function* genSec(start, end) { for(let i = start; i <= end; i++) yield i; } function* generatePassw() { yield* genSec(48, 57); yield* genSec(65, 90); } let str = ''; for(let code of generatePassw()) { str += String.fromCharCode(code); } console.log(str); 'use strict'; function* genFn() { yield* ["Черепашка","по имени" ,"Наташка" ]; // итерируем массив // yield* new Set([10, 20, 30]) //тоже самое } const c = genFn(); const val1 = c.next(); const val2 = c.next(); const val3 = c.next(); const val4 = c.next(); console.log({c, val1, val2, val3, val4}); 'use strict'; function* gen1() { yield 'Ходит кошка в коридоре'; yield 'У неё большое горе'; } function* gen2() { yield 'Злые люди бедной киске'; yield 'Не дают украсть сосиски'; } function* genFn1() { yield* gen1(); yield* gen2(); } console.log('[...genFn1()] =', [...genFn1()]); //ненужные методы return и throw //.throw генерирует ошибку 'use strict'; function* genFn5() { yield 10; } { const g = genFn5(); const g1 = g.next(); const g2 = g.return(20); // done:true const g3 = g.next(); const g4 = g.return(30); // done: true console.log({g1, g2, g3, g4}); }
const User = require('../models/User') const bcrypt = require('bcrypt') const jwt = require('jsonwebtoken') const validateRegisteration = require('../validation/register') const validateLogin = require('../validation/login') const sgMail = require('@sendgrid/mail'); // Registeration exports.register = (req, res) => { const { errors, isValid } = validateRegisteration(req.body); if (!isValid) { return res.status(400).json(errors); } User.findOne({ email: req.body.email }).then(user => { if (user) { errors.email = "Email already exist !!"; return res.status(400).json(errors); } else { const newUser = new User({ name: req.body.name, email: req.body.email, password: req.body.password }); bcrypt.genSalt(10, (err, salt) => { bcrypt.hash(newUser.password, salt, (err, hash) => { if (err) throw err; newUser.password = hash; newUser .save() .then(user => { const payload = { id: user.id, email: user.email, name: user.name }; jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: 3600 * 24}, (err, token) => { res.json({ success: true, token: "Bearer " + token, name: user.name, userId: user.id }); }); }) .catch(err => console.log(err)); }); }); } }); } // Login exports.Login = (req, res) => { const { errors, isValid } = validateLogin(req.body); if (!isValid) { return res.status(400).json(errors); } const { email, password } = req.body User.findOne({ email }).then(user => { if (!user) { errors.email = "User does not exist !!"; return res.status(400).json(errors); } bcrypt.compare(password, user.password).then(isMatch => { if (isMatch) { const payload = { id: user.id, email: user.email, name: user.name }; jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: 3600 * 24}, (err, token) => { res.json({ success: true, token: "Bearer " + token, name: user.name, userId: user.id }); }); } else { errors.password = "Incorrect password"; return res.status(400).json(errors); } }); }); } // forget password : generate a link and send it by email exports.ForgetPassword = async (req, res) => { const { email } = req.body const user = await User.findOne({ email }); if (!user) { return res.status(400).json({ msg: 'user email not found!!' }) } const payload = { id: user.id, iat: Date.now() }; const token = jwt.sign(payload, process.env.JWT_RESET_SECRET); user.passwordResetToken = token; user.passwordChangedAt = Date.now() + 60 * 1000 * 60 // expired after one hour await user.save(); const resetUrl = `${req.protocol}://localhost:3000/resetPassword/${token}`; const resetMessage = `Forgot your password? Click on the link and submit your new password and password confirmation to ${resetUrl} \n \n if you did not reset your password. Kindly ignore this email`; sgMail.setApiKey(process.env.SENDGRID_API_KEY) const msg = { to: user.email, from: 'a.alghetheth@gmail.com', subject: 'Your password reset Link valid only for 60 minutes ', text: resetMessage } sgMail .send(msg) .then(() => { console.log('Email Successfully sent!') res.json('Email Successfully sent.') }) .catch(err => console.log(err)) } // forget password : compare the token exports.CompareToken = async (req, res) => { /* res.json(req.params.token) */ const token = req.params.token; try { const user = await User.findOne({ passwordResetToken: token }); if (user) { jwt.verify(user.passwordResetToken, process.env.JWT_RESET_SECRET, (err, decode) => { console.log(decode) User.findById(decode.id, function (err, user) { if (err) { return res.status(500).send("An unexpected error occurred"); } if (!user) { return res.status(404).send({ message: `We were unable to find a user for this token.` }); } const id = decode.id return res.json({ msg: 'token is correct', token, id }) }) }) } else { res.status(500).json({ msg: 'invalid token or maybe your token expired!!' }) } } catch (error) { res.status(500).json({ msg: 'server error !!' }) } } // change the password in the database exports.ResetPassword = (req, res) => { const id = req.params.id User.findById(id, function (err, user) { bcrypt.genSalt(10, (err, salt) => { console.log(req.body.password) bcrypt.hash(req.body.password, salt, (err, hash) => { if (err) throw err; console.log(user.password, " password2") User.findByIdAndUpdate(id, { password: hash, passwordResetToken: "" }, (err, user) => { // Send mail confirming password change to the user const msg = { to: user.email, from: 'a.alghetheth@gmail.com', subject: "Your password has been changed", html: `<p>This is a confirmation that the password for your account ${user.email} has just been changed. </p>`, }; sgMail.send(msg) .then(() => { res.json('successfully changed the password') }) .catch(() => { return res.status(503).send({ message: `Can not send an email to ${user.email}, try again!!.`, }); }); }) }) }) }) } // user Profile details exports.ProfileDetails = async (req, res) => { //get user info from User db const user = await User.findById(req.params.id); //send user obj backto front end if there is user if (user) { res.json(user); } else { res.status(404).json({ message: 'User Not Found' }); } } // update profile exports.UpdateProfile = async (req, res) => { const user = await User.findById(req.user._id); if (user) { user.name = req.body.name || user.name; user.email = req.body.email || user.email; if (req.body.password) { user.password = bcrypt.hashSync(req.body.password, 10); } const updatedUser = await user.save(); res.json({ _id: updatedUser._id, name: updatedUser.name, email: updatedUser.email, password: updatedUser.password }); } } // details exports.Details = async (req, res) => { const user = await User.findById(req.params.id); if (user) { res.json(user); } else { res.status(404).json({ message: 'User Not Found' }); } }
import React from "react"; import './Header.css' const Header = () => ( <div className="title"> CHATS <div className="push"> <img className="push__image" src="https://cdn4.vectorstock.com/i/1000x1000/58/48/new-chat-message-notification-icon-vector-22615848.jpg" alt="Push Notification"/> </div> </div> ) export default Header
'use strict'; /** * @ngdoc function * @name dssiFrontApp.controller:ChecklistItemCreateCtrl * @description * # ChecklistItemCreateCtrl * Controller of the dssiFrontApp */ angular.module('dssiFrontApp') .controller('ChecklistItemCreateCtrl', function (ChecklistItem, $scope, ChecklistItemGroup, $localStorage, $uibModal, notificationService) { var vm = this; // Set scope to modal $scope = $scope.$parent || $scope; vm.checklistItem = new ChecklistItem({ checklist_id: $scope.$parent.checklist.id || null, checklist_item_group_id: null, status: false }); vm.checklistItemGroups = $scope.$parent.checklistItemGroups || ChecklistItemGroup.query({ property_id: $localStorage.property_id }); // Replace method from parent ModalDefaultCtrl var parentClose = $scope.close; $scope.ok = ok; $scope.formSubmit = formSubmit; //////////// function saveChecklistItem(checklistItem){ checklistItem.$save().then(function(){ notificationService.success('¡Guardado!'); parentClose(); }, function(){ notificationService.error('No ha sido posible atender la solicitud.'); }); } function ok(){ saveChecklistItem(vm.checklistItem); } function formSubmit(){ saveChecklistItem(vm.checklistItem); } });
import React from "react"; import axios from "./axios"; export default class JobBoard extends React.Component { constructor() { super(); this.state = {}; } componentDidMount() { axios.get("/jobs.json").then(resp => { this.setState({ jobs: resp.data.results }); }); } render() { if (!this.state.jobs) { return null; } const jobsList = this.state.jobs.map(job => ( <div className="jobBoard" key={job.id}> <h3>{job.job_title}</h3> <p>{job.description}</p> <p>{job.location}</p> <p>{job.contact}</p> </div> )); return ( <div> <h2 id="titleInjobs">Jobs of the Week</h2> {jobsList} </div> ); } }
let text = "String"; document.write(typeof text); document.write("<br>"); text = 55; document.write(typeof text); document.write("<br>"); text = true; document.write(typeof text); document.write("<br>"); text = null; document.write(typeof text);
var start = 0; var pageSize = 10; var pulpaselect = -1; var apikalselect = -1; var behandlingselect = -1; var otherDiagnosesselect = -1; var facetsSelected = -1; var firstIndex = 0; var secondIndex = 1; var elasticResult = null; function initialize() { $(document).ready(function () { // do jQuery }); document.getElementById("facetselect").selectedIndex = 0; start = 0; initFillBoxes(); } function lookup() { var q = ""; var delimiter = ""; var obj = JsonTool.createJsonPath("query"); var d = JSON.parse("{\"must\":[]}"); obj.query.bool = d; if (document.getElementById("facetsSelected").selectedIndex != -1) { var f = new Object(); var o = new Object(); f[document.getElementById("facetselect").value] = document.getElementById("facetsSelected").value; o.match = f; obj.query.bool.must.push(o); } if (document.getElementById("pulpaselect").selectedIndex != -1) { var f = new Object(); var o = new Object(); f.pulpalDiagnoses = document.getElementById("pulpaselect").value; o.match = f; obj.query.bool.must.push(o); } if (document.getElementById("apikalselect").selectedIndex != -1) { var f = new Object(); var o = new Object(); f.apicalDiagnoses = document.getElementById("apikalselect").value; o.match = f; obj.query.bool.must.push(o); } if (document.getElementById("behandlingselect").selectedIndex != -1) { var f = new Object(); var o = new Object(); f.typeOfTreatment = document.getElementById("behandlingselect").value; o.match = f; obj.query.bool.must.push(o); } if (document.getElementById("otherDiagnosesselect").selectedIndex != -1) { var f = new Object(); var o = new Object(); f.otherDiagnoses = document.getElementById("otherDiagnosesselect").value; o.match = f; obj.query.bool.must.push(o); } return obj; } function encodeValue(str) { return str.replace("+", "%2B"); } function makeSearch() { var query = lookup(); var url = "http://itfds-prod03.uio.no/elasticapi/odontologi/odontCase/_search"; query.from = start; $.ajax({ url: url, type: 'POST', data: query, dataType: "json", error: function (XMLHttpRequest, textStatus, errorThrown) { alert('status:' + XMLHttpRequest.status + ', status text: ' + XMLHttpRequest.statusText + " errorthrown " + errorThrown); return; }, success: function (data) { elasticResult = new ElasticClass(data); if (elasticResult.getDocCount() == 0) { document.getElementById("bla").innerHTML = "<h5 style='color:red'>No documents match the query - click t.ex Reset</h5>"; document.getElementById("testtable").innerHTML = ""; } else fillPortal(); } }); } function setZero() { document.getElementById("pulpaselect").selectedIndex = -1; pulpaselect = -1; document.getElementById("apikalselect").selectedIndex = -1; apikalselect = -1; document.getElementById("behandlingselect").selectedIndex = -1; behandlingselect = -1; document.getElementById("facetsSelected").selectedIndex = -1; document.getElementById("otherDiagnosesselect").selectedIndex = -1; otherDiagnosesselect = -1; facetsSelected = -1; start = 0; makeSearch(); } function initFillBoxes() { var url = "http://itfds-prod03.uio.no/elasticapi/odontologi/odontCase/_search"; var temp = 0; $.ajax({ url: url, type: 'POST', data: aggs, dataType: "json", error: function (XMLHttpRequest, textStatus, errorThrown) { alert('status:' + XMLHttpRequest.status + ', status text: ' + XMLHttpRequest.statusText + " errorthrown " + errorThrown); return; }, success: function (data) { var el = new ElasticClass(data); var pulpal = el.getFacetFieldWithFacetName("pulpal"); var sel = document.getElementById('pulpaselect'); for (temp = 0; temp < pulpal.length; temp++) Tools.addOption(sel, pulpal[temp].key, pulpal[temp].key); var apical = el.getFacetFieldWithFacetName("apical"); sel = document.getElementById('apikalselect'); for (temp = 0; temp < apical.length; temp++) Tools.addOption(sel, apical[temp].key, apical[temp].key); var typeOfTreatment = el.getFacetFieldWithFacetName("typeOfTreatment"); sel = document.getElementById('behandlingselect'); for (temp = 0; temp < apical.length; temp++) Tools.addOption(sel, typeOfTreatment[temp].key, typeOfTreatment[temp].key); var otherDiagnoses = el.getFacetFieldWithFacetName("otherDiagnoses"); sel = document.getElementById('otherDiagnosesselect'); for (temp = 0; temp < otherDiagnoses.length; temp++) Tools.addOption(sel, otherDiagnoses[temp].key, otherDiagnoses[temp].key); makeSearch(); } }); } // "field": "pulpalDiagnoses", function fillFacet() { Tools.removeAllOptions("facetsSelected"); if (document.getElementById('facetselect').selectedIndex == 0) { start = 0; makeSearch(); return; } selectAgg.aggs.agg.terms.field = document.getElementById('facetselect').value; var url = "http://itfds-prod03.uio.no/elasticapi/odontologi/odontCase/_search"; var temp = 0; $.ajax({ url: url, type: 'POST', data: selectAgg, dataType: "json", error: function (XMLHttpRequest, textStatus, errorThrown) { alert('status:' + XMLHttpRequest.status + ', status text: ' + XMLHttpRequest.statusText + " errorthrown " + errorThrown); return; }, success: function (data) { var el = new ElasticClass(data); var agg = el.getFacetFieldWithFacetName("agg"); var sel = document.getElementById('facetsSelected'); for (temp = 0; temp < agg.length; temp++) { Tools.addOption(sel, agg[temp].key, agg[temp].key); } facetsSelected = -1; /* start=0; makeSearch();*/ hideEmptySelectBoxes(); } }); var q = "q=*:*&wt=json&facet=true&facet.field=" + document.getElementById('facetselect').value + "&facet.limit=400&facet.sort=false&facet.mincount=0&rows=0&"; //search } function isNextPage() { if ((start + pageSize) < elasticResult.getDocCount()) return true; } function isPrevPage() { if (start > 0) return true; } function nextAndPreviousButtons() { var form2 = ""; form2 = "<form method='get' name='moveForm' accept-charset='UTF-8' >"; form2 += "<table class='tableClass' border='0' cellpadding='2' cellspacing='2'>"; form2 += "<tr><td colspan='1' style='text-align: left; height: 40px'>"; if (isNextPage() || isPrevPage()) { if (isPrevPage()) { var s = start - pageSize; form2 += "<input type='button' class='forrige_neste' value='Previous' "; form2 += " onclick='move(" + s + ")'/> "; } if (isNextPage()) { var s = start + pageSize; form2 += "<input type='button' class='forrige_neste' value='Next' "; form2 += " onclick='move(" + s + ")'/>"; } form2 += " " + getCountLabel(); } return form2; } function move(newStart) { start = newStart; makeSearch(); } function getCountLabel() { var countLabel = ""; if (elasticResult.getDocCount() > 0) { if (start == 0) countLabel = "1"; else countLabel = "" + start; countLabel += "-"; if (isNextPage()) countLabel += (start + pageSize); else countLabel += elasticResult.getDocCount(); countLabel += " of " + elasticResult.getDocCount(); } else { countLabel = "0 posts - search again"; } return countLabel; } function getInternetExplorerVersion() { var rv = -1; // Return value assumes failure. if (navigator.appName == 'Microsoft Internet Explorer') { var ua = navigator.userAgent; var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); if (re.exec(ua) != null) rv = parseFloat(RegExp.$1); } return rv; } function getResultList() { var resultCode = ""; var docs = elasticResult.getDocs(); var pos; var preSpan = "<span style='color:red'>"; var postSpan = "</span>"; var options = document.getElementById('cloneselect').innerHTML; var firstSelect = "<select id='firstSelect' onchange='changeColumn()'>" + options + "</select>"; var secondSelect = "<select id='secondSelect' onchange='changeColumn()'>" + options + "</select>"; resultCode += "<tr class='trResult'><th class='thResult'>Case title</th><th class='thResult'>" + firstSelect + "</th><th class='thResult'>" + secondSelect + "</th><th class='thResult'>PDF document</th></tr>"; for (var temp = 0; temp < docs.length; temp++) { resultCode += "<td class='tdBorder' style='text-align:left'>" + elasticResult.getSingleFieldFromDoc(docs[temp], "caseTitle") + "</td>"; resultCode += "<td class='tdBorder'>" + getColumnValue(docs[temp], document.getElementById("cloneselect").options[firstIndex].value) + "</td>"; resultCode += "<td class='tdBorder'>" + getColumnValue(docs[temp], document.getElementById("cloneselect").options[secondIndex].value) + "</td>"; var year = elasticResult.getSingleFieldFromDoc(docs[temp], "publicationYear"); var str = "<a target='_blank' href='http://nabu.usit.uio.no/odont/kasus/documents/" + year + "/" + elasticResult.getSingleFieldFromDoc(docs[temp], "caseBook") + "_" + elasticResult.getSingleFieldFromDoc(docs[temp], "caseNumber") + ".pdf'><img src='document.png'></a>"; resultCode += "<td class='tdBorder'>" + str + "</td>"; resultCode += "</tr>"; } return resultCode; } function fillPortal() { // alert(nextAndPreviousButtons()); document.getElementById("bla").innerHTML = nextAndPreviousButtons(); document.getElementById("testtable").innerHTML = "<table class='tableClass'>" + getResultList() + "</table>"; document.getElementById("firstSelect").selectedIndex = firstIndex; document.getElementById("secondSelect").selectedIndex = secondIndex; hideEmptySelectBoxes(); } function changeColumn() { firstIndex = document.getElementById("firstSelect").selectedIndex; secondIndex = document.getElementById("secondSelect").selectedIndex; document.getElementById("testtable").innerHTML = "<table class='tableClass'>" + getResultList() + "</table>"; document.getElementById("firstSelect").selectedIndex = firstIndex; document.getElementById("secondSelect").selectedIndex = secondIndex; } function changeClick(selectName) { switch (selectName) { case "pulpaselect": if (pulpaselect == document.getElementById("pulpaselect").selectedIndex) document.getElementById("pulpaselect").selectedIndex = -1; pulpaselect = document.getElementById("pulpaselect").selectedIndex; break; case "apikalselect": if (apikalselect == document.getElementById("apikalselect").selectedIndex) document.getElementById("apikalselect").selectedIndex = -1; apikalselect = document.getElementById("apikalselect").selectedIndex; break; case "behandlingselect": if (behandlingselect == document.getElementById("behandlingselect").selectedIndex) document.getElementById("behandlingselect").selectedIndex = -1; behandlingselect = document.getElementById("behandlingselect").selectedIndex; break; case "facetsSelected": if (facetsSelected == document.getElementById("facetsSelected").selectedIndex) document.getElementById("facetsSelected").selectedIndex = -1; facetsSelected = document.getElementById("facetsSelected").selectedIndex; break; case "otherDiagnosesselect": if (otherDiagnosesselect == document.getElementById("otherDiagnosesselect").selectedIndex) document.getElementById("otherDiagnosesselect").selectedIndex = -1; otherDiagnosesselect = document.getElementById("otherDiagnosesselect").selectedIndex; break; default: break; } start = 0; makeSearch(); } function hideEmptySelectBoxes() { var elements = document.getElementsByTagName('select'); for (var temp = 0; temp < elements.length; temp++) { if (elements[temp].options.length == 0) elements[temp].style.display = 'none'; else elements[temp].style.display = 'inline'; } } function getColumnValue(doc, field) { switch (field) { case 'gender': case 'typeOfTreatment': case 'cbct': case 'preOperativeStatusOfTheTooth': case 'flareUp': case 'biopsy': case 'periodontitis': case 'taper': case 'apicalSize': return elasticResult.getSingleFieldFromDoc(doc, field); // break; case 'disease': case 'medication': case 'quadrant': case 'pulpalDiagnoses': case 'apicalDiagnoses': case 'otherDiagnoses': case 'trauma': case 'symptoms': case 'preOperativeRestoration': case 'dentalAnomaly': case 'iatrogenicErrors': case 'instrumentationTecnique': case 'irrigation': case 'intervisitMedication': case 'numberOfVisits': case 'obturationTechnique': case 'obturationMaterial': case 'workingLength': case 'qualityOfRootFilling': case 'flapDesign': case 'postOpRestoration': var arr = elasticResult.getArrayFromDoc(doc, field); var delim = ""; var str = ""; for (var temp = 0; temp < arr.length; temp++) { str += delim + arr[temp]; delim = ", "; } return str; // break; default: return ""; } } function elastic(body) { var url = "http://itfds-prod03.uio.no/elasticapi/odontologi/odontCase/_search"; $.ajax({ url: url, type: 'POST', data: body, dataType: "json", error: function (XMLHttpRequest, textStatus, errorThrown) { alert('status:' + XMLHttpRequest.status + ', status text: ' + XMLHttpRequest.statusText + " errorthrown " + errorThrown); }, success: function (data) { alert(JSON.stringify(data, null, 2)); return data; } }); }
import React from 'react'; const Testimonial = (props) => { const { quote, name, from, img } = props?.testimonial; return ( <div className="card shadow p-4 ms-3"> <div className="card-body"> <p className="card-text text-justify">{quote}</p> </div> <div className="card-footer d-flex align-items-center"> <img className="mx-3" src={img} alt="" width="60" /> <div> <h6 style={{ color: '#1CC7C1' }}> <strong>{name}</strong> </h6> <p className="m-0">{from}</p> </div> </div> </div> ); }; export default Testimonial;
import { useStoreActions, useStoreState } from 'easy-peasy' import { useEffect } from 'react' import { useParams } from 'react-router-dom' const useOrderDetailHook = () => { const { id } = useParams() const orderDetail = useStoreState((state) => state.orderAdmin.orderDetail) const loadingOrderDetail = useStoreState( (state) => state.orderAdmin.loadingOrderDetail ) const getOrderDetail = useStoreActions( (action) => action.orderAdmin.getOrderDetail ) useEffect(() => { getOrderDetail(id) }, [getOrderDetail, id]) return { orderDetail, loadingOrderDetail } } export default useOrderDetailHook
/** * Set the first letter of each word to uppercase */ const FirstLetterUpperCase = (sentence) => ( sentence .toLowerCase() .split(/ |-/) .filter((str) => str.length > 0) .map((str) => str[0].toUpperCase() + str.slice(1)) .join(' ') ); /** * Set the data structure for Selector in the Compensation Module */ const constructDataForCompensation = (regions) => { const regionsArray = []; const regionsList = []; const statusList = []; Object.keys(regions).forEach((regionKey) => { const regionId = (regionKey === 'null') ? '(REGION SIN ASIGNAR)' : regionKey; const regionLabel = FirstLetterUpperCase(regionId); regionsList.push({ value: regionId, label: regionLabel, }); const region = { id: regionId, label: regionLabel, detailId: 'region', iconOption: 'expand', idLabel: `panel1-${regionLabel.replace(/ /g, '')}`, projectsStates: [], }; Object.keys(regions[regionKey]).forEach((statusKey) => { const statusId = (statusKey === 'null') ? '(ESTADO SIN ASIGNAR)' : statusKey; const statusLabel = (statusId.length > 3) ? FirstLetterUpperCase(statusId) : statusId; if (!statusList.find((st) => st.value === statusId)) { statusList.push({ value: statusId, label: statusLabel, }); } region.projectsStates.push({ id: statusId, label: statusLabel, detailId: 'state', iconOption: 'expand', idLabel: FirstLetterUpperCase(statusLabel).replace(/ /g, ''), projects: regions[regionKey][statusKey].map((project) => ({ id_project: project.gid, name: FirstLetterUpperCase(project.name), state: project.prj_status, region: project.id_region, area: project.area_ha, id_company: project.id_company, project: project.name, type: 'button', label: FirstLetterUpperCase(project.name), })), }); }); regionsArray.push(region); }); const newProject = { id: 'addProject', idLabel: 'panel1-newProject', detailId: 'region', iconOption: 'add', label: '+ Agregar nuevo proyecto', type: 'addProject', }; regionsArray.push(newProject); statusList.push({ value: 'newState', label: 'Agregar estado...', }); return { regionsList, statusList, regions: regionsArray }; }; export default constructDataForCompensation;
module.exports = { // your code here simplePromise:simplePromise, add10Promise:add10Promise, reject:reject, sum50:sum50, } function simplePromise( bool ) { return new Promise( function (resolve, reject) { bool ? resolve('OK') : resolve('BAD'); }) } function add10Promise( value ) { value > 0 ? value += 10 : value = 0 + 10; return new Promise( function (resolve, reject) { resolve(value); }) } function reject( value ) { return new Promise( function ( resolve, reject) { reject( value ); }) } function sum50( value ) { return new Promise( function ( resolve, reject) { resolve( 50 ); }) }
'use strict'; const _ = require('lodash'); const fs = require('fs'); const AwsCloudFormation = require('../aws-raw-services/AwsCloudFormation'); const BackoffUtils = require('../../util/BackoffUtils'); class CloudFormation extends AwsCloudFormation { constructor() { super(); } loadParamsFromCloudFormationTemplates(...filePaths){ let paths = _.flattenDeep(filePaths); let parameters = []; let prom = Promise.resolve(); //loop through all the cloud formation templates and load up all the parameters for(let path of paths) { prom = prom.then(()=>{ return this.retrieveParametersFromFile(path) .then((retrievedParams)=>{ parameters = parameters.concat(retrievedParams); }); }); } return prom.then(()=>{ return parameters; }); } retrieveParametersFromFile(fileUrl){ return Promise.resolve() .then(()=>{ return new Promise((resolve,reject)=>{ fs.readFile(fileUrl,'utf8', (err, data) => { if (err) { reject(err); } else{ resolve(data); } }); }); }) .then((cfTemplate)=>{ return this.retrieveParameters(cfTemplate); }); } retrieveParameters(cfTemplate){ return this.getTemplateSummary( { TemplateBody: cfTemplate }) .then((data)=>{ return data.Parameters; }); } deployTemplateFile(fileUrl,name,params,opts={capabilities:undefined,tags:undefined}){ return Promise.resolve() .then(()=>{ return new Promise((resolve,reject)=>{ fs.readFile(fileUrl,'utf8', (err, data) => { if (err) { reject(err); } else{ resolve(data); } }); }); }) .then((cfTemplate)=>{ return this.deployTemplate(name,cfTemplate,params,opts); }); } awaitStackStatus(stackIdOrName,statusesIn=[]){ let statuses = _.flattenDeep([statusesIn]);//make sure this is an array return BackoffUtils.exponentialBackoff( //backoff function (opts)=>{ console.info(`Attempting to retrieve stack (${stackIdOrName}) status after delaying, (HH:MM:SS.mmm) ${BackoffUtils.msToTime(opts.delayAmounts[opts.currentIndex])}`); //eslint-disable-line return this.retrieveStackStatus(stackIdOrName) .then((status)=>{ /* eslint-disable no-fallthrough */ return new Promise((resolve,reject)=>{ try{ switch(status.StackStatus){ case 'CREATE_COMPLETE': //Successful creation of one or more stacks. case 'CREATE_IN_PROGRESS': //Ongoing creation of one or more stacks. case 'CREATE_FAILED': //Unsuccessful creation of one or more stacks. View the stack events to see any associated error messages. Possible reasons for a failed creation include insufficient permissions to work with all resources in the stack, parameter values rejected by an AWS service, or a timeout during resource creation. case 'DELETE_COMPLETE': //Successful deletion of one or more stacks. Deleted stacks are retained and viewable for 90 days. case 'DELETE_FAILED': //Unsuccessful deletion of one or more stacks. Because the delete failed, you might have some resources that are still running; however, you cannot work with or update the stack. Delete the stack again or view the stack events to see any associated error messages. case 'DELETE_IN_PROGRESS': //Ongoing removal of one or more stacks. case 'REVIEW_IN_PROGRESS': //ngoing creation of one or more stacks with an expected StackId but without any templates or resources. *Important* A stack with this status code counts against the maximum possible number of stacks. case 'ROLLBACK_COMPLETE': //Successful removal of one or more stacks after a failed stack creation or after an explicitly canceled stack creation. Any resources that were created during the create stack action are deleted. This status exists only after a failed stack creation. It signifies that all operations from the partially created stack have been appropriately cleaned up. When in this state, only a delete operation can be performed. case 'ROLLBACK_FAILED': //Unsuccessful removal of one or more stacks after a failed stack creation or after an explicitly canceled stack creation. Delete the stack or view the stack events to see any associated error messages. case 'ROLLBACK_IN_PROGRESS': //Ongoing removal of one or more stacks after a failed stack creation or after an explicitly cancelled stack creation. case 'UPDATE_COMPLETE': //Successful update of one or more stacks. case 'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS': //Ongoing removal of old resources for one or more stacks after a successful stack update. For stack updates that require resources to be replaced, AWS CloudFormation creates the new resources first and then deletes the old resources to help reduce any interruptions with your stack. In this state, the stack has been updated and is usable, but AWS CloudFormation is still deleting the old resources. case 'UPDATE_IN_PROGRESS': //Ongoing update of one or more stacks. case 'UPDATE_ROLLBACK_COMPLETE': //Successful return of one or more stacks to a previous working state after a failed stack update. case 'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS': //Ongoing removal of new resources for one or more stacks after a failed stack update. In this state, the stack has been rolled back to its previous working state and is usable, but AWS CloudFormation is still deleting any new resources it created during the stack update. case 'UPDATE_ROLLBACK_FAILED': //Unsuccessful return of one or more stacks to a previous working state after a failed stack update. When in this state, you can delete the stack or continue rollback. You might need to fix errors before your stack can return to a working state. Or, you can contact customer support to restore the stack to a usable state. case 'UPDATE_ROLLBACK_IN_PROGRESS': //Ongoing return of one or more stacks to the previous working state after failed stack update. default: if(statuses.includes(status.StackStatus)){ resolve(status); } else{ resolve(false); } break; } } catch(e){ reject(e); } }); }); }, 3000, //use a delay of 3 seconds 45, //give up after 16 times (this will give up roughly at the hour mark) 60000 //dont delay any more than 5 minutes ); } _createAwsRequestArrayFromObj(params,usePrevious=false){ const paramsArr = []; Object.keys(params).forEach((prmName)=>{ paramsArr.push({ ParameterKey: prmName, ParameterValue: String(params[prmName]), UsePreviousValue: usePrevious }); }); return paramsArr; } deployTemplate(name,cfTemplate,params,opts={capabilities:undefined,tags:undefined}){ let paramsReq = params; if(_.isPlainObject(params)){ paramsReq = this._createAwsRequestArrayFromObj(params); } return Promise.resolve() .then(()=>{ //TODO normalize params return this.createStack({ TemplateBody: cfTemplate, StackName: name, Parameters: paramsReq, Capabilities: opts.capabilities, Tags: opts.tags }); }) //Capturing Create Failure reason to run stack update for Existing stack .catch((createError)=>{ if ('AlreadyExistsException' == createError.code){ return this.updateStack({ TemplateBody: cfTemplate, StackName: name, Parameters: params, Capabilities: opts.capabilities, Tags: opts.tags }); } else{ return Promise.reject(createError); } }) .then((createResponse)=>{ let stackId = createResponse.StackId; //use DescribeStacks API to test for completion (use exponential back off) return this.awaitStackStatus(stackId,['CREATE_COMPLETE','CREATE_FAILED','ROLLBACK_COMPLETE','ROLLBACK_FAILED','UPDATE_COMPLETE','UPDATE_FAILED','UPDATE_ROLLBACK_COMPLETE','UPDATE_ROLLBACK_FAILED']) .then((lastUpdatedStatus)=>{ if((lastUpdatedStatus.StackStatus === 'CREATE_FAILED') || (lastUpdatedStatus.StackStatus === 'UPDATE_FAILED') ){ let error = new Error(`Failed to deploy template, please see stack (${stackId}).`); error.errorDetails = { createResponse: createResponse, lastUpdatedStatus: lastUpdatedStatus }; return Promise.reject(error); } else{ return Promise.resolve({ createResponse: createResponse, lastUpdatedStatus: lastUpdatedStatus }); } }); }) .then((createResults)=>{ return createResults; }); } retrieveStackStatus(nameOrId){ return Promise.resolve() .then(()=>{ return this.describeStacks({ StackName: nameOrId }); }) .then((stackStatus)=>{ return stackStatus.Stacks.find((elem)=>{ if(elem.StackId === nameOrId || elem.StackName === nameOrId){ return true; } else{ return false; } }); }); } teardownStack(nameOrId){ return Promise.resolve() .then(()=>{ return this.deleteStack({ StackName: nameOrId }); }) .then((deleteResponse)=>{ //use DescribeStacks API to test for completion (use exponential back off) return this.awaitStackStatus(nameOrId,['DELETE_COMPLETE','DELETE_FAILED']) .then((lastUpdatedStatus)=>{ if(lastUpdatedStatus.StackStatus === 'DELETE_FAILED'){ let error = new Error(`Failed to delete stack, please see stack (${nameOrId}).`); error.errorDetails = { deleteResponse: deleteResponse, lastUpdatedStatus: lastUpdatedStatus }; return Promise.reject(error); } else{ return Promise.resolve({ deleteResponse: deleteResponse, lastUpdatedStatus: lastUpdatedStatus }); } }) .catch(e=>{ //TODO if the stack is no longer visible it is obviously is deleted Promise.reject(e); }); }) .then((createResults)=>{ return createResults; }); } } module.exports = CloudFormation;
function messageBox(msg, title, modal, callback, options) { new inews.MessageBox({ title: ((title == undefined) ? false : title), text: msg, modal: ((modal == undefined) ? true : modal), callback: ((callback == undefined) ? function () {} : callback), options: options }); } (function ($, undefined) { $.namespace('inews'); inews.MessageBox = function (options) { var body, button; var el, self = this; var params; this._options = options; body = $('<div></div>').addClass('messagebox'); if (options.id) body.attr('id', options.id); $('<div></div>').addClass('text').html(options.text).appendTo(body); $('<hr></hr>').appendTo(body); button = $('<div></div>').addClass('buttonset').appendTo(body); $('<button></button>').attr('id', 'messagebox-ok').html(MESSAGE['OK']).appendTo(button); params = { width: 'auto', height: 'auto', modal: ((options.modal) ? true : false), el: body, title: ((options.title) ? options.title : MESSAGE['MESSAGE']), showCloseBtn: true }; params = $.extend({}, params, this._options.options); this.dlg = new inews.Dialog(params); this._el = this.dlg.getEl(); $(this._el).find('.buttonset button').on(EVT_MOUSECLICK, function (e) { $(self._el).find('.buttonset button').off(EVT_MOUSECLICK); self.dlg.close(); }); $(this._el).one(EVT_CLOSE, options.callback); }; }(jQuery));
// mergeSort(p,,,r) = merge(mergeSort(p,,,,q)+mergeSort(q+1,,,,r)) // p >= r function mergeSort(arr) { if (Object.prototype.toString.call(arr) !== '[object Array]') { console.log('param is not an array'); return; } if(arr.length<2){ return arr; } return sort(arr); } function sort(array) { if(array.length<2){ return array } const middle = Math.floor(array.length / 2); const left = array.slice(0,middle); const right = array.slice(middle); return merge(sort(left),sort(right)); } function merge(left , right){ let result = []; while(left.length && right.length){ if(left[0]<right[0]){ result.push(left.shift()); }else{ result.push(right.shift()); } } return result.concat(left,right); } module.exports ={ sort: mergeSort }
import { SUDOKU_DIGITS, SUDOKU_LARGEST_DIGIT } from './constants'; /** * Shuffles an array. * * @param {Array} array * @param {Boolean} [shouldMutate=false] * @return {Array} */ const shuffleArray = (array = [], shouldMutate = false) => { const arr = shouldMutate ? array : array.slice(); for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); const temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } return arr; }; /** * Randomly generates a Sudoku row. * * @return {Array} - Shuffled numbers between 1 and 9 inclusive. */ const generateRow = () => shuffleArray(SUDOKU_DIGITS); /** * Given output, checks if row is usable in Sudoku solution. * * @param {Number} index * @param {Array} row * @param {Array} output * @return {Boolean} */ const isRowUsable = (index, row = [], output = []) => { let rowIndex = output.length - 1; for (; rowIndex > -1; rowIndex--) { let columnIndex = output[rowIndex].length - 1; for (; columnIndex > -1; columnIndex--) { // check if row value exists in output column const rowValue = row[columnIndex]; if (rowValue === output[rowIndex][columnIndex]) return false; let rowStart = 6; if (index < 3) { rowStart = 0; } else if (index < 6) { rowStart = 3; } let columnStart = 6; if (columnIndex < 3) { columnStart = 0; } else if (columnIndex < 6) { columnStart = 3; } let section = []; for (let i = 0; i < 3; i++) { if (output[rowStart + i] instanceof Array) { section = section.concat( output[rowStart + i].slice(columnStart, columnStart + 3) ); } } // check if row value exists in output 3x3 section if (section.indexOf(rowValue) !== -1) return false; } } return true; }; /** * Generates a Sudoku solution. * * @return {Array} */ const generateSolution = () => { // seed 1st row const output = [generateRow()]; // generate rows 2 to 8 let loopCount = 0; for (let index = 1; index < 8; index++) { while (true) { const row = generateRow(); if (isRowUsable(index, row, output)) { output[index] = row; loopCount = 0; break; } loopCount++; // break and try again if stuck in infinite loop if (loopCount > 2e5) return generateSolution(); } } // invert the output const columnValues = output.reduce((result, row, rowIndex) => { row.forEach((columnValue, columnIndex) => { result[columnIndex] = result[columnIndex] || []; result[columnIndex][rowIndex] = columnValue; }); return result; }, []); // get 9th row const lastRow = []; for (let number = SUDOKU_LARGEST_DIGIT; number > 0; number--) { for (let i = columnValues.length - 1; i > -1; i--) { if (columnValues[i].indexOf(number) === -1) { lastRow[i] = number; break; } } } output.push(lastRow); return output; }; /** * Creates Sudoku solution and puzzle. * * @param {Number} difficulty - A number between 0 and 1. * Lower means easier, higher means harder. * @return {Object} */ const createSudoku = difficulty => { const solution = generateSolution(); const puzzle = solution.map(row => row.slice().map(value => (Math.random() > difficulty ? value : null)) ); return { puzzle, solution }; }; export default createSudoku;
/** * Created by stephen on 12/14/13. */ myApp = angular.module('nuke',[]) ; function nukeCtrl($scope, $http,$sce) { $scope.trustSrc = function(src) { return $sce.trustAsResourceUrl(src); } $scope.songName = "white christmas" ; $scope.play = function(){ $scope.pAlbum = this.album.href ; } $scope.getSong = function(){ $http.get('http://ws.spotify.com/search/1/album.json?q=' + $scope.songName + '&page=2').success(function (data) { for(var i=0; i < data.albums.length ; i++){ data.albums[i].href = 'http://embed.spotify.com/?uri=' + data.albums[i].href ; } $scope.albums = data.albums ; }); } }
import React from 'react'; import Icon from '../../components/Icon'; export default ({icon, message}) => ( <span><Icon name={icon}/>{message}</span> );
export const config = { apiKey: "AIzaSyDu7OqiFRmnYh_81Dcke6m9jxiUuqFjU8M", authDomain: "shifted-timetables.firebaseapp.com", databaseURL: "https://shifted-timetables.firebaseio.com", projectId: "shifted-timetables", storageBucket: "shifted-timetables.appspot.com", messagingSenderId: "284988692648", appId: "1:284988692648:web:3ddec0cce41eca1fe44a9d", measurementId: "G-2LKBD9QF2C" }
import AddTasks from "./components/AddTasks"; import Header from "./components/Header"; import Tasks from "./components/Tasks"; import { useState } from "react"; import "./app.css"; const App = () => { const [tasks, setTasks] = useState([ { id: 1, Todo: "Learn React.js", date: "1 Oct 2021", check: false, }, { id: 2, Todo: "Do the homeworks", date: "5 Oct 2021", check: true, }, ]); const deleteTask = (id) => { setTasks( tasks.filter((task) => { return task.id !== id; }) ); }; const addTasks = (task) => { const id = Math.floor(Math.random() * 10000) + 1; const newTask = { id, ...task }; setTasks([...tasks, newTask]); }; const setCheckState = (taskId) => { setTasks( tasks.map((task) => task.id === taskId ? { ...task, check: !task.check } : task ) ); }; return ( <div className="container"> <Header /> <AddTasks onAdd={addTasks} /> <Tasks tasks={tasks} deleteTask={deleteTask} onDoubleClick={setCheckState} /> </div> ); }; export default App;
'use strict'; var app = angular.module('app', [ 'ngResource', 'ngRoute', 'ngAnimate', 'toastr' ]); //var SERVER = 'http://192.168.42.188:8083'; var SERVER = 'http://localhost:8083'; var ACTIVE = '1'; var INACTIVE = '0'; app.config(['$routeProvider', '$locationProvider', '$httpProvider', function ($routeProvider, $locationProvider, $httpProvider) { $routeProvider .when('/login', { templateUrl: 'login.html', controller: 'navigation', controllerAs: 'controller' }) .when('/home', { templateUrl: 'home.html' }) .when('/usuario', { templateUrl: 'views/usuario/usuario.html', controller: 'usuarioController' }) .when('/usuario/new', { templateUrl: 'views/usuario/usuario_form.html', controller: 'usuarioController' }) .when('/usuario/edit/:id', { templateUrl: 'views/usuario/usuario_edit.html', controller: 'usuarioController' }) .otherwise('/login'); $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; }]);
const persons = [ { id:1, name: "Marta Argerich", age: 201, profession: "Pianist", img: "https://upload.wikimedia.org/wikipedia/commons/a/a7/React-icon.svg" }, { id:2, name: "Tschakovsky", age: 50, profession: "Compositor", img: "https://upload.wikimedia.org/wikipedia/commons/a/a7/React-icon.svg" }, { id:3, name: "Mozart", age: 300, profession: "Compositor", img: "https://upload.wikimedia.org/wikipedia/commons/a/a7/React-icon.svg" }, { id:4, name: "Tu primita", age: 15, profession: "Pianist", img: "https://upload.wikimedia.org/wikipedia/commons/a/a7/React-icon.svg" }, { id:5, name: "Ludwig Beethooven", age: 201, profession: "Pianist", img: "https://upload.wikimedia.org/wikipedia/commons/a/a7/React-icon.svg" }, { id:6, name: "Rachmaninoff", age: 140, profession: "Pianist", img: "https://upload.wikimedia.org/wikipedia/commons/a/a7/React-icon.svg" } ] export default persons;
'use strict'; var path = require('path'); var validateNpmPackageName = require('validate-npm-package-name'); var expression = /^node_modules[/\\](@[^/\\]+[/\\][^/\\]+|[^/\\]+)/; function isPackageFile(filePath) { var relativePath = path.relative(process.cwd(), filePath); var match = expression.exec(relativePath); var isValidPackage = false; var report; var id; if (match) { id = match[1].replace(/\\/, '/'); report = validateNpmPackageName(id); isValidPackage = report.validForNewPackages; } return isValidPackage; } module.exports = isPackageFile;
import zhLocale from "element-ui/lib/locale/lang/zh-CN" //引入element语言包 const taiyu = { "menu": { "jilu": "อัดแผ่นเสียง", "wenxunjilu": "บันทึกการสอบถาม", "biaodanxiangqing": "รายละเอียดแบบฟอร์ม", "guanquguanli": "การผ่าน", "guanquliebiao": "การจัดการพื้นที่ผ่าน", "guanyuanguanli": "ผู้ควบคุม", "guanyuanliebiao": "เจ้าหน้าที่บริหาร", "biaodan": "แบบฟอร์ม", "biaodanguanli": "การจัดการแบบฟอร์ม", "ninhao": "หวัดดี", "yuyan": "ภาษา", "mingcheng": "นาม", "jilubianhao": "หมายเลขบันทึก", "tijiaoshijian": "เวลาส่ง", "caozuo": "การดำเนินการ", "chakan": "การตรวจสอบ", "qingxuanzeyuyan": "กรุณาเลือกภาษา", "daochu": "ส่งออก", "biaodanweiyibiaoshi": "เอกลักษณ์ของแบบฟอร์ม", "biaodancode": "รหัสแบบฟอร์ม", "chuangjianshijian": "สร้างเวลา", "yulan": "ตัวอย่าง", "bianji": "ตัดต่อ", "shanchu": "ลบทิ้ง", "zhanghao": "อธิบายแจกแจง", "guanqumingcheng": "ชื่อเขต", "xinzeng": "ใหม่", "shujuyuan": "แหล่งข้อมูล", "zhizuoshujuyuan": "แหล่งข้อมูล", "fanyi": "แปล", "jiexi": "วิเคราะห์", "mubanjiexijieguo": "ผลการวิเคราะห์แม่แบบ", "shangchuanwenjianmuban": "อัพโหลดไฟล์แม่แบบ", "dianjishangchuan": "คลิกที่อัพโหลด", "zhinengshangchuanword": "เพียงอัปโหลดไฟล์ EXCEL Word", "tijiao": "ทูลเกล้าฯถวาย", "fanhui": "วกกลับ", "quxiao": "ยกเลิก", "chaxun": "สอบถาม", "mima": "รหัสผ่าน", "tuichudenglu": "ออกจากระบบ" }, "language": { "zhongwen": "ภาษาจีน", "yingyu": "ภาษาอังกฤษ", "riyu": "ภาษาญี่ปุ่น", "hanyu": "ภาษาเกาหลี", "fayu": "ภาษาฝรั่งเศส", "xibanyayu": "ภาษาสเปน", "taiyu": "ภาษาไทย", "alaboyu": "ภาษาอาหรับ", "eyu": "ภาษารัสเซีย", "putaoyayu": "ภาษาโปรตุเกส", "deyu": "ภาษาเยอรมัน", "yidaliyu": "ภาษาอิตาลี", "xilayu": "ชาวกรีก", "helanyu": "ดัตช์", "bolanyu": "ภาษาโปแลนด์", "baojialiyayu": "ชาวบัลแกเรีย", "aishaniyayu": "ภาษาเอสโตเนีย", "danmaiyu": "ภาษาเดนมาร์ก", "fenlanyu": "ภาษาฟินแลนด์", "jiekeyu": "ภาษาเช็ก", "luomaniyayu": "ภาษาโรมาเนีย", "siluowenniyayu": "ภาษาสโลวีเนีย", "ruidianyu": "ชาวสวิส", "xiongyaliyu": "ชาวฮังการี", "yuenanyu": "ภาษาเวียดนาม", "fantizhongwen": "ภาษาจีนแบบดั้งเดิม" }, ...zhLocale } export default taiyu;
'use stric' var express = require("express") //var UserController = require("../controllers/userController") var ControladorPrincipal = require("../controllers/ControladorPrincipal") var md_auth = require('../middlewares/authenticated') //RUTAS var api = express.Router(); api.post('/commands', md_auth.ensureAuth, ControladorPrincipal.commands) module.exports = api;
function test() { } function sayHello(name) { console.log('${name}') } module.exports.test = test exports.sayHello = sayHello
import React, { useState, useEffect } from "react" import { graphql } from "gatsby" import Layout from "../components/Layout" import { documentToReactComponents } from "@contentful/rich-text-react-renderer" import { BLOCKS } from "@contentful/rich-text-types" import { FontAwesomeIcon } from "@fortawesome/react-fontawesome" import { faFacebookSquare, faTwitterSquare, faLinkedin, } from "@fortawesome/free-brands-svg-icons" import CopyableCodeSnippet from "../components/CopyableCodeSnippet/CopyableCodeSnippet" import styles from "./blog-template.module.scss" import FeaturedBlogTitle from "../components/FeaturedBlogTitle/FeaturedBlogTitle" import { Helmet } from "react-helmet" import GroupCode from "../components/GroupCode/GroupCode" export const query = graphql` query($slug: String!) { contentfulBlogPost(slug: { eq: $slug }) { title color author authorImg { file { url } } previewImage { file { url } } socialMediaImg { file { url } } date(formatString: "DD MMMM YYYY") slug body { json } } } ` const customRenderOptions = { renderNode: { [BLOCKS.EMBEDDED_ASSET]: node => { if (node.data.target.fields) { return ( <div className={styles.imgContainer}> <img class="img-fluid" src={`${node.data.target.fields.file["en-US"].url}`} alt="attached" /> </div> ) } }, [BLOCKS.PARAGRAPH]: node => { if ( node && node.content && node.content[0].marks && node.content[0].marks[0] && node.content[0].marks[0].type === "code" ) { if (!node.content[0].value.trim()) return " " const isGroupCode = node.content[0].value.startsWith("group<<") if (isGroupCode) { let groupCodeTypes = node.content[0].value .match(/group<<<(.*?)>>>/)[1] .split(",") let codeSnippets = groupCodeTypes.map(type => { let regex = new RegExp( `(?<=${type.trim()}::\\s+).*?(?=\\s+---)`, "gs" ) return node.content[0].value.match(regex)[0] }) return ( <GroupCode types={groupCodeTypes} codeSnippets={codeSnippets} /> ) } const codeType = node.content[0].value.split("::")[0] const codeValue = node.content[0].value.split("::")[1].trim() return ( <CopyableCodeSnippet codeValue={codeValue} codeLanguage={codeType} codeStyle={{ backgroundColor: "#343434", color: "white", fontSize: "18px", maxWidth: "94vw", overflow: "auto", borderRadius: "8px", }} /> ) } if (node.content.length > 1) { const container = [] node.content.forEach((item, index) => { if (item.nodeType === "hyperlink") { container.push( <a href={item.data.uri} target="_blank" rel="noopener noreferrer" className={styles.externalLink} > {item.content && item.content[0] ? item.content[0].value : item.data.uri} </a> ) } else { container.push(item.value) } }) return <p>{container}</p> } return ( <p dangerouslySetInnerHTML={{ __html: node.content[0].value.replace( /`(.*?)`/g, `<span class="word-highlighted">$1</span>` ), }} /> ) }, }, } const Blog = props => { const { data } = props const renderedReactComponents = documentToReactComponents( data.contentfulBlogPost.body.json, customRenderOptions ) return ( <Layout> {isDark => { return ( <div className={styles.container}> <div className={styles.blogTemplate}> <Helmet> <meta property="og:image" content={data.contentfulBlogPost.socialMediaImg.file.url} /> <meta property="og:title" content={data.contentfulBlogPost.title} /> <meta name="twitter:image" content={data.contentfulBlogPost.socialMediaImg.file.url} /> <meta name="twitter:title" content={data.contentfulBlogPost.title} /> <meta property="og:site_name" content="codecrumbs"></meta> <title>Codecrumbs: {data.contentfulBlogPost.title}</title> </Helmet> <FeaturedBlogTitle postTitle={data.contentfulBlogPost.title} isFeatured={false} postImg={data.contentfulBlogPost.previewImage.file.url} postColor={!isDark ? data.contentfulBlogPost.color : "#2d2d2d"} postAuthor={data.contentfulBlogPost.author} postAuthorImg={data.contentfulBlogPost.authorImg.file.url} date={data.contentfulBlogPost.date} /> <div className={styles.blogWrappper}> <div className={styles.socialMediaIcons}> <a href={`https://www.facebook.com/sharer/sharer.php?u=https://codecrumbs.netlify.com/blog/${data.contentfulBlogPost.slug}`} target="_blank" rel="noopener noreferrer" className={styles.socialMediaIcon} > <FontAwesomeIcon size="2x" icon={faFacebookSquare} /> </a> <a target="_blank" rel="noopener noreferrer" href={`https://twitter.com/intent/tweet/?text=${data.contentfulBlogPost.title}&url=https://codecrumbs.netlify.com/blog/${data.contentfulBlogPost.slug}&via=cheha6`} className={styles.socialMediaIcon} > <FontAwesomeIcon size="2x" icon={faTwitterSquare} /> </a> <a href={`https://www.linkedin.com/shareArticle?mini=true&url=https://codecrumbs.netlify.com/blog/${data.contentfulBlogPost.slug}&title=${data.contentfulBlogPost.title}&source=https://codecrumbs.netlify.com/`} target="_blank" rel="noopener noreferrer" className={styles.socialMediaIcon} > <FontAwesomeIcon size="2x" icon={faLinkedin} /> </a> </div> <div className={styles.blog}>{renderedReactComponents}</div> </div> </div> </div> ) }} </Layout> ) } export default Blog
const express = require('express'); const cors = require('cors'); const axios = require('axios').default; const app = express(); const bodyParser = require('body-parser'); const path = require('path'); const port = 4567; const url = 'http://52.26.193.201:3000'; const prefix = '/ov'; // const url = 'http://18.224.200.47/'; app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static(path.join(__dirname, '/../client/dist'))); app.use(cors()); // SEND bundle.js FILE app.get('/ov', (req, res) => { res.sendFile(path.join(__dirname, '/../client/dist/bundle.js')); }); // PRODUCTS app.get(`${prefix}/products/list`, (req, res) => { axios.get(`${url}/products/list`) .then((response) => res.status(200).send(response.data)) .catch((err) => res.status(500).send(err)); }); app.get(`${prefix}/products/:product_id/`, (req, res) => { axios.get(`${url}/products/${req.params.product_id}`) .then((response) => res.status(200).send(response.data)) .catch((err) => res.status(500).send(err)); }); app.get(`${prefix}/products/:product_id/styles`, (req, res) => { axios.get(`${url}/products/${req.params.product_id}/styles`) .then((response) => res.status(200).send(response.data)) .catch((err) => res.status(500).send(err)); }); app.get(`${prefix}/products/:product_id/related`, (req, res) => { axios.get(`${url}/products/${req.params.product_id}/related`) .then((response) => res.status(200).send(response.data)) .catch((err) => res.status(500).send(err)); }); // CART app.get(`${prefix}/cart/:user_session`, (req, res) => { axios.get(`${url}/cart/${req.params.user_session}`) .then((response) => res.status(200).send(response.data)) .catch((err) => res.status(500).send(err)); }); app.post(`${prefix}/cart/`, (req, res) => { axios.post(`${url}/cart/`, { user_session: req.params.user_session, product_id: req.params.product_id, }) .then((response) => res.status(200).send(response.data)) .catch((err) => res.status(500).send(err)); }); // REVIEWS app.get(`${prefix}/reviews/:product_id/list`, (req, res) => { axios.get(`${url}/reviews/${req.params.product_id}/list`, { params: { count: 20, sort: 'newest', }, }) .then((response) => res.status(200).send(response.data)) .catch((err) => res.status(500).send(err)); }); app.listen(port, () => { // eslint-disable-next-line no-console console.log(`Example app listening at http://localhost:${port}`); });
console.log("vendor1.js!");
ricoApp.controller('MarketProductControll', function ($scope,$uibModal,$sce,$routeParams,IndexedDb) { $scope.productContent; if(currentCustomer===undefined){ location="#/overview"; } for(var i=0;i<products.length;i++){ if(products[i].id==$routeParams.productId){ currentProduct=products[i]; if(language==='de'){ $scope.page= $sce.trustAsHtml(currentProduct.fileDe); }else if (language==='fr') { $scope.page= $sce.trustAsHtml(currentProduct.fileFr); }else { $scope.page= $sce.trustAsHtml(currentProduct.fileEn); }; $scope.product=currentProduct; break; }; } $scope.openProductDialog=function(){ var modalInstance = $uibModal.open({ animation: true, templateUrl: 'MarketAddEdit.tpl.html', controller: 'MarketAddEditControll', size: 'm', resolve: { product: function () { return currentProduct; } } }); modalInstance.result.then(function () { location="#/overview"; }); }; });
dojo.provide("dojox.embed.Quicktime"); (function(){ /******************************************************* dojox.embed.Quicktime Base functionality to insert a QuickTime movie into a document on the fly. ******************************************************/ var qtMarkup, qtVersion, installed, __def__={ width: 320, height: 240, redirect: null }; var keyBase="dojox-embed-quicktime-", keyCount=0; // reference to the test movie we will use for getting QT info from the browser. var testMovieUrl=dojo.moduleUrl("dojox", "embed/resources/version.mov"); // *** private methods ********************************************************* function prep(kwArgs){ kwArgs = dojo.mixin(dojo.clone(__def__), kwArgs || {}); if(!("path" in kwArgs)){ console.error("dojox.embed.Quicktime(ctor):: no path reference to a QuickTime movie was provided."); return null; } if(!("id" in kwArgs)){ kwArgs.id=(keyBase + keyCount++); } return kwArgs; } var getQTMarkup = 'This content requires the <a href="http://www.apple.com/quicktime/download/" title="Download and install QuickTime.">QuickTime plugin</a>.'; if(dojo.isIE){ qtVersion = 0; installed = (function(){ try{ var o = new ActiveXObject("QuickTimeCheckObject.QuickTimeCheck.1"); if(o!==undefined){ // pull the qt version too var v=o.QuickTimeVersion.toString(16); qtVersion={ major: parseInt(v.substring(0,1),10)||0, minor: parseInt(v.substring(1,2),10)||0, rev: parseInt(v.substring(2,3), 10)||0 }; return o.IsQuickTimeAvailable(0); } } catch(e){ } return false; })(); qtMarkup = function(kwArgs){ if(!installed){ return { id: null, markup: getQTMarkup }; } kwArgs = prep(kwArgs); if(!kwArgs){ return null; } var s = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" ' + 'codebase="http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0" ' + 'id="' + kwArgs.id + '" ' + 'width="' + kwArgs.width + '" ' + 'height="' + kwArgs.height + '">' + '<param name="src" value="' + kwArgs.path + '" />'; if(kwArgs.params){ for(var p in kwArgs.params){ s += '<param name="' + p + '" value="' + kwArgs.params[p] + '" />'; } } s += '</object>'; return { id: kwArgs.id, markup: s }; } } else { installed = (function(){ for(var i=0, l=navigator.plugins.length; i<l; i++){ if(navigator.plugins[i].name.indexOf("QuickTime")>-1){ return true; } } return false; })(); qtMarkup = function(kwArgs){ if(!installed){ return { id: null, markup: getQTMarkup }; } kwArgs = prep(kwArgs); if(!kwArgs){ return null; } var s = '<embed type="video/quicktime" src="' + kwArgs.path + '" ' + 'id="' + kwArgs.id + '" ' + 'name="' + kwArgs.id + '" ' + 'pluginspage="www.apple.com/quicktime/download" ' + 'enablejavascript="true" ' + 'width="' + kwArgs.width + '" ' + 'height="' + kwArgs.height + '"'; if(kwArgs.params){ for(var p in kwArgs.params){ s += ' ' + p + '="' + kwArgs.params[p] + '"'; } } s += '></embed>'; return { id: kwArgs.id, markup: s }; } } /*===== dojox.embed.__QTArgs = function(path, id, width, height, params, redirect){ // path: String // The URL of the movie to embed. // id: String? // A unique key that will be used as the id of the created markup. If you don't // provide this, a unique key will be generated. // width: Number? // The width of the embedded movie; the default value is 320px. // height: Number? // The height of the embedded movie; the default value is 240px // params: Object? // A set of key/value pairs that you want to define in the resultant markup. // redirect: String? // A url to redirect the browser to if the current QuickTime version is not supported. this.id=id; this.path=path; this.width=width; this.height=height; this.params=params; this.redirect=redirect; } =====*/ dojox.embed.Quicktime=function(/* dojox.embed.__QTArgs */kwArgs, /* DOMNode */node){ // summary: // Returns a reference to the HTMLObject/HTMLEmbed that is created to // place the movie in the document. You can use this either with or // without the new operator. Note that with any other DOM manipulation, // you must wait until the document is finished loading before trying // to use this. // // example: // Embed a QuickTime movie in a document using the new operator, and get a reference to it. // | var movie = new dojox.embed.QuickTime({ // | path: "path/to/my/movie.mov", // | width: 400, // | height: 300 // | }, myWrapperNode); // // example: // Embed a movie in a document without using the new operator. // | var movie = dojox.embed.QuickTime({ // | path: "path/to/my/movie.mov", // | width: 400, // | height: 300 // | }, myWrapperNode); return dojox.embed.Quicktime.place(kwArgs, node); // HTMLObject }; dojo.mixin(dojox.embed.Quicktime, { // summary: // A singleton object used internally to get information // about the QuickTime player available in a browser, and // as the factory for generating and placing markup in a // document. // // minSupported: Number // The minimum supported version of the QuickTime Player, defaults to // 6. // available: Boolean // Whether or not QuickTime is available. // supported: Boolean // Whether or not the QuickTime Player installed is supported by // dojox.embed. // version: Object // The version of the installed QuickTime Player; takes the form of // { major, minor, rev }. To get the major version, you'd do this: // var v=dojox.embed.Quicktime.version.major; // initialized: Boolean // Whether or not the QuickTime engine is available for use. // onInitialize: Function // A stub you can connect to if you are looking to fire code when the // engine becomes available. A note: do NOT use this stub to embed // a movie in your document; this WILL be fired before DOMContentLoaded // is fired, and you will get an error. You should use dojo.addOnLoad // to place your movie instead. minSupported: 6, available: installed, supported: installed, version: qtVersion, initialized: false, onInitialize: function(){ dojox.embed.Quicktime.initialized = true; }, // stub function to let you know when this is ready place: function(kwArgs, node){ var o = qtMarkup(kwArgs); node = dojo.byId(node); if(!node){ node=dojo.doc.createElement("div"); node.id=o.id+"-container"; dojo.body().appendChild(node); } if(o){ node.innerHTML = o.markup; if(o.id){ return (dojo.isIE)? dojo.byId(o.id) : document[o.id]; // QuickTimeObject } } return null; // QuickTimeObject } }); // go get the info if(!dojo.isIE){ // FIXME: Opera does not like this at all for some reason, and of course there's no event references easily found. qtVersion = dojox.embed.Quicktime.version = { major: 0, minor: 0, rev: 0 }; var o = qtMarkup({ path: testMovieUrl, width:4, height:4 }); function qtInsert(){ if(!dojo._initFired){ var s='<div style="top:0;left:0;width:1px;height:1px;;overflow:hidden;position:absolute;" id="-qt-version-test">' + o.markup + '</div>'; document.write(s); } else { var n = document.createElement("div"); n.id="-qt-version-test"; n.style.cssText = "top:0;left:0;width:1px;height:1px;overflow:hidden;position:absolute;"; dojo.body().appendChild(n); n.innerHTML = o.markup; } } function qtGetInfo(mv){ var qt, n, v = [ 0, 0, 0 ]; if(mv){ qt=mv, n=qt.parentNode; } else { if(o.id) { qtInsert(); if(!dojo.isOpera){ setTimeout(function(){ qtGetInfo(document[o.id]); }, 50); } else { var fn=function(){ setTimeout(function(){ qtGetInfo(document[o.id]) }, 50); }; if(!dojo._initFired){ dojo.addOnLoad(fn); } else { dojo.connect(document[o.id], "onload", fn); } } } return; } if(qt){ try { v = qt.GetQuickTimeVersion().split("."); qtVersion = { major: parseInt(v[0]||0), minor: parseInt(v[1]||0), rev: parseInt(v[2]||0) }; } catch(e){ qtVersion = { major: 0, minor: 0, rev: 0 }; } } dojox.embed.Quicktime.supported = v[0]; dojox.embed.Quicktime.version = qtVersion; if(dojox.embed.Quicktime.supported){ dojox.embed.Quicktime.onInitialize(); } else { console.log("quicktime is not installed."); } try { if(!mv){ dojo.body().removeChild(n); } } catch(e){ } } qtGetInfo(); } else if(dojo.isIE && installed){ dojox.embed.Quicktime.onInitialize(); } })();
export const hideFlash = () => dispatch => { dispatch({ type: "HIDE_FLASH" }); }; export const showFlash = flashId => { return dispatch => { dispatch({ type: flashId }); }; }; export const loggedInFlash = () => { return dispatch => { dispatch({ type: "loggedIn" }); }; };
var browserSync = require('browser-sync'); var gulp = require('gulp'); var config = require('../config'); var historyApiFallback = require('connect-history-api-fallback'); gulp.task('browserSync', ['build'], function () { browserSync.init({ server: { baseDir: [config.dest, config.src], middleware: [ historyApiFallback() ] }, port: 5000, ui: { port: 5001 }, files: [ config.dest + '/**' ] }); });