text stringlengths 7 3.69M |
|---|
spacesApp.controller(
'login-toggle.controller',
[
'$scope',
function($scope){
$scope.user = {
name : 'Timothy'
}
}
]
); |
"use strict";
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.bulkInsert(
"admins",
[
{
id: "ff233600-fc24-11e8-997c-93e49f55c445",
username: "vuph",
password: "123",
createdAt: new Date(),
updatedAt: new Date()
},
{
id: "1d38a080-fc25-11e8-997c-93e49f55c44",
username: "henry",
password: "123",
createdAt: new Date(),
updatedAt: new Date()
}
],
{}
);
},
down: (queryInterface, Sequelize) => {
return queryInterface.bulkDelete("admins", null, {});
}
};
|
import React, { Component } from 'react';
import './NewQuestion.css';
import MovieQuiz1 from'./MovieQuiz1';
import MovieQuiz2 from'./MovieQuiz2';
import SportQuiz1 from'./SportQuiz1';
import SportQuiz2 from'./SportQuiz2';
class Quiz extends Component {
constructor() {
super();
this.state = {
sport: false,
movie: false,
quiz1: false,
quiz2: false,
}
this.handleMSubmit = this.handleMSubmit.bind(this);
this.handleSSubmit = this.handleSSubmit.bind(this);
this.handle1Submit = this.handle1Submit.bind(this);
this.handle2Submit = this.handle2Submit.bind(this);
}
handleMSubmit (event) {
event.preventDefault();
this.setState({movie: true});
}
handleSSubmit (event) {
event.preventDefault();
this.setState({sport: true});
}
handle1Submit (event) {
event.preventDefault();
this.setState({quiz1: true});
}
handle2Submit (event) {
event.preventDefault();
this.setState({quiz2: true});
}
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Quiz</h1>
</header>
{!this.state.sport && !this.state.movie && localStorage.getItem('User') && <div>
<br/><br/>
<div className="formContainer">
<form onSubmit={this.handleMSubmit}>
<button type="submit" className="btn btn-default">Movie</button>
</form>
<form onSubmit={this.handleSSubmit}>
<button type="submit" className="btn btn-default">Sport</button>
</form>
</div>
</div>
}
{(this.state.sport || this.state.movie) && !this.state.quiz1 && !this.state.quiz2 && <div>
<br/><br/>
<div className="formContainer">
<form onSubmit={this.handle1Submit}>
<button type="submit" className="btn btn-default">1</button>
</form>
<form onSubmit={this.handle2Submit}>
<button type="submit" className="btn btn-default">2</button>
</form>
</div>
</div>
}
{this.state.movie && this.state.quiz1 &&
<MovieQuiz1 />
}
{this.state.movie && this.state.quiz2 &&
<MovieQuiz2 />
}
{this.state.sport && this.state.quiz1 &&
<SportQuiz1 />
}
{this.state.sport && this.state.quiz2 &&
<SportQuiz2 />
}
</div>
);
}
}
export default Quiz;
|
import React from 'react';
class MainWrapper extends React.Component {
render() {
return (
<article className="main-wrapper">
{this.props.children}
</article>
);
}
}
export default MainWrapper; |
var Mongoose = require('../config/database').Mongoose,
db = require('../config/database').db,
Schema = Mongoose.Schema,
autoIncrement = require('mongoose-auto-increment');
autoIncrement.initialize(db);
/**
* @module tenant
* @description tenant class contains the details of tenant
*/
var tenantSchema = new Schema({
/** tenant id is indexed */
tenantId : { type: Schema.Types.ObjectId, index: true },
/** name must be string and required field */
name : { type: String, required: true, trim: true },
/** status must be string and required field */
status : { type: String, required: true, trim: true},
/** description must be string */
description : { type: String, trim: true },
/** valid from must be string and required field */
validFrom : { type: String, required: true, trim: true },
/** valid to must be string and required field */
validTo : { type: String, required: true, trim: true }
});
tenantSchema.plugin(autoIncrement.plugin,{ model: 'tenant', field: 'tenantId' });
var tenant = Mongoose.model('tenant', tenantSchema);
module.exports = {
Tenant: tenant
};
|
// creating http module
var http = require('http');
// creating http request listener
var handleRequest = function(req, res){
console.log("Hello Alvina!");
};
// creating server module
var server = http.createServer(handleRequest);
// listen to localhost with port 3031
server.listen(3031, 'localhost');
|
global.moment = require('moment');
"use strict";
global.config;
var setConfig = require('./config').read(configLoaded);
function configLoaded(cfg) {
global.config = cfg;
try {
var watering = require('./watering');
} catch(e) {
console.log(e.stack);
}
watering.checkOutputs();
} |
function createSquareArray (board) {
var array = []
for (var i=0; i<board.length; i++){
array.push(board[i].children)
}
return(array)
}
module.exports = createSquareArray; |
import styled from "styled-components";
export const Container = styled.div`
display: flex;
flex-direction: column;
grid-area: ContentForm;
margin-top: 30%;
> label {
margin: 20px 0px;
font-size: 14px;
color: var(--gray-font-color);
font-weight: bold;
}
`;
export const InputText = styled.input`
background: var(--white);
border-radius: 10px;
padding-left: 20px;
margin-bottom: 15px;
color: var(--outline);
max-width: 467px;
width: 100%;
height: auto;
font-size: 14px;
line-height: 28px;
height: 39px;
box-sizing: border-box;
box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25);
border: 1px solid rgba(104, 104, 104, 0.2);
:hover,
:focus {
outline: none;
border: 1px solid rgba(104, 104, 104, 0.2);
box-shadow: 0px 4px 4px var(--hover-light-shadow);
}
`;
export const ButtonSingIn = styled.button`
background-color: var(--verde-skytef);
cursor:pointer;
border-radius: 10px;
box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25);
text-align: center;
max-width: 467px;
height: 39px;
width: 100%;
padding-top: 8px;
font-weight: bold;
color: white;
:hover{
opacity:0.7
}
`;
export const ForgetPwd = styled.div`
cursor:pointer;
margin-top: 20px;
font-size:14px;
color: var(--azul-skytef);
`; |
$(function(){
/* globals $, Vue, networkManager */
var loc = window.location;
var params = new URLSearchParams(loc.search)
var app = new Vue({
el: '#app',
data: function(){
return {
movies: [],
ordering: '-publication_date',
createMode: false,
username: params.get('search')
}
},
mounted: function(){
var ordering = (window.location.hash || '').replace('#', '') || this.ordering;
this.sortMovies(ordering);
},
methods: {
// utilities
getMovieIndex: function(id){
for (var i=0; i<this.movies.length; i++){
if (this.movies[i].id === id ){
return i;
}
}
},
updateUrl : function(query_key, query_value){
params.set(query_key, query_value);
var urlPath = loc.origin + loc.pathname + '?' + params.toString();
window.history.pushState('', document.title, urlPath);
},
// event callbacks
sortMovies: function(ordering){
var cmp = this;
networkManager
.getUserMovies(cmp.username, ordering)
.then(function(response){
cmp.movies = response['results'];
cmp.ordering = ordering;
// change url based on ordering
cmp.updateUrl('ordering', ordering );
});
},
setOpinion: function(movieId, opinion){
var cmp = this;
networkManager
.setOpinion(movieId, opinion)
.then(function(response){
var index = cmp.getMovieIndex(movieId);
cmp.movies.splice(index, 1, response)
});
},
getUserMovies: function(username){
var cmp = this;
networkManager
.getUserMovies(username)
.then(function(response){
cmp.movies = response['results'];
cmp.username = username;
cmp.updateUrl('search', username );
});
},
createMovie: function(movie){
var cmp = this;
networkManager
.createMovie(movie)
.then(function(response){
cmp.sortMovies(cmp.ordering);
cmp.$refs.createForm.resetData();
});
},
showCreateMovieForm : function(){
this.createMode = !this.createMode;
}
}
});
}); |
import React from 'react';
import { Link } from 'react-router-dom';
import * as ROUTES from '../../constants/routes';
//import '../../css/style.css';
const Navigation = () => (
<div className="App">
<nav>
<ul>
<li>
<Link to={ROUTES.SELECTUSER}>SelectUser</Link>
</li>
<li>
<Link to={ROUTES.LANDING}>Landing</Link>
</li>
<li>
<Link to={ROUTES.ORDER}>Order</Link>
</li>
<li>
<Link to={ROUTES.MENU}>Menu</Link>
</li>
<li>
<Link to={ROUTES.KITCHEN}>Kitchen</Link>
</li>
<li>
<Link to={ROUTES.ADMIN}>Admin</Link>
</li>
<li>
<Link to={ROUTES.DELIVER}>Deliver</Link>
</li>
</ul>
</nav>
</div>
);
export default Navigation;
|
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Toolbar from '@material-ui/core/Toolbar';
import AppBar from '@material-ui/core/AppBar';
import Divider from '@material-ui/core/Divider';
import Tabs from '@material-ui/core/Tabs';
import IconButton from '@material-ui/core/IconButton';
import List from '@material-ui/core/List';
import Drawer from '@material-ui/core/Drawer';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import Tab from '@material-ui/core/Tab';
import { CssBaseline, Typography, Box, Avatar } from '@material-ui/core';
import {AddBox, Equalizer, PieChart, Menu} from '@material-ui/icons';
const useStyles = makeStyles((theme) => ({
root: {
backgroundColor: "#20c8b8",
margin: '0',
color: 'black'
},
tab: {
margin: '10px 0',
textDecoration: 'none',
display: 'flex',
alignItems: 'center',
boxSizing:' border-box',
},
box: {
width: '250px',
height: '100%',
zIndex: '1'
},
avatar: {
width: theme.spacing(8),
height: theme.spacing(8),
margin: '0.5rem auto'
}
}));
const menuItems = [
{
icon: <AddBox/>,
text: 'Add Expense'
},
{
icon: <Equalizer/>,
text: 'Statistics'
},
{
icon: <PieChart/>,
text: 'Graphs'
},]
const Layout = (props) => {
const classes = useStyles();
const [value, setValue] = React.useState(0);
const [open, setOpen] = React.useState(false);
const openToggle = () =>{
setOpen(true)
}
const closeToggle = () =>{
setOpen(false)
}
const handleChange = (event, newValue) => {
setValue(newValue);
};
const slider = (
<Box className= {classes.box} onClick = {closeToggle}>
<Avatar className = {classes.avatar}>
t
</Avatar>
<Divider/>
<List>
{ menuItems.map((item, key)=>(
<ListItem button key = {key}>
<ListItemIcon>{item.icon}</ListItemIcon>
<ListItemText primary = {item.text}/>
</ListItem>
))}
</List>
</Box>
)
return (
<div >
<CssBaseline/>
<AppBar position="static" className={classes.root}>
<Toolbar>
<IconButton>
<Menu onClick = {openToggle}/>
</IconButton>
<Typography variant = 'h5'>
Expensify
</Typography>
</Toolbar>
{/* <Tabs className = {classes.tab}
value={value}
onChange={handleChange}>
<Tab label="Item One" />
<Tab label="Item Two" />
<Tab label="Item Three" />
</Tabs> */}
</AppBar>
<Drawer open = {open} onClick = {closeToggle}>
{slider}
</Drawer>
<main>
{props.children}
</main>
</div>
);
}
export default Layout; |
(function () {
'use strict';
// 1. Create a module called myApp.core which exposes a version constant 'VERSION'
// 2. Create a module called myApp.app which depends on myApp.core
// 3. Create a run function on this module, which injects '$rootScope' and 'VERSION'
// 4. Expose version on $rootScope and display it on the page
// 5. Expose todays date on $rootScope and display it on the page
// 6. Expose a function isBeforeNoon on $rootScope. Use ng-if in html to conditionally
// display some information if it is before noon.
// 7. Run the tests along the way (karma start in this folder)
// 8. Write additional tests as necessary
})(); |
import React, { Component } from "react";
import { subscribeToNewsletter } from "../../apiCalls/newsletter/newsletterListActions";
import { SUBSCRIBETONEWSLETTER_SUCCESS_MESSAGE } from "../../constants";
import Newsletter from "../../components/newsletter/Newsletter";
class NewsletterContainer extends Component {
constructor(props) {
super(props);
this.state = {
err: null,
success_message: ""
};
this.handleSubscribeToNewsletter = this.handleSubscribeToNewsletter.bind(
this
);
}
async handleSubscribeToNewsletter(email) {
if (this.state.err !== null || this.state.success_message !== "") {
this.setState({
success_message: "",
err: null
});
}
try {
await subscribeToNewsletter(email);
return this.setState({
err: null,
success_message: SUBSCRIBETONEWSLETTER_SUCCESS_MESSAGE
});
} catch (err) {
return this.setState({
success_msg: "",
err
});
}
}
render() {
let { err, success_message } = this.state;
return (
<Newsletter
err={err}
success_message={success_message}
handleSubscribeToNewsletter={this.handleSubscribeToNewsletter}
/>
);
}
}
export default NewsletterContainer;
|
"use strict";
exports.__esModule = true;
var interface_1 = require("./base/interface");
interface_1["default"].run();
|
const Sequelize = require('sequelize');
// Prod
const sequelize = new Sequelize(
'5IU45193DS',
'5IU45193DS',
'ZbDgPUdcA0',
{
dialect: 'mysql',
host: 'remotemysql.com'
,logging: false
});
// LOCAL
// const sequelize = new Sequelize(
// 'datamoviz',
// 'root',
// 'EXua8ups1',
// {
// dialect: 'mysql',
// host: 'localhost'
// ,logging: false
// });
module.exports = sequelize;
|
import Vue from 'vue'
import Vuex from 'vuex'
// Store Modules
import sidebar from './modules/sidebar'
import users from './modules/users'
Vue.use(Vuex)
export const store = new Vuex.Store({
modules: {
sidebar: sidebar,
users: users
}
}) |
let dtile = document.querySelector(".about-step-card-1")
let atile = document.querySelector(".about-step-card-2")
let wtile = document.querySelector(".about-step-card-3")
let ctile = document.querySelector(".about-step-card-4")
let stepnum1 = document.querySelector(".about-step-number-1")
let stepnum2 = document.querySelector(".about-step-number-2")
let stepnum3 = document.querySelector(".about-step-number-3")
let stepnum4 = document.querySelector(".about-step-number-4")
let content1 = document.querySelector(".about-pc-content-1")
let content2 = document.querySelector(".about-pc-content-2")
let content3 = document.querySelector(".about-pc-content-3")
let content4 = document.querySelector(".about-pc-content-4")
var width = window.innerWidth
var height = window.innerHeight
window.addEventListener('resize', () => {
if (typeof (window.innerWidth) == 'number') {
width = window.innerWidth;
height = window.innerHeight;
} else {
if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
width = document.documentElement.clientWidth;
height = document.documentElement.clientHeight;
} else {
if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
width = document.body.clientWidth;
height = document.body.clientHeight;
}
}
}
})
const toA = () => {
window.scrollTo(0, (height * 2 + 10))
}
const toW = () => {
window.scrollTo(0, (height * 3 + 10))
}
const toC = () => {
window.scrollTo(0, (height * 4 + 10))
}
const toTop = () => {
window.scrollTo(0, height)
}
const toggleD = () => {
dtile.style.cssText = `
grid-column: 1 / 5;
grid-row: 1 / 5;
padding: 30px;
`
atile.style.cssText = `
grid-column: 5 / 6;
grid-row: 1 / 5;
display: flex;
align-items: center;
justify-content: center;
`
wtile.style.cssText = `
grid-column: 5 / 6;
grid-row: 5 / 6;
display: flex;
align-items: center;
justify-content: center;
`
ctile.style.cssText = `
grid-column: 1 / 5;
grid-row: 5 / 6;
display: flex;
align-items: center;
justify-content: center;
`
stepnum1.style.opacity = 1
stepnum2.style.opacity = 0.3
stepnum3.style.opacity = 0.3
stepnum4.style.opacity = 0.3
content1.style.display = "block"
content2.style.display = "none"
content3.style.display = "none"
content4.style.display = "none"
}
const toggleA = () => {
dtile.style.cssText = `
grid-column: 1 / 2;
grid-row: 1 / 5;
display: flex;
align-items: center;
justify-content: center;
`
atile.style.cssText = `
grid-column: 2 / 6;
grid-row: 1 / 5;
padding: 30px;
`
wtile.style.cssText = `
grid-column: 2 / 6;
grid-row: 5 / 6;
display: flex;
align-items: center;
justify-content: center;
`
ctile.style.cssText = `
grid-column: 1 / 2;
grid-row: 5 / 6;
display: flex;
align-items: center;
justify-content: center;
`
stepnum1.style.opacity = 0.3
stepnum2.style.opacity = 1
stepnum3.style.opacity = 0.3
stepnum4.style.opacity = 0.3
content1.style.display = "none"
content2.style.display = "block"
content3.style.display = "none"
content4.style.display = "none"
}
const toggleW = () => {
dtile.style.cssText = `
grid-column: 1 / 2;
grid-row: 1 / 2;
display: flex;
align-items: center;
justify-content: center;
`
atile.style.cssText = `
grid-column: 2 / 6;
grid-row: 1 / 2;
display: flex;
align-items: center;
justify-content: center;
`
wtile.style.cssText = `
grid-column: 2 / 6;
grid-row: 2 / 6;
padding: 30px;
`
ctile.style.cssText = `
grid-column: 1 / 2;
grid-row: 2 / 6;
display: flex;
align-items: center;
justify-content: center;
`
stepnum1.style.opacity = 0.3
stepnum2.style.opacity = 0.3
stepnum3.style.opacity = 1
stepnum4.style.opacity = 0.3
content1.style.display = "none"
content2.style.display = "none"
content3.style.display = "block"
content4.style.display = "none"
}
const toggleC = () => {
dtile.style.cssText = `
grid-column: 1 / 5;
grid-row: 1 / 2;
display: flex;
align-items: center;
justify-content: center;
`
atile.style.cssText = `
grid-column: 5 / 6;
grid-row: 1 / 2;
display: flex;
align-items: center;
justify-content: center;
`
wtile.style.cssText = `
grid-column: 5 / 6;
grid-row: 2 / 6;
display: flex;
align-items: center;
justify-content: center;
`
ctile.style.cssText = `
grid-column: 1 / 5;
grid-row: 2 / 6;
padding: 30px;
`
stepnum1.style.opacity = 0.3
stepnum2.style.opacity = 0.3
stepnum3.style.opacity = 0.3
stepnum4.style.opacity = 1
content1.style.display = "none"
content2.style.display = "none"
content3.style.display = "none"
content4.style.display = "block"
}
if (width < 900) {
window.addEventListener("scroll", (event) => {
let scroll = this.scrollY;
let mobile1 = document.querySelector(".about-mobile-1")
let mobile2 = document.querySelector(".about-mobile-2")
let mobile3 = document.querySelector(".about-mobile-3")
let mobile4 = document.querySelector(".about-mobile-4")
let arrow1 = document.querySelector("#arrow1")
let arrow2 = document.querySelector("#arrow2")
let arrow3 = document.querySelector("#arrow3")
let arrow4 = document.querySelector("#arrow4")
if (scroll <= height * 2) {
mobile1.style.cssText = `
opacity: 1;
z-index: 99;
`
mobile2.style.cssText = `
opacity: 0;
pointer-events: none;
`
mobile3.style.cssText = `
opacity: 0;
pointer-events: none;
`
mobile4.style.cssText = `
opacity: 0;
pointer-events: none;
`
stepnum1.style.opacity = 1
stepnum2.style.opacity = 0.3
stepnum3.style.opacity = 0.3
stepnum4.style.opacity = 0.3
arrow1.style.display = "block"
arrow2.style.display = "none"
arrow3.style.display = "none"
arrow4.style.display = "none"
} else if ((scroll > height * 2) && (scroll <= height * 3)) {
mobile1.style.cssText = `
opacity: 0;
pointer-events: none;
`
mobile2.style.cssText = `
opacity: 1;
z-index: 99;
`
mobile3.style.cssText = `
opacity: 0;
pointer-events: none;
`
mobile4.style.cssText = `
opacity: 0;
pointer-events: none;
`
stepnum1.style.opacity = 0.3
stepnum2.style.opacity = 1
stepnum3.style.opacity = 0.3
stepnum4.style.opacity = 0.3
arrow1.style.display = "none"
arrow2.style.display = "block"
arrow3.style.display = "none"
arrow4.style.display = "none"
} else if ((scroll > height * 3) && (scroll <= height * 4)) {
mobile1.style.cssText = `
opacity: 0;
pointer-events: none;
`
mobile2.style.cssText = `
opacity: 0;
pointer-events: none;
`
mobile3.style.cssText = `
opacity: 1;
z-index: 99;
`
mobile4.style.cssText = `
opacity: 0;
pointer-events: none;
`
stepnum1.style.opacity = 0.3
stepnum2.style.opacity = 0.3
stepnum3.style.opacity = 1
stepnum4.style.opacity = 0.3
arrow1.style.display = "none"
arrow2.style.display = "none"
arrow3.style.display = "block"
arrow4.style.display = "none"
} else if (scroll > height * 4) {
mobile1.style.cssText = `
opacity: 0;
pointer-events: none;
`
mobile2.style.cssText = `
opacity: 0;
pointer-events: none;
`
mobile3.style.cssText = `
opacity: 0;
pointer-events: none;
`
mobile4.style.cssText = `
opacity: 1;
z-index: 99;
`
stepnum1.style.opacity = 0.3
stepnum2.style.opacity = 0.3
stepnum3.style.opacity = 0.3
stepnum4.style.opacity = 1
arrow1.style.display = "none"
arrow2.style.display = "none"
arrow3.style.display = "none"
arrow4.style.display = "block"
}
})
} else {
content1.style.display = "block"
window.addEventListener("scroll", (event) => {
let scroll = this.scrollY
if (scroll <= height * 2) {
toggleD()
} else if ((scroll > height * 2) && (scroll <= height * 3)) {
toggleA()
} else if ((scroll > height * 3) && (scroll <= height * 4)) {
toggleW()
} else if (scroll > height * 4) {
toggleC()
}
})
} |
$("a.nav-btn").on("click", function(e) {
if (this.hash !== "") {
e.preventDefault();
const hash = this.hash;
$("html, body").animate(
{
scrollTop: $(hash).offset().top
},
800
);
}
});
$(".button").on("click", function(e) {
if (this.hash !== "") {
e.preventDefault();
const hash = this.hash;
$("html, body").animate(
{
scrollTop: $(hash).offset().top
},
800
);
}
});
$("a.nav-link-sm").on("click", function(e) {
if (this.hash !== "") {
e.preventDefault();
const hash = this.hash;
$("html, body").animate(
{
scrollTop: $(hash).offset().top
},
800
);
}
});
|
var inMemoApp = angular.module('InMemoApp', ['ngRoute']);
inMemoApp.config([
'$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push(['$q', 'loadingService', function ($q, loadingService) {
return {
'request': function (config) {
loadingService.setError(false);
loadingService.increase();
return config;
},
'response': function (response) {
loadingService.decrease();
return response;
},
'responseError': function (rejection) {
loadingService.setError(true);
loadingService.decrease();
return $q.reject(rejection);
}
}
}]);
}
]);
inMemoApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '/app/views/home.cshtml',
controller: 'homeController'
})
.when('/login', {
templateUrl: '/app/views/login.cshtml',
controller: 'loginController',
caseInsensitiveMatch: true
})
.when('/user', {
templateUrl: '/app/views/user.cshtml',
controller: 'userController',
caseInsensitiveMatch: true
})
.when('/decks/list', {
templateUrl: '/app/views/decks/list.cshtml',
controller: 'listDecksController',
caseInsensitiveMatch: true
})
.when('/decks/add', {
templateUrl: '/app/views/decks/add.cshtml',
controller: 'addDeckController',
caseInsensitiveMatch: true
})
.when('/decks/edit/:deckId?', {
templateUrl: '/app/views/decks/edit.cshtml',
controller: 'editDeckController',
caseInsensitiveMatch: true
})
.when('/cards/list', {
templateUrl: '/app/views/cards/list.cshtml',
controller: 'listCardsController',
caseInsensitiveMatch: true
})
.when('/cards/add', {
templateUrl: '/app/views/cards/add.cshtml',
controller: 'addCardController',
caseInsensitiveMatch: true
})
.when('/cards/edit/:cardId?', {
templateUrl: '/app/views/cards/edit.cshtml',
controller: 'editCardController',
caseInsensitiveMatch: true
})
.when('/train', {
templateUrl: '/app/views/cards/train.cshtml',
controller: 'trainController',
caseInsensitiveMatch: true
})
.when('/emails/list', {
templateUrl: '/app/views/emails/list.cshtml',
controller: 'listEmailsController',
caseInsensitiveMatch: true
});
}]); |
module.exports=function(app){
// const socket=new WebSocket("ws://localhost:8000");
// socket.addEventListener('onopen',function(event){
// socket.send('hello Server!');
// });
// socket.addEventListener('onmessage',function(event){
// console.log('message form server',event.data);
// })
} |
define([],function(){
rdk.$ngModule.controller("sign_out",['$scope','Utils',function(scope,Utils){
scope.message="此场景为用户登出";
this.controller="sign_out controller";
this.sayHello=function(){
return 'hello world';
}
}]);
}); |
import gulp from 'gulp';
module.exports = (options) => {
gulp.task('server', () => {
$.nodemon({
script: 'server/server.js',
ext: 'js yml',
watch: ['server/**/*.js', 'config']
});
});
};
|
const mongoose = require('mongoose');
const CategoryModel = mongoose.model('gameCategory');
const errors = require('errors/index');
const validationError = errors.ValidationError;
const UserModel = mongoose.model('user');
module.exports = {
createCategory,
getCategories,
deleteCategories,
enableDisableCategories,
editGameCategory,
getCategoriesById
};
async function createCategory(req, res, next) {
try {
// if (!await UserModel.isAdmin(req.user._id) || !await UserModel.isSubAdmin(req.user._id) ) {
// throw new validationError("can created by subadmin")
// }
res.data = CategoryModel.createCategory(req.body, req.user._id);
next();
} catch (ex) {
errors.handleException(ex, next);
}
}
async function getCategories(req, res, next) {
try {
let query = {};
if (req.query.status !== 'null') {
query.status = req.query.status;
}
res.data = await CategoryModel.find(query).exec();
next();
} catch (ex) {
errors.handleException(ex, next);
}
}
async function deleteCategories(req, res, next) {
try {
if (!req.params.id) {
throw new validationError("enter valid id");
}
res.data = await CategoryModel.remove({ _id: req.params.id }).exec();
next();
} catch (ex) {
errors.handleException(ex, next);
}
}
async function enableDisableCategories(req, res, next) {
try {
if (!req.params.id) {
throw new validationError("enter valid id");
}
let categoryData = await CategoryModel.findOne({ _id: req.params.id }).exec();
categoryData.status = req.body.enable ? "Active" : "Inactive";
categoryData.enable = req.body.enable;
res.data = await categoryData.save();
next();
} catch (ex) {
errors.handleException(ex, next);
}
}
async function editGameCategory(req, res, next) {
try {
if (!req.params.id) {
throw new validationError("Send valid Id");
}
let gameCategoryData = await CategoryModel.findOne({ _id: req.params.id }).exec();
gameCategoryData.description = req.body.description;
if (req.body.icon) {
gameCategoryData.icon = req.body.icon;
}
res.data = await gameCategoryData.save();
next();
} catch (ex) {
errors.handleException(ex, next);
}
}
async function getCategoriesById(req, res, next) {
try {
if (!req.params.id) {
throw new validationError("Send Valid Id")
}
res.data = await CategoryModel.findOne({ _id: req.params.id }).exec();
next();
} catch (ex) {
errors.handleException(ex, next);
}
} |
/*
CLRS Exercise 16.2-2, p. 427
*/
class Knapsack01 {
constructor(v = [], w = [], W = 0) {
this.v = {};
v.forEach((value, index) => this.v[index + 1] = value);
this.w = {};
w.forEach((weight, index) => this.w[index + 1] = weight);
this.n = v.length;
this.W = W;
}
knapsack01 = (n = this.n, W = this.W) => {
let K = [];
for (let i = 0; i <= this.n; i++) {
K.push(new Array(this.W + 1))
}
for (let j = 0; j <= this.W; j++) {
K[0][j] = 0;
}
for (let i = 0; i <= this.n; i++) {
K[i][0] = 0;
}
for (let i = 1; i <= this.n; i++) {
for (let j = 1; j <= this.W; j++) {
if (j < this.w[i]) {
K[i][j] = K[i - 1][j];
} else {
K[i][j] = Math.max(K[i - 1][j], K[i - 1][j - this.w[i]] + this.v[i]);
}
}
}
return K[n][W];
}
}
module.exports = {
Knapsack01
} |
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { connect } from 'react-redux';
import { petUpdate } from '../actions';
import { CardSection, Input } from './common';
class PetForm extends Component {
render() {
return (
<View>
<CardSection>
<Input
label="Name"
placeholder="Cooper"
value={this.props.name}
onChangeText={value => this.props.petUpdate({ prop: 'name', value })}
/>
</CardSection>
</View>
);
}
}
const styles = {
pickerLabelStyle: {
fontSize: 18,
paddingLeft: 20
}
};
const mapStateToProps = (state) => {
const { name } = state.petForm;
return { name };
};
export default connect(mapStateToProps, { petUpdate })(PetForm); |
'use strict';
require('./pictureComponent');
$('body').append('<div>profile script loaded</div>'); |
///print numbers 0 to 9
/*
for loop
the for loop has three parts
i - the counter value the initial value where the loop should start
ii - the condition where the loop should end
ii - an counter update
*/
/*for (let i =0; i < 10; i++){
console.log(i)
}
//i = 0, 0 < 10 true its gonna add 1 the i is gonna be 1 till i > 10
let john = ["john",28,"banker","married"]
for(let i = 0; i < john.length; i++){
console.log(john[i])
}
/* while loop
while loop only has the condition
let i = 0
while(i < john.length){
console.log(john[i])
i++
}
// conitnue skips the value and contiues the loop
let john = ["john",28,"banker","married"]
for(let i = 0; i < john.length; i++){
if(typeof john[i] !== "string") continue // if type of is different from a string if its a string continue if its not a string skip it
console.log(john[i])
}
// break stops the loop
let john = ["john",28,"banker","married"]
for(let i = 0; i < john.length; i++){
if(typeof john[i] !== "string") break // if type of is different from a string if its a string stop the loop
console.log(john[i])
}
*/
// looping backingwords
let john = ["john", 28, "banker", "blue"]
for(let i =john.length -1; i >= 0; i--){
console.log(john[i])
}
// we want our i to start at the last element in the array(john.length - 1)
// how long do we want this array to run(the condition) we want it to run until i hits 0 (i >=0)
//we have to decrease the counter start at 5 and move to zero
|
//1. Cree un programa que lea los tres ángulos internos de un triángulo y muestre si los ángulos corresponden a un triángulo o no. Realice una versión con condicionales y otra con estructura switch-case.
let a=parseFloat(prompt("ingrese valor de angulo a"));
let b=parseFloat(prompt("ingrese valor de angulo b"));
let c=parseFloat(prompt("ingrese valor de angulo c"));
function ComprobarAngulos(a,b,c) {
if(a+b+c==180){
let mensaje="este es un triangulo, la suma de sus angulos da como resultado 180 grados";
return mensaje;
}
if(a+b+c!=180){
let mensaje="este no es un triangulo, la suma de sus angulos no da como resultado 180 grados";
return mensaje;
}
}
let angulos_internos=ComprobarAngulos(a,b,c);
console.log(angulos_internos);
/* Programe un procedimiento que no reciba parámetros, sume los números
enteros 12 y 23, e imprima el resultado de la suma de estos dos números.
Haga las respectivas versiones para pseudocódigo y código.
function suma() {
let suma_sin_parametros=12+23;
return suma_sin_parametros;
}
let valor=suma();
console.log("funcion:",valor);
*/ |
import React, { Component } from 'react';
import {
TabBarIOS,
Image,
Text,
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome'
import { layout, colors } from './styles'
import { HomeStack, NotificationStack, SettingStack, PostStack, PluginStack } from './Nav'
import { createBottomTabNavigator, TabBarBottom } from 'react-navigation'
export default createBottomTabNavigator(
{
Console: HomeStack,
Post: PostStack,
Plugin: PluginStack,
Notification: NotificationStack,
Setting: SettingStack,
},
{
navigationOptions: ({ navigation }) => ({
tabBarIcon: ({ focused, tintColor }) => {
const { routeName } = navigation.state;
let iconName = 'home' //,tintColor = focused? colors.blue: colors.lightGray
switch(routeName){
case 'Console':
iconName = 'home'
break
case 'Post':
iconName = 'clone'
break
case 'Setting':
iconName = 'cogs'
break
case 'Plugin':
iconName = 'plug'
break
case 'Notification':
iconName = 'envelope'
break
}
return (<Icon name={ iconName } size={ 24 } color={ tintColor } />)
},
}),
tabBarOptions: {
activeTintColor: colors.blue,
inactiveTintColor: colors.textGray,
},
tabBarPosition: 'bottom',
animationEnabled: false,
swipeEnabled: false,
}
) |
function importScript(url) {
const script = document.createElement('script');
script.src = url;
return loader(script);
}
function loader(element) {
return new Promise((resolve, reject) => {
element.addEventListener('load', () => {
resolve();
});
element.addEventListener('error', e => {
reject(e);
});
document.head.appendChild(element);
});
}
document.body.innerHTML = `
<a href="https://web-sandbox.js.org/examples/single-spa/index.html">link</a>
<button id="import-script">importScript()</button>
`;
document.getElementById('import-script').addEventListener('click', () => {
importScript('/examples/sandbox-attr/sub.js');
});
|
window._3rd_party_test_step1_loaded = function() {
// At this point, a third-party domain has now attempted to set a cookie (if all went to plan!)
var step2Url = 'https://lti.cs.vt.edu/2',
resultsEl = document.getElementById('3rd_party_cookie_test_results'),
step2El = document.createElement('script');
// Update loading / results message
resultsEl.innerHTML = 'Stage one complete, loading stage 2…';
// And load the second part of the test (reading the cookie)
step2El.setAttribute('src', step2Url);
resultsEl.appendChild(step2El);
}
window._3rd_party_test_step2_loaded = function(cookieSuccess) {
var resultsEl = document.getElementById('3rd_party_cookie_test_results'),
errorEl = document.getElementById('3rd_party_cookie_test_error'),
instructionEl = document.getElementById('instructions'),
enabledMsg = 'Good news! We have detected that you have third-party cookies enabled for OpenDSA-LTI.',
disabledMsg = 'We have detected that you have third-party cookies disabled.';
// Show message
resultsEl.innerHTML = (cookieSuccess ? enabledMsg : disabledMsg);
// Done, so remove loading class
resultsEl.className = resultsEl.className.replace(/\bloading\b/, (cookieSuccess ? 'enabled' : 'disabled'));
instructionEl.className = (cookieSuccess ? 'hidden' : 'shown');
// And remove error message
errorEl.className = 'hidden';
} |
import Header from "./Header";
const localStyle = {
margin: 20,
padding: 20,
};
const bodyStyle = {
width: 1000,
marginLeft: "auto",
marginRight: "auto",
marginTop: 50,
fontFamily: '"Open Sans", "Microsoft YaHei", "微软雅黑", STXihei,"华文细黑", sans-serif'
};
const MyLayout = (props) => (
<div style={localStyle}>
<Header/>
<div style={bodyStyle}>
{props.children}
</div>
</div>
);
export default MyLayout;
|
const UserRepository = require("./model");
const encriptor = require("../helpers");
const mailSender = require("../mail/sender");
const login = async ({ username, password }) => {
return new Promise(async (resolve, reject) => {
try {
const userDocument = await UserRepository.findOne({
"login": username,
"password": encriptor.Crypto(password, username),
});
if (userDocument != null) {
return resolve({
"userId": userDocument.id,
"userName": userDocument.name
});
}
return resolve(null);
} catch (error) {
console.error(error);
reject(error);
}
});
}
const create = async ({ username, password, mail }) => {
return new Promise(async (resolve, reject) => {
try {
const user = await UserRepository.findOne({ "login": mail });
if (user != null) {
return reject({ "code": "USER_ERROR_ALREADY_EXISTS" });
}
const createdUser = await UserRepository.create({
login: mail,
name: username,
password: encriptor.Crypto(password, mail)
});
return resolve(createdUser);
} catch (error) {
console.error(error);
reject(error);
}
});
}
const recovery = async (email) => {
return new Promise(async (resolve, reject) => {
try {
const user = await UserRepository.findOne({ "login": email });
if (user == null) {
return reject({ "code": "USER_DO_NOT_EXISTS" });
}
const recoveryCode = Math.floor(Math.random() * 10000000000) + 1;;
const recoveredUser = await UserRepository.updateOne(
{ login: email },
{ $set: { recoveryCode: recoveryCode } }
);
if (recoveredUser.ok) {
mailSender.recovery(email, recoveryCode)
.then(response => {
console.log(response);
return resolve(recoveredUser)
})
.catch(error => {
console.log(error);
return reject(error);
})
return resolve(recoveredUser);
}
return reject();
} catch (error) {
console.error(error);
reject(error);
}
});
}
const isValidRecovery = async (mail, code) => {
try {
const user = await UserRepository.findOne({ "login": mail, "recoveryCode": code });
if (user == null) {
return false;
}
return true;
} catch (error) {
console.error(error);
return error;
}
}
const resetPassword = async (mail, code, newPassword) => {
return new Promise(async (resolve, reject) => {
try {
const isValid = await isValidRecovery(mail, code)
if (!isValid) {
return reject(new Error("Invalid recovery code"));
}
const response = await UserRepository.updateOne(
{ login: mail, recoveryCode: code },
{ $set: { password: encriptor.Crypto(newPassword, mail), recoveryCode: null } }
);
if(!response.ok) {
console.log(response);
return reject(new Error("Error reseting password"));
}
resolve();
} catch (error) {
console.error(error);
reject(error);
}
});
}
const userService = {
login,
create,
recovery,
isValidRecovery,
resetPassword
};
module.exports = userService; |
import React from 'react';
import styles from './FilterRadio.less';
export default (props) => {
const { data, onClick, selected } = props;
const isSelected = (value)=>{
if(selected.find(i=>i.childVal === value)){
return true;
}
return false;
}
return (
<div>
<div className={styles.label}>{data.label}</div>
<div className={styles.itemWrap}>
{
data && data.children.map(i => (
<div
className={isSelected(i.value) ? styles.itemSelected : styles.item}
onClick={() => onClick(i.value)}
>{i.label}</div>
))
}
</div>
</div>
)
}
|
function newItem() {
let n = (lib.math.rndi(17) + 1) * 100
let variation = lib.math.rndi(60)/10 - 3
let price = 5 + variation
let total = Math.round(price * n)
let item = new lab.shell.Cmd(
'selling ' + n + ' chips\n $' + price
+ ' for each, $' + total + ' total', function() {
if (env.state.money < total) {
lab.shell.print("you don't have enough money!")
} else {
lab.shell.println('buying ' + n + ' rom chips for $' + total)
env.state.rom += n
env.state.money -= total
lab.shell.println('you have ' + env.state.rom + ' chips now')
lab.shell.print('you balance: ' + env.state.money)
this.parent.detach(this)
}
})
lab.shell.market.put(item)
}
function sale(item) {
if (item.stock === 0) return
// determine number
let n = lib.math.rndi(20)
if (n > item.stock) n = item.stock
// determine price
let pv = 4 - lib.math.rnd(80)/10
let price = 7 + pv
let total = Math.round(n * price)
item.stock -= n
env.state.money += total
env.state.saleStat += total
}
let REPORT_NUM = 1
function stat() {
let stock = env.state.catalog.reduce((a, v) => a + v.stock, 0)
lab.shell.messages.put(new lab.shell.Msg(
'sonado inc.',
'sales report #' + REPORT_NUM++,
'sales: $' + env.state.saleStat
+ '\nstock: ' + stock + ' roms'
))
env.state.saleStat = 0
}
module.exports = function() {
// simulate market
if (lab.shell.cur !== lab.shell.market) {
// regenerate only when player is out of market
// to avoid selection mismatch
lab.shell.market.clean()
let n = lib.math.rndi(4) + 1
for (let i = 0; i < n; i++) newItem()
}
// simulate sales
env.state.catalog.forEach(e => sale(e))
if (env.state.day % 10 === 0 && env.state.saleStat > 0) stat()
}
|
import React from "react";
import { Modal, Button, Form } from "react-bootstrap";
const UserModal = (props) => {
const {
handleChange,
showDetails,
hideDetails,
selectedUser,
updateUser,
edited
} = props;
return (
<Modal show={showDetails}>
<Modal.Header>
<Modal.Title id="contained-modal-title-vcenter">
{edited ? "Input Room" : "Edit User"}
</Modal.Title>
</Modal.Header>
<form method="post" onSubmit={(event) => updateUser(event)}>
<Modal.Body>
<div className="form-group">
<label htmlFor="username">Username</label>
<input
name="username"
type="text"
onChange={(event) => {
handleChange(event, "username");
}}
value={selectedUser["username"]}
required
/>
</div>
<div className="form-group">
<label htmlFor="firstName">Firstname</label>
<input
name="firstName"
type="text"
onChange={(event) => {
handleChange(event, "firstName");
}}
value={selectedUser["firstName"]}
required
/>
</div>
<div className="form-group">
<label htmlFor="lastName">Lastname</label>
<input
name="lastName"
type="text"
onChange={(event) => {
handleChange(event, "lastName");
}}
value={selectedUser["lastName"]}
required
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
name="password"
type="password"
onChange={(event) => {
handleChange(event, "password");
}}
value={selectedUser["password"]}
required
/>
</div>
</Modal.Body>
<Modal.Footer>
<Button
className="float-right"
variant="primary"
type="submit"
>
UPDATE
</Button>
<Button
onClick={() => {
hideDetails();
}}
>
Cancel
</Button>
</Modal.Footer>
</form>
</Modal>
);
};
export default UserModal;
|
import React, { Component } from "react";
import fetch from "isomorphic-fetch";
import logo from "./logo.svg";
import "./App.css";
const API = 'http://localhost:3001/api/';
const DEALS_QUERY = 'deals/';
const STATS_QUERY = 'stats/';
class App extends Component {
constructor(props) {
super(props);
this.state = {
deals: [],
stats: [],
date: "",
}
}
componentDidMount() {
fetch(API + DEALS_QUERY)
.then(response => response.json())
.then(response => {
this.setState({ deals: response });
});
fetch(API + DEALS_QUERY + STATS_QUERY)
.then(response => response.json())
.then(response => {
this.setState({ stats: response });
});
}
// Method to set new state of date when selected from drop-down menu
handleDateChange = (event) => {
this.setState({ date: event.target.value });
}
// Method to render all deals sorted by date or specific deals by date of creation
renderDeals = () => {
let dealRows;
if (this.state.date.length === 0) {
if (this.state.deals.length !== 0) {
dealRows = this.state.deals.map((item, index) => {
return (
<tr key={index}>
<td>{item.title}</td>
<td>{item.amountRequired}</td>
<td>{item.createdAt}</td>
</tr>
);
});
}
} else {
if (this.state.deals.length !== 0) {
dealRows = this.state.deals.map((item, index) => {
let isDate = item.createdAt.search(this.state.date);
if (isDate !== -1) {
return (
<tr key={index}>
<td>{item.title}</td>
<td>{item.amountRequired}</td>
<td>{item.createdAt}</td>
</tr>
);
}
});
}
}
return dealRows;
}
// Method to render statistics of the deal
renderStats = () => {
if (this.state.stats.length !== 0) {
return (
<div>
<p>
<b>Deals count</b>: {this.state.stats[0].deals_count}
<span className="text-warning"> || </span>
<b>Total amount</b>: £{this.state.stats[0].total_amounts}
<span className="text-warning"> || </span>
<b>Average amount</b>: £{(this.state.stats[0].avg_amount).toFixed(2)}
</p>
</div>
);
}
}
// Method for the dropdown menu
renderForm = () => {
let dates = [];
const uniqueDateList = this.state.deals.map((date, i) => {
let slicedDate = new Date(date.createdAt).toISOString().slice(0, 10);
if (dates.indexOf(slicedDate) === -1) {
dates.push(slicedDate);
return (
<option value={slicedDate} key={i}>{slicedDate}</option>
);
}
return 1;
})
if (this.state.deals.length !== 0) {
return (
<div className="form-group">
<select className="form-control" name="date" onChange={this.handleDateChange}>
<option value=''>All deals</option>
{uniqueDateList}
</select>
</div>
);
}
}
render() {
return (
<div className="App container">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
</header>
<p></p>
<div className="row text-center stat-info">
<div className="col-12">
<h5><p className="text-danger">Statistics</p></h5>
{this.renderStats()}
</div>
</div>
<div className="row text-center">
<div className="col-6">
<h3 className="text-info"><p>Deals</p></h3>
</div>
<div className="col-5 offset-1">
{this.renderForm()}
</div>
</div>
<div className="row">
<div className="col-12">
<main>
<table className="table table-hover text-left">
<thead className="table-info">
<tr>
<th scope="col">Title</th>
<th scope="col">Amount required</th>
<th scope="col">Created date</th>
</tr>
</thead>
<tbody>
{this.renderDeals()}
</tbody>
</table>
</main>
</div>
</div>
</div>
);
}
}
export default App; |
import React, { Component, Fragment } from 'react';
import { NavLink } from 'reactstrap';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { logout } from '../../actions/authActions';
import PropTypes from 'prop-types';
class Logout extends Component {
static propTypes = {
logout: PropTypes.func.isRequired
};
render() {
return (
<Fragment>
<NavLink
onClick={this.props.logout}
style={navLinkStyle}
tag={Link}
to='/login'
>
Logout
</NavLink>
</Fragment>
);
}
}
const navLinkStyle = {
fontWeight: 'bold'
};
export default connect(
null,
{ logout }
)(Logout);
|
/**
* Created by Rodion on 20.06.2016.
*/
app.factory("TableService", ['$http', function($http) {
return {
update: function() {
var words = [];
words = $http.get("");
}
};
}]); |
// import ReactDOM from 'react-dom';
// import React from 'react';
const DUMMY_DATA = [
{
senderId: "perbrogen",
text: "hello mate"
},
{
senderId: "whatevs",
text: "who'll win?"
}
]
const instanceLocator = "v1:us1:8c67c0fa-8074-4af7-b53f-7926775744bb"
const testToken = "https://us1.pusherplatform.io/services/chatkit_token_provider/v1/8c67c0fa-8074-4af7-b53f-7926775744bb/token"
const username = "Thomas"
const roomId = 18764145
class App extends React.Component{
//mnethod to create states
constructor(){
super()
this.state={
messages: DUMMY_DATA
}
this.sendMessage = this.sendMessage.bind(this);
}
//this is the method to connect react components with api's
componentDidMount(){
const chatManager = new Chatkit.ChatManager({
instanceLocator: instanceLocator,
userId: username,
tokenProvider: new Chatkit.TokenProvider({
url: testToken
})
});
chatManager.connect().then(currentUser => {
this.currentUser = currentUser
this.currentUser.subscribeToRoom({
roomId: roomId,
hooks: {
onNewMessage: message => {
this.setState({
// spread syntax used in react so that messages is copied then message is added to it
messages: [...this.state.messages, message]
});
}
}
})
}).catch(error => {
console.error("error: ", error);
});
}
sendMessage(text){
this.currentUser.sendMessage({
text,
roomId: roomId
})
}
//method to send data to the html file
render(){
return(
<div className="app">
<Title />
<MessageList messages={this.state.messages}/>
<SendMessageForm sendMessage={this.sendMessage}/>
</div>
)
}
}
class MessageList extends React.Component{
render(){
return (
<ul className="messages-list">
{this.props.messages.map(message => {
return (
<li className="msg" key={message.id}>
<div className="m-author">{message.senderId}</div>
<div className="m-text">{message.text}</div>
</li>
)
})}
</ul>
)
}
}
function Title(){
return <p id="header">The Ting Chat</p>;
}
class SendMessageForm extends React.Component{
constructor(props){
super(props)
this.state = {
message: ""
}
//the this keyword is by default undefined inside the body of a function.
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit(e){
e.preventDefault();
this.props.sendMessage(this.state.message)
this.setState({
message: ""
})
}
handleChange(e){
this.setState({
message:e.target.value
})
}
render(){
return (
<form onSubmit={this.handleSubmit} className="message-form">
<input
id="typedmsg"
onChange={this.handleChange}
value={this.state.message}
placeholder="Enter a message Ting"
type="text" />
</form>
)
}
}
ReactDOM.render(<App />, document.getElementById('root')); |
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';
Meteor.startup(() => {
Meteor.methods({
addForm: function(formData, orderNumber, formId) {
//body...
//update form serial order evetytime
Iform.find({ parent_id : formId}).forEach(function(doc){
if(parseInt(doc.ordernumber)>= parseInt(orderNumber)){
Iform.update(doc._id, {
$set: { ordernumber: parseInt(doc.ordernumber)+1 },
});
}
});
//add new form in collection
var formsID = Iform.insert(formData);
return formsID;
},
addFormFiled: function(formData) {
// body...
var formsID = IformField.insert(formData);
return formsID;
},
addPage: function(formsData) {
var pageID = cms.insert(formsData);
//console.log('hello');
return pageID;
},
addPlan: function(formsData) {
var planID = plan.insert(formsData);
//console.log('hello');
return planID;
},
addPopup: function(formsData) {
var poupID = popup.insert(formsData);
//console.log('hello');
return poupID;
},
updatePopup:function(id,title,description,parentForm,ChildForm,popup_status)
{
popup.update(id,{
$set: {
popup_title: title,
description: description,
parentForm: parentForm,
ChildForm: ChildForm,
popup_status: popup_status
},
});
},
addWidget: function(formsData) {
var pageID = cmsWidget.insert(formsData);
//console.log('hello');
return pageID;
},
deleteParentForm: function(formId){
var test = Iform.find({parent_id : formId}).forEach(function(doc){
Iform.find({parent_id : doc._id}).forEach(function(docC){
Iform.find({parent_id : docC._id}).forEach(function(docA){
Iform.remove(docA._id);
});
Iform.remove(docC._id);
});
Iform.remove(doc._id);
});
Iform.remove(formId);
return;
},
updateForm: function(formTitle, ordernumber, description, formId){
//update form serial order evetytime
Iform.find({ parent_id : formId}).forEach(function(doc){
if(parseInt(doc.ordernumber)>= parseInt(ordernumber)){
Iform.update(doc._id, {
$set: { ordernumber: parseInt(doc.ordernumber)+1 },
});
}
});
//update form serial order into collection
Iform.update(formId, {
$set: { form_title: formTitle,ordernumber: parseInt(ordernumber),description: description },
});
return;
},
deleteChildForm: function(formId){
Iform.find({parent_id : formId}).forEach(function(doc){
Iform.remove(doc._id);
});
Iform.remove(formId);
return;
},
updateChildForm: function(cond_heading, formTitle, ordernumber, formnumber,formId){
var forms = Iform.findOne({_id: formId});
forms = Iform.find({ parent_id : forms.parent_id}).forEach(function(doc){
if(parseInt(doc.ordernumber)>= parseInt(ordernumber)){
Iform.update(doc._id, {
$set: { ordernumber: parseInt(doc.ordernumber)+1 },
});
}
});
forms = Iform.update(formId, {
$set: {
cond_heading: cond_heading,
child_form_title: formTitle,
ordernumber: parseInt(ordernumber),
child_form_type: parseInt(formnumber)
},
});
},
deleteAttr: function(formId){
Iform.remove(formId);
},
// event.target.form_attr_title.value, event.target.ordernumber.value, event.target.input_type.value, event.target.is_required.value, event.target.help_text.value, options, event.target.type.value,event.target.parent_field.value,event.target.applicable_on.value,id
updateFormAttr: function(formTitle, ordernumber, inputType, required,RCselectedValues,helpText, options, type,parent, applicable,formId){
var forms = Iform.findOne({_id: formId});
parentForm = Iform.findOne({_id: forms.parent_id})
Iform.find({ parent_id : forms.parent_id}).forEach(function(doc){
if(parseInt(doc.ordernumber)>= parseInt(ordernumber)){
Iform.update(doc._id, {
$set: { ordernumber: parseInt(doc.ordernumber)+1 },
});
}
});
var is_required = '';
if(parentForm.child_form_type == 2){
Iform.update(formId, {
$set: {
form_attr_title: formTitle,
ordernumber: parseInt(ordernumber),
input_type: inputType,
is_required: 'no',
is_rc:RCselectedValues,
help_text: helpText,
options:options,
type:'main-attr',
parent_field: '',
applicable_on: ''
},
});
}else{
Iform.update(formId, {
$set: {
form_attr_title: formTitle,
ordernumber: parseInt(ordernumber),
input_type: inputType,
is_required: required,
is_rc: RCselectedValues,
help_text: helpText,
options: options,
type: type,
parent_field: parent,
applicable_on: applicable
},
});
}
},
updateFormChild: function(cond_heading, child_form_field,ordernumber,input_type,RCselectedValues, formId){
var forms = Iform.findOne({_id: formId});
Iform.find({ parent_id : forms.parent_id}).forEach(function(doc){
if(parseInt(doc.ordernumber)>= ordernumber){
// console.log(event.target.ordernumber.value);
Iform.update(doc._id, {
$set: { ordernumber: parseInt(doc.ordernumber)+1 },
});
}
});
//change collection name here
Iform.update(formId, {
$set: {
cond_heading: cond_heading,
child_form_field: child_form_field,
ordernumber: ordernumber,
field_type: input_type,
is_rc: RCselectedValues
},
});
return;
},
deleteFormChild:function(id){
Iform.find({_id : id}).forEach(function(doc){
Iform.remove(doc._id);
});
Iform.find({parent_id: id}).forEach(function(doc){
Iform.remove(doc._id);
});
Iform.remove(id);
return;
},
addWelcomePage: function(title, content) {
// body...
ParentForm.insert({
title: title,
content: content,
type: 'welcome'
})
},
updateWelcomePage: function(title, content, id) {
// body...
ParentForm.update(id,{
$set: {
title: title,
content: content
}
});
},
addinfoTitlePageId: function(title) {
// body...
ParentForm.insert({
title: title,
type: 'infoTitle'
})
},
updateinfoTitlePageId: function(title, id) {
// body...
ParentForm.update(id,{
$set: {
title: title
}
});
},
addpowerPageTitleId: function(title) {
// body...
var data = ParentForm.insert({
title: title,
type: 'power'
})
console.log(data);
},
updatepowerPageTitleId: function(title, id) {
// body...
ParentForm.update(id,{
$set: {
title: title
}
});
},
deleteUser: function(formId)
{
Meteor.users.remove({_id:formId})
},
getSubscriberList: function() {
var data = SubscriptionDetail.find().fetch();
return{
status: 1,
error: null,
data : data
}
},
deleteSubscriber: function(formId)
{
SubscriptionDetail.remove({_id:formId});
return;
},
checkSubscriberAsUser: function ( subscribe_emali ) {
var userData = Meteor.users.findOne({"username":subscribe_emali});
//console.log('hiiiiiiiiiiiiii');
//console.log(userData);
if(userData)
{
return{
status: 1,
error: null,
data : true
}
}
else
{
return{
status: 0,
error: null,
data : false
}
}
},
getplanList: function() {
var data = plan.find().fetch();
return{
status: 1,
error: null,
data : data
}
},
deletePlan: function(planId)
{
plan.remove({_id:planId});
return;
},
getplan: function( plan_id ) {
var data = plan.findOne({_id: plan_id});
return{
status: 1,
error: null,
data : data
}
},
updatePlan: function(plan_title,plan_code,plan_rc, id) {
// body...
plan.update(id,{
$set: {
plan_title: plan_title,
plan_code: plan_code,
plan_rc: plan_rc
}
});
},
userUpdate: function (id, doc) {
// Update account
Meteor.users.update(id, {
$set: {
username: doc.username,
profile: doc.profile
}
});
// Update password
if (doc.password != '') {
Accounts.setPassword(id, doc.password);
}
return true;
},
});
}); |
const Quote = require('./../models/Quote')
module.exports = {
Query: {
quote: async (parent, { _id }, context, info) => {
return await Quote.findOne({ _id }).exec()
},
quotes: async (parent, { query, options }, context, info) => {
console.log('Querying: ', query, options)
let q = parseQuery(query)
return Quote.paginate(q, options)
.then(result => {
let docs = result.docs.map(quote => ({
_id: quote._id.toString(),
body: quote.body,
author: quote.author,
source: quote.source,
tags: quote.tags,
votes: quote.votes
}))
return {
docs,
total: result.totalDocs,
limit: result.limit,
offset: result.offset
}
})
},
randomQuote: async (parent, { query }, context, info) => {
let q = parseQuery(query)
// count how many records are in the collection
let count = await Quote.countDocuments(q).exec()
// make a random integer between 0 and count -1
let random = Math.floor(Math.random() * count)
// console.log('query: ', q, 'count: ', count, 'random: ', random)
// Query the quote collection again, but only fetch one record offset by our random intger
return await Quote.findOne(q).skip(random).exec()
},
},
Mutation: {
createQuote: async (parent, { quote }, context, info) => {
const newQuote = await new Quote({
body: quote.body,
author: quote.author,
source: quote.source,
tags: quote.tags
})
return new Promise((resolve, reject) => {
newQuote.save((err, res) => {
err ? reject(err) : resolve(res)
})
})
},
updateQuote: async (parent, { _id, quote }, context, info) => {
return new Promise((resolve, reject) => {
Quote.findByIdAndUpdate(_id, { $set: { ...quote } }, { new: true }).exec(
(err, res) => {
err ? reject(err) : resolve(res)
}
)
})
},
deleteQuote: (parent, { _id }, context, info) => {
return new Promise((resolve, reject) => {
Quote.findByIdAndDelete(_id).exec((err, res) => {
err ? reject(err) : resolve(res)
})
})
}
},
Subscription: {
quote: {
subscribe: (parent, args, { pubsub }) => {
//return pubsub.asyncIterator(channel)
}
}
}
}
function parseQuery(query) {
let q = {}
if (query.author) {
q.author = new RegExp(query.author, 'i')
}
if (query.source) {
q.source = new RegExp(query.source, 'i')
}
if (query.tags) {
q.tags = new RegExp(query.tags, 'i')
}
return q
} |
var mongoose = require('mongoose');
var Product = require('../models/Product.js');
module.exports = {
updateProduct: function(req, res) {
if(!req.params.id){
return res.status(400).send('id query needed');
}
Product.findOneAndUpdate({_id: req.params.id}, req.body, function(err, productItem) {
if (err) {
res.status(500).send(err);
} else {
res.status(200).json(productItem);
}
});
},
addNewProduct: function(req, res) {
console.log(req.body);
new Product(req.body).save(function(err, productItem) {
if (err) {
console.log(err);
return res.status(500).json(err);
} else {
return res.json(productItem);
}
});
},
destroyProduct: function(req, res) {
console.log("hitting delete", req.params.id);
if (!req.params.id) {
return res.status(400).send('id query needed');
}
Product.findByIdAndRemove({_id: req.params.id}, function(err, productItem) {
if (err) {
res.status(500).send(err);
} else {
res.send(productItem);
}
});
},
getOneProduct : function(req, res) {
console.log("hitting get one", req.params.id);
Product.findOne({_id: req.params.id}, function(err, productItem) {
if (err) {
res.status(500).json(err);
} else {
res.status(200).json(productItem);
}
});
},
getProducts: function(req, res) {
Product.find().then(function(response) {
res.send(response);
});
}
};
|
const fs = require('fs')
const __log = (...args) => console.debug(...args)
const categories = {
major: 0,
minor: 1,
patch: 2,
}
const [, , category] = process.argv
// Validate the passed category
const categoryValues = Object.keys(categories)
if (!categoryValues.includes(category)) {
const categoryOptions = categoryValues.map(c => `"${c}"`).join(', ')
throw new Error(
`Category required.\nUseage: node bump.js [category].\nPossible values: ${categoryOptions}`
)
}
// Returns the new version number, zeroing out other values if necessary
// Receives "1.1.1" and would return "1.2.0" if type were `minor`
function getNewVersion(version = '0.0.0', type) {
const parsed = version.split('.').map(Number)
const index = categories[type]
parsed[index]++
// decrement the other version categories
let i = index + 1
while (i <= 2) {
parsed[i] = 0
++i
}
return parsed.join('.')
}
const pkg = require('../package.json')
__log(`Current package version: ${pkg.version}`)
const newVersion = getNewVersion(pkg.version, category)
__log(`Bumping to ${newVersion}`)
const newPkg = { ...pkg, version: newVersion }
fs.writeFile('package.json', JSON.stringify(newPkg, null, 2), (err, res) => {
if (err) {
return __log('Failed to write to package.json')
}
__log('Written to package.json')
})
|
const express = require('express')
const router = express.Router()
const User = require('./controller/UserController')
router.get('/users/:handle/:mode?', async (req, res, next) => {
return res.json(await User.getUserInfo(req.params.handle, req.params.mode))
})
module.exports = router
|
describe('App Tests', function() {
var controller, rootScope, location, route, $log, httpBackend;
beforeEach(function () {
module('app');
inject(function (_$log_, $controller, $rootScope, $location, $route, $httpBackend) {
$log = _$log_;
controller = $controller;
rootScope = $rootScope;
location = $location;
route = $route;
httpBackend = $httpBackend;
});
});
describe('routing', function() {
it('should route to home', function() {
var url = 'static/components/home/templates/home.html';
httpBackend.when('GET', url)
.respond(200, {});
location.path('/');
rootScope.$digest();
expect(route.current.templateUrl)
.toBe(url);
});
it('should route to blog', function() {
var url = 'static/components/blog/templates/blog.html';
httpBackend.when('GET', url)
.respond(200, {});
location.path('/blog');
rootScope.$digest();
expect(route.current.templateUrl)
.toBe(url);
});
it('should route to hobbies', function() {
var url = 'static/components/hobbies/templates/hobbies.html';
httpBackend.when('GET', url)
.respond(200, {});
location.path('/hobbies');
rootScope.$digest();
expect(route.current.templateUrl)
.toBe(url);
});
it('should route to work', function() {
var url = 'static/components/work/templates/work.html';
httpBackend.when('GET', url)
.respond(200, {});
location.path('/work');
rootScope.$digest();
expect(route.current.templateUrl)
.toBe(url);
});
});
});
|
import { connect } from 'react-redux';
import EditDialog from '../../../components/EditDialog3';
import helper, { postOption, fetchJson, showError, showSuccessMsg, deepCopy } from '../../../common/common';
import { Action } from '../../../action-reducer/action';
import { getPathValue } from '../../../action-reducer/helper';
import { afterEditActionCreator } from './OrderPageContainer';
const URL_SAVE = '/api/config/suppliersArchives/';
const URL_SALEMEN = '/api/config/suppliersArchives/buyers';
const URL_CURRENCY = '/api/config/suppliersArchives/currency';
const URL_DISTRICT = '/api/config/suppliersArchives/district_options';
const URL_INSTITUTION = `/api/config/customersArchives/corporations`;
const STATE_PATH = ['config', 'suppliersArchives', 'edit'];
const action = new Action(STATE_PATH);
const getSelfState = (rootState) => {
return getPathValue(rootState, STATE_PATH);
};
//更改controls下合作信息中税率的type
const changeItemType = (controls, type) => {
const newData = controls[1].data.map(item => {
if (item.key === 'tax') item.type = type;
return item;
});
controls[1].data = newData;
return controls;
};
const changeActionCreator = (keyName, keyValue) => async (dispatch, getState) => {
const {value, controls} = getSelfState(getState());
if (keyName === 'tax') {
const options = controls[1].data.find(item => item.key === 'tax').options;
keyValue = options.find(item => item.value === keyValue).title;
}else if (keyName === 'taxType') {
let newControls;
if (keyValue === 'tax_rate_way_not_calculate') {
newControls = changeItemType(controls, 'readonly');
dispatch(action.assign({controls: newControls}));
dispatch(action.assign({tax: 0}, 'value'));
} else {
newControls = changeItemType(controls, 'select');
dispatch(action.assign({controls: newControls}));
}
}
if(keyValue === value[keyName]) return dispatch(action.assign({[keyName]: keyValue}, 'value'));
let data, options, body;
const dealDistrictFunc = async (district, payload) => {
options = undefined;
if(keyValue && keyValue.value && keyValue.value !== '') {
body = {maxNumber: 300, parentDistrictGuid:keyValue.value};
data = await fetchJson(URL_DISTRICT, postOption(body));
if (data.returnCode !== 0) return showError(data.returnMsg);
options = data.result;
}
const cols = deepCopy(controls);
helper.setOptions(district, cols[0].data, options);
dispatch(action.assign({controls: cols}));
dispatch(action.assign(payload, 'value'));
};
switch (keyName) {
case 'country': {
const payload = {[keyName]: keyValue, province:undefined, city:undefined, district:undefined, street:undefined};
return await dealDistrictFunc('province', payload);
}
case 'province': {
const payload = {[keyName]: keyValue, city:undefined, district:undefined, street:undefined};
return await dealDistrictFunc('city', payload);
}
case 'city': {
const payload = {[keyName]: keyValue, district:undefined, street:undefined};
return await dealDistrictFunc('district', payload);
}
case 'district': {
const payload = {[keyName]: keyValue, street:undefined};
return await dealDistrictFunc('street', payload);
}
default:
dispatch(action.assign({[keyName]: keyValue}, 'value'));
}
};
const searchActionCreator = (key, value) => async (dispatch, getState) => {
const {controls} = getSelfState(getState());
let data, options, formIndex=1;
switch (key) {
case 'purchasePersonId': {
const option = helper.postOption({maxNumber: 20, filter: value});
data = await fetchJson(URL_SALEMEN, option);
options = data.result.data;
break;
}
case 'balanceCurrency': {
const option = helper.postOption({maxNumber: 20, filter: value});
data = await fetchJson(URL_CURRENCY, option);
options = data.result;
break;
}
case 'institutionId': {
const option = helper.postOption({maxNumber: 20, filter: value});
data = await fetchJson(URL_INSTITUTION, option);
options = data.result;
formIndex = 0;
break;
}
default: return;
}
if(data.returnCode !== 0) return showError(data.returnMsg);
const cols = deepCopy(controls);
helper.setOptions(key, cols[formIndex].data, options);
dispatch(action.assign({controls: cols}));
};
const exitValidActionCreator = () => action.assign({valid: false})
const okActionCreator = () => async (dispatch, getState) => {
const {edit, value, controls} = getSelfState(getState());
const item = controls.find(item => !helper.validValue(item.data, value));
if (item) {
return dispatch(action.assign({valid: item.key}));
};
const url = `${URL_SAVE}${edit ? 'edit' : 'add'}`;const arr = ['true_false_type_false', 'true_false_type_true'];
if (typeof value.isContract !== 'number') {
const isCon = arr.findIndex(o => o === value.isContract);
value.isContract = isCon < 0 ? null : isCon;
}
const {returnCode, returnMsg, result} = await fetchJson(url, postOption(helper.convert(value)));
if (returnCode !== 0) return showError(returnMsg);
showSuccessMsg(returnMsg);
afterEditActionCreator(true, dispatch, getState);
};
const cancelActionCreator = () => (dispatch, getState) => {
afterEditActionCreator(false, dispatch, getState)
};
const mapStateToProps = (state) => {
return getSelfState(state);
};
const actionCreators = {
onChange: changeActionCreator,
onSearch: searchActionCreator,
onExitValid: exitValidActionCreator,
onOk: okActionCreator,
onCancel: cancelActionCreator
};
const EditDialogContainer = connect(mapStateToProps, actionCreators)(EditDialog);
export default EditDialogContainer;
|
import React from 'react';
import s from './Dialogs.module.css';
import DialogsItem from './DialogsItem/DialogsItem';
import Message from './Message/Message';
const Dialogs = (props) => {
let dialogsElements = props.state.dialogs.map(d => <DialogsItem name={d.name} id={d.id} />);
let messageElements = props.state.messages.map(m => <Message message={m.message} />);
return (
<div className={s.apper}>
<div className={s.dialog}>
<DialogsItem />
{dialogsElements}
</div>
<div className={s.message}>
<Message />
{messageElements}
</div>
</div>
)
}
export default Dialogs; |
import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";
const firebaseConfig = {
apiKey: "AIzaSyANSkWvNgXH8N8Y_ccp17DSNcBiRL0Z6Sk",
authDomain: "rn-instagram-clone-6cade.firebaseapp.com",
projectId: "rn-instagram-clone-6cade",
storageBucket: "rn-instagram-clone-6cade.appspot.com",
messagingSenderId: "18148016880",
appId: "1:18148016880:web:af4234346a0c1d529e7835",
};
!firebase.apps.length ? firebase.initializeApp(firebaseConfig) : firebase.app();
const db = firebase.firestore();
const auth = firebase.auth();
export { auth, db };
|
var async = require('async');
var sendMail = require('../../lib/mailer');
var User = require('../../models/user').User;
exports.get = function(req, res) {
User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {
if (!user) {
req.flash('passwordReset', 'Password reset token is invalid or has expired.');
return res.redirect('/forgot');
}
res.render('auth/reset', {
user: req.user,
message: req.flash('passwordReset')
});
});
}
exports.post = function(req, res) {
async.waterfall([
function(done) {
User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {
if (!user) {
req.flash('error', 'Password reset token is invalid or has expired.');
return res.redirect('back');
}
user.password = user.generateHash(req.body.password);
user.resetPasswordToken = undefined;
user.resetPasswordExpires = undefined;
user.save(function(err) {
req.logIn(user, function(err) {
done(err, user);
});
});
});
},
function(user, done) {
sendMail({
from: 'hello@eventrr.com',
to: user.email,
subject: 'Your password has been changed',
reply_to: 'hello@eventrr.com',
text: 'Hello,\n\n' +
'This is a confirmation that the password for your account ' + user.email + ' has just been changed.\n'
}, function (err) {
req.flash('passwordReset', 'Success! Your password has been changed.');
done(err, 'done');
});
res.redirect('/login');
}
], function(err) {
res.redirect('/');
});
}
|
let numbers=[10,20,30,40,50]
// numbers[1]=2000 // it will replace 20 of array
numbers[numbers.length]=60
numbers[numbers.length]=70
numbers[numbers.length]=80
console.log(numbers)
//With array constructor
let roll=Array(1,2,3,4,5,6,7)
console.log(roll)
|
const express = require("express");
const { request } = require("http");
server = express();
server.use(express.json()); //tell server to pass data as json format
function hello(request, response) {
response.status(200).send("Hello!");
}
//3 paths created below.
router = express.Router();
//router.get("/", hello); URI is this case is /
//creates mapper table which maintains the type of GET request
//api 1
router.get('/', (request, response) => { //telling the server if you are getting a get request then you need to call the function below.
response.status(200).send("Hello"); //sets status to 200 and sends message hello.
});
//api 2
router.get("/greet", (request, response) => { //create another mapping in the router
let name = request.query.name; //it will take one parameter from the request and send that response as a message
//getting the name parameter from request.query.name
response.status(200).send(`Hello! ${name}!`)
})
//api 3 Simple api to give you a sum of X + Y
router.get("/sum", (request, response) => {
let sum = parseInt(request.query.x) + parseInt(request.query.y);
response.status(200).send(`Sum is: ${sum}`);
});
/*router.get("/user/by-uid", (request, response) => {
if (request.query.user_id = 1)
let result = {
"user_id": 1,
"first_name": "Fred",
"last_name" : "Nerk",
"email" : "fred@nerk.com"
"phone" : "8888888",
"plan_id" : 1,
"signup_date": "12-Aug-2021"
}
else result = "not found";
response.status(200).send(result);
});
*/
router.post("/post-example", (request,response)=> {
//we will assume that data is coming in request's body in JSON format.
let name = request.body.name;
let age = request.body.age;
response.status(200).send(`Received Name : ${name} and Age: ${age}`);
})
server.use(router);
server.listen(3000);
//port 3000 is the dev standard for node js
//creating this creates a simple backend server that listens to the request.
|
import React from 'react'
import { useState } from 'react'
import serImg from "../images/server_img.png"
import axios from "axios"
import {getId} from "../index"
import { useDispatch } from 'react-redux'
require('dotenv').config({path: '../../'})
const Register = ({setAuth}) => {
const [entreprise, setentreprise]=useState("")
const [username, setusername]=useState("")
const [password, setpassword]=useState("")
const [rpassword, setRpassword]=useState("")
const [email, setemail]=useState("")
const handleSubmit = (e)=> {
e.preventDefault();
axios({
method: "post",
withCredentials:true,
url: `http://localhost:9000'/api/register`,
data: {
username,
entreprise,
password,
email
}
}).then(data => {
console.log(data)
setAuth(false)
})
}
return (
<div className="server-container">
<div className="server-container-left container">
<img className="server-img" src={serImg} />
</div>
<div className="server-container-right">
<form className="container server-form" onSubmit={handleSubmit}>
<h3 className="server-h3 mb-3 text-primary">INSCRIPTION</h3>
<div className="mb-3">
<label htmlFor="exampleInputEmail1" className="form-label">Nom de votre entreprise</label>
<input type="text" className="form-control" required value={entreprise} onChange={(e)=>setentreprise(e.target.value)} />
</div>
<div className="mb-3">
<label htmlFor="exampleInputEmail1" className="form-label">Votre Nom</label>
<input type="text" className="form-control" required value={username} onChange={(e)=>setusername(e.target.value)} />
</div>
<div className="mb-3">
<label htmlFor="exampleInputEmail1" className="form-label">Email address</label>
<input type="email" className="form-control" required value={email} onChange={(e)=>setemail(e.target.value)} />
</div>
<div className="mb-3">
<label htmlFor="exampleInputEmail1" className="form-label">Password</label>
<input type="password" className="form-control" required value={password} onChange={(e)=>setpassword(e.target.value)}/>
</div>
<div className="mb-3">
<label htmlFor="exampleInputEmail1" className="form-label">Password</label>
<input type="password" className="form-control" required value={rpassword} onChange={(e)=>setRpassword(e.target.value)} />
</div>
<div className="mb-3">
<button className="form-control btn-primary text-light" >S'inscrire</button>
</div>
<div className="mb-3">
<button className="form-control btn-outline-primary " onClick={()=>setAuth(false)} >Se connecter</button>
</div>
</form>
</div>
</div>
)
}
const Login = ({setAuth}) => {
const [username, setusername]=useState("")
const [password, setpassword]=useState("")
const [errorUsername, setErrorUsername]= useState()
const [errorPassword, setErrorPassword]= useState()
const handleSubmit=(e)=>{
e.preventDefault();
axios({
method: 'POST',
url:`http://localhost:9000'/api/login`,
withCredentials:true,
data: {
username, password
}
}).then((data) => {
if(data.data==="username incorrect"){
setErrorUsername("username inconnu")
setErrorPassword("")
}
if(data.data==="password incorrect"){
setErrorUsername("")
setErrorPassword("password incorrect")
}
if(data.data._id)
window.location="/shop"
}).catch((err) => console.log(err))
}
return (
<div className="server-container">
<div className="server-container-left container">
<img className="server-img" src={serImg} />
</div>
<div className="server-container-right">
<form className="container server-form" onSubmit={handleSubmit}>
<h3 className="server-h3 mb-3 text-primary">CONNECTION</h3>
<div className="mb-3">
<label htmlFor="exampleInputEmail1" className="form-label">Votre nom</label>
<input type="text" className="form-control" required value={username} onChange={(e)=>setusername(e.target.value)}/>
<div className="text-danger">{errorUsername}</div>
</div>
<div className="mb-3">
<label htmlFor="exampleInputEmail1" className="form-label">Password</label>
<input type="password" className="form-control" required value={password} onChange={(e)=>setpassword(e.target.value)} />
<div className="text-danger">{errorPassword}</div>
</div>
<div className="mb-3">
<button className="form-control btn-primary text-light" >Se connecter</button>
</div>
<div className="mb-3">
<button className="form-control btn-outline-primary " onClick={()=>setAuth(true)}>S'inscrire</button>
</div>
</form>
</div>
</div>
)
}
export default function AuthServer() {
const [aut, setAuth] = useState(true)
return (
<div>
{aut ?
(<div>
<Register setAuth={setAuth}/>
</div>) :
(
<div>
<Login setAuth={setAuth}/>
</div>
)
}
</div>
)
}
|
// In this simple exercise, you will create a program that will take two lists of integers, a and b. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids a and b. You must find the difference of the cuboids' volumes regardless of which is bigger.
// For example, if the parameters passed are ([2, 2, 3], [5, 4, 1]), the volume of a is 12 and the volume of b is 20. Therefore, the function should return 8.
// Your function will be tested with pre-made examples as well as random ones.
// If you can, try writing it in one line of code.
// function findDifference(a, b) {
// //loading...
// }
//parameters
// 2 array of integers above 0
//returns
// an integer that is the difference of the 2 volumes
//examples
//console.log(findDifference([3, 2, 5], [1, 4, 4])) //14
//console.log(findDifference([9, 7, 2], [5, 2, 2]) //106
//console.log(findDifference([11, 2, 5], [1, 10, 8]) //30
//console.log(findDifference([4, 4, 7], [3, 9, 3]) //31
//console.log(findDifference([15, 20, 25], [10, 30, 25]) //0
//pseudocode
// need to calculate volume and determine difference
// const findDifference = (a, b) => {
// let aVolume =a.reduce((a,b) => a *b, 1);
// let bVolume =b.reduce((a,b) => a *b, 1);
// return Math.abs(aVolume - bVolume)
// }
// console.log(findDifference([9, 7, 2], [5, 2, 2]))
//refactored
const findDifference = (a, b) => Math.abs((a.reduce((a,b) => a * b, 1)) - (b.reduce((a,b) => a * b, 1)));
console.log(findDifference([9, 7, 2], [5, 2, 2])) |
const config = require('../../config/index.js');
const { req } = require('../prototype.js');
module.exports = {
// 获取通用字典
getMetaData() {
const url = `${config.apiUrl}/business-api/api/sys/dict/getCommonDataDicts`;
return req({ url });
},
// 获取用户信息
getInfoByUserId(data) {
const url = `${config.apiUrl}/business-api/api/worker/getWorkerDetails/${data.userId}`;
return req({ url });
},
// 获取申请入场人数
getJoinApplicationCounts(data) {
const url = `${config.apiUrl}/business-api/api/worker/getWorkerApplyNumber`;
return req({ url, data });
},
// 获取申请入场列表
getJoinApplications(data) {
const url = `${config.apiUrl}/business-api/api/project/getProjectApplyList`;
return req({ url, data, method: 'POST' });
},
};
|
var a = getApp();
Page(function (a, t, e) {
return t in a ? Object.defineProperty(a, t, {
value: e,
enumerable: !0,
configurable: !0,
writable: !0
}) : a[t] = e, a;
}({
data: {
orders: {
loaded: 0,
empty: 0,
data: []
}
},
goOrder: function () {
wx.switchTab({
url: '/pages/store/goods',
})
},
historyOrder: function () {
wx.navigateTo({
url: '/pages/order/index',
})
},
checkVip: function () {
wx.navigateTo({
url: '/pages/makeOrder/VipRecord/VipRecord',
})
},
onJsEvent: function (t) {
a.util.jsEvent(t);
},
onLoad: function (a) {
// this.onReachBottom();
},
onFinishMealPay: function () {
wx.showModal({
title: "",
content: "您的支付方式为餐后支付,请到商家收银台付款",
success: function (a) { }
});
},
onReady: function () { },
onShow: function () {
this.onReachBottom();
},
onHide: function () { },
onUnload: function () { },
onPullDownRefresh: function () {
this.onReachBottom();
},
onReachBottom: function () {
var t = this;
if (-1 == t.data.min) return !1;
a.util.request({
url: "wmall/order/indextoday",
data: {
min: t.data.min
},
success: function (a) {
var e = t.data.orders.data.concat(a.data.message.message);
t.data.orders.data = e, e.length || (t.data.orders.empty = 1);
var n = a.data.message.min;
!n && e.length > 0 && (t.data.orders.loaded = 1), n || (n = -1), t.setData({
orders: t.data.orders,
min: n,
config_mall: a.data.message.config_mall,
errander_status: a.data.message.errander_status,
showloading: !1
});
}
});
},
onShareAppMessage: function () { }
}, "onPullDownRefresh", function () {
var a = this;
a.data.min = 0, a.data.orders = {
loaded: 0,
empty: 0,
data: []
}, a.onReachBottom(), wx.stopPullDownRefresh();
})); |
const name = 'John';
const {log} = console;
$('h2').eq(0).html(`Это предложение именно для вас, ${name}!`);
// $('h2').eq(2).click(function() {
// $(this).toggleClass('text-color-primary');
// });
// function handler () {
// console.log('Click');
// }
// $('h2').on('click', handler);
// $('h1').click(() => {
// $('h2').off('click', handler);
// console.log('Off');
// });
$('h1').click(function() {
$(this).fadeOut(1000);
setTimeout(() => {
$(this).fadeToggle(1000);
}, 2000);
});
|
var searchData=
[
['zdepthdecoder',['ZDepthDecoder',['../classmoetsi_1_1ssp_1_1ZDepthDecoder.html#a69f45e16839baaa30da870efbfb48101',1,'moetsi::ssp::ZDepthDecoder']]],
['zdepthencoder',['ZDepthEncoder',['../classmoetsi_1_1ssp_1_1ZDepthEncoder.html#a97902734a32136d68782f4b8c9bf111c',1,'moetsi::ssp::ZDepthEncoder']]]
];
|
var htmlRenderer = (function () {
'use strict';
function render(htmlTemplate, data) {
var source = htmlTemplate;
var template = Handlebars.compile(source);
var html = template(data);
return html;
}
return {
render: render
};
}());
|
module.exports = (sequelize, dataTypes) => {
let alias = "User";
let cols = {
name: { type: dataTypes.STRING(50), allowNull: true },
last_name: { type: dataTypes.STRING(50), allowNull: true },
documento: { type: dataTypes.INTEGER(11), allowNull: true },
tipo_documento_id: { type: dataTypes.INTEGER(11), allowNull: true },
email: { type: dataTypes.STRING(50), allowNull: true },
pass: { type: dataTypes.STRING(250), allowNull: true },
condicion_fiscal_id: { type: dataTypes.INTEGER(11), allowNull: true },
razon_social: { type: dataTypes.STRING(50), allowNull: true },
telefono: { type: dataTypes.INTEGER(11) },
ofertas: dataTypes.INTEGER(11),
tipo_persona_id: { type: dataTypes.INTEGER(11), allowNull: true },
mail_confirmado: { type: dataTypes.INTEGER(11) },
image: { type: dataTypes.STRING },
admin: { type: dataTypes.BOOLEAN },
medio_pago: { type: dataTypes.STRING },
};
let config = {
timestamps: true,
paranoid: true,
tableName: "users",
};
const User = sequelize.define(alias, cols, config);
User.associate = function (models) {
User.belongsTo(models.TipoId, {
as: "identificacion",
foreignKey: "tipo_documento_id",
});
User.belongsTo(models.TipoPersona, {
as: "tipo_persona",
foreignKey: "tipo_persona_id",
});
User.belongsTo(models.CondicionFiscal, {
as: "cond_fiscal",
foreignKey: "condicion_fiscal_id",
});
User.hasMany(models.Domicilio, {
as: "domicilio",
foreignKey: "user_id",
});
User.hasMany(models.Compra, {
as: "compras",
foreignKey: "user_id",
});
User.hasMany(models.Pedido, {
as: "pedidos",
foreignKey: "user_id",
});
};
return User;
};
|
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const commitHash = require('child_process')
.execSync('git rev-parse --short HEAD')
.toString()
.trim();
module.exports = {
entry: ['./src/app.js', './src/styles/styles.scss'],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './dist')
},
module: {
rules: [
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
},
{
test: /\.(png|jpg|gif)$/,
use: ['file-loader']
}
]
},
plugins: [
new webpack.DefinePlugin({
__COMMIT_HASH__: JSON.stringify(commitHash),
}),
new HtmlWebpackPlugin({
template: './src/index.html',
favicon: './src/assets/favicon.ico',
hash: true
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
};
|
// ================================================================================
//
// Copyright: M.Nelson - technische Informatik
// Die Software darf unter den Bedingungen
// der APGL ( Affero Gnu Public Licence ) genutzt werden
//
// weblet: dbadmin/weblet/subwebletselectdetail
// ================================================================================
{
var i;
var str = "";
weblet.loadview();
var attr =
{
hinput : false,
}
weblet.findIO(attr);
weblet.showLabel();
weblet.showids = new Array('htmlcomposetabselectid');
weblet.titleString.add = weblet.txtGetText("#mne_lang#Selektionstabelle hinzufügen");
weblet.titleString.mod = weblet.txtGetText("#mne_lang#Selektionstabelle bearbeiten");
weblet.showValue = function(weblet)
{
var i;
if ( weblet == null ) return;
if ( typeof weblet.act_values.htmlcomposeid != 'undefined' || weblet.act_values.htmlcomposeid != null )
this.defvalues["htmlcomposeid"] = weblet.act_values.htmlcomposeid;
else
this.defvalues['htmlcomposeid'] = 'no weblet';
if ( this.eleIsNotdefined(weblet.act_values) || this.eleIsNotdefined(weblet.act_values[this.showids[0]]) || weblet.act_values[this.showids[0]] == '################' )
{
this.add();
return;
}
MneAjaxWeblet.prototype.showValue.call(this, weblet);
}
weblet.checkmodified = function()
{
return false;
}
} |
(function () {
'use strict';
angular
.module('app.inbox')
.controller('InboxController', InboxController)
InboxController.$inject = ['mailservice', 'logger'];
function InboxController(mailservice, logger) {
/* jshint validthis:true */
var vm = this;
vm.title = 'Inbox';
vm.messages = [];
activate();
function activate() {
return getInboxMail().then(function() {
logger.info('Retrieved Inbox');
});
}
function getInboxMail() {
return mailservice.getInbox().then(function (data) {
vm.messages = data;
return vm.messages;
});
}
}
})(); |
/**
* 封装的判断页面是否需要渲染的组件
*/
import { Component } from 'react'
import { is } from 'immutable'
const shallowEqual = (objA, objB) => {
const keysA = Object.keys(objA)
const keysB = Object.keys(objB)
if (keysA.length !== keysB.length) return false
return !keysA.some(v => (!Object.prototype.hasOwnProperty.call(objB, v) || !is(objA[v], objB[v])))
}
class PureComponent extends Component {
shouldComponentUpdate(nextProps, nextState) {
return (
!shallowEqual(this.props, nextProps) ||
!shallowEqual(this.state, nextState)
)
}
}
export default PureComponent
|
// ==UserScript==
// @id ajax_pixiv_bookmark
// @name AJAX Pixiv Bookmark
// @version 1.0.1
// @namespace http://blog.k2ds.net/
// @author killtw
// @description Using AJAX to add a bookmark in Pixiv
// @match http://www.pixiv.net/member_illust.php?*
// @include http://www.pixiv.net/member_illust.php?*
// ==/UserScript==
// a function that loads jQuery and calls a callback function when jQuery has finished loading
function addJQuery(callback) {
var script = document.createElement("script");
script.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js");
script.addEventListener('load', function() {
var script = document.createElement("script");
script.textContent = "(" + callback.toString() + ")();";
document.body.appendChild(script);
}, false);
document.body.appendChild(script);
}
function main() {
$("div.bookmark-container a._button").live('click', function(e) {
e.preventDefault();
var tt = $('input[name="tt"]').val();
var illust_id = $('div#rpc_i_id').attr('title');
$.ajax({
url: 'bookmark_add.php',
data: {
mode: 'add',
tt: tt,
id: illust_id,
type: 'illust',
form_sid: '',
restrict: '0'
},
dataType: 'html',
type: 'POST',
beforeSend: function() {
$("div.bookmark-container a._button").text('追加中…');
},
success: function() {
$("div.bookmark-container a._button").text('加入成功');
// $('div.bookmark').load('member_illust.php?mode=medium&illust_id='+illust_id+' div.bookmark');
$('div.bookmark-container').fadeOut('fast').html('[ <a href="bookmark_detail.php?illust_id=' + illust_id + '">ブックマーク済み</a> | <a href="bookmark_add.php?type=illust&illust_id=' + illust_id + '">編輯</a> ]').fadeIn('fast');
}
});
return false;
});
}
addJQuery(main);
GM_addStyle(".AutoPager_Related, .ads_area { display:none !important; }"); |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
steal(
'can/control/control.js',
'can/view/ejs',
'sigma/common.js',
'./page_loader.css')
.then(
function(){
can.Control("Mobile_Page_Loader",{
defaults : {
msgText: undefined
}
},{
'init': function( element , options ) {
//modificamos y agregamos el modal jQueryMobile Custom Loader
element.append(can.view('//sigma/mobile_page_loader/loader.ejs',options.msgText))
this.hideLoader()
},
showLoader: function() {
//Muestro el Loader en Modal mientras cargo el contenido de la proxima pag
this.element.find('div.loader-loading-overlay').show()
this.element.find('div.loader-loading').show()
},
hideLoader: function(){
//Oculto el Loader Modal
this.element.find('div.loader-loading').hide()
this.element.find('div.loader-loading-overlay').hide()
}
})
}
); |
export { default } from './navigation'
export { default as Menu } from './menu'
|
const React = require('react');
const Link = require('react-router').Link;
const NearbyVenueItem = React.createClass({
render(){
return (
<div className="comment-item">
<p><Link to={`venues/${this.props.venue.id}`}>{this.props.venue.name}</Link></p>
<div>
<p id="nearby-desc">{this.props.venue.address}<br />
{this.props.venue.description}</p>
</div>
</div>
);
}
});
module.exports = NearbyVenueItem;
|
import { html, define } from 'packmar';
export default define('todo-filters', function Filters ({ filters, selectFilter, currentFilter }) {
return html`
<div class="filters display--flex">
${filters.map(filter => {
const isActive = filter.name === currentFilter.name;
return html`
<button
class=${`filter-button ${isActive ? 'active' : ''}`}
onclick=${() => selectFilter(filter.name)}
>
${filter.name}
</button>
`;
})}
</div>
`;
});
|
var dir_4f165475ca9abacfad6de90fe731e2c4 =
[
[ "codelibrary", "dir_39bd4401e93e8dc493bfe276386eaa4a.html", "dir_39bd4401e93e8dc493bfe276386eaa4a" ]
]; |
/**
* Created by fdr08 on 2016/7/1.
*/
import "../../style/css/awesome.less";
import "../../style/css/base.less";
import "../../style/css/com.less";
import "../../style/css/play.less";
import "../lib/video-js/video-js.less";
import "../../style/css/share.min.less";
import {core, com} from "../common/com";
import "../lib/jquery.screenshot";
import "../lib/video-js/video";
import "../lib/jquery.share.min";
/**
* video配置
*/
window.onload = () => {
$("#video-parent-box").screenshot("#my-video", "", true);
};
/**
* videojs插件初始化
* @type {string}
*/
var player = videojs('#my-video', {
"language": "zh",
"autoplay": false,
"controls": true,
"preload": "auto",
"bigPlayButton": false,
// "textTrackDisplay": false,
"controlBar": {
"remainingTimeDisplay": false,
"VolumeControl": {
"VolumeBar": {
"VolumeLevel": '3',
"VolumeHandle": "100%"
}
}
}
}, function () {
this.addClass('vjs-has-started');
this.on("ended", function () {
$(".end").css({display: "block"});
});
/**
* 全屏调整canvas画布大小
*/
// $(".vjs-fullscreen-control").on("click", function () {
// var v = $("#my-video"), canvas = document.getElementById("shot-canvas");
// if(!isFull) {
// var w = v.width(), h = v.height();
// canvas.width = w;
// canvas.height = h;
// isFull = true;
// }else {
// canvas.width = 720;
// canvas.height = 400;
// isFull = false;
// }
// });
});
videojs.addLanguage("zh", {
"Play": "播放",
"Pause": "暂停",
"Current Time": "当前时间",
"Duration Time": "时长",
"Remaining Time": "剩余时间",
"Stream Type": "媒体流类型",
"LIVE": "直播",
"Loaded": "加载完毕",
"Progress": "进度",
"Fullscreen": "全屏",
"Non-Fullscreen": "退出全屏",
"Mute": "静音",
"Unmuted": "取消静音",
"Playback Rate": "播放码率",
"Subtitles": "字幕",
"subtitles off": "字幕关闭",
"Captions": "内嵌字幕",
"captions off": "内嵌字幕关闭",
"Chapters": "节目段落",
"You aborted the video playback": "视频播放被终止",
"A network error caused the video download to fail part-way.": "网络错误导致视频下载中途失败。",
"The video could not be loaded, either because the server or network failed or because the format is not supported.": "视频因格式不支持或者服务器/网络的问题无法加载。",
"The video playback was aborted due to a corruption problem or because the video used features your browser did not support.": "由于视频文件损坏或该视频使用了你的浏览器不支持的功能,播放终止。",
"No compatible source was found for this video.": "无法找到此视频兼容的源。",
"The video is encrypted and we do not have the keys to decrypt it.": "视频已加密,无法解密。"
});
/**
* 视频播放器相关
* @type {{els: {end: (*|jQuery|HTMLElement), vcb: (*|jQuery|HTMLElement), close: (*|jQuery|HTMLElement), ratio: (*|jQuery|HTMLElement), brush: (*|jQuery|HTMLElement), poptxt: (*|jQuery|HTMLElement), setting: (*|jQuery|HTMLElement)}, event: {addSetBtn: video.event.addSetBtn, setBindEvent: video.event.setBindEvent, end: video.event.end, close: video.event.close, switchRatio: video.event.switchRatio, switchBrush: video.event.switchBrush, switchPoptxt: video.event.switchPoptxt}}}
*/
var video = {
els: {
end: $(".end"),
vcb: $(".vjs-control-bar"),
vpc: $(".vjs-play-control"),
fullScreen: $(".vjs-fullscreen-control"),
isFull: false,
close: $(".setting > .close"),
ratio: $(".ratio"),
brush: $(".brush>.color"),
poptxt: $(".poptxt>.color"),
setting: $(".setting"),
tab: $(".s_tab")
},
event: {
resizeCavas() {
var originW = video.els.canvas.width(),
originH = video.els.canvas.height();
var screenW = window.screen.width,
screenH = window.screen.height;
if (video.els.isFull) {
video.els.canvas[0].width = screenW;
video.els.canvas[0].height = screenH;
video.els.isFull = true;
} else {
video.els.canvas[0].width = originW;
video.els.canvas[0].height = originH;
video.els.isFull = false;
}
},
addSetBtn() {
video.els.vcb.append('<div class="ico ico-cog vjs-control"></div>');
video.els.vcb.children("div.ico-cog").on("click", video.event.setBindEvent);
},
setBindEvent() {
video.els.setting.css({display: "block"});
},
addPlayRate() {
video.els.vcb.append(
'<div class="vjs-control playRate"><span class="currentPlayRate">1.0X</span>' +
'<div class="rates"><button>0.5x</button><button class="active">1.0x</button><button>1.5x</button><button>2.0x</button></div>'+
'</div>');
$(".currentPlayRate").on("click", video.event.playRateBindEvent);
$(".rates").on("click", "button", video.event.playRateBtnBindEvent);
},
playRateBindEvent() {
$(".rates").addClass("show");
},
playRateBtnBindEvent() {
$(this).addClass("active").siblings().removeClass("active");
var v = $(this).html();
$(".currentPlayRate").html(v);
$(".rates").removeClass("show");
var rate = v.replace("x", "");
player.playbackRate(rate);
},
addNext() {
$('<div class="ico ico-step-forward vjs-control"></div>').insertBefore($(".vjs-current-time"));
// $('<div class="ico ico-step-backward vjs-control"></div>').insertBefore($(".ico-step-forward"));
},
addShotImage() {
video.els.vcb.append('<div class="shot">识图<span class="ico ico-toggle-off"></span></div>');
video.els.vcb.children("span.ico-crop").on("click", video.event.setBindEvent);
$(".shot").on("click", video.event.openShot);
},
openShot() {
let open = !$(this).children("span").hasClass("ico-toggle-on");
$(this).children("span").toggleClass("ico-toggle-on");
video.els.canvas = $("#shot-canvas");
if (open) {
video.els.canvas.css({zIndex: "2147483649"});
window.openShot = true;
} else {
video.els.canvas.css({zIndex: "-1"});
window.openShot = false;
}
},
end() {
player.play();
$(this).css({display: "none"});
},
close() {
$(this).parent().css({display: "none"});
},
switchRatio() {
$(this).addClass("active").siblings("button").removeClass("active");
},
switchBrush() {
$(this).addClass("active").siblings("button").removeClass("active");
},
switchPoptxt() {
$(this).addClass("active").siblings("button").removeClass("active");
}
}
};
/**
* 快进/快退
*/
$(document).keydown(function(event){
var keyCode = window.event ? event.keyCode : event.which,
video = document.getElementById("my-video");
if (keyCode === 39) {
player.currentTime(player.currentTime() + 10);
}else if(keyCode === 37) {
player.currentTime(player.currentTime() - 10);
}
});
/**
* 重播按钮事件
*/
video.els.end.on("click", video.event.end);
/**
* 添加设置控制按钮
*/
video.event.addSetBtn();
/**
* 播放速度调节
*/
video.event.addPlayRate();
/**
* 下一集
*/
video.event.addNext();
// video.event.addShotImage();
/**
* 设置关闭按钮
*/
video.els.close.on("click", video.event.close);
/**
* 切换清晰度
*/
video.els.ratio.on("click", "button", video.event.switchRatio);
/**
* 切换画笔颜色
*/
video.els.brush.on("click", "button", video.event.switchBrush);
/**
* 弹幕样式
*/
video.els.poptxt.on("click", "button", video.event.switchPoptxt);
window.onload = function () {
$("#video-parent-box").screenshot("#my-video", "", true);
};
/**
* 视频分享
* @type {{els: {ss: (*|jQuery|HTMLElement), s: (*|jQuery|HTMLElement)}, config: {source: string, title: string, description: string, image: string, sites: string[], disabled: string[], wechatQrcodeTitle: string, wechatQrcodeHelper: string}, event: {hover: shareVideo.event.hover}}}
*/
var shareVideo = {
els: {
ss: $('.social-share'),
s: $(".share")
},
config: {
source: 'XXX视频', // <meta name="site" content="xxx" />
title: '', // document.title / <meta name="title" content="share.js" />
description: '', // <meta name="description" content="" />
image: '', // img
sites: ['qq', 'weibo', 'wechat'],
disabled: ['google', 'facebook', 'twitter'],
wechatQrcodeTitle: "微信扫一扫:分享",
wechatQrcodeHelper: ''
},
event: {
hover() {
$(this).children(".social-share").toggleClass("show");
}
}
};
/**
* 配置分享功能
*/
shareVideo.els.ss.share(shareVideo.config);
shareVideo.els.s.hover(shareVideo.event.hover);
/**
* 右侧tab页
* @type {{els: {tab: (*|jQuery|HTMLElement), teleplay: (*|jQuery|HTMLElement)}, event: {initTab: tab.event.initTab, getMovieUUID: tab.event.getMovieUUID, teleplayClick: tab.event.teleplayClick}}}
*/
var tab = {
els: {
tab: $("ul.r_tab"),
teleplay: $(".teleplay"),
tabList: $("div.tabList"),
tabInfo: $(".tabInfo")
},
event: {
initTab() {
var _id = tab.els.tab.find(".active").attr("id");
$("." + _id).css({display: "block"}).siblings("div").css({display: "none"});
},
getMovieUUID() {
var href = window.location.href,
srcUid = href.getParameter('uid');
$("#" + srcUid).addClass("active");
if (!core.debug) {
$.ajax({
type: 'get',
url: "/Index/ajaxPlay",
dataType: 'json',
data: {'src_uid': srcUid},
success: data => {
if (data.ok == 'success') {
document.title = data.info.videoone_name;
$(document.getElementsByTagName('meta')['title']).attr('content', data.info.videoone_name);
$('.videoOneName').html(data.info.videoone_name);
tool.els.praise.html(data.info.praise);
tool.els.tread.html(data.info.tread);
var episode = data.info.video_src;
var _video = videojs('#my-video');
_video.ready(function () {
var myPlayer = this;
myPlayer.src(core.videoSite + '/Public/Uploads/' + episode);
myPlayer.load(core.videoSite + '/Public/Uploads/' + episode);
myPlayer.play();
});
comment.event.content(srcUid);
}
},
fail(e) {
// $("body").shortMessage(false, true, '服务器开小差咯,点赞失败,重新试试呢!')
console.log(e);
}
});
}
},
teleplayClick() {
$(this).addClass("active").siblings("button").removeClass("active");
var srcUid = $('.teleplay>.active').attr('id');
if (!core.debug) {
$.ajax({
type: 'get',
url: "/Index/ajaxPlay",
dataType: 'json',
data: {'src_uid': srcUid},
success: data => {
if (data.ok == 'success') {
document.title = data.info.videoone_name;
$(document.getElementsByTagName('meta')['title']).attr('content', data.info.videoone_name);
$('.videoOneName').html(data.info.videoone_name);
tool.els.praise.html(data.info.praise);
tool.els.tread.html(data.info.tread);
var href = window.location.href;
window.location.href = core.delQueStr(href, 'uid', '#') + "#uid=" + data.info.src_uid;
var episode = $('.teleplay>.active').attr('src');
var _video = videojs('#my-video');
_video.ready(function () {
var myPlayer = this;
myPlayer.src(core.videoSite + '/Public/Uploads/' + episode);
myPlayer.load(core.videoSite + '/Public/Uploads/' + episode);
myPlayer.play();
});
comment.event.content(srcUid);
}
},
fail(e) {
// $("body").shortMessage(false, true, '服务器开小差咯,点赞失败,重新试试呢!')
console.log(e);
}
})
}
},
feedback() {
if(!core.debug) {
var isLogin = com.event.isLogin();
if(isLogin) {
$("div.panel, div.mask").addClass("show");
}else {
com.els.loginBtn.trigger("click");
}
}else {
if(!core.isLogin) {
$("div.panel, div.mask").addClass("show");
}else {
com.els.loginBtn.trigger("click");
}
}
},
closeProvide() {
$("div.panel, div.mask").removeClass("show");
},
provideInfo() {
if (!core.debug) {
// 数据信息
var _data = core.dealData.serialize($('div.panel'));
$.ajax({
url: "",
data: _data
}, data => {
if(data.ok === "success") {
$("div.panel, div.mask").removeClass("show");
$("div.provide").empty().html("<span class='ico ico-check'></span>提交成功,若通过后台验证和获得其他用户认可,即点赞数大于>100,将发放奖励至您的账户,感谢您的反馈!");
}
}, error => {
$(".tabList").shortMessage(false, true, '提交失败,请重试!', 1500, {
width: "160px"
});
})
} else {
$("div.panel, div.mask").removeClass("show");
$("div.provide").empty().html("<span class='ico ico-check'></span>提交成功,若通过后台验证和获得其他用户认可,即点赞数大于>100,将发放奖励至您的账户,感谢您的反馈!");
}
}
}
};
tab.event.initTab();
/**
* 获取视频UUID
*/
tab.event.getMovieUUID();
/**
* 视频集数选择
*/
tab.els.teleplay.on("click", ">button", tab.event.teleplayClick);
/**
* 反馈尚未收录的商品信息
*/
tab.els.tabList.on("click", "#feedback", tab.event.feedback);
tab.els.tabList.on("click", "#provideInfo", tab.event.provideInfo);
tab.els.tabList.on("click", ".panel .ico-close", tab.event.closeProvide);
/**
* 限制剧情介绍最大字符长度
*/
core.sliceStr(tab.els.tabInfo.find("span.drama"), 300);
/**
* 视频工具栏
* @type {{els: {lock: (*|jQuery|HTMLElement), ap: (*|jQuery|HTMLElement), shot: (*|jQuery|HTMLElement)}, event: {openPoptxt: tool.event.openPoptxt, love: tool.event.love, openShot: tool.event.openShot}}}
*/
var tool = {
els: {
lock: $(".lock"),
loveOrHate: $(".loveOrHate"),
hate: $(".hate"),
love: $(".love"),
shot: $(".shot"),
praise: $('#praise'),
tread: $('#tread'),
canvas: null,
imageCanvas: null
},
event: {
openPoptxt() {
var isOpen = $(this).siblings("span").hasClass("ico-unlock-alt");
if (isOpen) {
$(this).siblings("span").removeClass("ico-unlock-alt")
.parent().siblings("input").attr("readonly", true);
$(this).parent().siblings("button.send").removeClass("active").prop("disabled", true);
$(this).prev("span").removeClass("active");
} else {
$(this).siblings("span").addClass("ico-unlock-alt")
.parent().siblings("input").removeAttr("readonly");
$(this).parent().siblings("button.send").addClass("active").prop("disabled", false);
$(this).parent().next("input").focus();
$(this).prev("span").addClass("active");
}
},
isLoveHate() {
if (window.localStorage.loveVideo && window.localStorage.hateVideo) {
var love = window.localStorage.loveVideo.split(",");
var hate = window.localStorage.hateVideo.split(",");
var h = window.location.href,
src_uid = h.getParameter('uid');
$.each(love, function (i, d) {
if (src_uid === d) {
tool.els.love.children("button").addClass("active");
}
});
$.each(hate, function (i, d) {
if (src_uid === d) {
tool.els.hate.children("button").addClass("active");
}
});
} else {
window.localStorage.loveVideo = ",";
window.localStorage.hateVideo = ",";
}
var isLove = tool.els.love.children("button").hasClass("active"),
isHate = tool.els.hate.children("button").hasClass("active");
if (isLove) {
tool.els.love.children("button").off("click");
tool.els.hate.addClass("notAllowed");
} else if (isHate) {
tool.els.hate.children("button").off("click");
tool.els.love.addClass("notAllowed");
} else {
/**
* 赞/踩绑定事件
*/
tool.els.loveOrHate.one("click", tool.event.loveOrHate);
}
},
loveOrHate() {
$(this).children(".ico").addClass("active");
var cls = $(this).hasClass("love");
$(this).off("click");
var h = window.location.href,
src_uid = h.getParameter('uid');
if (cls) {
//点赞
tool.els.hate.off("click").addClass("notAllowed");
tool.els.hate.children(".ico").prop("disabled", true);
if (!core.debug) {
$.ajax({
type: 'get',
dataType: 'json',
data: {'type': 'praise', 'src_uid': src_uid},
url: "/Index/ajaxPraiseTread",
success: data => {
if (data.ok == 'success') {
tool.els.praise.html(data.info.praise);
window.localStorage.loveVideo += src_uid + ",";
} else if (data.ok == 'true') {
$("body").shortMessage(false, true, '你已经赞过了!')
}
},
fail(e) {
// $("body").shortMessage(false, true, '服务器开小差咯,点赞失败,重新试试呢!')
console.log(e);
}
})
} else {
var o = $(this).children(".num"),
v = Number(o.html());
o.html(v + 1);
$(this).off("click");
/**
* 写入localstorage
* @type {string}
*/
window.localStorage.loveVideo += src_uid + ",";
}
} else {
//踩
tool.els.love.off("click").addClass("notAllowed");
tool.els.love.children(".ico").prop("disabled", true);
if (!core.debug) {
$.ajax({
type: 'get',
dataType: 'json',
data: {'type': 'tread', 'src_uid': src_uid},
url: "/Index/ajaxPraiseTread",
success: data => {
if (data.ok == 'success') {
tool.els.tread.html(data.info.tread);
$(this).off("click");
window.localStorage.hateVideo += src_uid + ",";
} else if (data.ok == 'true') {
$("body").shortMessage(false, true, '你已经踩过了!')
}
},
fail(e) {
// $("body").shortMessage(false, true, '服务器开小差咯,点赞失败,重新试试呢!')
console.log(e);
}
})
} else {
var _o = $(this).children(".num"),
_v = Number(_o.html());
_o.html(_v + 1);
$(this).off("click");
window.localStorage.hateVideo += src_uid + ",";
}
}
},
openShot() {
let open = !$(this).children("button").hasClass("ico-toggle-on");
$(this).children("button").toggleClass("ico-toggle-on");
$(this).children("button").toggleClass("active");
tool.els.canvas = $("#shot-canvas");
if (open) {
$("#shot-canvas").css({zIndex: "2147483646"});
window.openShot = true;
} else {
$("#shot-canvas").css({zIndex: "-1"});
window.openShot = false;
}
}
}
};
/**
* 弹幕切换
* @type {boolean}
*/
tool.els.lock.on("click", ">button.txt", tool.event.openPoptxt);
/**
* 是否已赞/踩
*/
tool.event.isLoveHate();
/**
* 开启搜图模式
*/
tool.els.shot.on("click", tool.event.openShot);
/**
* 描述字符限制
*/
core.sliceStr($(".item .desc"), 20, true);
core.sliceStr($(".goodsName"), 20, false);
/**
* 评论区
* @type {{els: {approve: (*|jQuery|HTMLElement), textarea: (*|jQuery|HTMLElement)}, event: {approve: comment.event.approve, inputWords: comment.event.inputWords}}}
*/
var comment = {
els: {
approve: $('.approve'),
textarea: $("#commentTextarea"),
surplus: $(".surplus"),
submit: $("#commentSubmit"),
commLists: $(".commLists")
},
event: {
approve() {
$(this).addClass("active");
$(this).off("click");
var numSpan = $(this).children('span');
var v = numSpan.html() || 0;
numSpan.html(parseInt(v) + 1);
if (!core.debug) {
var con_id = $(this).parents(".commList").attr('id');
$.ajax({
type: "get",
url: "/Comment/ajaxContentPraise",
dataType: "json",
data: {'con_id': con_id},
success: data => {
if (data.ok == 'success') {
$(this).children("span").html(data.info.praise);
}
}
})
}
},
inputWords() {
var v = $(this).val(), len = v.length;
if (len <= 300) {
comment.els.surplus.html(300 - len);
}
},
content(srcUid) {
if (!core.debug) {
$.ajax({
type: 'get',
url: "/Comment/ajaxContent",
dataType: 'json',
data: {'src_uid': srcUid},
success: data => {
if (data.ok == 'success') {
var html = '';
var i = 0;
for (data.info; i < data.info.length; i++) {
html += `<div class="commList clr-float" id="${data.info[i].id}">
<div class="img"><img src="/public/${data.info[i].face}" alt=""></div>
<div class="content">
<a href="###" class="name">${data.info[i].username}</a>
<p class="desc">${data.info[i].content}</p>
<div class="operate"><span class="time">${data.info[i].addtime}</span>
<span class="ico ico-thumbs-up approve"><span>${data.info[i].praise}</span></span>
<span class="reply">回复</span></div></div></div>`;
}
$(".commLists").html(html);
$(".approve").on("click", comment.event.approve);
$(".reply").on("click", comment.event.openReply);
}
}
})
}
},
submit() {
var v = comment.els.textarea.val();
var h = window.location.href,
src_uid = h.getParameter('uid');
if (!core.debug) {
$.ajax({
type: 'post',
url: '/Comment/ajaxComment',
dataType: 'json',
data: {'content': v, 'uid': src_uid},
success: data => {
if (data.ok == 'success') {
var html = '';
var i = 0;
for (data.info; i < data.info.length; i++) {
html += `<div class="commList clr-float" id="${data.info[i].id}">
<div class="img"><img src="/public/${data.info[i].face}" alt=""></div>
<div class="content"><a href="###" class="name">${data.info[i].username}</a>
<p class="desc">${data.info[i].content}</p><div class="operate">
<span class="time">${data.info[i].addtime}</span>
<span class="ico ico-thumbs-up approve">${data.info[i].praise}</span>
<span class="reply">回复</span></div></div></div>`;
}
$(".commLists").html(html);
$(".approve").on("click", comment.event.approve);
$(".reply").on("click", comment.event.openReply);
} else {
com.els.loginBtn.trigger("click");
}
},
fail(e) {
$(".commLists").shortMessage(false, true, '评论提交失败,重新试试呢', 1500);
}
});
} else {
var html = '<div class="commList clr-float"><div class="img"><img src="style/images/logo0.png" alt="">' +
'</div><div class="content"><a href="###" class="name">一只蜗牛</a>' +
'<p class="desc">' + v + '</p>' +
'<div class="operate"><span class="time">刚刚</span><span class="ico ico-thumbs-up approve"></span>' +
'<span class="reply">回复</span></div></div></div>';
comment.els.commLists.prepend(html);
$(".approve").on("click", comment.event.approve);
$(".reply").on("click", comment.event.openReply);
}
},
openReply(e) {
if (core.isLogin) {
$(".replyBox").remove();
var html = '<div class="replyBox clr-gap"><input type="text" placeholder="说点什么吧"><button class="rep">回复</button></div>';
$(this).parents(".content").append(html);
$(".rep").on("click", comment.event.submitReply);
} else {
com.els.loginBtn.trigger("click");
}
},
submitReply() {
var h = window.location.href,
src_uid = h.getParameter('uid');
var v = $(this).prev().val();
var con_id = $(this).parent().parent().parent().attr('id');
if (!core.debug) {
$.ajax({
type: "post",
url: "/Comment/ajaxReply",
dataType: "json",
data: {'content': v, 'uid': src_uid, 'con_id': con_id},
success: data => {
if (data.ok == 'success') {
var html = '';
var i = 0;
for (data.info; i < data.info.length; i++) {
html += `<div class="commList clr-float" id="${data.info[i].id}">
<div class="img"><img src="/Public/${data.info[i].face}" alt=""></div>
<div class="content"><a href="###" class="name">${data.info[i].username }</a>
<p class="desc">${data.info[i].content}</p><div class="operate">
<span class="time">${data.info[i].addtime}</span>
<span class="ico ico-thumbs-up approve"><span>${data.info[i].praise}</span></span>
<span class="reply">回复</span></div></div></div>`;
}
$(this).parents(".commList").after(html);
$(this).parent().remove();
$(".approve").on("click", comment.event.approve);
$(".reply").on("click", comment.event.openReply);
}
},
fail(e) {
}
})
}
}
}
};
/**
* 评论区点赞
*/
comment.els.commLists.find(".approve").one("click", comment.event.approve);
/**
* 检测输入字数
* @type {Element}
*/
var isInput = document.createElement('input');
if ('oninput' in isInput) {
comment.els.textarea.on("input", comment.event.inputWords);
} else {
comment.els.textarea.on("propertychange", comment.event.inputWords);
}
/**
* 提交评论
*/
comment.els.submit.on("click", comment.event.submit);
/**
* 打开回复框
*/
comment.els.commLists.find(".reply").on("click", comment.event.openReply);
var related = {
els: {
star: $(".star"),
rm: $("#relatedMovies")
},
event: {
mouseenter() {
$(this).addClass("active").siblings().removeClass("active");
if (!core.debug) {
var actor_id = $(this).attr('id').replace("act_", "");
$.ajax({
type: "get",
url: "/Index/ajaxActor",
dataType: "json",
data: {'actor_id': actor_id},
success: data => {
if (data.ok == 'success') {
var html = '',
i = 0;
for (data.info; i < data.info.length; i++) {
html += `<div class="item"><a href="/Index/info/${data.info[i].video_uid}" target="_blank">
<img src="/Public/Uploads/${data.info[i].logo}" alt="">
<span>更新至<span>${data.info[i].number}</span>集</span></a>
<div class="msg"><p>${data.info[i].video_name}</p>
<p class="desc">${data.info[i].short_desc}</p></div></div>`;
}
related.els.rm.empty().append(html);
}
}
});
} else {
var temp = ["style/images/pic.jpg", "style/images/pic1.jpg"];
var rand = Math.round(Math.random());
var htmlArr = [];
for (var i = 0; i < 10; i++) {
htmlArr[i] = `<div class="item"><a href="" target="_blank"><img src="${temp[rand]}" alt="">
<span>更新至<span>32</span>集</span></a><div class="msg"><p>一个人的喧嚣</p>
<p class="desc">在JavaScript发展初期就是为了实现简单的页面交互逻辑...</p>' + '</div></div>`;
}
related.els.rm.empty().append(htmlArr.join(""));
}
}
}
};
/**
* 切换人物相关视频
*/
related.els.star.on("mouseenter", related.event.mouseenter);
/**
* 默认第一个
*/
$(".star.active").trigger("mouseenter"); |
'use strict';
const { push } = require('react-router-redux');
module.exports = {
taskActions: require('./task'),
userActions: require('./user'),
navigate: push
};
|
import React, { useState } from 'react';
import { useSelector } from 'react-redux';
import { Loader, Grid, Form, Button } from 'semantic-ui-react';
import { ErrMsg } from '../components';
import { BACKEND } from '../config';
import { useAPI } from '../hooks';
export default () => {
const { token } = useSelector(state => state.user);
const [connection, connect] = useAPI("json");
const [courseThreshold, setCourseThreshold] = useState(-1);
const [companyThreshold, setCompanyThreshold] = useState(-1);
const [list, setList] = useState(null);
let display = null;
const onFilter = () => {
let id_to_user = {};
let id_to_count = {}; // id -> [courseCount, companyCount]
for(let event of connection.response) {
const isCourse = event.admin.group === "seminarStaff";
for(let participant of event.participant) {
if(id_to_user[participant._id] === undefined) {
id_to_user[participant._id] = participant;
id_to_count[participant._id] = [0,0];
}
let count = id_to_count[participant._id];
if(isCourse) count[0] = count[0] += 1;
else count[1] = count[1] += 1;
id_to_count[participant._id] = count;
}
}
let userList = [];
for(const [id, count] of Object.entries(id_to_count)) {
if(count[0] >= courseThreshold && count[1] >= companyThreshold) {
userList.push(id_to_user[id]);
}
}
setList(userList);
}
if (connection.isInit()) {
connect(
BACKEND + `/event?populate=1`,
"GET",
null,
{ 'authorization': token, 'content-type': "application/json" }
);
}
if (connection.error) {
display = <ErrMsg />;
}
else if (connection.success) {
display = <div>Set filter first.</div>;
if(list !== null) {
const text = "Username,Email\n" + list.map(user => `${user.name},${user.email}`).join("\n");
const data = new Blob([text], {type: 'text/plain'});
const url = window.URL.createObjectURL(data);
display = (
<div>
<span>There are {list.length} users qualified.</span><br />
<Button color="blue" as="a" href={url} download="list.csv" style={{marginTop: "2vh"}}>Download List</Button>
</div>
)
}
}
else {
display = <Loader active={true} />;
}
return (
<Grid textAlign="center" verticalAlign='middle' style={{ width: "100%", marginTop: "2vh" }}>
<Grid.Row columns={2}>
<Grid.Column style={{ width: "80%", maxWidth: "30em" }}>
<Form>
<Form.Field>
<label>Course Threshold</label>
<input
type='number'
placeholder='Some Number...'
onInput={e => setCourseThreshold(parseInt(e.target.value))}
/>
</Form.Field>
<Form.Field>
<label>Company Threshold</label>
<input
type='number'
placeholder='Some Number...'
onInput={e => setCompanyThreshold(parseInt(e.target.value))}
/>
</Form.Field>
<Button onClick={_ => onFilter()}>Filter</Button>
</Form>
</Grid.Column>
<Grid.Column>
{display}
</Grid.Column>
</Grid.Row>
</Grid>
)
} |
/**
* Created by xiaojiu on 2016/11/7.
*/
define(['../../../app','../../../services/storage/inventory-manage/inventoryEntryService','../../../services/uploadFileService'], function (app) {
var app = angular.module('app');
app.controller('inventoryEntryCtrl', ['$rootScope','$scope', '$sce', '$timeout', 'inventoryEntry','$window','$stateParams','$state','uploadFileService', function ($rootScope,$scope, $sce, $timeout, inventoryEntry,$window,$stateParams,$state,uploadFileService) {
//theadr
$scope.pageModel={
SKU:''
}//查询框
$scope.thHeader = inventoryEntry.getThead();
//分页下拉框
$scope.pagingSelect = [
{value: 5, text: 5},
{value: 10, text: 10, selected: true},
{value: 20, text: 20},
{value: 30, text: 30},
{value: 50, text: 50}
];
//分页对象
$scope.paging = {
totalPage: 1,
currentPage: 1,
showRows: 30,
};
//查询
$scope.searchClick = function () {
$scope.paging = {
totalPage: 1,
currentPage: 1,
showRows: $scope.paging.showRows
};
get();
}
$scope.exGoodsAlloParam={};
function get(){
//获取选中 设置对象参数
var opts ={
taskId:$stateParams['taskId'],
sku:$scope.pageModel.SKU
}
$scope.exGoodsAlloParam={query:opts};
var promise = inventoryEntry.getDataTable('/ckInventory/inventoryOrderInput',{param: {query: opts}});
promise.then(function (data) {
if(data.code==-1){
alert(data.message);
$scope.result = [];
$scope.paging = {
totalPage: 1,
currentPage: 1,
showRows: $scope.paging.showRows,
};
return false;
}
$scope.result = data.grid;
$scope.banner=data.banner;
//重置paging 解决分页指令不能监听对象问题
$scope.paging = {
totalPage: data.total,
currentPage: $scope.paging.currentPage,
showRows: $scope.paging.showRows,
};
}, function (error) {
console.log(error);
});
}
//导入
$scope.isShow=true;
$scope.impUploadFiles= function (files) {
if(files.length==0) return false;
var opts ={
taskId:$stateParams['taskId'],
}
//多文件上传
var count=0;
function upFiles(){
uploadFileService.upload('/ckInventory/importExcel'+"?taskId="+$stateParams["taskId"],files[count],{query: opts},function(evt){
//进度回调
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
$scope.impUploadFilesProgress=evt.config.data.file.name+'的进度:'+progressPercentage+'%';
}).then(function (resp) {
if(resp.data.status.code=="0000"){
//上传成功
$scope.impUploadFilesProgress='上传完成!';
get();
alert( resp.data.status.msg);
count++;
$timeout(function(){
$scope.isShow = false;
},3000);
if(files.length>count)
upFiles();
}else{
$scope.impUploadFilesProgress='上传失败!';
}
});
}
upFiles();
}
$scope.ajaxInput= function (index, obj) {
var opts = {};//克隆出新的对象,防止影响scope中的对象
var inventoryCount=obj.inventoryCount;
obj.inventoryCount= obj.inventoryCount.replace(/\D/g,'');
opts.taskId = $stateParams['taskId'];
opts.customerName = obj.customerName;
opts.suppliersName = obj.suppliersName;
opts.inventoryCount =obj.inventoryCount;
opts.id =obj.id;
opts.remarks =obj.remarks;
var reg = new RegExp("^[0-9]{0,5}$");
if(!reg.test(opts.inventoryCount)){
alert("转移数量必须为1-99999的数字!");
$("#confirmApplication").modal("hide");
return false;
}
if(inventoryCount==obj.inventoryCount){
var promise = inventoryEntry.getDataTable('/ckInventory/ajaxInputSuccess',{param: {query: opts}});
promise.then(function (data) {
// console.log(data);
}, function (error) {
console.log(error);
});
}
}
$scope.ajaxInput2= function (index, obj) {
var opts = {};//克隆出新的对象,防止影响scope中的对象
opts.taskId = $stateParams['taskId'];
opts.customerName = obj.customerName;
opts.suppliersName = obj.suppliersName;
opts.inventoryCount =obj.inventoryCount;
opts.id =obj.id;
opts.remarks =obj.remarks;
var promise2 = inventoryEntry.getDataTable('/ckInventory/ajaxInputSuccess',{param: {query: opts}});
promise.then(function (data) {
}, function (error) {
console.log(error);
});
}
//完成登记
$scope.completeRegistration=function(){
//var isTrue=true;
//var reg = new RegExp("^[0-9]*$");
//angular.forEach($scope.result, function (item,index){
// if(!reg.test(item.inventoryCount)){
// alert("请输入正确的实盘数量!")
// isTrue=false
// }
//});
//if(isTrue==false){
// return false
//}
var opts = {};
opts.taskId = $stateParams['taskId'];
var promise = inventoryEntry.getDataTable('/ckInventory/inputSuccess',{param: {query: opts}});
promise.then(function (data) {
if(data.status.code == "0000"){
alert(data.status.msg);
$state.go('main.inventoryTask')
}
}, function (error) {
console.log(error);
});
}
get();
//返回
$scope.update= function () {
$window.history.back();
}
}]);
}); |
import React from 'react';
import { array } from 'prop-types';
import FriendListItem from '../FriendListItem/FriendListItem';
import './FriendList.scss'
function FriendList({friends}) {
return (
<ul className="friend-list">
{
friends.map(item => {
return (
<FriendListItem key={item.id} friend={item} />
)
})
}
</ul>
);
}
FriendList.propTypes = {
friends: array.isRequired
}
FriendList.defaultProps = {
friends: []
};
export default FriendList; |
const express = require('express');
const HomeController = require('../controllers/home.js');
const { isAuthorizedAsIn } = require('../helpers/AuthUtils');
const router = express.Router();
router.get('/', isAuthorizedAsIn(['ADMIN', 'PROJECT']), HomeController.findByMonthYear);
module.exports = router;
|
var cancelModal=UIkit.modal("#cancelModal");
// 取消订单按钮
$('.wl-cancelOrder').on('click',function () {
console.log($(this).attr('orderid'))
cancelModal.show()
})
|
import { makeStyles } from '@material-ui/core/styles';
import { createMuiTheme } from "@material-ui/core/styles";
export const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
backgroundColor: "#0090e6",
display: "flex",
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
},
indicator: {
backgroundColor: "#F8F8F8"
},
navContent: {
display: "flex",
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between"
},
navItemDefault: {
color: "#B6D3F1",
},
navItemActive: {
color: "#F8F8F8"
},
shopLogo: {
width: 200,
height: 40,
maxWidth: "33.33%",
flex: 1,
},
socialLogo: {
width: 24,
height: 24
},
searchBar: {
flex: 3,
},
tabs: {
flex: 2
}
}));
export const theme = createMuiTheme({
overrides: {
MuiTabs: {
root: {
maxWidth: "33.33%"
},
},
MuiTab: {
root: {
minWidth: "100px !important"
},
}
}
}); |
var num=0;
var obj={};
function addType(){
var divElem = document.getElementById('types');
var newdiv = document.createElement('div');
var inp = document.createElement('input');
inp.id = 'type' + num;
inp.className = 'form-control';
inp.placeholder = 'Type ' + num;
var inp1 = document.createElement('input');
inp1.id = 'value' + num;
inp1.className = 'form-control';
inp1.placeholder = 'Values of ' + num;
newdiv.appendChild(inp);
newdiv.appendChild(document.createElement('br'));
newdiv.appendChild(inp1);
newdiv.className = 'form-group';
divElem.insertBefore(newdiv, divElem.childNodes[num]);
divElem.style.display = 'block';
num+=1;
}
function getValues(){
alert("called");
var typeVaule=[];
var objJson=[];
var i,j,x;
var count=1;
for(i=0;i<num;i++){
x={};
x.type = document.getElementById('type' + i).value;
x.values = document.getElementById('value' + i).value.split(',');
count = count * x.values.length;
typeVaule.push(x);
// console.log(obj.typeVaule);
}
obj.typeVaule=typeVaule;
// console.log(obj.typeVaule);
var y=1;
for(i=0;i<typeVaule.length;i++){
y*=typeVaule[i].values.length;
var dum=0;
for(j=0;j<count;j++){
if(j%(count/y)==0){
dum+=1;
if(dum==typeVaule[i].values.length){
dum=0;
}
}
// console.log()
if(objJson[j]==undefined){
x={};
x[typeVaule[i].type]=typeVaule[i].values[dum];
objJson.push(x);
}
else{
objJson[j][typeVaule[i].type]=typeVaule[i].values[dum];
// console.log(objJson);
}
}
}
// console.log(objJson,obj);
obj.objJson=objJson;
var newDiv = document.createElement('div');
newDiv.id = 'newDiv';
var key = Object.keys(obj.objJson[0]);
for (i = 0; i < count; i++) {
var newDiv1 = document.createElement('div');
var lab = document.createElement('label');
lab.setAttribute('for', 'val' + i);
var inp1 = document.createElement('input');
inp1.name = 'val' + i;
inp1.id = 'val' + i;
inp1.value = 0;
inp1.className = 'form-control';
for (j = 0; j < key.length; j++) {
if (j == 0) {
lab.innerHTML = obj.objJson[i][key[j]];
} else {
lab.innerHTML = lab.innerHTML + '/' + obj.objJson[i][key[j]];
}
}
newDiv1.appendChild(lab);
newDiv1.appendChild(inp1);
newDiv.appendChild(newDiv1);
}
var btn=document.createElement('input');
btn.type="button";
btn.value="output";
btn.setAttribute('onclick', 'priceAdd()');
newDiv.appendChild(btn);
// console.log(obj.objJson);
}
function priceAdd(){
for (i = 0; i < obj.objJson.length; i++) {
obj.objJson[i].Price = parseInt(document.getElementById('val' + i).value);
}
}
function display() {
console.log(obj);
// var i;
// for(i=0;i<obj.varientDetails.length;i++){
document.getElementById("Display").innerHTML=JSON.stringify(obj.objJson);
// }
} |
const ruta = require('path');
module.exports.validateExtension = ( path ) => {
let ext = ruta.extname(path);
if (ext === '.md') {
return true;
} else {
return false;
}
} |
import React, {Component} from 'react'
import T from 'prop-types'
//import {Icon} from 'antd'
import '../assets/index.less'
class ScrollPagination extends Component {
constructor(props) {
super(props)
this.timeout = null
this.startTime = new Date()
this.DataStatus = {
loading: <span type="loading"> 加载中,请稍后!</span>,
more: <span style={{cursor: "pointer"}} onClick={this.fetchData}> 点击或滚动加载更多!</span>,
full: '没有更多内容!'
}
this.state = {
className: props.className,
showScroll: props.showScroll,
height: props.height && props.height < 0 ? 0 : props.height,
innerHeight: 'auto',
isScrollRender: true, //是否滚动触发渲染
isInited: true,//是否初始化
isScrolled: false,//是否已滚动
status: props.hasData ? this.DataStatus.more : this.DataStatus.full//是否有数据
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.isReset) {//切换数据源滚动置顶,防止底部无限请求数据
this.scrollTop()
}
let {height, innerHeight, isInited, isScrollRender, showScroll, className} = this.state,
isHeightChange = false//是否高度变更
if (nextProps.hasData === true) {//存在数据,加载更多
this.setState({status: this.DataStatus.more})
} else if (nextProps.hasData === false) {//不存在数据,数据已满
this.setState({status: this.DataStatus.full})
}
if (nextProps.className != className) {
this.setState({className: nextProps.className})
}
if (nextProps.showScroll != showScroll) {
this.setState({showScroll: nextProps.showScroll})
}
if (nextProps.height != height) {
isHeightChange = true
this.throttleFunction(//高度变更节流
() => {
this.setState({height: nextProps.height})
if (innerHeight != "auto") {
this.setState({innerHeight: nextProps.height + 100})
}
}, 167, 300)()
} else {
isHeightChange = false
}
if (!isHeightChange) {
if (isInited) {
this.fetchAfter()
this.setState({isInited: false, isScrollRender: false})
} else {
if (isScrollRender) {
this.fetchAfter()
}
}
}
}
checkScroll = () => {
if (!this.state.isScrolled) {//非滚动状态,检测是否需要添加滚动条
let dom = document.getElementsByClassName('sp-content')[0],
{height, innerHeight} = this.state,
{scrollHeight} = dom
if (scrollHeight <= height) {//手动添加滚动条
this.setState({isScrolled: false, innerHeight: height + 100})
} else {//不需要滚动,设置自滚动,打开滚动状态
this.setState({isScrolled: true, innerHeight: 'auto'})
}
}
}
resetScroll = () => {
if (!this.state.isScrolled) {//非滚动状态,重置滚动
this.setState({innerHeight: 'auto'})
}
}
scrollTop = (height) => {
let dom = document.getElementsByClassName('sp-content')[0]
dom.scrollTop = height
}
resetRender = () => {
if (!this.state.isScrollRender) {//非滚动状态,设置滚动
this.setState({isScrollRender: true})
}
}
scrollBefore = () => {
let {scrollBefore} = this.props
if (scrollBefore) {
scrollBefore()
} else {
//console.log('滚动加载前!')
}
this.resetRender()//滚动加载之前,重置加载
}
scrollAfter = () => {
let {scrollAfter} = this.props
if (scrollAfter) {
scrollAfter()
} else {
//console.log('滚动加载后!')
}
}
fetchBefore = () => {
let {fetchBefore} = this.props
if (fetchBefore) {
fetchBefore()
} else {
//console.log('数据加载前!')
}
this.resetScroll()//加载数据之前,重置滚动
}
fetchAfter = () => {
let {fetchAfter} = this.props
if (fetchAfter) {
fetchAfter()
} else {
//console.log('数据加载后!')
}
this.checkScroll()//加载数据之后,检测滚动
}
fetchData = () => {
if (!this.state.isInited) {//初始化状态,不发生滚动
this.scrollAfter()
}
this.fetchBefore()
this.setState({status: this.DataStatus.loading},//请求数据之前,设置加载状态
() => {
// anruo test loading
setTimeout(
() => {
this.props.fetchData()
}, 0
)
}
)
}
throttleFunction = (method, delay, time) => {
let timeout = this.timeout, startTime = this.startTime
return () => {
let context = this,
args = arguments,
curTime = new Date()
clearTimeout(timeout)
if (curTime - startTime >= time) {
method.apply(context, args)
this.startTime = curTime
} else {
this.timeout = setTimeout(method, delay)
}
}
}
onScroll = (event) => {
const dom = event.currentTarget
this.throttleFunction(//滚动事件节流
() => {
const {status} = this.state
if (status == this.DataStatus.more) {
const {scrollTop, clientHeight, scrollHeight} = dom
if (scrollTop + clientHeight == scrollHeight) {
this.scrollBefore()
this.fetchData()
}
}
}, 167, 300)()
}
render() {
let {status, height, innerHeight, className, showScroll} = this.state,
{showTip} = this.props
return (
<div className={'scroll-pagination ' + (className ? className : '')}>
<div className='sp-content' onScroll={this.onScroll} style={{
height: height,
width: (showScroll ? "100%" : "120%"),
paddingRight: (showScroll ? "1%" : "20%")
}}>
<div style={{height: innerHeight}}>
{this.props.children}
</div>
</div>
{
showTip ? (
<div className='split-line' style={{marginTop: "16px"}}>
<div className='sl-item sl-line'/>
<div className='sl-item sl-wrap '>
<div className='sl-text'>
{status}
</div>
</div>
</div>
) : ""
}
</div>
)
}
}
ScrollPagination.propTypes = {
fetchData: T.func.isRequired,//数据加载函数,参数:'init'、'more'
hasData: T.bool,//有数据、无数据
height: T.number.isRequired,//滚动区间高度
className: T.string,//容器类
showTip: T.bool,//是否显示提示
showScroll: T.bool,//是否显示滚动条
scrollBefore: T.func,//滚动之前处理函数
scrollAfter: T.func,//滚动之后处理函数
fetchBefore: T.func,//数据请求开始时处理函数
fetchAfter: T.func//数据请求结束时处理函数
}
ScrollPagination.defaultProps = {
showTip: false,
showScroll: false,
className: ""
}
export default ScrollPagination
/*
*** 滚动分页组件:无限滚动加载数据 ***
> 高度事件节流
> 滚动事件节流
> 滚动触发前后监听
> 数据加载前后监听
> 数据加载自动识别滚动(空数据,数据不够高时可触发滚动)
> 滚动条隐藏
> 数据自动加载
*/
|
let idades = [15, 39, 18, 23, 10]; // Um array
console.log('Array Original', idades);
let maiores = idades.filter(function(idade) { // Um novo Array
return idade >= 18;
});
console.log(maiores); |
import React, { useState, useEffect, useContext } from 'react'
import { View, Image, ScrollView, TouchableOpacity } from 'react-native'
import styles from './styles'
import { verticalScale, colors, alignment, scale } from '../../utils'
import BlueBtn from '../../ui/Buttons/BlueBtn'
import { SafeAreaView } from 'react-native-safe-area-context'
import {
BackHeader,
BottomTab,
TextDefault,
FlashMessage,
Spinner
} from '../../components'
import { useNavigation, useRoute } from '@react-navigation/native'
import { AntDesign, Feather } from '@expo/vector-icons'
import UserContext from '../../context/User'
import ConfigurationContext from '../../context/Configuration'
import { stripeCurrencies, paypalCurrencies } from '../../utils/currencies'
import { useMutation, gql } from '@apollo/client'
import { placeOrder, getCoupon } from '../../apollo/server'
import TextField from '../../ui/Textfield/Textfield'
import MainBtn from '../../ui/Buttons/MainBtn'
const PLACEORDER = gql`
${placeOrder}
`
const GET_COUPON = gql`
${getCoupon}
`
/* Config/Constants
============================================================================= */
const COD_PAYMENT = {
payment: 'COD',
label: 'COD',
index: 2,
icon: require('../../assets/images/cashIcon.png')
}
function Checkout() {
const route = useRoute()
const navigation = useNavigation()
const payObj = route.params ? route.params.PayObject : null
const [paymentMethod, setPaymentMethod] = useState(null)
const [coupan, setCoupan] = useState(null)
const [coupanError, setCoupanError] = useState(null)
const [discount, setDiscount] = useState(0)
const configuration = useContext(ConfigurationContext)
const { isLoggedIn, cart, profile, loadingProfile, clearCart } = useContext(
UserContext
)
const [mutate] = useMutation(GET_COUPON, {
onCompleted,
onError
})
const [mutateOrder, { loading: loadingOrderMutation }] = useMutation(
PLACEORDER,
{
onCompleted: placeOrderCompleted,
onError: errorPlaceOrder
}
)
useEffect(() => {
setPaymentMethod(payObj || COD_PAYMENT)
}, [payObj])
const address =
isLoggedIn && profile.addresses
? profile.addresses.filter(a => a.selected)[0]
: null
function applyCoupan() {
mutate({ variables: { coupon: coupan } })
}
function onCompleted({ coupon }) {
if (coupon) {
if (coupon.enabled) {
setDiscount(coupon.discount)
setCoupan(coupon.code)
FlashMessage({ message: 'Coupon Applied', type: 'success' })
} else {
setDiscount(0)
setCoupan(null)
setCoupanError('Invalid')
FlashMessage({ message: 'Coupon Failed', type: 'warning' })
}
}
}
function onError() {
setDiscount(0)
setCoupan(null)
setCoupanError('Invalid')
FlashMessage({ message: 'Invalid Coupon', type: 'warning' })
}
function validateOrder() {
if (!cart.length) {
FlashMessage({ message: 'Cart is empty !', type: 'warning' })
return false
}
if (!address) {
FlashMessage({
message: 'Set delivery address before checkout',
type: 'warning'
})
navigation.navigate('AddressList', { backScreen: 'Cart' })
return false
}
if (!paymentMethod) {
FlashMessage({
message: 'Set payment method before checkout',
type: 'warning'
})
return false
}
if (profile.phone.length < 1) {
navigation.navigate('EditingProfile', { backScreen: 'Cart' })
return false
}
return true
}
function checkPaymentMethod(currency) {
if (paymentMethod.payment === 'STRIPE') {
return stripeCurrencies.find(val => val.currency === currency)
}
if (paymentMethod.payment === 'PAYPAL') {
return paypalCurrencies.find(val => val.currency === currency)
}
return true
}
function transformOrder(cartData) {
return cartData.map(product => {
return {
productId: product._id,
product: product.product,
quantity: product.quantity,
image: product.image,
selectedAttributes: product.selectedAttributes,
price: parseFloat(product.price)
}
})
}
async function onPayment() {
if (checkPaymentMethod(configuration.currency)) {
const Items = transformOrder(cart)
// console.log('Items', JSON.stringify(Items))
mutateOrder({
variables: {
orderInput: Items,
paymentMethod: paymentMethod.payment,
couponCode: coupan,
address: {
label: address.label,
region: address.region,
city: address.city,
apartment: address.apartment,
building: address.building,
details: address.details
}
}
})
} else {
FlashMessage({
message: 'Payment not supported yet!',
type: 'warning'
})
}
}
async function clear() {
await clearCart()
}
function placeOrderCompleted(data) {
if (paymentMethod.payment === 'COD') {
clear()
navigation.reset({
routes: [
{ name: 'MainLanding' },
{
name: 'OrderDetail',
params: { _id: data.placeOrder._id, clearCart: true }
}
]
})
} else if (paymentMethod.payment === 'PAYPAL') {
navigation.replace('Paypal', {
_id: data.placeOrder.orderId,
currency: configuration.currency
})
} else if (paymentMethod.payment === 'STRIPE') {
navigation.replace('StripeCheckout', {
_id: data.placeOrder.orderId,
amount: data.placeOrder.orderAmount,
email: data.placeOrder.user.email,
currency: configuration.currency
})
}
}
function errorPlaceOrder(error) {
console.log('error', JSON.stringify(error))
FlashMessage({ message: JSON.stringify(error), type: 'warning' })
}
function calculatePrice(deliveryCharges = 0, withDiscount) {
let itemTotal = 0
cart.forEach(cartItem => {
if (!cartItem.price) {
return
}
itemTotal += cartItem.price * cartItem.quantity
})
if (withDiscount && discount) {
itemTotal = itemTotal - (discount / 100) * itemTotal
}
return (itemTotal + deliveryCharges).toFixed(2)
}
function renderItem(item, index) {
return (
<View key={index} style={styles.listItem}>
<View style={styles.productRow}>
<TextDefault textColor={colors.fontBlue}>
{item.quantity}x{' '}
</TextDefault>
<TextDefault textColor={colors.fontSecondColor}>
{item.product}
</TextDefault>
</View>
<TextDefault
textColor={colors.fontBlue}
style={{ maxWidth: '15%' }}
center>
{configuration.currencySymbol} {item.price * item.quantity}
</TextDefault>
</View>
)
}
return (
<SafeAreaView style={[styles.flex, styles.safeAreaStyle]}>
<View style={[styles.flex, styles.mainContainer]}>
<BackHeader title="Summary" backPressed={() => navigation.goBack()} />
{loadingProfile ? (
<Spinner />
) : (
<ScrollView
showsVerticalScrollIndicator={false}
style={styles.flex}
contentContainerStyle={styles.container}>
<View style={styles.body}>
<View style={styles.main_top}>
<View style={[styles.orders, styles.line]}>
<View style={styles.row}>
<TextDefault textColor={colors.fontBrown} H5>
{'My Orders'}
</TextDefault>
<TouchableOpacity
activeOpacity={0}
onPress={() => navigation.goBack()}>
<Feather
name="edit"
size={scale(18)}
color={colors.fontPlaceholder}
/>
</TouchableOpacity>
</View>
<View style={[styles.simpleRow, styles.padding]}>
<Image
source={require('../../assets/icons/delivery.png')}
style={{
height: verticalScale(13),
width: verticalScale(25)
}}
/>
<TextDefault
textColor={colors.fontBlue}
style={styles.deliveryDate}>
{' Delivery Expected : 3-4 days'}
</TextDefault>
</View>
{!!cart && cart.length > 0 && (
<View style={styles.items}>
{cart.map((item, index) => renderItem(item, index))}
</View>
)}
</View>
{isLoggedIn && (
<>
<View style={[styles.coupan, styles.line]}>
<TextDefault textColor={colors.fontBrown} H5>
{'Coupon'}
</TextDefault>
<View style={styles.coupanRow}>
<View style={styles.coupanInput}>
<TextField
error={coupanError}
value={coupan}
placeholder="Coupon"
onChange={event => {
setCoupan(event.nativeEvent.text.trim())
}}
/>
</View>
{!coupanError && discount > 0 ? (
<MainBtn
style={styles.coupanBtn}
onPress={() => {
if (coupan) {
setCoupan(null)
setCoupanError(null)
setDiscount(0)
}
}}
text={'Remove'}
/>
) : (
<MainBtn
style={styles.coupanBtn}
onPress={() => {
if (!coupan) setCoupanError('Invalid')
else {
setCoupanError(null)
applyCoupan()
}
}}
text={'Apply'}
/>
)}
</View>
</View>
<TouchableOpacity
style={[styles.address, styles.line]}
onPress={() => {
isLoggedIn &&
navigation.navigate('AddressList', {
backScreen: 'Cart'
})
}}>
<TextDefault textColor={colors.fontBrown} H5>
{'Deliver to'}
</TextDefault>
<View style={styles.addressDetail}>
<TextDefault textColor={colors.fontSecondColor}>
{profile.name}
</TextDefault>
<TextDefault textColor={colors.fontSecondColor}>
{profile.email}
</TextDefault>
<TextDefault textColor={colors.fontSecondColor}>
{profile.phone}
</TextDefault>
</View>
{address ? (
<View style={styles.borderBottom}>
<View style={styles.row}>
<TextDefault textColor={colors.fontMainColor}>
{address.region}
</TextDefault>
<Feather
name="edit"
size={scale(15)}
color={colors.fontThirdColor}
/>
</View>
<TextDefault textColor={colors.fontMainColor}>
{address.city},
</TextDefault>
<TextDefault textColor={colors.fontMainColor}>
{address.apartment}, {address.building}
</TextDefault>
{!!address.details && (
<TextDefault textColor={colors.fontMainColor}>
{address.details}
</TextDefault>
)}
</View>
) : (
<View style={styles.borderBottom}>
<View style={styles.row}>
<TextDefault textColor={colors.fontMainColor}>
Select Address
</TextDefault>
<Feather
name="edit"
size={scale(15)}
color={colors.fontThirdColor}
/>
</View>
</View>
)}
</TouchableOpacity>
<View style={styles.dealContainer}>
<View style={[styles.floatView]}>
<TextDefault
textColor={colors.fontSecondColor}
style={{ width: '70%' }}>
{'Payment Method'}
</TextDefault>
<TouchableOpacity
activeOpacity={0.7}
style={styles.changeText}
onPress={() =>
navigation.navigate('Payment', {
payment: paymentMethod
})
}>
<TextDefault
textColor={colors.buttonBackground}
right>
{'Change'}
</TextDefault>
</TouchableOpacity>
</View>
{paymentMethod === null ? (
<TouchableOpacity
style={styles.floatView}
onPress={() =>
navigation.navigate('Payment', {
payment: paymentMethod
})
}>
<AntDesign
name="plus"
size={scale(20)}
color={colors.buttonBackground}
/>
<TextDefault
textColor={colors.buttonBackground}
style={[alignment.PLsmall, { width: '70%' }]}>
{'Payment Method'}
</TextDefault>
</TouchableOpacity>
) : (
<TouchableOpacity
style={styles.floatView}
onPress={() =>
navigation.navigate('Payment', {
payment: paymentMethod
})
}>
<View style={{ width: '10%' }}>
<Image
resizeMode="cover"
style={styles.iconStyle}
source={paymentMethod.icon}
/>
</View>
<TextDefault
textColor={colors.buttonBackground}
style={[alignment.PLsmall, { width: '90%' }]}>
{paymentMethod.label}
</TextDefault>
</TouchableOpacity>
)}
</View>
</>
)}
</View>
<View style={styles.main_bot}>
<View style={[styles.subtotal_container, styles.line]}>
<View style={styles.row}>
<TextDefault textColor={colors.fontSecondColor} H5>
{'Sub Total'}
</TextDefault>
<TextDefault textColor={colors.fontMainColor} H5>
{configuration.currencySymbol} {calculatePrice(0, false)}
</TextDefault>
</View>
<View style={styles.row}>
<TextDefault textColor={colors.fontSecondColor} H5>
{'Delivery'}
</TextDefault>
<TextDefault textColor={colors.fontMainColor} H5>
{configuration.currencySymbol}{' '}
{parseFloat(configuration.deliveryCharges).toFixed(2)}
</TextDefault>
</View>
<View style={styles.row}>
<TextDefault textColor={colors.fontSecondColor} H5>
{'Discount'}
</TextDefault>
<TextDefault textColor={colors.fontMainColor} H5>
{'-'}
{configuration.currencySymbol}{' '}
{parseFloat(
calculatePrice(0, false) - calculatePrice(0, true)
).toFixed(2)}
</TextDefault>
</View>
</View>
<View style={styles.total_container}>
<View style={styles.row}>
<TextDefault
textColor={colors.fontMainColor}
H5
style={styles.text_bold}>
{'Total'}
</TextDefault>
<TextDefault textColor={colors.fontBlue} H5 bold>
{configuration.currencySymbol}{' '}
{calculatePrice(configuration.deliveryCharges, true)}
</TextDefault>
</View>
</View>
<View style={styles.submit_container}>
{isLoggedIn ? (
<BlueBtn
loading={loadingOrderMutation}
onPress={() => {
// navigation.navigate('OrderDetail')
if (validateOrder()) onPayment()
}}
text="Order Now"
/>
) : (
<BlueBtn
onPress={() =>
navigation.navigate('SignIn', { backScreen: 'Cart' })
}
text="Login/Create Account"
/>
)}
</View>
</View>
</View>
</ScrollView>
)}
</View>
<BottomTab screen="CART" />
</SafeAreaView>
)
}
export default Checkout
|
for(var i=0; i<=100; i++) {
if (i%2 === 0) {
console.log("even")
} else {
console.log("odd")
}
} |
import { combineReducers } from 'redux';
import { reducer } from '../reducers/place';
const rootReducer = combineReducers({
place: reducer
});
export default rootReducer; |
const fs = require('fs');
const path = require('path');
const shell = require('child_process').execSync;
exports.default = async context => {
const projectRoot = path.join(__dirname, '..');
const studioMainPath = path.join(projectRoot, 'projects', 'studio-main');
console.log('Remove Renderer...');
if (fs.existsSync(path.join(studioMainPath, 'renderer'))) {
shell(`rm -r ${path.join(studioMainPath, 'renderer')}`);
}
};
|
import React, { Component } from 'react';
import './style.css';
import ContBar from './../ContBar';
import Logo from './../Logo';
import Lightbox from 'react-image-lightbox';
import 'react-image-lightbox/style.css';
import Navigate from './../Navigate';
var acoes = [
"https://uploadiadep.s3.amazonaws.com/b6ab4396a6290a4376336c6238c02486-acao_social%20%20%2843%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/dc7042534aefaa03522344bf6fd3f949-acao_social%20%20%2864%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/0ba5763499678cb5e5e28410cf1cdfdf-acao_social%20%20%2866%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/144d76cca33aa00f59e199511a451660-acao_social%20%20%2845%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/159b254ded22a383f73b1081d741007d-acao_social%20%20%2848%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/f02a720d42b0ab442915249d4acbdd8a-acao_social%20%20%2867%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/a9ce494661e201f884b5090c76f8add5-acao_social%20%20%2849%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/98e6976998afe9c5dd176b524c95795f-acao_social%20%20%2847%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/08a5ec39669d1b589fbaa1d903697d6a-acao_social%20%20%2850%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/5a945d5589cee11e579b12878643f44f-acao_social%20%20%2851%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/998ae2b8f27ef30c7dafe624a3f43199-acao_social%20%20%2853%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/0e3f37981edcc9869a717ec15086cdec-acao_social%20%20%2852%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/ac9b2b246d946b0755d0468e9c40b59e-acao_social%20%20%2856%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/bf11158f588f8f1a2e4b9d0d70600332-acao_social%20%20%2846%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/974c074ac97264f764bb38261fa2279b-acao_social%20%20%2863%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/8a0ef32e909a206eef4e6d1bbe529d14-acao_social%20%20%2855%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/47bd185ecec80d78b69691f98b1c4ecb-acao_social%20%20%2865%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/02c77bb39b75c99985feed40ed953ce3-acao_social%20%20%2859%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/61f79f279c3dc8024f16fc63f1642463-acao_social%20%20%2854%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/ea53cd7a2cb2878303eedff8a51e3ae6-acao_social%20%20%2857%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/16162a97c9e3ecf0938a1eb7fcf91d83-acao_social%20%20%2858%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/59bd8fae50a6996970d0ec6fe7fc8ed3-acao_social%20%20%2861%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/2703501fe02dd0de872f8d8916d28359-acao_social%20%20%2862%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/ef2ddd94c8a4ba688f3b2db13341ab75-acao_social%20%20%2860%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/509aefcdd99eba9a88d2cf742d1c0a81-acao_social%20%20%2844%29.jpeg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/69fd71e572687bb25b6ced9e308cc304-acao_social%20%286%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/0a15764bfedd570f261fb0880a866198-acao_social%20%285%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/7371f890dbe9e01c6fabe57146453dc0-acao_social%20%283%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/2c0a367b2a02cc1810f3e229edde0c01-acao_social%20%287%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/aaa0de7f85b9f2b4c01f5f3074ac4b31-acao_social%20%284%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/d62c0e180c56420547a54c969b9f2c16-acao_social%20%2811%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/3fe5124845be4b9bf4baeb231a4ad040-acao_social%20%281%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/41cf9f8f2f951d9cee0b18fe9793fa0e-acao_social%20%288%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/0c401047e65d39fb16ccddbc75fb5aa0-acao_social%20%282%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/9ffd41f81fae078590b0b8c28370db81-acao_social%20%289%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/a99fdedbcdea93c1780a090d65a69f86-acao_social%20%2816%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/4b86ee68951d62da1a07e5865449e78d-acao_social%20%2812%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/420be496579269e2b6036468f6fe4836-acao_social%20%2813%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/e084e9afc3775bc8f6742a2f041b6c78-acao_social%20%2810%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/4ec3e7d425b0a74eb35a07e6410e60b9-acao_social%20%2820%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/573b50387a007277a3bde4379823c060-acao_social%20%2821%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/6dedf03484165f78fca2658b877427b0-acao_social%20%2815%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/04acd97cda4cd7b817005dd8417db1c5-acao_social%20%2822%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/7c681c1e856893fca9e5c19a95121ef6-acao_social%20%2823%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/150b3e687c42e008d8fd4e85155f88e7-acao_social%20%2824%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/7a39a32d957681b0e0ddedaef276f6c7-acao_social%20%2826%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/74698ca9c4248d7798eddd41fc0d8e62-acao_social%20%2814%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/5be924a14a69f6c4e480c4fd2efd3394-acao_social%20%2825%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/fce866dda282bf02a2fc25300f80a9fd-acao_social%20%2827%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/c4e20744363045bc5bb6fdeb8d651274-acao_social%20%2829%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/bea018085ca4acd23229681a1b2424b9-acao_social%20%2831%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/dbcb73a5e3d6576f8150baa58b244508-acao_social%20%2828%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/9956130a1d53fe53e51c28e3f169a9b7-acao_social%20%2830%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/3dee5ab913eaf9de05f1d5e5314f4cb0-acao_social%20%2818%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/963994f3517928217dfb7e3f859bf4f1-acao_social%20%2817%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/0433c2416418f353c576e6437dc36ba7-acao_social%20%2832%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/812aee3b2b79185bcd5c16b5cf6900cc-acao_social%20%2835%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/84587e021b772c35289b68f6d160387e-acao_social%20%2833%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/fb22db8e71564c169edc0576f9ab5449-acao_social%20%2837%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/35681086cd5d0645ec943c427e3d7fa6-acao_social%20%2836%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/ed4c6c63d2fa97a98b74e36759ae53f6-acao_social%20%2834%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/8c8e727a00609863aa56e1739e82224f-acao_social%20%2838%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/ef25ab8ea26b6afd6f7c579fc8a97fae-acao_social%20%2840%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/59e5f2c889a814339f38eebb14d1d121-acao_social%20%2839%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/aaab2abd2ca2bb37ba5ee62f4f007f17-acao_social%20%2841%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/33bad3e9ea8ca5607a65700853c82926-acao_social%20%2842%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/7396defed8bbe7525cff89f83f178054-acao_social%20%2819%29.jpg"
];
var missoes = [
"https://uploadiadep.s3.us-east-2.amazonaws.com/d2cac62e6a3e7b061f99dbf2437a9778-missoes%20%286%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/d391c09ceb8073cc3f3e77b75bbc5527-missoes%20%281%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/285762b1d9a5f744b4d86e9be105a541-missoes%20%285%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/ed746b45b90e2aa57cacf79d04c85889-missoes%20%284%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/3729c8d19561338877d577db37eda8ab-missoes%20%282%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/fede4e5aa01db5c76bd593555e83c05a-missoes%20%287%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/d7bc5089a5f8fe8fd0dbb66fb8556acd-missoes%20%2811%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/3a77f29dae1fdb14b8cfbce0c94f3c4f-missoes%20%288%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/bf36ebc0bc8ed65552c2c8aec1cb3abb-missoes%20%2810%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/ab43426430415d34853c78149f1d1c37-missoes%20%289%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/9c2f8ac9fb6aae38f4780f56db5d31e1-missoes%20%2812%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/eb315f003b96cc394924c26e2e702d96-missoes%20%283%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/56d41ca875a970bb5bbc60b8a9e85f39-missoes%20%2814%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/46b028b68d9241f9fe2bb4ec02bd363d-missoes%20%2815%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/69ea3334cc25a558428a9560222aabd9-missoes%20%2813%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/70a82605f2f2fbb181db3f610bc6d360-missoes%20%2818%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/d8ed2ada2e2a263c1706181673545186-missoes%20%2817%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/7b2e0bb7b0ffda8911f81e1f12a10e04-missoes%20%2820%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/d0a49703000c7095b20b874c080a92e0-missoes%20%2819%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/a58ffda0b6b4968f348f01b7aaec646b-missoes%20%2821%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/de62129fe7df146abe6845c506f38683-missoes%20%2824%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/13fa74117897d639527cd090d5935788-missoes%20%2826%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/b6d414e1850b6e19d5361332151cd938-missoes%20%2823%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/344f795cad76abea4ae89139c5892e7d-missoes%20%2825%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/e0b8a5593a35e8fdff364c204651788c-missoes%20%2828%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/d2cf78781b985d22098afe6c6461aed9-missoes%20%2822%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/1bf84687b301bc2c37680bd1cf27974c-missoes%20%2827%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/6aa23d486bd7e421b3f4250a8b843638-missoes%20%2830%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/c22efab750c9ca34bebee6815ee4162e-missoes%20%2829%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/4829df483c60fab8998e325dd4312b78-missoes%20%2816%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/19bc87a75322d8b928db299837c58e88-missoes%20%2832%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/a1051145e5ac59013af95449614d3a3f-missoes%20%2831%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/561a64c73279d1354ec8a7369c31c625-missoes%20%2836%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/cd8d6cc6f7597861a8e6a2b9de850015-missoes%20%2834%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/2baccd3d903428d3fbec663269398945-missoes%20%2839%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/a1b0ef48014239fce30bad4de7685abc-missoes%20%2835%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/331c40d4fac9ca2696a335dc0d35a8e0-missoes%20%2838%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/84e73ff7bc2d341eb8b971639ee2627f-missoes%20%2833%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/1945fd91d38c8545f4d0cc574badb596-missoes%20%2841%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/b17dd57c35efdce3f86cfb95c47070b7-missoes%20%2840%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/33b0c79fcbf0f8e542225407042709fb-missoes%20%2837%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/4cfd0903ba0b84aee146775c0d8bb620-missoes%20%2843%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/5aa655f9bddffd7ee77c06707adb63bf-missoes%20%2842%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/87bb2e759e0cbb42424b2231ee9a35e3-missoes%20%2848%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/e89488b703320167e44525df22b9c7fa-missoes%20%2847%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/0e0f2cc08eaed031be56f8e5e2338622-missoes%20%2844%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/465c586630cd471a243b2c5b9c86ea15-missoes%20%2845%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/f7455acb865f3e125d96dc2e1b8c60f9-missoes%20%2849%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/5f6d0a7e604462f5a8e4954b21e1dbfc-missoes%20%2851%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/2c94a03cb40b7e3a8d220f648b0acb85-missoes%20%2846%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/5d04911cb09bd2e706f76125b8eec242-missoes%20%2853%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/6360dd3c0d3cf45c91103bc6d40e4c87-missoes%20%2852%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/f6827137ee12f7e6ac2eb18f26a9fe04-missoes%20%2854%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/c6861222144f4f18e8e77f5ba1f8ed33-missoes%20%2850%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/da29b667107b37c17201dd5ae51155d8-missoes%20%2855%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/b2c584111907dcd507957f53b0d9c2f8-missoes%20%2856%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/311a2d956f05684402548e176a231c81-missoes%20%2860%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/e52fc3fb5350a6b16e12b04d49c1789f-missoes%20%2859%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/c11b2943e1da2a977888b7143bb1ea31-missoes%20%2857%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/c6a8356aac855bf9a6793fbdb3e34e26-missoes%20%2858%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/c1ab73d316257f091de2189eeb4d4c79-missoes%20%2861%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/9a5879f0ee78ec61766384f2ac1c8c8e-missoes%20%2862%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/f69a57f42cf1ca768297a5439dabea64-missoes%20%2863%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/558fec0402a735ad91fc627f9e27ae4c-missoes%20%2865%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/f444719da8758cc9bef360afe08b8607-missoes%20%2864%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/d9b9ac8ec9c6d58ae869a2c0e588f212-missoes%20%2866%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/0b8a482987cce2785e9983279b7d81bf-missoes%20%2869%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/ad758bb2f041279a5ad7813c1e680e84-missoes%20%2868%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/4223e1ce02da01aba9cc8e382f22fe18-missoes%20%2873%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/9b4f3696a9be729124fb08845432a012-missoes%20%2875%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/540674f868703627b2caf834368fa8c6-missoes%20%2874%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/3e94d4894f8ed92300f18c39cc8fb787-missoes%20%2878%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/8db7cc99987652d84e8a94fee134be8d-missoes%20%2876%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/68e29682afe4bb76a5354055a61c6172-missoes%20%2877%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/ca91f348cfe1d4ab83d57731d43e4f95-missoes%20%2867%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/a27c103680995c85abaa833303a827bd-missoes%20%2879%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/09657e04d414738aaa238036a6ccc24c-missoes%20%2880%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/0a2d12cef94e9ef067a37801866004d0-missoes%20%2881%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/e4dd3d085947a2e0436a133f9c16adf9-missoes%20%2882%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/ef3676c4037e3331cfa92da0511549ee-missoes%20%2884%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/260cdd809cf24c183c96388f68c6a6bc-missoes%20%2883%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/1ec5e94eb597d5fe4bcd690cb5fd865b-missoes%20%2885%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/f9bf59e6295a2009b0c4b56c2d327688-missoes%20%2871%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/bd5ffd71ccdad2ae5f97bd6ae7a455bf-missoes%20%2886%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/7e53a92119c7cac24e40651ca261e8b4-missoes%20%2870%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/72c02cc88873c4edeb1affbfb26f50cc-missoes%20%2887%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/0536b861e6efd7794e3a716a79a66d18-missoes%20%2889%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/97a8a3b29394a7a95df7c5afcd55d6ad-missoes%20%2890%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/7e0d9a7540bb626d8d763647a809d126-missoes%20%2891%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/5aae91f10d23801549411ef5f3a37179-missoes%20%2892%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/1d5f0c4ea06760d6afe6b6b8b5332121-missoes%20%2888%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/25b693f86740fcfb67a5b72a4eed3768-missoes%20%2893%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/4976c791fcdf3c4a81266574bae5108d-missoes%20%2895%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/124f75472d2bbe08612ce555adfe81e5-missoes%20%2894%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/ca41bedba8b563a58d7468aca1d2c5cc-missoes%20%2896%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/0aa1a2d556827e70bf80fe831488cb85-missoes%20%2899%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/c2e236db3f44f6df04ecbac812a34f5e-missoes%20%2898%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/5afb3b645b8ca97cd4a60fb58b600481-missoes%20%2897%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/f3af8f661413400e8a9b970634720b68-missoes%20%28101%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/f27b5d60b6b1472be8e53f35c95a516a-missoes%20%28100%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/e3cb09fbb96c5eac5eac1681338bd10f-missoes%20%28102%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/ea316d640062137a5a8b9936c8ab5e7e-missoes%20%28104%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/63e984d4b1636693b6fbd66f18b625ca-missoes%20%28103%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/62b1855c3d4b86c91179d76320dc92e2-missoes%20%28106%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/0e1a75510ef11fc804b453645ef644af-missoes%20%28105%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/c369c507382b95055cebc103f28e939d-missoes%20%28107%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/04e4e7c22b5901fcd716dee9c9b9c5dc-missoes%20%28108%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/6c59c9838a96e5285169da39e423daee-missoes%20%28109%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/2f283312912409a340a443e4273d05ba-missoes%20%28110%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/9fbd8e37d560af8ddc1912137a7245ec-missoes%20%28111%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/627e56ec7f8c30e79a1127502d550040-missoes%20%28113%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/8020725e176f4bd7bbde93b8084dc43c-missoes%20%28114%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/76806b38fc32c77c29556ea63096e6c4-missoes%20%28115%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/7bf1786e0e4deb5d8ad06e4599aa91f1-missoes%20%28116%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/5bee92b11213b06f4cc97ea39b2c2376-missoes%20%28112%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/2631df73762645d9f2c8835bf7ef4110-missoes%20%28117%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/7f89121f40d21fb287fe607ab6341fa7-missoes%20%28120%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/efa558fc3189be11272bac1b6780dae2-missoes%20%28118%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/b78cbbf1f4a4073a16d0172677a9c696-missoes%20%28123%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/85e96ae3ea19d1e31c256b2312c78980-missoes%20%28119%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/10ad5122140158f56569191aaa710d99-missoes%20%28121%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/8a6a58873cc85db960a7a5af9d1f6368-missoes%20%28124%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/19d269c1e394937b13978c2962150a94-missoes%20%28122%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/a6fef851d7ba540ac8936a438c7d69c0-missoes%20%28127%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/0b212b87c65ce699617f3490e77020ca-missoes%20%28126%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/578cc23782eef7ca11737c464cbd66c3-missoes%20%28125%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/2f389746843830b657473024ac66b12c-missoes%20%28133%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/7fb6b8e511711fdeee1d8376487b59e8-missoes%20%28128%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/46a82f67af914d10d4a527f9730f41d5-missoes%20%28129%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/5efb98929b94148096a06c2fb08f5c0f-missoes%20%28131%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/534c31af672b73a1a9e1d7fdf2a24f1b-missoes%20%28132%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/3c0bad2ed16747b4f27bf9e51555bb54-missoes%20%28136%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/f362e660d8f56fc4d417fa1041d8f3be-missoes%20%28134%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/e54b0df2b52be66c679667a42b39df3a-missoes%20%28137%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/6170f44bd7b347c191f1766bac7a3df9-missoes%20%28135%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/b95c9bc5260d99ac0ca5348c5036240c-missoes%20%28138%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/6b2b7329ee724c7669652ed82cbf49ca-missoes%20%28139%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/eb69212098553fb94b2157be6fbd70b6-missoes%20%28130%29.jpg",
"https://uploadiadep.s3.us-east-2.amazonaws.com/5bd1d5c752911efb7001a91e89671672-missoes%20%2872%29.jpg"
];
export default class AcaoPage extends Component{
constructor(props) {
super(props);
this.state = {
photoIndex1: 0,
photoIndex2: 0,
isOpen1: false,
isOpen2: false,
};
}
render(){
function toggle() {
var sec = document.getElementById('sec');
var nav = document.getElementById('navigation');
sec.classList.toggle('active');
nav.classList.toggle('active');
}
return(
<>
<section className="banner" id="sec">
<header>
<Logo/>
<div id="toggle" onClick={toggle}></div>
</header>
<div className="content">
<br/>
<br/>
<h2>Ação Social</h2>
<br/>
<br/>
<div className="galery">
<br/>
<h2>Mão Amiga <span>IADEP</span></h2>
<br/>
<br/>
<p>A Mão Amiga Iadep é um projeto social em que ajudamos os mais nessecitados e fazemos o ide do Senhor, e cumprimos a palavra visitar os orfãos e das viúvas! (Tiago 1:27)</p>
<br/>
<br/>
<img src={acoes[0]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 0 })} />
<img src={acoes[1]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 1 })} />
<img src={acoes[2]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 2 })} />
<img src={acoes[3]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 3 })} />
<img src={acoes[4]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 4 })} />
<img src={acoes[5]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 5 })} />
<img src={acoes[6]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 6 })} />
<img src={acoes[7]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 7 })} />
<img src={acoes[8]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 8 })} />
<img src={acoes[9]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 9 })} />
<img src={acoes[10]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 10 })} />
<img src={acoes[11]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 11 })} />
<img src={acoes[12]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 12 })} />
<img src={acoes[13]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 13 })} />
<img src={acoes[14]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 14 })} />
<img src={acoes[15]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 15 })} />
<img src={acoes[16]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 16 })} />
<img src={acoes[17]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 17 })} />
<img src={acoes[18]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 18 })} />
<img src={acoes[19]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 19 })} />
<img src={acoes[20]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 20 })} />
<img src={acoes[21]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 21 })} />
<img src={acoes[22]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 22 })} />
<img src={acoes[23]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 23 })} />
<img src={acoes[24]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 24 })} />
<img src={acoes[25]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 25 })} />
<img src={acoes[26]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 26 })} />
<img src={acoes[27]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 27 })} />
<img src={acoes[28]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 28 })} />
<img src={acoes[29]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 29 })} />
<img src={acoes[30]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 30 })} />
<img src={acoes[31]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 31 })} />
<img src={acoes[32]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 32 })} />
<img src={acoes[33]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 33 })} />
<img src={acoes[34]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 34 })} />
<img src={acoes[35]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 35 })} />
<img src={acoes[36]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 36 })} />
<img src={acoes[37]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 37 })} />
<img src={acoes[38]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 38 })} />
<img src={acoes[39]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 39 })} />
<img src={acoes[40]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 40 })} />
<img src={acoes[41]} onClick={() => this.setState({ isOpen1: true, photoIndex1: 41 })} />
<br/>
<br/>
<h2>Missões</h2>
<br/>
<br/>
<img src={missoes[0]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 0 })} />
<img src={missoes[1]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 1 })} />
<img src={missoes[2]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 2 })} />
<img src={missoes[3]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 3 })} />
<img src={missoes[4]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 4 })} />
<img src={missoes[5]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 5 })} />
<img src={missoes[6]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 6 })} />
<img src={missoes[7]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 7 })} />
<img src={missoes[8]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 8 })} />
<img src={missoes[9]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 9 })} />
<img src={missoes[10]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 10 })} />
<img src={missoes[11]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 11 })} />
<img src={missoes[12]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 12 })} />
<img src={missoes[13]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 13 })} />
<img src={missoes[14]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 14 })} />
<img src={missoes[15]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 15 })} />
<img src={missoes[16]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 16 })} />
<img src={missoes[17]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 17 })} />
<img src={missoes[18]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 18 })} />
<img src={missoes[19]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 19 })} />
<img src={missoes[20]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 20 })} />
<img src={missoes[21]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 21 })} />
<img src={missoes[22]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 22 })} />
<img src={missoes[23]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 23 })} />
<img src={missoes[24]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 24 })} />
<img src={missoes[25]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 25 })} />
<img src={missoes[26]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 26 })} />
<img src={missoes[27]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 27 })} />
<img src={missoes[28]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 28 })} />
<img src={missoes[29]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 29 })} />
<img src={missoes[30]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 30 })} />
<img src={missoes[31]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 31 })} />
<img src={missoes[32]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 32 })} />
<img src={missoes[33]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 33 })} />
<img src={missoes[34]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 34 })} />
<img src={missoes[35]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 35 })} />
<img src={missoes[36]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 36 })} />
<img src={missoes[37]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 37 })} />
<img src={missoes[38]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 38 })} />
<img src={missoes[39]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 39 })} />
<img src={missoes[40]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 40 })} />
<img src={missoes[41]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 41 })} />
<img src={missoes[42]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 42 })} />
<img src={missoes[43]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 43 })} />
<img src={missoes[44]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 44 })} />
<img src={missoes[45]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 45 })} />
<img src={missoes[46]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 46 })} />
<img src={missoes[47]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 47 })} />
<img src={missoes[48]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 48 })} />
<img src={missoes[49]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 49 })} />
<img src={missoes[50]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 50 })} />
<img src={missoes[51]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 51 })} />
<img src={missoes[52]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 52 })} />
<img src={missoes[53]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 53 })} />
<img src={missoes[54]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 54 })} />
<img src={missoes[40]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 40 })} />
<img src={missoes[41]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 41 })} />
<img src={missoes[42]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 42 })} />
<img src={missoes[43]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 43 })} />
<img src={missoes[44]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 44 })} />
<img src={missoes[45]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 45 })} />
<img src={missoes[46]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 46 })} />
<img src={missoes[47]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 47 })} />
<img src={missoes[48]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 48 })} />
<img src={missoes[49]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 49 })} />
<img src={missoes[50]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 50 })} />
<img src={missoes[51]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 51 })} />
<img src={missoes[52]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 52 })} />
<img src={missoes[53]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 53 })} />
<img src={missoes[54]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 54 })} />
<img src={missoes[55]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 55 })} />
<img src={missoes[56]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 56 })} />
<img src={missoes[57]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 57 })} />
<img src={missoes[58]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 58 })} />
<img src={missoes[59]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 59 })} />
<img src={missoes[60]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 60 })} />
<img src={missoes[61]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 61 })} />
<img src={missoes[62]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 62 })} />
<img src={missoes[63]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 63 })} />
<img src={missoes[64]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 64 })} />
<img src={missoes[65]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 65 })} />
<img src={missoes[66]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 66 })} />
<img src={missoes[67]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 67 })} />
<img src={missoes[68]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 68 })} />
<img src={missoes[69]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 69 })} />
<img src={missoes[70]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 70 })} />
<img src={missoes[71]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 71 })} />
<img src={missoes[72]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 72 })} />
<img src={missoes[73]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 73 })} />
<img src={missoes[74]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 74 })} />
<img src={missoes[75]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 75 })} />
<img src={missoes[76]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 76 })} />
<img src={missoes[77]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 77 })} />
<img src={missoes[78]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 78 })} />
<img src={missoes[79]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 79 })} />
<img src={missoes[80]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 80 })} />
<img src={missoes[81]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 81 })} />
<img src={missoes[82]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 82 })} />
<img src={missoes[83]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 83 })} />
<img src={missoes[84]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 84 })} />
<img src={missoes[85]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 85 })} />
<img src={missoes[86]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 86 })} />
<img src={missoes[87]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 87 })} />
<img src={missoes[88]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 88 })} />
<img src={missoes[89]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 89 })} />
<img src={missoes[90]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 90 })} />
<img src={missoes[91]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 91 })} />
<img src={missoes[92]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 92 })} />
<img src={missoes[93]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 93 })} />
<img src={missoes[94]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 94 })} />
<img src={missoes[95]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 95 })} />
<img src={missoes[96]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 96 })} />
<img src={missoes[97]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 97 })} />
<img src={missoes[98]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 98 })} />
<img src={missoes[99]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 99 })} />
<img src={missoes[100]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 100 })} />
<img src={missoes[101]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 101 })} />
<img src={missoes[102]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 102 })} />
<img src={missoes[103]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 103 })} />
<img src={missoes[104]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 104 })} />
<img src={missoes[105]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 105 })} />
<img src={missoes[106]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 106 })} />
<img src={missoes[107]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 107 })} />
<img src={missoes[108]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 108 })} />
<img src={missoes[109]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 109 })} />
<img src={missoes[110]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 110 })} />
<img src={missoes[111]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 111 })} />
<img src={missoes[112]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 112 })} />
<img src={missoes[113]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 113 })} />
<img src={missoes[114]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 114 })} />
<img src={missoes[115]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 115 })} />
<img src={missoes[116]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 116 })} />
<img src={missoes[117]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 117 })} />
<img src={missoes[118]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 118 })} />
<img src={missoes[119]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 119 })} />
<img src={missoes[120]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 120 })} />
<img src={missoes[121]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 121 })} />
<img src={missoes[122]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 122 })} />
<img src={missoes[123]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 123 })} />
<img src={missoes[124]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 124 })} />
<img src={missoes[125]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 125 })} />
<img src={missoes[126]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 126 })} />
<img src={missoes[127]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 127 })} />
<img src={missoes[128]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 128 })} />
<img src={missoes[129]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 129 })} />
<img src={missoes[130]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 130 })} />
<img src={missoes[131]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 131 })} />
<img src={missoes[132]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 132 })} />
<img src={missoes[133]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 133 })} />
<img src={missoes[134]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 134 })} />
<img src={missoes[135]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 135 })} />
<img src={missoes[136]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 136 })} />
<img src={missoes[137]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 137 })} />
<img src={missoes[138]} onClick={() => this.setState({ isOpen2: true, photoIndex2: 138 })} />
{this.state.isOpen1 && (
<Lightbox
mainSrc={acoes[this.state.photoIndex1]}
nextSrc={acoes[(this.state.photoIndex1 + 1) % acoes.length]}
prevSrc={acoes[(this.state.photoIndex1 + acoes.length - 1) % acoes.length]}
onCloseRequest={() => this.setState({ isOpen1: false })}
onMovePrevRequest={() =>
this.setState({
photoIndex1: (this.state.photoIndex1 + acoes.length - 1) % acoes.length,
})
}
onMoveNextRequest={() =>
this.setState({
photoIndex1: (this.state.photoIndex1 + 1) % acoes.length,
})
}
/>
)}
{this.state.isOpen2 && (
<Lightbox
mainSrc={missoes[this.state.photoIndex2]}
nextSrc={missoes[(this.state.photoIndex2 + 1) % missoes.length]}
prevSrc={missoes[(this.state.photoIndex2 + missoes.length - 1) % missoes.length]}
onCloseRequest={() => this.setState({ isOpen2: false })}
onMovePrevRequest={() =>
this.setState({
photoIndex2: (this.state.photoIndex2 + missoes.length - 1) % missoes.length,
})
}
onMoveNextRequest={() =>
this.setState({
photoIndex2: (this.state.photoIndex2 + 1) % missoes.length,
})
}
/>
)}
</div>
<ContBar/>
</div>
</section>
<Navigate />
</>
);
}
}
|
Magix.tmpl("app/views/myunion/overview","<vframe id=J_vf_os mx-view=\"app/views/myunion/overview_settlement\"> <div class=wrap-loading></div> </vframe> <vframe id=J_vf_ol mx-view=\"app/views/myunion/overview_list\"> <div class=wrap-loading></div> </vframe>");
KISSY.add('app/views/myunion/overview', function (S, Node, DOM, JSON, View, MM, Util, Offline) {
var $ = Node.all;
var storageKey = 'imessage' + window.UserInfo.memberid;
return View.extend({
init: function (e) {
this.manage('importData', e);
this.manage('offline', new Offline());
},
render: function () {
var me = this;
me.setViewPagelet({}, function () {
me._message();
});
},
_message: function () {
var me = this;
me.manage(MM.fetchAll([
{
name: 'get_tms_content',
urlParams: {
path: '/alp/union/pub/imessage.html',
encode: 'utf-8'
}
},
{ name: 'violation_info' }
], function (MesModel, ViolationModel) {
var message = MesModel.get('data').jsonString;
message = JSON.parse(message);
var messageId = message.id;
if (messageId != me._getOffline()) {
me._showMessage(message);
me._setOffline(messageId);
}
var ViolationData = ViolationModel.get('data');
var tipCnt = [];
if (ViolationData.haveViolation) {
tipCnt.push('\u4EB2\uFF0C\u60A8\u7684\u8D26\u6237\u6D89\u5ACC\u8FDD\u89C4\uFF0C\u5982\u9700\u67E5\u770B\u548C\u7533\u8BC9\uFF0C<a href="http://media.alimama.com/violation/violation_list.htm" target="_blank" class="color-orange">\u8BF7\u70B9\u6B64\u67E5\u770B</a>');
}
if (ViolationData.haveViolationNeedMaterial) {
tipCnt.push('\u60A8\u5DF2\u63D0\u4EA4\u7684\u7533\u8BC9\u6750\u6599\u4E0D\u5168\uFF0C\u8BF7\u53CA\u65F6\u8865\u5145\u63D0\u4EA4\u7533\u8BC9\u6750\u6599\uFF0C <a href="http://media.alimama.com/violation/violation_list.htm" target="_blank" class="color-orange mr10">\u70B9\u51FB\u53BB\u8865\u5145</a>');
}
if (ViolationData.isHighRiskUser) {
tipCnt.push('\u7CFB\u7EDF\u68C0\u6D4B\u5230\u60A8\u7684\u8D26\u53F7\u5B58\u5728\u6F5C\u5728\u98CE\u9669\u9700\u8981\u60A8\u8FDB\u884C\u4E8C\u6B21\u8BA4\u8BC1\uFF0C\u8BF7\u60A8\u52A1\u5FC5\u5728\u89C4\u5B9A\u65F6\u95F4<a href="http://media.alimama.com/verify/risk.htm" target="_blank" class="color-orange">\u70B9\u6B64\u8FDB\u5165</a>\u8BA4\u8BC1\u9875\u9762\u5B8C\u6210\u8BA4\u8BC1\u3002\u903E\u671F\u672A\u8BA4\u8BC1\u6216\u8BA4\u8BC1\u5931\u8D25\u8D26\u6237\u5C06\u7EC8\u6B62\u5408\u4F5C\uFF0C<a href="http://rule.alimama.com/#!/announce/business/detail?id=8307063&knowledgeid=6528139" target="_blank" class="color-orange">\u8BE6\u60C5\u70B9\u51FB</a>\u3002');
}
if (tipCnt.length) {
Util.showGlobalTip(tipCnt.join('<br/>'), '', '', '', true);
}
}));
},
_showMessage: function (message) {
var dialogWidth = 600;
var docWidth = DOM.docWidth();
var dialogLeft = (docWidth - dialogWidth) / 2;
var dialogConfig = {
start: {
left: dialogLeft,
top: -200,
opacity: 0
},
end: {
left: dialogLeft,
top: 0,
opacity: 1
},
width: dialogWidth
};
var viewName = 'app/views/myunion/imessage';
var viewOptions = message;
Util.showDialog(dialogConfig, viewName, viewOptions);
},
_getOffline: function () {
var me = this;
var offline = me.getManaged('offline');
return offline.getItem(storageKey) || '';
},
_setOffline: function (value) {
var me = this;
var offline = me.getManaged('offline');
offline.setItem(storageKey, value);
}
});
}, {
requires: [
'node',
'dom',
'json',
'mxext/view',
'app/models/modelmanager',
'app/util/util',
'gallery/offline/1.1/index',
'mxext/mmanager',
'app/models/model',
'app/models/basemodel',
'mxext/model',
'ajax',
'app/util/datepicker/datepicker',
'app/util/dialog/dialog',
'app/util/format/format',
'app/util/globaltip/globaltip',
'app/util/robot/sourceid',
'app/util/spmlog/spmlog',
'app/util/mathextend/mathextend',
'app/util/tooltip/tooltip',
'app/util/widgetds/widgetds',
'app/util/rank/rank',
'app/util/reporttip/reporttip',
'app/util/vcode/vcode',
'app/util/pagination/index',
'app/util/fields/fields',
'app/util/mouseevent/index',
'magix/vframe',
'magix/vom',
'magix/router',
'brix/gallery/datepicker/index',
'brix/gallery/calendar/index',
'brix/gallery/dialog/index',
'app/util/spmlog/pathmap'
]
}); |
// 设置用户token
export const SET_TOKEN = 'SET_TOKEN';
//登录
export const LOGIN = 'LOGIN';
//退出
export const LOGOUT = 'LOGOUT';
|
export default {
state: {
lists:[
{top:"与火星孩子的对话",path:"http://s3.music.126.net/mobile-new/img/index_icon_2x.png?5207a28c3767992ca4bb6d4887c74880=",bottom:"华晨宇-与火星孩子的对话"},
{top:"与火星孩子的对话",path:"http://s3.music.126.net/mobile-new/img/index_icon_2x.png?5207a28c3767992ca4bb6d4887c74880=",bottom:"华晨宇-与火星孩子的对话"},
{top:"与火星孩子的对话",path:"http://s3.music.126.net/mobile-new/img/index_icon_2x.png?5207a28c3767992ca4bb6d4887c74880=",bottom:"华晨宇-与火星孩子的对话"},
{top:"与火星孩子的对话",path:"http://s3.music.126.net/mobile-new/img/index_icon_2x.png?5207a28c3767992ca4bb6d4887c74880=",bottom:"华晨宇-与火星孩子的对话"},
{top:"与火星孩子的对话",path:"http://s3.music.126.net/mobile-new/img/index_icon_2x.png?5207a28c3767992ca4bb6d4887c74880=",bottom:"华晨宇-与火星孩子的对话"},
{top:"与火星孩子的对话",path:"http://s3.music.126.net/mobile-new/img/index_icon_2x.png?5207a28c3767992ca4bb6d4887c74880=",bottom:"华晨宇-与火星孩子的对话"},
{top:"与火星孩子的对话",path:"http://s3.music.126.net/mobile-new/img/index_icon_2x.png?5207a28c3767992ca4bb6d4887c74880=",bottom:"华晨宇-与火星孩子的对话"},
{top:"与火星孩子的对话",path:"http://s3.music.126.net/mobile-new/img/index_icon_2x.png?5207a28c3767992ca4bb6d4887c74880=",bottom:"华晨宇-与火星孩子的对话"},
{top:"与火星孩子的对话",path:"http://s3.music.126.net/mobile-new/img/index_icon_2x.png?5207a28c3767992ca4bb6d4887c74880=",bottom:"华晨宇-与火星孩子的对话"},
{top:"与火星孩子的对话",path:"http://s3.music.126.net/mobile-new/img/index_icon_2x.png?5207a28c3767992ca4bb6d4887c74880=",bottom:"华晨宇-与火星孩子的对话"},
]
},
mutations: {
goplay(){
this.$router.push("/playMusic")
}
},
actions: {},
modules: {
}
} |
const userProfile = document.getElementById("userProfile");
const userImg = document.querySelector("#userProfile img");
const username = document.querySelector(".username");
import { staticAssetsUrl } from "./config";
import { url } from "./config";
import axios from "axios";
import $ from "jquery";
import { showAlert, hideAlert } from "./showAlert";
export async function checkLoggedInUser(userId) {
// if (document.cookie && document.cookie.split("%")[2]) {
// const userId = document.cookie.split("%")[2].slice(2);
if (userId) {
const user = await findUser(userId);
if (user) {
updateUserOnUI(user);
return user;
}
}
}
// }
async function findUser(userId) {
try {
const response = await axios.get(`${url}api/v1/users/getMe`);
console.log(response);
const user = JSON.stringify(response.data.data);
localStorage.setItem("loggedInUser", user);
return response.data.data;
} catch (ex) {
// console.log(ex);
// showAlert("error", ex.response);
}
}
function updateUserOnUI(user) {
$("#userProfile img").attr(
"src",
`${staticAssetsUrl}img/users/${user.photo}`
);
username.textContent = user.name;
document.getElementById("userPic").removeAttribute("hidden");
document.getElementById("userInfo").removeAttribute("hidden");
welcomeMsg.setAttribute("hidden", true);
}
|
import React, { Component } from 'react'
import PostList from './PostList'
class HomeContent extends Component {
constructor() {
super()
this.postList = [
{ name: '测试' },
{ name: '测试' },
{ name: '测试' },
{ name: '测试' },
{ name: '测试' },
{ name: '测试' },
{ name: '测试' },
{ name: '测试' }
]
}
renderHeader() {
return (
<header className="header">
<h1 className="header-title">博客列表</h1>
<h3 className="header-subtitle">下面是一些文章的列表</h3>
</header>
)
}
renderContent() {
return <PostList postList={this.postList} />
}
renderButton() {
let showReadMore = this.postList.length > 6
return showReadMore ? (
<button className="button button-readmore">查看更多</button>
) : null
}
render() {
return (
<div className="home-content">
{this.renderHeader()}
{this.renderContent()}
{this.renderButton()}
</div>
)
}
}
export default HomeContent
|
import React, {Component} from 'react';
import {
View,
ScrollView,
Text,
StyleSheet,
Image,
ImageBackground,
TouchableOpacity,
Alert,
PermissionsAndroid,
} from 'react-native';
import {Header} from 'react-native-elements';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import ViewShot from 'react-native-view-shot';
import CameraRollExtended from 'react-native-store-photos-album';
import DiamondModel from '../components/DiamondModel';
import {BLUE} from '../config/constants';
export default class ModelScreen extends Component {
constructor(props) {
super(props);
this.state = {
imgUri: '',
};
}
requestCameraPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: 'My App Storage Permission',
message:
'My App needs access to your storage so you can save your photos',
},
);
console.log('granted = ', granted);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
this.takeScreenShot();
} else {
console.log('Camera permission denied');
}
} catch (err) {
console.log(err);
}
};
takeScreenShot = () => {
// eslint-disable-next-line react/no-string-refs
this.refs.viewShot.capture().then(uri => {
this.setState({imgUri: uri});
CameraRollExtended.saveToCameraRoll(
{uri, album: 'Diamond Models', fileName: Date.now() + '.jpg'},
'photo',
)
.then(img => Alert.alert('Success! Photo added to camera roll!', img))
.catch(error => {
Alert.alert('Something went wrong...');
console.log(error);
});
});
};
render() {
return (
<View style={{flex: 1}}>
<Header
containerStyle={styles.header}
leftComponent={
<Image
source={require('../assets/diamond.png')}
style={styles.headerImg}
/>
}
centerComponent={<Text style={styles.headerTxt}>Diamond Models</Text>}
rightComponent={
<TouchableOpacity onPress={this.requestCameraPermission}>
<Icon name={'camera-enhance'} style={styles.headerIcon} />
</TouchableOpacity>
}
/>
<ImageBackground
source={require('../assets/64002-edit-verypale.jpg')}
style={{width: '100%', height: '100%'}}
imageStyle={{resizeMode: 'stretch'}}>
<ScrollView
contentContainerStyle={{
marginTop: 30,
marginBottom: 60,
flexDirection: 'row',
justifyContent: 'center',
}}>
{/* eslint-disable-next-line react/no-string-refs */}
<ViewShot ref="viewShot" options={{format: 'jpg', quality: 0.9}}>
<ScrollView
horizontal={true}
contentContainerStyle={{marginTop: 0, marginBottom: 0}}>
<DiamondModel />
</ScrollView>
</ViewShot>
<Text>{'\n\n\n\n\n\n\n'}</Text>
</ScrollView>
</ImageBackground>
</View>
);
}
}
const styles = StyleSheet.create({
header: {
backgroundColor: BLUE,
padding: 20,
},
headerImg: {
width: 45,
height: 40,
},
headerTxt: {
color: 'white',
fontSize: 20,
},
headerIcon: {
fontSize: 45,
color: 'white',
},
});
|
var hoy;
var idsuccursales
window.onload = function () {
hoy = new Date();
//alert(hoy)
var dd = hoy.getDate();
var mm = hoy.getMonth() + 1; //hoy es 0!
var yyyy = hoy.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
hoy = yyyy + '-' + mm + '-' + dd;
$('#fechaentregas').val(hoy);
cargaralmacen();
var fechaentrega = $('#fechaentregas').val();
var d = new Date();
var dia = d.getDate();
var mes = d.getMonth()+1;
var anio= d.getFullYear()
var token = $("#token").val();
$.ajax({
url: '/faltanterafa',
headers: {'X-CSRF-TOKEN': token},
type: 'POST',
dataType: 'json',
data: {
// anio: anio,
mes : mes
},
contentType: 'application/json; charset=utf-8',
success: function ($route) {
var stock = [];
var faltante = [];
var etiqueta = [];
var colore = [];
var cantidad=[];
var cant,prod,falta,otro
$($route).each(
function(key, value) {
prod=value.producto;
cant = value.ideal;
stock.push(cant);
etiqueta.push(prod)
falta=value.faltante;
if(falta<0 )
{ falta=falta*-1 }
faltante.push(falta)
cantidad.push(value.cantidad)
}
);
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'STOCK ACTUAL VS IDEAL'
},
xAxis: {
categories: (function() {
var data = [];
// debugger
etiqueta.forEach(function(element) {
// debugger
data.push([ (element)]);
});
return data;
})()
},
yAxis: {
min: 0,
title: {
text: 'Productos Faltantes IRIS PUB'
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
},
legend: {
align: 'right',
x: -30,
verticalAlign: 'top',
y: 25,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
borderColor: '#CCC',
borderWidth: 1,
shadow: false
},
tooltip: {
headerFormat: '<b>{point.x}</b><br/>',
pointFormat: '{series.name}: {point.y}<br/>Total : {point.stackTotal}',
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
}
}
},
series: [{
name: 'ideal',
data: (function() {
var data = [];
// debugger
stock.forEach(function(element) {
data.push([ parseInt(element)]);
});
return data;
})()
}, {
name: 'faltante',
data: (function() {
var data = [];
//alert(stock.pop())
// debugger
faltante.forEach(function(element) {
// debugger
data.push([ parseInt(element)]);
});
return data;
})()
}, ]
});
}
});
/* $.ajax({
url: '/ventasusers',
headers: {'X-CSRF-TOKEN': token},
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function ($route) {
var valores = [];
var etiquetas = [];
var colores = [];
$($route).each(
function (key, value) {
var cant = value.total;
valores.push(cant);
var fecha = value.nombre;
var subcad = fecha.substring(0, 10) + "...";
etiquetas.push(subcad);
colores.push(dame_color_aleatorio());
}
);
var dataBarChart = {
labels: etiquetas,
datasets: [
{
label: "Bar dataset",
backgroundColor: colores,
fillColor: "#f7464a",
strokeColor: "#f7464a",
highlightFill: "rgba(70, 191, 189, 0.4)",
highlightStroke: "rgba(70, 191, 189, 0.9)",
data: valores
}
]
};
var trendingBarChart = document.getElementById('trending-bar-chart').getContext('2d');
window.trendingBarChart = new Chart(trendingBarChart).Bar(dataBarChart, {
scaleShowGridLines: true,
scaleGridLineColor: "#eceff1",
showScale: true,
animationSteps: 15,
tooltipTitleFontFamily: "'Roboto','Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // String - Tooltip title font declaration for the scale label
responsive: true
});
}
});*/
var datos = $('#datos');
$.ajax({
url: '/abc',
headers: {'X-CSRF-TOKEN': token},
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function ($route) {
// debugger
var valores = [];
var etiquetas = [];
var colores = [];
$($route).each(
function (key, value) {
// debugger
// var cant = value.total;
var cant = value.valorvendido2;
valores.push(cant);
var nombreproducto = value.nombrep2+'--'+value.clasificacion2;
var subcad = nombreproducto; //fecha.substring(0, 20);
etiquetas.push(subcad);
colores.push(dame_color_aleatorio());
//debugger
if(value.clasificacion2=='A')
{
datos.append("<tr>" +
"<td>" + value.nombrep2 + "</td>" +
"<td>" + value.preciopromediop2 + "</td>" +
"<td>" + value.unidadesvendidas2 + "</td>" +
"<td>" + value.valorvendido2 + "</td>" +
"<td>" + value.participacion2 + "</td>" +
"<td>" + value.participacionacumulada2 + "</td>" +
"<td bgcolor=red>" + value.clasificacion2 + "</td>" +
"</tr>");
}else
{
if(value.clasificacion2=='B')
{
datos.append("<tr>" +
"<td>" + value.nombrep2 + "</td>" +
"<td>" + value.preciopromediop2 + "</td>" +
"<td>" + value.unidadesvendidas2 + "</td>" +
"<td>" + value.valorvendido2 + "</td>" +
"<td>" + value.participacion2 + "</td>" +
"<td>" + value.participacionacumulada2 + "</td>" +
"<td bgcolor=yellow>" + value.clasificacion2 + "</td>" +
"</tr>");
} else {
if(value.clasificacion2=='C')
{
datos.append("<tr>" +
"<td>" + value.nombrep2 + "</td>" +
"<td>" + value.preciopromediop2 + "</td>" +
"<td>" + value.unidadesvendidas2 + "</td>" +
"<td>" + value.valorvendido2 + "</td>" +
"<td>" + value.participacion2 + "</td>" +
"<td>" + value.participacionacumulada2 + "</td>" +
"<td bgcolor=green>" + value.clasificacion2 + "</td>" +
"</tr>");
}
}
}
}
);
var data = {
labels: etiquetas,
datasets: [
{
label: "First dataset",
fillColor: "rgba(128, 222, 234, 0.6)",
strokeColor: "#ffffff",
pointColor: "#00bcd4",
pointStrokeColor: "#ffffff",
pointHighlightFill: "#ffffff",
pointHighlightStroke: "#ffffff",
data: valores
}
]
};
var trendingLineChart = document.getElementById("trending-line-chart").getContext("2d");
window.trendingLineChart = new Chart(trendingLineChart).Line(data, {
scaleShowGridLines: true, ///Boolean - Whether grid lines are shown across the chart
scaleGridLineColor: "rgba(255,255,255,0.4)", //String - Colour of the grid lines
scaleGridLineWidth: 1, //Number - Width of the grid lines
scaleShowHorizontalLines: true, //Boolean - Whether to show horizontal lines (except X axis)
scaleShowVerticalLines: false, //Boolean - Whether to show vertical lines (except Y axis)
bezierCurve: true, //Boolean - Whether the line is curved between points
bezierCurveTension: 0.4, //Number - Tension of the bezier curve between points
pointDot: true, //Boolean - Whether to show a dot for each point
pointDotRadius: 5, //Number - Radius of each point dot in pixels
pointDotStrokeWidth: 2, //Number - Pixel width of point dot stroke
pointHitDetectionRadius: 20, //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
datasetStroke: true, //Boolean - Whether to show a stroke for datasets
datasetStrokeWidth: 3, //Number - Pixel width of dataset stroke
datasetFill: true, //Boolean - Whether to fill the dataset with a colour
animationSteps: 15, // Number - Number of animation steps
animationEasing: "easeOutQuart", // String - Animation easing effect
tooltipTitleFontFamily: "'Roboto','Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // String - Tooltip title font declaration for the scale label
scaleFontSize: 12, // Number - Scale label font size in pixels
scaleFontStyle: "normal", // String - Scale label font weight style
scaleFontColor: "#fff", // String - Scale label font colour
tooltipEvents: ["mousemove", "touchstart", "touchmove"], // Array - Array of string names to attach tooltip events
tooltipFillColor: "rgba(255,255,255,0.8)", // String - Tooltip background colour
tooltipTitleFontFamily: "'Roboto','Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // String - Tooltip title font declaration for the scale label
tooltipFontSize: 12, // Number - Tooltip label font size in pixels
tooltipFontColor: "#000", // String - Tooltip label font colour
tooltipTitleFontFamily: "'Roboto','Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // String - Tooltip title font declaration for the scale label
tooltipTitleFontSize: 14, // Number - Tooltip title font size in pixels
tooltipTitleFontStyle: "bold", // String - Tooltip title font weight style
tooltipTitleFontColor: "#000", // String - Tooltip title font colour
tooltipYPadding: 8, // Number - pixel width of padding around tooltip text
tooltipXPadding: 16, // Number - pixel width of padding around tooltip text
tooltipCaretSize: 10, // Number - Size of the caret on the tooltip
tooltipCornerRadius: 6, // Number - Pixel radius of the tooltip border
tooltipXOffset: 10, // Number - Pixel offset from point x to tooltip edge
responsive: true
});
}
});
///////////////////////////////////
var datos22 = $('#datos22');
$.ajax({
url: '/analisisabc',
headers: {'X-CSRF-TOKEN': token},
dataType: 'json',
type: 'GET',
contentType: 'application/json; charset=utf-8',
success: function ($route) {
debugger
var valores = [];
var etiquetas = [];
var colores = [];
$($route).each(
function (key, value) {
debugger
// var cant = value.total;
//var cant = value.valorvendido2;
//valores.push(cant);
//var nombreproducto = value.nombrep2+'--'+value.clasificacion2;
//var subcad = nombreproducto; //fecha.substring(0, 20);
//etiquetas.push(subcad);
//colores.push(dame_color_aleatorio());
debugger
if(value.participacion=='A')
{
datos22.append("<tr>" +
"<td>" + value.participacion_estimada + "</td>" +
"<td bgcolor=red>" + value.participacion + "</td>" +
"<td>" + value.n + "</td>" +
"<td>" + value.participacionn + "</td>" +
"<td>" + value.ventas + "</td>" +
"<td>" + value.participacionventas + "</td>" +
"</tr>");
}else
{
if(value.participacion=='B')
{
datos22.append("<tr>" +
"<td>" + value.participacion_estimada + "</td>" +
"<td bgcolor=yellow>" + value.participacion + "</td>" +
"<td>" + value.n + "</td>" +
"<td>" + value.participacionn + "</td>" +
"<td>" + value.ventas + "</td>" +
"<td>" + value.participacionventas + "</td>" +
"</tr>");
} else {
if(value.participacion=='C')
{
datos22.append("<tr>" +
"<td>" + value.participacion_estimada + "</td>" +
"<td bgcolor=green>" + value.participacion + "</td>" +
"<td>" + value.n + "</td>" +
"<td>" + value.participacionn + "</td>" +
"<td>" + value.ventas + "</td>" +
"<td>" + value.participacionventas + "</td>" +
"</tr>");
}
}
}
}
);
}
});
///////////////////////////////////
var doughnutData = [];
var listacategorias = $("#listacategorias");
$.ajax({
url: '/productstipo',
headers: {'X-CSRF-TOKEN': token},
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function ($route) {
$($route).each(
function (key, value) {
var color = dame_color_aleatorio();
listacategorias.append("<div class='col s6 m6 l4'>" +
"<i class='mdi-action-bookmark' style='color: " + color + ";'></i><strong>" +
value.categoria + "</strong>"
+ "</div>");
var datos = {
value: value.total,
color: color,
highlight: "rgba(70, 191, 189, 0.4)",
label: value.categoria
};
doughnutData.push(datos);
}
);
var doughnutChart = document.getElementById("doughnut-chart").getContext("2d");
window.myDoughnut = new Chart(doughnutChart).Doughnut(doughnutData, {
segmentStrokeColor: "#fff",
tooltipTitleFontFamily: "'Roboto','Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // String - Tooltip title font declaration for the scale label
percentageInnerCutout: 50,
animationSteps: 15,
segmentStrokeWidth: 4,
animateScale: true,
percentageInnerCutout : 60,
responsive: true
});
}
});
/*$.ajax({
url: '/ventasmes',
headers: {'X-CSRF-TOKEN': token},
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function ($route) {
var valores = [];
var etiquetas = [];
var colores = [];
$($route).each(
function (key, value) {
var cant = value.contador;
valores.push(cant);
var fecha = value.anno + "-" + dame_mes(value.mes);
etiquetas.push(fecha);
colores.push(dame_color_aleatorio());
}
);
var lineChartData = {
labels: etiquetas,
datasets: [
{
label: "My dataset",
fillColor: "rgba(255,255,255,0)",
strokeColor: "#fdb45c ",
pointColor: "#fdb45c",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: valores
}
]
};
var lineChart = document.getElementById("line-chart").getContext("2d");
window.lineChart = new Chart(lineChart).Line(lineChartData, {
scaleShowGridLines: true,
scaleGridLineColor: "#eceff1",
bezierCurve: false,
scaleFontSize: 12,
scaleFontStyle: "normal",
scaleFontColor: "#000",
responsive: true
});
}
});*/
var datosMensuales = $('#datos-mensuales');
$.ajax({
url: '/ventasmes',
headers: {'X-CSRF-TOKEN': token},
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function ($route) {
var valores = [];
var etiquetas = [];
var colores = [];
$($route).each(
function (key, value) {
var cant = value.total;
valores.push(cant);
var fecha = value.anno + "-" + dame_mes(value.mes);
etiquetas.push(fecha);
colores.push(dame_color_aleatorio());
datosMensuales.append("<tr>" +
"<td>" + fecha + "</td>" +
"<td>" + value.contador + "</td>" +
"<td>" + value.total + " Bs.</td>" +
"</tr>");
}
);
var data = {
labels: etiquetas,
datasets: [
{
label: "First dataset",
fillColor: "rgba(128, 222, 234, 0.2)",
strokeColor: "#ffffff",
pointColor: "orange",
pointStrokeColor: "#ffffff",
pointHighlightFill: "#ffffff",
pointHighlightStroke: "#ffffff",
data: valores
}
]
};
var trendingLineChart = document.getElementById("trending-line-chart2").getContext("2d");
window.trendingLineChart = new Chart(trendingLineChart).Line(data, {
scaleShowGridLines: true, ///Boolean - Whether grid lines are shown across the chart
scaleGridLineColor: "rgba(255,255,255,0.4)", //String - Colour of the grid lines
scaleGridLineWidth: 1, //Number - Width of the grid lines
scaleShowHorizontalLines: true, //Boolean - Whether to show horizontal lines (except X axis)
scaleShowVerticalLines: false, //Boolean - Whether to show vertical lines (except Y axis)
bezierCurve: true, //Boolean - Whether the line is curved between points
bezierCurveTension: 0.4, //Number - Tension of the bezier curve between points
pointDot: true, //Boolean - Whether to show a dot for each point
pointDotRadius: 5, //Number - Radius of each point dot in pixels
pointDotStrokeWidth: 2, //Number - Pixel width of point dot stroke
pointHitDetectionRadius: 20, //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
datasetStroke: true, //Boolean - Whether to show a stroke for datasets
datasetStrokeWidth: 3, //Number - Pixel width of dataset stroke
datasetFill: true, //Boolean - Whether to fill the dataset with a colour
animationSteps: 15, // Number - Number of animation steps
animationEasing: "easeOutQuart", // String - Animation easing effect
tooltipTitleFontFamily: "'Roboto','Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // String - Tooltip title font declaration for the scale label
scaleFontSize: 12, // Number - Scale label font size in pixels
scaleFontStyle: "normal", // String - Scale label font weight style
scaleFontColor: "#fff", // String - Scale label font colour
tooltipEvents: ["mousemove", "touchstart", "touchmove"], // Array - Array of string names to attach tooltip events
tooltipFillColor: "rgba(255,255,255,0.8)", // String - Tooltip background colour
tooltipTitleFontFamily: "'Roboto','Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // String - Tooltip title font declaration for the scale label
tooltipFontSize: 12, // Number - Tooltip label font size in pixels
tooltipFontColor: "#000", // String - Tooltip label font colour
tooltipTitleFontFamily: "'Roboto','Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // String - Tooltip title font declaration for the scale label
tooltipTitleFontSize: 14, // Number - Tooltip title font size in pixels
tooltipTitleFontStyle: "bold", // String - Tooltip title font weight style
tooltipTitleFontColor: "#000", // String - Tooltip title font colour
tooltipYPadding: 8, // Number - pixel width of padding around tooltip text
tooltipXPadding: 16, // Number - pixel width of padding around tooltip text
tooltipCaretSize: 10, // Number - Size of the caret on the tooltip
tooltipCornerRadius: 6, // Number - Pixel radius of the tooltip border
tooltipXOffset: 10, // Number - Pixel offset from point x to tooltip edge
responsive: true
});
}
});
$.ajax({
url: '/ventastipopago',
headers: {'X-CSRF-TOKEN': token},
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function ($route) {
var valores = [];
var etiquetas = [];
$($route).each(
function (key, value) {
var cant = value.total;
valores.push(cant);
var fecha = value.formaPago;
if (value.formaPago == "Tarjeta de Credito") {
fecha = "T. Credito";
}
if (value.formaPago == "Tarjeta de Debito") {
fecha = "T. Debito";
}
if (value.formaPago == "Deposito Banco") {
fecha = "D. Banco";
}
etiquetas.push(fecha);
}
);
var dataBarChart = {
labels: etiquetas,
datasets: [
{
label: "Bar dataset",
fillColor: "#00b0ff",
strokeColor: "#00b0ff",
highlightFill: "rgba(70, 191, 189, 0.4)",
highlightStroke: "rgba(70, 191, 189, 0.9)",
data: valores
}
]
};
var trendingBarChart = document.getElementById('trending-bar-chart2').getContext('2d');
window.trendingBarChart = new Chart(trendingBarChart).Bar(dataBarChart, {
scaleShowGridLines: true,
scaleGridLineColor: "#eceff1",
showScale: true,
animationSteps: 15,
tooltipTitleFontFamily: "'Roboto','Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // String - Tooltip title font declaration for the scale label
responsive: true
});
}
});
var datosporductos = $('#datos-top-productos');
$.ajax({
url: '/topproductos',
headers: {'X-CSRF-TOKEN': token},
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function ($route) {
var valores = [];
var etiquetas = [];
$($route).each(
function (key, value) {
var cant = value.Cantidadvendida;
valores.push(cant);
var fecha = value.Producto;
etiquetas.push(fecha);
datosporductos.append("<tr>" +
"<td>" + value.Producto + "</td>" +
"<td>" + value.codigoDeBarra + "</td>" +
"<td>" + value.color + "</td>" +
"<td>" + value.tamano + "</td>" +
"<td>" + value.Cantidadvendida + "</td>" +
"<td>" + value.ImporteTotal + " Bs.</td>" +
"</tr>");
}
);
var lineChartData = {
labels: etiquetas,
datasets: [
{
label: "My dataset",
fillColor: "rgba(255,255,255,0.1)",
strokeColor: "#fff ",
pointColor: "#fff",
pointStrokeColor: "e91e63",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: valores
}
]
};
var lineChart = document.getElementById("line-chart2").getContext("2d");
window.lineChart = new Chart(lineChart).Line(lineChartData, {
scaleShowGridLines: true,
scaleGridLineColor: "rgba(255,255,255,0.4)",
bezierCurve: false,
scaleFontSize: 12,
scaleFontStyle: "normal",
scaleFontColor: "#fff",
responsive: true
});
}
});
var doughnutData2 = [];
var listaclientefacturas = $("#listaclientefacturas");
var datosclientesfacturas = $('#datos-cliente-facturas');
$.ajax({
url: '/topclientesfactura',
headers: {'X-CSRF-TOKEN': token},
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function ($route) {
$($route).each(
function (key, value) {
var color = dame_color_aleatorio();
listaclientefacturas.append("<div class='col s6 m6 l4'>" +
"<i class='mdi-action-bookmark' style='color: " + color + ";'></i><strong>" +
value.razonSocial + "</strong>"
+ "</div>");
datosclientesfacturas.append("<tr>" +
"<td>" + value.razonSocial + "</td>" +
"<td>" + value.nit + "</td>" +
"<td>" + value.cantidad + "</td>" +
"<td>" + value.total + "</td>" +
"</tr>");
var datos = {
value: value.total,
color: color,
hhighlight: "rgba(70, 191, 189, 0.4)",
label: value.razonSocial
};
doughnutData2.push(datos);
}
);
var doughnutChart = document.getElementById("doughnut-chart2").getContext("2d");
window.myDoughnut = new Chart(doughnutChart).Doughnut(doughnutData2, {
segmentStrokeColor: "#fff",
tooltipTitleFontFamily: "'Roboto','Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // String - Tooltip title font declaration for the scale label
percentageInnerCutout: 50,
animationSteps: 15,
segmentStrokeWidth: 4,
animateScale: true,
percentageInnerCutout : 60,
responsive: true
});
}
});
var doughnutData3 = [];
var listaclientesventas = $("#listaclientesventas");
var datosclientesventas = $('#datos-cliente-ventas');
$.ajax({
url: '/topclientesventas',
headers: {'X-CSRF-TOKEN': token},
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function ($route) {
$($route).each(
function (key, value) {
if (value.cliente == "SIN NOMBRE") {
} else {
var color = dame_color_aleatorio();
listaclientesventas.append("<div class='col s6 m6 l4'>" +
"<i class='mdi-action-bookmark' style='color: " + color + ";'></i><strong>" +
value.cliente + "</strong>"
+ "</div>");
datosclientesventas.append("<tr>" +
"<td>" + value.cliente + "</td>" +
"<td>" + value.NIT + "</td>" +
"<td>" + value.cantidad + "</td>" +
"<td>" + value.totalventa + "</td>" +
"</tr>");
var datos = {
value: value.totalventa,
color: color,
highlight: "rgba(70, 191, 189, 0.4)",
label: value.cliente
};
doughnutData3.push(datos);
}
}
);
var doughnutChart = document.getElementById("doughnut-chart3").getContext("2d");
window.myDoughnut = new Chart(doughnutChart).Doughnut(doughnutData3, {
segmentStrokeColor: "#fff",
tooltipTitleFontFamily: "'Roboto','Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // String - Tooltip title font declaration for the scale label
percentageInnerCutout: 50,
animationSteps: 15,
segmentStrokeWidth: 4,
animateScale: true,
percentageInnerCutout : 60,
responsive: true
});
}
});
};
/* METODOS PARA LLAMAR DESDE INFERFACE RAFA */
function consultar()
{
debugger
var mes = $("#mes").val();
var anio = $("#anio").val();
// var almacen = $("#almacencombo").val();
var almacen = 1;
// return 0
var token = $("#token").val();
var datosABC = $('#datos');
$.ajax({
url: '/analisismetodo/'+mes+ '/'+anio+'/'+almacen,
headers: {'X-CSRF-TOKEN': token},
type: 'GET',
dataType: 'json',
success: function ($route) {
debugger
var valores = [];
var etiquetas = [];
var colores = [];
var cant,prod,falta,otro
$($route).each(
function(key, value) {
debugger
if ((value.mensaje == "El anio q consulta no existe")||
(value.mensaje == "El anio y mes q consulta no pueden ser cero")||
(value.mensaje=="El mes q consulta no existe")) {
return swal({title: "Bien!",
text: value.mensaje,
type: "warning",
showConfirmButton: false,
closeOnConfirm: false,
timer: 1000});
}else {
var cant = value.valorvendido2;
valores.push(cant);
var nombreproducto = value.nombrep2+'--'+value.clasificacion2;
var subcad = nombreproducto; //fecha.substring(0, 20);
etiquetas.push(subcad);
colores.push(dame_color_aleatorio());
//debugger
if(value.clasificacion2=='A')
{
datosABC.append("<tr>" +
"<td>" + value.nombrep2 + "</td>" +
"<td>" + value.preciopromediop2 + "</td>" +
"<td>" + value.unidadesvendidas2 + "</td>" +
"<td>" + value.valorvendido2 + "</td>" +
"<td>" + value.participacion2 + "</td>" +
"<td>" + value.participacionacumulada2 + "</td>" +
"<td bgcolor=red>" + value.clasificacion2 + "</td>" +
"</tr>");
}else
{
if(value.clasificacion2=='B')
{
datosABC.append("<tr>" +
"<td>" + value.nombrep2 + "</td>" +
"<td>" + value.preciopromediop2 + "</td>" +
"<td>" + value.unidadesvendidas2 + "</td>" +
"<td>" + value.valorvendido2 + "</td>" +
"<td>" + value.participacion2 + "</td>" +
"<td>" + value.participacionacumulada2 + "</td>" +
"<td bgcolor=yellow>" + value.clasificacion2 + "</td>" +
"</tr>");
} else {
if(value.clasificacion2=='C')
{
datosABC.append("<tr>" +
"<td>" + value.nombrep2 + "</td>" +
"<td>" + value.preciopromediop2 + "</td>" +
"<td>" + value.unidadesvendidas2 + "</td>" +
"<td>" + value.valorvendido2 + "</td>" +
"<td>" + value.participacion2 + "</td>" +
"<td>" + value.participacionacumulada2 + "</td>" +
"<td bgcolor=green>" + value.clasificacion2 + "</td>" +
"</tr>");
}
}
}
}
}
);
calcular()
//////AUI EMPIEZAN LAS GRAFICAS
var data = {
labels: etiquetas,
datasets: [
{
label: "First dataset",
fillColor: "rgba(128, 222, 234, 0.6)",
strokeColor: "#ffffff",
pointColor: "#00bcd4",
pointStrokeColor: "#ffffff",
pointHighlightFill: "#ffffff",
pointHighlightStroke: "#ffffff",
data: valores
}
]
};
var trendingLineChart = document.getElementById("trending-line-chart").getContext("2d");
window.trendingLineChart = new Chart(trendingLineChart).Line(data, {
scaleShowGridLines: true, ///Boolean - Whether grid lines are shown across the chart
scaleGridLineColor: "rgba(255,255,255,0.4)", //String - Colour of the grid lines
scaleGridLineWidth: 1, //Number - Width of the grid lines
scaleShowHorizontalLines: true, //Boolean - Whether to show horizontal lines (except X axis)
scaleShowVerticalLines: false, //Boolean - Whether to show vertical lines (except Y axis)
bezierCurve: true, //Boolean - Whether the line is curved between points
bezierCurveTension: 0.4, //Number - Tension of the bezier curve between points
pointDot: true, //Boolean - Whether to show a dot for each point
pointDotRadius: 5, //Number - Radius of each point dot in pixels
pointDotStrokeWidth: 2, //Number - Pixel width of point dot stroke
pointHitDetectionRadius: 20, //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
datasetStroke: true, //Boolean - Whether to show a stroke for datasets
datasetStrokeWidth: 3, //Number - Pixel width of dataset stroke
datasetFill: true, //Boolean - Whether to fill the dataset with a colour
animationSteps: 15, // Number - Number of animation steps
animationEasing: "easeOutQuart", // String - Animation easing effect
tooltipTitleFontFamily: "'Roboto','Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // String - Tooltip title font declaration for the scale label
scaleFontSize: 12, // Number - Scale label font size in pixels
scaleFontStyle: "normal", // String - Scale label font weight style
scaleFontColor: "#fff", // String - Scale label font colour
tooltipEvents: ["mousemove", "touchstart", "touchmove"], // Array - Array of string names to attach tooltip events
tooltipFillColor: "rgba(255,255,255,0.8)", // String - Tooltip background colour
tooltipTitleFontFamily: "'Roboto','Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // String - Tooltip title font declaration for the scale label
tooltipFontSize: 12, // Number - Tooltip label font size in pixels
tooltipFontColor: "#000", // String - Tooltip label font colour
tooltipTitleFontFamily: "'Roboto','Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // String - Tooltip title font declaration for the scale label
tooltipTitleFontSize: 14, // Number - Tooltip title font size in pixels
tooltipTitleFontStyle: "bold", // String - Tooltip title font weight style
tooltipTitleFontColor: "#000", // String - Tooltip title font colour
tooltipYPadding: 8, // Number - pixel width of padding around tooltip text
tooltipXPadding: 16, // Number - pixel width of padding around tooltip text
tooltipCaretSize: 10, // Number - Size of the caret on the tooltip
tooltipCornerRadius: 6, // Number - Pixel radius of the tooltip border
tooltipXOffset: 10, // Number - Pixel offset from point x to tooltip edge
responsive: true
});
}
});
}
function calcular(mes,anio,almacen)
{
$('#datos22').empty();
var datos22 = $('#datos22');
if(mes==0 && anio>0) // AQUI ES MES==0 Y ANIO>0
{
$.ajax({
url: '/analisisabc_anioalmacen'+'/'+anio+'/'+almacen,
headers: {'X-CSRF-TOKEN': token},
dataType: 'json',
type: 'GET',
contentType: 'application/json; charset=utf-8',
success: function ($route) {
debugger
var valores = [];
var etiquetas = [];
var colores = [];
$($route).each(
function (key, value) {
debugger
// var cant = value.total;
//var cant = value.valorvendido2;
//valores.push(cant);
//var nombreproducto = value.nombrep2+'--'+value.clasificacion2;
//var subcad = nombreproducto; //fecha.substring(0, 20);
//etiquetas.push(subcad);
//colores.push(dame_color_aleatorio());
debugger
if(value.participacion=='A')
{
datos22.append("<tr>" +
"<td>" + value.participacion_estimada + "</td>" +
"<td bgcolor=red>" + value.participacion + "</td>" +
"<td>" + value.n + "</td>" +
"<td>" + value.participacionn + "</td>" +
"<td>" + value.ventas + "</td>" +
"<td>" + value.participacionventas + "</td>" +
"</tr>");
}else
{
if(value.participacion=='B')
{
datos22.append("<tr>" +
"<td>" + value.participacion_estimada + "</td>" +
"<td bgcolor=yellow>" + value.participacion + "</td>" +
"<td>" + value.n + "</td>" +
"<td>" + value.participacionn + "</td>" +
"<td>" + value.ventas + "</td>" +
"<td>" + value.participacionventas + "</td>" +
"</tr>");
} else {
if(value.participacion=='C')
{
datos22.append("<tr>" +
"<td>" + value.participacion_estimada + "</td>" +
"<td bgcolor=green>" + value.participacion + "</td>" +
"<td>" + value.n + "</td>" +
"<td>" + value.participacionn + "</td>" +
"<td>" + value.ventas + "</td>" +
"<td>" + value.participacionventas + "</td>" +
"</tr>");
}
}
}
}
);
}
});
}else
{
if (mes>0 && anio>0) ////AQUI ES MES>0 Y ANIO==0
{
$.ajax({
url: '/analisisabc_aniomesalmacen'+'/'+mes+'/'+anio+'/'+almacen,
headers: {'X-CSRF-TOKEN': token},
dataType: 'json',
type: 'GET',
contentType: 'application/json; charset=utf-8',
success: function ($route) {
debugger
var valores = [];
var etiquetas = [];
var colores = [];
$($route).each(
function (key, value) {
debugger
// var cant = value.total;
//var cant = value.valorvendido2;
//valores.push(cant);
//var nombreproducto = value.nombrep2+'--'+value.clasificacion2;
//var subcad = nombreproducto; //fecha.substring(0, 20);
//etiquetas.push(subcad);
//colores.push(dame_color_aleatorio());
debugger
if(value.participacion=='A')
{
datos22.append("<tr>" +
"<td>" + value.participacion_estimada + "</td>" +
"<td bgcolor=red>" + value.participacion + "</td>" +
"<td>" + value.n + "</td>" +
"<td>" + value.participacionn + "</td>" +
"<td>" + value.ventas + "</td>" +
"<td>" + value.participacionventas + "</td>" +
"</tr>");
}else
{
if(value.participacion=='B')
{
datos22.append("<tr>" +
"<td>" + value.participacion_estimada + "</td>" +
"<td bgcolor=yellow>" + value.participacion + "</td>" +
"<td>" + value.n + "</td>" +
"<td>" + value.participacionn + "</td>" +
"<td>" + value.ventas + "</td>" +
"<td>" + value.participacionventas + "</td>" +
"</tr>");
} else {
if(value.participacion=='C')
{
datos22.append("<tr>" +
"<td>" + value.participacion_estimada + "</td>" +
"<td bgcolor=green>" + value.participacion + "</td>" +
"<td>" + value.n + "</td>" +
"<td>" + value.participacionn + "</td>" +
"<td>" + value.ventas + "</td>" +
"<td>" + value.participacionventas + "</td>" +
"</tr>");
}
}
}
}
);
}
});
}
}
}
function cargaralmacen(){
var idpunto = $("#iddelpuntoventa").val();
$('#almacencombo')
.find('option')
.remove()
.end();
$('#almacencombo').material_select();
// debugger;
var route = "/listaralmacensucursal/" + idpunto;
$.get(route, function (res) {
$(res).each(function (key, value) {
$('#almacencombo').append('<option value=' + value.id + ' >' + value.nombre + '</option>');
$('#almacencombo').material_select();
});
});
}
/********************************************/
function dame_numero_aleatorio(superior, inferior) {
var numPosibilidades = (superior + 1) - inferior;
var aleat = Math.random() * numPosibilidades;
aleat = Math.floor(aleat);
aleat = (inferior + aleat);
return aleat
}
function dame_color_aleatorio() {
color_aleat = "#"
hexadecimal = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
var inferior = 0;
var superior = hexadecimal.length - 1;
for (i = 0; i < 6; i++) {
color_aleat += hexadecimal[dame_numero_aleatorio(superior, inferior)];
}
return color_aleat
}
function dame_mes(mes) {
if (mes == 1) {
return "EN";
} else if (mes == 2) {
return "FEB";
} else if (mes == 3) {
return "MAR";
} else if (mes == 4) {
return "ABR";
} else if (mes == 5) {
return "MAY";
} else if (mes == 6) {
return "JUN";
} else if (mes == 7) {
return "JUL";
} else if (mes == 8) {
return "AGO";
} else if (mes == 9) {
return "SEPT";
} else if (mes == 10) {
return "OCT";
} else if (mes == 11) {
return "NOV";
} else if (mes == 12) {
return "DIC";
}
} |
import React from 'react';
import pic1 from './bilibili搜索.png';
import './search_box.scss'
import pic2 from './search.png'
const SLlist=[
'综合','视频','番剧','影视','直播','专栏','话题','用户','赛事'
]
class Search_box extends React.Component{
render(){
return(
<div id={'sB'}>
<div id={'sbL'}><img src={pic1}></img></div>
<div id={'sBox'}><input type="search"></input><img src={pic2}></img></div>
<div id={'Lcon'}>
{SLlist.map((item,index)=>(
index==0?
<a id={'First'} className={'sbC'}>{item}</a>
:<a className={'sbC'}>{item}</a>
))}
</div>
</div>
)
}
}
export default Search_box; |
var api = angular.module("lugaresApi", []);
api.factory("lugaresApi", function () {
var usuarios = [
{
"nome": "Paulo",
"data_nascimento": "01/01/1993",
"estado": "SP",
"cidade": "São Carlos",
"telefone": "(19) 9999-8888",
"email": "paulo@email.com",
"senha": "senha123"
},
{
"nome": "Matheus",
"data_nascimento": "01/01/1992",
"estado": "SP",
"cidade": "São Carlos",
"telefone": "(19) 9999-7777",
"email": "matheus@email.com",
"senha": "senha123"
}
];
var categorias = [
{
"nome": "América",
"id": "america"
},
{
"nome": "Ásia",
"id": "asia"
},
{
"nome": "Europa",
"id": "europa"
}
];
var lugares = [
{
"nome": "Vale do Silicio",
"autor": "Paulo",
"descricao": "Ótimo lugar para os fãs de tecnologia. Os passeios incluem visitas a gigantes da tecnologia como Apple, Google, Twitter, Facebook e muito mais.",
"imagens": ["media/lugares/1.jpg","media/lugares/2.jpg","media/lugares/13.jpg"],
"categorias": ["america"],
"componentes": [{
nome: "População",
valor: "Aproximadamente 4 Milhões"
},{
nome: "Língua",
valor: "Inglês"
}],
"data": new Date(2010, 12, 10),
"comentarios": [{
usuario: "paulo@email.com",
nome: "Paulo",
comentario: "Muito interessante"
}],
"ranking": 4,
"numeroVotos": 2,
"id": 1
},
{
"nome": "Nova York",
"autor": "Matheus",
"descricao": "Cidade com ótimos roteiros gastronômicos.",
"imagens": ["media/lugares/2.jpg"],
"categorias": ["america"],
"componentes": [],
"comentarios": [],
"data": new Date(),
"ranking": 3,
"numeroVotos": 1,
"id": 2
},
{
"nome": "Machu Picchu",
"autor": "Paulo",
"descricao": "Cidadela da civilização Inca localizada no topo da cordilheira dos Andes.",
"imagens": ["media/lugares/3.jpg"],
"categorias": ["america"],
"componentes": [],
"comentarios": [],
"data": new Date(),
"ranking": 4,
"numeroVotos": 5,
"id": 3
},
{
"nome": "Rio de Janeiro",
"autor": "Matheus",
"descricao": "Cidade maravilhosa, com diversas e belissimas praias paradisiacas. Possui atrações como o Cristo Redentor (considerado uma das maravilhas modernas atuais) e o Pão de Açucar.",
"imagens": ["media/lugares/4.jpg"],
"categorias": ["america"],
"componentes": [],
"comentarios": [],
"data": new Date(),
"ranking": 2,
"numeroVotos": 4,
"id": 4
},
{
"nome": "Muralha da China",
"autor": "Paulo",
"descricao": "Grande muralha construída durante o império chinês, considerada uma das maravilhas modernas atuais.",
"imagens": ["media/lugares/5.jpg"],
"categorias": ["asia"],
"componentes": [],
"comentarios": [],
"data": new Date(),
"ranking": 4,
"numeroVotos": 3,
"id": 5
},
{
"nome": "Tokyo",
"autor": "Matheus",
"descricao": "Cidade para os fãs da cultura nipônica.",
"imagens": ["media/lugares/6.jpg"],
"categorias": ["asia"],
"componentes": [],
"comentarios": [],
"data": new Date(),
"ranking": 4,
"numeroVotos": 6,
"id": 6
},
{
"nome": "Seoul",
"autor": "Paulo",
"descricao": "Capital da Coréia do Sul.",
"imagens": ["media/lugares/7.jpg"],
"categorias": ["asia"],
"componentes": [],
"comentarios": [],
"data": new Date(),
"ranking": 3,
"numeroVotos": 12,
"id": 7
},
{
"nome": "Hong Kong",
"autor": "Matheus",
"descricao": "Ótima cidade turística.",
"imagens": ["media/lugares/8.jpg"],
"categorias": ["asia"],
"componentes": [],
"comentarios": [],
"data": new Date(),
"ranking": 3,
"numeroVotos": 4,
"id": 8
},
{
"nome": "Stonehenge",
"autor": "Paulo",
"descricao": "Monumento pré-histórico com propósito desconhecido.",
"imagens": ["media/lugares/9.jpg"],
"categorias": ["europa"],
"componentes": [],
"comentarios": [],
"data": new Date(),
"ranking": 5,
"numeroVotos": 2,
"id": 9
},
{
"nome": "Castelo de Versailles",
"autor": "Matheus",
"descricao": "Castelo francês que atualmente foi transformado em um museu. Conta com diversos itens da época, tais como objetos da realeza, itens históricos e o ambiente do castelo que permanece inalterado.",
"imagens": ["media/lugares/10.jpg"],
"categorias": ["europa"],
"componentes": [],
"comentarios": [],
"data": new Date(),
"ranking": 4,
"numeroVotos": 2,
"id": 10
},
{
"nome": "Coliseu",
"autor": "Paulo",
"descricao": "Anfiteatro da época do império romando, utilizado na época para as batalhas dos gladiadores.",
"imagens": ["media/lugares/11.jpg"],
"categorias": ["europa"],
"componentes": [],
"comentarios": [],
"data": new Date(),
"ranking": 4,
"numeroVotos": 7,
"id": 11
},
{
"nome": "Partenon",
"autor": "Matheus",
"descricao": "Templo dedicado a deusa grega Atena.",
"imagens": ["media/lugares/12.jpg"],
"categorias": ["europa"],
"componentes": [],
"comentarios": [],
"data": new Date(),
"ranking": 5,
"numeroVotos": 2,
"id": 12
}
];
return {
listarCategorias: function () {
return categorias;
},
listarLugares: function (categoria) {
//Filtra lugares de acordo com a categoria
var lugares_filtrados = lugares.filter(function (lugar) {
return lugar.categorias.some(function (cat) {
return cat === categoria;
});
});
return lugares_filtrados;
},
listaTodosLugares: function () {
return lugares;
},
listarLugar: function (lugarId) {
//Filtra lugares de acordo com a categoria
var lugares_filtrados = lugares.filter(function (lugar) {
return parseInt(lugar.id) === parseInt(lugarId);
});
if (lugares_filtrados.length)
return lugares_filtrados[0];
else
return {};
},
listarLugarNome: function (nome) {
//Filtra lugares de acordo com a categoria
var lugares_filtrados = lugares.filter(function (lugar) {
return lugar.nome === nome;
});
if (lugares_filtrados.length)
return lugares_filtrados[0];
else
return {};
},
listarCategoria: function (catId) {
//Filtra lugares de acordo com o id da categoria
var categorias_filtradas = categorias.filter(function (categoria) {
return categoria.id === catId;
});
return categorias_filtradas;
},
listShotComments: function (shotId) {
var n_url = url + "/shots/" + shotId + "/comments?callback=JSON_CALLBACK";
return $http.jsonp(n_url).then(function (response) {
return response.data.comments;
});
},
adicionarComentario: function (username, comentario, lugarId) {
var usuario = usuarios.filter(function (usuario) {
return usuario.email === username;
});
var lugar = lugares.filter(function (lugar) {
return parseInt(lugar.id) === parseInt(lugarId);
});
var novoComentario = {
"nome": usuario[0].nome,
"email": usuario[0].email,
"comentario": comentario
};
if (lugar.length > 0)
lugar[0].comentarios.push(novoComentario);
},
calcularAvaliacao: function (voto, lugarId) {
var lugar_avaliado = lugares.filter(function (lugar) {
return parseInt(lugar.id) === parseInt(lugarId);
});
if (lugar_avaliado.length > 0) {
lugar_avaliado[0].numeroVotos = parseInt(lugar_avaliado[0].numeroVotos) + 1;
console.log("numVotos:" + lugar_avaliado[0].numeroVotos);
console.log("ranking: " + lugar_avaliado[0].ranking);
console.log("voto: " + voto);
lugar_avaliado[0].ranking = ((parseInt(lugar_avaliado[0].numeroVotos) - 1) * parseFloat(lugar_avaliado[0].ranking) + parseInt(voto)) / (lugar_avaliado[0].numeroVotos);
console.log("avaliacao: " + lugar_avaliado[0].ranking);
}
},
emailJaExiste: function (email) {
var u = usuarios.filter(function (u) {
return u.email.toLowerCase() === email.toLowerCase();
});
if (u.length > 0) {
return true;
} else {
return false;
}
},
login: function (usuario, senha) {
var u = usuarios.filter(function (u) {
return u.senha === senha && u.email.toLowerCase() === usuario.toLowerCase();
});
if (u.length > 0) {
return u[0];
} else {
return false;
}
},
novoUsuario: function (nome, data_nasc, estado, cidade, telefone, email, senha) {
var u = {
"nome": nome,
"data_nascimento": data_nasc,
"estado": estado,
"cidade": cidade,
"telefone": telefone,
"email": email,
"senha": senha
};
usuarios.push(u);
},
adicionarLugar: function (nome, autor, descricao, imagem, categoria, componentes) {
// Calculando o id do novo elemento
var id = lugares[lugares.length - 1].id;
console.log(componentes);
// Criando o novo objeto
var lugar = {
"nome": nome,
"autor": autor,
"descricao": descricao,
"imagens": imagem,
"categorias": categoria,
"componentes": componentes,
"comentarios": [],
"data": new Date(),
"ranking": 1,
"numeroVotos": 0,
"id": ++id
};
lugares.push(lugar);
return id;
},
autoComplete: function (){
var ac = [];
//Obtem todos os nomes de categorias
for (var i =0; i<categorias.length; i++){
ac.push(categorias[i].nome);
}
//Obtem todos os nomes de lugares
for (var i =0; i<lugares.length; i++){
ac.push(lugares[i].nome);
}
return ac;
},
buscaLugares: function (termo){
var l = [];
var termo = termo.toLowerCase()
//Obtem todos os nomes de lugares
for (var i =0; i<lugares.length; i++){
var cats = lugares[i].categorias;
var cat;
var pertence = false;
for (var j = 0; j < cats.length; j++){
cat = this.listarCategoria(cats[j])[0].nome.toLowerCase();
if ( cat.toLowerCase().indexOf(termo) > -1 ){
console.log('oba');
pertence = true;
break;
}
}
if( (lugares[i].nome.toLowerCase().indexOf(termo) > -1 ) || pertence ){
l.push(lugares[i]);
}
}
return l;
}
}
}); |
class JZFQ {
head = document.querySelector("head");
constructor() {
// if (new.target === JZFQ) {
// }
this.body = document.body;
}
ranStr(n) {
for (let e = "abcdefghijklmnopqrstuvwxyzABCDEFGHIZKLMNOPQRSTUVWXYZ0123456789", a = "", r = 0; r < n; r++) {
let i = ~~(Math.random() * (e.length - 1));
a += e.charAt(i);
}
return a;
}
uploadImg(opts) {
if (this.typeOf(opts, 'Object')) {
let [formData, xhr] = [new FormData(), new XMLHttpRequest()];
formData.append("image", opts.ele.files[0]);
xhr.open("post", opts.url, true);
xhr.onreadystatechange = () => {
if (4 === xhr.readyState) {
if (200 === xhr.status) {
let res = JSON.parse(xhr.responseText);
opts.cb(res)
} else {
this.tips("error");
}
}
};
xhr.send(formData);
}
}
loading() {
if (!document.getElementById('loadingWrap')) {
let lhtml = '', mainHtml = '';
let classArray = ['loadfirst', 'second', 'loadlast'];
let loading = document.createElement('div');
loading.id = 'loadingWrap';
for (let l = 1; l < 5; l++) {
lhtml += '<div class="circle' + l + '"></div>';
}
Array.from(new Array(3).keys()).forEach(i => {
mainHtml += `<div class="loading-container ${classArray[i]}">${lhtml}</div>`;
});
loading.innerHTML = `<div class="loading">${mainHtml}</div>`;
this.body.appendChild(loading);
}
}
removeLoading() {
let loading = document.getElementById('loadingWrap');
loading && this.body.removeChild(loading);
}
getQueryString(name) {
let url = window.location.href;
if (/\?(.+)/.test(url)) {
let args = url.split('?');
if (args[0] !== url) {
let arr = args[1].split('&');
let obj = {};
for (let i = 0; i < arr.length; i++) {
let arg = arr[i].split('=');
obj[arg[0]] = arg[1];
}
return !name ? obj : obj[name];
}
}
}
loadJS(pageUrl, insetPos, cb, id) {
if (!document.getElementById(id)) {
let loadJs = document.createElement("script");
// Object.assign(loadJs, { src: pageUrl, type: "text/javascript", id: id })
loadJs.src = pageUrl, loadJs.type = "text/javascript", loadJs.id = id;
document.querySelector(insetPos || "body").appendChild(loadJs);
if (loadJs.readyState) {
loadJs.onreadystatechange = () => {
if (loadJs.readyState == "loaded" || loadJs.readyState == "complete") {
loadJs.onreadystatechange = null;
return cb()
}
};
}
loadJs.onload = () => cb();
}
}
tips(txt) {
if (document.getElementById("systemTips")) return;
let clear = null;
let div = document.createElement("div");
div.id = "systemTips";
div.innerHTML = txt.toString();
this.body.appendChild(div);
clear = setTimeout(() => { this.body.removeChild(div), clearTimeout(clear) }, 2000)
}
browserInfo() {
return {
isAndroid: Boolean(navigator.userAgent.match(/android/ig)),
isIphone: Boolean(navigator.userAgent.match(/iphone|ipod/ig)),
isIpad: Boolean(navigator.userAgent.match(/ipad/ig)),
isWeixin: Boolean(navigator.userAgent.match(/MicroMessenger/ig)),
isAli: Boolean(navigator.userAgent.match(/AlipayClient/ig)),
isPhone: Boolean(/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent))
}
}
goTop(ele, scrToShow) {
window.animation = window.requestAnimationFrame || function (fn) { return setTimeout(fn, 1000 / 60) };
let el = document.querySelector(ele);
window.addEventListener('scroll', () => {
let currentScroll = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
let clientH = document.documentElement.clientHeight || document.body.clientHeight;
currentScroll >= (Math.abs(scrToShow) || clientH) ? (el.style.display = 'block') : (el.style.display = 'none');
}, !1);
el.addEventListener('click', function fn() {
let currentScroll = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
if (currentScroll > 0) {
window.animation(fn);
window.scrollTo(0, currentScroll - (currentScroll / 30));
}
}, !1);
}
copy(text, tips) {
if (!this.body.querySelector('.cInpt')) {
let input = document.createElement('input');
input.setAttribute('readonly', 'readonly');
input.value = text;
this.body.appendChild(input);
this.body.className.includes('ios') ? input.setSelectionRange(0, text.length) : input.select();
document.execCommand("Copy");
input.className = 'cInpt';
input.style.display = 'none';
this.tips(tips || '复制成功');
setTimeout(() => this.body.removeChild(input), 2e3);
}
}
typeOf(tgt, type) {
const dataType = Object.prototype.toString.call(tgt).replace(/\[object (\w+)\]/, "$1");
return type ? dataType === type : dataType;
}
extNumber(str) {
return str.replace(/[^0-9]/ig, "") * 1
}
getStyle(obj, attr) {
return obj.currentStyle ? obj.currentStyle[attr] : document.defaultView.getComputedStyle(obj, null)[attr]
}
GBCR(obj) {
return obj.getBoundingClientRect()
}
inverse(number) {
return - number || 0
}
parents(ele, selector) {
let matchesSelector = ele.matches || ele.webkitMatchesSelector || ele.mozMatchesSelector || ele.msMatchesSelector;
while (ele) {
if (matchesSelector.call(ele, selector)) break;
ele = ele.parentElement;
}
return ele
}
imgLoaded(imgList, callback) {
let [clear, isLoad, imgs] = [null, true, []];
for (let i = 0; i < imgList.length; i++) {
if (imgList[i].height === 0) isLoad = false, imgs.push(imgList[i])
}
isLoad ? (clearTimeout(clear), callback()) : clear = setTimeout(() => imgLoaded(imgs, callback), 300)
}
turnArray(nodeList) { return [].slice.call(nodeList) }
toThousands(num) {
return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
}
setDate(format) {
setInterval(() => {
return new Date().format(format); // "yyyy-MM-dd hh:mm:ss w"
}, 1000);
Date.prototype.format = function (fmt) {
let o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": ~~((this.getMonth() + 3) / 3),
"S": this.getMilliseconds(),
'w': ['日', '一', '二', '三', '四', '五', '六'][this.getDay()]
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (let k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return fmt
}
}
}
class Pop extends JZFQ {
constructor(opts) {
super();
if (/Object/.test(Object.prototype.toString.call(opts))) {
this.main(opts, opts => {
this.event(opts);
})
}
}
main(opts, cb) {
let [div, mask] = [document.createElement("div"), document.createElement("div")];
mask.className = "h5pop-mask";
mask.id = "h5PopMasks";
div.className = "h5pop-main clearfix";
div.id = "h5PopMainEle";
let popHtml = '';
if (!!opts['isHideClose']) {
popHtml += '<a href="javascript:;" class="h5pop-close">×</a>';
}
if (!!opts['title']) {
popHtml += '<h3 class="h5tips-title">' + opts["title"] + '</h3>';
}
if (!!opts['tipTxt']) {
popHtml += '<div class="h5pop-content clearfix">' + opts["tipTxt"] + '</div>';
}
popHtml += '<div class="h5pop-footer">';
if (!!opts['cancelBtn']) {
popHtml += '<a type="button" class="h5pop-cancel" href="javascript:;">' + opts["cancelBtn"] + '</a>';
}
if (!!opts['confirmBtn']) {
popHtml += '<a type="button" class="h5pop-confirm" href="javascript:;">' + opts["confirmBtn"] + '</a>';
}
popHtml += '</div>';
div.innerHTML = popHtml;
this.body.appendChild(div), this.body.appendChild(mask);
cb(opts)
}
event(opts) {
let isEvent = true;
document.querySelector('#h5PopMainEle').addEventListener('click', e => {
let target = (e = e || window.event).target || e.srcElement;
let targetType = target.className.toLowerCase() || target.id;
if (isEvent) {
let isExist = key => {
if (opts[key] && this.typeOf(opts[key], 'Function')) {
opts[key]()
}
}
switch (targetType) {
case "h5pop-cancel":
isExist('cancelBtnRun')
break;
case "h5pop-confirm":
isExist('confirmBtnRun')
break;
}
if (targetType == "h5pop-close" || targetType == "h5pop-cancel" || targetType == "h5pop-confirm") {
return this.remove(), e.preventDefault(), isEvent = false;
}
}
});
}
remove() {
let popMask = document.getElementById("h5PopMasks");
let popMain = document.getElementById("h5PopMainEle");
if (popMask.parentNode && popMain.parentNode) {
popMask.parentNode.removeChild(popMask);
popMain.parentNode.removeChild(popMain);
}
}
}
HTMLElement.prototype.css = function (opts) {
if (/Object/.test(Object.prototype.toString.call(opts))) {
for (let key in opts) {
opts[key] && (this.style[key] = opts[key].toString())
}
}
};
HTMLElement.prototype.removeAttr = function (attr) {
if (this.getAttribute('style')) {
!Array.isArray(attr) && (attr = attr.split(','))
let styles = this.getAttribute('style').replace(/\s+/g, '');
for (let i = 0; i < attr.length; i++) {
styles = styles.replace(new RegExp(attr[i] + ':.+?;'), '')
this.setAttribute('style', styles)
}
}
};
HTMLElement.prototype.replaceClass = function replaceClass(...args) {
return this.classList.replace.apply(this.classList, args);
};
NodeList.prototype.replaceClass = function replaceClass(...args) {
this.forEach(item => item.replaceClass(...args));
return this;
};
if (window.NodeList && !NodeList.prototype.forEach) {
NodeList.prototype.forEach = function (callback, thisArg) {
thisArg = thisArg || window;
for (let i = 0; i < this.length; i++) {
callback.call(thisArg, this[i], i, this);
}
};
} |
export default (target, fns) => {
let proto = Object.create(target)
Object.setPrototypeOf(fns, target)
Object.keys(fns).forEach(key => {
let desc = Object.getOwnPropertyDescriptor(target, key)
desc.enumerable = false
Object.defineProperty(target, key, desc)
})
return target
}
|
var background = {
init: function () {
var colors = [
[0,100,255],
[255,0,0],
[180,0,180],
[200,100,0],
[0,220,0],
]
var color = colors[state.level % colors.length], r = color[0], g = color[1], b = color[2]
this.plasma = [
UFX.texture.nightsky({
size: 512, r0: r, dr: 0, g0: g, dg: 0, b0: b, db: 0, a0: 10, da: 10, fraclevel: 3, scale: 4, rstar1: 0.4,
}),
UFX.texture.overcast({
size: 512, r0: r, dr: 0, g0: g, dg: 0, b0: b, db: 0, a0: 10, da: 10, fraclevel: 3, scale: 4,
}),
UFX.texture.overcast({
size: 512, r0: r, dr: 0, g0: g, dg: 0, b0: b, db: 0, a0: 10, da: 10, fraclevel: 3, scale: 4,
}),
UFX.texture.overcast({
size: 512, r0: r, dr: 0, g0: g, dg: 0, b0: b, db: 0, a0: 10, da: 10, fraclevel: 3, scale: 4,
}),
]
this.t = 0
this.x0 = 0
this.y0 = 0
},
think: function (dt) {
this.t += dt
},
draw: function () {
var sx = canvas.width, sy = canvas.height
UFX.draw("fs black f0")
for (var j = 0 ; j < 4 ; ++j) {
var x = this.x0 + (j ? 18 * Math.sin(1 + 2 * j) * this.t : 0)
var y = this.y0 + (j ? 18 * Math.cos(1 + 2 * j) * this.t : 0)
var px0 = Math.floor(x), py0 = Math.floor(y)
for (var px = px0 - 512 * Math.ceil(px0 / 512) ; px < sx ; px += 512) {
for (var py = py0 - 512 * Math.ceil(py0 / 512) ; py < sy ; py += 512) {
UFX.draw("drawimage", this.plasma[j], px, py)
}
}
}
UFX.draw("ss rgba(255,255,255,0.05) lw 1 b")
var pmin = view.togame(0, 0), pmax = view.togame(sx, sy)
for (var x = Math.ceil(pmin[0] + 0.5) - 0.5 ; x <= pmax[0] ; ++x) {
var screenx = view.toscreen(x, 0)[0]
UFX.draw("m", screenx, 0, "l", screenx, sy)
}
for (var y = Math.ceil(pmin[1] + 0.5) - 0.5 ; y <= pmax[1] ; ++y) {
var screeny = view.toscreen(0, y)[1]
UFX.draw("m", 0, screeny, "l", sx, screeny)
}
UFX.draw("s")
},
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.