text
stringlengths
7
3.69M
var textInputSearch = document.getElementById("search"); var timeout = null; textInputSearch.addEventListener("keyup", (e) => { var spinner = document.createElement("div"); spinner.className = "loader"; document.getElementById("searchProduct").appendChild(spinner); if (e.keyCode == 13) { window.location.href = "SearchProductServlet?navigate=true&query=" + textInputSearch.value; }//Enter if (textInputSearch.value) { clearTimeout(timeout); timeout = setTimeout(() => { console.log("search value: " + textInputSearch.value) searchProduct(textInputSearch.value); },700) } }) function getXMLHTTPRequest() { var xmlHttp = null if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else { xmlHttp = new ActiveXObject(); } return xmlHttp; } function searchProduct(strSearchValue) { //var strSearchValue = document.getElementById("search").value; if (strSearchValue != null) { var request = getXMLHTTPRequest(); var header = getResponseHeader(request, getXMLResponse); request.open("POST", "SearchProductServlet", true); request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); request.send("query=" + strSearchValue + "&navigate=false"); request.onreadystatechange = header; } else { document.getElementById("searchProduct").innerHTML = ""; } } function getXMLResponse(xmlDoc) { document.getElementById("searchProduct").innerHTML = ""; if (xmlDoc) { var parser = new DOMParser(); var res = parser.parseFromString(xmlDoc,"text/xml"); var products = res.documentElement.childNodes; //products for (var i = 0; i < products.length; i++) { var product = products[i].childNodes, id = product[0].childNodes[0].textContent, type = product[1].childNodes[0].textContent, name = product[2].childNodes[0].textContent, // Name tag p = document.createElement('p'); p.className = "search-result-element" p.innerHTML = name; p.onclick = () => window.location.href = "ProductDetailServlet?id="+id+"&type="+type; document.getElementById("searchProduct").appendChild(p); } } else { var p = document.createElement('p'); p.innerHTML = "Không tìm thấy sản phẩm" document.getElementById("searchProduct").appendChild(p); } } function getResponseHeader(request, response) { return function () { if (request.status == 200 && request.readyState == 4) { console.log("response text: " + request.responseText); response(request.responseText); } } }
import React from 'react'; import { Link } from 'react-router-dom'; import Panel from 'component/panel/index.jsx'; import TableList from 'component/table-list/index.jsx'; import Pagination from 'component/pagination/index.jsx'; import BaseUtil from 'util/base-util.jsx'; import Field from 'service/field-service.jsx'; import FormSearch from './form-search.jsx'; const _baseUtil = new BaseUtil(); const _field = new Field(); class FieldList extends React.Component{ constructor(props){ super(props); this.state = { pageNum: 1, list: [], name: '', enable: '' } } componentDidMount(){ this.loadList(); } loadList(){ let list_param = { page: this.state.pageNum, name: this.state.name, enable: this.state.enable }; _field.getList(list_param) .then(res=>{ this.setState({ total: res.count, list: res.fields || [] }); },errMsg=>{ this.setState({ list: [] }); _baseUtil.errorTips(errMsg); }); } onPageNumChange(pageNum){ this.setState({pageNum}, ()=>{ this.loadList(); }); } onSearch(name, enable){ this.setState({ name: name, enable: enable==='true' ? true:enable==='false' ? false:'' },()=>{ this.loadList(); }); } //启用禁用 onEnable(enable, userId){ _field.enableDisenable(enable, userId) .then(res=>{ this.loadList(); _baseUtil.successTips(res); },errMsg=>{ _baseUtil.errorTips(errMsg); }); } render(){ let tableHeads = ['ID', '名称', '状态', '操作']; let listBody = this.state.list.map((field,index)=>{ return ( <tr key={index}> <td>{field.id}</td> <td>{field.name}</td> <td>{field.enable ? '启用':'禁用'}</td> <td> <a onClick={(enable, fieldId )=>{this.onEnable(field.enable, field.id)}} className="btn btn-xs btn-primary mr-5">{field.enable ? '禁用' : '启用'}</a> </td> </tr> ); }); return ( <Panel title="领域列表"> <div className="content-row"> <div className="col-md-12"> <Link className="btn btn-primary fr" to="/field/save"> <i className="fa fa-plus"></i>&nbsp;&nbsp;添加 </Link> </div> </div> <FormSearch onSearch={(name, enable)=>{this.onSearch(name, enable)}}/> <TableList tableHeads={tableHeads}> {listBody} </TableList> <Pagination current={this.state.pageNum} total={this.state.total} onChange={pageNum=>{ this.onPageNumChange(pageNum) }}/> </Panel> ); } } export default FieldList;
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { showLoading, hideLoading } from 'modules/example/actions/loading'; // import { actionAjaxGetNewsList } from '../../actions/news.js'; import { Loading } from 'components'; import 'components/loading/loading.less'; class PageLoading extends React.Component { constructor(props) { super(props); } componentDidMount() {} render() { return ( <div> <div className="padding-10"> <button className="btn btn-orange btn-full" onClick={() => { this.props.showLoading({ children: 'hello, world', }); setTimeout(() => { this.props.hideLoading(); }, 2000); }} > show loading </button> <button style={{ marginTop: '10px' }} className="btn btn-orange btn-full" onClick={() => { Loading.show(); setTimeout(() => { Loading.hide(); }, 2000); }} > static show loading </button> </div> </div> ); } } PageLoading.propTypes = { showLoading: PropTypes.func, hideLoading: PropTypes.func, }; export default connect( (state) => ({ dataNewsList: state.newsList.dataNewsList }), (dispatch) => ({ showLoading: (requestData) => { showLoading(dispatch, requestData); }, hideLoading: () => { hideLoading(dispatch); }, }) )(PageLoading);
/* * File: app/view/mainView.js * * This file was generated by Sencha Architect version 3.0.4. * http://www.sencha.com/products/architect/ * * This file requires use of the Sencha Touch 2.3.x library, under independent license. * License of Sencha Architect does not include license for Sencha Touch 2.3.x. For more * details see http://www.sencha.com/license or contact license@sencha.com. * * This file will be auto-generated each and everytime you save your project. * * Do NOT hand edit this file. */ Ext.define('vertex.view.mainView', { extend: 'Ext.form.Panel', alias: 'widget.mainView', requires: [ 'Ext.TitleBar', 'Ext.Button', 'Ext.field.Search', 'Ext.Panel', 'Ext.Label', 'Ext.field.Select' ], config: { cls: 'vertexTheme', id: 'mainView', itemId: 'mainView', items: [ { xtype: 'titlebar', docked: 'top', id: 'mainViewTitle', itemId: 'mainViewTitle', title: 'SEARCH', items: [ { xtype: 'button', itemId: 'mybutton5', ui: 'plain', text: 'Logout' }, { xtype: 'button', align: 'right', ui: 'plain', text: 'History' } ] }, { xtype: 'searchfield', centered: false, id: 'companyName', itemId: 'companyName', name: 'companyName', required: true, placeHolder: 'Company Name' }, { xtype: 'button', cls: [ 'vertexBgText', 'vertexBtn' ], id: 'searchBtn', itemId: 'searchBtn', text: 'SEARCH' }, { xtype: 'button', id: 'advanceSearchBtn', itemId: 'advanceSearchBtn', ui: 'plain', text: 'Advance Search' }, { xtype: 'panel', height: '680px', hidden: true, id: 'advPanel', itemId: 'advPanel', items: [ { xtype: 'titlebar', docked: 'top', itemId: 'mytitlebar2', title: 'Advance Search', titleAlign: 'left', items: [ { xtype: 'button', align: 'right', id: 'advancedCloseBtn', itemId: 'advancedCloseBtn', ui: 'plain', text: 'X' }, { xtype: 'label', align: 'right', hidden: true, html: '&#x25BC;' } ] }, { xtype: 'selectfield', id: 'countryOption', itemId: 'countryOption', label: 'Country', labelAlign: 'top', placeHolder: 'Optional' }, { xtype: 'selectfield', id: 'industryOption', itemId: 'industryOption', label: 'Industry', labelAlign: 'top', placeHolder: 'Optional' }, { xtype: 'selectfield', id: 'dealLeadOption', itemId: 'dealLeadOption', label: 'Deal Lead', labelAlign: 'top', placeHolder: 'Optional' }, { xtype: 'selectfield', id: 'decisionOptional', itemId: 'decisionOptional', label: 'Decision', labelAlign: 'top', placeHolder: 'Optional' }, { xtype: 'selectfield', id: 'dealStatusOption', itemId: 'dealStatusOption', label: 'Deal Status', labelAlign: 'top', placeHolder: 'Optional' }, { xtype: 'selectfield', id: 'coLeadOption', itemId: 'coLeadOption', label: 'Co-Lead', labelAlign: 'top', placeHolder: 'Optional' }, { xtype: 'textfield', id: 'notesOption', itemId: 'notesOption', label: 'Notes', labelAlign: 'top', placeHolder: 'Any Keywords' } ] } ] } });
export const formatter = (v) => { let timeDistance = (new Date().getTime() - new Date(v).getTime()) / 1000 if ((timeDistance / 60) < 1) { return `1分钟前` } else if ((timeDistance / 60) < 60) { return `${Math.floor((timeDistance / 60))}分钟前` } else if ((timeDistance / 60 / 60) < 24) { return `${Math.floor((timeDistance / 60 / 60))}小时前` } else if ((timeDistance / 60 / 60 / 24) < 30) { return `${Math.floor((timeDistance / 60 / 60 / 24))}天前` } else if ((timeDistance / 60 / 60 / 24 / 30) < 12) { return `${Math.floor((timeDistance / 60 / 60 / 24 / 30))}月前` } else { return `${Math.floor((timeDistance / 60 / 60 / 24 / 30 / 12))}年前` } }
const ItemQtyLogger = require( './log/item.qty.log.js' ) ; module.exports.ItemAdded = async ( itemData ) => { const log = new ItemQtyLogger() ; Object.assign( log, { Type : 'add', Item : itemData.Name, Qty : itemData.LogQty, }) ; log.save() ; } ; module.exports.ItemPurchased = async ( purchaseData ) => { const logData = [] ; for( const item of purchaseData.Items ) { logData.push( { Type : 'pur', Item : item.Name, Qty : item.LogQty, RefID : purchaseData.PurchaseID, }) ; } ItemQtyLogger.insertMany( logData ); } ; module.exports.ItemSold = async ( saleData ) => { const logData = [] ; for( const item of saleData.Items ) { logData.push( { Type : 'sal', Item : item.Name, Qty : item.LogQty, RefID : saleData.SaleID, }) ; } ItemQtyLogger.insertMany( logData ); } ;
import liquidityAskBid from '../../../utils/liquidity-ask-bid.json'; // eslint-disable-next-line import/prefer-default-export export const generateChartData = () => liquidityAskBid;
let moduleLog = function () { let log = (message) => { console.log('log:' + message); } return { log: log } }(); module.exports = moduleLog;
import React from "react"; import { Link } from "react-router-dom"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { logoutUser } from "../../actions/authActions"; import { StyledNavbar, List, ListElement } from "../common/styles/Navbar"; const onLogoutClick = logoutUser => e => { e.preventDefault(); logoutUser(); }; export const Navbar = ({ auth, logoutUser }) => { const authLinks = ( <List> <ListElement> <Link style={{ color: "black" }} to="/items" id="itemsLink"> BROWSE ITEMS </Link> </ListElement> <ListElement> <Link style={{ color: "black" }} to="/dashboard" id="dashboardLink"> DASHBOARD </Link> </ListElement> <ListElement> <Link style={{ color: "black" }} to="/cart" id="cartLink"> CART <i className="ml-2 fas fa-shopping-cart" /> </Link> </ListElement> <ListElement> <Link style={{ color: "black" }} to="/" onClick={onLogoutClick(logoutUser)} id="logoutLink" > LOGOUT </Link> </ListElement> </List> ); const guestLinks = ( <List> <ListElement> <Link style={{ color: "black" }} className="link" to="/login" id="loginLink" > LOGIN </Link> </ListElement> <ListElement> <Link style={{ color: "black" }} to="/register" id="registerLink"> SIGN UP </Link> </ListElement> </List> ); return ( <StyledNavbar className="text-center"> {auth.isAuthenticated ? authLinks : guestLinks} </StyledNavbar> ); }; Navbar.propTypes = { logoutUser: PropTypes.func.isRequired, auth: PropTypes.object.isRequired }; const mapStateToProps = state => ({ auth: state.auth }); export default connect( mapStateToProps, { logoutUser } )(Navbar);
const User = require('./../models/userModel'); // Set user id exports.getMe = (req, res, next) => { req.params.id = req.user._id; next(); }; // Get user by param id exports.getUser = async (req, res, next) => { try { const user = await User.findById(req.params.id); return res.status(200).json({ status: 'success', data: { user: user } }); } catch (err) { res.status(404).json({ status: 'fail', message: 'Can not serve the request get user.' }); } };
import React from 'react'; import Users from './Users'; //import * as axios from 'axios'; import {follow, unfollow, setCurrentPage, toggleFollowingProgress, getUsersThunkCreator} from '../../redux/users-reducer'; import {connect} from 'react-redux'; import Preloader from '../common/preloader/Preloader.jsx'; import {withAuthRedirect} from '../../hoc/withAuthRedirect'; import {compose} from 'redux'; import {getUsers, getPageSize, getPortionSize, getTotalUsersCount, getCurrentPage, getIsFetching, getFollowingInProgress} from '../../redux/users-selectors'; let mapStateToProps = (state) =>{ return { users: getUsers(state), portionSize: getPortionSize(state), pageSize: getPageSize(state), totalUsersCount: getTotalUsersCount(state), currentPage: getCurrentPage(state), isFetching: getIsFetching(state), followingInProgress: getFollowingInProgress(state) } }; class UsersContainer extends React.Component { componentDidMount(){ const {currentPage, pageSize} = this.props; this.props.getUsersThunkCreator(currentPage, pageSize); } onPageChanged = (pageNumber) => { const {pageSize} = this.props; this.props.getUsersThunkCreator(pageNumber, pageSize); } render(){ return <> {this.props.isFetching ? <Preloader/> : null} <Users totalUsersCount={this.props.totalUsersCount} pageSize={this.props.pageSize} portionSize={this.props.portionSize} currentPage={this.props.currentPage} selectedPage={this.props.selectedPage} onPageChanged ={this.onPageChanged} isFetching={this.props.isFetching} follow={this.props.follow} unfollow={this.props.unfollow} users={this.props.users} toggleFollowingProgress={this.props.toggleFollowingProgress} followingInProgress={this.props.followingInProgress} /> </> } } let mapDispatchToProps = {follow, unfollow, setCurrentPage, toggleFollowingProgress, getUsersThunkCreator}; export default compose( withAuthRedirect, connect(mapStateToProps, mapDispatchToProps) )(UsersContainer);
const {table} = require('table'); const color = require('colors'); const mysql = require("mysql"); /** * Main database function for customers to connect and disconnect from database, view products * and make purchases. */ let SQLmain = function () { this.data = [ ['Item Number'.blue, 'Description'.yellow, 'Department'.blue, 'Price'.green] ]; this.output = ''; this.listOfIds = []; this.connection = mysql.createConnection({ //Parameters to connect to db. host: "localhost", port: 3306, user: 'alex', password: 'password', database: 'bamazon' }); this.dbDisconnect = function () {//Function to allow disconnect from the db this.connection.end(); }; this.displayDB = function () {//Displays all products available this.connection.query('SELECT * FROM products', (err, res) => { if (err) { throw err; } else { for (let i = 0; i < res.length; i++) { this.listOfIds.push(res[i].item_id.toString()); this.data.push([`${res[i].item_id}`, `${res[i].product_name}`, `${res[i].department_name}`, `$${res[i].price}`]); } //ends for loop } //ends else console.log(` Available items for sale.`.bgCyan); this.output = table(this.data); console.log(this.output); }); //ends connection.query }; //ends displayDB this.processOrder = function (id, qty) {//Runs quesries to allow purchase to go through this.id = id; this.qty = qty; this.okToBuy = false; if(this.listOfIds.indexOf(this.id) !== -1){ this.connection.query(`SELECT stock_quantity,price,product_name FROM products WHERE item_id=${parseInt(this.id)}`, (err, res) => { if (err) { throw err; } else { if (this.qty <= res[0].stock_quantity) { this.newQty = res[0].stock_quantity - this.qty; this.newVal = res[0].price * this.qty; this.connection.query('UPDATE products SET ? WHERE ?', [{ stock_quantity: this.newQty, product_sales: this.newVal }, { item_id: this.id }, ]); console.log(`You purchased ${this.qty} ${res[0].product_name}(s) for a total of $${this.newVal}`); } else { console.log(`Sorry! We only have ${res[0].stock_quantity} ${res[0].product_name}(s) in stock.`); } } //ends else }); //ends connection.query } else { console.log('Invalid ID. Transaction cancelled.'.red); } }; this.dbConnect = function () {//connects o db this.connection.connect(function (err) { if (err) throw err; }); }; this.dbConnect(); }; //ends SQLmain function module.exports = SQLmain;
var Marketplace = artifacts.require('Marketplace') contract('Marketplace', function(accounts) { const owner = accounts[0] const alice = accounts[1] const bob = accounts[2] const charlie = accounts[3] const emptyAddress = "0x0000000000000000000000000000000000000000" /* Test 1: Tests whether owner can add another admin */ it("should add an admin", async() => { const marketplace = await Marketplace.deployed({from: owner}) var eventEmitted = false var event = marketplace.AdminAdded() await event.watch((err,res) => { eventEmitted = true }) await marketplace.addAdmin(alice, {from: owner}) const result = await marketplace.userStatus.call(alice) assert.equal(result, 1, "the address of the admin was not added") assert.equal(eventEmitted, true, "adding an admin should emit a AdminAdded Event") }) /* Test 2: Tests whether a new admin can add a storeowner */ it("should add a storeowner", async() => { const marketplace = await Marketplace.deployed() var eventEmitted = false var event = marketplace.StoreownerAdded() await event.watch((err,res) => { eventEmitted = true }) await marketplace.addStoreowner(bob, {from: alice}) const result = await marketplace.userStatus.call(bob) assert.equal(result, 2, "the address of the storeowner was not added") assert.equal(eventEmitted, true, "adding a storeowner should emit a SoreownerAdded Event") }) // Test 3: tests whether a storeowner and another admin can open a store it("should open a store", async() => { const marketplace = await Marketplace.deployed() var eventEmitted = false var event = marketplace.StoreOpened() await event.watch((err, res) => { eventEmitted = true }) await marketplace.openStore({from: alice}) const result1_1 = await marketplace.storeId.call() const result1_2 = await marketplace.fetchStoreowner(1) await marketplace.openStore({from: bob}) const result2_1 = await marketplace.storeId.call() const result2_2 = await marketplace.fetchStoreowner(2) assert.equal(result1_1, 1, "the store was not opened") assert.equal(result1_2, alice, "the address of the storeowner is wrong") assert.equal(result2_1, 2, "not all stores were opened") assert.equal(result2_2, bob, "the address of a storeowner is wrong") assert.equal(eventEmitted, true, "opening a store should emit a Store Opened Event") }) // Test 4: tests whether a storeowner can list an item after opening a store it("should list an item", async() => { const marketplace = await Marketplace.deployed() var eventEmitted = false var event = marketplace.ItemListed() await event.watch((err, res) => { eventEmitted = true }) await marketplace.listItem(1, "boots", 2, {from: alice}) const result1_1 = await marketplace.itemId.call() const result1_2 = await marketplace.fetchItem(1) assert.equal(result1_1, 1, "the item was not added") assert.equal(result1_2[0], 1, "the shop of the listed item is incorrect") assert.equal(result1_2[2], "boots", "the name of the listed item is incorrect") assert.equal(result1_2[3], 2, "the price of the listed item is incorrect") assert.equal(result1_2[4], 0, "the status of the item is incorrect") assert.equal(result1_2[5], alice, "the seller of the listed item is incorrect") assert.equal(result1_2[6], emptyAddress, "the buyer of the listed item should be empty") assert.equal(eventEmitted, true, "listing an item should emit a Item Listed Event") }) // tests whether a listed item can be bought it("should buy an item", async() => { const marketplace = await Marketplace.deployed() var eventEmitted = false var event = marketplace.ItemSold() await event.watch((err, res) => { eventEmitted = true }) var amount = web3.toWei(2, "ether") await marketplace.buyItem(1, {from: bob, value: amount}) const result1_1 = await marketplace.fetchItem(1) assert.equal(result1_1[6], bob, "the buyer of the item is incorrect") assert.equal(eventEmitted, true, "buying an item should emit a Item Sold Event") }) });
export default firebaseConfig = { apiKey: "AIzaSyCduuJq491xyTbkUJE8m1eXvxxZlRgXU9M", authDomain: "moviesarea-c286b.firebaseapp.com", projectId: "moviesarea-c286b", storageBucket: "moviesarea-c286b.appspot.com", messagingSenderId: "33453687652", appId: "1:33453687652:web:6863a777f3b993d5683071", measurementId: "G-9MCWLCCD6W" };
Messages = new Mongo.Collection("messages"); Chats = new Mongo.Collection("chats"); if (Meteor.isClient) { Tracker.autorun(function () { Meteor.subscribe("messages", {chat: Session.get("selectedChat")}); }); Meteor.subscribe("chats"); Template.message.helpers({ isAuthor: function () { return this.author === Meteor.userId(); } }); Template.registerHelper('fromNow', function(date) { if (date) { return moment(date).fromNow(); } }); Template.chatList.helpers({ selectedChat: function () { selectedChat = Chats.findOne(Session.get("selectedChat")); return selectedChat && selectedChat.name; } }); Template.body.helpers({ messages: function () { return Messages.find({}, {sort: {createdAt: -1}}); }, chats: function () { return Chats.find({}, {sort: {createdAt: -1}}); } }); Template.chat.helpers({ selected: function () { return Session.equals("selectedChat", this._id) ? "selected" : ''; } }); Template.chat.events({ 'click': function () { var chat = this._id; Session.set("selectedChat", chat); var user = Meteor.userId(); Meteor.users.update({_id: user}, {$set: {'profile.selectedChat': chat}}); } }); Template.body.events({ "submit .new-message": function (event) { var text = event.target.text.value; var chat = Session.get("selectedChat"); Meteor.call("addMessage", text, chat); event.target.text.value = ""; return false; }, "submit .new-chat": function (event) { var name = event.target.text.value; Meteor.call("addChat", name); event.target.text.value = ""; return false; } }); Template.message.events({ "click .delete": function () { Meteor.call("deleteMessage", this._id); } }); Accounts.ui.config({ passwordSignupFields: "USERNAME_ONLY" }); } if (Meteor.isServer) { Meteor.startup(function () { Meteor.publish("chats", function() { return Chats.find(); }); Meteor.publish("messages", function () { var user = Meteor.users.findOne(this.userId); var selectedChat = user.profile.selectedChat; return Messages.find({ chat: selectedChat }); }); }); } Meteor.methods({ addChat: function (name) { if (! Meteor.userId()) { throw new Meteor.Error("not-authorized"); } Chats.insert({ name: name, createdAt: new Date (), owner: Meteor.userId(), }); }, addMessage: function (text, chat) { if (! Meteor.userId()) { throw new Meteor.Error("not-authorized"); } Messages.insert({ text: text, createdAt: new Date(), author: Meteor.userId(), username: Meteor.user().username || Meteor.user().profile.name, chat: chat }); }, deleteMessage: function (messageId) { var message = Messages.findOne(messageId); if (message.author !== Meteor.userId()) { throw new Meteor.Error("not-authorized"); } Messages.remove(messageId); } });
import jwt from "jsonwebtoken"; import dotenv from "dotenv"; dotenv.config(); const authorization = async (req, res, next) => { try { // GET The JWT Token const jwtToken = req.header("token"); if (!jwtToken) { // if it doesn'exist res.status(403).send({ message: "You are not authorized", }); } // Check to verify const payload = jwt.verify(jwtToken, process.env.jwtSecret); // if checked // give it to the req.user - .id - req.user = payload.user; next(); } catch (err) { res.status(403).send({ message: "You are not authorized", }); } }; export default authorization;
/** * Configure your Gatsby site with this file. * * See: https://www.gatsbyjs.org/docs/gatsby-config/ */ module.exports = { siteMetadata: { title: "KnoGeo", description: "KnoGeo", keywords: "KnoGeo", siteUrl: `https://www.KnoGeo.com`, }, plugins: [ { resolve: "gatsby-plugin-robots-txt", options: { host: "https://www.KnoGeo.com", sitemap: "https://www.KnoGeo.com/sitemap.xml", policy: [{ userAgent: "*", allow: "/" }], }, }, "gatsby-plugin-sitemap", { // keep as first gatsby-source-filesystem plugin for gatsby image support resolve: "gatsby-source-filesystem", options: { path: `${__dirname}/static/images`, name: "images", }, }, `gatsby-plugin-sharp`, { resolve: `gatsby-transformer-sharp`, options: { maxWidth: 2560, quality: 90, }, }, `gatsby-plugin-react-helmet`, { resolve: "gatsby-plugin-manifest", options: { name: "KnoGeo", short_name: "KnoGeo", icon: "static/images/icon.png", start_url: "/", background_color: "#0D0A0B", theme_color: "#0074b8", display: "standalone", }, }, `gatsby-plugin-styled-components`, ], }
!(function (NioApp, $) { "use strict"; //////// for developer - User Balance //////// // Avilable options to pass from outside // labels: array, // legend: false - boolean, // dataUnit: string, (Used in tooltip or other section for display) // datasets: [{label : string, color: string (color code with # or other format), data: array}] // // Student enrolement chart var enrolement = { labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], dataUnit: 'USD', stacked: true, datasets: [{ label: "Sales Revenue", color: [NioApp.hexRGB("#6576ff", .2), NioApp.hexRGB("#6576ff", .2), NioApp.hexRGB("#6576ff", .2), NioApp.hexRGB("#6576ff", .2), NioApp.hexRGB("#6576ff", .2), NioApp.hexRGB("#6576ff", .2), NioApp.hexRGB("#6576ff", .2), NioApp.hexRGB("#6576ff", .2), NioApp.hexRGB("#6576ff", .2), NioApp.hexRGB("#6576ff", .2), NioApp.hexRGB("#6576ff", .2), "#6576ff"], //@v2.0 data: [11000, 8000, 12500, 5500, 9500, 14299, 11000, 8000, 12500, 5500, 9500, 14299] }] }; function enrolementChart(selector, set_data) { var $selector = (selector) ? $(selector) : $('.student-enrole'); $selector.each(function () { var $self = $(this), _self_id = $self.attr('id'), _get_data = (typeof set_data === 'undefined') ? eval(_self_id) : set_data, _d_legend = (typeof _get_data.legend === 'undefined') ? false : _get_data.legend; var selectCanvas = document.getElementById(_self_id).getContext("2d"); var chart_data = []; for (var i = 0; i < _get_data.datasets.length; i++) { chart_data.push({ label: _get_data.datasets[i].label, data: _get_data.datasets[i].data, // Styles backgroundColor: _get_data.datasets[i].color, borderWidth: 2, borderColor: 'transparent', hoverBorderColor: 'transparent', borderSkipped: 'bottom', barPercentage: .7, categoryPercentage: .7 }); } var chart = new Chart(selectCanvas, { type: 'bar', data: { labels: _get_data.labels, datasets: chart_data, }, options: { legend: { display: (_get_data.legend) ? _get_data.legend : false, labels: { boxWidth: 30, padding: 20, fontColor: '#6783b8', } }, maintainAspectRatio: false, tooltips: { enabled: true, rtl: NioApp.State.isRTL, callbacks: { title: function (tooltipItem, data) { return false; }, label: function (tooltipItem, data) { return data['labels'][tooltipItem['index']] + ' ' + data.datasets[tooltipItem.datasetIndex]['data'][tooltipItem['index']]; } }, backgroundColor: '#eff6ff', titleFontSize: 11, titleFontColor: '#6783b8', titleMarginBottom: 4, bodyFontColor: '#9eaecf', bodyFontSize: 10, bodySpacing: 3, yPadding: 8, xPadding: 8, footerMarginTop: 0, displayColors: false }, scales: { yAxes: [{ display: false, stacked: (_get_data.stacked) ? _get_data.stacked : false, ticks: { beginAtZero: true } }], xAxes: [{ display: false, stacked: (_get_data.stacked) ? _get_data.stacked : false, ticks: { reverse: NioApp.State.isRTL } }] } } }); }) } // init chart NioApp.coms.docReady.push(function () { enrolementChart(); }); // // Course Progress Chart var courseProgress = { labels: ["Web Development", "Mobile Application", "Graphics Design", "Database", "Marketing", "Machine Learning", "Data Science"], stacked: true, datasets: [{ label: "Weekly Enrole", color: ["#f98c45", "#6baafe", "#8feac5", "#6b79c8", "#79f1dc", "#FF65B6", "#6A29FF"], data: [1740, 2500, 1820, 1200, 1600, 2500, 2250, 3410] // data: [2500, 2500, 2500, 2500, 2500, 2800] }, { label: "Monthly Enrole", color: [NioApp.hexRGB('#f98c45', .2), NioApp.hexRGB('#6baafe', .4), NioApp.hexRGB('#8feac5', .4), NioApp.hexRGB('#6b79c8', .4), NioApp.hexRGB('#79f1dc', .4), NioApp.hexRGB('#FF65B6', .4), NioApp.hexRGB('#6A29FF', .4)], data: [2420, 1820, 3000, 5000, 2450, 1820, 2000, 1890] // data: [1820, 1820, 1820, 1820, 1820, 1120] }] }; function courseProgressChart(selector, set_data) { var $selector = (selector) ? $(selector) : $('.course-progress-chart'); $selector.each(function () { var $self = $(this), _self_id = $self.attr('id'), _get_data = (typeof set_data === 'undefined') ? eval(_self_id) : set_data, _d_legend = (typeof _get_data.legend === 'undefined') ? false : _get_data.legend; var selectCanvas = document.getElementById(_self_id).getContext("2d"); var chart_data = []; for (var i = 0; i < _get_data.datasets.length; i++) { chart_data.push({ label: _get_data.datasets[i].label, data: _get_data.datasets[i].data, // Styles backgroundColor: _get_data.datasets[i].color, borderWidth: 2, borderColor: 'transparent', hoverBorderColor: 'transparent', borderSkipped: 'bottom', barThickness: '8', categoryPercentage: 0.5, barPercentage: 1.0 }); } var chart = new Chart(selectCanvas, { type: 'horizontalBar', data: { labels: _get_data.labels, datasets: chart_data, }, options: { legend: { display: (_get_data.legend) ? _get_data.legend : false, rtl: NioApp.State.isRTL, labels: { boxWidth: 30, padding: 20, fontColor: '#6783b8', } }, maintainAspectRatio: false, tooltips: { enabled: true, rtl: NioApp.State.isRTL, callbacks: { title: function (tooltipItem, data) { return data['labels'][tooltipItem[0]['index']]; }, label: function (tooltipItem, data) { return data.datasets[tooltipItem.datasetIndex]['data'][tooltipItem['index']] + ' ' + data.datasets[tooltipItem.datasetIndex]['label']; } }, backgroundColor: '#eff6ff', titleFontSize: 13, titleFontColor: '#6783b8', titleMarginBottom: 6, bodyFontColor: '#9eaecf', bodyFontSize: 12, bodySpacing: 4, yPadding: 10, xPadding: 10, footerMarginTop: 0, displayColors: false }, scales: { yAxes: [{ display: false, stacked: (_get_data.stacked) ? _get_data.stacked : false, ticks: { beginAtZero: true, padding: 0, }, gridLines: { color: NioApp.hexRGB("#526484", .2), tickMarkLength: 0, zeroLineColor: NioApp.hexRGB("#526484", .2) }, }], xAxes: [{ display: false, stacked: (_get_data.stacked) ? _get_data.stacked : false, ticks: { fontSize: 9, fontColor: '#9eaecf', source: 'auto', padding: 0, reverse: NioApp.State.isRTL }, gridLines: { color: "transparent", tickMarkLength: 0, zeroLineColor: 'transparent', }, }] } } }); }) } // init chart NioApp.coms.docReady.push(function () { courseProgressChart(); }); // var analyticAuData = { labels: ["01 Jan", "02 Jan", "03 Jan", "04 Jan", "05 Jan", "06 Jan", "07 Jan", "08 Jan", "09 Jan", "10 Jan", "11 Jan", "12 Jan", "13 Jan", "14 Jan", "15 Jan", "16 Jan", "17 Jan", "18 Jan", "19 Jan", "20 Jan", "21 Jan", "22 Jan", "23 Jan", "24 Jan", "25 Jan", "26 Jan", "27 Jan", "28 Jan", "29 Jan", "30 Jan"], dataUnit: 'People', lineTension: .1, datasets: [{ label: "Active Users", color: "#9cabff", background: "#9cabff", data: [1110, 1220, 1310, 980, 900, 770, 1060, 830, 690, 730, 790, 950, 1100, 800, 1250, 850, 950, 450, 900, 1000, 1200, 1250, 900, 950, 1300, 1200, 1250, 650, 950, 750] }] }; function analyticsAu(selector, set_data) { var $selector = (selector) ? $(selector) : $('.analytics-au-chart'); $selector.each(function () { var $self = $(this), _self_id = $self.attr('id'), _get_data = (typeof set_data === 'undefined') ? eval(_self_id) : set_data; var selectCanvas = document.getElementById(_self_id).getContext("2d"); var chart_data = []; for (var i = 0; i < _get_data.datasets.length; i++) { chart_data.push({ label: _get_data.datasets[i].label, tension: _get_data.lineTension, backgroundColor: _get_data.datasets[i].background, borderWidth: 2, borderColor: _get_data.datasets[i].color, data: _get_data.datasets[i].data, barPercentage: .7, categoryPercentage: .7 }); } var chart = new Chart(selectCanvas, { type: 'bar', data: { labels: _get_data.labels, datasets: chart_data, }, options: { legend: { display: (_get_data.legend) ? _get_data.legend : false, rtl: NioApp.State.isRTL, labels: { boxWidth: 12, padding: 20, fontColor: '#6783b8', } }, maintainAspectRatio: false, tooltips: { enabled: true, rtl: NioApp.State.isRTL, callbacks: { title: function (tooltipItem, data) { return false; //data['labels'][tooltipItem[0]['index']]; }, label: function (tooltipItem, data) { return data.datasets[tooltipItem.datasetIndex]['data'][tooltipItem['index']]; } }, backgroundColor: '#eff6ff', titleFontSize: 9, titleFontColor: '#6783b8', titleMarginBottom: 6, bodyFontColor: '#9eaecf', bodyFontSize: 9, bodySpacing: 4, yPadding: 6, xPadding: 6, footerMarginTop: 0, displayColors: false }, scales: { yAxes: [{ display: true, position: NioApp.State.isRTL ? "right" : "left", ticks: { beginAtZero: false, fontSize: 12, fontColor: '#9eaecf', padding: 0, display: false, stepSize: 300 }, gridLines: { color: NioApp.hexRGB("#526484", .2), tickMarkLength: 0, zeroLineColor: NioApp.hexRGB("#526484", .2), }, }], xAxes: [{ display: false, ticks: { fontSize: 12, fontColor: '#9eaecf', source: 'auto', padding: 0, reverse: NioApp.State.isRTL }, gridLines: { color: "transparent", tickMarkLength: 0, zeroLineColor: 'transparent', offsetGridLines: true, } }] } } }); }) } // init chart NioApp.coms.docReady.push(function () { analyticsAu(); }); var totalSells = { labels: ["01 Jan", "02 Jan", "03 Jan", "04 Jan", "05 Jan", "06 Jan", "07 Jan", "08 Jan", "09 Jan", "10 Jan", "11 Jan", "12 Jan", "13 Jan", "14 Jan", "15 Jan", "16 Jan", "17 Jan", "18 Jan", "19 Jan", "20 Jan", "21 Jan", "22 Jan", "23 Jan", "24 Jan", "25 Jan", "26 Jan", "27 Jan", "28 Jan", "29 Jan", "30 Jan"], dataUnit: 'Orders', lineTension: .3, datasets: [{ label: "Courses", color: "#6A29FF", background: NioApp.hexRGB('#6A29FF', .25), data: [85, 125, 105, 115, 130, 106, 141, 110, 95, 120, 111, 105, 113, 107, 122, 100, 95, 110, 120, 107, 100, 105, 123, 115, 110, 117, 125, 75, 95, 101] }] }; var weeklySells = { labels: ["01 Jan", "02 Jan", "03 Jan", "04 Jan", "05 Jan", "06 Jan", "07 Jan", "08 Jan", "09 Jan", "10 Jan", "11 Jan", "12 Jan", "13 Jan", "14 Jan", "15 Jan", "16 Jan", "17 Jan", "18 Jan", "19 Jan", "20 Jan", "21 Jan", "22 Jan", "23 Jan", "24 Jan", "25 Jan", "26 Jan", "27 Jan", "28 Jan", "29 Jan", "30 Jan"], dataUnit: 'Students', lineTension: .3, datasets: [{ label: "Students", color: "#4258FF", background: NioApp.hexRGB('#4258FF', .25), data: [92, 105, 125, 85, 110, 106, 131, 105, 110, 115, 135, 105, 120, 85, 122, 100, 125, 110, 120, 125, 85, 105, 123, 115, 90, 117, 125, 100, 95, 65] }] }; function courseSellsChart(selector, set_data) { var $selector = (selector) ? $(selector) : $('.courseSells'); $selector.each(function () { var $self = $(this), _self_id = $self.attr('id'), _get_data = (typeof set_data === 'undefined') ? eval(_self_id) : set_data; var selectCanvas = document.getElementById(_self_id).getContext("2d"); var chart_data = []; for (var i = 0; i < _get_data.datasets.length; i++) { chart_data.push({ label: _get_data.datasets[i].label, tension: _get_data.lineTension, backgroundColor: _get_data.datasets[i].background, borderWidth: 2, borderColor: _get_data.datasets[i].color, pointBorderColor: 'transparent', pointBackgroundColor: 'transparent', pointHoverBackgroundColor: "#fff", pointHoverBorderColor: _get_data.datasets[i].color, pointBorderWidth: 2, pointHoverRadius: 4, pointHoverBorderWidth: 2, pointRadius: 4, pointHitRadius: 4, data: _get_data.datasets[i].data, }); } var chart = new Chart(selectCanvas, { type: 'line', data: { labels: _get_data.labels, datasets: chart_data, }, options: { legend: { display: (_get_data.legend) ? _get_data.legend : false, rtl: NioApp.State.isRTL, labels: { boxWidth: 12, padding: 20, fontColor: '#6783b8', } }, maintainAspectRatio: false, tooltips: { enabled: true, rtl: NioApp.State.isRTL, callbacks: { title: function (tooltipItem, data) { return data['labels'][tooltipItem[0]['index']]; }, label: function (tooltipItem, data) { return data.datasets[tooltipItem.datasetIndex]['data'][tooltipItem['index']] + ' ' + _get_data.dataUnit; } }, backgroundColor: '#1c2b46', titleFontSize: 10, titleFontColor: '#fff', titleMarginBottom: 4, bodyFontColor: '#fff', bodyFontSize: 10, bodySpacing: 4, yPadding: 6, xPadding: 6, footerMarginTop: 0, displayColors: false }, scales: { yAxes: [{ display: false, ticks: { beginAtZero: true, fontSize: 12, fontColor: '#9eaecf', padding: 0 }, gridLines: { color: NioApp.hexRGB("#526484", .2), tickMarkLength: 0, zeroLineColor: NioApp.hexRGB("#526484", .2) }, }], xAxes: [{ display: false, ticks: { fontSize: 12, fontColor: '#9eaecf', source: 'auto', padding: 0, reverse: NioApp.State.isRTL }, gridLines: { color: "transparent", tickMarkLength: 0, zeroLineColor: NioApp.hexRGB("#526484", .2), offsetGridLines: true, } }] } } }); }) } // init chart NioApp.coms.docReady.push(function () { courseSellsChart(); }); // Traffic var TrafficChannelDoughnutData = { labels: ["Organic Search", "Social Media", "Referrals", "Others"], dataUnit: 'People', legend: false, datasets: [{ borderColor: "#fff", background: ["#9d72ff", "#b8acff", "#ffa9ce", "#f9db7b"], data: [4305, 859, 482, 138] }] }; function analyticsDoughnut(selector, set_data) { var $selector = (selector) ? $(selector) : $('.analytics-doughnut'); $selector.each(function () { var $self = $(this), _self_id = $self.attr('id'), _get_data = (typeof set_data === 'undefined') ? eval(_self_id) : set_data; var selectCanvas = document.getElementById(_self_id).getContext("2d"); var chart_data = []; for (var i = 0; i < _get_data.datasets.length; i++) { chart_data.push({ backgroundColor: _get_data.datasets[i].background, borderWidth: 2, borderColor: _get_data.datasets[i].borderColor, hoverBorderColor: _get_data.datasets[i].borderColor, data: _get_data.datasets[i].data, }); } var chart = new Chart(selectCanvas, { type: 'doughnut', data: { labels: _get_data.labels, datasets: chart_data, }, options: { legend: { display: (_get_data.legend) ? _get_data.legend : false, rtl: NioApp.State.isRTL, labels: { boxWidth: 12, padding: 20, fontColor: '#6783b8', } }, rotation: -1.5, cutoutPercentage: 70, maintainAspectRatio: false, tooltips: { enabled: true, rtl: NioApp.State.isRTL, callbacks: { title: function (tooltipItem, data) { return data['labels'][tooltipItem[0]['index']]; }, label: function (tooltipItem, data) { return data.datasets[tooltipItem.datasetIndex]['data'][tooltipItem['index']] + ' ' + _get_data.dataUnit; } }, backgroundColor: '#1c2b46', titleFontSize: 13, titleFontColor: '#fff', titleMarginBottom: 6, bodyFontColor: '#fff', bodyFontSize: 12, bodySpacing: 4, yPadding: 10, xPadding: 10, footerMarginTop: 0, displayColors: false }, } }); }) } // init chart NioApp.coms.docReady.push(function () { analyticsDoughnut(); }); })(NioApp, jQuery); // Dashboard 2 Charts var totalSales = { labels: ["01 Jan", "02 Jan", "03 Jan", "04 Jan", "05 Jan", "06 Jan", "07 Jan", "08 Jan", "09 Jan", "10 Jan", "11 Jan", "12 Jan", "13 Jan", "14 Jan", "15 Jan", "16 Jan", "17 Jan", "18 Jan", "19 Jan", "20 Jan", "21 Jan", "22 Jan", "23 Jan", "24 Jan", "25 Jan", "26 Jan", "27 Jan", "28 Jan", "29 Jan", "30 Jan"], dataUnit: 'Sales', lineTension: .3, datasets: [{ label: "Sales", color: "#9d72ff", background: NioApp.hexRGB('#9d72ff', .25), data: [130, 105, 125, 115, 110, 95, 131, 110, 115, 120, 111, 97, 113, 107, 122, 100, 85, 110, 130, 107, 90, 105, 123, 115, 100, 117, 125, 95, 137, 101] }] }; var totalOrders = { labels: ["01 Jan", "02 Jan", "03 Jan", "04 Jan", "05 Jan", "06 Jan", "07 Jan", "08 Jan", "09 Jan", "10 Jan", "11 Jan", "12 Jan", "13 Jan", "14 Jan", "15 Jan", "16 Jan", "17 Jan", "18 Jan", "19 Jan", "20 Jan", "21 Jan", "22 Jan", "23 Jan", "24 Jan", "25 Jan", "26 Jan", "27 Jan", "28 Jan", "29 Jan", "30 Jan"], dataUnit: 'Orders', lineTension: .3, datasets: [{ label: "Orders", color: "#7de1f8", background: NioApp.hexRGB('#7de1f8', .25), data: [85, 125, 105, 115, 130, 106, 141, 110, 95, 120, 111, 105, 113, 107, 122, 100, 95, 110, 120, 107, 100, 105, 123, 115, 110, 117, 125, 75, 95, 101] }] }; var activeStudents = { labels: ["01 Jan", "02 Jan", "03 Jan", "04 Jan", "05 Jan", "06 Jan", "07 Jan", "08 Jan", "09 Jan", "10 Jan", "11 Jan", "12 Jan", "13 Jan", "14 Jan", "15 Jan", "16 Jan", "17 Jan", "18 Jan", "19 Jan", "20 Jan", "21 Jan", "22 Jan", "23 Jan", "24 Jan", "25 Jan", "26 Jan", "27 Jan", "28 Jan", "29 Jan", "30 Jan"], dataUnit: 'Students', lineTension: .3, datasets: [{ label: "Students", color: "#7de1f8", background: NioApp.hexRGB('#7de1f8', .25), data: [85, 125, 105, 115, 130, 106, 141, 110, 95, 120, 111, 105, 113, 107, 122, 100, 95, 110, 120, 107, 100, 105, 123, 115, 110, 117, 125, 75, 95, 101] }] }; var newStudents = { labels: ["01 Jan", "02 Jan", "03 Jan", "04 Jan", "05 Jan", "06 Jan", "07 Jan", "08 Jan", "09 Jan", "10 Jan", "11 Jan", "12 Jan", "13 Jan", "14 Jan", "15 Jan", "16 Jan", "17 Jan", "18 Jan", "19 Jan", "20 Jan", "21 Jan", "22 Jan", "23 Jan", "24 Jan", "25 Jan", "26 Jan", "27 Jan", "28 Jan", "29 Jan", "30 Jan"], dataUnit: 'Students', lineTension: .3, datasets: [{ label: "Students", color: "#83bcff", background: NioApp.hexRGB('#83bcff', .25), data: [92, 105, 125, 85, 110, 106, 131, 105, 110, 115, 135, 105, 120, 85, 122, 100, 125, 110, 120, 125, 85, 105, 123, 115, 90, 117, 125, 100, 95, 65] }] }; var totalCustomers = { labels: ["01 Jan", "02 Jan", "03 Jan", "04 Jan", "05 Jan", "06 Jan", "07 Jan", "08 Jan", "09 Jan", "10 Jan", "11 Jan", "12 Jan", "13 Jan", "14 Jan", "15 Jan", "16 Jan", "17 Jan", "18 Jan", "19 Jan", "20 Jan", "21 Jan", "22 Jan", "23 Jan", "24 Jan", "25 Jan", "26 Jan", "27 Jan", "28 Jan", "29 Jan", "30 Jan"], dataUnit: 'Customers', lineTension: .3, datasets: [{ label: "Customers", color: "#83bcff", background: NioApp.hexRGB('#83bcff', .25), data: [92, 105, 125, 85, 110, 106, 131, 105, 110, 115, 135, 105, 120, 85, 122, 100, 125, 110, 120, 125, 85, 105, 123, 115, 90, 117, 125, 100, 95, 65] }] }; function lmsLineS1(selector, set_data) { var $selector = (selector) ? $(selector) : $('.lms-line-chart-s1'); $selector.each(function () { var $self = $(this), _self_id = $self.attr('id'), _get_data = (typeof set_data === 'undefined') ? eval(_self_id) : set_data; var selectCanvas = document.getElementById(_self_id).getContext("2d"); var chart_data = []; for (var i = 0; i < _get_data.datasets.length; i++) { chart_data.push({ label: _get_data.datasets[i].label, tension: _get_data.lineTension, backgroundColor: _get_data.datasets[i].background, borderWidth: 2, borderColor: _get_data.datasets[i].color, pointBorderColor: 'transparent', pointBackgroundColor: 'transparent', pointHoverBackgroundColor: "#fff", pointHoverBorderColor: _get_data.datasets[i].color, pointBorderWidth: 2, pointHoverRadius: 4, pointHoverBorderWidth: 2, pointRadius: 4, pointHitRadius: 4, data: _get_data.datasets[i].data, }); } var chart = new Chart(selectCanvas, { type: 'line', data: { labels: _get_data.labels, datasets: chart_data, }, options: { legend: { display: (_get_data.legend) ? _get_data.legend : false, rtl: NioApp.State.isRTL, labels: { boxWidth: 12, padding: 20, fontColor: '#6783b8', } }, maintainAspectRatio: false, tooltips: { enabled: true, rtl: NioApp.State.isRTL, callbacks: { title: function (tooltipItem, data) { return data['labels'][tooltipItem[0]['index']]; }, label: function (tooltipItem, data) { return data.datasets[tooltipItem.datasetIndex]['data'][tooltipItem['index']] + ' ' + _get_data.dataUnit; } }, backgroundColor: '#1c2b46', titleFontSize: 10, titleFontColor: '#fff', titleMarginBottom: 4, bodyFontColor: '#fff', bodyFontSize: 10, bodySpacing: 4, yPadding: 6, xPadding: 6, footerMarginTop: 0, displayColors: false }, scales: { yAxes: [{ display: false, ticks: { beginAtZero: true, fontSize: 12, fontColor: '#9eaecf', padding: 0 }, gridLines: { color: NioApp.hexRGB("#526484", .2), tickMarkLength: 0, zeroLineColor: NioApp.hexRGB("#526484", .2) }, }], xAxes: [{ display: false, ticks: { fontSize: 12, fontColor: '#9eaecf', source: 'auto', padding: 0, reverse: NioApp.State.isRTL }, gridLines: { color: "transparent", tickMarkLength: 0, zeroLineColor: NioApp.hexRGB("#526484", .2), offsetGridLines: true, } }] } } }); }) } // init chart NioApp.coms.docReady.push(function () { lmsLineS1(); }); var storeVisitors = { labels: ["01 Jan", "02 Jan", "03 Jan", "04 Jan", "05 Jan", "06 Jan", "07 Jan", "08 Jan", "09 Jan", "10 Jan", "11 Jan", "12 Jan", "13 Jan", "14 Jan", "15 Jan", "16 Jan", "17 Jan", "18 Jan", "19 Jan", "20 Jan", "21 Jan", "22 Jan", "23 Jan", "24 Jan", "25 Jan", "26 Jan", "27 Jan", "28 Jan", "29 Jan", "30 Jan"], dataUnit: 'People', lineTension: .1, datasets: [{ label: "Current Month", color: "#9d72ff", dash: 0, background: "transparent", data: [4110, 4220, 4810, 5480, 4600, 5670, 6660, 4830, 5590, 5730, 4790, 4950, 5100, 5800, 5950, 5850, 5950, 4450, 4900, 8000, 7200, 7250, 7900, 8950, 6300, 7200, 7250, 7650, 6950, 4750] }] }; function lmsLineS4(selector, set_data) { var $selector = (selector) ? $(selector) : $('.lms-line-chart-s4'); $selector.each(function () { var $self = $(this), _self_id = $self.attr('id'), _get_data = (typeof set_data === 'undefined') ? eval(_self_id) : set_data; var selectCanvas = document.getElementById(_self_id).getContext("2d"); var chart_data = []; for (var i = 0; i < _get_data.datasets.length; i++) { chart_data.push({ label: _get_data.datasets[i].label, tension: _get_data.lineTension, backgroundColor: _get_data.datasets[i].background, borderWidth: 2, borderDash: _get_data.datasets[i].dash, borderColor: _get_data.datasets[i].color, pointBorderColor: 'transparent', pointBackgroundColor: 'transparent', pointHoverBackgroundColor: "#fff", pointHoverBorderColor: _get_data.datasets[i].color, pointBorderWidth: 2, pointHoverRadius: 4, pointHoverBorderWidth: 2, pointRadius: 4, pointHitRadius: 4, data: _get_data.datasets[i].data, }); } var chart = new Chart(selectCanvas, { type: 'line', data: { labels: _get_data.labels, datasets: chart_data, }, options: { legend: { display: (_get_data.legend) ? _get_data.legend : false, rtl: NioApp.State.isRTL, labels: { boxWidth: 12, padding: 20, fontColor: '#6783b8', } }, maintainAspectRatio: false, tooltips: { enabled: true, rtl: NioApp.State.isRTL, callbacks: { title: function (tooltipItem, data) { return data['labels'][tooltipItem[0]['index']]; }, label: function (tooltipItem, data) { return data.datasets[tooltipItem.datasetIndex]['data'][tooltipItem['index']]; } }, backgroundColor: '#1c2b46', titleFontSize: 13, titleFontColor: '#fff', titleMarginBottom: 6, bodyFontColor: '#fff', bodyFontSize: 12, bodySpacing: 4, yPadding: 10, xPadding: 10, footerMarginTop: 0, displayColors: false }, scales: { yAxes: [{ display: true, stacked: (_get_data.stacked) ? _get_data.stacked : false, position: NioApp.State.isRTL ? "right" : "left", ticks: { beginAtZero: true, fontSize: 11, fontColor: '#9eaecf', padding: 10, callback: function (value, index, values) { return '$ ' + value; }, min: 0, stepSize: 3000 }, gridLines: { color: NioApp.hexRGB("#526484", .2), tickMarkLength: 0, zeroLineColor: NioApp.hexRGB("#526484", .2) }, }], xAxes: [{ display: false, stacked: (_get_data.stacked) ? _get_data.stacked : false, ticks: { fontSize: 9, fontColor: '#9eaecf', source: 'auto', padding: 10, reverse: NioApp.State.isRTL }, gridLines: { color: "transparent", tickMarkLength: 0, zeroLineColor: 'transparent', }, }] } } }); }) } // init chart NioApp.coms.docReady.push(function () { lmsLineS4(); }); var trafficSources = { labels: ["Organic Search", "Social Media", "Referrals", "Others"], dataUnit: 'People', legend: false, datasets: [{ borderColor: "#fff", background: ["#b695ff", "#b8acff", "#ffa9ce", "#f9db7b"], data: [4305, 859, 482, 138] }] }; function lmsDoughnutS1(selector, set_data) { var $selector = (selector) ? $(selector) : $('.lms-doughnut-s1'); $selector.each(function () { var $self = $(this), _self_id = $self.attr('id'), _get_data = (typeof set_data === 'undefined') ? eval(_self_id) : set_data; var selectCanvas = document.getElementById(_self_id).getContext("2d"); var chart_data = []; for (var i = 0; i < _get_data.datasets.length; i++) { chart_data.push({ backgroundColor: _get_data.datasets[i].background, borderWidth: 2, borderColor: _get_data.datasets[i].borderColor, hoverBorderColor: _get_data.datasets[i].borderColor, data: _get_data.datasets[i].data, }); } var chart = new Chart(selectCanvas, { type: 'doughnut', data: { labels: _get_data.labels, datasets: chart_data, }, options: { legend: { display: (_get_data.legend) ? _get_data.legend : false, rtl: NioApp.State.isRTL, labels: { boxWidth: 12, padding: 20, fontColor: '#6783b8', } }, rotation: -1.5, cutoutPercentage: 70, maintainAspectRatio: false, tooltips: { enabled: true, rtl: NioApp.State.isRTL, callbacks: { title: function (tooltipItem, data) { return data['labels'][tooltipItem[0]['index']]; }, label: function (tooltipItem, data) { return data.datasets[tooltipItem.datasetIndex]['data'][tooltipItem['index']] + ' ' + _get_data.dataUnit; } }, backgroundColor: '#1c2b46', titleFontSize: 13, titleFontColor: '#fff', titleMarginBottom: 6, bodyFontColor: '#fff', bodyFontSize: 12, bodySpacing: 4, yPadding: 10, xPadding: 10, footerMarginTop: 0, displayColors: false }, } }); }) } // init chart NioApp.coms.docReady.push(function () { lmsDoughnutS1(); });
import React, {Component} from 'react' import {omit} from 'lodash' export default class Tabs extends Component { componentWillMount() { if (!this.state) { this.setState({active: this.props.children.find(a => a.props.active).key}) } } componentWillReceiveProps(props) { if (this.props.active !== props.active) { this.setState({active: props.children.find(a => a.props.active).key}) } } open(key) { this.setState({active: (this.props.children.find(a => a.key === key) || this.props.children[0]).key}) } buttons(active) { const buttons = this.props.children.map(a => <a className={active === a.key ? 'active item' : 'item'} key={a.key} onClick={() => this.open(a.key)}>{a.props.title}</a>) return <div className="ui menu top attached tabular">{buttons}</div> } render() { const active = this.props.children.find(a => this.state.active === a.key) return <div className="tabs"> {this.buttons(active.key)} {active} </div> } } Tabs.Panel = function Panel(props) { const children = props.children props = omit(props, 'active', 'title', 'children') props.className = (props.className || '') + ' ui bottom attached active tab segment' return <div {...props}>{children}</div> }
import C from '../constants/actions'; export default function showTour(state = false, action) { switch (action.type) { case C.SKIP_TOUR: return false; default: return state; } }
import characteristics from './characteristics'; import originPropositions from './originPropositions'; import {selectOriginProposition, defaultSelectedOrigin} from './originPropositions'; import professionPropositions from './professionPropositions'; import {selectProfessionProposition, defaultSelectedProfession} from './professionPropositions'; const initialState = { characteristics : [ { title : `Courage`, number : 0 }, { title : `Intelligence`, number : 0 }, { title : `Charisme`, number : 0 }, { title : `Adresse`, number : 0 }, { title : `Force`, number : 0 } ], originPropositions : [], professionPropositions : [], isCheater : false, selectedOriginProposition : defaultSelectedOrigin, selectedProfessionProposition : defaultSelectedProfession }; const isCheater = (isCheater, action) => { switch (action.type) { case 'TOOGLE_CHEATER_MODE' : return !isCheater; default: return isCheater } }; const NaheulbeukApp = (state = initialState, action) => { return { characteristics : characteristics(state.characteristics, action), originPropositions : originPropositions(state, action), professionPropositions : professionPropositions(state, action), selectedOriginProposition : selectOriginProposition(state, action), selectedProfessionProposition : selectProfessionProposition(state, action), isCheater : isCheater(state.isCheater, action) } }; export default NaheulbeukApp;
/* Treehouse FSJS Techdegree * Project 4 - OOP Game App * app.js */ const startGame = document.querySelector("#btn__reset"); let game; //const game = new Game(); startGame.addEventListener("click",() =>{ game = new Game(); game.startGame(); }); console.log(game); const keyboards = document.querySelectorAll(".key"); document.addEventListener("keydown",(e)=>{ if(/^Key/.test(e.code)){ const letter = e.code.charAt(e.code.length-1).toLowerCase(); keyboards.forEach(keyboard =>{ if(keyboard.innerHTML === letter){ keyboard.click(); } }) } }); keyboards.forEach(keyboard => { keyboard.addEventListener("click",(e)=>{ game.handleInteraction(e.target); }); });
var emptyFunction = require('emptyFunction'); var Validator = require('Validator'); var Any = Validator('Any', { test: emptyFunction.thatReturnsTrue, assert: emptyFunction, }); module.exports = Any;
import React, { PropTypes } from 'react'; import { Link } from 'react-router'; import FlatButton from 'material-ui/FlatButton'; import ContentAdd from 'material-ui/svg-icons/content/add'; const CreateButton = ({ basePath = '' }) => <FlatButton primary label="Create" icon={<ContentAdd />} containerElement={<Link to={`${basePath}/create`} />} style={{ overflow: 'inherit' }}/>; CreateButton.propTypes = { basePath: PropTypes.string, }; export default CreateButton;
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsAirplay = { name: 'airplay', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M6 22h12l-6-6zM21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h4v-2H3V5h18v12h-4v2h4c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/></svg>` };
(function () { angular .module('myApp') .controller('GroupDigitViewController', GroupDigitViewController) GroupDigitViewController.$inject = ['$state', '$scope', '$rootScope', '$sce']; function GroupDigitViewController($state, $scope, $rootScope, $sce) { $rootScope.setData('showMenubar', true); $rootScope.setData('backUrl', "groupDigitAnswer"); $scope.question = $rootScope.settings.questionObj; if ($scope.question.result_videoID) { $scope.question.result_videoURL = $sce.trustAsResourceUrl('https://www.youtube.com/embed/' + $scope.question.result_videoID + "?rel=0&enablejsapi=1"); $rootScope.removeRecommnedVideo() } $rootScope.safeApply(); $scope.$on("$destroy", function () { if ($rootScope.instFeedRef) $rootScope.instFeedRef.off('value'); if ($rootScope.questionResultImageRef) $rootScope.questionResultImageRef.off('value') if ($scope.answerRef) $scope.answerRef.off('value') }); //Get Class Average Answer $scope.getclassAverage = function () { var sumval = 0; var i = 0; $scope.averageanswer = " "; $scope.answerRef = firebase.database().ref('GroupAnswers').orderByChild('questionKey').equalTo($rootScope.settings.questionKey); $scope.answerRef.on('value', function (snapshot) { for (var key in snapshot.val()) { var ansSnapshot = snapshot.val()[key]; var checkSecond = true; if ($rootScope.settings.groupType == 'second') { if (ansSnapshot.subSetKey != $rootScope.settings.subSetKey || ansSnapshot.secondIndex != $rootScope.settings.secondIndex) { checkSecond = false; } } if (ansSnapshot.groupType == $rootScope.settings.groupType && ansSnapshot.studentgroupkey == $rootScope.settings.groupKey && ansSnapshot.groupSetKey == $rootScope.settings.groupSetKey && ansSnapshot.subIndex == $rootScope.settings.subIndex && checkSecond) { sumval += ansSnapshot['answer']; i++; } } if (sumval && i) { $scope.averageanswer = (sumval / i).toFixed(1); } else { $scope.averageanswer = 0; } $rootScope.safeApply() }); } } })();
import {takeEvery, call, put} from 'redux-saga/effects' import {fetchSearchId} from "../../api/fetch"; import {FETCH_ID_FETCHING} from "./types"; import {fetchIdFailed, fetchIdSuccess} from "./actions"; import {saveSearchId} from "../tickets/actions"; export function* onGetSearchId() { try { const id = yield call(fetchSearchId) yield put(fetchIdSuccess()) yield put(saveSearchId(id)) } catch (e) { yield put(fetchIdFailed()) } } export default function* idSaga() { yield takeEvery(FETCH_ID_FETCHING, onGetSearchId) }
const {Router} = require('express'); const router = Router(); const jwt = require('jsonwebtoken'); const config = require('../config'); const verifyToken = require('../controllers/verifyToken'); /* Para guardar los datos de las peticiones post es necesario que el body contenga exactamente los datos solicitados en el modelo de Users, de igual forma para que esto funcione hay que importar el archivo de la carpeta models */ const User = require('../models/User'); router.post('/signup', async (req, res, next) => { const { username, email, password } = req.body; const user = new User({ // Guarda datos directamente a la DB username: username, email: email, password: password }); /* Agregando la configuración de hasheo */ user.password = await user.encryptPassword(user.password) await user.save(); /* Se devuelve un json y un token, el cual hay que importar (JWT) y también hay que configurarlo*/ /* EL método sign es el que permite crear el token y recibe como parámetro tres cosas: 1.- Payload, mas que nada es un id único 2.- Clave secreta, este debe ser un string, declarado en una variable de entorno o config 3.-Un buffer, es más que nada el tiempo en el que el token expirará y se declara en un objeto */ const token = jwt.sign({id: user._id}, config.secret, { expiresIn: 60 * 60 * 24 }) // Una vez configurado el token se pasa como valor en el objeto de la respuesta json res.json({auth: true, token}) }); // Verificación del token, se tendría que hacer el la ruta del perfil del usuario router.get('/me', verifyToken, async (req, res, next) => { const user = await User.findById(req.userId, { password: 0 }); if(!user) { return res.status(404).send('No user found') } res.json(user) }); // Validador de constraseñas router.post('/signin', async (req, res, next) => { // Necesitamos recibir solamente el email y el password del body const { email, password } = req.body; // hay que comprobar si el email o usuario existe para eso hay que llamar a la db const user = await User.findOne({email:email}) // En caso de que no exista la respuesta es 404 if(!user) { res.status(404).send("The email doesn't exists"); } // En el caso de que si exista hay que valudar la contaseña con un método creado desde el modelo const validPassword = await user.validatePassword(password) // Después de hacer la validación y todo coincida, lo siguiente es darle un Token // Si la contraseña es incorrecta o false, no se le dará un token if(!validPassword){ return res.status(401).json({auth:false, token: null }); } // Si la contraseña es correcta si tendrá token const token = jwt.sign({id:user._id}, config.secret, { expiresIn: 60 * 60 * 24 }); res.json({auth: true, token}) }); module.exports = router;
import { Fresco } from '../../services/database'; // retourne une fresque par identifiant (PARCELLE) const getFresco = async (req, res) => { let { frescoId } = req.params; try { const fresco = await Fresco.find({ PARCELLE: parseInt(frescoId) }).value(); if (!fresco) { return res.json({ status: 'error', message: 'getFresco: Pas de fresque', }); } return res.json({ status: 'success', data: fresco, }); } catch (err) { return res.json({ status: 'error', message: `Erreur db: ${err}`, }); } }; export default getFresco;
const $ = jQuery = jquery = require ("jquery") const notification = require ("cloudflare/core/notification") function initializeCustom ( prop = "value", on = "on" ) { return function initialize ( event, data ) { let value if ( typeof prop === "object" && prop.constructor.name === "Array" ) { value = prop.reduce ( ( a, e ) => { return a [ e ] }, data.response.result ) } else { value = data.response.result [ prop ] } $(data.section).find ("[name='mode']").prop ( "checked", value == on ) } } function toggle ( event, data ) { var state = $(data.section).find ("[name='mode']:checked").length > 0 $(data.section).addClass ("loading") $.ajax ({ url: data.form.endpoint, type: "POST", data: { "form_key": data.form.key, "state": state }, success: ( response ) => { if ( !response.success ) { $(data.section) .find ("[name='mode']") .prop ( "checked", !state ) } notification.showMessages ( response ) $(data.section).removeClass ("loading") } }) } module.exports = { initialize: initializeCustom (), toggle, initializeCustom, }
/* * Module code goes here. Use 'module.exports' to export things: * module.exports.thing = 'a thing'; * * You can import it from another modules like this: * var mod = require('prototype.flag'); * mod.thing == 'a thing'; // true */ var logger = require("screeps.logger"); logger = new logger("prototype.flag"); Flag.prototype.hostilesInRange = function(range) { if (!this.room) { return []; } var hostiles = this.pos.findInRange(FIND_HOSTILE_CREEPS, range, {filter: function(c) { //logger.log(c.name, c.isHostile()) return c.isHostile(); }}); //logger.log(this.name, "found bad guys:", hostiles) return hostiles; }
import React from 'react' import PropTypes from 'prop-types' import { NavLink } from 'react-router-dom' import { Icon } from 'semantic-ui-react' import classes from './StretchSidebarSub_2.module.scss' const stretchSidebarSub_1 = props => { const { navigations, showup, activateHandler, childPusher, actives } = props const subClassName = showup ? [classes.SubTwo, classes.Active].join(' ') : classes.SubTwo return ( <ul className={subClassName}> {navigations.map((nav, key) => ( <li className={classes.SubTwo_Menu} key={key}> <NavLink activeClassName={classes.Active} to={nav.route} onClick={() => activateHandler(nav.route, nav.nested)}> <Icon className={classes.SubTwo_MenuIcon} name={nav.icon} size='large' /> <span className={classes.SubTwo_MenuText}> <b>{nav.text}</b> </span> { nav.nested ? childPusher(actives.includes(nav.route)) : null } </NavLink> </li> ))} </ul> ) } stretchSidebarSub_1.propTypes = { navigations: PropTypes.array, childPusher: PropTypes.func, showup: PropTypes.bool, activateHandler: PropTypes.func, actives: PropTypes.array } export default stretchSidebarSub_1
// I think this connects everything to the database and use the logging.js module to allow you to console.log everything as it happens const log = require('./logging.js') // accesses logging module const dbConfigs = require('../knexfile.js') // accesses knexfile module that specifies the database to use log.info('Connecting to the database ...') const db = require('knex')(dbConfigs.development) // What does this do? db.raw('SELECT 1') // Queries the database for data, but why 'SELECT 1'? .then(function (result) { // When it retrieves the promise, it will log the following message log.info('Successfully connected to the database!') }) .catch(function (err) { // If it does not retrieve it (return the promise), then the error message is sent console.error(err) log.error('Unable to connect to the database!') }) // ----------------------------------------------------------------------------- // Public API module.exports = { db: db }
/* baseID is the ID of the element our widget lives in */ function ShardView (baseID) { /* If this constructor is called without the "new" operator, "this" points * to the global object. Log a warning and call it correctly. */ if (false === (this instanceof ShardView)) { console.log('Warning: ShardView constructor called without "new" operator'); return new ExampleWidget(baseID); } /* Return immediately if baseID doesn't match any DOM element */ if ($('#' + baseID).length === 0) { console.log("Error: element: " + baseID + " not found!"); return; } /* construct unique IDs for all the elements in this widget */ var ids = { main: baseID, stats: baseID + "-stats", alerts: baseID + "-alerts", statsButton: baseID + "-statsButton", pie: baseID + "-pie", pieCanvas: baseID + "-pieCanvas", }; /* create a list of id's with the '#' prepended for convenience */ var sel = {}; for (var id in ids) { sel[id] = "#" + ids[id]; } /* Elements of the stats pane */ var statsDiv = '<div id="' + ids.stats + '" class="widget-stats-container"></div>'; var alertsDiv = '<div id="' + ids.alerts + '" class="widget-stats-container"></div>'; var statsHeader = '<h1 class="widget-stats-header">Stats!</hi>'; var statsButton = '<button type=button id="' + ids.statsButton + '">' + 'Add Stats!</button>'; /* Elements of the pie pane */ var pieDiv = '<div id="' + ids.pie + '" class="widget-default-container"></div>'; var pieHeader = '<h1 class="widget-default-header">Shard View</hi>'; var pieCanvas = '<canvas id="' + ids.pieCanvas + '" width=600 height=500 style="width: 600px; height: 500px; display: inline;">' + 'If you can read this, your browser doesn\'t support the canvas ' + 'element.</canvas>'; /* Clear the element we are using */ $(sel.main).empty(); /* Insert the stats and pie panes */ $(sel.main).append(pieDiv); $(sel.main).append(statsDiv); /* Put together the pie pane */ $(sel.pie).append(pieHeader); $(sel.pie).append(pieCanvas); $(sel.stats).append(alertsDiv); /* The only public field of this object is the "render" function. It takes * as an argument the raw data from MongoDB */ this.render = function(data) { this.map = new TopologicalMap(data); this.shards = this.map.getShards(); this.alerts = this.map.getAlerts(); var app_loop = this.start(); } this.start = function(){ var app_loop; var canvas = $(sel.pieCanvas)[0]; var statPanel = $(sel.stats); var alertPanel = $(sel.alerts); if (canvas.getContext) { //canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height); canvas.width = canvas.width; var board = new Board(canvas.getContext('2d'),"#FFF",canvas.width,canvas.height, statPanel, alertPanel, this.shards, this.alerts, this.map); canvas.addEventListener('mousemove',function(evt){ var mousePos = ShardViewWidgetGetMousePos(canvas, evt); board.mouseOver(mousePos.x, mousePos.y); }, false); canvas.addEventListener('click',function(evt){ var mousePos = ShardViewWidgetGetMousePos(canvas, evt); board.mouseClick(mousePos.x, mousePos.y); }, false); app_loop = setInterval(function(){ board.draw(); }, 1000 / 60); } else { alert('You lack a browser able to run HTML5'); } return app_loop; }; } // Getting the mouse position based on the canvas function ShardViewWidgetGetMousePos(canvas, evt){ var obj = canvas; var top = 0; var left = 0; while (obj && obj.tagName != 'BODY') { top += obj.offsetTop; left += obj.offsetLeft; obj = obj.offsetParent; } var mouseX = evt.clientX - left + window.pageXOffset; var mouseY = evt.clientY - top + window.pageYOffset; return { x: mouseX, y: mouseY }; } function countProperties(foo){ var count = 0; for (var k in foo) { if (foo.hasOwnProperty(k)) { ++count; } } return count; } function processAlerts(map){ var hostalerts = map.getAlerts('server'); var hostmap = {}; var servers = map.getServers(); for (var s in servers){ var a = servers[s].getAlerts(); hostmap[servers[s].id] = a.content; } return hostmap; } function Board(ctx,rgba,cw,ch,statPanel, alertPanel, passedShards, passedAlerts, passedMap){ this.statPanel = statPanel; this.alertPanel = alertPanel; this.map = passedMap; this.hostAlertsMap = processAlerts(this.map); this.shards = passedShards; this.alerts = passedAlerts; this.colls = this.uniqueCollections(this.shards); this.colors = ["#B9F73E","#1F7D63","#BF6430","#992667","#86B32D","#5FD3B3","#FFA573","#E667AF"]; this.colors = zip(this.colors, this.colls); var MARGIN = 20; var num_repsets = countProperties(this.shards); var shardW = ((cw - MARGIN) / num_repsets) - MARGIN; var shardH = ch - 2*MARGIN; var X = MARGIN; this.shardShapes = []; for (var index in this.shards){ this.shardShapes.push(new ShardShape(ctx, this.shards[index], X, MARGIN, shardH, shardW, this.colors, this.alerts)); X += shardW + MARGIN; } this.back = new ShardBlock(ctx,this.cw,this.ch,0,0,this.alerts, 0, "#333"); } Board.prototype.draw = function() { //this.back.draw(); for (var i = 0; i < this.shardShapes.length; i++) { this.shardShapes[i].draw(); } } Board.prototype.mouseOver = function(cX,cY) { } Board.prototype.mouseClick = function(cX, cY){ for (var i = 0; i < countProperties(this.shards); i++) { if (this.shardShapes[i].inShape(cX,cY)) { this.statPanel.html(""); var coll = this.shardShapes[i].pointedCollection; var theShard = ithShard(this.shards, i); if (!coll){ var info = "Shard " + theShard.getID() + " has no collections."; } else { var info = "Shard " + theShard.getID() + " of collection " + coll + "."; } this.statPanel.html("<p>" + info + "</p>"); var words = ""; for (var s in theShard.getServers()){ var serv = theShard.getServers()[s]; var id = serv.id; var alerts = serv.getAlerts(); if (alerts.content.length > 0) { words += "<li class = \"shard-view-alert\" >" + serv.id ; words += "<ul>"; for (var a = 0; a < alerts.content.length; a++){ var er = alerts.content[a]; var erstr = er.toString(); var ertip = er.tips(); var splitid = id.split(":"); var stripped = splitid[0] + splitid[1]; words += "<li><a href = \"#\" id = \"" + stripped + "\" class = \"shard-view-click\" onclick=\"shardviewshowHide(\'"+ stripped +"\');\"> " + erstr + "</a></li>"; words += "<li id =\"" + stripped + "-show\" class = \"shard-view-reveal\">" + ertip + "</li>" ; } words += "</ul></li>"; } else { words += "<li>" + serv.id + "</li>"; } } this.statPanel.append("<p><ul>" + words + "</ul>" + "</p>"); } } } function shardviewshowHide(shID) { if (document.getElementById(shID)) { var disp = document.getElementById(shID+'-show').style.display; if (disp != 'none') { document.getElementById(shID+'-show').style.display = 'none'; } else { document.getElementById(shID+'-show').style.display = 'inline'; } return true; } return false; } function priorityToColor(priority){ if (priority > 150){ // oh no! return '#F' + (255 - priority).toString(16) + (255 - priority).toString(16); } else { return '#FFO'; } } function ithShard(shards, i){ var theShard; var theShardctr = 0; for (var s in shards){ if (theShardctr == i){ return shards[s]; } theShardctr++; } return 'ERROR; i > number of shards.'; } Board.prototype.uniqueCollections = function(shards){ var collNames = {}; var result = []; for (var s in shards){ var names = shards[s].getChunks(); for (var n in names){ var cName = names[n].getCollection(); collNames[cName] = ""; } // TEMPORARY -- if a collection is not chunked, // the number of chunks seems to be 0 and not 1, // so we kind of have to do this... // if (names.length == 0){ // collNames["Collection " + shards[s].id] = ""; // } } // now get just the keys for (var n in collNames){ result.push(n); } return result; } // Zips 2 arrays into a map. Array 1 can be longer than Array 2. function zip(colors, collections){ var result = {}; var len = Math.max(colors.length, collections.length); for (var i = 0; i < len; i++){ result[collections[i]] = colors[i]; } return result; } function reversemap(map){ var result = {}; for (var i in map){ result[map[i]] = i; } return result; } /** end static-ish functions **/ // An encapsulated visual representation of a shard. // Displays how much space each collection takes up. // // Contains shapes. Is sort of a shape in the sense that it can be drawn. // colors = mapping of collection name to color name function ShardShape(ctx, rep_set, X, Y, height, width, colors, shardAlerts){ this.ctx = ctx; this.shard = rep_set; this.shardH = height; this.shardW = width; this.X = X; // top left corner coordinates this.Y = Y; this.colors = colors; this.colorsToColl = reversemap(colors); this.pointedCollection = ""; this.allAlerts = shardAlerts; // may be undefined. this.shardIDs = []; // {collectionA : number-chunks-in-that-collection, collectionB : number-chunks-in-collection-B, ...} this.collections = {}; this.collShapes = []; // make initial shape this.UpdateShard(this.shard); } // So that we can redraw this when new data comes in ShardShape.prototype.UpdateShard = function(shard, init){ var c = shard.getChunks(); this.collections = {}; for (var chunk in c){ if (this.collections.hasOwnProperty(c[chunk].getCollection())){ this.collections[c[chunk].getCollection()]++; } else { this.collections[c[chunk].getCollection()] = 1; } } // TEMPORARY -- if a collection is not chunked, // the number of chunks seems to be 0 and not 1, // so we kind of have to do this... if (c.length == 0){ this.collections["NONE"] = 1; } for (var c in this.collections){ this.shardIDs.push(Math.floor(1024*Math.random())); } } ShardShape.prototype.draw = function(){ this.calculateSizes(); this.collShapes = []; var Y = this.Y; var ctr = 0; for (var c in this.collections){ var alerts = 0; id = this.shardIDs[ctr]; ctr++; if (c == "NONE"){ var block = new ShardBlock(this.ctx, this.shardW, this.shardH, this.X, Y, alerts, id, '#CCC'); } else { var block = new ShardBlock(this.ctx, this.shardW, this.collections[c], this.X, Y, alerts, id, this.colors[c]); } this.collShapes.push(block); Y += this.collections[c]; } for (var s in this.collShapes){ this.collShapes[s].draw(); } } ShardShape.prototype.calculateSizes = function(){ var sizes = []; var totalChunks = 0.0; // get the sum... for (var c in this.collections){ totalChunks += this.collections[c]; } // now scale each chunk count to a height, in pixels for (var c in this.collections){ this.collections[c] = this.collections[c]*1.0*this.shardH / totalChunks; } } ShardShape.prototype.inShape = function(x, y){ var found = false; for (var s in this.collShapes){ if (this.collShapes[s].inShape(x, y)){ found = true; this.pointedCollection = this.colorsToColl[this.collShapes[s].color]; } } return found; } // Shardblock: represents one chunk in a collection. // Fundamentally, a shape. // Knows about its alerts. // Has unique id. This allows the main board to have some idea of when the mouse has changed blocks. function ShardBlock(ctx, width, height, cornerX, cornerY, alerts, id, color){ this.ctx = ctx; this.alerts = alerts; this.id = id; this.color = color; this.x = cornerX; this.y = cornerY; this.w = width; this.h = height; } ShardBlock.prototype.draw = function(){ this.ctx.fillStyle = this.color; this.ctx.fillRect(this.x,this.y,this.w,this.h); this.ctx.stroke = '#FFF'; this.ctx.strokeRect(this.x,this.y,this.w,this.h); } ShardBlock.prototype.inShape = function(x, y){ return (x >= this.x && x <= (this.x + this.w) && y >= this.y && y <= (this.y + this.h)); }
// For an introduction to the Blank template, see the following documentation: // http://go.microsoft.com/fwlink/?LinkID=397704 // To debug code on page load in Ripple or on Android devices/emulators: launch your app, set breakpoints, // and then run "window.location.reload()" in the JavaScript Console. (function () { "use strict"; angular.module("prosjekApp", []) .constant('appConfig', { lowMark: 1, hiMark: 5 }) .controller("mainCtrl", ['$scope', 'appConfig', function ($scope, appConfig) { $scope.total = 20; $scope.rez = []; $scope.calculate2 = function () { var result = []; $scope.calcErr = false; for (var i = appConfig.lowMark; i <= appConfig.hiMark; i++) { var index = i - 1; //validation check before values are less than after if ($scope.range[index].fields[1].value <= $scope.range[index].fields[0].value) { $scope.calcErr = true; $scope.range[index].fields[0].error = true; } else { $scope.range[index].fields[0].error = false; } if (i > 1) { if ($scope.range[index].fields[0].value <= $scope.range[index - 1].fields[1].value) { $scope.calcErr = true; $scope.range[index - 1].fields[1].error = true; } else { $scope.range[index - 1].fields[1].error = false; } } // end validation var res = { ocjena: i, minbod: $scope.range[index].fields[0].value * $scope.total, maxbod: $scope.range[index].fields[1].value * $scope.total }; result.push(res); } $scope.rez = result; } $scope.range = function (min, max, step) { step = step || 1; var input = []; for (var i = min; i <= max; i += step) { var props = { ocjena: i, fields: [{ minname: "min" + i, value: i === min ? 0 : 0.51 + ((i - 1) * 0.1) }, { maxname: "max" + i, value: 0.6 + ((i - 1) * 0.1) }] } input.push(props); } return input; }(appConfig.lowMark, appConfig.hiMark, 1); } ]); document.addEventListener('deviceready', onDeviceReady.bind(this), false); function onDeviceReady() { // Handle the Cordova pause and resume events document.addEventListener('pause', onPause.bind(this), false); document.addEventListener('resume', onResume.bind(this), false); // TODO: Cordova has been loaded. Perform any initialization that requires Cordova here. }; function onPause() { // TODO: This application has been suspended. Save application state here. }; function onResume() { // TODO: This application has been reactivated. Restore application state here. }; })();
Ext.define('cfa.view.Dashboards', { extend: 'Ext.dataview.DataView', xtype: 'dashboards', config: { title: 'CFA Mobile', id: 'dashboard', scrollable: false, refs: { main: 'main' }, baseCls: 'dashboards-list', itemTpl: [ '<div class="image" style="background-image:url(resources/icons/{urlId}.png)"></div>', '<div class="name">{label}</div>' ].join('') }, applyData: function(data) { this.setRecords(data); return Ext.pluck(data || [], 'data'); } });
import React from 'react'; import {Tab, Tabs, TabList, TabPanel} from 'react-tabs'; import RingCharts from './ring-charts'; require('./detail.scss'); export default class SlavesDetail extends React.Component { calculatePercent(used, max) { return Math.round((used / max) * 100); } renderTabHeaders(slaves) { const titles = slaves.map(s => s.pid); return (<TabList> {titles.map(t => <Tab>{t}</Tab>)} </TabList>); } renderTabPanels(slaves) { return slaves.map(s => { const {cpus: usedCpus, mem: usedMem, disk: usedDisk} = s.used_resources; const {cpus: maxCpus, mem: maxMem, disk: maxDisk} = s.resources; const charts = [ { id: 'cpus', text: 'CPUS', color: '#00CC00', width: 60, value: this.calculatePercent(usedCpus, maxCpus), }, { id: 'mem', text: 'Memory', color: '#CD0074', width: 60, value: this.calculatePercent(usedMem, maxMem), }, { id: 'disk', text: 'Disk', color: '#FF7400', width: 60, value: this.calculatePercent(usedDisk, maxDisk), }, ]; return (<TabPanel> <div> <RingCharts charts={charts} /> </div> </TabPanel>); }); } render() { const selectedSlaves = this.props.selectedSlaves; const slaves = this.props.slaves.filter(s => selectedSlaves.contains(s.pid)); return (<Tabs> {this.renderTabHeaders(slaves)} {this.renderTabPanels(slaves)} </Tabs>); } } SlavesDetail.propTypes = { slaves: React.PropTypes.object.isRequired, selectedSlaves: React.PropTypes.object.isRequired, };
/** * Created by xuwusheng on 15/11/30. */ define(['../app'], function (app) { app.directive('pl4Query', ['$sce', function ($sce) { return { restrict: 'EA', replace: true, transclude: true, //scope:{ // querySeting:'=', // searchModel:'=' //}, templateUrl: 'views/query.html', link: function (scope) { var isClick = false; scope.selectChange = function (change) { if (scope[change] instanceof Function) { scope[change](); } } scope.btnClick = function (item) { if (scope[item.click] instanceof Function) { isClick = true; if(checkDate()) scope[item.click](); } } scope.submit = function (btns) { if (isClick) { isClick = false; return false; } angular.forEach(btns, function (item) { if ($sce.getTrustedHtml(item.text).indexOf('查询') > -1) { if (scope[item.click] instanceof Function) { if(checkDate()) scope[item.click](); } return false; } }); } var checkDate = function () { var $dates = $('.query-date').find('input[type="text"]'), date1=$dates.eq(0).val(), date2=$dates.length==2?$dates.eq(1).val():null; if(date1&&date2&&date1!==''&&date2!==''){ date1=new Date(date1).getTime(); date2=new Date(date2).getTime(); if(date1>date2){ alert('后者日期不能小于前者'); return false; } /*else if(date1==date2){ alert('前后日期不能相同'); return false; }*/ } return true; } scope.isShowMove = false; scope.dataList = scope.querySeting.items; if (scope.querySeting.items.length > 3) { scope.isShowMove = true; scope.btnSearch7=true; scope.dataList = scope.dataList.slice(0, 3); }else if(scope.querySeting.items.length ==3){ scope.btnSearch7=true; }else if(scope.querySeting.items.length ==1){ scope.btnSearch3=true; } else { scope.dataList = scope.querySeting.items; scope.btnSearch5=true; } scope.loadMove = function () { var moveBtn = document.getElementById('move'); var moveText = moveBtn.innerText; if (moveText=='展开更多') { moveBtn.innerText = '收起更多'; scope.dataList = scope.querySeting.items; } else { moveBtn.innerText = '展开更多'; scope.dataList = scope.querySeting.items.slice(0, 3); } } } } }]); });
/*jslint node: true */ "use strict"; var http = require('http'); var config = require('./config/config'); var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var cors = require('cors'); var timeout = require('connect-timeout'); var _portSocket = config.APP_PORT; app.use(cors()); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); app.use(timeout('200s')) app.use(bodyParser.urlencoded({ limit: '50mb', 'extended': 'true' })); // parse application/x-www-form-urlencoded app.use(bodyParser.json({ limit: '50mb' })); // parse application/json app.use(bodyParser.json({ limit: '50mb', type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json app.use(haltOnTimedout) app.use(haltOnTimedout) // handle app level errors app.use(function(err, req, res, next) { console.error(err.stack); return res.status(500).send('Something broke!'); }); // handle app level errors var errorFilter = function(err, req, res, next) { if (!res.headersSent) { //just because of your current problem, no need to exacerbate it. var errcode = err.status || 500; //err has status not statusCode // var msg = err.message || 'server error!'; res.status(errcode).send(err); //the future of send(status,msg) is hotly debated }; } function haltOnTimedout(req, res, next) { if (!req.timedout) next(); } require('./lib/mongoconnection'); require('./src/routes/index')(app); app.use(errorFilter); var server = http.createServer(app); server.listen((process.env.PORT || 8080), function () { var port = server.address().port; console.log("App now running on port", port); })
'use strict'; angular. module('tourDetail'). component('tourDetail', { templateUrl: '../static/templates/tour/tour-detail.template.html', controller: ['$routeParams', 'Tour', function TourDetailController($routeParams, Tour) { var self = this; self.tour = Tour.get({tourId: $routeParams.tourId}, function(tour) { self.tour.cost = parseFloat(tour.cost) || 0.0; self.tour.trans_cost = parseFloat(tour.trans_cost) || 0.0; self.tour.hotel_cost = parseFloat(tour.hotel_cost) || 0.0; self.tour.excurs_cost = parseFloat(tour.excurs_cost) || 0.0; self.tour.price = self.tour.cost + self.tour.trans_cost + + self.tour.hotel_cost + self.tour.excurs_cost; }); } ] });
// various functions for formatting data /** * baseName * returns the basename of a filename * greets to https://stackoverflow.com/questions/3820381/need-a-basename-function-in-javascript * * @param {string} str - string to get basename of. example: "test.json" * @returns {string} base - basename of str. example: "test" */ function baseName(str) { var base = new String(str).substring(str.lastIndexOf('/') + 1); if(base.lastIndexOf(".") != -1) base = base.substring(0, base.lastIndexOf(".")); return base; } module.exports = { baseName: baseName };
if(moz) { extendEventObject(); extendElementModel(); emulateAttachEvent(); } function viewArc(aid){ if(aid==0) aid = getOneItem(); window.open("archives_do.php?aid="+aid+"&dopost=viewArchives"); } function editArc(id, returnUrl){ location="AdminEditArticle.do?act=gettype&op=edit&id="+id+"&returnUrl=" + returnUrl; } function updateArc(aid){ var qstr=getCheckboxItem(); if(aid==0) aid = getOneItem(); location="archives_do.php?aid="+aid+"&dopost=makeArchives&qstr="+qstr; } function checkArc(returnUrl){ var qstr=getCheckboxItem(); if(qstr.length > 0) location="AdminUpdateArticle.do?act=verify&arcID="+qstr+"&returnUrl="+returnUrl; else alert("请选择要审核的文章!"); } function moveArc(aid){ var qstr=getCheckboxItem(); if(aid==0) aid = getOneItem(); location="archives_do.php?aid="+aid+"&dopost=moveArchives&qstr="+qstr; } function adArc(returnUrl){ var qstr=getCheckboxItem(); if(qstr.length > 0) location="AdminUpdateArticle.do?act=command&arcID="+qstr+"&returnUrl="+returnUrl; else alert("请选择要删除的文章!"); } function delArc(returnUrl){ var qstr=getCheckboxItem(); //alert(qstr); //if(aid==0) aid = getOneItem(); if(qstr.length > 0) location="AdminUpdateArticle.do?act=delete&arcID="+qstr+"&returnUrl="+returnUrl; else alert("请选择要删除的文章!"); } function modArc(returnUrl){ var qstr=getCheckboxItem(); //alert(qstr); //if(aid==0) aid = getOneItem(); if(qstr.length > 0) location="article_batch_modify.jsp?arcID="+qstr+"&returnUrl="+returnUrl; else alert("请选择要批量修改的文章!"); } //Video function viewVideo(aid){ if(aid==0) aid = getOneItem(); window.open("archives_do.php?aid="+aid+"&dopost=viewArchives"); } function editVideo(id, returnUrl){ location="AdminEditVideo.do?act=gettype&op=edit&id="+id+"&returnUrl=" + returnUrl; } function editVideoUrl(videoid, returnUrl){ location="AdminUpdateVideoUrl.do?act=list&videoid="+videoid+"&returnUrl=" + returnUrl; } function updateVideo(aid){ var qstr=getCheckboxItem(); if(aid==0) aid = getOneItem(); location="archives_do.php?aid="+aid+"&dopost=makeArchives&qstr="+qstr; } function checkVideo(returnUrl){ var qstr=getCheckboxItem(); if(qstr.length > 0) location="AdminUpdateVideo.do?act=verify&arcID="+qstr+"&returnUrl="+returnUrl; else alert("请选择要审核的文章!"); } function moveVideo(aid){ var qstr=getCheckboxItem(); if(aid==0) aid = getOneItem(); location="archives_do.php?aid="+aid+"&dopost=moveArchives&qstr="+qstr; } function adVideo(returnUrl){ var qstr=getCheckboxItem(); if(qstr.length > 0) location="AdminUpdateVideo.do?act=command&arcID="+qstr+"&returnUrl="+returnUrl; else alert("请选择要删除的文章!"); } function delVideo(returnUrl){ var qstr=getCheckboxItem(); //alert(qstr); //if(aid==0) aid = getOneItem(); if(qstr.length > 0) location="AdminUpdateVideo.do?act=delete&arcID="+qstr+"&returnUrl="+returnUrl; else alert("请选择要删除的文章!"); } //上下文菜单 function ShowMenu(obj,aid,atitle) { var eobj,popupoptions popupoptions = [ new ContextItem("浏览文档",function(){ viewArc(aid); }), new ContextItem("编辑文档",function(){ editArc(aid); }), new ContextSeperator(), new ContextItem("更新HTML",function(){ updateArc(aid); }), new ContextItem("审核文档",function(){ checkArc(aid); }), new ContextItem("推荐文档",function(){ adArc(aid); }), new ContextSeperator(), new ContextItem("删除文档",function(){ delArc(aid); }), new ContextSeperator(), new ContextItem("全部选择",function(){ selAll(); }), new ContextItem("取消选择",function(){ noSelAll(); }), new ContextSeperator(), new ContextItem("频道管理",function(){ location="catalog_main.php"; }) ] ContextMenu.display(popupoptions) } //获得选中文件的文件名 function getCheckboxItem() { var allSel=""; if(document.form2.arcID.value) return document.form2.arcID.value; for(i=0;i<document.form2.arcID.length;i++) { if(document.form2.arcID[i].checked) { if(allSel=="") allSel=document.form2.arcID[i].value; else allSel=allSel+"`"+document.form2.arcID[i].value; } } return allSel; } //获得选中其中一个的id function getOneItem() { var allSel=""; if(document.form2.arcID.value) return document.form2.arcID.value; for(i=0;i<document.form2.arcID.length;i++) { if(document.form2.arcID[i].checked) { allSel = document.form2.arcID[i].value; break; } } return allSel; } function selAll() { for(i=0;i<document.form2.arcID.length;i++) { if(!document.form2.arcID[i].checked) { document.form2.arcID[i].checked=true; } } } function noSelAll() { for(i=0;i<document.form2.arcID.length;i++) { if(document.form2.arcID[i].checked) { document.form2.arcID[i].checked=false; } } }
const video = document.getElementById("myvideo"); const canvas = document.getElementById("canvas"); const context = canvas.getContext("2d"); let trackButton = document.getElementById("trackbutton"); let updateNote = document.getElementById("updatenote"); let points = []; start = false; let isVideo = false; let model = null; const modelParams = { flipHorizontal: true, // flip e.g for video maxNumBoxes: 1, // maximum number of boxes to detect iouThreshold: 0.85, // ioU threshold for non-max suppression scoreThreshold: 0.87, // confidence threshold for predictions. }; function startVideo() { handTrack.startVideo(video).then(function (status) { console.log("video started", status); if (status) { updateNote.innerText = "Video started. Now tracking"; isVideo = true; runDetection(); } else { updateNote.innerText = "Please enable video"; } }); } function toggleVideo() { if (!isVideo) { updateNote.innerText = "Starting video"; startVideo(); } else { updateNote.innerText = "Stopping video"; handTrack.stopVideo(video); isVideo = false; updateNote.innerText = "Video stopped"; } } function runDetection() { model.detect(video).then((predictions) => { console.log("Predictions: ", predictions); if (predictions.length > 0) { let xpos = predictions[0].bbox[0] + predictions[0].bbox[2] / 2; let ypos = predictions[0].bbox[1] + predictions[0].bbox[3] / 2; points.push([xpos, ypos]); console.log("pushed"); } // model.renderPredictions(predictions, canvas, context, video); runDrawPredictions(predictions); if (isVideo) { requestAnimationFrame(runDetection); } }); } function runDrawPredictions(predictions) { // context.clearRect(0, 0, canvas.width, canvas.height); context.save(); context.scale(-1, 1); context.translate(-video.width, 0); // context.drawImage(mediasource, 0, 0, mediasource.width, mediasource.height); context.restore(); // context.font = '10px Arial'; // console.log('number of detections: ', predictions.length); console.log("above loop"); console.log(points); let nxpos, nypos, xpos, ypos if (points.length > 0) { nxpos = points[points.length - 1][0]; nypos = points[points.length - 1][1]; xpos = nxpos; ypos = nypos; } if (points.length > 1) { xpos = points[points.length - 2][0]; ypos = points[points.length - 2][1]; } if (points.length >= 2) { drawDoodle(nxpos, nypos, xpos, ypos); } } function drawDoodle(nxpos, nypos, xpos, ypos) { context.beginPath(); // begin context.lineWidth = 5; context.lineCap = "round"; context.strokeStyle = "#1780DC"; context.moveTo(xpos, ypos); // from context.lineTo(nxpos, nypos); // to context.stroke(); // draw it! console.log("Drawn in drawDoodle"); context.closePath(); console.log("closed path"); } // Load the model. handTrack.load(modelParams).then((lmodel) => { // detect objects in the image. model = lmodel; updateNote.innerText = "Loaded Model!"; trackButton.disabled = false; }); // function draw(x, y) { // background(51); // stroke(0); // strokeWeight(25); // noFill(); // if (start) { // points.push(createVector(mouseX, mouseY)); // } // beginShape(); // for (let i = 0; i < points.length; i++) { // let x = points[i].x; // let y = points[i].y; // console.log(x) // vertex(x,y); // } // endShape(); // } // function mousePressed() { // start = true; // points = []; // } // function mouseReleased() { // start = false; // }
import React from 'react' // import { connect } from 'react-redux' // import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom' import { BrowserRouter as Router, Route, Switch } from 'react-router-dom' import Header from './components/Header' import Signin from './components/Signin' import Signup from './components/Signup' import Home from './containers/Home' class Routes extends React.Component { render () { return <Router> <Switch> <div> <Route component={Header} /> <Route path='/' exact component={Home} /> <Route path='/sign_up' component={Signup} /> <Route path='/sign_in' component={Signin} /> </div> </Switch> </Router> } } export default Routes
angular.module('app.books') .controller( 'BookAddController', function($scope, $window, $location, bookService, Flash, $modal) { 'use strict'; $scope.title = 'title'; $scope.authors = []; $scope.gridOptions = { data : 'authors' }; $scope.addNewBook = function() { if ($scope.title === '') { $window.alert('Musisz podac tytul ksiazki!'); return; } if ($scope.title.length > 50) { $window.alert('Tytul nie moze posiadac wiecej niz 50 znakow!'); return; } if ($scope.authors.length === 0) { $window.alert('Lista autorow jest pusta!'); return; } addBook(); }; var addBook = function() { var book = { title : $scope.title, authors : $scope.authors }; bookService.addNewBook(book).then( function() { Flash.create('success', 'Książka została dodana.', 'custom-class'); $scope.authors = []; $location.url('/books/book-list/'); }, function() { Flash.create('danger', 'Wyjątek', 'custom-class'); }); }; $scope.addAuthor = function() { $modal.open({ templateUrl : 'books/html/book-modal.html', controller : 'BookModalController', size : 'lg' }).result.then(function(author) { $scope.authors.push(author); }); }; $scope.deleteAuthor = function(authorId) { deleteAuthor(authorId); }; var deleteAuthor = function(authorId) { for (var i = 0; i < $scope.authors.length; i = i + 1) { if ($scope.authors[i].id === authorId) { $scope.authors.splice(i, 1); break; } } }; });
'use strict' import { StyleSheet, View, Text, ScrollView, Dimensions, } from 'react-native'; import React , {Component} from 'react'; import {connect} from 'react-redux'; import * as Progress from 'react-native-progress'; import TeamsLog from './teamsLog'; const navigationHeight = 30 const headerHeight = 120 class DetailedStats extends Component { constructor (props) { super(props) this.state = { progress: 0, indeterminate: true, } } componentDidMount () { this.animate(this.props.stats.percentage); } animate(num) { let progress = 0; this.setState({ progress }); setTimeout(() => { this.setState({ indeterminate: false }); setInterval(() => { progress += Math.random() / 5; if (progress > num) { progress = num; } this.setState({ progress }); }, 500); }, 1500); } color(p){ if(p>.5) return '#FFF'; else if(p==.5) return 'yellow' else return 'red' } render () { const { totalNumOfGames , winNum ,drawNum , loseNum ,points , scored , conceded} = this.props.stats; /* ScrollView need a specific height */ const scrollHeight = Dimensions.get('window').height - navigationHeight - headerHeight return ( <View style = {styles.container}> <View style={styles.header}> <View style={styles.portraitView}> <Progress.Circle style={styles.progress} color = {this.color(this.state.progress)} borderColor = {this.color(this.state.progress)} progress={this.state.progress} indeterminate={this.state.indeterminate} showsText = {true} size = {100} /> </View> <Text style={styles.totalNumOfGames}>{totalNumOfGames}</Text> </View> <ScrollView style={{height: scrollHeight , backgroundColor: "#FFF"}}> <View style={styles.basicData}> <View style={styles.basicDataBlock}> <Text style={styles.basicDataNumber}>{winNum}</Text> <Text style={styles.basicDataMark}>Win</Text> </View> <View style={styles.basicDataBlock}> <Text style={styles.basicDataNumber}>{drawNum}</Text> <Text style={styles.basicDataMark}>Draw</Text> </View> <View style={styles.basicDataBlock}> <Text style={styles.basicDataNumber}>{loseNum}</Text> <Text style={styles.basicDataMark}>Defeats</Text> </View> </View> <View style={styles.basicData}> <View style={styles.basicDataBlock}> <Text style={styles.basicDataNumber}>{points}</Text> <Text style={styles.basicDataMark}>Points</Text> </View> <View style={styles.basicDataBlock}> <Text style={styles.basicDataNumber}>{scored}</Text> <Text style={styles.basicDataMark}>Goals scored</Text> </View> <View style={styles.basicDataBlock}> <Text style={styles.basicDataNumber}>{conceded}</Text> <Text style={styles.basicDataMark}>Goals conceded</Text> </View> </View> <TeamsLog data = {this.props.data}/> </ScrollView> </View> ) } } const mapStateToProps = (state , props)=>{ return { user: state.authReducer.auth.user, matches: state.matchesReducer.matches }; } export default connect(mapStateToProps , null)(DetailedStats); const styles = StyleSheet.create({ container: { flex: 1, }, // Header part header: { height: headerHeight, backgroundColor: '#4D98E4' }, portraitView: { alignSelf: 'center', backgroundColor: '#0076FF', borderRadius: 110, marginTop: 5, height: 110, width: 110 }, portrait: { height: 60, width: 60, }, progress:{ alignSelf: 'center', marginTop: 5, } , totalNumOfGames: { alignSelf: 'center', color: '#fff', fontSize: 16, marginTop: 5 }, jersey: { alignSelf: 'center', color: '#fff', fontSize: 14 }, // Basic data basicData: { flexDirection: 'row', height: 28, justifyContent: 'center' }, basicDataBlock: { alignItems: 'flex-end', flexDirection: 'row', justifyContent: 'center', width: 100 }, basicDataNumber: { color: '#909CAF', fontSize: 19, fontWeight: '500', marginRight: 3 }, basicDataMark: { color: '#909CAF', fontSize: 12, position: 'relative', bottom: 1 }, })
const fs = require('fs').promises; const findRegex = require('./find'); module.exports = { async * parseFile(filename) { try { const code = await fs.readFile(filename) yield* this.parseCode(code, filename); } catch (error) { yield JSON.stringify({ error, filename }); } }, * parseCode(code, filename) { try { for (const regex of findRegex.extractRegexesFromSource(code, filename)) { yield JSON.stringify({ ...regex, filename, }); } } catch (error) { yield JSON.stringify({ error, filename }); } } }
import React from 'react' import Gallery from 'react-grid-gallery'; function Mars (props){ const date = props.date; let IMAGES = [{ src: "https://c2.staticflickr.com/9/8817/28973449265_07e3aa5d2e_b.jpg", thumbnail: "https://c2.staticflickr.com/9/8817/28973449265_07e3aa5d2e_n.jpg", thumbnailWidth: 250, thumbnailHeight: 174, isSelected: false, caption: "After Rain (Jeshu John - designerspics.com)" }] if(props.data){ console.log(props.data) const photos = Array(...props.data.photos); const photoArray = photos.map( photo => { return( { src: photo.img_src, thumbnail: photo.img_src, thumbnailWidth: 250, thumbnailHeight: 174, isSelected: false, caption: `Taken by ${photo.rover.name} using ${photo.camera.full_name} on ${photo.earth_date}` } ) }) IMAGES = photoArray; } document.getElementById('example-0') const body = document.querySelector('body'); body.classList.add('mars') return ( <div> <h1 className='text-center negative-margin mb-5 text-white'>MARS DATA {date}</h1> <Gallery images={IMAGES}/> </div> ) } export default Mars;
import axios from 'axios' const urlBaseMarvel = 'http://relatorio.prsonline.com.br/api/usuario' const apiKey = '5e3735b69dc80e8bf8599e8dbd989b42' export default { getAllComics: (limit, callback) => { const urlComics = urlBaseMarvel axios.get(urlComics).then((comics) => { if (callback) { callback(comics) } }) } }
// Import here... const express = require("express"); const router = express.Router(); const films = [ { id: 1, title: "Bonnie and Clyde", director: "Arthur Penn" }, { id: 2, title: "Reservoir Dogs", director: "Quentin Tarantino" }, { id: 3, title: "Inception", director: "Christopher Nolan" }, { id: 4, title: "Django Unchained", director: "Quentin Tarantino" } ]; // Write routes here... router.get("/", (req, res) => { console.log("here"); res.json({ films }); }); router.get("/:id", (req, res) => { const { id } = req.params; const film = films.find((film) => film.id === id); res.json({ film }); console.log(film); }); router.get("/director/:director", (req, res) => { const { director } = req.params; console.log(director); const film = films.filter((filmss) => filmss.director === director); console.log(film); res.json({ film }); }); router.post("/", (req, res) => { const filmToCreate = { ...req.body }; filmToCreate.id = films.length + 1; const updatedFilms = [...films, filmToCreate]; console.log("Check updatedFilms: ", updatedFilms); res.json({ film: filmToCreate }); }); module.exports = router;
import React, { Component } from 'react' import Navbar from './navbar' import { Link } from 'react-router-dom' import Servers from './servers' import Dashboard from './readExcel' import ReportWithChartJS from './reportWithChart' class Home extends Component{ state ={ currentPage : '' } setCurrentPage=(e)=>{ console.log('Inside set current page: clicked page='); console.log(e) console.log(e.target.id) this.setState({ currentPage : e.target.id }) } render(){ console.log('Inside render method in Home JS'); var clickedComponent; const clickedLink = this.state.currentPage console.log(this.state.currentPage); console.log('printed clicked component'); const currentPage = this.state.currentPage==='servers'?( < Servers /> ):this.state.currentPage==='dashboard'?( < Dashboard /> ):this.state.currentPage==='reportsChart'?( < ReportWithChartJS /> ):( <div className="center-align"><h4>No choice made yet!!!</h4></div> ) return( <div className="row"> <div className="col m12" id="navBarDiv"> <Navbar /> </div> <div className="col m2 hide-on-med-and-down"> <Link to="/dashboard" onClick={this.setCurrentPage} id="dashboard" className="btn blue darken-4 navButtons">Dashboard</Link> <Link to="/reportsChart" onClick={this.setCurrentPage} id="reportsChart" className="btn blue darken-4 navButtons">Reports</Link> <a href="#" className="btn blue darken-4 navButtons">Major releases</a> <a href="#" className="btn blue darken-4 navButtons">Support Contacts</a> <Link to="/servers" onClick={this.setCurrentPage} id="servers" className="btn blue darken-4 navButtons">Server list </Link> <a href="#" className="btn blue darken-4 navButtons">Customer Codes</a> <a href="#" className="btn blue darken-4 navButtons">Vendor Codes</a> <a href="#" className="btn blue darken-4 navButtons">Loan Codes</a> <a href="#" className="btn blue darken-4 navButtons">Payment Codes</a> <a href="#" className="btn blue darken-4 navButtons">VVS Rules</a> <a href="#" className="btn blue darken-4 navButtons">Auth Logic</a> <a href="#" className="btn blue darken-4 navButtons">Common Issues</a> <a href="#" className="btn blue darken-4 navButtons">Communication tracking Ids</a> <a href="#" className="btn blue darken-4 navButtons">MFPA codes</a> <a href="#" className="btn blue darken-4 navButtons">Deloitte codes</a> <a href="#" className="btn blue darken-4 navButtons">Common URLS</a> <a href="#" className="btn blue darken-4 navButtons">CERTIFICATE EXPIRY</a> </div> <div className="col offset-m1 m8 contentDiv"> {currentPage} </div> <div className="col m1"></div> </div> ); } } export default Home;
/** * Created by Kevin Blondel on 05/03/2017. */ $.DNA = function () { this.genes = []; this.population = 200; };
var BigNumber = require('bignumber.js'); var Tokensale = artifacts.require('./Tokensale.sol'); let presaleStartTime = 1512370800; // 1512568800; // Dec 6, 2pm UTC let startTime = 1512371800; // 1512655200; // Dec 7, 2pm UTC let hardCap = fromEtherToWei(5412); // at $462/ETH let investmentFundWallet = "0xB4e817449b2fcDEc82e69f02454B42FE95D4d1fD" let miscellaneousWallet = "0x7F744e420874AF3752CE657181e4b37CA9594779" let treasury = "0xB4e817449b2fcDEc82e69f02454B42FE95D4d1fD" let teamWallet = "0xC29789f465DF1AAF791027f4CABFc6Eb3EC2fc19" let reserveWallet = "0xb30CC06c46A0Ad3Ba600f4a66FB68F135EAb716D" let advisorsWallet = "0x14589ba142Ff8686772D178A49503D176628147a" /* TODO: Replace with full list of 484 whitelist addresses */ let presalesWhitelist = [ ["0x00A29Dbd171B43d3b3BDd02291F308454eF0A4cE", 1000], ["0x10A29Dbd171B43d3b3BDd02291F308454eF0A4cE", 1001], ["0x20A29Dbd171B43d3b3BDd02291F308454eF0A4cE", 1002], ["0x30A29Dbd171B43d3b3BDd02291F308454eF0A4cE", 1003], ["0x40A29Dbd171B43d3b3BDd02291F308454eF0A4cE", 1004], ["0x50A29Dbd171B43d3b3BDd02291F308454eF0A4cE", 1005], ["0x60A29Dbd171B43d3b3BDd02291F308454eF0A4cE", 1006], ["0x70A29Dbd171B43d3b3BDd02291F308454eF0A4cE", 1007], ["0x80A29Dbd171B43d3b3BDd02291F308454eF0A4cE", 1008], ["0x90A29Dbd171B43d3b3BDd02291F308454eF0A4cE", 1009], ["0x00A29Dbd171B43d3b3BDd02291F308454eF0A4cE", 2000], ["0x10A29Dbd171B43d3b3BDd02291F308454eF0A4cE", 2001], ["0x888623a6DeEc123c844BcEfD57bE30B8bc0a5e27", 2002] ]; function fromEtherToWei(amountInether) { return web3.toWei(new BigNumber(amountInether), 'ether'); } async function whitelist(saleContract) { let sliceSize = 10; for (var i = 0; i < presalesWhitelist.length; i += sliceSize) { var slice = presalesWhitelist.slice(i, i + sliceSize) var addresses = slice.map(item => item[0]); var maxes = slice.map(item => fromEtherToWei(item[1])); console.log("Whitelisting address:"); console.log(slice); console.log("Please confirm transaction."); var receipt = await saleContract.addPresaleWallets(addresses, maxes); console.log("Whitelisted", addresses.length, "addreses.\n\n"); } } async function deploySaleContract() { console.log("Deploying sales contract. Please confirm transaction."); var saleContract = await Tokensale.new(presaleStartTime, startTime, hardCap, investmentFundWallet, miscellaneousWallet, treasury, teamWallet, reserveWallet, advisorsWallet, {from: web3.eth.accounts[0], gas: 6000000}); console.log("Deployed sales contract at address: ", saleContract.address, "\n\n"); return saleContract; } module.exports = async function (deployer, network, accounts) { try { var saleContract = await deploySaleContract(); await whitelist(saleContract); } catch(e) { console.error(e); } }
import { Link } from 'react-router-dom' import styles from './not-found.module.scss' export default function NotFound() { return ( <main className={styles.main}> <h1>.404</h1> <div> The page you are trying to reach does not exist, or has been moved. <Link className="link" to="/">Go to homepage</Link> </div> </main> ) }
export const getTodo = (state) => { return state.taskReducer }
const solution = (S, K) => { let separator = ' '; let splitedString = S.split(separator); let count = 0; let arrayOfSms = ['']; let isItLastWord = index => index === (splitedString.length - 1); const newSplitedArray = [] splitedString.forEach((el, index) => { if (!isItLastWord(index)) newSplitedArray.push(el, separator) else newSplitedArray.push(el); }); let canWeSendEveryWord = newSplitedArray.every(el => el.length <= K); if (!canWeSendEveryWord) return -1; let i = 0; newSplitedArray.forEach((el) => { if (count + el.length <= K) { arrayOfSms[i] += el; } else { count = 0; arrayOfSms.push(''); arrayOfSms[++i] += el; } count += el.length; }); return arrayOfSms.length; } module.exports = solution;
angular.module('myModule', []) .directive('userListTag', function () { return { restrict: 'ECMA', template: '<ul><li ng-repeat="user in users">{{ user.id }} {{ user.name }}</li></ul>', replace: true, controller: function ($scope) { console.log('001 - userListTag controller -', $scope); $scope.users = [ { id: 1, name: '张三', click_count: 0, }, { id: 2, name: '李四', click_count: 0, }, ]; this.addUser = function () { console.log('addUser'); }; $scope.removeUser = function () { console.log('removeUser'); }; }, controllerAs: 'userListTagController', link: { post: function postLink(scope, iElement, iAttrs, userListTagController) { console.log('002 - link (link, object) - postLink', scope); console.log(userListTagController); iElement.on('click', userListTagController.addUser); iElement.on('click', scope.removeUser); }, }, } }) .controller('firstController', ['$scope', function ($scope) { // console.log('002 - firstController -', $scope); }]);
/** * Created by kingson·liu on 2017/3/12. */ goceanApp.controller('AddressCtrl', function ($scope, $rootScope, $state, $timeout, $stateParams, addressService, localStorageService,configService) { var params = configService.parseQueryString(window.location.href); if (params.passportId){ params.nickName = decodeURI(params.nickName); try { params.nickName = Base64.decode(params.nickName); }catch (e){ } localStorageService.set("passport",params); } $scope.passport = localStorageService.get("passport"); var _state = "address"; if ($scope.passport == null){ window.location = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0cae6e3b9632e632&redirect_uri=http://wxsdk.yezaigou.com/wx/page/base&response_type=code&scope=snsapi_base&state="+_state; return; } // 获取JSSDK configService.getJssdkInfo(window.location.href); // 隐藏右上角 configService.hideWXBtn(); $("#ssx").cityPicker({ title: "选择省市县" }); function reset() { $scope.address = {// save, createOrRefresh, 选中地址,设置为default,并且可以更新 id:0, country: "", province: "", city: "", area: "", address: "", receiver: "", tel: "", temp:"" }; } var addressList = []; var obj = { passportId:$scope.passport.passportId, token:$scope.passport.token }; addressService.listAddress(obj).then(function(data){ console.log(data); if (data.status == "OK") { var result = data.result; $scope.addressList = result.addressList; addressList = $scope.addressList; var defaultId = result.defaultId; initDefaultAddress(addressList, defaultId); } reset(); },function(err){ }); function initDefaultAddress(addressList, defaultId) { if (addressList.length > 0) { for (i in addressList) { var address = addressList[i]; if (address.id == defaultId) { address.isDefault = 1; $rootScope.defaultAddress = address; } else { address.isDefault = 0; } } } } // $rootScope.addressList = store.addressList; // // 改变全局默认地址内容 $scope.changeDefaultAddress = function (address) { $scope.address = address; $rootScope.defaultAddress = address; var obj = { passportId:$scope.passport.passportId, token:$scope.passport.token, id:address.id }; addressService.setDefaultAddress(obj).then(function(data){ console.log(data); if (data.status == "OK") { for (i in addressList) { var addr = addressList[i]; if (addr.id == address.id) { addr.isDefault = 1; }else{ addr.isDefault = 0; } } if ($rootScope.isAddressChanged != null && $rootScope.isAddressChanged != "undefined" && $rootScope.isAddressChanged == 0){ $rootScope.isAddressChanged = 1; } } },function(err){ }); } $scope.createOrRefresh = function (){ var arr = $scope.address.temp.split(" "); var obj = { passportId:$scope.passport.passportId, token:$scope.passport.token, id:$scope.address.id, country:$scope.address.country, province:arr[0], city:arr[1], area:arr[2], address:$scope.address.address, receiver:$scope.address.receiver, tel:$scope.address.tel } addressService.createOrRefresh(obj).then(function(data){ console.log(data); if (data.status == "OK") { var result = data.result; $scope.addressList = result.addressList; addressList = $scope.addressList; var defaultId = result.defaultId; if (addressList.length == 1) { $rootScope.defaultAddress = addressList[0]; } initDefaultAddress(addressList, defaultId); } reset(); },function(err){ }); } });
$(window).scroll(function (event) { $scroll = $(window).scrollTop(); $menu = $('header nav').first(); if ($scroll <= 3) { $menu.removeClass('menu-active'); } else { $menu.addClass('menu-active'); } }); /* ----------------------------- Slider Testimonial Section ----------------------------- */ $(document).ready(function() { 'use strict'; $('.testimonial-slider').bxSlider({ pagerCustom: '#bx-pager', pager: true, touchEnabled: true, controls: false }); });
var searchData= [ ['porta',['Porta',['../structPorta.html',1,'']]], ['processo',['Processo',['../classProcesso.html',1,'']]] ];
import React, { Component } from 'react'; import Attendee from './attendee.png'; import Bullet from './dot.svg'; import Quizz from './quizz.png'; import Venue from './venue.png'; import Speaker from './speaker.png'; import './index.module.css'; const SOCIAL_LINKS = [ { name: 'facebook', link: 'https://www.facebook.com/mirrorconf/', }, { name: 'twitter', link: 'https://twitter.com/mirrorconf', }, { name: 'youtube', link: 'https://www.youtube.com/channel/UCDez53TT1_v3jr3lGv-QhKw', }, ]; const EVENT_STATS = [ { count: '5', description: 'Days', }, { count: '1', description: 'Party', }, { count: '6', description: 'Workshops', }, { count: '12', description: 'Speakers', }, { count: '1', description: 'Quiz', }, { count: '700+', description: 'Attendees', }, ]; export default class CommandBar extends Component { renderList = (bulletpoint, index) => ( <li role="listitem" key={index}> <img aria-hidden="true" src={Bullet} styleName="bullet" /> <p styleName="bulletpoint"> {bulletpoint.count} {bulletpoint.description} </p> </li> ); renderSocialLinks = (socialNetwork, index) => ( <li role="listitem" styleName="listitem" key={index}> <img aria-hidden="true" src={Bullet} styleName="bullet" /> <p styleName="bulletpoint"> {socialNetwork.name} -{' '} <a href={socialNetwork.link}>{socialNetwork.link}</a> </p> </li> ); render() { return ( <div ref={this.props.onViewport} styleName="root"> <h1 styleName="title">About Mirror Conf</h1> <div styleName="division" /> <p styleName="text"> Mirror Conf is a conference designed to empower designers and front-end developers who have a thirst for knowledge and want to broaden their horizons. It aims to create the perfect set to blur the differences between these two worlds and point towards a more collaborative future. </p> <div styleName="division" /> <h3 id="social-links" styleName="visuallyHidden"> Social Links </h3> <ul aria-labelledby="social-links" styleName="text" role="list"> {SOCIAL_LINKS.map(this.renderSocialLinks)} </ul> <div styleName="division" /> <h2 styleName="subtitle">2018 - The future of web</h2> <div styleName="division" /> <h3 id="event-details" styleName="visuallyHidden"> Event details </h3> <ul aria-labelledby="event-details" styleName="text" role="list"> {EVENT_STATS.map(this.renderList)} </ul> <div styleName="division" /> <img aria-hidden="true" src={Attendee} styleName="verticalImage" /> <img aria-hidden="true" src={Speaker} styleName="horizontalImage" /> <img aria-hidden="true" src={Quizz} styleName="horizontalImage" /> <img aria-hidden="true" src={Venue} styleName="verticalImage" /> </div> ); } }
import React, { Component } from 'react' import RecommendItem from './RecommendItem' export default class Find extends Component { PLUBLICURL = process.env.PUBLIC_URL; recommendMenu = [{ imgUrl: 'imgs/privateFM.jpg', recommendDes: '私人FM' }, { imgUrl: 'imgs/everyDayRecommend.jpg', recommendDes: '每日推荐' }, { imgUrl: 'imgs/musicSheet.jpg', recommendDes: '歌单' }, { imgUrl: 'imgs/rank.jpg', recommendDes: '排行榜' }]; recommendArr = [{ itemName: '推荐歌单', musicList: [{ imgUrl: 'imgs/recommend1.jpg', musicDes: '分手后再次与前任相见你会怎么办?' }, { imgUrl: 'imgs/recommend2.jpg', musicDes: '如何舒服地瘫在沙发上' }, { imgUrl: 'imgs/recommend3.png', musicDes: '2017年度热议单曲TOP100' }, { imgUrl: 'imgs/recommend4.png', musicDes: '聆听话语里百听不厌R&B' }, { imgUrl: 'imgs/recommend5.png', musicDes: '国语古风中国风神曲,细腻地抚摸你的心灵' }, { imgUrl: 'imgs/recommend6.png', musicDes: '【剑网三】天光乍破-暮雪白头' }] }, { itemName: '主播电台', musicList: [{ imgUrl: 'imgs/radio-station1.png', musicDes: '影响你未来的100次心理谈话' }, { imgUrl: 'imgs/radio-station2.png', musicDes: '帮你寻找最有品质的音乐' }, { imgUrl: 'imgs/radio-station3.png', musicDes: '焦元薄古典音乐入门指南' }, { imgUrl: 'imgs/radio-station4.png', musicDes: '知性女神陈一发的空灵音色' }, { imgUrl: 'imgs/radio-station5.png', musicDes: '明星驾到记录音乐人的音乐故事' }, { imgUrl: 'imgs/radio-station6.png', musicDes: '听她的声音,会上瘾' }] }]; constructor(props) { super(props); this.state = { curTab: 'music' } } render() { return ( <div className='content-div'> <div className='find-menu'> <div className={this.state.curTab === 'music' ? 'menu-item actived' : 'menu-item'} onClick={e => this.tabClick('music', e)}>音乐</div> <div className={this.state.curTab === 'video' ? 'menu-item actived' : 'menu-item'} onClick={e => this.tabClick('video', e)}>视频</div> <div className={this.state.curTab === 'radio' ? 'menu-item actived' : 'menu-item'} onClick={e => this.tabClick('radio', e)}>电台</div> </div> <div className='find-music'> <div className='swiper-container'> <img className='swiper-img' src={this.PLUBLICURL + 'imgs/swiper1.jpg'} alt='' /> </div> <div className='recommend-menu'> {this.recommendMenu.map((item, index) => <div key={index} className='recommend-type'> <img className='recommend-img' src={this.PLUBLICURL + item.imgUrl} alt='' /> <span className='recommend-des'>{item.recommendDes}</span> </div> )} </div> {this.recommendArr.map((item, index) => <RecommendItem key={index} {...item} PLUBLICURL={this.PLUBLICURL} /> )} </div> </div> ) } tabClick(tabName,e) { e.stopPropagation(); this.setState({ curTab:tabName }) } }
/** * Switchable - jQuery plugin to create a simple iOS style switcher for checkboxes. * Copyright (c) 2014, Rogério Taques. * * Licensed under MIT license: * http://www.opensource.org/licenses/mit-license.php * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @requires jQuery v1.9 or above * @version 1.1 * @cat Plugins/Form Validation * @author Rogério Taques (rogerio.taques@gmail.com) * @see https://github.com/rogeriotaques/switchable */ /** * CHANGELOG * * 1.0 First release. * Supports label position (after/before), custom checked color and readonly property. * */ (function($){ var version = '1.0.1', // default options defaults = { // define the label position // possible values are 'before' (default) and 'after' label_position: 'before', // a custom color for the switch when checked // default is null, but you can provide following pattern: // #FFF, rgb(255,255,255), rgba(255,255,255, 0.5) or white checked_color: null, // indicates wheter the widget is readonly // possible values: true/false. default is false. readonly: false, // on click callback // function parameters are: event, boolean (that indicates if it's checked) click: null }, methods = { version: function() { return this.each(function() { $(this).html(version); }); }, // version init: function(options) { var o = $.extend(defaults, options); return this.each( function() { var me = $(this), wrapper = $('<div />', {'class': 'switchable-wrapper'}), switcher = $('<div />', {'class': 'switchable-holder', 'style': 'display: inline-block'}), button = $('<div />', {'class': 'switchable-switcher'}), label = $('<div />', {'class': 'switchable-label', 'html': (me.data('label') ? me.data('label'): '')}); button.appendTo(switcher.appendTo(wrapper)); me.after(wrapper); if (me.data('label')) { if (o.label_position == 'before') { switcher.before(label); } else { wrapper.append(label); } } me.hide(); switcher.toggleClass('switchable-checked', me.is(':checked')); // when a custom checked_color is given // force to use this color instead of the default one if (o.checked_color) { _setCustomColor( switcher, me.is(':checked'), o ); } if (! o.readonly) { switcher.on('click', function(e){ me.prop('checked', !me.is(':checked') ); switcher.toggleClass('switchable-checked', me.is(':checked')); // when a custom checked_color is given // force to use this color instead of the default one if (o.checked_color) { _setCustomColor( switcher, me.is(':checked'), o ); } if (o.click && $.isFunction(o.click)) { e.switcher = me; return o.click(e, me.is(':checked')); } }); } else { switcher.addClass('switchable-readonly'); button.css({'cursor': 'not-allowed'}); } }); // this.each } // init }; // methods function _setCustomColor( switcher, is_checked, options ) { switcher.css({ 'border-color': (is_checked ? options.checked_color : ''), 'background-color': (is_checked ? options.checked_color : '') }); } // _setCustomColor $.fn.switchable = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.Switchable()' ); } }; })(jQuery);
// Needs to be called with <script id="rca" data-year="2020" data-type="adult" src="..."></script> to work // Default year is 2020 // type is: adult, train, para, junior, coxie // Needs the store items like adult-membership, junior-membership, coxie-membership, etc. // For example: // <span id="arcextra"></span><script id="rca" data-id="arcextra" data-year="2020" data-type="adult" src="https://msreckovic.github.io/scripts/arc/rca.js"></script> function FixLink(url) { var all = document.getElementsByTagName("a"); for (var i=0; i<all.length; i++) { var el = all[i]; if (el.innerHTML.includes("Pay Online Now") || el.innerHTML.includes("Payez maintenant")) { if (el.hasAttributes()) { var attrs = el.attributes; for (var j=0; j<attrs.length; j++) { if (attrs[j].name.includes("href")) { attrs[j].value = url; } } } } } } function ShortText(membership_type, year) { var text; if (membership_type == "adult") { text = ` <b>Club</b> - Club (recreational) crews typically row 2 or 3 times per week in sculling or sweep boats. Club rowing program is led by volunteer coordinators, who help athletes find rowing opportunities to increase fitness level and rowing proficiency. The crews participate in Summer and Fall regattas.<br> <b>Masters</b> - This program is for rowers over 21 years of age. Typically, these crews are interested in competitive regattas and train more than 3 times a week. The objective is to get compatible crews in terms of technical competency, physical ability and age.<br> `; } else if (membership_type == "university") { text = ` <b>University/U23</b> - This program is for athletes who are at least 19 years old and interested mostly in competitive rowing opportunities. The program includes a wide range of athletes, from those in their first year of competitive rowing to those pushing for provincial and national team opportunities. The program involves an intensive training schedule. `; } else if (membership_type == "junior") { text = ` <b>Junior Program (Boys and Girls)</b> - The Junior Competitive program is open to all junior rowers with rowing experience. Non-experienced athletes are directed to enter the sport through either our Learn-To-Row program and Camp Argo or the Junior Development program. This is a program where Junior athletes learn how to compete. The training is dedicated to the sports of rowing and continuous squad and boat selection occurs. Athletes develop their sports psychology and mental hardness in order to arrive at their best for competition.<br> <b>High School Program</b> - The Argonaut Rowing Club provides expertise coaching and equipment to allow many of the local high schools students to learn to row and to compete. Each year the students compete at Canadian Secondary School Rowing Association Championships. This regatta allows athletes to compete against schools from all across Canada. The High School Rowing Program is a great way to get involved in the sport, build your endurance and meet many new friends. `; } else if (membership_type == "para") { text = ` This program is suited to those Para Athletes who wish to learn/improve/develop their stroke. You will have access to suitable rowing equipment and be supervised by coaches and volunteers. `; } else if (membership_type == "train") { text = ` This is the first full year Club program, for those who have completed our learn to row program. `; } return text; } function HeaderText(membership_type, year, is_bold) { var text = ""; if (is_bold) { text = "<h2>ARC "; } text += year + " "; if (membership_type == "adult") { text += "Club and Masters Programs Membership"; } else if (membership_type == "university") { text += "University/U23 Program Membership"; } else if (membership_type == "junior") { text += "Junior (High School) Program Membership"; } else if (membership_type == "para") { text += "Para Program Membership"; } else if (membership_type == "train") { text += "Learn to Train Membership Program Membership"; } if (is_bold) { text += "</h2>"; } return text; } function AgreeText(membership_type, nextyear) { var text = ` <h3>Membership Application and Membership Agreement</h3><br> <h4>To the President and Directors of the Argonaut Rowing Club:</h4><br> <ul> <li>I hereby confirm that I have read and understood and that I agree to abide by this Membership Agreement, the Club Code of Conduct, all Rules, the By-laws and Policies of the Argonaut Rowing Club including, but not limited to, the ARC Harassment Policy, the Safety Policy of the ARC, the Regulations of the Canadian Coast Guard and the Regulations of Transport Canada. To review all club rules, by-laws and policies, please click here.</li> <li>I understand and accept that it is my responsibility (as per Coast Guard regulations) to have the following required safety equipment either in my shell or in a coach boat accompanying my shell, failing which I will pay any fines issued for failure to adhere to the safety rules and guidelines: one life jacket for each rower or cox; one tow rope; one bailer; a whistle or sounding horn; and one navigation light (flashlight). I agree that a violation of the safety rules and guidelines may result in the suspension or termination of my membership and privileges with the Argonaut Rowing Club.</li> <li>I understand and accept that it is my responsibility to ensure all my fees have been paid in full and all information has been received by the ARC prior to deadlines for membership and regatta registrations. I understand that membership may be denied until prior year debts have been settled.</li> <li>I understand and consent that certain of my personal information will be made available to Rowing Canada Aviron (RCA) and ROWONTARIO.</li> <li>I agree to participate fully on a committee as explained above.</li> <li>I acknowledge that my membership fees and all other fees paid to the ARC are non-refundable.</li> <li>I agree and acknowledge that I undertake any activity, including rowing, weight and fitness training entirely at my own risk, and that I am medically fit to undertake such activity.</li> <li>I agree and acknowledge that rowing is a competitive sport and that if I choose to compete for a space in one of the competitive crews, I will do so with the understanding and full acceptance that the Argonaut Rowing Club does not guarantee that I will succeed in being selected for a competitive program or by the coach of my preferred crew.</li> <li>I agree that the ARC is not responsible for any personal injury sustained by myself or any other person, or for the loss or damage to any property which I have brought to the premises including but not limited to privately owned boats, racks or oars, personal items or other equipment, whether caused by theft, during transportation or by any other cause, including negligence of the ARC or any of its members, coaches, servants, agents or contractors.</li> </ul> By clicking Accept below, I hereby apply for membership in Argonaut Rowing Club under terms that expire on March 31, ` + nextyear + `. In doing so, I agree to the above terms and conditions.<br><br> <h3>Argonaut Rowing Club Photo Release</h3> I grant to the Argonaut Rowing Club (ARC), its representatives and employees the right to take photographs of me and my property in connection with ARC, Regattas and the Western Beaches. I authorize the Argonaut Rowing Club, its assigns and transferees to copyright, use and publish the same in print and/or electronically.<br> I agree that the Argonaut Rowing Club may use such photographs of me with or without my name and for any lawful purpose, including for example such purposes as publicity, illustration, advertising, and Web content.<br><br><br> <h2>Please click the Accept button at bottom left, and follow the payment instructions.</h2> ` return text; } function Everything() { var year = "2020"; var nextyear = "2021"; var membership_type = "adult"; var id_tag = "arcextra"; var script_tag = document.getElementById('rca') if (script_tag) { var argyear = script_tag.getAttribute("data-year"); if (argyear) { year = argyear; nextyear = parseInt(year) + 1; } var argtype = script_tag.getAttribute("data-type"); if (argtype) { membership_type = argtype; } var argid = script_tag.getAttribute("data-id"); if (argid) { id_tag = argid; } } if (window.location.href.includes("Agree")) { document.getElementById(id_tag).innerHTML = HeaderText(membership_type, year, true) + "<br><br>" + ShortText(membership_type, year); } else if (window.location.href.includes("Complete")) { var text = "Click here to open the Argo store and complete the payment"; var url = "https://argonaut-rowing-club.myshopify.com/products/" + membership_type + "-membership"; var el = document.getElementById("HeadLoginName"); if (el) { //url = "https://argonaut-rowing-club.myshopify.com/cart/16140123537510:1?note=" + // el.innerHTML + "-for-Membership-" + year + "-" + membership_type + "-membership"; } document.getElementById(id_tag).innerHTML = "<a href=\"" + url + "\"><h2>" + text + "</h2></a>"; FixLink(url); } else { document.getElementById(id_tag).innerHTML = HeaderText(membership_type, year, false); } } document.addEventListener('DOMContentLoaded', Everything, false);
export const titles = { CONNECTION_ERROR: 'Connection Error', USER_PROFILE_UPDATED: 'Profile update', RESET_PASSWORD: 'Password reset', EMAIL_CONFIRMATION: 'Email confirmation', CONFIRMATION_EMAIL: 'Confirmation Email', BASE_CURRENCY_CHANGE: 'Change in base currency', TIMEZONE_CHANGE: 'Change in timezone', LOGOUT: 'Logout', }; export const errors = { SERVER_CONNECTION_LOST: 'Server connection is lost.', THIS_IS_BETA: 'The information presented here is for the platform demonstration only and should not be considered for trading or making a financial decision.', FIRST_NAME_FIELD_IS_EMPTY: 'Please enter your first name.', LAST_NAME_FIELD_IS_EMPTY: 'Please enter your last name.', NAME_IS_TOO_LONG: 'Your name is too long.', EMAIL_FIELD_IS_EMPTY: 'Please enter your Email.', EMAIL_FORMAT_IS_INCORRECT: 'Please enter your Email correctly.', EMAIL_IS_TOO_LONG: 'Your Email address is too long.', PASSWORD_FIELD_IS_EMPTY: 'Please enter your password.', PASSWORD_IS_TOO_SIMPLE: 'Your password is too simple.', PASSWORD_IS_TOO_LONG: 'Your password is too long.', PASSWORD_CONFIRMATION_FAILED: 'Passwords are not the same.', GRECAPTCHA_VERIFICATION_FAILED: 'Please try again.', USERNAME_FIELD_IS_EMPTY: 'Please enter your username.', USERNAME_IS_TOO_LONG: 'Your username is too long.', ORDER_FAILED_ERROR_TITLE: 'Order Failed', ORDER_FAILED_PRICE_VALIDATION: 'Please enter price.', ORDER_FAILED_AMOUNT_VALIDATION: 'Please enter amount.', ORDER_FAILED_TOTAL_VALIDATION: minimumTradeAmount => `Total must be at least ${minimumTradeAmount}`, BALANCE_IS_NOT_ENOUGH: 'Your balance is not enough.', INTERNET_CONNECTION_LOST: 'Your internet connection is lost.', PHONE_NUMBER_IS_NOT_PROVIDED: 'Phone number is not provided.', PHONE_NUMBER_IS_INCORRECT: 'Please enter your Phone Number correctly.', EMAIL_NOT_CONFIRMED: 'Problem in Email confirmation.', }; export const infos = { COPY_TO_CLIPBOARD_TITLE: 'Copied!', COPY_TO_CLIPBOARD_DESCRIPTION_DEPOSIT: 'The deposit address copied to clipboard.', DEPOSIT_OCCURANCE: (tokenName, amount) => `${amount} ${tokenName} were successfully deposited into your account.`, TRADE_OCCURANCE: 'The trade done successfully.', // TRADE_OCCURANCE: (tokenName, amount, bought) => // `${amount} ${tokenName} were ${bought ? 'bought' : 'sold'} successfully.`, BASE_CURRENCY_CHANGED_TO: baseCurrency => `Your base currency updated to ${baseCurrency}.`, TIMEZONE_CHANGED_TO: timezone => `Your timezone updated to ${timezone}.`, }; export const successes = { PROFILE_UPDATED: 'Your user profile is updated successfully.', PROFILE_IMAGE_UPDATED_SUCCESSFULLY: 'Profile image updated successfully.', RESET_PASSWORD_DESCRIPTION: 'Your password has been updated successfully.', EMAIL_CONFIRMATION_DESCRIPTION: 'Your Email has been confirmed successfully.', CONFIRMATION_EMAIL_SENT: email => `Verification Email sent to ${email}.`, USER_LOGOUT: 'You have successfully logged out.', };
import React, { useState, useEffect, useRef } from 'react'; import { useSelector, useDispatch } from "react-redux"; import { Link as RouterLink } from 'react-router-dom'; import { makeStyles } from '@material-ui/styles'; import { Card, CardContent, CardMedia, Typography, Divider, Link, Avatar, Button, Box } from '@material-ui/core'; import clsx from 'clsx'; import LockIcon from '@material-ui/icons/Lock'; import Grid from '@material-ui/core/Grid'; import { Page } from 'components'; import gradients from 'utils/gradients'; import * as ReactPdf from 'react-pdf'; import { pdfjs } from 'react-pdf'; import ReactToPrint from 'react-to-print'; import { LoginForm, CreatePasswordForm, ForgotPassword } from './components'; import {getJobDetailsPost} from 'actions' import ModalCustom from 'components/ModalCustom'; pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`; const useStyles = makeStyles(theme => ({ root: { height: '100%', display: 'flex', alignItems: 'center', // justifyContent: 'center', // paddingLeft:'50px', padding: theme.spacing(6, 10), [theme.breakpoints.down('xs')]: { alignItems: 'initial', padding: theme.spacing(2), } }, white:{ color:theme.palette.white }, subtitle2: { color: '#ffffffe6' }, typoColor: { color: '#555' }, login: { background: 'url(/images/login-bg.jpg) no-repeat', backgroundSize: 'cover', backgroundPosition: '50% 26%', [theme.breakpoints.down('sm')]: { backgroundPosition: '90% 26%', } }, card: { // width: theme.breakpoints.values.md, maxWidth: '100%', overflow: 'unset', // display: 'flex', position: 'relative', backgroundColor: 'transparent', boxShadow: 'none', '& > *': { flexGrow: 1, flexBasis: '50%', width: '50%', [theme.breakpoints.down('xs')]: { flexBasis: '100%', width: '100%' } }, [theme.breakpoints.down('xs')]: { flexDirection: 'column' } }, content: { padding: '20px', paddingBottom: '15px !important', backgroundColor: '#fff', [theme.breakpoints.down('xs')]: { order: '2', padding: '10px 15px', } }, media: { position: 'relative', borderTopRightRadius: 4, borderBottomRightRadius: 4, padding: theme.spacing(2.5), color: theme.palette.white, display: 'flex', paddingBottom: '70px', backgroundColor: '#0001197d', flexDirection: 'column', // justifyContent: 'flex-end', marginBottom: '15px', [theme.breakpoints.down('xs')]: { order: '1', padding: '5px 20px 15px 20px', } }, mediaTitle: { marginBottom: '5px' }, mediaButton: { position: 'absolute', bottom: '20px', width: 'max-content', [theme.breakpoints.down('xs')]: { position: 'static', marginTop:'5px' } }, descPoints: { paddingLeft: '15px', marginTop: '8px' }, icon: { backgroundImage: gradients.green, color: theme.palette.white, borderRadius: theme.shape.borderRadius, padding: theme.spacing(1), position: 'absolute', top: -32, left: theme.spacing(3), height: 64, width: 64, fontSize: 32 }, loginForm: { marginTop: theme.spacing(2) }, divider: { margin: '12px 0px 8px 0' }, divider2: { margin: theme.spacing(1, 0), backgroundColor: '#b3b3b3' }, person: { marginTop: theme.spacing(2), display: 'flex' }, avatar: { marginRight: theme.spacing(2) }, createTitle: { marginBottom: '15px' }, firstLink: { cursor: 'pointer', marginRight:'15px' }, returningApplicant: { color: theme.palette.yellow, textDecoration: 'underline' }, printTextColor: { color: "inherit" }, pdfButton: { '& > *': { margin: theme.spacing(1), }, 'text-align': 'right', }, forgetUl:{ marginBottom:'20px' }, ElectrinicSignature:{ backgroundColor: '#6a80a0', color:'#fff', padding: '10px 24px', textAlign:'center', }, ElectrinicSignatureDetails:{ height:'360px', overflowY:'auto', padding:'15px', textAlign:'left' }, closeSignatureBtn:{ } })); const Login = () => { const classes = useStyles(); const reactPdfComp = useRef(null); const dispatch = useDispatch(); const [openCreatePass, setOpenCreatePass] = useState(false); const [openPDFDialog, setOpenPDFDialog] = useState(false); const [pdfFilePath, setPdfFilePath] = useState(""); const [numPages, setNumPages] = useState(null); const [pageNumber, setPageNumber] = useState(1); const [openForgotPass, setOpenForgotPass] = useState(false); const [electroicSignature, setElectroicSignature] = useState(false); useEffect(() => { let mounted = true; if (mounted) { setPdfFilePath("https://arxiv.org/pdf/2005.07213.pdf"); const params = { ClientSuffix : 'kellertransportationllc', JobCode : 'neenahcdl' } dispatch(getJobDetailsPost(params)); } return () => { mounted = false; }; }, []); const jobDetails = useSelector( state => state.auth.jobDetails ); const handleOpenCreatePass = () => { setOpenCreatePass(true); }; const handleCloseCreatePass = () => { setOpenCreatePass(!openCreatePass); }; const handleOpenPDFDialog = () => { setOpenPDFDialog(true); }; const handleClosePDFDialog = () => { setOpenPDFDialog(!openPDFDialog); }; const onDocumentLoadSuccess = ({ numPages }) => { setNumPages(numPages); } const renderAllPages = () => { let allPages = []; for (let i = 1; i <= numPages; i++) { allPages.push(<ReactPdf.Page pageNumber={i} key={"Page_" + i} />); } return allPages; } const handleOpenForgotPass =()=>{ setOpenForgotPass(true) } const handleCloseForgotPass =() => { setOpenForgotPass(!openForgotPass) } const handleOpenSignature =() => { setElectroicSignature(true) } const handleCloseSignature =() => { setElectroicSignature(!electroicSignature) } const handleCloseError = () =>{ } console.log(jobDetails); return ( <Page className={clsx(classes.root, classes.login)} title="Login"> <Card className={classes.card}> <CardMedia className={classes.media} title="Cover"> <Typography color="inherit" className={classes.mediaTitle} variant="h3" gutterBottom> {jobDetails.greeting} </Typography> <Typography color="inherit" variant="h5"> {jobDetails.jobTitle} </Typography> <Divider className={classes.divider2} /> <Typography className={classes.subtitle2} color="inherit" variant="subtitle2"> {jobDetails.jobDescription} </Typography> {/* <ul className={classes.descPoints}> <li> {' '} <Typography className={classes.subtitle2} color="inherit" variant="subtitle2"> Steady hours! </Typography> </li> <li> <Typography className={classes.subtitle2} color="inherit" variant="subtitle2"> Straight, box or drywall box truck experience is a plus. </Typography> </li> <li> <Typography className={classes.subtitle2} color="inherit" variant="subtitle2"> No dock work at terminals. </Typography> </li> <li> <Typography className={classes.subtitle2} color="inherit" variant="subtitle2"> Sign on bonus! </Typography> </li> </ul> */} <Button className={classes.mediaButton} variant="contained" color="primary" onClick={handleOpenPDFDialog} > View Full Job Description </Button> </CardMedia> <CardContent className={classes.content}> <Typography gutterBottom variant="h4"> Get Started! </Typography> <Typography className={classes.returningApplicant} variant="subtitle2"> Returning Applicant </Typography> <LoginForm className={classes.loginForm} /> <Divider className={classes.divider} /> <Link align="center" color="secondary" onClick={handleOpenCreatePass} underline="always" className={classes.firstLink} variant="subtitle2"> First Visit? Create Your Password </Link> <Link align="center" color="secondary" onClick={handleOpenForgotPass} underline="always" className={classes.firstLink} variant="subtitle2"> Forgot Password? </Link> </CardContent> </Card> <ModalCustom title="Welcome New Applicant" open={openCreatePass} close={handleCloseCreatePass} actions={false} backDrop={true} width="md"> <Grid container spacing={6}> <Grid item xs={12} sm={6} md={6} lg={6}> {electroicSignature == false ? <Box component="div"> <Typography color="inherit" variant="h4"> Before you begin, you will need: </Typography> <ul className={classes.descPoints}> <li> {' '} <Typography className={classes.typoColor} color="inherit" variant="subtitle1"> Residency history for prior 3 years </Typography> </li> <li> <Typography className={classes.typoColor} color="inherit" variant="subtitle1"> Employment history - must provide 3 years </Typography> </li> <li> <Typography className={classes.typoColor} color="inherit" variant="subtitle1"> Employment history - plus 7 years if applying for CDL position </Typography> </li> <li> <Typography className={classes.typoColor} color="inherit" variant="subtitle1"> Driving Experience history </Typography> </li> <li> <Typography className={classes.typoColor} color="inherit" variant="subtitle1"> Driver’s License Information (current license and license held in another state within the prior 3 years) </Typography> </li> </ul> </Box> : <Box className={classes.ElectrinicSignature} component="div"> <Typography color="inherit" variant="h4" align='center' className={classes.createTitle}> Electronic Signature Details </Typography> <Divider className={classes.divider} /> <Box className={classes.ElectrinicSignatureDetails} component="div"> <Typography className={classes.white} color="inherit" variant="subtitle1"> To sign a document electronically, fill out your name and last four digits of your [SSN or password] and click both the ["I Accept" button and the "Submit" button] appearing at the bottom of the document. NOTE: Your electronic signature will not be applied to the document until you correctly complete all of these steps. </Typography> <Typography className={classes.white} color="inherit" variant="subtitle1"> If you want to make changes in information you provided, click "Back" button on your browser. If you do not agree to sign the document electronically, click the "I do not agree" button. </Typography> <Typography className={classes.white} color="inherit" variant="subtitle1"> When you have completed a document that requires your electronic signature, you may use your browser to view, print, or download the document before you sign it and/or after you sign it. Once all of the documents have been completed and signed, you may also view, download or print the complete, signed documents by clicking the "Print" button that appears on your screen, or at a later time by logging in again using your candidate name and password. </Typography> <Typography className={classes.white} color="inherit" variant="subtitle1"> Click here for the hardware/software requirements needed to access and retain the electronic records related to your application, including the documents you are asked to sign. You may also contact: </Typography> <Typography className={classes.white} color="inherit" variant="subtitle1"> [ADD COMPANY INFORMATION] for a free copy of the documents you sign. Proper identification will be required before such information is provided. </Typography> <Typography className={classes.white} color="inherit" variant="subtitle1"> Once the signature process is completed, your electronic signature will be binding as if you had physically signed the document by hand. </Typography> <Typography className={classes.white} color="inherit" variant="subtitle1"> If at any point you would like to withdraw your consent for your electronic signature, or if you need to update information needed to contact you electronically, please contact _______ at _________. Any withdrawal of consent will be effective as of the date it is received. </Typography> </Box> <Divider className={classes.divider} /> <Button type="submit" className={classes.closeSignatureBtn} variant="contained" color="default" size="large" align="center" // disabled={isSubmitting} onClick={handleCloseSignature} > Close </Button> </Box>} </Grid> <Grid item xs={12} sm={6} md={6} lg={6}> <Typography color="inherit" variant="h4" className={classes.createTitle}> Create Your User Name &amp; Password </Typography> <CreatePasswordForm handleOpenSignature={()=>handleOpenSignature()} /> </Grid> </Grid> </ModalCustom> <ModalCustom title="Job Description" open={openPDFDialog} close={handleClosePDFDialog} actions={false} backDrop={true} width="md"> <div className={classes.pdfButton}> <Button href={pdfFilePath} target="_blank" download="proposed_file_name" component={Link} variant="contained" color="primary"> Download </Button> <Button variant="contained" color="primary"> <ReactToPrint trigger={() => { return <Link className={classes.printTextColor} href="#">Print</Link>; }} content={() => reactPdfComp.current} /> </Button> </div> <ReactPdf.Document ref={reactPdfComp} loading={""} file={pdfFilePath} onLoadSuccess={onDocumentLoadSuccess}> {renderAllPages()} </ReactPdf.Document> </ModalCustom> <ModalCustom title="Forgot your Password?" open={openForgotPass} close={handleCloseForgotPass} // submitButton={} actions={false} backDrop={true} width="sm"> <Typography color="inherit" variant="subtitle1" className={classes.createTitle}> Change your password in three easy steps. This will help you to secure password! </Typography> <ul className={clsx(classes.descPoints, classes.forgetUl)}> <li> {' '} <Typography className={classes.typoColor} color="inherit" variant="subtitle1"> Enter your email address below. </Typography> </li> <li> <Typography className={classes.typoColor} color="inherit" variant="subtitle1"> Our system will send you a temporary link. </Typography> </li> <li> <Typography className={classes.typoColor} color="inherit" variant="subtitle1"> Use the link to reset your password. </Typography> </li> </ul> <ForgotPassword /> </ModalCustom> </Page> ); }; export default Login;
import React from 'react'; // eslint-disable-line no-unused-vars import { AlignmentToolbar } from '@wordpress/block-editor'; import { Fragment } from '@wordpress/element'; export const ParagraphToolbar = (props) => { const { paragraph: { styleAlign, }, onChangeStyleAlign, } = props; return ( <Fragment> {onChangeStyleAlign && <AlignmentToolbar value={styleAlign} onChange={onChangeStyleAlign} /> } </Fragment> ); };
var map; var graphicsLayer; require(["esri/map", "esri/layers/ArcGISTiledMapServiceLayer", "esri/tasks/query", "esri/tasks/QueryTask", "dojo/data/ItemFileReadStore", "dijit/form/FilteringSelect", "esri/layers/GraphicsLayer", "esri/symbols/SimpleFillSymbol", "esri/graphic", "dojo/dom", "dojo/on", "dojo/domReady!"], function init(Map, Tiled, Query, QueryTask, itemFileReadStore, FilteringSelect, GraphicsLayer, SimpleFillSymbol, Graphic, dom, on) { map = new Map("mapDiv"); var basemap = new Tiled("http://eservices.alriyadh.gov.sa:7070/wariyadhgeomap/rest/services/riyadhgeomap/RiyadhBaseMap/MapServer"); map.addLayer(basemap); graphicsLayer = new GraphicsLayer({ id: "myGraphicsLayer" }); map.addLayer(graphicsLayer); var queryTask, query; LoadAllPlans(); on(dom.byId("execute"), "click", execute); function LoadAllPlans() { queryTask = new QueryTask("http://eservices.alriyadh.gov.sa:7070/wariyadhgeomap/rest/services/riyadhgeomap/RiyadhBaseMap/MapServer/14"); query = new Query(); query.returnGeometry = true; query.outFields = ["GIS.Plans.PLANID", "GIS.PLANPRIMARYINFO.PLANNO", "GIS.PLANPRIMARYINFO.PLANVERSION"]; query.where = "1=1"; queryTask.execute(query, showResultsPlans); dojo.byId('cmbPlans').onchange = function () { PlansComboChange(dojo.byId('cmbPlans')); }; } function LoadParcels(PlanId) { queryTask = new QueryTask("http://eservices.alriyadh.gov.sa:7070/wariyadhgeomap/rest/services/riyadhgeomap/RiyadhBaseMap/MapServer/9"); query = new Query(); query.returnGeometry = true; query.outFields = ["PARCELID", "PARCELNO", "PLANID", "PLANBLOCKID", "PLANNO", "DISTRICT"]; query.where = "PLANID =" + PlanId; queryTask.execute(query, showResultsParcels); dojo.byId('cmbVersion').onchange = function () { parcelComboChange(dojo.byId('cmbVersion')); }; } function showResultsPlans(results) { var planArray = new Array(); for (var i = 0, il = results.features.length; i < il; i++) { var featureAttributes = results.features[i].attributes; if (featureAttributes["GIS.PLANPRIMARYINFO.PLANNO"] && featureAttributes["GIS.PLANPRIMARYINFO.PLANNO"] != "0") { var option = document.createElement("option"); if (!featureAttributes["GIS.PLANPRIMARYINFO.PLANVERSION"] || featureAttributes["GIS.PLANPRIMARYINFO.PLANVERSION"] == "0") { option.text = featureAttributes["GIS.PLANPRIMARYINFO.PLANNO"]; } else { option.text = featureAttributes["GIS.PLANPRIMARYINFO.PLANNO"] + "(" + featureAttributes["GIS.PLANPRIMARYINFO.PLANVERSION"] + ")"; } planArray[i] = option.text; option.Value = results.features[i]; dojo.byId('cmbPlans').options.add(option); } } var sortedArray = planArray.sort(); var options = dojo.byId('cmbPlans').options; dojo.byId('cmbPlans').options = null; var optionSelect = document.createElement("option"); optionSelect.text = "-- إختر --"; optionSelect.Value = null; dojo.byId('cmbPlans').options.add(optionSelect); for (var k = 0; k < sortedArray.length; k++) { for (var j = 0; j < options.length; j++) { if (sortedArray[k] == options[j].text) { dojo.byId('cmbPlans').options.add(options[j]); } } } HidePleaseWait(); SelectChooseOption(document.getElementById('cmbPlans')); } function showResultsParcels(results) { var disArray = new Array(); ClearCombo(dojo.byId('cmbVersion')); for (var i = 0, il = results.features.length; i < il; i++) { var featureAttributes = results.features[i].attributes; if (featureAttributes["PARCELNO"]) { var option = document.createElement("option"); if (!featureAttributes["PLANBLOCKID"] || featureAttributes["PLANBLOCKID"] == "0") { option.text = featureAttributes["PARCELNO"]; } else { option.text = featureAttributes["PARCELNO"] + "(بلوك " + featureAttributes["PLANBLOCKID"] + ")"; } disArray[i] = option.text; option.Value = results.features[i]; dojo.byId('cmbVersion').options.add(option); } } var sortedArray = disArray.sort(); var options = dojo.byId('cmbVersion').options; dojo.byId('cmbVersion').options = null; var optionSelect = document.createElement("option"); optionSelect.text = "-- إختر --"; optionSelect.Value = null; dojo.byId('cmbVersion').options.add(optionSelect); for (var k = 0; k < sortedArray.length; k++) { for (var j = 0; j < options.length; j++) { if (sortedArray[k] == options[j].text) { dojo.byId('cmbVersion').options.add(options[j]); } } } HidePleaseWait(); SelectChooseOption(document.getElementById('cmbVersion')); } function PlansComboChange(dropdown) { var myindex = dropdown.selectedIndex; var SelValue = dropdown.options[myindex].Value; if (SelValue) { map.graphics.clear(); HighlightPolygonSymbol(SelValue); //Add graphic to the map graphics layer. map.graphics.add(SelValue); var OBJECTIDExtent = SelValue.geometry.getExtent(); map.setExtent(OBJECTIDExtent); } LoadParcels(dropdown.options[myindex].Value.attributes["GIS.Plans.PLANID"]); } function parcelComboChange(dropdown) { var myindex = dropdown.selectedIndex; var SelValue = dropdown.options[myindex].Value; if (SelValue) { map.graphics.clear(); HighlightPolygonSymbol(SelValue); //Add graphic to the map graphics layer. map.graphics.add(SelValue); var OBJECTIDExtent = SelValue.geometry.getExtent(); map.setExtent(OBJECTIDExtent); map.infoWindow.hide(); showInfowWindow("قطعة أرض", PreparePlanNumberText(SelValue), SelValue); HideMainMenu(); } } function HighlightPolygonSymbol(Graphic) { var symbol = new esri.symbol.SimpleFillSymbol().setColor(new dojo.Color([235, 150, 237, 0.35])); Graphic.setSymbol(symbol); } function PreparePlanNumberText(SelValue) { return "قطعة رقم: " + SelValue.attributes["PARCELNO"] + "\n" + " رقم المخطط:" + SelValue.attributes["PLANNO"]; } function showInfowWindow(title, content, polygon) { map.infoWindow.setTitle(title); map.infoWindow.setContent(content); var screenPoint = map.toScreen(polygon.geometry.getExtent().getCenter()); var mapPoint = map.toMap(screenPoint); map.infoWindow.show(mapPoint, screenPoint); map.setExtent(polygon.geometry.getExtent()); } function ClearCombo(combo) { var length = combo.options.length; if (length > 1) { for (i = length; i >= 0; i--) { combo.options[i] = null; } } } });
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const express_1 = require("express"); const controladorIndex_1 = __importDefault(require("../controladores/controladorIndex")); class RutaInicial { constructor() { this.rutaInicio = express_1.Router(); this.configuracion(); } configuracion() { this.rutaInicio.get('/', controladorIndex_1.default.inicio); } } const rutas = new RutaInicial(); exports.default = rutas.rutaInicio;
export default { basket: { "title": "Cesta", "loading": "Espera. Estamos actualizando tu cesta...", "removeItem": "eliminar {{name}} de tu cesta", "empty": "Tu cesta está vacía", "remainingUntilFreeShipping": "Añade otra {{amount, currency}} a tu pedido para tener envío gratuito.", "totalPrice": "Precio total", "discount": "Descuento", "shippingPrice": "Envio", "tax": "[Tax]", "totalToPay": "A pagar", "goToCheckout": "Ir a pagar", "vouchers": { "title": "Vale", "invalidCode": "El vale no ha podido ser aplicado", "inputPlaceholder": "[Got a voucher code?]", "applyCode": "[Apply]", "remove": "[Remove voucher]" } }, checkout: { "title": "Comprar", "payNow": "Pagar ahora", "choosePaymentMethod": "Elegir método de pago", "noPaymentProvidersConfigured": "No hay proveedores de pago configurados", "paymentProviderNotConfigured": "El proveedor de pagos {{name}} no está configurado", "paymentProviderLogoAlt": "Logo de {{name}}", "loadingPaymentGateway": "Inicializando pasarela de pago...", "loadingPaymentGatewayFailed": "Oh no. No pudimos cargar la pasarela de pago de {{name}}", "confirmation": { "title": "Confirmación de pedido", "shortStatus": "Tu pedido se ha confirmado.", } }, common: { "frontpage": "Inicio", "price": "{{value, currency}}", "tax": "VAT: {{value, currency}}", "close": "Cerrar", "menu": "Menú", "searchPlaceholder": "Busca cosas", "ecomBy": "eCommerce por", "loadingVideo": "Cargando video", "slider": { "previous": "Ver el elemento siguiente", "next": "Ver el elemento anterior" }, "search": { "placeholder": "[Find things]", "label": "Buscar", "foundResults": "Hemos encontrado {{count}} resultado de búsqueda", "foundResults": "Hemos encontrado {{count}} resultados de búsqueda" } }, customer: { "name": "Nombre", "firstName": "Nombre", "lastName": "Apellido", "streetAddress": "Dirección", "postalCode": "Codigo postal", "email": "Correo electrónico", "emailPlaceholder": "tu@tu.direcction", "login": { "title": "Inicio sesión", "loggedIn": "Tienes una sesión activa", "instructions": "Introduce una dirección de correo electrónico y te enviaremos un enlace mágico para inciar sesión a tu correo.", "emailAddressInvalid": "Por favor introduce una dirección de correo electrónico válida", "sendMagicLink": "Envíame el enlace mágico" }, "account": { "title": "[My account]" } }, order: { "total": "Total", "item": "Ordenar objeto", "item_plural": "Ordenar objetos" }, product: { "relatedProduct": "También podrías estar interesado en", "relatedProduct_plural": "También podríais estar interesados en", "addToBasket": "Añadir a la cesta", "buy": "COMPRA", "stock": "{{stockCount}} en reserva", "outOfStock": "Sin reserva" }, search: { "orderTitle": "Ordenar por", "order": { "ITEM_NAME_ASC": "Nombre ascendente", "ITEM_NAME_DESC": "Nombre descendente", "PRICE_ASC": "Precio ascendente", "PRICE_DESC": "Precio descendente", "STOCK_ASC": "Objetos reserva ascendente", "STOCK_DESC": "Objetos reserva descendente" }, "filter": "Filtrar", "facets": { "viewNResults": "Mostrar {{count}} resultado", "reset": "Reiniciar", "price": { "title": "Precio", "min": "Precio mínimo", "max": "Precio máximo" } } }, }
module.exports = { title: 'CSS Tricks', description: '记录常用的 CSS 技巧', themeConfig: { nav: [ { text: '主页', link: '/' }, { text: 'Github', link: 'https://github.com/onecun' }, ], sidebar: [ ['/', '首页'], { title: '技巧', collapsable: false, children: [ '/tricks/vertical-middle/', '/tricks/horizontal-middle/', '/tricks/layout/three/', '/tricks/layout/two/', '/tricks/sticky-footor/', '/tricks/ellipsis/', '/tricks/glass/', '/tricks/line-break/', ] }, { title: '动画', collapsable: false, children: [ '/animation/tab/', '/animation/accordion/', '/animation/border/', '/animation/loading/', ] }, { title: '原理', collapsable: false, children: [ '/theory/css-animation/', '/theory/flex/', '/theory/grid/', '/theory/bfc/', '/theory/box-shadow/', '/theory/cursor/', ] }, ], }, }
import { args } from '@kuba/router' import h from '@kuba/h' import text from '@kuba/text' function component () { return ( <text.Strong master dark xxs medium>{args.email}</text.Strong> ) } export default component
const greeter = (name = 'Guest') => { console.log(`Hi, ${name}`); } greeter('Beto') greeter();
const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(45, 250 / 300, 1, 2000); camera.position.z = 150; scene.add(camera); const ambientLight = new THREE.AmbientLight(0xaaaaaa, 0.4); scene.add(ambientLight); const pointLight = new THREE.PointLight(0xdddddd, 0.8); camera.add(pointLight); const root = new THREE.Object3D(); scene.add(root); const models = []; function setModel(i, el, materials) { const path = el.selectedOptions[0].getAttribute("data-path"); const obj = new THREE.OBJLoader2(); obj.setLogging(false); obj.setMaterials(materials); obj.load("../Content/CharacterModels/" + path, e => { console.log(e); const object = e.detail.loaderRootNode; const oldObject = models[i]; if (oldObject) root.remove(oldObject); root.add(object); models[i] = object; }) } new THREE.MTLLoader() .setPath("../Content/CharacterModels/") .load("materials.mtl", function (materials) { materials.preload(); document.querySelectorAll("select").forEach((el, i) => { setModel(i, el, materials.materials); el.addEventListener("change", () => setModel(i, el, materials.materials)) }); }) const renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true }); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(250, 300); document.getElementById("helios").appendChild(renderer.domElement); let speed = 0; let otherSpeed = 0; document.addEventListener("mousemove", e => { speed += e.movementX; otherSpeed += e.movementY; }); function animate() { requestAnimationFrame(animate); camera.lookAt(scene.position); renderer.render(scene, camera); root.rotation.y += speed / 1000; root.rotation.y *= 0.975; root.rotation.x += otherSpeed / 1000; root.rotation.x *= 0.975; speed *= 0.9; otherSpeed *= 0.9; } animate();
//adding to an array //add at the end let a = [1, 2, 3]; console.log(a); a.push(4); console.log(a); //add at the beginning a.unshift(0); console.log(a); //Removing an item from an array from the end a.pop(); console.log(a); //removing an item from the beginning a.shift(); console.log(a); //remove at a random position console.log("remove at a random position"); let b = [1, 2, 3, 4, 5, 6, 7, 8]; console.log(b); let getFirst2Items = b.splice(0, 2);// get the first 2 items. console.log(b); console.log(getFirst2Items); a.splice(3, 2); //get the 2 items starting from index 3 console.log(b); //remove and insert in place a.splice(2, 3, 2, a, b); //removes 3 items starting from //index 2, and adds 2 items still starting from index 2 //join multiple arrays const z = [1, 2]; const y = [3, 4]; console.log(z.concat(y)); //a.indexOf() //Returns the index of the first matching item found, or - 1 if not found //a.lastIndexOf() //Returns the index of the last matching item found, or - 1 if not found
{ "phoneList": [ { "id": "001", "name": "Nexus S", "img": "Samsung.jpg", "snippet": "Fast just got faster with Nexus S!", "age": 0 }, { "id": "002", "name": "Nokia X", "img": "Nokia.jpg", "snippet": "Niubility phone!", "age": 2 }, { "id": "003", "name": "Iphone5", "img": "Iphone.jpg", "snippet": "The next generate phone!", "age": 4 }, { "id": "004", "name": "MeizuMX", "img": "Meizu.jpg", "snippet": "Made in china and we proud of it!", "age": 3 }, { "id": "005", "name": "Iphone4", "img": "Iphone4.jpg", "snippet": "The 4 generate phone!", "age": 5 }, { "id": "006", "name": "Meizu2", "img": "Meizu2.jpg", "snippet": "Made in china and we proud of it!", "age": 6 } ], "phoneDetail": [ { "id":"001", "additionalFeatures": "Contour Display, Near Field Communications (NFC),...", "android": { "os": "Android 2.3", "ui": "Android" }, "images": [ "/Image/Iphone.jpg", "/Image/Iphone4.jpg", "/Image/Meizu2.jpg" ], "storage": { "flash": "16384MB", "ram": "512MB" } }, { "id":"002", "additionalFeatures": "Contour Display, Near Field Communications (NFC),...", "android": { "os": "Android 2.3", "ui": "Android" }, "images": [ "/Image/Samsung.jpg", "/Image/Nokia.jpg", "/Image/Meizu.jpg" ], "storage": { "flash": "16384MB", "ram": "512MB" } }, { "id":"003", "additionalFeatures": "Contour Display, Near Field Communications (NFC),...", "android": { "os": "Android 2.3", "ui": "Android" }, "images": [ "/Image/Nokia.jpg", "/Image/Meizu.jpg", "/Image/Meizu2.jpg" ], "storage": { "flash": "16384MB", "ram": "512MB" } }, { "id":"004", "additionalFeatures": "Contour Display, Near Field Communications (NFC),...", "android": { "os": "Android 2.3", "ui": "Android" }, "images": [ "/Image/Meizu2.jpg", "/Image/Meizu.jpg", "/Image/Samsung.jpg" ], "storage": { "flash": "16384MB", "ram": "512MB" } }, { "id":"005", "additionalFeatures": "Contour Display, Near Field Communications (NFC),...", "android": { "os": "Android 2.3", "ui": "Android" }, "images": [ "/Image/Iphone4.jpg", "/Image/Iphone.jpg", "/Image/Meizu2.jpg" ], "storage": { "flash": "16384MB", "ram": "512MB" } }, { "id":"006", "additionalFeatures": "Contour Display, Near Field Communications (NFC),...", "android": { "os": "Android 2.3", "ui": "Android" }, "images": [ "/Image/Nokia.jpg", "/Image/Iphone4.jpg", "/Image/Meizu2.jpg" ], "storage": { "flash": "16384MB", "ram": "512MB" } } ] }
// Load required modules... var mongoose = require('mongoose'); // Define the schema for our space time model var spacetimeSchema = mongoose.Schema({ uid: String, time: Number, type: String }); // Create the model for space times and expose it to our app module.exports = mongoose.model('Spacetime', spacetimeSchema);
const connection = require("../config/connection.js"); var orm = { selectAll: function(table, cb){ const queryString = `SELECT * FROM ${table};`; connection.query(queryString, function (err, result) { if (err) {throw err;}; cb(result); }); }, insertOne: function (table, column, value, cb) { let queryString = `INSERT INTO ${table} (${column.toString()}) VALUES ("${value.toString()}");`; console.log(queryString); connection.query(queryString, function (err, result) { if (err) {throw err;}; cb(result); }); }, updateOne: function (table, column, value, condition, cb) { let queryString = `UPDATE ${table.toString()} SET ${column.toString()} = ${value} WHERE ${condition.toString()};`; console.log(queryString); connection.query(queryString, function (err, result) { if (err) { throw err; }; cb(result); }); } }; module.exports = orm;
//验证手机号 export default { isMObile: function(value){ var val = value.replace(/\ +/g, ""); if (!value.match("^((13[0-9])|(14[0-9])|(15[0|1|2|3|5|6|7|8|9])|(17[0-9])|18[0-9])\\d{8}|(170\\d{8})$")) { return true; } }, lengthCheck: function(value, length){ var value = value.replace(/\ +/g, ""); if(value.length < length){ return true; } }, checkPwd: function(value){ var value = value.replace(/\ +/g, ""); if(!value.match(/^[0-9a-zA-Z]{6,16}$/)){ return true; } }, isEqual: function(value1, value2){ var value1 = value1.replace(/\ +/g, ""); var value2 = value2.replace(/\ +/g, ""); if(value1 != value2){ return true; } }, isEmail: function(value){ if (!value.match("^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$")) { return true; } } }
/* eslint-disable no-extend-native */ /** * 获取当前字符串hashCode */ String.prototype.getHashCode = function () { var hash = 1315423911 var i = null var ch for (i = this.length - 1; i >= 0; i--) { ch = this.charCodeAt(i) hash ^= ((hash << 5) + ch + (hash >> 2)) } return (hash & 0x7FFFFFFF) } /** * 删除数组中对象 * @param {Object} val - 将要移除的对象 */ Array.prototype.remove = function (val) { var index = this.indexOf(val) if (index > -1) { this.splice(index, 1) } } /** * 删除指定index的元素 * @param {Nubmer} index - 将要删除的元素的下标,默认-1不删除 */ Array.prototype.removeByIndex = function (index = -1) { if (index > -1) { this.splice(index, 1) } } /** * 获取格式化时间 * @param {String} format - 格式化参数,默认:yyyy-MM-dd hh:mm:ss */ Date.prototype.format = function (format = 'yyyy-MM-dd hh:mm:ss') { var o = { 'M+': this.getMonth() + 1, 'd+': this.getDate(), 'h+': this.getHours(), 'm+': this.getMinutes(), 's+': this.getSeconds(), 'q+': Math.floor((this.getMonth() + 3) / 3), 'S': this.getMilliseconds() } if (/(y+)/.test(format)) { format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length)) } for (var k in o) { if (new RegExp('(' + k + ')').test(format)) { format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) } } return format } /** * 获取当前的季度 */ Date.prototype.getQuarter = function () { return parseInt(this.getMonth() / 3) } /** * 定义Cookie对象,便于高效操作Cookie */ window.Cookie = { /** * 获取Cookie * @param {String} key 获取Cookie的key */ getItem: function (key) { var reg = RegExp(key + '=([^;]+)') var arr = document.cookie.match(reg) if (arr) { return arr[1] } else { return null } }, /** * 存储Cookie * @param {String} key key * @param {String} value value * @param {Integer} hour 有效时长,默认24小时 */ setItem: function (key, value, hour = 24) { var date = new Date() date.setTime(date.getTime() + hour * 60 * 60 * 1000) document.cookie = key + '=' + value + ';expires=' + date } }
/* eslint-disable no-undef */ describe('Favorties view', () => { it('Should display no favorites yet if no favorites are added', () => { cy.visit('http://localhost:3000/favorites') cy.get('h3').contains('No favorites yet') }) it('Should have a back to home button to take users back to game', () => { cy.get('a').contains('Back to Home').click() }) it('User should be able to click title to navigate to landing page', () => { cy.visit('http://localhost:3000/favorites') cy.get('h1').contains('Yeezaid What Now?').click() }) })
var struct________line________________number________________table____8js__8js_8js = [ [ "struct____line________number________table__8js_8js", "struct________line________________number________________table____8js__8js_8js.html#a0972131f05347ca1c549bc4337c3dc3d", null ] ];
import React, { Component } from 'react'; import Link from 'next/link' import { getTVshowDetails } from '../lib/moviesLib' import Layout from '../components/Layout' import TvModal from '../components/TvModal' import { Spinner } from 'react-bootstrap'; class TV extends Component { static getInitialProps({ req, res, query }) { const storyid = query.id; return { storyid } } componentDidMount() { this.setState({ loading: true }) getTVshowDetails(this.props.storyid).then(TVshow => this.setState({ TVshow, loading: false })) .catch(this.handleError) } handleError = error => { this.setState({ error: error.response || "Something went Wrong", loading: false }) } state = { TVshow: {}, error: null, loading: false } render() { const { TVshow, error } = this.state; const { name, overview, image_url, homepage, tagline, first_air_date,networks, number_of_seasons, vote_average,created_by, genres, imdb_id } = TVshow; let content = ( this.state.loading ? <Spinner animation="border" variant="primary" /> : <> <h1>{name}</h1> <p className="tagline">{tagline}</p> <img src={image_url} onClick={() => window.open(`${homepage}`, '_blank')} /> <h3>About</h3> <p>{overview}</p> <TvModal homepage={homepage} title={name} genres={genres} rating={vote_average} release_date={first_air_date} seasons={number_of_seasons} networks={networks} creators={created_by} > </TvModal> </> ) content = error?<p>{error.data||error}</p>:content return ( <Layout title={name}> <div className="movie-details"> {content} </div> </Layout> ); } } export default TV;
module.exports = { schema: { enums: require("./enums"), keywords: require("./keywords"), typeDefs: require("./type-defs"), }, content: { breakfasts: require("./breakfasts"), coffeeBreaks: require("./coffee-breaks"), lunches: require("./lunches"), organizers: require("./organizers"), panels: require("./panels"), partners: require("./partners"), presentations: require("./presentations"), schedules: require("./schedules"), speakers: require("./speakers"), tickets: require("./tickets"), workshops: require("./workshops"), }, };
import React from 'react'; import DeleteIcon from '@material-ui/icons/Delete'; import VisibilityIcon from '@material-ui/icons/Visibility'; import ProductCardForList from '../../SharedComponents/Product/ProductCardForList'; import { useStateValue } from '../../StateProvider/StateProvider'; const CartProducts = (props) => { const [state, dispatch] = useStateValue(); const viewIcon = <VisibilityIcon />; const deleteIcon = <DeleteIcon />; const removeProductfromCart = () => { dispatch({ type: 'REMOVE_PRODUCT_FROM_CART', id: props.id, }); console.log(props.description); }; return ( <ProductCardForList id={props.id} name={props.name} image={props.image} price={props.price} description={props.description} viewIcon={viewIcon} deleteIcon={deleteIcon} removeProduct={removeProductfromCart} /> ); }; export default CartProducts;
const { expect } = require("chai"); const { YoTest, assert } = require("yo-unit"); const { YoGenerator, YoHelper } = require("../index"); describe("mergePromptOrOption test", () => { describe("mergePromptOrOption this.prompt test", () => { class FakeGenerator extends YoGenerator { async prompting() { const { mergePromptOrOption } = YoHelper(this); const prompts = [ { type: "input", name: "fakeName", message: `This is fake quetion?`, default: false, }, { type: "input", name: "foo", message: `This is fake quetion?`, }, { type: "input", name: "foo1", message: `This is fake quetion?`, }, ]; this.payload = await mergePromptOrOption(prompts, (nextPrompts) => this.prompt(nextPrompts) ); } writing() {} } let runResult; before(async () => { runResult = await YoTest({ source: FakeGenerator, options: { pwd: __dirname, foo1: "bar1" }, params: { fakeName: "fakeValue", }, }); }); after(() => { if (runResult) { runResult.restore(); } }); it("test mergePromptOrOption", () => { const { generator } = runResult; expect(generator.payload).to.deep.equal({ fakeName: "fakeValue", foo: "bar", foo1: "bar1", }); }); }); describe("mergePromptOrOption promptChain test", () => { class FakeGenerator extends YoGenerator { async prompting() { const { promptChainAll } = YoHelper(this); const prompts = [ { type: "input", name: "fakeName", message: `This is fake quetion?`, default: false, }, { type: "input", name: "foo", message: `This is fake quetion?`, }, { type: "input", name: "foo1", message: `This is fake quetion?`, }, ]; this.payload = await promptChainAll(prompts); } writing() {} } let runResult; before(async () => { runResult = await YoTest({ source: FakeGenerator, options: { pwd: __dirname, foo1: "bar1" }, params: { fakeName: "fakeValue", }, }); }); after(() => { if (runResult) { runResult.restore(); } }); it("test mergePromptOrOption", () => { const { generator } = runResult; expect(generator.payload).to.deep.equal({ fakeName: "fakeValue", foo: "bar", foo1: "bar1", }); }); }); describe("mergePromptOrOption empty prompt test", () => { class FakeGenerator extends YoGenerator { async prompting() { const { mergePromptOrOption, promptChain, promptChainLocator } = YoHelper(this); const prompts = []; this.payload = await mergePromptOrOption(prompts, (nextPrompts) => promptChain(promptChainLocator(nextPrompts)) ); } writing() {} } let runResult; before(async () => { runResult = await YoTest({ source: FakeGenerator, options: { pwd: __dirname, foo1: "bar1" }, params: { fakeName: "fakeValue", }, }); }); after(() => { if (runResult) { runResult.restore(); } }); it("test mergePromptOrOption", () => { const { generator } = runResult; expect(generator.payload).to.deep.equal({}); }); }); });
import React from 'react' import PropTypes from 'prop-types' import { Spinner, Alert } from 'reactstrap' import { useIpfsFilesUpload } from 'hooks/useIpfs' export default function IpfsUploader ({ dir, onDone = () => {} }) { const path = useIpfsFilesUpload(dir) if (path == null) { return ( <Alert color="info"> <Spinner size="sm" color="secondary" /> &nbsp; Uploading to IPFS. </Alert> ) } onDone(path) return null } IpfsUploader.propTypes = { dir: PropTypes.array.isRequired, onDone: PropTypes.func }
import { willMount, paint } from '@kuba/h' import { urlFor } from '@kuba/router' import component from './component' import supabase from '@kuba/supabase' @paint(component) class Auth { @willMount logOut () { supabase .auth .signOut() .then(() => location.assign(urlFor('logIn'))) return this } } export default Auth
import { showLoading, hideLoading } from 'react-redux-loading'; import { getUsers, userAddAnswerToQuestion, userAddNewQuestion, } from './userActions'; import { _getUsers, _getQuestions, _saveQuestion, _saveQuestionAnswer, } from '../utils/Data'; import { addNewQuestion, getQuetions, answerQuestion } from './questionsAction'; export const handleIniteData = () => { return (dispatch) => { dispatch(showLoading()); return _getUsers().then((users) => { dispatch(getUsers(users)); dispatch(hideLoading()); }); }; }; export const handleGetQuestions = () => { return (dispatch) => { return _getQuestions().then((questions) => { dispatch(getQuetions(questions)); }); }; }; export const handleAddQuestion = ({ optionOneText, optionTwoText, author }) => { return (dispatch) => { dispatch(showLoading()); return _saveQuestion({ optionOneText, optionTwoText, author }).then( (questionRes) => { dispatch(addNewQuestion(questionRes)); dispatch(userAddNewQuestion({ qid: questionRes.id, author })); dispatch(hideLoading()); } ); }; }; export const handleAnswerQuestion = ({ answer, loggedInUser, qid }) => { return (dispatch) => { dispatch(showLoading()); return _saveQuestionAnswer({ answer, qid, authedUser: loggedInUser }).then( (_) => { dispatch(hideLoading()); dispatch(userAddAnswerToQuestion({ answer, loggedInUser, qid })); dispatch(answerQuestion({ answer, loggedInUser, qid })); } ); }; };
'use strict'; { $('#logout-button').click((e) => { e.preventDefault(); $.post('/logout', (res) => { window.location.replace('/'); }); }); }
import mongoose, { Schema } from 'mongoose'; const TeamSchema = new Schema({ name: { type: String, required: true, unique: true }, league: { type: mongoose.Schema.Types.ObjectId, ref: 'League' }, year: { type: Number, required: true }, coach: { type: String, required: true }, players: { type: [String], required: true } }); const Team = mongoose.model('Team', TeamSchema); export default Team;
$(function() { window.$Qmatic.components.dropdown.profileSelection = new window.$Qmatic.components.dropdown.BaseDropdownComponent('#prioListModal') })
TQ.floatingPopulationStatistics = function (dfop){ function search(orgId){ var condition = $("#searchByCondition").val(); var initParam = { "organizationId": orgId } if(condition == '请输入姓名或身份证号码'){ initParam = { "organizationId": orgId, "searchFloatingPopulationVo.logOut":0, "searchFloatingPopulationVo.isDeath":false } }else{ initParam = { "organizationId": orgId, "searchFloatingPopulationVo.logOut":0, "searchFloatingPopulationVo.isDeath":false, "searchFloatingPopulationVo.fastSearchKeyWords":condition } } $("#floatingPopulationList").setGridParam({ url: PATH + '/baseinfo/floatingPopulationManage/fastSearchFloatingPopulation.action', datatype: "json", page:1 }); $("#floatingPopulationList").closest(".ui-jqgrid-bdiv").css({ "height" : $("#floatingPopulationListDiv").parent().height()-70}); $("#floatingPopulationList").setPostData(initParam); $("#floatingPopulationList").trigger("reloadGrid"); } function nativePlaceFormatter(el, options, rowData){ var str = ""; if(rowData.province != null) str += rowData.province; if(rowData.city != null) str += rowData.city; if(rowData.district != null) str += rowData.district; return str; } function inflowingSourceFormatter(el, options, rowData){ var str = ""; if(rowData.inflowingProvince != null) str += rowData.inflowingProvince; if(rowData.inflowingCity != null) str += rowData.inflowingCity; if(rowData.inflowingDistrict != null) str += rowData.inflowingDistrict; return str; } function idCardNoFont(el,options,rowData){ if(rowData.logOut==1||rowData.logOut=='1'){ return "<font color='#778899'>"+rowData.idCardNo+"</font>"; }else{ return "<font color='#000'>"+rowData.idCardNo+"</font>"; } } var dialogWidth=800; var dialogHeight=600; $(document).ready(function(){ $("#floatingPopulationList").jqGridFunction({ datatype: "local", colModel:[ {name:"id", index:"id", hidden:true,frozen:true}, {name:"encryptId",index:"id",sortable:false,hidden:true,frozen:true}, {name:"operator", index:'id', label:'操作',formatter:operateFormatter,width:50,frozen:true,sortable:false,align:'center' }, {name:"name", index:'name', label:'姓名',formatter:nameFont,width:80,frozen:true }, {name:'gender',formatter:genderFormatter, label:'性别', align:'center', width:40}, {name:'idCardNo-formmater',index:'idCardNo', label:'身份证号码', formatter:idCardNoFont, width:130,frozen:true}, {name:'idCardNo',index:'idCardNo',label:'身份证号码', hidden:true,hidedlg:true}, {name:'currentAddress', sortable:false, label:'常住地址', width:150 }, {name:'workUnit', sortable:false, label:'工作单位或就读学校', width:200}, {name:'inflowingReason', sortable:false,formatter:inflowingReasonFormatter, label:'流入原因', width:80}, {name:'sourcesState',index:'sourcesState',label:"数据来源",sortable:false,hidden:true,formatter:sourceStateFormatter,width:80,align:'center'}, {name:'updateDate', sortable:false, label:'数据更新时间', width:140}, {name:"usedName", index:'usedName', label:'曾用名/别名', width:80 ,hidden:true}, {name:'organization.orgName',sortable:false,index:'organization.orgName',label:'所属网格',width:200,hidden:true}, {name:'mobileNumber', sortable:false, label:'联系手机', width:80,hidden:true}, {name:'telephone', sortable:false, label:'固定电话', width:80,hidden:true}, {name:"birthday", index:'birthday', label:'出生日期', width:80 ,hidden:true}, {name:"nation",sortable:false,label:"民族",formatter:nationFormatter,width:80, hidden:true }, {name:"politicalBackground",sortable:false,label:"政治面貌",formatter:politicalBackgroundFormatter,width:80,hidden:true}, {name:"schooling",sortable:false,label:"文化程度",formatter:schoolingFormatter,width:80, hidden:true }, {name:'career', sortable:false,formatter:careerFormatter,label:'职业', width:80,hidden:true}, {name:"maritalState",sortable:false,label:"婚姻状况",formatter:maritalStateFormatter,width:80, hidden:true }, {name:"stature",sortable:false,label:"身高(cm)",width:80, hidden:true }, {name:"bloodType",sortable:false,label:"血型",formatter:bloodTypeFormatter,width:80, hidden:true }, {name:"faith",sortable:false,label:"宗教信仰",formatter:faithFormatter,width:80, hidden:true }, {name:"email",sortable:false,label:"电子邮箱",width:80, hidden:true }, {name:'province',index:'province',sortable:false,label:'户籍地',formatter:nativePlaceFormatter,width:150,hidden:true}, {name:'nativePlaceAddress', sortable:false, label:'户籍地详址', width:150,hidden:true}, {name:'otherAddress', sortable:false, label:'临时居所', width:150,hidden:true}, {name:'inflowingDate',index:'inflowingDate', sortable:false, label:'流入时间', width:80,hidden:true}, {name:'inflowingProvince',index:'inflowingProvince',label:'流入来源',formatter:inflowingSourceFormatter,width:150,hidden:true}, {name:'registrationType', sortable:false,formatter:registrationTypeFormatter, label:'登记证情况', width:80,hidden:true}, {name:'registerDate', sortable:false, label:'登记日期', width:80,hidden:true}, {name:'expectedDatedue', sortable:false, label:'预计到期日期', width:80,hidden:true}, {name:'death',sortable:false,hidden:true,hidedlg:true,width:80}, {name:'logOut',sortable:false,hidden:true,hidedlg:true,width:80} ], width:870, height:430, multiselect:true, onSelectAll:function(aRowids,status){ if(status) { var selectedIds = $("#floatingPopulationList").jqGrid("getGridParam", "selarrrow"); var cancelLogOut = 0; var isLogOut = 0; for(var i = 0;i<selectedIds.length;i++){ var row=$("#floatingPopulationList").getRowData(selectedIds[i]); if(selectedIds.length ==1){ $("#view").buttonEnable(); $("#update").buttonEnable(); } if(selectedIds.length >2){ $("#view").buttonDisable(); $("#update").buttonDisable(); $("#cancelLogOut").buttonDisable(); $("#isLogOut").buttonDisable(); } if(selectedIds.length != 0){ $("#delete").buttonEnable();if(isGrid()){ $("#shift").buttonEnable(); } } if(row.logOut == 1 ||row.logOut == "1" ){ cancelLogOut++; }else{ isLogOut++; } } if(cancelLogOut>0&&isLogOut==0){ $("#cancelLogOut").buttonEnable(); $("#isLogOut").buttonDisable(); }else if(cancelLogOut==0&&isLogOut>0){ $("#cancelLogOut").buttonDisable(); $("#isLogOut").buttonEnable(); }else{ $("#cancelLogOut").buttonDisable(); $("#isLogOut").buttonDisable(); } }else{ $("#delete").buttonDisable(); $("#shift").buttonDisable(); $("#view").buttonDisable(); $("#update").buttonDisable(); $("#cancelLogOut").buttonDisable(); $("#isLogOut").buttonDisable(); }}, ondblClickRow: function (rowid){ if(dfop.hasViewFloatingPopulationPermission == 'true'){ viewFloatingPopulationInfo(rowid); } }, loadComplete: afterLoad, onSelectRow: selectRow }); if (getOrgIdForStat() !=null && getOrgIdForStat()!=""){ if('<s:property value="#parameters.isSearch"/>' == 1){ searchFloatingPopulation(); }else{ search(getOrgIdForStat()); } } function getOrgIdForStat(){ var orgIdForStat = $("#orgIdForStat").val(); if(orgIdForStat == null || orgIdForStat == '' || orgIdForStat == 'undefined'){ return getCurrentOrgId(); }else{ return orgIdForStat; } } jQuery("#floatingPopulationList").jqGrid('setFrozenColumns'); }); function afterLoad(){ logOutFormatter(); disableButtons(); checkExport(); } function logOutFormatter(){ var idCollection = new Array(); idCollection=$("#floatingPopulationList").getDataIDs(); for(var i=0;i<idCollection.length;i++){ var ent = $("#floatingPopulationList").getRowData(idCollection[i]); if(ent.logOut==1||ent.logOut=='1'){ $("#floatingPopulationList tr[id="+idCollection[i]+"]").css('color','#778899'); } } } function checkExport(){ if($("#floatingPopulationList").getGridParam("records")>0 || $("#floatingPopulationList").getGridParam("selrow")!=null){ $("#export").buttonEnable(); }else{ $("#export").buttonDisable(); } } function disableButtons(){ $("#update").buttonDisable(); $("#delete").buttonDisable(); $("#view").buttonDisable(); $("#cancelLogOut").buttonDisable(); $("#isLogOut").buttonDisable(); $("#shift").buttonDisable(); } function selectRow(){ var count = $("#floatingPopulationList").jqGrid("getGridParam","records"); var selectedCounts = getActualjqGridMultiSelectCount("floatingPopulationList"); if(selectedCounts == count){ jqGridMultiSelectState("floatingPopulationList", true); }else{ jqGridMultiSelectState("floatingPopulationList", false); } if(selectedCounts==1){ $("#view").buttonEnable(); $("#update").buttonEnable(); $("#delete").buttonEnable(); var selectedId = getSelectedIdLast(); var floatingPopulation = $("#floatingPopulationList").getRowData(selectedId); if(floatingPopulation.logOut==1 ||floatingPopulation.logOut=="1"){ $("#cancelLogOut").buttonEnable(); $("#isLogOut").buttonDisable(); }else{ $("#isLogOut").buttonEnable(); $("#cancelLogOut").buttonDisable(); } }else{ $("#view").buttonDisable(); $("#update").buttonDisable(); var selectedIds = $("#floatingPopulationList").jqGrid("getGridParam", "selarrrow"); var cancelLogOut = 0; var isLogOut = 0; for(var i = 0;i<selectedIds.length;i++){ var row=$("#floatingPopulationList").getRowData(selectedIds[i]); if(row.logOut == 1 ||row.logOut == "1" ){ cancelLogOut++; }else{ isLogOut++; } } if(cancelLogOut>0&&isLogOut==0){ $("#cancelLogOut").buttonEnable(); $("#isLogOut").buttonDisable(); }else if(cancelLogOut==0&&isLogOut>0){ $("#cancelLogOut").buttonDisable(); $("#isLogOut").buttonEnable(); }else{ $("#cancelLogOut").buttonDisable(); $("#isLogOut").buttonDisable(); } } if(isGrid()){ $("#shift").buttonEnable(); }else{ $("#shift").buttonDisable(); } if(selectedCounts==0){ $("#shift").buttonDisable(); $("#delete").buttonDisable(); $("#cancelLogOut").buttonDisable(); $("#isLogOut").buttonDisable(); } } function print(rowid){ if(rowid==null){ return; } var floatingPopulation = $("#floatingPopulationList").getRowData(rowid); $("#floatingPopulationDialog").createDialog({ width: dialogWidth, height: dialogHeight, title:'打印'+title+'信息', modal : true, url: PATH + '/baseinfo/floatingPopulationManage/dispatch.action?mode=print&floatingPopulation.id='+floatingPopulation.id, buttons: { "确定" : function(){ $("#printSpaceDiv").printArea(); $(this).dialog("close"); }, "关闭" : function(){ $(this).dialog("close"); } } }); } function deleteFloatingPopulation(allValue){ $.ajax({ url: PATH + "/baseinfo/floatingPopulationManage/deleteFloatingPopulation.action?floatingPopulationIds="+allValue, success:function(data){ for(var ids=0;ids<data.length;ids++){ $("#floatingPopulationList").delRowData(data[ids]); } $("#floatingPopulationList").trigger("reloadGrid"); $.messageBox({message:"已经成功删除该"+title+"信息!"}); disableButtons(); checkExport(); } }); } function searchFloatingPopulation() { var conditionName = $("#conditionName").val(); var conditionIdCardNo = $("#conditionIdCardNo").val(); var conditionInflowingReasonId = $("#conditionInflowingReason").val(); var conditionUsedName = $("#conditionUsedName").val(); var conditionInflowingStartDate = $("#conditionInflowingStartDate").val(); var conditionInflowingEndDate = $("#conditionInflowingEndDate").val(); var conditionExpectedStartDatedue = $("#conditionExpectedStartDatedue").val(); var conditionExpectedEndDatedue = $("#conditionExpectedEndDatedue").val(); var conditionInflowingProvince = $("#conditionInflowingProvince").val(); var conditionInflowingCity = $("#conditionInflowingCity").val(); var conditionInflowingDistrict = $("#conditionInflowingDistrict").val(); var conditionRegistrationTypeId = $("#conditionRegistrationType").val(); var conditionGenderId = $("#conditionGender").val(); var conditionRegisterStartDate = $("#conditionRegisterStartDate").val(); var conditionRegisterEndDate = $("#conditionRegisterEndDate").val(); var conditionStartBirthday = $("#conditionStartBirthday").val(); var conditionEndBirthday = $("#conditionEndBirthday").val(); var conditionCareerId = $("#conditionCareer").val(); var conditionWorkUnit = $("#conditionWorkUnit").val(); var conditionProvince = $("#conditionProvince").val(); var conditionCity = $("#conditionCity").val(); var conditionDistrict = $("#conditionDistrict").val(); var conditionNativePlaceAddress = $("#conditionNativePlaceAddress").val(); var conditionCurrentAddress = $("#conditionCurrentAddress").val(); var conditionLogOutState = $("#conditionLogOutState").val(); var conditionIsDeathState = $("#conditionIsDeathState").val(); var initParam = { "organizationId": getCurrentOrgId(), "searchFloatingPopulationVo.name":conditionName, "searchFloatingPopulationVo.idCardNo":conditionIdCardNo, "searchFloatingPopulationVo.inflowingReason":conditionInflowingReasonId, "searchFloatingPopulationVo.usedName":conditionUsedName, "searchFloatingPopulationVo.inflowingStartDate":conditionInflowingStartDate, "searchFloatingPopulationVo.inflowingEndDate":conditionInflowingEndDate, "searchFloatingPopulationVo.expectedStartDatedue":conditionExpectedStartDatedue, "searchFloatingPopulationVo.expectedEndDatedue":conditionExpectedEndDatedue, "searchFloatingPopulationVo.inflowingProvince":conditionInflowingProvince, "searchFloatingPopulationVo.inflowingCity":conditionInflowingCity, "searchFloatingPopulationVo.inflowingDistrict":conditionInflowingDistrict, "searchFloatingPopulationVo.registrationType":conditionRegistrationTypeId, "searchFloatingPopulationVo.gender":conditionGenderId, "searchFloatingPopulationVo.registerStartDate":conditionRegisterStartDate, "searchFloatingPopulationVo.registerEndDate":conditionRegisterEndDate, "searchFloatingPopulationVo.startBirthday":conditionStartBirthday, "searchFloatingPopulationVo.endBirthday":conditionEndBirthday, "searchFloatingPopulationVo.career":conditionCareerId, "searchFloatingPopulationVo.workUnit":conditionWorkUnit, "searchFloatingPopulationVo.province":conditionProvince, "searchFloatingPopulationVo.city":conditionCity, "searchFloatingPopulationVo.district":conditionDistrict, "searchFloatingPopulationVo.nativePlaceAddress":conditionNativePlaceAddress, "searchFloatingPopulationVo.currentAddress":conditionCurrentAddress } if(conditionLogOutState!=-1){ $.extend(initParam,{"searchFloatingPopulationVo.logOut":conditionLogOutState}); } if(conditionIsDeathState!=-1){ $.extend(initParam,{"searchFloatingPopulationVo.isDeath":conditionIsDeathState}); } $("#floatingPopulationList").setGridParam({ url: PATH + '/baseinfo/floatingPopulationManage/searchFloatingPopulation.action', datatype: "json", page:1 }); $("#floatingPopulationList").setPostData(initParam); $("#floatingPopulationList").trigger("reloadGrid"); $("#TRAMPRESIDENTstatisticsDialog").dialog("close"); } function checkFieldIsUndefined(field){ if (field.val() != undefined) { return field.val(); } else { return ""; } } function getSelectedIds(){ var selectedIds=''; var selectedIds = $("#floatingPopulationList").jqGrid("getGridParam", "selarrrow"); return selectedIds; } function getSelectedIdLast(){ var selectedId; var selectedIds = $("#floatingPopulationList").jqGrid("getGridParam", "selarrrow"); for(var i=0;i<selectedIds.length;i++){ selectedId = selectedIds[i]; } return selectedId; } }
import uiModules from 'ui/modules'; import FilterBuilder from 'plugins/t4p-graph-plugin/services/filterBuilder'; import GraphBuilder from 'plugins/t4p-graph-plugin/services/graphBuilder'; uiModules.get('t4p-graph-plugin').controller('GraphVisController', function ($scope, $element, Private, courier) { const queryFilter = Private(require('ui/filter_bar/query_filter')); $scope.graphBuilder = new GraphBuilder({ sourceNodeIdExpression: $scope.vis.params.sourceNodeIdExpression, sourceNodeLabelExpression: $scope.vis.params.sourceNodeLabelExpression, targetNodeIdExpression: $scope.vis.params.targetNodeIdExpression, targetNodeLabelExpression: $scope.vis.params.targetNodeLabelExpression, }); $scope.filterBuilder = new FilterBuilder({ index: $scope.vis.indexPattern.title, sourceNodeIdExpression: $scope.vis.params.sourceNodeIdExpression, targetNodeIdExpression: $scope.vis.params.targetNodeIdExpression, }); $scope.message = null; $scope.graphData = { nodes: [], edges: [], }; // dirty hack to get the parent SearchSource, with global query and timerange filter set up const getParentSearchSource = () => { const $parentScope = $element.closest('visualize').parent().scope(); const savedVis = $parentScope.savedVis || $parentScope.savedObj; if (!savedVis) { return; } return savedVis.searchSource; }; const initSearchSource = (parentSearchSource) => { if (this.searchSource || !parentSearchSource) { return; } this.searchSource = new courier.SearchSource(); this.searchSource.inherits(parentSearchSource); this.searchSource.size(() => $scope.vis.params.numberOfRowsToFetch); this.searchSource.onResults((res) => { $scope.graphData = $scope.graphBuilder.buildGraphFromRows(res.hits.hits); if (res.hits.hits.length !== res.hits.total) { $scope.message = 'Displayed ' + res.hits.hits.length + '/' + res.hits.total + ' rows'; } else { $scope.message = 'Displayed ' + res.hits.hits.length + ' rows'; } }); this.searchSource.fetchQueued(); }; $scope.onGraphNodeClick = function (event) { const filter = $scope.filterBuilder.buildNodeFilter(event.data.node.id); queryFilter.addFilters(filter); }; $scope.onGraphEdgeClick = function (event) { const filter = $scope.filterBuilder.buildEdgeFilter(event.data.edge.source, event.data.edge.target); queryFilter.addFilters(filter); }; $scope.$watch(getParentSearchSource, initSearchSource); });
'use strict'; var express = require('express'); var bodyParser = require('body-parser'); var favicon = require('serve-favicon'); var logger = require('morgan'); module.exports = function () { var _publicPath; var _app = express(); var _router = express.Router; return { name : 'http', attach : function (options) { this.http = { app : _app, router : _router }; _publicPath = options.publicPath; _app.use(favicon(_publicPath + '/assets/favicon.ico')); _app.use(express.static(_publicPath)); _app.use(logger('dev')); _app.use(bodyParser.json()); _app.all('*', function (req, res, next) { res.set('Access-Control-Allow-Origin', 'http://localhost'); res.set('Access-Control-Allow-Credentials', true); res.set('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT'); res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Authorization'); if (req.method == 'OPTIONS') { return res.send(200); } next(); }); this.on('allPluginsInitDone', function () { _app.all('/*', function (req, res) { res.sendFile(_publicPath + '/index.html'); }); var server = _app.listen(3000, function () { console.log('Listening on port ' + server.address().port); }); }); }, detach : function() { }, init : function (done) { return done(); } }; };
import mongoose, { SchemaTypes } from 'mongoose'; import httpStatus from 'http-status'; import APIError from '../helpers/APIError'; import { SchemaOptions } from '../helpers/utils'; /* * ***************** * Inputs Schema ******************* * * An Input is a given response to a question * * Details : * ---------- * * question_num — The Question num. * answer - The answer to the Question * */ const InputSchema = new mongoose.Schema( { question_num: { type: String, ref: 'Question' }, answer: SchemaTypes.Mixed }, SchemaOptions ); /** * Add your * - pre-save hooks * - validations * - virtuals */ InputSchema.virtual('question', { ref: 'Question', // The model to use localField: 'question_num', // Find people where `localField` foreignField: 'num', // is equal to `foreignField` // If `justOne` is true, 'members' will be a single doc otherwise an array. // `justOne` is false by default. justOne: true }); /** * Methods */ InputSchema.method({}); /** * Statics */ InputSchema.statics = { /** * Get the inputs by the question_num * @param {String} question_num - The question Num. * @param {boolean} full - If the document should be populated. * @returns {Promise<Input, APIError>} */ getByQuestionNum: async function get({ question_num, full }) { const query = this.find({ question_num }); if (full) query.populate('question'); const input = await query; if (!input) { throw new APIError('No such input exists!', httpStatus.NOT_FOUND, true); } else { return input; } } }; /** * @typedef Input */ export default mongoose.model('Input', InputSchema);
import React, { Component, PropTypes } from 'react'; import { Router, Route, IndexRoute, browserHistory, Link } from 'react-router'; import { connect } from 'react-redux'; import action from '../../Action/Index'; import { Tool, merged } from '../../Container/Tool'; import { DataLoad, DataNull, Header, TipMsgSignin, GetData } from '../common/index'; import './ResetPWD.less'; /** * 聊天头部 * * @export * @class ResetPWDHead * @extends {Component} */ export class ResetPWDHead extends Component { constructor() { super(); } render() { return ( <div className = "ResetPWDHead-box"> <div className="ResetPWDHead-list"> <input type="password" placeholder="请输入原始密码" /> </div> <div className="ResetPWDHead-list"> <input type="password" placeholder="请输入6位以上的新密码" /> </div> </div> ); } } /** * 聊天头部 * * @export * @class ResetPWDBottom * @extends {Component} */ export class ResetPWDBottom extends Component { render() { return ( <div className = "ResetPWDMain-box"> <div> <input type="button" value="完成更改" /> </div> </div> ); } } /** * 模块入口 * * @class Main * @extends {Component} */ class Main extends Component { constructor(props) { super(props); } render() { return ( <div> <ResetPWDHead /> <ResetPWDBottom /> </div> ); } } Main.contextTypes = { router: React.PropTypes.object.isRequired } //export default connect((state) => { return { User: state.User } }, action('ResetPWD'))(Main); //连接redux export default GetData({ id: 'MyMessages', //应用关联使用的redux component: Main, //接收数据的组件入口 url: '/api/v1/messages', //服务器请求的地址 stop: (props, state) => { return !Boolean(props.User); //true 拦截请求,false不拦截请求 }, data: (props, state) => { //发送给服务器的数据 return { accesstoken: props.User.accesstoken } }, success: (state) => { return state; }, //请求成功后执行的方法 error: (state) => { return state } //请求失败后执行的方法 });
'use strict'; // javascript 严格说明 module.exports = { /** * 模块内容定义 * @public */ "define": { "id": "app-error-request-handler", /** 模块名称 */ "name": "应用程序异常处理", /** 模块版本 */ "version": "1.0" }, /** * 处理应用程序进程异常 * @param {object} app 应用程序实例 * @return {void} */ "run": (app) => { //error hanlder app.use(function (err, req, res, next) { console.log("error:" + err.stack || err.message); res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; res.status(err.status || 500); res.render('error'); }); } }
import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux' import App from './App'; import StoreGlobal from './reducers/driver' ReactDOM.render( <Provider store={StoreGlobal}> <App /> </Provider> , document.getElementById('root') ); // store.dispatch({ // type:'add', // payload:1300 // }) // store.dispatch({ // type:'minus', // payload:199 // }) // store.dispatch({ // type:'add', // payload:5500 // }) // store.dispatch({ // type:'chgName', // payload:'bank 2019' // }) // store.dispatch({ // type:'chgAge', // payload:25.5 // })
const initialState = { user_id: 0, first_name: "", last_name: "", email: "", profile_pic: "", }; const UPDATE_USER = "UPDATE_USER"; const LOGOUT_USER = "LOGOUT_USER"; export function updateUser(userObj) { return { type: UPDATE_USER, payload: userObj, }; } export function logoutUser() { return { type: LOGOUT_USER, payload: {}, }; } export default function userReducer(state = initialState, action) { const { type, payload } = action; switch (type) { case UPDATE_USER: const { user_id, first_name, last_name, email, profile_pic } = payload; return { ...state, user_id, first_name, last_name, email, profile_pic }; case LOGOUT_USER: return state; default: return state; } }