text stringlengths 7 3.69M |
|---|
import { Form, Select } from 'antd';
import React from 'react';
const renderAccountOptions = account => {
const { number, amount, id } = account;
const title = `${number} | Balance: S$ ${amount}`;
return (
<Select.Option value={account} key={id}>
{title}
</Select.Option>
);
};
const AccountField = ({ accounts, form }) => {
const { getFieldDecorator } = form;
return (
<Form.Item label="Account" hasFeedback>
{getFieldDecorator('account', {
rules: [{ required: true, message: 'Account is not selected!' }]
})(
<Select placeholder="Please select account">
{accounts && accounts.map(renderAccountOptions)}
</Select>
)}
</Form.Item>
);
};
export default AccountField;
|
'use strict';
const gulp = require('gulp');
const fs = require('fs');
const request = require('request');
const configPath = process.cwd() + '/data/config.json';
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
const methode = config.copy.methode;
let _queue = [];
let _output = '';
let _imageDirectory = 'assets/';
gulp.task('fetch-methode', function(cb) {
if (methode.story.length) {
_imageDirectory += methode.imageDirectory || '';
var next = function(index) {
// fetch xml
var base = 'http://prdedit.bostonglobe.com/eom/Boston/Content/';
var url = base + methode.section + '/Stories/' + methode.story[index].slug + '.xml';
console.log('fetching', url);
request(url, function(error, response, body) {
// did we get a valid response?
if (!error && response.statusCode === 200) {
// extract the html between content tags
var content = body.match(/(<content>)([\s\S]*)(<\/content>)/);
if (content.length) {
content = content[2];
// replace all the weird bits and bobs
content = deMethodeify(content);
// insert graphic templates
content = content.replace(/<annotation.*(graphic:)(.*)<\/annotation>(.*|[\r\n]+).*(<\/p>)/g, function(a, b, c) {
return '</p>\n{{> graphic/' + c.trim() + '}}';
});
// replace photo tags with desired markup
content = content.replace(/<photogrp-inline (.*?)>([\S\s]*?)<\/photogrp-inline>/g, createImageMarkup);
appendOutput(content, methode.story[index]);
} else {
console.error('empty methode file, check config settings');
advance(index);
}
} else {
// http error. log and quit.
console.error(JSON.stringify(error, null, 4));
advance(index);
}
advance(index);
});
};
var advance = function(index) {
index++;
if (index < methode.story.length) {
next(index);
} else {
fs.writeFileSync('src/html/partials/graphic/methode.hbs', _output);
downloadImages(cb);
}
};
next(0);
} else {
console.error('No methode story');
cb();
}
});
function deMethodeify(content) {
// remove notes
content = content.replace(/<span class="@notes"(.|\n)*?\/span>/g, '');
content = content.replace(/<p class="@notes"(.|\n)*?\/p>/g, '');
// remove channel...
content = content.replace(/<span.*channel=\"\!\".*\/*.span>/g, '');
// remove empty p tags
content = content.replace(/<p><\/p>/g, '');
// replace *** with hr
content = content.replace(/\<p\> *\*+ *\<\/p\>/g, '<hr>');
// remove bold tag
content = content.replace(/<b>/g, '');
content = content.replace(/<\/b>/g, '');
// -- to mdash
content = content.replace(/--/g, '—');
// add class for methode p tags
content = content.replace(/<p>/g, "<p class='methode-graf'>")
return content;
}
function createImageMarkup(str) {
// match src
var fileref = str.match(/fileref="(.*?)"/);
var float = str.match(/float="(.*?)"/);
if (fileref && fileref.length) {
var src = fileref[1];
var floatClass = float && float.length ? float[1] : '';
var customClass = methode.imageClass ? floatClass : '';
// match caption and remove
var caption = str.match(/<caption (?:.*?)>([\S\s]*?)<\/caption>/);
caption = caption && caption.length ? caption[1].replace(/\<p\>|\<\/p\>/g,'').trim() : '';
// match credit and remove
var credit = str.match(/<credit (?:.*?)>([\S\s]*?)<\/credit>/);
credit = credit && credit.length ? credit[1].replace(/\<p\>|\<\/p\>/g,'').trim() : '';
var imgPath = src.split('?')[0];
var figure = createFigure({
lib: methode.imageLibrary,
imgPath: imgPath,
caption: caption,
credit: credit,
customClass: customClass
});
return figure;
} else {
return '';
}
}
function createFigure(params) {
var imgFull = params.imgPath.substr(params.imgPath.lastIndexOf('/') + 1);
var imgSplit = imgFull.split('.');
var name = imgSplit[0];
var extension = imgSplit[1];
var imageSizes = methode.imageSizes && methode.imageSizes.length ? methode.imageSizes : [1200];
for (var i in imageSizes) {
_queue.push({
url: 'http://prdedit.bostonglobe.com/rf/image_' + imageSizes[i] + 'w' + params.imgPath,
src: name + '_' + imageSizes[i] + '.' + extension
});
}
// start generating markup
var src;
var figure = '<figure class="' + params.customClass + '">';
if (params.lib === 'imager') {
src = _imageDirectory + '/' + name + '_{width}' + '.' + extension;
figure += '<img data-src="' + src + '" alt="' + params.caption + '" class="delayed-image-load" />';
} else if (params.lib === 'picturefill') {
figure += '<picture>';
figure += '<!--[if IE 9]><video style="display: none;"><![endif]-->';
for (var j = imageSizes.length - 1; j > -1; j--) {
src = _imageDirectory + '/' + name + '_' + imageSizes[j] + '.' + extension;
figure += '<source srcset="' + src + '" ';
if (j > 0) {
figure += 'media="(min-width: ' + Math.floor(imageSizes[j-1] / 1.5) + 'px)"';
} else {
figure += 'media="(min-width: 1px)"';
}
figure += '>';
}
figure += '<!--[if IE 9]></video><![endif]-->';
src = _imageDirectory + '/' + name + '_' + imageSizes[0] + '.' + extension;
figure += '<img src="' + src + '" data-srcset="' + src + '" alt="' + params.caption + '">';
figure += '</picture>';
} else if (params.lib === 'lazy-picturefill') {
// picturefill + lazysizes.js (changes srcset to data-srcset)
figure += '<picture>';
figure += '<!--[if IE 9]><video style="display: none;"><![endif]-->';
for (var j = imageSizes.length - 1; j > -1; j--) {
src = _imageDirectory + '/' + name + '_' + imageSizes[j] + '.' + extension;
figure += '<source data-srcset="' + src + '" ';
if (j > 0) {
figure += 'media="(min-width: ' + Math.floor(imageSizes[j-1] / 1.5) + 'px)"';
} else {
figure += 'media="(min-width: 1px)"';
}
figure += '>';
}
figure += '<!--[if IE 9]></video><![endif]-->';
src = _imageDirectory + '/' + name + '_' + imageSizes[0] + '.' + extension;
figure += '<img class="lazyload" src="' + src + '" data-srcset="' + src + '" alt="' + params.caption + '">';
figure += '</picture>';
} else {
// plain old image
src = _imageDirectory + '/' + name + '_' + imageSizes[0] + '.' + extension;
figure += '<img src="' + src + '" alt="' + params.caption + '" />';
}
figure += '<small>' + params.credit + '</small>';
figure += '<figcaption>' + params.caption + '</figcaption>';
figure += '</figure>';
return figure;
}
function appendOutput(content, story) {
_output += content;
}
function downloadImages(cb) {
var next = function(index) {
var path = 'src/' + _imageDirectory + '/' + _queue[index].src;
try {
var exists = fs.lstatSync(path);
advance(index);
} catch (e) {
console.log('downloading', _queue[index].url);
request(_queue[index].url, {encoding: 'binary'}, function(error, response, body) {
if (error) {
console.error(error);
advance(index);
} else {
fs.writeFile(path, body, 'binary', function(err) {
if (err) {
console.error(err);
}
advance(index);
});
}
});
}
};
var advance = function(index) {
index++;
if (index < _queue.length) {
next(index);
} else {
cb();
}
};
if (_queue.length) {
next(0);
}
}
|
window.TodoApp = ( function( d, ls ){
'use strict';
var todos, todoView, todoController;
todoController = {
addTodo: function( todo ){
todos.push( todo );
ls.setItem( 'todos', JSON.stringify( todos ) );
todoView.render();
}
, getTodos: function(){
return todos;
}
, init: function(){
todos = JSON.parse( ls.getItem( 'todos' ) ) || [];
todoView.init();
}
, removeTodo: function( id ){
todos.splice( +id, 1 );
ls.setItem( 'todos', JSON.stringify( todos ) );
todoView.render();
}
, toString: function(){
return todos.map( function( todo ){ return '-' + todo; } ).join( '\n' );
}
};
todoView = {
init: function(){
d.getElementById( 'todo-add-item' ).addEventListener( 'click', function(){
todoController.addTodo( d.getElementById( 'todo-item' ).value );
});
d.getElementById( 'todo-compose-email' ).addEventListener( 'click', function(){
d.getElementById( 'email' ).classList.remove( 'hidden' );
d.getElementById( 'email-body' ).value = todoController.toString();
});
todoView.render();
}
, render: function(){
var todoList = d.getElementById( 'todo-items' )
, nodes = d.createDocumentFragment()
, el, removeButton;
todoList.innerHTML = '';
todoController.getTodos().forEach(function( todo, index ){
el = d.createElement( 'li' );
el.dataset.id = index;
removeButton = d.createElement( 'button' );
removeButton.innerHTML = 'x';
removeButton.classList.add( 'todo-remove-item' );
el.appendChild( d.createTextNode( todo ) );
el.appendChild( removeButton );
nodes.appendChild( el );
removeButton.addEventListener( 'click', function( event ){
todoController.removeTodo( event.target.parentNode.dataset.id );
});
});
todoList.appendChild( nodes );
}
};
return { init: todoController.init };
})( document, localStorage );
TodoApp.init();
|
import React from 'react';
import { connect } from 'react-redux';
import { Table } from 'antd';
import './UserMissionInfo.scss';
class UserMissionInfo extends React.Component {
constructor(props) {
super(props);
this.state = {
columns: [],
data: []
};
}
componentDidMount() {
this.setTable();
}
setTable() {
let columns = [
{
title: '任务编号',
dataIndex: 'demo1',
width: 150
},
{
title: '场景任务',
dataIndex: 'demo2',
width: 150
},
{
title: '类型',
dataIndex: 'demo3',
width: 150
},
{
title: '任务金额',
dataIndex: 'demo4',
width: 150
},
{
title: '任务状态',
dataIndex: 'demo5',
width: 150
},
{
title: '下单时间',
dataIndex: 'demo6',
width: 150
},
{
title: '接单时间',
dataIndex: 'demo7',
width: 150
}
];
let data = [
{
key: '1',
demo1: '测试数据',
demo2: '测试数据',
demo3: '测试数据',
demo4: '测试数据',
demo5: '测试数据',
demo6: '测试数据',
demo7: '测试数据',
demo8: '测试数据',
demo9: '测试数据'
},
{
key: '2',
demo1: '测试数据',
demo2: '测试数据',
demo3: '测试数据',
demo4: '测试数据',
demo5: '测试数据',
demo6: '测试数据',
demo7: '测试数据',
demo8: '测试数据',
demo9: '测试数据'
},
{
key: '3',
demo1: '测试数据',
demo2: '测试数据',
demo3: '测试数据',
demo4: '测试数据',
demo5: '测试数据',
demo6: '测试数据',
demo7: '测试数据',
demo8: '测试数据',
demo9: '测试数据'
},
{
key: '4',
demo1: '测试数据',
demo2: '测试数据',
demo3: '测试数据',
demo4: '测试数据',
demo5: '测试数据',
demo6: '测试数据',
demo7: '测试数据',
demo8: '测试数据',
demo9: '测试数据'
},
{
key: '5',
demo1: '测试数据',
demo2: '测试数据',
demo3: '测试数据',
demo4: '测试数据',
demo5: '测试数据',
demo6: '测试数据',
demo7: '测试数据',
demo8: '测试数据',
demo9: '测试数据'
},
{
key: '6',
demo1: '测试数据',
demo2: '测试数据',
demo3: '测试数据',
demo4: '测试数据',
demo5: '测试数据',
demo6: '测试数据',
demo7: '测试数据',
demo8: '测试数据',
demo9: '测试数据'
}
];
this.setState({
columns,
data
})
}
render() {
let { columns, data } = this.state;
return (
<div className="user-mission-info">
<Table columns={columns} dataSource={data}/>
</div>
)
}
}
const mapStateToProps = state => {
return {
}
}
const mapDispatchToProps = dispatch => {
return {
}
}
export default connect(mapStateToProps, mapDispatchToProps)(UserMissionInfo); |
/* should be a stream managing backpressure */
class EventQueue {
constructor (options) {
this.options = options || {}
this.backlog = []
this.stored = []
}
attachResponse (res) {
this._res = res
res.writeHead(200, {
'content-type': 'text/event-stream',
'Access-Control-Allow-Origin': '*'
})
}
sendEvent (event, flushing) {
if (event.name === 'clear') {
this.stored = []
this.backlog = []
} else {
if (event.name === 'view' && !flushing) {
this.stored.push(event)
if (this.options.verbose) console.log('stored: ', this.stored.length)
}
if (this._res) {
const name = `event: ${event.name}\n`
const data = `data: ${event.data ? JSON.stringify(event.data) : ''}\n\n`
this._res.write(name)
this._res.write(data)
if (this.options.verbose) {
console.error('Sending SSE:')
process.stderr.write(name + data)
}
} else if (event.name !== 'view') {
this.backlog.push(event)
if (this.options.verbose) console.log('backlog: ', this.backlog.length)
}
}
}
flush () {
for (const event of this.stored) {
this.sendEvent(event, true)
}
while (this.backlog.length) {
const event = this.backlog.shift()
this.sendEvent(event, true)
}
}
end () {
if (this._res) this._res.end()
}
}
export default EventQueue
|
import {
CommandLineExerciseState,
GitExerciseState,
} from "../core/classes/exercise-state.js";
import {
handleKeydown,
handleKeyup,
} from "../core/handlers/command-line-handlers.js";
import { COMMANDS_MAP } from "../core/handlers/command-handlers.js";
import {
initializeGitVisualization,
updateFileStructureVisualization,
updateGitVisualization,
} from "../core/handlers/visualization-handlers.js";
import { CommandHistory } from "../core/classes/command-history.js";
import {
INITIALIZE_FILE_TREE_OFFSETS,
INITIALIZE_OFFSETS,
RESET_FILE_TREE_OFFSETS,
RESET_OFFSETS,
} from "../core/config/timing-offsets.js";
import {
createHistoryLineHTMLString,
createPromptHTMLString,
} from "../html-string-components/html-string-components.js";
import { COMBINED_COMMANDS_MAP } from "../core/handlers/git-command-handlers.js";
import { EXERCISE_TYPES } from "../core/config/exercise-types.js";
function initializeExercise(config) {
switch (config.type) {
case EXERCISE_TYPES.GIT:
initializeGitExercise(config);
break;
default:
initializeCommandLineExercise(config);
break;
}
}
function initializeCommandLineExercise({
title,
description,
task,
checkCompleted,
initialFileStructure,
initialIndexPath,
}) {
const state = new CommandLineExerciseState(
initialFileStructure,
initialIndexPath
);
initializeExerciseHelper(
state,
updateFileStructureVisualization,
COMMANDS_MAP,
INITIALIZE_FILE_TREE_OFFSETS,
RESET_FILE_TREE_OFFSETS,
title,
description,
task,
checkCompleted
);
}
function initializeGitExercise({
title,
description,
task,
checkCompleted,
initialFileStructure,
initialIndexPath,
emptyLocal,
initialCommands,
initialRemoteCommands,
}) {
const state = new GitExerciseState(
initialFileStructure,
initialIndexPath,
emptyLocal,
initialCommands,
initialRemoteCommands
);
initializeExerciseHelper(
state,
updateGitVisualization,
COMBINED_COMMANDS_MAP,
INITIALIZE_OFFSETS,
RESET_OFFSETS,
title,
description,
task,
checkCompleted,
initializeGitVisualization
);
}
function initializeExerciseHelper(
state,
handleUpdateVisualization,
commandsMap,
initialVisualizationOffsets,
resetVisualizationOffsets,
title,
description,
task,
handleCheckCompleted,
initializeVisualization
) {
// Load the config object with interpreter and code created by odsaUtils.js
// const config = ODSA.UTILS.loadConfig();
const config = ODSA.UTILS.loadConfig(),
interpret = config.interpreter; // get the interpreter
updateText(title, description, task);
const commandHistory = new CommandHistory();
let svgData;
const awardCredit = (args) => {
if (handleCheckCompleted(args, state)) {
$("#progress-indicator").text("Completed");
$("#progress-indicator").removeClass("in-progress").addClass("completed");
ODSA.AV.awardCompletionCredit();
}
};
const updateVisualization = (offsets, extraVisualizations) =>
handleUpdateVisualization(svgData, state, offsets, extraVisualizations);
const handleAfterEnter = () => {
updatePrompt();
$("#commandline").scrollTop($("#commandline")[0].scrollHeight);
};
const updatePrompt = () => {
$("#prompt-placeholder")
.empty()
.append(createPromptHTMLString(state.getPromptData()));
};
const handleKeydownWrapper = (event) => {
handleKeydown(
event,
getInput(),
setInput,
state,
commandsMap,
updateVisualization,
awardCredit,
addHistory,
commandHistory,
handleAfterEnter
);
};
const handleKeyupWrapper = (event) => {
handleKeyup(event, getInput(), commandHistory);
};
const handleReset = () => {
state.reset();
updateVisualization(resetVisualizationOffsets);
clearHistory();
commandHistory.reset();
setInput("");
focusInput();
updatePrompt();
};
$("#prompt-placeholder").append(
createPromptHTMLString(state.getPromptData())
);
$("#command-line-value").keydown(handleKeydownWrapper);
$("#command-line-value").keyup(handleKeyupWrapper);
$("#commandline").click(() => focusInput());
$("#reset").click(handleReset);
//delay render because of sizing issues
setTimeout(() => {
const id = "#visualization-container";
const width = $(id).width();
const height = $(id).height();
const svg = d3.select("#visualization-container").append("svg");
svg.attr("width", width);
svg.attr("height", height);
const group = svg.append("g");
svgData = { width, height, group };
if (initializeVisualization) {
initializeVisualization(svgData);
}
updateVisualization(initialVisualizationOffsets);
}, 500);
}
const getInput = () => $("#command-line-value").val();
const setInput = (input) => $("#command-line-value").val(input);
const focusInput = () => {
$("#command-line-value").focus();
};
const addHistory = (value) => {
$("#history").append(
createHistoryLineHTMLString(value.input, value.output, value.promptData)
);
};
const clearHistory = () => {
$("#history").empty();
};
const updateText = (title, description, task) => {
$("#command-title").text(title);
$("#command-description").text(description);
$("#challenge-description").text(task);
};
export { initializeExercise };
|
const axios = require('axios');
const {config} = require('./config.js');
const api = axios.create({
baseURL: process.env.API_SERVER_URL,
headers: {'X-Agent-Id': config.agentId},
});
function fetchAgentSettings() {
return api.get('/notify-agent');
}
function sendBuildResult({buildId, status, log}) {
return api.post('/notify-build-result', {buildId, status, log});
}
exports.serverApi = {
fetchAgentSettings,
sendBuildResult,
};
|
import { helper } from '@ember/component/helper';
export default helper(function satsToBtc(amount/*, hash*/) {
return amount / 100000000;
});
|
import React, { Component } from "react";
import MapView, { PROVIDER_GOOGLE } from "react-native-maps";
import { View, StyleSheet, Dimensions, Linking, Button } from "react-native";
import SegmentedControlTab from "react-native-segmented-control-tab"
import { Container, Content, Text } from "native-base";
import eventIcon from '../../assets/event.png';
//Components
import PlaceList from "../Place/PlaceList";
//Styles
import styles from "./styles";
//Firebase
import * as firebase from 'firebase';
import 'firebase/firestore';
/*
* For MapView, refer to: https://github.com/react-native-community/react-native-maps
* For Firebase, refer to: https://docs.expo.io/guides/using-firebase/
*/
class MapScreen extends Component {
static navigationOptions = {
};
constructor(props) {
super(props);
//Initial State
this.state = {
places: [],
selectedIndex: 0
};
}
async componentDidMount() {
console.log(this.props);
try {
await this.getPlaces();
} catch(err){
console.log(err);
}
}
async getPlaces() {
const placeMarkers = [];
//const eventMarkers = [];
// Get data from firestore
const firestore = firebase.firestore();
// Loop through the compost centers data and generate placeMarkers array
await firestore.collection("compost_centers").get().then(querySnapshot => {
console.log("Total compost centers: ", querySnapshot.size);
querySnapshot.forEach(documentSnapshot => {
console.log("data: ", documentSnapshot.data());
placeMarkers.push(documentSnapshot.data());
});
});
//Update our places array
this.setState({ places: placeMarkers });
console.log("updated markers data.");
//console.log("places to display: " + JSON.stringify(markers,null,4));
}
// Handle tab clicks
handleIndexChange = index => {
this.setState({
...this.state,
selectedIndex: index
});
console.log("selected tab:" + index);
console.log("load data...");
};
// render the map
render() {
// Use Chapel Hill location
const initialRegion = {
latitude: 35.913978,
longitude: -79.053979,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
};
const { places } = this.state;
// Followed the solution from https://stackoverflow.com/questions/58564916/react-native-maps-show-marker-callout
if (places.length>0) {
console.log("data is ready.");
return (
<View style={styles.container}>
<View style={styles.mapView}>
<MapView
style={{
flex: 1
}}
showsUserLocation = {false}
enableZoomControl={true}
provider={PROVIDER_GOOGLE}
ref={ref => this.map = ref}
initialRegion = {initialRegion}
onRegionChangeComplete={region => this.setState({ region })}
>
{places.map((marker, i) => (
<MapView.Marker
key={i}
coordinate={{
latitude: marker.location.latitude,
longitude: marker.location.longitude
}}
title={marker.name}
onCalloutPress={
() => {
// Launch google map
const url = "https://www.google.com/maps/search/?api=1&query="+marker.location.longitude+","+marker.location.latitude+"&query_place_id="+marker.place_id;
Linking.openURL(url);
}
}>
<MapView.Callout>
<View>
<Text>{marker.name}</Text>
</View>
</MapView.Callout>
</MapView.Marker>
))}
</MapView>
</View>
<View style={styles.placeList}>
<PlaceList type='places' places={places} map={this.map} />
</View>
</View>
) }
else {
console.log("data not arrived yet...");
return (
<View>
</View>
);
}
}
}
export default MapScreen;
|
angular.module('starter.services', ['ngResource'])
/**
* A simple example service that returns some data.
*/
.factory('PetService', function() {
// Might use a resource here that returns a JSON array
// Some fake testing data
var pets = [
{ id: 0, title: 'Cats', description: 'Furry little creatures. Obsessed with plotting assassination, but never following through on it.' },
{ id: 1, title: 'Dogs', description: 'Lovable. Loyal almost to a fault. Smarter than they let on.' },
{ id: 2, title: 'Turtles', description: 'Everyone likes turtles.' },
{ id: 3, title: 'Sharks', description: 'An advanced pet. Needs millions of gallons of salt water. Will happily eat you.' }
];
return {
all: function() {
return pets;
},
get: function(petId) {
// Simple index lookup
return pets[petId];
}
}
})
.factory('TrainingStats', function($resource){
return $resource('http://bb3.nifnic.nl/api/training', {})
})
.factory('PlayerTrainingStats', ['$resource', function($resource) {
return $resource( 'http://bb3.nifnic.nl/api/playerTraining/:playerID',
{ playerID: '@playerID', }
);
}])
.factory('Topscorers', function($resource){
return $resource('http://bb3.nifnic.nl/api/topScorers/1', {})
})
.factory('Ranking', function($resource){
return $resource('http://bb3.nifnic.nl/api/ranking/1', {})
})
.factory('SoccerMatches', function($resource){
return $resource('http://bb3.nifnic.nl/api/match', {})
})
.factory('Books', ['$resource', function($resource) {
return $resource( 'http://bb3.nifnic.nl/api/match/:bookId',
{ bookId: '@bookId' }, {
loan: {
method: 'PUT',
params: { bookId: '@bookId' },
isArray: false
}
/* , method2: { ... } */
} );
}])
.factory('MatchStats', ['$resource', function($resource) {
return $resource( 'http://bb3.nifnic.nl/api/match/:matchID/stats',
{ matchID: '@matchID', }
);
}])
.factory('Login', function($rootScope, $location, $window, $http) {
var isLoggedIn = false;
isLoggedIn = $window.sessionStorage.token !== null;
$rootScope.$on('user.login', function() {
$location.path('/index');
});
$rootScope.$on('user.logout', function() {
isLoggedIn = false;
// redir to login page
$location.path('/');
});
return {
isLoggedIn: function() { return isLoggedIn; },
login: function(usr, pass) {
// Do login here
//$http.defaults.useXDomain = true;
var postParams = {email: usr, password: pass};
$http
.post('http://bb3.nifnic.nl/api/login', postParams)
.success(function (data, status, headers, config) {
$window.sessionStorage.token = data.token;
isLoggedIn = true;
$rootScope.$broadcast('user.login');
})
.error(function (data, status, headers, config) {
//error handler
});
},
logout: function() {
$rootScope.$broadcast('user.logout');
}
}
});
|
import React, { useContext } from "react"
import styled from "styled-components"
import Image from "gatsby-image"
import { ElementContainer } from "../../styles/Containers"
import Headline1 from "./Headlines/Headline1"
import { SetBodyText } from "../../styles/BodyText"
import ScreenWidthContext from "../../context/ScreenWidthContext"
import { above } from "../../styles/Theme"
const IgniteCard = ({ headline, body, horizontalImage, verticalImage }) => {
const device = useContext(ScreenWidthContext)
return (
<CardContainer>
<ImageWrapper>
{device === "mobile" ? (
<ExtendedImage fluid={horizontalImage} />
) : (
<ExtendedImage fluid={verticalImage} />
)}
</ImageWrapper>
<ContentWrapper>
<Headline1>{headline}</Headline1>
<ElementContainer setMobileMarginTop={12}>
<SetBodyText dangerouslySetInnerHTML={{ __html: body }} />
</ElementContainer>
</ContentWrapper>
</CardContainer>
)
}
export default IgniteCard
const CardContainer = styled.div`
display: grid;
grid-template-columns: 1fr;
align-items: center;
background-color: #101010;
width: 100%;
max-width: 670px;
overflow: hidden;
border-radius: 10px;
box-shadow: 0 3px 4px 0px rgba(0, 0, 0, 0.4);
${above.mobile`
grid-template-columns: auto 1fr;
`}
`
const ExtendedImage = styled(Image)`
margin: 0;
padding: 0;
`
const ImageWrapper = styled.div`
width: 100%;
${above.mobile`
width: 280px;
`}
`
const ContentWrapper = styled.div`
display: flex;
flex-direction: column;
justify-items: center;
align-items: flex-start;
padding: 20px;
`
|
import * as React from "react";
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import clsx from 'clsx';
import businessCard from '../assests/business-card.jpg'
import businessCardMobile from '../assests/business-card-mobile.jpg'
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
}
}));
function BusinessCard(props) {
const classes = useStyles();
return (
<div className={clsx(classes.root, "pt-md-5 pb-md-5"
)}>
<Grid container spacing={0} className={"pt-md-5 pb-md-5 justify-center businessCard-container"}>
<Grid item xs={12} sm={10} md={5} className="businessCard-logo-col">
<picture className="w-100">
<source className="w-100" media="(max-width: 600px)" srcSet={businessCardMobile}/>
<source media="(max-width: 1200px)" srcSet={businessCard}/>
<img className="w-100 businessCard-logo" src={businessCard} alt="booking logo"></img>
</picture>
</Grid>
<Grid item xs={12} sm={10} md={4} className="content-section mb-5 businessCard-content-col">
<h2 className="businessCard-h2 text-right mt-md-5">بطاقه اعمال</h2>
<p className="businessCard-p text-right">
أنت تستحق بطاقة عمل تحمل شعارك واسمك ومعلومات الاتصال الخاصة بك ورمز الباركود الخاص بك لحجز مواعيدك من خلال الإنترنت
</p>
{/* <ul className="list businessCard-list">
<li className="item">
عرض كل معلومات الاتصال الخاصة بك بحيث يسهل الوصول الى حجز المواعيد من خلال الإنترنت
</li>
</ul> */}
</Grid>
</Grid>
</div>
);
}
export default BusinessCard; |
import { combineReducers } from "redux";
import breedReducer from "./breed";
import myListReducer from "./myList";
const allReducers = combineReducers({
breedReducer,
myListReducer,
});
export default allReducers; |
//require statements are loaded via browserify
//if browserify doesn't support a file, load it with file path
//angular dependencies
require('angular');
require('angular-ui-router');
require('./auth/auth.js');
require('./create/create.js');
require('./main/main.js');
require('./main/slide/slide.js');
require('./main/video/video.js');
require('./main/flyout/flyout.js');
require('./main/toolbar/toolbar.js');
require('./services.js');
//other dependencies
require('../../../node_modules/socket.io-client/socket.io.js');
//LearnSyncly
angular.module('lsync', [
'ui.router',
'lsync.auth',
'lsync.create',
'lsync.main',
'lsync.flyout',
'lsync.slide',
'lsync.video',
'lsync.services',
'lsync.toolbar'
])
.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('create', {
url: '/create',
templateUrl: 'app/create/create.html',
controller: 'CreateController'
})
.state('login', {
url: '/login',
templateUrl: 'app/auth/login.html',
controller: 'AuthController'
})
.state('logout', {
url: "/logout",
controller: function($scope, Auth) {
Auth.logout();
}
})
.state('main', {
url: '/',
views: {
'@': {
templateUrl: 'app/main/main.html',
controller: 'MainController',
},
'flyout@main': {
templateUrl: 'app/main/flyout/flyout.html',
controller: 'FlyoutController'
},
'toolbar@main': {
templateUrl: 'app/main/toolbar/toolbar.html',
controller: 'ToolbarController'
},
'slide@main': {
templateUrl: 'app/main/slide/slide.html',
controller: 'SlideController'
},
'video@main': {
templateUrl: 'app/main/video/video.html',
controller: 'VideoController'
}
}
})
.state('register', {
url: '/register',
templateUrl: 'app/auth/register.html',
controller: 'AuthController'
});
$httpProvider.interceptors.push('AttachTokens');
})
.factory('AttachTokens', function($window) {
var attach = {
request: function(object) {
var jwt = $window.localStorage.getItem('com.nova');
if (jwt) {
object.headers['x-access-token'] = jwt;
}
object.headers['Allow-Control-Allow-Origin'] = '*';
return object;
}
};
return attach;
})
.run(function($rootScope, $state, Auth) {
$rootScope.$on('$stateChangeStart', function(evt, toState, toParams, fromState, fromParams) {
if (toState.name === 'login') {
return;
}
if (!Auth.isAuth() && toState.name !== 'register') {
evt.preventDefault();
$state.go('login');
}
});
});
|
require('./configs/db.js');
const conf = require('./configs/conf.js');
const express = require('express');
const bodyParser = require('body-parser');
const verify = require('./middleware/verify-token.js');
const verifyToken = require('./middleware/verify-token.js');
const app = express();
const router = express.Router();
const API_VERSION = '/api/v1';
app.set('api_secret_key', conf.api_secret_key);
app.use(bodyParser.json());
// app.use('/',verifyToken);
app.use(API_VERSION, router);
const PORT = process.env.PORT || 3050;
require('./routers/add_user.js')(router);
require('./routers/get_users.js')(router);
require('./routers/get_user.js')(router);
app.listen(PORT, () => console.log('Server Running PORT : ' + PORT)); |
import React from 'react';
import styled from 'styled-components';
const StyledCol = styled.div`
display: flex;
flex: 1;
flex-direction: column;
flex-wrap: wrap;
width: 100%;
box-sizing: border-box;
`;
const Col = ({ children, justifyContent = 'flex-start', alignItems = 'flex-start', style, ...rest }) => {
return <StyledCol style={{ justifyContent, alignItems, ...style, ...rest }}>{children}</StyledCol>;
};
export default Col;
|
/**
* @file
* Utilities relating to files.
*/
const { workspace } = require('vscode');
/**
* Returns the `extraFiles` configuration as an array of document filters.
*
* @return {import('vscode').DocumentFilter[]}
* Document filters.
*/
module.exports.getExtraFileSelectors = () => workspace
.getConfiguration('phpSniffer')
.get('extraFiles', [])
.map((pattern) => ({ pattern, scheme: 'file' }));
|
export const adrian = {
"name": "Adrian",
"skills": "Python",
"gif": "https://media.giphy.com/media/l2Je0H39CPLlG4UkE/giphy.gif"
}
export default adrian
|
var assert = require('assert');
var nodeunit = require('nodeunit');
/**
* This test shows that native += operator on a String is much faster than a node Buffer
*/
/**
* @constructor
*/
function StringBuffer(preallocate) {
this.byteLength = 0;
this.buffer = new Buffer(preallocate);
};
StringBuffer.prototype.append = function (string) {
var lenNeeded = Buffer.byteLength(string) + this.byteLength;
if ( lenNeeded > this.buffer.length ) {
// reallocate
var newLen = this.buffer.length * 2 > lenNeeded ? this.buffer.length * 2 : lenNeeded;
var newBuffer = new Buffer(newLen);
this.buffer.copy(newBuffer, 0, 0, this.byteLength);
this.byteLength += newBuffer.write(string, this.byteLength, 'utf-8');
this.buffer = newBuffer;
}
else {
// append
this.byteLength += this.buffer.write(string, this.byteLength, 'utf-8');
}
};
StringBuffer.prototype.toString = function () {
return this.buffer.toString('utf-8', 0 , this.byteLength);
};
/**
* nodeunit test cases
*/
module.exports.test = function(test) {
var loops = 100000;
console.time("string concat");
var buf = '';
for (var i = 0 ; i < loops ; i++) {
buf += "@";
}
test.equals(loops, buf.length);
console.timeEnd('string concat');
console.time("string buffer");
var buf = new StringBuffer(100001);
for (var i = 0 ; i < 100000 ; i++) {
buf.append("@");
}
test.equals(loops, buf.toString().length);
console.timeEnd('string buffer');
test.done();
};
|
function getRootWin(){
var win = window;
while (win != win.parent){
win = win.parent;
}
return win;
}
/*
*异步http请求的session超时
*a)所有的ajax请求均带有x-requested-with:XMLHttpRequest头信息
*b)Ext.Ajax是单实例对象(非常重要,全局单一Ext.Ajax实例!)
*c)注册Ext.Ajax的requestcomplete事件,每个ajax请求成功后首先响应该事件(概念类似spring的aop拦截)。
Ext.Ajax.on(
'requestcomplete',
function (conn,response,options){
//Ext重新封装了response对象
if(typeof response.getResponseHeader.sessionstatus != 'undefined'){
//发现请求超时,退出处理代码...
getRootWin().location.href="/CustomerSecurityManagementSystem/login/login.jsp";
}
},
this
);
*/
// Create ajax request with hinting message while process data
// also contains session time out management
var myAjax = new Ext.data.Connection({
listeners : {
beforerequest : function() {
Ext.MessageBox.show({
title: 'Please wait',
progressText: 'Processing Data...',
width:300,
progress:true,
closable:false,
animEl: 'body'
});
},
requestcomplete : function(conn, response, options) {
Ext.MessageBox.hide();
if(typeof response.getResponseHeader.sessionstatus != 'undefined'){
getRootWin().location.href="/CustomerSecurityManagementSystem/selfService/start.action";
}
}
}
});
Ext.onReady(function(){
// create the Data Store
var store = new Ext.data.JsonStore({
root: 'customerInfos',
totalProperty: 'totalCount',
idProperty: 'id',
remoteSort: true,
fields: [ {name: 'id', type: 'int'}, 'customerId', 'customerName', 'nationality', 'certificateType', 'certificateId', {name: 'certificateBeginDate', mapping: 'certificateBeginDate', type: 'date', dateFormat: 'Y-m-d\\TH:i:s'}, {name: 'certificateEndDate', mapping: 'certificateEndDate', type: 'date', dateFormat: 'Y-m-d\\TH:i:s'}, 'mobileNumber', 'phoneNumber', {name: 'foreignFlag', type: 'bool'}, 'sex', 'birthday', 'zipcode', 'certificateAddress', 'address', 'relationcertificateId', 'relationcertificateType', 'instrperName', 'customerType', 'professionCode', 'branch', {name: 'riskValue', type: 'int'}, 'riskType', 'remark' ],
// ScriptTagProxy: load using script tags for cross domain, if the data in on the same domain as
// this page, an HttpProxy would be better
proxy: new Ext.data.HttpProxy ({
url: document.getElementById('example')
})
});
store.setDefaultSort('riskValue', 'desc');
var pagingBar = new Ext.PagingToolbar({
pageSize: 12,
store: store,
displayInfo: true,
displayMsg: 'Displaying topics {0} - {1} of {2}',
emptyMsg: "No topics to display"
});
// pluggable renders
function renderCertificate(value, p, record){
var str = '';
if(value != null && value != '')
str = str + String.format('<b>Type:</b>{0}<br/>', value);
if(record.data.certificateId != null && record.data.certificateId != '')
str = str + String.format('<b>ID:</b>{0}<br/>', record.data.certificateId);
if(record.data.certificateBeginDate != null && record.data.certificateBeginDate != '')
str = str + String.format('<b>BeginDate:</b>{0}<br/>', Ext.util.Format.date(record.data.certificateBeginDate,"Y-m-d"));
if(record.data.certificateEndDate != null && record.data.certificateEndDate != '')
str = str + String.format('<b>EndDate:</b>{0}<br/>', Ext.util.Format.date(record.data.certificateEndDate,"Y-m-d"));
if(record.data.certificateAddress != null && record.data.certificateAddress != '')
str = str + String.format('<b>Address:</b>{0}', record.data.certificateAddress);
return str;
}
function renderRelationCertificate(value, p, record){
if(record.data.relationcertificateId == null && value == null)
return String.format('');
if(record.data.relationcertificateId == null)
return String.format('<b>Type:</b>{0}', value);
if(value == null)
return String.format('<b>ID:</b>{0}', record.data.relationcertificateId);
return String.format(
'<b>Type:</b>{0}<br/><b>ID:</b>{1}',
value, record.data.relationcertificateId);
}
var sm = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
var grid = new Ext.grid.GridPanel({
id: 'customerInfosGrid',
el:'customers',
width:1000,
height:300,
title:'CustomerInfos List',
autoScroll:true,
store: store,
trackMouseOver:false,
disableSelection:true,
loadMask: true,
// grid columns
columns:[
sm,
{
id: 'info', // id assigned so we can apply custom css (e.g. .x-grid-col-info b { color:#333 })
header: "CustomerID",
dataIndex: 'customerId'
// width: 70,
// renderer: renderTopic,
// sortable: true
},{
header: "CustomerName",
dataIndex: 'customerName',
// width: 100,
hidden: true
// sortable: true
},{
header: "Nationality",
dataIndex: 'nationality',
// width: 70,
hidden: true,
align: 'left'
//sortable: true
},{
header: "Certificate",
dataIndex: 'certificateType',
renderer: renderCertificate,
align: 'left'
// sortable: true
},{
header: "MobileNumber",
dataIndex: 'mobileNumber',
hidden: true
// width: 150,
// renderer: renderLast,
// sortable: true
},{
header: "PhoneNumber",
dataIndex: 'phoneNumber',
hidden: true
// width: 150,
// renderer: renderLast,
// sortable: true
},{
header: "ForeignFlag",
dataIndex: 'foreignFlag',
// width: 150,
renderer: function(value){if(value==true) {return "境外";} else {return "境内";}},
sortable: true
},{
header: "Sex",
dataIndex: 'sex',
hidden: true
// width: 150,
// renderer: renderLast,
// sortable: true
},{
header: "Birthday",
dataIndex: 'birthday',
hidden: true
// width: 150,
// renderer: Ext.util.Format.dateRenderer('Y-m-d')
// sortable: true
},{
header: "ZipCode",
dataIndex: 'zipcode',
hidden: true
// width: 150,
// renderer: renderLast,
// sortable: true
},{
header: "Relationcertificate",
dataIndex: 'relationcertificateType',
// width: 150,
renderer: renderRelationCertificate,
hidden: true
// sortable: true
},{
header: "InstrperName",
dataIndex: 'instrperName',
// width: 150,
sortable: true
},{
header: "CustomerType",
dataIndex: 'customerType',
// width: 150,
// renderer: renderLast,
sortable: true
},{
header: "ProfessionCode",
dataIndex: 'professionCode'
// width: 150,
// sortable: true
},{
header: "Branch",
dataIndex: 'branch',
// width: 150,
sortable: true
},{
header: "RiskValue",
dataIndex: 'riskValue',
// width: 150,
// renderer: renderLast,
sortable: true
},{
header: "RiskType",
dataIndex: 'riskType',
// width: 150,
sortable: true
},{
header: "Remark",
dataIndex: 'remark',
hidden: true,
align: 'right'
}],
// customize view config
viewConfig: {
forceFit:true,
enableRowBody:true
//showPreview:true,
// Return CSS class to apply to rows depending upon preview
//getRowClass : function(record, rowIndex, p, store){
// if(this.showPreview){
// p.body = '<p>'+record.data.excerpt+'</p>';
// return 'x-grid3-row-expanded';
//}
// return 'x-grid3-row-collapsed';
// }
},
sm: sm,
// paging bar on the bottom
bbar: pagingBar
});
grid.on("rowcontextmenu",function(grid,rowIndex,e){
e.preventDefault();
if ( rowIndex < 0 ) {
return;
}
var treeMenu = new Ext.menu.Menu([
{xtype:"button",text:"添加",icon:"../images/add.png",pressed:true,handler:function(){ Ext.Msg.alert("提示消息","该功能还未实现!");}},
{xtype:"button",text:"编辑",icon:"../images/edit.png",pressed:true,handler:function(){
var rows = Ext.getCmp("customerInfosGrid").getSelections();
var record;
if(rows.length >= 1) {
record = rows[0];
} else {
Ext.Msg.alert("提示消息","请选择一行数据然后才能够编辑!");
return false;
}
//Create edit form
var fs = new Ext.FormPanel({
frame: true,
//headerAsText: true,
//bodyStyle: 'padding:5px 5px 5px 5px',
//style: 'padding:5px 5px 5px 5px;align:left',
anchor: '99%',
//defaultType: "textfield",
defaults: { anchor: this["anchor"] == null ? '95%' : this["anchor"] },
//baseCls: "x-plain",
labelAlign: 'right',
bodyStyle:'padding:5px 5px 0',
labelWidth: 150,
width:700,
waitMsgTarget: true,
method: 'POST',
//disabled: true,
items: [
new Ext.form.FieldSet({
autoHeight: true,
items: [{
layout:'column',
items:[{
columnWidth:.5,
layout: 'form',
items: [{
xtype:'textfield',
fieldLabel: 'CustomerID',
name: 'customerInfo.customerId',
value: record.data.customerId
//anchor:'95%'
}, {
xtype:'textfield',
fieldLabel: 'CustomerType',
name: 'customerInfo.customerType',
value: record.data.customerType
}]
},{
columnWidth:.5,
layout: 'form',
items: [{
xtype:'textfield',
fieldLabel: 'RiskValue',
name: 'customerInfo.riskValue',
value: record.data.riskValue
},{
xtype:'textfield',
fieldLabel: 'RiskType',
name: 'customerInfo.riskType',
value: record.data.riskType
}]
}]
},{
xtype:'textarea',
fieldLabel: 'Remark',
name: 'customerInfo.remark',
value: record.data.remark,
height: 60,
width: 300
},{
xtype:'tabpanel',
plain:true,
activeTab: 0,
height:180,
defaults:{bodyStyle:'padding:10px'},
items:[{
title:'Branch Details',
layout:'form',
defaults: {width: 230},
defaultType: 'textfield',
items: [{
fieldLabel: 'Branch',
hiddenName: 'customerInfo.branch',
value: record.data.branch,
// 需要更新营业部信息
store: new Ext.data.SimpleStore({data: [["总部"],["北京"]], fields:["branch"]}),
xtype: 'combo',
mode: 'local',
triggerAction: 'all',
forceSelection: true,
displayField: 'branch',
valueField: 'branch',
typeAhead:true,
//allowBlank: false,
editable: false,
anchor:'50%'
},{
xtype:'textfield',
fieldLabel: 'InstrperName',
name: 'customerInfo.instrperName',
value: record.data.instrperName
},{
xtype:'textfield',
fieldLabel: 'RelationcertificateId',
name: 'customerInfo.relationcertificateId',
value: record.data.relationcertificateId
}, {
xtype:'textfield',
fieldLabel: 'RelationcertificateType',
name: 'customerInfo.relationcertificateType',
value: record.data.relationcertificateType
}]
},{
title:'Certificate Details',
layout:'form',
defaults: {width: 230},
defaultType: 'textfield',
items: [{
fieldLabel: 'certificateID',
name: 'customerInfo.certificateId',
value: record.data.certificateId
}, {
fieldLabel: 'CertificateType',
name: 'customerInfo.certificateType',
value: record.data.certificateType
//vtype:
// allowBlank:false,
},{
xtype: 'datefield',
fieldLabel: 'CertificateBeginDate',
name: 'customerInfo.certificateBeginDate',
value: record.data.certificateBeginDate,
format: "Y-m-d"
}, {
fieldLabel: 'CertificateEndDate',
name: 'customerInfo.certificateEndDate',
value: record.data.certificateEndDate,
xtype: 'datefield',
format: "Y-m-d"
},{
//xtype:'textfield',
fieldLabel: 'CertificateAddress',
name: 'customerInfo.certificateAddress',
value: record.data.certificateAddress
}]
},{
title:'Contact Details',
layout:'form',
defaults: {width: 230},
defaultType: 'textfield',
items: [{
xtype:'textfield',
fieldLabel: 'MobileNumber',
name: 'customerInfo.mobileNumber',
value: record.data.mobileNumber
},{
xtype:'textfield',
fieldLabel: 'PhoneNumber',
name: 'customerInfo.phoneNumber',
value: record.data.phoneNumber
},{
xtype:'textfield',
fieldLabel: 'Zipcode',
name: 'customerInfo.zipcode',
value: record.data.zipcode
},{
xtype:'textfield',
fieldLabel: 'Address',
name: 'customerInfo.address',
value: record.data.address
},{
xtype:'textfield',
fieldLabel: 'Nationality',
name: 'customerInfo.nationality',
value: record.data.nationality
}]
},{
title:'Person Details',
layout:'form',
defaults: {width: 230},
defaultType: 'textfield',
items: [{
xtype:'textfield',
fieldLabel: 'CustomerName',
name: 'customerInfo.customerName',
value: record.data.customerName
},{
fieldLabel: 'Sex',
hiddenName: 'customerInfo.sex',
value: record.data.sex,
store: new Ext.data.SimpleStore({data: [["男"],["女"]], fields:["sex"]}),
xtype: 'combo',
mode: 'local',
triggerAction: 'all',
forceSelection: true,
displayField: 'sex',
valueField: 'sex',
typeAhead:true,
//allowBlank: false,
editable: false,
anchor:'50%'
}, {
fieldLabel: 'Birthday',
name: 'customerInfo.birthday',
value: record.data.birthday,
xtype: 'datefield',
format: 'Y-m-d'
}, {
xtype:'textfield',
fieldLabel: 'ProfessionCode',
name: 'customerInfo.professionCode',
value: record.data.professionCode
},{
fieldLabel: 'ForeignFlag',
hiddenName: 'customerInfo.foreignFlag',
value: record.data.foreignFlag,
store: new Ext.data.SimpleStore({data: [[true, "境外"],[false, "境内"]], fields:["foreignFlag","foreignFlagDesc"]}),
xtype: 'combo',
mode: 'local',
triggerAction: 'all',
forceSelection: true,
displayField: 'foreignFlagDesc',
valueField: 'foreignFlag',
typeAhead:true,
//allowBlank: false,
editable: false,
anchor:'50%'
}]
}]
},{
fieldLabel: 'id',
xtype: 'hidden',
name: 'customerInfo.id',
type: 'int',
value: record.data.id
}]
})
]
});
// EXT Window contains form
var win = new Ext.Window({
title: 'Edit Customer Information',
modal:true,
items: [fs],
plain: true,
width: 700,
buttons:[{
text: " OK ",
closeAction: function(){ win.destroy();},
handler: function(){
myAjax.request({
url:'/CustomerSecurityManagementSystem/example/save.action',
//method:POST,
params: fs.getForm().getValues(false),
success: function(result, request) {
var jsonData = Ext.util.JSON.decode(result.responseText);
Ext.Msg.alert("Success", jsonData.msg);
Ext.getCmp("customerInfosGrid").store.reload();
win.destroy();
},
failure: function(form, action) {
switch (action.failureType) {
case Ext.form.Action.CLIENT_INVALID:
Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
break;
case Ext.form.Action.CONNECT_FAILURE:
Ext.Msg.alert("Failure", "Ajax communication failed");
break;
case Ext.form.Action.SERVER_INVALID:
var jsonData = Ext.util.JSON.decode(result.responseText);
Ext.Msg.alert("Failure", jsonData.msg);
}
}
})
}
}, {
text: "Cancel",
handler: function(){
win.destroy();
//fs.destroy();
}
}]
});
win.show();
//fs.show();
}
},
//{xtype:"button",text:"隐藏",icon:"../images/arrow-down.gif",pressed:true,handler:function(){ Ext.Msg.alert("提示消息","该功能还未实现!");}},
// {xtype:"button",text:"显示",icon:"../images/arrow-up.gif",pressed:true,handler:function(){ Ext.Msg.alert("提示消息","该功能还未实现!");}},
{xtype:"button",text:"删除",icon:"../images/delete.png",pressed:true, handler:function(){
var rows = Ext.getCmp("customerInfosGrid").getSelections();
var record;
if(rows.length >= 1) {
record = rows[0];
} else {
Ext.Msg.alert("提示消息","请选择一行数据然后才能够删除!");
return false;
}
myAjax.request({
url:'/CustomerSecurityManagementSystem/example/delete.action',
//method:post,
params:{id:record.data.id},
success: function(result, request) {
var jsonData = Ext.util.JSON.decode(result.responseText);
Ext.Msg.alert("Success", jsonData.msg);
Ext.getCmp("customerInfosGrid").store.reload();
},
failure: function(form, action) {
switch (action.failureType) {
case Ext.form.Action.CLIENT_INVALID:
Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
break;
case Ext.form.Action.CONNECT_FAILURE:
Ext.Msg.alert("Failure", "Ajax communication failed");
break;
case Ext.form.Action.SERVER_INVALID:
var jsonData = Ext.util.JSON.decode(result.responseText);
Ext.Msg.alert("Failure", jsonData.msg);
}
}
})
}}
]);
treeMenu.showAt(e.getPoint());
});
// render it
grid.render();
// Create file upload form
var fileUpload = new Ext.FormPanel({
labelAlign: 'right',
title: 'Upload Customer Source File',
bodyStyle:'padding:5px',
//frame: true,
width: 600,
renderTo: 'customersSource',
fileUpload: true,
//baseCls: 'x-plain',
items: [{
xtype:'textfield',
inputType: 'file',
allowBlank:false,
fieldLabel: '文件',
disabled:false,
name: 'upload',
//maxLength:25,
blankText: '请上传文件',
anchor:'90%'
}],
buttons: [{
text: '上传',
handler: function(){
fileUpload.getForm().submit({
//clientValidation: true,
//method: POST,
url: '/CustomerSecurityManagementSystem/example/upload.action',
success: function(form, action) {
Ext.Msg.alert("Success", action.result.msg);
},
failure: function(form, action) {
switch (action.failureType) {
case Ext.form.Action.CLIENT_INVALID:
Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
break;
case Ext.form.Action.CONNECT_FAILURE:
Ext.Msg.alert("Failure", "Ajax communication failed");
break;
case Ext.form.Action.SERVER_INVALID:
Ext.Msg.alert("Failure", action.result.msg);
}
}
})
}
}]
});
// trigger the data store load
store.load({params:{start:0, limit:12}});
});
|
// get an instance of mongoose and mongoose.Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// set up a mongoose model and pass it using module.exports
module.exports = mongoose.model('Matrix', new Schema({
name: { type: String, trim: true },
user_id: String,
created: Date,
circles:{
last_modified: Date,
first_circle:{
total: Number,
voucher: Array, //{ id: String, grade: Number, source: String }
last_modified: Date
},
second_circle:{
total: Number,
voucher: Array, //{ id: String, grade: Number, source: String }
last_modified: Date
},
third_circle:{
total: Number,
voucher: Array, //{ id: String, grade: Number, source: String }
last_modified: Date
},
my_voucher:{
total: Number,
voucher: Array, //{ id: String, grade: Number, source: String }
last_modified: Date
}
}
})); |
// let s = new Subject()
// setInterval(() => {
// s.sendNext(1)
// }, 1000)
//every
// Signal
// //.fromArray([2, 3, 4])
// .error('error')
// .catchError(Signal.fromArray([5,6,7]))
// .startWith(4)
// .endWith(8)
// // .every(v => v >= 2)
// // .some(v => v)
// // .concat(Signal.of(2).delay(1000))
// // .concat(Signal.of(3).delay(1000))
// // .concat(Signal.of(1).delay(1000))
// .concat(Signal.interval(1000).take(4))
// .repeat(3)
// // .bufferTime(1000, 1)
// // .debounce(s)
// // .debounceTime(2000)
// // .throttleTime(3000)
// .subscribeNext(v => {
// console.log(v)
// })
// let a = []
// a.length = 2
// let b = new Proxy(a, {
// get: function(obj, pro) {
// if (typeof pro === 'string') {
// console.log(pro)
// }
// return a[pro]
// },
// set: function(obj, pro, value) {
// a[pro] = value
// }
// })
// console.log(b)
|
import React from 'react';
const ChapterView = () => (
<h1>ChapterView</h1>
);
export default ChapterView;
|
"use strict";
const input = document.querySelector("input#name-input");
const output = document.querySelector("span#name-output");
input.addEventListener('input', () => {
output.textContent = input.value || "незнакомец";
});
|
require('dotenv').config()
const express = require('express')
const cors = require('cors')
const morgan = require('morgan')
const db = require('./db')
const app = express()
app.use(cors())
app.use(express.json())
app.use(morgan('dev'))
const port = process.env.PORT
//GET ALL RESTAURANTS
app.get('/api/v1/restaurants', async (req,res) => {
try {
const {rows} = await db.query('SELECT * FROM restaurants LEFT JOIN (SELECT restaurant_id, COUNT(*),TRUNC(AVG(rating),1) as average_rating from reviews group by restaurant_id) reviews on restaurants.id = reviews.restaurant_id')
res.json({
status: 'success',
results: rows.length,
data:{
restaurants: rows
}
})
} catch (error) {
res.status(500).send(error)
console.log(error)
}
})
//GET SINGLE RESTAURANT
app.get('/api/v1/restaurants/:id',async(req,res) => {
try {
const restaurant = await db.query('SELECT * FROM restaurants LEFT JOIN (SELECT restaurant_id, COUNT(*),TRUNC(AVG(rating),1) as average_rating from reviews group by restaurant_id) reviews on restaurants.id = reviews.restaurant_id WHERE id = $1',[req.params.id])
const reviews = await db.query('SELECT * FROM reviews WHERE restaurant_id = $1',[req.params.id])
console.log(restaurant)
res.json({
status:'success',
data:{
restaurant: restaurant.rows[0],
reviews: reviews.rows
}
})
} catch (error) {
res.status(500).send(error)
console.log(error)
}
})
//CREATE RESTAURANT
app.post('/api/v1/restaurants',async (req,res) => {
try {
const {name,location,price_range} = req.body
const {rows} = await db.query('INSERT INTO restaurants(name,location,price_range) VALUES ($1,$2,$3) returning *',
[name,location,price_range]
)
res.status(201).json({
status:'success',
data:{
restaurant: rows[0]
}
})
} catch (error) {
res.status(500).send(error)
console.log(error)
}
})
//update restaurant
app.put('/api/v1/restaurants/:id',async(req,res) => {
try {
const {name,location,price_range} = req.body
const {rows} = await db.query('UPDATE restaurants SET name = $1, location = $2, price_range = $3 WHERE id = $4 returning *',[name,location,price_range,req.params.id])
res.status(200).json({
status:'success',
data: {
restaurant: rows[0]
}
})
} catch (error) {
res.status(500).send(error)
console.log(error)
}
})
//DELETE RESTAURANT
app.delete('/api/v1/restaurants/:id',async(req,res) => {
try {
const {rows} = await db.query('DELETE FROM restaurants WHERE id = $1',[req.params.id])
res.status(204).json({
status:"success"
})
} catch (error) {
console.log(error)
res.status(500).send(error)
}
})
app.post('/api/v1/restaurants/:id/addReview',async (req,res) => {
try {
const {name,review,rating} = req.body
const {rows} = await db.query('INSERT INTO reviews(restaurant_id,name,review,rating) VALUES ($1,$2,$3,$4)',[req.params.id,name,review,rating])
res.status(201).json({
status:'success',
data:{
review: rows[0]
}
})
} catch (error) {
res.status(500).send(error)
console.log(error)
}
})
app.listen(port,() => {
console.log(`its working on port: ${port}`)
}) |
function getUrlForLinks (val) {
if (val === "Home") {
return url_for(".");
} else if (val === "My Poor Skills - Blog") {
return "http://blog.anshulgautam.in";
} else if (val === "About") {
return url_for("about");
} else if (val === "Labels") {
return url_for("tags");
} else if (val === "Archives") {
return url_for("archives");
}
} |
/**
* The rand7() API is already defined for you.
* var rand7 = function() {}
* @return {number} a random integer in the range 1 to 7
*/
var rand10 = function() {
let temp = 100;
while(temp > 40) {
temp = (rand7()-1) * 7 + rand7();
}
return temp %10+1;
};
function rand7() {
return Math.ceil(Math.random()*7);
} |
/**
* Created by johni on 25/04/2016.
*/
var aws = require('aws-sdk'),
s3 = new aws.S3(),
q = require('q'),
gm = require('gm').subClass({imageMagick: true}),
_ = require('lodash');
function parse(sqsMessage) {
console.info("parse: input:\n", JSON.stringify(sqsMessage));
if (_.isEmpty(sqsMessage.Records)) {
throw Error("SQS message has no records");
}
var image = {
Bucket: sqsMessage.Records[0].s3.bucket.name,
Key: sqsMessage.Records[0].s3.object.key.replace(/\+/g, " ")
};
console.info("parse: output:\n", JSON.stringify(image));
return q.resolve(image);
}
function s3GetObjectPromise(params) {
var defer = q.defer();
s3.getObject(params, function (err, data) {
if (err) {
defer.reject(err);
} else {
params.Body = data.Body;
params.ContentType = data.ContentType;
defer.resolve(params);
}
});
return defer.promise;
}
function s3PutObjectPromise(params) {
var defer = q.defer();
params.ACL = 'public-read';
s3.putObject(params, function (err, data) {
if (err) {
defer.reject(err);
} else {
defer.resolve(data);
}
});
return defer.promise;
}
function makeThumbnail(image) {
var defer = q.defer();
gm(image.Body, 'image')
.resize(256, 256)
.toBuffer('JPG', function (err, stdout) {
if (err) {
defer.reject(err);
} else {
image.Body = stdout;
image.Key = image.Key.replace(/^images/, "thumbs");
defer.resolve(image);
}
});
return defer.promise;
}
module.exports = {
parse: parse,
s3GetObject: s3GetObjectPromise,
s3PutObject: s3PutObjectPromise,
makeThumbnail: makeThumbnail
};
|
import 'bootstrap';
import 'bootstrap/css/bootstrap.css!';
import {RoutesConfig} from 'app/router-config';
import {AuthorizeStep} from 'app/security/authorization-step';
export class App {
configureRouter(config, router){
config.title = 'Notes';
config.addPipelineStep('authorize',AuthorizeStep);
var routes = RoutesConfig.getRoutes();
config.map(routes);
this.router = router;
}
}
|
/**
* 模块引用
* @private
*/
let { generator, db } = require('../../core/framework');
/**
* 内部变量定义
* @private
*/
let entity = {
"table": "common_dicts",
"columns": [
{ "name": "dictkey", "primary": true, "filter": true, "unique": true },
{ "name": "itemkey", "primary": true, "filter": true, "unique": true },
{ "name": "itemvalue", "filter": true, "requid": true }
]
}
/**
* 模块定义
* @public
*/
module.exports = {
"rootpath": "/api/dict/",
"description":"数据字典管理",
"mapping": {
"default": { "description": "获取字典数据列表" },
"all": { "description": "获取全部字典数据列表" },
"insert": { "description": "新增字典数据" },
"update": { "description": "修改字典数据" },
"delete": { "description": "删除字典数据" }
},
"entity": entity,
"all": (req, res) => {
var params = [];
var sql = 'SELECT * from ' + entity.table;
db.query(sql, params, function (err, rows, fields) {
if (err) {
res.send(generator.message(err.message));
} else {
// rows.forEach(function (row) {
// row.itemvalue = base64.encode(row.itemvalue);
// });
res.send(generator.data({ "list": rows }));
}
});
}
}; |
import styled from "styled-components";
const Title = styled.h1`
color: #fff;
font-weight: lighter;
margin-left: 10px;
`;
export default ({ text, style }) => {
return <Title style={style}>{text}</Title>;
};
|
import React, {Component} from 'react'
import { Breadcrumb } from 'antd'
class MyCrumb extends Component {
render() {
return (
<Breadcrumb style={{ padding: '20px' }}>
<Breadcrumb.Item>Home</Breadcrumb.Item>
<Breadcrumb.Item>An Application</Breadcrumb.Item>
</Breadcrumb>
)
}
}
export default MyCrumb |
import React, { useState } from "react";
import { registerDoctorAPI } from "../Utils/Shared/apiCall";
function Doctor() {
const [doctorName, setDoctorName] = useState("");
const [gender, setGender] = useState("");
const handleSelectChange = (e) => {
setGender(e.target.value);
};
const handleSaveClick = () => {
if ((doctorName !== "") & (gender !== "CHOOSE")) {
const promise = registerDoctorAPI(doctorName, gender);
promise
.then((res) => {
let serverData = res.data;
alert(serverData);
setDoctorName("");
})
.catch((err) => {
alert("Error Occured while Regiter Doctor");
});
} else {
alert("Provide Valid Data");
}
};
return (
<div>
<h4>Add Your Doctors</h4>
<div>
<label>DoctorName</label>
<input
type="text"
value={doctorName}
onChange={(e) => setDoctorName(e.target.value)}
/>
</div>
<div>
<label>Gender</label>
<select onChange={handleSelectChange}>
<option>CHOOSE</option>
<option>MALE</option>
<option>FEMALE</option>
<option>OTHERS</option>
</select>
</div>
<div>
<input type="button" value="SAVE" onClick={handleSaveClick} />
</div>
</div>
);
}
export default Doctor;
|
import React, { Component } from 'react';
import './App.css';
import Display from './Display';
import * as math from 'mathjs-simple-integral'
export default class Derivative extends Component {
constructor(props) {
super(props);
this.state = ({
value: null,
variable: 'x',
displayvalue: null,
})
}
input = (event) => {
this.setState({
[event.target.name]: event.target.value
});
}
integrate = () => {
try {
this.setState({displayvalue: math.integral(this.state.value, this.state.variable).toString()});
}
catch(e) {
this.setState({displayvalue:'error'});
}
}
render() {
return (
<div class="calculator">
<span class="main-input">
Expression: <input type="text" name="value" onChange={this.input}></input> <br></br>
Variable: <input type="text" value={this.state.variable} name="variable" onChange={this.input}></input>
</span>
<button class="btn" onClick={ this.integrate }>Calculate</button>
<Display value= { this.state.displayvalue } />
</div>
);
}
}
|
import React, { useState } from "react";
import Header from "./Header";
import Editor from "./Editor";
import { StateContext } from "./contexts/StateContext";
function App() {
// controls whether or not dark mode is enabled
const [darkMode, setDarkMode] = useState(false);
// controls whether or not the modal is displayed
const [modal, setModal] = useState(true);
// required for reactstrap dropdown menu to work -
// controls if dropdown is collapsed or displayed
const [dropdownOpen, setDropdownOpen] = useState(false);
// The next two slices of state are updated by the Editor component
// string representation of the words written
const [text, setText] = useState("");
// number of words written
const [wordsWritten, setWordsWritten] = useState(0);
// number of lights to turn on based on the challenge parameters and words written
const [lightsToTurnOn, setLightsToTurnOn] = useState(0);
// how many words it takes to power one light (this is set by user)
const [wordsPerLight, setWordsPerLight] = useState(167);
return (
<StateContext.Provider
value={{
darkMode,
setDarkMode,
modal,
setModal,
dropdownOpen,
setDropdownOpen,
text,
setText,
wordsWritten,
setWordsWritten,
wordsPerLight,
setWordsPerLight,
lightsToTurnOn,
setLightsToTurnOn
}}
>
<div className={darkMode ? "app-dark" : "app-light"}>
<Header />
<Editor />
</div>
</StateContext.Provider>
);
}
export default App;
|
const studentDelete = require('./DeleteStudentDetails');
const studentUpdate = require('./UpdateStudentDetails');
class StudentUpdateController {
async input(req, message) {
message.METHOD = req.method;
if (req.method == "DELETE") {
studentDelete.input(req, message)
}
else if (req.method == "PUT") {
studentUpdate.input(req, message)
}
}
async process(message) {
if (message.METHOD == "DELETE") {
await studentDelete.process(message)
}
else if (message.METHOD == "PUT") {
await studentUpdate.process(message)
}
}
async output(res, message) {
if (message.METHOD == "DELETE") {
studentDelete.output(res, message)
}
else if (message.METHOD == "PUT") {
studentUpdate.output(res, message)
}
}
inputValidation(req) {
}
}
module.exports = new StudentUpdateController();
|
import { connect } from 'react-redux'
import { addTicker, addAlert } from '../actions'
import AddTickerComponent from '../components/AddTicker'
const mapStateToProps = (state) => ({
tickers: state.tickerList,
})
const dispatchProps = (dispatch) => ({
addTicker: (newTicker, tickers) => {
if (tickers.indexOf(newTicker) > -1) {
dispatch(addAlert(`${newTicker} already exists!`))
return;
}
dispatch(addTicker(newTicker))
}
})
const AddTicker = connect(
mapStateToProps,
dispatchProps,
)(AddTickerComponent)
export default AddTicker
|
import fetchBooks from '../util/fetchBooks';
global.fetch = jest.fn(() => {
return Promise.resolve({
json: () => Promise.resolve({ kind: 'books#volumes' })
});
});
beforeEach(() => {
fetch.mockClear();
});
describe('fetch-books-unit-test', () => {
it('contains items', async () => {
const json = await fetchBooks('salesforce');
await expect(json.kind).toBe('books#volumes');
});
}); |
import React, { Component } from 'react';
import Column from './column';
import './stylesheet/styles.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
enteredData: [],
};
}
componentDidMount() {
// Simple GET request using fetch
fetch('/routes')
.then(response => response.json())
.then(data => this.setState({ databaseInfo: data }))
.catch(error => {
this.setState({ errorMessage: error.toString() });
console.error('There was an error!', error);
});
getSix(this.state.databaseInfo)
}
componentDidMount() {
// var requestOptions = {
// // mode: 'no-cors',
// method: 'GET',
// redirect: 'follow'
// };
fetch("/routes/tickets")
.then(data => data.json())
.then(data => console.log('THIS IS THE DATA WE ARE GETTING BACK -------->', data))
// .then(response => response.text())
// .then(result => console.log('resit;',result))
.catch(error => console.log('error in APP.jS FETCH REQUEST ====>', error));
// console.log("component did mount");
// fetch('http://localhost:3000/routes')
// .then((res) => console.log('RES.BODY IS HERE ->>>>>', res.body));
// // .then((res) => res.json())
// // .then((res) => console.log(res));
// // .then((data) => this.setState({ enteredData: enteredData.concat(data) }))
// // .catch((err) => console.log('DATA FETCH ERROR'));
}
render() {
const columnDisplay = [];
const columnName = ['Backlog', 'Sprint', 'To Do', 'Doing', 'Review', 'Done'];
for (let i = 0; i < 6; i++) {
columnDisplay.push(<Column name={columnName[i]} key={i} />);
}
//check if column name is "blacklog, if it is, push Card component "
return (
<div>
<h2 id="appName">taskShark</h2>
<h4 id="title">THAT IS GOING TO BE A TITLE</h4>
<div className="container">
{columnDisplay}
</div>
</div>
);
}
}
export default App;
|
var alertsControllers = angular.module('alertsControllers', []);
//////////////////////////////// ALERTAS
alertsControllers.controller('AlertsListCtrl', ['$scope', 'getAlerts',
function($scope, getAlerts) {
$scope.alerts = getAlerts.query();
}]);
alertsControllers.controller('AlertsForAlertIdCtrl', ['$scope','$routeParams','getAlerts',
function($scope,$routeParams, getAlerts) {
$scope.alerts = getAlerts.query({idAlerta:$routeParams.alertId});
}]);
//////////////////////////////// CLIENTES
alertsControllers.controller('ClientsListCtrl', ['$scope', 'getClients',
function($scope,getClients) {
$scope.clients = getClients.query();
}]);
alertsControllers.controller('ClientsForClientIdCtrl', ['$scope','$routeParams', 'getClients',
function($scope,$routeParams,getClients) {
$scope.clients = getClients.query({idCliente:$routeParams.clientId});
}]);
//////////////////////////////// TRANSACCIONES
alertsControllers.controller('TransactionsListCtrl', ['$scope','getTransactions',
function($scope,getTransactions) {
$scope.transactions = getTransactions.query();
}]);
alertsControllers.controller('TransactionsForAlertIdCtrl', ['$scope','$routeParams', 'getTransactions',
function($scope,$routeParams,getTransactions) {
$scope.transactions = getTransactions.query({idAlerta:$routeParams.alertId});
}]);
//////////////////////////////// TRANSACCIONES RELEVANTES
alertsControllers.controller('TransactionsRListCtrl', ['$scope','getTransactionsR',
function($scope,getTransactionsR) {
$scope.transactionsR = getTransactionsR.query();
}]);
alertsControllers.controller('TransactionsRForAccountIdCtrl', ['$scope','$routeParams', 'getTransactionsR',
function($scope,$routeParams,getTransactionsR) {
$scope.transactionsR = getTransactionsR.query({idCuenta:$routeParams.accountId});
}]);
//////////////////////////////// ACCOUNTS
alertsControllers.controller('AccountsListCtrl', ['$scope','getAccounts',
function($scope,getAccounts) {
$scope.accounts = getAccounts.query();
}]);
alertsControllers.controller('AccountsForClientIdCtrl', ['$scope','$routeParams', 'getAccounts',
function($scope,$routeParams,getAccounts) {
$scope.accounts = getAccounts.query({idCliente:$routeParams.clientId});
}]);
//////////////////////////////// CR OPERATIONS
alertsControllers.controller('CrOpListCtrl', ['$scope','getCrOp',
function($scope,getCrOp) {
$scope.crOp = getCrOp.query();
}]);
alertsControllers.controller('CrOpForCrIdCtrl', ['$scope','$routeParams', 'getCrOp',
function($scope,$routeParams,getCrOp) {
$scope.crOp = getCrOp.query({idCr:$routeParams.crId});
}]);
|
// The first century spans from the year 1 up to and including the year 100, the second century - from the year 101 up to and including the year 200, etc.
// Task
// Given a year, return the century it is in.
// Examples
// 1705 --> 18
// 1900 --> 19
// 1601 --> 17
// 2000 --> 20
// function century(year) {
// // Finish this :)
// return;
// }
// at first I was going to write one long conditional for each century but then I realized that it would be too much code to do it that way
// to simplify the code I decided I should check the last number in the num/str to see if it is 0 or !
// if 0 then century could be calculated by year / 100
// if !0 then century could be calculated by year/ 100 + 1
// to check the last number I wanted to check the index of the year.split("") at [3] this wouldn't work for year < 1000
//I then realized that I could solve this problem by looking at the yearArr[-1]
// after that I realized that I would need to take off the 2 end numbers instead of year/100
//Pages used
//https://dev.to/sanchithasr/7-ways-to-convert-a-string-to-number-in-javascript-4l
//A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence.
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
let century = year => {
let yearNum = year.toString()
let yearSlice = yearNum.slice(-2)
let centurySlice = yearNum.slice(0,-2)
if (yearSlice == "00") {
console.log(Number(centurySlice))
return Number(centurySlice)
} else {
console.log(Number(centurySlice) + 1)
return Number(centurySlice) + 1
}
}
console.log(century(820))
//other solutions that are even simpler
function century(year) {
return Math.ceil(year/100); //using ceiling method to round up to nearest century (100)
}
let century = year => Math.ceil(year/100) |
$(document).ready(function () {
Cargar();
$("#closemodal").click(function (event) {
$(".lean-overlay").remove();
});
});
function openmodal(btn) {
$("#modal2").openModal();
Mostrar(btn);
}
function Cargar() {
var tabladatos = $('#datos');
var route = "/listarmoneda/";
$('#datos').empty();
$.get(route, function (res) {
$(res).each(function (key, value) {
tabladatos.append("<tr>" +
"<td>" + value.moneda + "</td>" +
"<td>" + value.bs + "</td>" +
"<td>" +
"<button value=" + value.id + " OnClick='openmodal(this);' class='waves-effect waves-light btn btn-floating' href='#' title='Editar'>" +
"<i class='material-icons'>mode_edit</i>" +
"</button>" +
"</td><td>" +
"<button class='btn btn-danger btn-floating' value=" + value.id + " OnClick='Eliminar(this);' title='Eliminar'>" +
"<i class='material-icons'>delete</i>" +
"</button>" +
"</td>" +
"</tr>");
});
paginador();
});
}
function Mostrar(btn) {
debugger;
var route = "/Moneda/" + btn.value + "/edit";
$.get(route, function (res) {
debugger;
$("#bss").val(res[0].bs);
$("#nombre").val(res[0].moneda);
$("#idactualizar").val(res[0].id);
});
}
function Eliminar(btn) {
if ($("#perfilpuedeEliminar").val() == 1) {
var route = "/Moneda/" + btn.value + "";
var token = $("#token").val();
swal({title: "ESTA SEGURO QUE DESEA ELIMINAR LA MONEDA?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Si, eliminarlo!",
cancelButtonText: "No, cancelar!",
closeOnConfirm: false,
closeOnCancel: false},
function (isConfirm) {
if (isConfirm) {
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: 'DELETE',
dataType: 'json',
success: function () {
$('#tablacategoria').DataTable().destroy();
Cargar();
swal({title: "ELIMINACION COMPLETA",
type: "success",
showConfirmButton: false,
closeOnConfirm: false,
timer: 1000});
}
});
} else {
swal({title: "CANCELADO",
type: "error",
showConfirmButton: false,
closeOnConfirm: false,
timer: 1000});
}
});
} else {
swal({title: "NO TIENE PERMISO PARA ELIMINAR",
type: "warning",
showConfirmButton: false,
closeOnConfirm: false,
timer: 1000});
}
}
$("#actualizar").click(function () {
debugger;
if ($("#perfilpuedeModificar").val() == 1) {
var value = $("#idactualizar").val();
var nombre = $("#nombre").val();
var bs = $("#bss").val();
if (!nombre || !nombre.trim().length) {
Materialize.toast("NOMBRE VACIO", 1000, "rounded");
return;
}
if (!bs || !bs.trim().length) {
Materialize.toast("BS VACIO", 1000, "rounded");
return;
}
var route = "/Moneda/" + value + "";
var token = $("#token").val();
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: 'PUT',
dataType: 'json',
data: {
moneda: nombre,
bs: bs
},
success: function () {
$('#tablacategoria').DataTable().destroy();
Cargar();
$("#modal2").closeModal();
$('.lean-overlay').remove();
swal({title: "ACTUALIZACION COMPLETA",
type: "success",
showConfirmButton: false,
closeOnConfirm: false,
timer: 1000});
},
error: function () {
$("#modal2").closeModal();
$('.lean-overlay').remove();
swal({title: "ERROR AL ACTUALIZAR",
type: "error",
showConfirmButton: false,
closeOnConfirm: false,
timer: 1000});
}
});
} else {
swal({title: "NO TIENE PERMISO PARA ACTUALIZAR",
type: "warning",
showConfirmButton: false,
closeOnConfirm: false,
timer: 1000});
}
});
$("#guardar").click(function () {
debugger;
if ($("#perfilpuedeGuardar").val() == 1) {
var nombre = $("#moneda").val();
var bs = $("#bs").val();
if (!nombre || !nombre.trim().length) {
Materialize.toast("NOMBRE VACIO", 1000, "rounded");
return;
}
if (!bs || !bs.trim().length) {
Materialize.toast("BS VACIO", 1000, "rounded");
return;
}
var route = "/Moneda";
var token = $("#token").val();
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: 'POST',
dataType: 'json',
data: {
moneda: nombre,
bs: bs
},
success: function () {
$('#tablacategoria').DataTable().destroy();
Cargar();
$("#modal1").closeModal();
$(".lean-overlay").remove();
swal({title: "CARGO GUARDADO EXITOSAMENTE",
type: "success",
showConfirmButton: false,
closeOnConfirm: false,
timer: 1000});
$("#nombre").val("");
},
error: function () {
$('.lean-overlay').remove();
swal({title: "ERROR AL GUARDAR",
type: "error",
showConfirmButton: false,
closeOnConfirm: false,
timer: 1000});
}
});
} else {
swal({title: "NO TIENE PERMISO PARA GUARDAR",
type: "warning",
showConfirmButton: false,
closeOnConfirm: false,
timer: 1000});
}
});
function paginador() {
// Setup - add a text input to each footer cell
$('#tablacategoria tfoot th').each(function () {
var title = $(this).text();
if (title == "") {
} else {
$(this).html('<input type="text" placeholder="' + title + '" style=" border-radius: 3px;"/>');
}
});
var table = $('#tablacategoria').DataTable({
pagingType: "full_numbers",
retrieve: true,
order: [0, 'asc'],
responsive: true
});
table.columns().every(function () {
var that = this;
$('input', this.footer()).on('keyup change', function () {
if (that.search() !== this.value) {
that.search(this.value).draw();
}
});
});
} |
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const config_1 = require("../config");
const moment = require("moment");
const request = require("request-promise");
const LogHelper_1 = require("../helpers/LogHelper");
const fileName = 'YodleeHelper';
class YodleeHelper {
static getAccessToken() {
return __awaiter(this, void 0, void 0, function* () {
let YODLEE = config_1.Config.PROJECT.YODLEE;
try {
let result = yield request({
uri: YODLEE.API_BASE + 'cobrand/login',
headers: { 'Content-Type': 'application/json' },
method: 'POST',
body: {
'cobrand': {
'cobrandLogin': YODLEE.USERNAME,
'cobrandPassword': YODLEE.PASSWORD,
'locale': 'en_US'
}
},
json: true
});
return result;
}
catch (error) {
LogHelper_1.default.logService.create(error);
}
});
}
static getLoginToken(loginName, password) {
return __awaiter(this, void 0, void 0, function* () {
let YODLEE = config_1.Config.PROJECT.YODLEE;
const fnName = 'Login Yodlee';
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: `${YODLEE.API_BASE} + 'user/login'`, description: `loging On Yodlee With Login Name : ${loginName}`, status: 1 });
let cobrandToken = yield this.getAccessToken();
let userToken = yield request({
uri: YODLEE.API_BASE + 'user/login',
headers: { 'Content-Type': 'application/json', 'Authorization': `{cobSession=${cobrandToken.session.cobSession}}` },
method: 'POST',
body: {
'user': {
'loginName': loginName,
'password': password,
}
},
json: true
});
return {
cobrandToken: cobrandToken.session.cobSession,
userToken: userToken.user.session.userSession
};
});
}
static createAccount(userId, email) {
return __awaiter(this, void 0, void 0, function* () {
const fnName = 'create Account';
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: `${config_1.Config.PROJECT.YODLEE.API_BASE} + 'user/register'`, description: `Create Account With UserId: ${userId} - Email:${email}`, status: 1 });
let cobrandToken = yield this.getAccessToken();
const body = {
'user': {
'loginName': 'JustDone_Live_' + userId,
'password': '@69n@mTech@hungLive!',
'email': email,
'preferences': {
'currency': 'USD',
'timeZone': 'PST',
'dateFormat': 'MM/dd/yyyy',
'locale': 'en_US'
}
}
};
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: `${config_1.Config.PROJECT.YODLEE.API_BASE} + 'user/register'`, description: 'Request Yodlee With Url :' + config_1.Config.PROJECT.YODLEE.API_BASE + 'user/register', status: 1 });
let yodleeAccount = yield request({
uri: config_1.Config.PROJECT.YODLEE.API_BASE + 'user/register',
headers: { 'Content-Type': 'application/json', 'Authorization': `{cobSession=${cobrandToken.session.cobSession}}` },
method: 'POST',
body: body,
json: true
});
if (yodleeAccount && yodleeAccount.user)
return 1;
else
return 0;
});
}
static removeBank(loginName, password, providerAccountId) {
return __awaiter(this, void 0, void 0, function* () {
let userToken = yield this.getLoginToken(loginName, password);
return yield request({
uri: config_1.Config.PROJECT.YODLEE.API_BASE + 'providerAccounts/' + providerAccountId,
headers: {
'Content-Type': 'application/json',
'Authorization': `{cobSession=${userToken.cobrandToken},userSession=${userToken.userToken}}`
},
method: 'DELETE',
json: true
});
});
}
static addBank(loginName, password, providerId, loginForm) {
return __awaiter(this, void 0, void 0, function* () {
let userToken = yield this.getLoginToken(loginName, password);
const fnName = 'Add Bank';
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: config_1.Config.PROJECT.YODLEE.API_BASE + 'providerAccounts?providerId=' + providerId, description: 'Add Bank', status: 1 });
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: config_1.Config.PROJECT.YODLEE.API_BASE + 'providerAccounts?providerId=' + providerId, description: 'Request Yodlee With Url :' + config_1.Config.PROJECT.YODLEE.API_BASE + 'providerAccounts?providerId=' + providerId, status: 1 });
return request({
uri: config_1.Config.PROJECT.YODLEE.API_BASE + 'providerAccounts?providerId=' + providerId,
headers: {
'Content-Type': 'application/json',
'Authorization': `{cobSession=${userToken.cobrandToken},userSession=${userToken.userToken}}`
},
method: 'POST',
body: {
'loginForm': loginForm
},
json: true
});
});
}
static getProviders(loginName, password) {
return __awaiter(this, void 0, void 0, function* () {
let YODLEE = config_1.Config.PROJECT.YODLEE;
let userToken = yield this.getLoginToken(loginName, password);
let query = '';
const fnName = 'Get Provider';
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: YODLEE.API_BASE + 'providers?' + query, description: 'Add Bank', status: 1 });
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: YODLEE.API_BASE + 'providers?' + query, description: 'Request Yodlee With Url :' + YODLEE.API_BASE + 'providers?' + query, status: 1 });
return yield request({
uri: YODLEE.API_BASE + 'providers?' + query,
headers: {
'Content-Type': 'application/json',
'Authorization': `{cobSession=${userToken.cobrandToken},userSession=${userToken.userToken}}`
},
method: 'GET',
json: true
});
});
}
static getListProvider(loginName, password, options) {
return __awaiter(this, void 0, void 0, function* () {
let userToken = yield this.getLoginToken(loginName, password);
let YODLEE = config_1.Config.PROJECT.YODLEE;
let query = '';
if (options) {
query = (typeof options.top !== 'undefined' && options.top ? 'top=' + options.top : '500');
query = query + (typeof options.skip !== 'undefined' && options.skip ? (query ? '&skip=' : 'skip=') + options.skip : '');
query = query + (typeof options.name !== 'undefined' && options.name ? (query ? '&name=' : 'name=') + options.name : '');
query = query + (typeof options.name !== 'undefined' && options.name ? (query ? '&id=' : 'id=') + options.id : '');
}
return yield request({
uri: YODLEE.API_BASE + 'providers?' + query,
headers: {
'Content-Type': 'application/json',
'Authorization': `{cobSession=${userToken.cobrandToken},userSession=${userToken.userToken}}`
},
method: 'GET',
json: true
});
});
}
static getProviderById(loginName, password, providerId) {
return __awaiter(this, void 0, void 0, function* () {
const fnName = 'Get Provider By Id';
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: config_1.Config.PROJECT.YODLEE.API_BASE + 'providers/' + providerId, description: `Get Provider:${providerId}`, status: 1 });
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: config_1.Config.PROJECT.YODLEE.API_BASE + 'providers/' + providerId, description: 'Request Yodlee With Url :' + config_1.Config.PROJECT.YODLEE.API_BASE + 'providers/' + providerId, status: 1 });
let userToken = yield this.getLoginToken(loginName, password);
return yield request({
uri: config_1.Config.PROJECT.YODLEE.API_BASE + 'providers/' + providerId,
headers: {
'Content-Type': 'application/json',
'Authorization': `{cobSession=${userToken.cobrandToken},userSession=${userToken.userToken}}`
},
method: 'GET',
json: true,
});
});
}
static getFormLoginBank(loginName, password, providerId) {
return __awaiter(this, void 0, void 0, function* () {
let userToken = yield this.getLoginToken(loginName, password);
const fnName = 'Get Login Form Bank';
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: config_1.Config.PROJECT.YODLEE.API_BASE + 'providers/' + providerId, description: `Get Login Form Bank Provider:${providerId}`, status: 1 });
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: config_1.Config.PROJECT.YODLEE.API_BASE + 'providers/' + providerId, description: 'Request Yodlee With Url :' + config_1.Config.PROJECT.YODLEE.API_BASE + 'providers/' + providerId, status: 1 });
return yield request({
uri: config_1.Config.PROJECT.YODLEE.API_BASE + 'providers/' + providerId,
headers: {
'Content-Type': 'application/json',
'Authorization': `{cobSession=${userToken.cobrandToken},userSession=${userToken.userToken}}`
},
method: 'GET',
json: true
});
});
}
static getStatusConnectingBank(loginName, password, providerAccountId) {
return __awaiter(this, void 0, void 0, function* () {
let userToken = yield this.getLoginToken(loginName, password);
const fnName = 'Get Connected Bank Status';
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: config_1.Config.PROJECT.YODLEE.API_BASE + 'providerAccounts/' + providerAccountId, description: `Get Connected Bank Status With Account Id:${providerAccountId}`, status: 1 });
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: config_1.Config.PROJECT.YODLEE.API_BASE + 'providerAccounts/' + providerAccountId, description: 'Request Yodlee With Url :' + config_1.Config.PROJECT.YODLEE.API_BASE + 'providerAccounts/' + providerAccountId, status: 1 });
return yield request({
uri: config_1.Config.PROJECT.YODLEE.API_BASE + 'providerAccounts/' + providerAccountId,
headers: {
'Content-Type': 'application/json',
'Authorization': `{cobSession=${userToken.cobrandToken},userSession=${userToken.userToken}}`
},
method: 'GET',
json: true
});
});
}
static getStatement(loginName, password, fromDate, toDate, type, accountIdSelected, skip = 0, timeLoop = 0) {
return __awaiter(this, void 0, void 0, function* () {
const fnName = 'Get Transaction';
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: '', description: `Get Transaction With Account Id:${accountIdSelected}`, status: 1 });
fromDate = moment(fromDate, 'YYYY-MM-DD').format('YYYY-MM-DD');
toDate = moment(toDate, 'YYYY-MM-DD').format('YYYY-MM-DD');
console.log('=============> params:', fromDate, toDate, type, accountIdSelected);
if (fromDate === 'Invalid date' || toDate === 'Invalid date') {
throw new Error('format day input not true');
}
let userToken = yield this.getLoginToken(loginName, password);
let options = {
accountId: accountIdSelected,
fromDate: fromDate,
toDate: toDate,
type: type,
skip: skip
};
let query = '';
query = (typeof options.accountId !== 'undefined' && options.accountId ? 'accountId=' + options.accountId : '');
query = query + (options.fromDate ? (query ? '&fromDate=' : 'fromDate=') + options.fromDate : '');
query = query + (options.toDate ? (query ? '&toDate=' : 'toDate=') + options.toDate : '');
query = query + (options.type ? '&container=' + options.type : '');
query = query + (options.skip ? '&skip=' + options.skip : '');
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: config_1.Config.PROJECT.YODLEE.API_BASE + 'transactions' + (query ? '?' + query : ''), description: 'Request Yodlee With Url :' + config_1.Config.PROJECT.YODLEE.API_BASE + 'transactions' + (query ? '?' + query : ''), status: 1 });
let response;
try {
response = yield request({
uri: config_1.Config.PROJECT.YODLEE.API_BASE + 'transactions' + (query ? '?' + query : ''),
headers: {
'Content-Type': 'application/json',
'Authorization': `{cobSession=${userToken.cobrandToken},userSession=${userToken.userToken}}`
},
method: 'GET',
json: true,
});
}
catch (error) {
if (timeLoop === 2)
throw error;
return yield YodleeHelper.getStatement(loginName, password, fromDate, toDate, type, accountIdSelected, skip, timeLoop + 1);
}
let transactions = response && response.transaction ? response.transaction : [];
return transactions;
});
}
static getPublicKey(timeLoop = 0) {
return __awaiter(this, void 0, void 0, function* () {
const fnName = 'Get Public Key';
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: config_1.Config.PROJECT.YODLEE.API_BASE + 'cobrand/publicKey', description: `Function Is Geting Public Key`, status: 1 });
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: config_1.Config.PROJECT.YODLEE.API_BASE + 'cobrand/publicKey', description: 'Request Yodlee With Url :' + config_1.Config.PROJECT.YODLEE.API_BASE + 'cobrand/publicKey', status: 1 });
let cobrandToken = yield this.getAccessToken();
let response;
try {
response = yield request({
uri: config_1.Config.PROJECT.YODLEE.API_BASE + 'cobrand/publicKey',
headers: { 'Content-Type': 'application/json', 'Authorization': `{cobSession=${cobrandToken.session.cobSession}}` },
method: 'GET',
json: true,
});
}
catch (error) {
if (timeLoop === 2)
throw error;
return yield YodleeHelper.getPublicKey(timeLoop + 1);
}
return response;
});
}
static getFormByProviderId(loginName, password, providerId) {
return __awaiter(this, void 0, void 0, function* () {
let userToken = yield this.getLoginToken(loginName, password);
const fnName = 'Get Bank Account';
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: config_1.Config.PROJECT.YODLEE.API_BASE + `providerAccounts/${providerId}?include=credentials`, description: `Function Is Geting Bank Account`, status: 1 });
return request({
uri: config_1.Config.PROJECT.YODLEE.API_BASE + `providerAccounts/${providerId}?include=credentials`,
headers: {
'Content-Type': 'application/json',
'Authorization': `{cobSession=${userToken.cobrandToken},userSession=${userToken.userToken}}`
},
method: 'GET',
json: true,
});
});
}
static updateBank(loginName, password, providerAccountId, loginForm) {
return __awaiter(this, void 0, void 0, function* () {
let userToken = yield this.getLoginToken(loginName, password);
const fnName = 'Add Bank';
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: config_1.Config.PROJECT.YODLEE.API_BASE + 'providerAccounts?providerAccountIds=' + providerAccountId, description: `Update Bank`, status: 1 });
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: config_1.Config.PROJECT.YODLEE.API_BASE + 'providerAccounts?providerAccountIds=' + providerAccountId, description: 'Request Yodlee Method PUT With Url :' + config_1.Config.PROJECT.YODLEE.API_BASE + 'providerAccounts?providerId=' + providerAccountId, status: 1 });
return request({
uri: config_1.Config.PROJECT.YODLEE.API_BASE + 'providerAccounts?providerAccountIds=' + providerAccountId,
headers: {
'Content-Type': 'application/json',
'Authorization': `{cobSession=${userToken.cobrandToken},userSession=${userToken.userToken}}`
},
method: 'PUT',
body: {
'loginForm': loginForm
},
json: true
});
});
}
static getBankAccounts(loginName, password) {
return __awaiter(this, void 0, void 0, function* () {
let userToken = yield this.getLoginToken(loginName, password);
const fnName = 'Get Bank Account';
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: config_1.Config.PROJECT.YODLEE.API_BASE + 'accounts', description: `Function Is Geting Bank Account`, status: 1 });
LogHelper_1.default.logService.create({ system: fileName, module: null, method: fnName, path: config_1.Config.PROJECT.YODLEE.API_BASE + 'accounts', description: 'Request Yodlee With Url :' + config_1.Config.PROJECT.YODLEE.API_BASE + 'accounts', status: 1 });
return request({
uri: config_1.Config.PROJECT.YODLEE.API_BASE + 'accounts',
headers: {
'Content-Type': 'application/json',
'Authorization': `{cobSession=${userToken.cobrandToken},userSession=${userToken.userToken}}`
},
method: 'GET',
json: true,
});
});
}
}
exports.default = YodleeHelper;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const chai_1 = require("chai");
const flatten_1 = require("./flatten");
describe('"flattenArray"', () => {
it('should exist and be a function', () => {
chai_1.expect(flatten_1.flattenArray).to.be.a('function');
});
it('should flatten an array of arbitrarily nested arrays of integers', () => {
const nested = [[1, 2, [3]], 4, [5]];
const flat = [1, 2, 3, 4, 5];
chai_1.expect(flatten_1.flattenArray(nested)).to.deep.equal(flat);
});
});
|
import React from "react"
import { css } from "@emotion/core"
import { useTranslation } from "react-i18next"
export default ({ ...props }) => {
const { t } = useTranslation()
return (
<button
css={css`
background: #c5003e;
border-radius: 3px;
border: none;
padding-top: 18px;
padding-bottom: 18px;
color: white;
cursor: pointer;
font-weight: 500;
font-size: 18px;
outline: none;
text-decoration: none;
display: block;
text-align: center;
margin: 30px 0;
width: 100%;
&:hover {
background: #b60039;
}
&:active {
background: #f4004d;
}
&:disabled {
cursor: default;
}
&.progress {
background: #c5003e;
@keyframes progress-bar-stripes {
from {
background-position: 1rem 0;
}
to {
background-position: 0 0;
}
}
animation: progress-bar-stripes 1s linear infinite;
background-image: linear-gradient(
45deg,
rgba(255, 255, 255, 0.15) 25%,
transparent 25%,
transparent 50%,
rgba(255, 255, 255, 0.15) 50%,
rgba(255, 255, 255, 0.15) 75%,
transparent 75%,
transparent
);
background-size: 1rem 1rem;
}
`}
type="submit"
{...props}
>
{t("request")}
</button>
)
}
|
// import { state } from 'src/boot/country'
import {
getCartList,
updateQuantity,
addCartItem,
deleteCartItem
} from '../boot/axios'
import { Notify } from 'quasar'
export default {
state: {
shoppingCart: []
// shoppingCart: [
// {
// id: '', // 购物车id
// productId: '1', // 商品id
// productName:
// 'modelo de lichi de Color sólido bufanda bolsa hombroDiagonal bolso', // 商品名称
// productPic: '/bu1.jpg', // 商品图片
// Hprice: 25.5, // 商品价格
// Mprice: 25.0,
// Lprice: 24.5,
// quantity: 1, // 商品数量
// maxquantity: 1000000 // 商品限购数量
// },
// {
// id: '', // 购物车id
// productId: '2', // 商品id
// productName:
// 'modelo de lichi de Color sólido bufanda bolsa hombroDiagonal bolso', // 商品名称
// productPic: '/bu2.jpg', // 商品图片
// Hprice: 28.0, // 商品价格
// Mprice: 27.5,
// Lprice: 27.0,
// quantity: 3, // 商品数量
// maxquantity: 1000000 // 商品限购数量
// },
// {
// id: '', // 购物车id
// productId: '3', // 商品id
// productName:
// 'modelo de lichi de Color sólido bufanda bolsa hombroDiagonal bolso', // 商品名称
// productPic: '/bu3.jpg', // 商品图片
// Hprice: 28.0, // 商品价格
// Mprice: 27.5,
// Lprice: 27.0,
// quantity: 3, // 商品数量
// maxquantity: 1000000 // 商品限购数量
// },
// {
// id: '', // 购物车id
// productId: '4', // 商品id
// productName:
// 'modelo de lichi de Color sólido bufanda bolsa hombroDiagonal bolso', // 商品名称
// productPic: '/bu4.jpg', // 商品图片
// Hprice: 28.0, // 商品价格
// Mprice: 27.5,
// Lprice: 27.0,
// quantity: 3, // 商品数量
// maxquantity: 1000000 // 商品限购数量
// },
// {
// id: '', // 购物车id
// productId: '5', // 商品id
// productName:
// 'modelo de lichi de Color sólido bufanda bolsa hombroDiagonal bolso', // 商品名称
// productPic: '/bu5.jpg', // 商品图片
// Hprice: 28.0, // 商品价格
// Mprice: 27.5,
// Lprice: 27.0,
// quantity: 3, // 商品数量
// maxquantity: 1000000 // 商品限购数量
// }
// ]
},
getters: {
getCart(state) {
return state.shoppingCart
},
getTotalPrice(state) {
var totalPrice = 0
for (let i = 0; i < state.shoppingCart.length; i++) {
const temp = state.shoppingCart[i]
if (temp.quantity > 0 && temp.quantity <= 10) {
totalPrice += temp.Hprice * temp.quantity
} else if (temp.quantity <= 999) {
totalPrice += temp.Mprice * temp.quantity
} else {
totalPrice += temp.Lprice * temp.quantity
}
}
return totalPrice
},
// 通过让 getter 返回一个函数,来实现给 getter 传参
/**
*
* @param {string} productId
* @returns
* 根据id返回对应的购物车商品
*/
getProductById: state => productId => {
for (let i = 0; i < state.shoppingCart.length; i++) {
if (
state.shoppingCart[i].productId.toString() === productId.toString()
) {
// console.log(state.shoppingCart[i])
return state.shoppingCart[i]
}
}
},
// 通过让 getter 返回一个函数,来实现给 getter 传参
getProductPrice: state =>
function(productId) {
var totalPrice = 0
for (let i = 0; i < state.shoppingCart.length; i++) {
const temp = state.shoppingCart[i]
if (temp.productId.toString() === productId.toString()) {
// console.log(productId)
if (temp.quantity > 0 && temp.quantity <= 10) {
totalPrice += temp.Hprice * temp.quantity
} else if (temp.quantity <= 999) {
totalPrice += temp.Mprice * temp.quantity
} else {
totalPrice += temp.Lprice * temp.quantity
}
}
}
// console.log(totalPrice)
this.$store.commit('changePriceById', {
productId: productId,
price: totalPrice.toFixed(2)
})
// console.log(this.$store)
return totalPrice.toFixed(2)
}
},
mutations: {
changePriceById(state, payload) {
const index = state.shoppingCart.findIndex(
item => item.productId.toString() === payload.productId.toString()
)
if (index !== -1) {
// console.log('index:', index, '| price:', payload.price)
state.shoppingCart[index].price = payload.price
}
},
addCartQuantity(state, id) {
// 增加购物车商品数量
for (let i = 0; i < state.shoppingCart.length; i++) {
const temp = state.shoppingCart[i]
if (temp.id.toString() === id.toString()) {
temp.quantity++
}
}
},
removeCartQuantity(state, id) {
// 减少购物车商品数量
for (let i = 0; i < state.shoppingCart.length; i++) {
const temp = state.shoppingCart[i]
if (temp.id.toString() === id.toString() && temp.quantity > 0) {
temp.quantity--
if (temp.quantity === 0) {
// debugger
// const list = state.shoppingCart.map(product => {
// if (product.id.toString() !== id.toString()) {
// return product
// }
// })
const index = state.shoppingCart.findIndex(
product => product.id.toString() === id.toString()
)
state.shoppingCart.splice(index, 1)
// this.$store.commit('setCartList', list)
}
break
}
}
},
setCartList(state, cardList) {
state.shoppingCart = cardList
},
/**
* 往购物车添加新商品
* @param {*} state
* @param {*} product
*/
insertProduct(state, product) {
state.shoppingCart.push(product)
}
},
actions: {
async getCartList({ commit }) {
const { data, code, message } = await getCartList()
if (code === 200) {
console.log(data)
commit('setCartList', data)
} else {
Notify.create({
type: 'danger',
message: message
})
}
},
async addCartQuantity({ commit }, productInfo) {
if (productInfo.quantity < 0) return
const { code, message } = await updateQuantity(productInfo)
if (code === 200) {
commit('addCartQuantity', productInfo.id)
} else {
Notify.create({
type: 'danger',
message: message
})
}
},
async removeCartQuantity({ commit }, productInfo) {
// debugger
if (productInfo.quantity < 0) return
if (productInfo.quantity === 0) {
const { code, message } = await deleteCartItem(productInfo.id)
if (code === 200) {
commit('removeCartQuantity', productInfo.id)
} else {
Notify.create({
type: 'danger',
message: message
})
}
} else {
const { code, message } = await updateQuantity(productInfo)
if (code === 200) {
commit('removeCartQuantity', productInfo.id)
} else {
Notify.create({
type: 'danger',
message: message
})
}
}
},
async insertProduct({ commit }, item) {
const { code, data } = await addCartItem(item)
if (code === 200) {
commit('insertProduct', item)
} else {
Notify.create({
type: 'danger',
message: data.message
})
}
}
}
}
|
// Write your Pizza Builder JavaScript in this file.
var list = {
chessePizza: 10,
mushroom: 1,
pepperonni: 1,
greenPeppers: 1,
sauceWhite: 3,
crustGlutenFree: 5,
}
var cart = [
"chessePizza",
"mushroom",
"pepperonni",
"greenPeppers",
"sauceWhite",
"crustGlutenFree"
]
function find(item){
for ( var i = 0; i < cart.length; i++){
if ( cart[i] === item ) {
return i
}
}
return undefined;
}
function calculateTotalPrice () {
var total = 0;
cart.forEach(function(ingridient){
total += list[ingridient]
})
return total
}
function addItem(item) {
cart.push(item);
console.log(cart)
};
function removeItem(item) {
var position = find(item)
if ( position != undefined ) {
cart.splice(position,1);
}
console.log(cart)
};
$(document).ready(function(){
$(".btn-pepperonni").click(function(){
$(this).toggleClass('active');
$(".pep").toggle();
$(".price ul li:nth-child(1)").toggle();
if($(this).hasClass("active")){
addItem("pepperonni");
}else{
removeItem("pepperonni");
}
$("strong").html("$" + calculateTotalPrice());
});
$(".btn-mushrooms").click(function(){
$(this).toggleClass('active');
$(".mushroom").toggle();
$(".price ul li:nth-child(2)").toggle();
if($(this).hasClass("active")){
addItem("mushroom");
}else{
removeItem("mushroom");
}
console.log("total", calculateTotalPrice());
$("strong").html("$" +calculateTotalPrice());
});
$(".btn-green-peppers").click(function(){
$(this).toggleClass('active');
$(".green-pepper").toggle();
$(".price ul li:nth-child(3)").toggle();
if($(this).hasClass("active")){
addItem("greenPeppers");
}else{
removeItem("greenPeppers");
}
$("strong").html("$" +calculateTotalPrice());
});
//End of Iteration 1
$( ".btn-sauce" ).click(function() {
$(this).toggleClass('active');
$( ".sauce" ).toggleClass( "sauce-white" );
$(".price ul li:nth-child(4)").toggle();
if($(this).hasClass("active")){
addItem("sauceWhite");
}else{
removeItem("sauceWhite");
}
$("strong").html("$" +calculateTotalPrice());
});
$( ".btn-crust" ).on("click",function() {
$(this).toggleClass('active');
$( ".crust" ).toggleClass( "crust-gluten-free" );
$(".price ul li:nth-child(5)").toggle();
if($(this).hasClass("active")){
addItem("crustGlutenFree");
}else{
removeItem("crustGlutenFree");
}
$("strong").html("$" + calculateTotalPrice());
});
//End of Iteration 2 // En of Iteration 3
});
|
const fs = require('fs')
const path = require('path');
const ObjectsToCsv = require('objects-to-csv')
const glob = require("glob")
const folder1 = '/mnt/d/Dropbox/0_ISEP/TDMEI/tdmei/other/slither/'
const folder2 = '/mnt/d/Dropbox/0_ISEP/TDMEI/tdmei/test/'
let stats = [] //stats by vulnerability
let stats2 = [] //stats by contract
let errors = []
let cleanContracts = []
let total = 0
const getStats = (folder) => {
glob(folder+'*.json', function (er, files) {
console.log('Total contracts:' +files.length)
for (let i=0; i<files.length; i++) {
let fileName = path.basename(files[i])
fileName = fileName.split('.').slice(0, -1).join('.')
let obj = JSON.parse(fs.readFileSync(files[i], 'utf8'));
if (obj.error !== null || obj.success === false){
errors.push(fileName)
}
if (obj.success === true && Object.keys(obj.results).length === 0){
cleanContracts.push(fileName)
}
if (obj.results.detectors !== undefined){
for (let j=0; j<obj.results.detectors.length; j++) {
total++
let contractsArray, aux
let aux2 = stats.filter(stat => stat.check === obj.results.detectors[j].check)
if (aux2.length > 0){
aux2[0].count++
aux2[0].contracts.push(fileName)
}else{
contractsArray = []; contractsArray.push(fileName)
aux = {check: obj.results.detectors[j].check, count: 1, contracts: contractsArray}
stats.push(aux)
}
aux2 = stats2.filter(stat => stat.contract === fileName)
if (aux2.length > 0){
aux2[0].count++
aux2[0].vulns.push(obj.results.detectors[j].check)
}else{
contractsArray = []; contractsArray.push(obj.results.detectors[j].check)
aux = {contract: fileName, count: 1, vulns: contractsArray}
stats2.push(aux)
}
}
}
}
})
}
getStats(folder1)
setTimeout(async () => {
console.log('Total Vulnerabilities: '+total)
console.log('Clean: '+cleanContracts.length+' - '+JSON.stringify(cleanContracts, null, '\t'))
console.log('Errors: '+errors.length+' - '+JSON.stringify(errors, null, '\t'))
console.log('Stats: '+JSON.stringify(stats, null, '\t'))
let csv = new ObjectsToCsv(stats)
await csv.toDisk('slitherStats.csv', { append: false})
csv = new ObjectsToCsv(stats2)
await csv.toDisk('slitherStats_2.csv', { append: false})
},1000)
|
import React from 'react'
import Filter from '../components/Filter'
import Navbar from '../components/Navbar'
import NavbarLeft from '../components/NavbarLeft'
const Repository = () => {
return (
<>
<Navbar />
<NavbarLeft />
<Filter/>
</>
)
}
export default Repository
|
const UPDATE_NEW_MESSAGE_TEXT = 'UPDATE-NEW-MESSAGE-TEXT';
const SEND_NEW_MESSAGE = 'SEND-NEW-MESSAGE';
const dialogRedicer = (state, action) => {
switch (action.type) {
case UPDATE_NEW_MESSAGE_TEXT:
state.newMessageText = action.text;
return state;
case SEND_NEW_MESSAGE:
let text = state.newMessageText;
state.newMessageText = '';
state.messages.push({ id: 6, message: text });
return state;
default:
return state;
}
};
export const updateNewMessageCreator = (text) => ({ type: UPDATE_NEW_MESSAGE_TEXT, text: text });
export const sendMessageCreator = () => ({ type: SEND_NEW_MESSAGE });
export default dialogRedicer; |
import {
NP_CITES_LOADED,
NP_SKLADS_LOADED,
ORDER_DELIVERY_CHANGE,
ORDER_NP_CITY_CHANGE,
ORDER_CITY_CHANGE,
ORDER_CHANGE_NP_SKLAD,
ORDER_ADDRESS_CHANGE,
ORDER_COMMENT_CHANGE,
ORDER_PHONE_CHANGE
} from '../actions/types';
const INITIAL_STATE = {
showCities: 'flex',
showNPCities: 'none',
showNPSklads: 'none',
showAdress: 'flex',
npCity: null,
NPskald: null,
NPskalds: [],
city: null,
delivery: 1,
country: 'Украина',
sklad: null,
address: null,
comment: null,
phone: null
}
export default (state = INITIAL_STATE, action) => {
switch(action.type) {
case ORDER_DELIVERY_CHANGE:
if (action.payload == 2) { // Нова пошта
return {...state,
showCities: 'none',
showNPCities: 'flex',
showNPSklads: 'none',
showAdress: 'none',
delivery: action.payload}
}
if (action.payload == 1) { // Курьер
return {...state,
showCities: 'flex',
showNPCities: 'none',
showNPSklads: 'none',
showAdress: 'flex',
delivery: action.payload}
}
case ORDER_NP_CITY_CHANGE:
return {
...state,
showCities: 'none',
showNPCities: 'flex',
showNPSklads: 'flex',
showAdress: 'none',
npCity: action.payload
}
case ORDER_CITY_CHANGE:
return {
...state,
showCities: 'flex',
showNPCities: 'none',
showNPSklads: 'none',
showAdress: 'flex'
}
case ORDER_ADDRESS_CHANGE:
return {...state, address: action.payload}
case ORDER_CHANGE_NP_SKLAD:
return {...state, NPskald: action.payload}
case ORDER_PHONE_CHANGE:
return {...state, phone: action.payload}
case ORDER_COMMENT_CHANGE:
return {...state, comment: action.payload}
default: return state;
}
} |
import React from "react";
import styled from "styled-components";
import Text from "../BaseComponents/Text";
import CustomizedButton from "../BaseComponents/CustomizedButton";
import { whiteBackground } from "../themes";
const Container = styled.div`
display: flex;
justify-content: center;
align-items: center;
height: 100%;
${whiteBackground}
`;
function RightAside() {
return (
<Container>
<div style={{ textAlign: "center" }}>
<div style={{ marginBottom: "10px" }}>
<Text xlarge bold>
你还没有选择一条私信
</Text>
</div>
<Text secondary>从你的已有私信中选择一条,或者写一条新私信。</Text>
<div
style={{
display: "flex",
justifyContent: "center",
marginTop: "18px"
}}
>
<CustomizedButton filled>新私信</CustomizedButton>
</div>
</div>
</Container>
);
}
export default RightAside;
|
import react from 'react';
const BuildInfo = () => (
<div className="infobars workinfo">
<h3>Build your WebPage</h3>
<p>
Place your order using the builder on the left
</p>
</div>
);
export default BuildInfo; |
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import * as constants from '../../redux/constants'
import {connect} from 'react-redux'
import {handleError, ERROR_CODES} from '../../utils/errorHandling'
import Mosaic from '../../components/partials/mosaic/Mosaic'
import {MosaicTypes} from '../../utils/constants/MosaicTypes'
import LoaderComponent from '../../components/ui/loader/LoaderComponent'
import ArtistServices from '../../utils/services/artistServices'
import {NotificationTypes} from '../../components/alerts/notifications/NotificationTypes'
class ArtistsPage extends Component {
componentWillMount() {
let {clearAllNotifications, receiveArtistGallery, addNotification, loadingGallery} = this.props
clearAllNotifications()
loadingGallery(true)
ArtistServices.getAll()
.then(function (response) {
if(response.length > 0) {
receiveArtistGallery(response);
} else {
addNotification({code: ERROR_CODES.NO_CARDS_FOUND.code}, NotificationTypes.INFO)
}
loadingGallery(false)
})
.catch(function (error) {
addNotification(error)
loadingGallery(false)
})
}
render() {
return (
<div className="col-xs-12 col-md-12 ArtistsPage">
<div className="row">
{
this.props.updatingArtistGallery
? <div className="marginTop"><center><LoaderComponent/></center></div>
: <Mosaic cardList={this.props.artistGallery} mosaicType={MosaicTypes.ARTIST}/>
}
</div>
</div>
);
}
}
ArtistsPage.displayName = 'ArtistsPage'
ArtistsPage.propTypes = {
artistGallery: PropTypes.array,
receiveArtistGallery: PropTypes.func,
addNotification: PropTypes.func,
clearAllNotifications: PropTypes.func,
loadingGallery: PropTypes.func,
updatingArtistGallery: PropTypes.bool
}
export const mapStateToProps = ({artistGallery, updatingArtistGallery}) => ({
artistGallery, updatingArtistGallery
})
export const mapDispatchToProps = dispatch => ({
receiveArtistGallery: artistGallery => dispatch({type: constants.ARTIST_GALLERY_RECIEVED, artistGallery}),
addNotification: (notification, notificationType) => handleError(dispatch, notification, notificationType),
clearAllNotifications: () => dispatch({type: constants.CLEAR_ALL_NOTIFICATIONS}),
loadingGallery: updatingArtistGallery => dispatch({type: constants.UPDATING_ARTIST_GALLERY, updatingArtistGallery})
})
export default connect(mapStateToProps, mapDispatchToProps)(ArtistsPage) |
const camelCase = require('camel-case').camelCase
const stringify = require('javascript-stringify').stringify
const visit = require('unist-util-visit')
function isGalleryNode (node) {
return node.type === 'list' &&
node.children.length === 1 &&
node.children[0].children[0].children[0].value.toLowerCase() === 'gallery'
}
function extractImages (list) {
return list
.children // list items
.map(({ children }) => children[0]) // paragraphs
.map(({ children }) => children) // images + dividers
.map(row => row.filter(({ type }) => type === 'image'))
}
function unquoteSrc (string) {
return string.replace(/src:'(?!http)(.*?)'/g, (_, match) => `src:${match}`)
}
function getVimeoId (url) {
return url.replace('https://vimeo.com/', '')
}
function generateGalleryComponent (galleryItems) {
const galleryProps = galleryItems.map(
row => row.map(item => {
if (item.alt.toLowerCase() === ':iframe:') {
return { type: 'iframe', src: item.url }
}
if (item.alt.toLowerCase() === ':video:') {
return { type: 'video', src: getVimeoId(item.url) }
}
if (item.alt.toLowerCase() === ':component:') {
return { type: 'component', src: item.url }
}
return { type: 'img', src: item.url, alt: item.alt }
})
)
const stringifiedProps = unquoteSrc(stringify(galleryProps))
return `<Gallery media={${stringifiedProps}} />`
}
function importLocalAssets (assets, tree) {
const imports = []
assets.forEach(row => {
row.forEach(asset => {
const { type, url } = asset
if (!url.includes('./')) return
const name = type === 'component'
? url.split('/').slice(-1)
: camelCase(url)
asset.url = name
imports.push(`import ${name} from '${url}'`)
})
})
// TODO: Handle existing <script> tags, extract Gallery import.
const scriptTag = '<script>\n'
+ imports.join('\n')
+ '\nimport Gallery from "$lib/components/Gallery.svelte"'
+ '\nimport TagList from "$lib/components/TagList.svelte"\n'
+ '</script>'
tree.children.unshift({
type: 'html',
value: scriptTag
})
}
function createGallery () {
return function transformer (tree, file) {
visit(tree, 'list', gallery)
function gallery (node) {
if (!isGalleryNode(node)) return
const images = extractImages(node.children[0].children[1])
importLocalAssets(images, tree)
const gallery = generateGalleryComponent(images)
node.type = 'html'
node.value = gallery
delete node.ordered
delete node.start
delete node.spread
delete node.position
delete node.children
}
};
}
module.exports = createGallery
|
import { expect } from 'chai'
import { build, dev, init } from '../src/defaults'
describe('defaults', () => {
it('should have the correct build defaults', () => {
expect(build).to.eql({
main: './src/Main.elm',
stylesheets: './src/Stylesheets.elm',
html: './index.ejs',
outputPath: 'build',
publicPath: '',
assetTag: 'AssetUrl',
minify: true,
})
})
it('should have the correct dev defaults', () => {
expect(dev).to.eql({
stylesheets: './src/Stylesheets.elm',
html: './index.ejs',
host: '127.0.0.1',
port: 8000,
reactorHost: '127.0.0.1',
reactorPort: 8001,
proxy: [],
proxyRewrite: true,
})
})
it('should have the correct init defaults', () => {
expect(init).to.eql({
force: false,
})
})
})
|
describe('authors service', function () {
'use strict';
beforeEach(function () {
module('app.main');
module('app.authors');
});
var $scope;
beforeEach(inject(function ($rootScope) {
$scope = $rootScope.$new();
}));
it('search is defined', inject(function (authorService) {
// then
expect(authorService.search).toBeDefined();
}));
it('search book should call bookService.search', inject(function ($controller,authorService, authorRestService) {
// given
spyOn(authorRestService, 'search').and.returnValue();
// when
authorService.search();
// then
expect(authorRestService.search).toHaveBeenCalled();
}));
}); |
export default async function handler(req, res) {
const { type, email } = req.query;
let sql;
if (type === 'private') {
sql = `SELECT *
FROM tryshape.shapes s
INNER JOIN tryshape.users u ON s.createdBy=u.email
WHERE s.private=false
ORDER BY s.likes DESC`;
} else if(type === 'public') {
sql = `SELECT * FROM tryshape.shapes`;
} else if(type === 'public-logged-in') {
sql = `SELECT *
FROM tryshape.shapes s
INNER JOIN tryshape.users u
ON s.createdBy=u.email
WHERE s.private=false
OR createdBy = '${email}'
ORDER BY s.likes DESC`;
}
const request = await fetch(process.env.NEXT_PUBLIC_DB_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Basic ${process.env.NEXT_PUBLIC_DB_AUTHORIZATION}`,
},
body: JSON.stringify({
operation: "sql",
sql: sql,
}),
});
const data = await request.json();
res.status(200).json(data);
} |
import { Link } from "@reach/router"
import { navigate } from "gatsby"
import PropTypes from "prop-types"
import React, { useContext } from "react"
import AuthContext from "../../context/AuthContext"
import { defaultUser, isBrowser } from "../../utils/auth-service"
const UserHeader = ({ siteTitle }) => {
const { user, setUser } = useContext(AuthContext)
const logout = () => {
if (!isBrowser) return
setUser(defaultUser)
navigate("/")
return null
}
return (
<header
style={{
position: "fixed",
top: 0,
width: "100%",
backgroundColor: `#333`,
marginBottom: `1.45rem`,
border: "1px solid black",
zIndex: "10",
}}
>
<span style={{ color: "white" }}> Hello, you are {user.name} </span>
{user.role === "student" && (
<>
<Link to="/app/student/dashboard">
<button>
Student Dashboard
</button>
</Link>
<Link to="/app/student/profile">
<button >
{" "}
Student Profile
</button>
</Link>
</>
)}
{user.role === "donor" && (
<>
<Link to="/app/donor/dashboard">
<button >
Donor Dashboard
</button>
</Link>
<Link to="/app/donor/profile">
<button>
Donor Profile
</button>
</Link>
</>
)}
<button onClick={() => logout()}>
Logout
</button>
</header>
)
}
UserHeader.propTypes = {
siteTitle: PropTypes.string,
}
UserHeader.defaultProps = {
siteTitle: ``,
}
export default UserHeader
|
var comb = require('comb');
var client = require('./client.js');
var logger = require(LIB_DIR + 'log_factory').create("links_client");
var LinksClient = comb.define(client,{
instance : {
constructor : function(options){
options = options || {};
options.url = "links";
this._super([options]);
}
}
});
module.exports = new LinksClient();
|
import { delay } from 'redux-saga'
import { put, takeEvery, all, call } from 'redux-saga/effects' //
export function* helloSaga() {
console.log('Hello Sagas!');
}
// Our worker Saga: 将执行异步的 increment 任务
// incrementAsync Saga 通过 delay(1000) 延迟了 1 秒钟,然后 dispatch 一个叫 INCREMENT 的 action。
export function* incrementAsync() {
yield call(delay, 1000) //delay()函数返回一个延迟1秒再resolve的Promise
yield put({ type: 'INCREMENT' }) //告诉middleware发起一个INCREMENT的action
}
// Our watcher Saga: 在每个 INCREMENT_ASYNC action spawn 一个新的 incrementAsync 任务
function* watchIncrementAsync() {
yield takeEvery('INCREMENT_ASYNC', incrementAsync) //takeEvery()用于监听所有的 INCREMENT_ASYNC action,并在 action 被匹配时执行 incrementAsync 任务。
}
// notice how we now only export the rootSaga
// single entry point to start all Sagas at once
export default function* rootSaga() {
yield all([
helloSaga(),
watchIncrementAsync()
])
} |
define(function (require, exports, module) {
var Global = require("global"),
doT = require("dot"),
Upload = require("upload"),
Easydialog = require("easydialog"),
City = require("city"), CityObject,
Verify = require("verify"), VerifyObject,
moment = require("moment");
require("daterangepicker");
require("pager");
var ObjectJS = {};
ObjectJS.Params = {
PageSize: 10,
PageIndex: 1,
Status: -1,
Type: -1,
BeginDate: '',
EndDate:''
};
//初始化
ObjectJS.init = function (option) {
var _self = this;
_self.getDetail();
_self.getClientOrders(1);
_self.bindEvent();
if (option !== 1) {
$(".search-stages li[data-id='" + option + "']").click();
}
}
//绑定事件
ObjectJS.bindEvent = function () {
$(document).click(function (e) {
//隐藏下拉
if (!$(e.target).parents().hasClass("dropdown-ul") && !$(e.target).parents().hasClass("dropdown") && !$(e.target).hasClass("dropdown")) {
$(".dropdown-ul").hide();
}
});
//切换
$(".search-nav-box li").click(function () {
var _this = $(this);
if (!_this.hasClass("hover")) {
_this.siblings().removeClass("hover");
_this.addClass("hover");
$(".nav-part").hide();
$("#" + _this.data("id")).show();
if (_this.data("id") == "navOrderLog" && (!_this.data("first") || _this.data("first") == 0)) {
_this.data("first", "1");
ObjectJS.getClientAuthorizeData(1);
}
}
});
//搜索
require.async("dropdown", function () {
var OrderStatus = [
{
ID: "0",
Name: "未支付"
},
{
ID: "1",
Name: "已支付"
},
{
ID: "9",
Name: "已关闭"
}
];
$("#OrderStatus").dropdown({
prevText: "订单状态-",
defaultText: "所有",
defaultValue: "-1",
data: OrderStatus,
dataValue: "ID",
dataText: "Name",
width: "120",
onChange: function (data) {
$(".tr-header").nextAll().remove();
ObjectJS.Params.Status = parseInt(data.value);
ObjectJS.getClientOrders(1);
}
});
var OrderTypes = [
{
ID: "1",
Name: "购买系统"
},
{
ID: "2",
Name: "购买人数"
},
{
ID: "3",
Name: "续费"
}
];
$("#OrderTypes").dropdown({
prevText: "订单类型-",
defaultText: "所有",
defaultValue: "-1",
data: OrderTypes,
dataValue: "ID",
dataText: "Name",
width: "120",
onChange: function (data) {
$(".tr-header").nextAll().remove();
ObjectJS.Params.Type = parseInt(data.value);
ObjectJS.getClientOrders(1);
}
});
});
//日期插件
$("#iptCreateTime").daterangepicker({
showDropdowns: true,
empty: true,
opens: "right",
ranges: {
'今天': [moment(), moment()],
'昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'上周': [moment().subtract(6, 'days'), moment()],
'本月': [moment().startOf('month'), moment().endOf('month')]
}
}, function (start, end, label) {
ObjectJS.Params.BeginDate = start ? start.format("YYYY-MM-DD") : "";
ObjectJS.Params.EndDate = end ? end.format("YYYY-MM-DD") : "";
ObjectJS.getClientOrders(1);
});
//继续支付客户端订单
$("#PayClientOrder").click(function () {
var id = $(this).data("id"), type = $(this).data("type");
var url = "/Auction/BuyNow";
if (type == 2) {
url = "/Auction/BuyUserQuantity";
} else if (type == 3) {
url = "/Auction/ExtendNow";
}
url += "/" + id;
location.href = url;
});
//关闭客户端订单
$("#CloseClientOrder").click(function () {
Global.post("/System/CloseClientOrder",{id:$(this).data("id")},function(data){
if (data.Result == 1) {
ObjectJS.getClientOrders(1);
}
else {
alert("关闭失败");
}
});
});
//绑定编辑客户信息
$("#updateClient").click(function () {
ObjectJS.editClient();
});
}
//获取详情
ObjectJS.getDetail = function () {
var _self = this;
Global.post("/System/GetClientDetail", null, function(data) {
if (data.Client) {
var item = data.Client;
_self.item = data.Client;
//基本信息
$("#divCompanyName").html(item.CompanyName);
$("#lblCompanyName").html(item.CompanyName);
$("#lblContactName").html(item.ContactName);
$("#lblMobilePhone").html(item.MobilePhone);
$("#lblOfficePhone").html(item.OfficePhone);
$("#lblIndustry").html(item.IndustryEntity != null ? item.IndustryEntity.Name : "");
if (item.City) {
$("#lblcitySpan").html(item.City ? item.City.Description : "--");
}
if (item.Logo) {
$("#posterDisImg").attr("src", item.Logo);
}
$("#lblAddress").html(item.Address);
//$("#lblDescription").html(item.Description);
//授权信息
var agent = data.Agent;
$("#UserQuantity").html(agent.UserQuantity);
$("#EndTime").html(agent.EndTime.toDate("yyyy-MM-dd"));
$("#agentRemainderDays").html(data.Days);
if (agent.authorizeType == 0) {
$(".btn-buy").html("立即购买");
}
else {
if (parseInt(data.remainderDays) < 31) {
$("#agentRemainderDays").addClass("red");
$(".btn-buy").html("续费").data("url", "/Auction/ExtendNow");
}
else {
$(".btn-buy").html("购买人数").data("url", "/Auction/BuyUserQuantity");
}
}
}
});
}
ObjectJS.editClient = function () {
var _self = this;
$("#show-contact-detail").empty();
doT.exec("template/system/client-detail.html", function (template) {
var innerText = template(_self.item);
Easydialog.open({
container: {
id: "#show-model-detail",
header: "编辑公司信息",
content: innerText,
yesFn: function () {
if (!VerifyObject.isPass()) {
return false;
}
var modules = [];
var entity = {
CompanyName: $("#CompanyName").val(),
Logo: $("#posterDisImg").attr("src"),
ContactName: $("#ContactName").val(),
MobilePhone: $("#MobilePhone").val(),
OfficePhone: $("#OfficePhone").val(),
CityCode: CityObject.getCityCode(),
Industry: $("#Industry").val(),
Address: $("#Address").val(),
Description: ""//$("#Description").val()
};
ObjectJS.saveModel(entity);
},
callback: function () {
}
}
});
ObjectJS.Setindustry(_self.item);
CityObject = City.createCity({
cityCode: _self.item.CityCode,
elementID: "citySpan"
});
VerifyObject = Verify.createVerify({
element: ".verify",
emptyAttr: "data-empty",
verifyType: "data-type",
regText: "data-text"
});
//选择海报图片
PosterIco = Upload.createUpload({
element: "#Logo",
buttonText: "选择LOGO",
className: "",
data: { folder: '', action: 'add', oldPath: _self.item.Logo },
success: function (data, status) {
if (data.Items.length > 0) {
$("#posterDisImg").attr("src", data.Items[0]);
} else {
alert("只能上传jpg/png/gif类型的图片,且大小不能超过10M!");
}
}
});
});
}
ObjectJS.Setindustry = function (model) {
$('#Industry').html($('#industrytemp').html());
$('#Industry').val(model.Industry || '');
}
//保存实体
ObjectJS.saveModel = function (model) {
var _self = this;
Global.post("/System/SaveClient", { entity: JSON.stringify(model) }, function(data) {
if (data.Result == 1) {
alert("保存成功");
ObjectJS.getDetail();
}
});
}
//获取客户端的订单列表
ObjectJS.getClientOrders = function(index) {
var _self = this;
$("#client-order").nextAll().remove();
$("#client-order").after("<tr><td colspan='8'><div class='data-loading' ><div></td></tr>");
Global.post("/System/GetClientOrders", {
pageSize: ObjectJS.Params.PageSize,
pageIndex: index,
status: ObjectJS.Params.Status,
type: ObjectJS.Params.Type,
beginDate: ObjectJS.Params.BeginDate,
endDate: ObjectJS.Params.EndDate
},
function (data) {
$("#client-order").nextAll().remove();
if (data.Items.length > 0) {
doT.exec("template/system/client-orders.html", function (template) {
var innerhtml = template(data.Items);
innerhtml = $(innerhtml);
$("#client-order").after(innerhtml);
//下拉事件
innerhtml.find(".dropdown").click(function () {
var _this = $(this);
var position = _this.find(".ico-dropdown").position();
$(".dropdown-ul li").data("id", _this.data("id")).data("type", _this.data("type"));
$(".dropdown-ul").css({ "top": position.top + 20, "left": position.left - 80 }).show().mouseleave(function () {
$(this).hide();
});
return false;
});
});
} else {
$("#client-order").after("<tr><td colspan='8'><div class='nodata-txt' >暂无数据!<div></td></tr>");
}
$("#pager").paginate({
total_count: data.TotalCount,
count: data.PageCount,
start: index,
display: 5,
images: false,
mouse: 'slide',
onChange: function (page) {
_self.getClientOrders(page);
}
});
}
);
};
//获取授权记录
ObjectJS.getClientAuthorizeData = function (index) {
var _self = this;
$("#client-header").nextAll().remove();
_self.Params.pageIndex = index;
Global.post("/System/GetClientAuthorizeLogs", _self.Params, function (data) {
if (data.Items.length > 0) {
doT.exec("template/system/client-authorizelog.html?1", function(templateFun) {
var innerText = templateFun(data.Items);
innerText = $(innerText);
$("#client-header").after(innerText);
});
} else {
$("#client-header").after("<tr><td colspan='6'><div class='nodata-txt' >暂无数据!<div></td></tr>");
}
$("#pager2").paginate({
total_count: data.TotalCount,
count: data.PageCount,
start: index,
display: 5,
border: true,
rotate: true,
images: false,
mouse: 'slide',
onChange: function (page) {
_self.getClientAuthorizeData(page);
}
});
});
};
module.exports = ObjectJS;
}); |
module.exports = function randomIntArray(n, min, max) {
let a = [];
let b = [];
for (let i = 0; i < n; i++) {
let rnd = getRandomInt(min, max);
a.push(rnd);
b.push(rnd);
}
return {a, b};
};
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
|
import React, { useState, } from 'react';
import jwt_decode from 'jwt-decode';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import { CardGroup, Card, Navbar, Nav, Button } from 'react-bootstrap';
import { AiOutlineMenu, AiOutlineLogin, AiOutlineFileDone } from 'react-icons/ai';
import { BsEye } from 'react-icons/bs';
import Collage from './Image/collage.jpg';
import Rocket from './Image/rocket.svg';
import UserContext from './context/UserContext';
import Demo from './components/Demo';
import Register from './components/Register';
import Login from './components/Login';
import User from './components/User';
import About from './components/About';
const linkStyle = {
color: 'white',
fontSize: '1.25rem',
margin: '5px',
}
function App() {
const [currentToken, setCurrentToken] = useState(localStorage.getItem('userToken'));
const [currentUser, setCurrentUser] = useState(
//If token exist, set currentUser as userName. Else, set as empty string.
currentToken ? jwt_decode(currentToken).data.userName : ''
);
return (
<UserContext.Provider value={{ currentToken, setCurrentToken, currentUser, setCurrentUser }}>
<Router>
<Navbar expand="lg" style={{
background: `linear-gradient(25deg,#d64c7f,#ee4758 50%)`,
color: 'white',
position: 'sticky',
top: '0',
zIndex: '99999'
}}>
<Navbar.Brand >
<Link style={{ color: 'white' }} to='/'>Home</Link>
</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" style={{ background: 'white' }}>
<AiOutlineMenu />
</Navbar.Toggle>
<Navbar.Collapse id="basic-navbar-nav" >
<Nav className="mr-auto" >
{
//Show Login and Register links if token exists.
//Show Playlist link if token exists.
!currentToken ?
<>
<Link style={linkStyle} to='/demo'>Demo</Link>
<Link style={linkStyle} to='/login'>Login</Link>
<Link style={linkStyle} to='/register'>Register</Link>
<Link style={linkStyle} to='/about'>About</Link>
</> :
<Link style={linkStyle} to={`/${currentUser}`} >
{currentUser}'s Playlist
</Link>
}
</Nav>
</Navbar.Collapse>
</Navbar>
<Switch>
<Route exact path='/demo'>
<Demo />
</Route>
<Route exact path='/login'>
<Login />
</Route>
<Route exact path='/register'>
<Register />
</Route>
<Route exact path='/about'>
<About />
</Route>
{
//Only render User page if token exists.
currentToken ?
<Route exact path={`/${currentUser}`}>
<User />
</Route> : <></>
}
</Switch>
<Route exact path='/'>
<div style={{
background: `url(${Collage})`,
width: '100vw',
height: '100vh',
overflowY: 'hidden',
position: 'fixed',
backgroundSize: '100vh',
}}></div>
{
//Only render User page if token exists.
currentToken ? <></> :
<CardGroup style={{ margin: '25vh 15vw', }}>
<Card
style={{
borderRadius: '10px',
margin: '10px',
color: 'white',
backgroundImage: `linear-gradient( 108.3deg, rgba(202,73,118,1) 15.2%, rgba(255,84,84,1) 99.3% )`,
}}>
<Link to='/demo' style={{ color: 'white', textDecoration: 'none' }}>
<Card.Title style={{ textAlign: 'center' }}>Demo</Card.Title>
<BsEye style={{ width: '100%', height: '100%', maxHeight: '150px', margin: 'auto' }} />
<Card.Text style={{ margin: '5px auto', textAlign: 'center' }}>
Take a look the app before signing up.
</Card.Text>
</Link>
</Card>
<Card style={{
borderRadius: '10px',
margin: '10px',
color: 'white',
backgroundImage: `linear-gradient( 107deg, rgba(13,198,180,1) 8.1%, rgba(33,198,138,1) 79.5% )`,
}}>
<Link to='/register' style={{ color: 'white', textDecoration: 'none' }}>
<Card.Title style={{ textAlign: 'center' }}>Register</Card.Title>
<AiOutlineFileDone style={{ width: '100%', height: '100%', maxHeight: '150px', margin: 'auto' }} />
<Card.Text style={{ margin: '5px auto', textAlign: 'center' }}>
Don't have an account? Signup Here.
</Card.Text>
</Link>
</Card>
<Card style={{
borderRadius: '10px',
color: 'white',
height: '100%',
margin: '10px',
padding: '10px',
backgroundImage: `linear-gradient( 111.5deg, rgba(20,100,196,1) 0.4%, rgba(33,152,214,1) 100.2% )`
}}>
<Link to='/login' style={{ color: 'white', textDecoration: 'none' }}>
<Card.Title style={{ textAlign: 'center' }}>Login</Card.Title>
<AiOutlineLogin style={{ width: '100%', height: '100%', maxHeight: '150px', margin: 'auto' }} />
<Card.Text style={{ margin: '5px auto', textAlign: 'center' }}>
Already have an account? Signin Here.
</Card.Text>
</Link>
</Card>
</CardGroup>
}
</Route>
</Router >
</UserContext.Provider >
);
}
export default App;
|
var handleFormDateTimePicker = function () {
$('#startDate').MdPersianDateTimePicker({
targetTextSelector: '#startDate',
fromDate: true,
enableTimePicker: true,
groupId: 'rangeSelector1',
dateFormat: 'yyyy/MM/dd HH:mm:ss',
textFormat: 'yyyy/MM/dd HH:mm:ss',
});
$('#endDate').MdPersianDateTimePicker({
targetTextSelector: '#endDate',
fromDate: true,
enableTimePicker: true,
groupId: 'rangeSelector1',
dateFormat: 'yyyy/MM/dd HH:mm:ss',
textFormat: 'yyyy/MM/dd HH:mm:ss',
});
};
var FormDateTimePicker = function () {
return {
//main function
init: function () {
handleFormDateTimePicker();
}
};
}();
|
export default class GeometryEdge {
constructor(start, end, type, id, data) {
this.__start = start;
this.__end = end;
this.__type = type;
this.__id = id;
this.__dxfData = data;
//TODO: Do classification of kind of edge (curve, horizontal, vertical, angled, etc), compute length
}
get id() {
return this.__id;
}
get start() {
return this.__start;
}
get end() {
return this.__end;
}
get type() {
return this.__type;
}
get dxfData() {
return this.__dxfData;
}
}
|
'use strict';
angular.module('myApp.view', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view', {
templateUrl: 'views/photoDisplay/photoDisplayTemplate.html',
controller: 'PhotoDisplayController'
});
}])
.controller('PhotoDisplayController', ['$scope', '$routeParams', 'photoTransferService', function($scope, $routeParams, photoTransferService) {
$scope.image = photoTransferService.image;
$scope.title = photoTransferService.title;
$scope.caption = photoTransferService.caption;
$scope.fullResVisible = false;
$scope.showFullRes = function showFullRes() {
$scope.fullResVisible = true;
},
$scope.hideFullRes = function showFullRes() {
$scope.fullResVisible = false;
}
}]); |
'use strict'
var fs = require('fs');
var path = require('path');
var bcrypt = require('bcrypt-nodejs');
var mongoosePaginate = require ('mongoose-Pagination');
var Persona = require('../models/persona');
var jwt = require('../services/jwt');
function getConductor(req, res){
var conductorId = req.params.id;
Persona.findById(conductorId, (err, conductor) =>{
if(err){
res.status(500).send({message: 'Error en la petición'});
}else{
if(!conductor){
res.status(404).send({message: 'El conductor no existe'});
}else{
if(conductor.rol.descripcion != "Conductor"){
res.status(404).send({message: 'El rol no es conductor'});
}else{
res.status(200).send({conductor});
}
}
}
});
}
function getConductores(req, res){
if(req.params.page){
var page = req.params.page;
}else{
var page = 1;
}
var itemsPerPage = 4;
Persona.find({'rol.descripcion': 'Conductor'}).sort('rol.apellido').paginate(page, itemsPerPage, function(err,conductores,total){
if(err){
res.status(500).send({message:'Error en la petición'});
}else{
if(!conductores){
res.status(404).send({message:'No hay conductores!!'});
}else{
return res.status(200).send({
total_items: total,
conductores: conductores
});
}
}
});
}
function saveConductor(req, res){
var persona = new Persona();
var params = req.body;
var rol = persona.rol;
persona.nombreUsuario = params.nombreUsuario;
persona.email = params.email;
rol.descripcion = "Conductor";
rol.nombre = params.nombre;
rol.apellido = params.apellido;
rol.dni = params.dni;
rol.saldo = 0;
if(params.clave){
// Encriptar contraseña y guardar datos
bcrypt.hash(params.clave,null,null,function(err,hash){
persona.clave = hash;
if(persona.nombreUsuario != null && persona.email != null){
// Guarda el conductor
persona.save((err,personaStored) => {
if(err){
res.status(500).send({message: 'Error al guardar el conductor'});
}else{
if(!personaStored){
res.status(404).send({message: 'No se ha registrado el conductor'});
}else
{
res.status(200).send({persona: personaStored});
}
}
});
}else{
res.status(200).send({message: 'Rellene todos los cambios'});
}
});
}else{
res.status(500).send({message: 'Introduce la contraseña'});
}
}
function updateConductor(req, res){
var conductorId = req.params.id;
var update = req.body;
Persona.findByIdAndUpdate(conductorId, update, (err, conductorUpdated) =>{
if(err){
res.status(500).send({message:'Error al actualizar el conductor'});
}else{
if(!conductorUpdated)
{
res.status(404).send({message:'El conductor no ha sido actualizado'});
}else{
res.status(200).send({persona: conductorUpdated});
}
}
});
}
// Ver bien si vamos a usar o no este metodo
function deleteConductor(req, res){
var conductorId = req.params.id;
Persona.findByIdAndRemove(conductorId, (err, conductorRemoved) =>{
if(err){
res.status(500).send({message: 'Error en el servidor'});
}else{
if(!conductorRemoved){
res.status(404).send({message: 'No se ha borrado el conductor'});
}else{
res.status(200).send({persona: conductorRemoved});
}
}
});
}
module.exports = {
saveConductor,
updateConductor,
deleteConductor,
getConductor,
getConductores
}; |
import React from "react";
import { InputLabel, Select } from "@material-ui/core";
import classes from "./bills.module.css";
const Category = ({ formik }) => {
return (
<div className={classes.Container}>
<h3 className={classes.Title}>
لطفا دسته بندی و نوع پروژه مورد نظر خود را مشخص کنید
</h3>
<div className={`${classes.Box} ${classes.categoryBox} `}>
<div className={classes.selectBox}>
<InputLabel>دسته بندی مهارت ها</InputLabel>
<Select
className={classes.selectCategory}
name="skills"
value={formik.values.skills}
onChange={formik.handleChange}
variant="outlined"
native
>
<option value="">انتخاب کنید</option>
<option value={1}>دلق ساز</option>
<option value={2}>دلق گیر</option>
</Select>
</div>
<div className={classes.selectBox}>
<InputLabel>نوع پروژه</InputLabel>
<Select
className={classes.selectCategory}
name="projectType"
value={formik.values.projectType}
onChange={formik.handleChange}
variant="outlined"
native
>
<option value="">انتخاب کنید</option>
<option value={1}>دلق معمولی</option>
<option value={2}>دلق کلاسیک</option>
<option value={2}>دلق ویژه</option>
</Select>
</div>
</div>
</div>
);
};
export default Category;
|
/**
* 화면 초기화 - 화면 로드시 자동 호출 됨
*/
function _Initialize() {
// 추가 조회조건 사용
$NC.setInitAdditionalCondition();
// 그리드 초기화
grdMasterInitialize();
// 조회조건 - 물류센터 세팅, 조회조건 - 물류센터 초기화
$NC.setInitCombo("/WC/getDataSet.do", {
P_QUERY_ID: "WC.POP_CSUSERCENTER",
P_QUERY_PARAMS: $NC.getParams({
P_USER_ID: $NC.G_USERINFO.USER_ID,
P_CENTER_CD: "%"
})
}, {
selector: ["#cboQCenter_Cd", "#cboQCenter_Cd"],
codeField: "CENTER_CD",
nameField: "CENTER_NM",
onComplete: function() {
$("#cboQCenter_Cd").val($NC.G_USERINFO.CENTER_CD);
$NC.setValue("#cboQCenter_Cd", $NC.G_USERINFO.CENTER_CD);
}
});
// 사업구분 검색 이미지 클릭
$("#btnQBu_Cd").click(showUserBuPopup);
// 사업구분 위탁사 검색 이미지 클릭
$("#btnQOwn_Brand_Cd").click(showOwnBrandPopup);
$("#btnQCarrier_Cd").click(showQCarrierPopup);
// 조회조건 - 브랜드 세팅
$NC.setValue("#edtQBu_Cd", $NC.G_USERINFO.BU_CD);
$NC.setValue("#edtQBu_Nm", $NC.G_USERINFO.BU_NM);
$NC.setValue("#edtQCust_Cd", $NC.G_USERINFO.CUST_CD);
$NC.setInitDatePicker("#dtpQOutbound_Date1");
$NC.setInitDatePicker("#dtpQOutbound_Date2");
}
/**
* 화면 리사이즈 Offset 세팅
*/
function _SetResizeOffset() {
$NC.G_OFFSET.nonClientHeight = $("#divConditionView").outerHeight() + $NC.G_LAYOUT.nonClientHeight;
}
/**
* Window Resize Event - Window Size 조정시 호출 됨
*/
function _OnResize(parent) {
var clientWidth = parent.width() - $NC.G_LAYOUT.border1;
var clientHeight = parent.height() - $NC.G_OFFSET.nonClientHeight;
$NC.resizeContainer("#divMasterView", clientWidth, clientHeight);
var height = clientHeight - $NC.G_LAYOUT.header;
// Grid 사이즈 조정
$NC.resizeGrid("#grdMaster", clientWidth, height);
}
/**
* Input, Select Change Event 처리
*/
function _OnConditionChange(e, view, val) {
// 조회 조건에 Object Change
var id = view.prop("id").substr(4).toUpperCase();
switch (id) {
case "BU_CD":
var P_QUERY_PARAMS;
var O_RESULT_DATA = [ ];
if (!$NC.isNull(val)) {
P_QUERY_PARAMS = {
P_USER_ID: $NC.G_USERINFO.USER_ID,
P_BU_CD: val
};
O_RESULT_DATA = $NP.getUserBuInfo({
queryParams: P_QUERY_PARAMS
});
}
if (O_RESULT_DATA.length <= 1) {
onUserBuPopup(O_RESULT_DATA[0]);
} else {
$NP.showUserBuPopup({
queryParams: P_QUERY_PARAMS,
queryData: O_RESULT_DATA
}, onUserBuPopup, onUserBuPopup);
}
return;
case "OWN_BRAND_CD":
var P_QUERY_PARAMS;
var O_RESULT_DATA = [ ];
if (!$NC.isNull(val)) {
P_QUERY_PARAMS = {
P_CUST_CD: $NC.G_USERINFO.CUST_CD,
P_BU_CD: $NC.getValue("#edtQBu_Cd"),
P_OWN_BRAND_CD: $NC.getValue("#edtQOwn_Brand_Cd")
};
O_RESULT_DATA = $NP.getOwnBrandInfo({
queryParams: P_QUERY_PARAMS
});
}
if (O_RESULT_DATA.length <= 1) {
onOwnBrandPopup(O_RESULT_DATA[0]);
} else {
$NP.showOwnBrandPopup({
queryParams: P_QUERY_PARAMS,
queryData: O_RESULT_DATA
}, onOwnBrandPopup, onOwnBrandPopup);
}
return;
case "CARRIER_CD":
var P_QUERY_PARAMS;
var O_RESULT_DATA = [ ];
if (!$NC.isNull(val)) {
P_QUERY_PARAMS = {
P_CARRIER_CD: val,
P_VIEW_DIV: "1"
};
O_RESULT_DATA = $NP.getCarrierInfo({
queryParams: P_QUERY_PARAMS
});
}
if (O_RESULT_DATA.length <= 1) {
onQCarrierPopup(O_RESULT_DATA[0]);
} else {
$NP.showCarrierPopup({
queryParams: P_QUERY_PARAMS,
queryData: O_RESULT_DATA
}, onQCarrierPopup, onQCarrierPopup);
}
return;
}
// 조회 조건에 Object Change
onChangingCondition();
}
/**
* 조회조건이 변경될 때 호출
*/
function onChangingCondition() {
// 초기화
$NC.clearGridData(G_GRDMASTER);
// 버튼 활성화 처리
$NC.G_VAR.buttons._inquiry = "1";
$NC.G_VAR.buttons._new = "0";
$NC.G_VAR.buttons._save = "0";
$NC.G_VAR.buttons._cancel = "0";
$NC.G_VAR.buttons._delete = "0";
$NC.G_VAR.buttons._print = "0";
$NC.setInitTopButtons($NC.G_VAR.buttons);
}
/**
* Inquiry Button Event - 메인 상단 조회 버튼 클릭시 호출 됨
*/
function _Inquiry() {
var CENTER_CD = $NC.getValue("#cboQCenter_Cd");
if ($NC.isNull(CENTER_CD)) {
alert("물류센터를 선택하십시오.");
$NC.setFocus("#cboQCenter_Cd");
return;
}
var BU_CD = $NC.getValue("#edtQBu_Cd");
if ($NC.isNull(BU_CD)) {
alert("사업구분 코드를 입력하십시오.");
$NC.setFocus("#edtQBu_Cd");
return;
}
var OUTBOUND_DATE1 = $NC.getValue("#dtpQOutbound_Date1");
if ($NC.isNull(OUTBOUND_DATE1)) {
alert("검색 시작일자를 입력하십시오.");
$NC.setFocus("#dtpQOutbound_Date1");
return;
}
var OUTBOUND_DATE2 = $NC.getValue("#dtpQOutbound_Date2");
if ($NC.isNull(OUTBOUND_DATE2)) {
alert("검색 종료일자를 입력하십시오.");
$NC.setFocus("#dtpQOutbound_Date2");
return;
}
if (OUTBOUND_DATE1 > OUTBOUND_DATE2) {
alert("출고예정일자 범위 입력오류입니다.");
$NC.setFocus("#dtpQOutbound_Date1");
return;
}
var WB_NO = $NC.getValue("#edtQWb_No");
var CARRIER_CD = $NC.getValue("#edtQCarrier_Cd", true);
var BRAND_CD = $NC.getValue("#edtQOwn_Brand_Cd", true);
// 조회시 전역 변수 값 초기화
$NC.setInitGridVar(G_GRDMASTER);
// 파라메터 세팅
G_GRDMASTER.queryParams = $NC.getParams({
P_CENTER_CD: CENTER_CD,
P_BU_CD: BU_CD,
P_OUTBOUND_DATE1: OUTBOUND_DATE1,
P_OUTBOUND_DATE2: OUTBOUND_DATE2,
P_BRAND_CD: BRAND_CD,
P_WB_NO: WB_NO,
P_CARRIER_CD: CARRIER_CD
});
// 데이터 조회
$NC.serviceCall("/LOM9070Q/getDataSet.do", $NC.getGridParams(G_GRDMASTER), onGetMaster);
}
/**
* New Button Event - 메인 상단 신규 버튼 클릭시 호출 됨
*/
function _New() {
}
/**
* Save Button Event - 메인 상단 저장 버튼 클릭시 호출 됨
*/
function _Save() {
}
/**
* Delete Button Event - 메인 상단 삭제 버튼 클릭시 호출 됨
*/
function _Delete() {
}
/**
* Cancel Button Event - 메인 상단 취소 버튼 클릭시 호출 됨
*/
function _Cancel() {
}
/**
* Print Button Event - 메인 상단 출력 버튼 클릭시 호출 됨
*
* @param printIndex
* 선택한 출력물 Index
*/
function _Print(printIndex, printName) {
}
function grdMasterOnGetColumns() {
var columns = [ ];
$NC.setGridColumn(columns, {
id: "OUTBOUND_DATE",
field: "OUTBOUND_DATE",
name: "출고일자",
minWidth: 80,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "OUTBOUND_NO",
field: "OUTBOUND_NO",
name: "출고번호",
minWidth: 50,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "OWN_BRAND_CD",
field: "OWN_BRAND_CD",
name: "위탁사코드",
minWidth: 80
});
$NC.setGridColumn(columns, {
id: "CARRIER_CD",
field: "CARRIER_CD",
name: "위탁사",
minWidth: 100
});
$NC.setGridColumn(columns, {
id: "CARRIER_NM",
field: "CARRIER_NM",
name: "운송사코드",
minWidth: 80
});
$NC.setGridColumn(columns, {
id: "OWN_BRAND_NM",
field: "OWN_BRAND_NM",
name: "운송사",
minWidth: 100
});
$NC.setGridColumn(columns, {
id: "WB_NO",
field: "WB_NO",
name: "송장번호",
minWidth: 80,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "BU_NO",
field: "BU_NO",
name: "전표번호",
minWidth: 80,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "BU_KEY",
field: "BU_KEY",
name: "전표KEY",
minWidth: 80,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "REG_USER_ID_PRINT",
field: "REG_USER_ID_PRINT",
name: "출력사용자",
minWidth: 90,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "REG_DATETIME_PRINT",
field: "REG_DATETIME_PRINT",
name: "출력시간",
minWidth: 120,
cssClass: "align-center"
});
return $NC.setGridColumnDefaultFormatter(columns);
}
function grdMasterInitialize() {
var options = {
frozenColumn: 1,
};
// Grid Object, DataView 생성 및 초기화
$NC.setInitGridObject("#grdMaster", {
columns: grdMasterOnGetColumns(),
queryId: "LOM9070Q.RS_MASTER",
sortCol: "LOCATION_CD",
gridOptions: options
});
G_GRDMASTER.view.onSelectedRowsChanged.subscribe(grdMasterOnAfterScroll);
}
function grdMasterOnAfterScroll(e, args) {
var row = args.rows[0];
// 상단 현재로우/총건수 업데이트
$NC.setGridDisplayRows("#grdMaster", row + 1);
}
/**
* @param ajaxData
*/
function onGetMaster(ajaxData) {
$NC.setInitGridData(G_GRDMASTER, ajaxData);
if (G_GRDMASTER.data.getLength() > 0) {
$NC.setGridSelectRow(G_GRDMASTER, 0);
} else {
$NC.setGridDisplayRows("#grdMaster", 0, 0);
}
// 버튼 활성화 처리
$NC.G_VAR.buttons._inquiry = "1";
$NC.G_VAR.buttons._new = "0";
$NC.G_VAR.buttons._save = "0";
$NC.G_VAR.buttons._cancel = "0";
$NC.G_VAR.buttons._delete = "0";
$NC.G_VAR.buttons._print = "0";
$NC.setInitTopButtons($NC.G_VAR.buttons);
}
/**
* 검색조건의 사업구분 검색 이미지 클릭
*/
function showUserBuPopup() {
$NP.showUserBuPopup({
P_USER_ID: $NC.G_USERINFO.USER_ID,
P_BU_CD: "%"
}, onUserBuPopup, function() {
$NC.setFocus("#edtQBu_Cd", true);
});
}
function onUserBuPopup(resultInfo) {
if (!$NC.isNull(resultInfo)) {
$NC.setValue("#edtQBu_Cd", resultInfo.BU_CD);
$NC.setValue("#edtQBu_Nm", resultInfo.BU_NM);
$NC.setValue("#edtQCust_Cd", resultInfo.CUST_CD);
} else {
$NC.setValue("#edtQBu_Cd");
$NC.setValue("#edtQBu_Nm");
$NC.setValue("#edtQCust_Cd");
$NC.setFocus("#edtQBu_Cd", true);
}
onChangingCondition();
}
/**
* 검색조건의 위탁사 검색 이미지 클릭
*/
function showOwnBrandPopup() {
$NP.showOwnBrandPopup({
P_CUST_CD: $NC.G_USERINFO.CUST_CD,
P_BU_CD: $NC.getValue("#edtQBu_Cd"),
P_OWN_BRAND_CD: $NC.getValue("#edtQOwn_Brand_Cd")
}, onOwnBrandPopup, function() {
$NC.setFocus("#edtQOwn_Brand_Cd", true);
});
}
/**
* 위탁사 검색 결과 / 검색 실패 했을 경우(not found)
*/
function onOwnBrandPopup(resultInfo) {
if (!$NC.isNull(resultInfo)) {
$NC.setValue("#edtQOwn_Brand_Cd", resultInfo.OWN_BRAND_CD);
$NC.setValue("#edtQOwn_Brand_Nm", resultInfo.OWN_BRAND_NM);
} else {
$NC.setValue("#edtQOwn_Brand_Cd");
$NC.setValue("#edtQOwn_Brand_Nm");
$NC.setFocus("#edtQOwn_Brand_Cd", true);
}
onChangingCondition();
}
function showQCarrierPopup() {
var carrier_Cd = $NC.getValue("#edtQCarrier_Cd", true);
$NP.showCarrierPopup({
queryParams: {
P_CARRIER_CD: carrier_Cd,
P_VIEW_DIV: "2"
}
}, onQCarrierPopup, function() {
$NC.setFocus("#edtQCarrier_Cd", true);
});
}
function onQCarrierPopup(resultInfo) {
if (!$NC.isNull(resultInfo)) {
$NC.setValue("#edtQCarrier_Cd", resultInfo.CARRIER_CD);
$NC.setValue("#edtQCarrier_Nm", resultInfo.CARRIER_NM);
} else {
$NC.setValue("#edtQCarrier_Cd");
$NC.setValue("#edtQCarrier_Nm");
}
onChangingCondition();
} |
import React, {Component} from 'react';
import {View, Text} from 'react-native';
class BottomMenu extends Component {
render() {
const {containerStyle} = styles;
return (
<View style={{flex: 1}}>
<View style={containerStyle}>{this.props.children}</View>
</View>
);
}
}
const styles = {
containerStyle: {
flex: 1,
padding: 5,
flexDirection: 'row',
alignItems: 'flex-end',
justifyContent: 'space-around',
height: 50,
borderRadius: 1,
shadowColor: '#1d1d1d',
shadowOffset: {width: 2, height: 2},
shadowOpacity: 0.2,
},
};
export {BottomMenu};
|
var pageSize = 25;
//查詢條件
var searchStore = Ext.create('Ext.data.Store', {
fields: ['searchCondition', 'searchValue'],
data: [
{ "searchCondition": "所有資料", "searchValue": "0" },
{ "searchCondition": "標題", "searchValue": "1" },
{ "searchCondition": "短標題", "searchValue": "2" },
{ "searchCondition": "上稿者", "searchValue": "3" }
]
});
var sizeStore = Ext.create('Ext.data.Store', {
fields: ['sizeText', 'sizeValue'],
data: [
{ "sizeText": "所有尺寸", "sizeValue": "0" },
{ "sizeText": "725px", "sizeValue": "725px" },
{ "sizeText": "900px", "sizeValue": "900px" }
]
});
var activeStatusStore = Ext.create('Ext.data.Store', {
fields: ['activeStatusText', 'activeStatusValue'],
data: [
{ "activeStatusText": "所有狀態", "activeStatusValue": "-1" },
{ "activeStatusText": "新建", "activeStatusValue": "0" },
{ "activeStatusText": "顯示", "activeStatusValue": "1" },
{ "activeStatusText": "隱藏", "activeStatusValue": "2" },
{ "activeStatusText": "下檔", "activeStatusValue": "3" }
]
});
//日期條件
var dateStore = Ext.create('Ext.data.Store', {
fields: ['searchCondition', 'searchValue'],
data: [
{ "searchCondition": "所有日期", "searchValue": "0" },
{ "searchCondition": "上線日期", "searchValue": "1" },
{ "searchCondition": "下線日期", "searchValue": "2" }
]
});
//model
Ext.define('gigade.EpaperContentModel', {
extend: 'Ext.data.Model',
fields: [
{ name: "epaper_id", type: "int" },
{ name: "user_id", type: "int" },
{ name: "user_username", type: "string" },
{ name: "epaper_title", type: "string" },
{ name: "epaper_short_title", type: "string" },
{ name: "epaper_content", type: "string" },
{ name: "epaper_sort", type: "int" },
{ name: "epaper_status", type: "int" },
{ name: "epaper_size", type: "string" },
{ name: "epaper_show_start", type: "string" },
{ name: "epaper_show_end", type: "string" },
{ name: "fb_description", type: "string" },
{ name: "epaper_createdate", type: "string" },
{ name: "epaper_updatedate", type: "string" },
{ name: "epaper_ipfrom", type: "string" },
{ name: "epaperShowStart", type: "string" },
{ name: "epaperShowEnd", type: "string" },
{ name: "epaperCreateDate", type: "string" },
{ name: "epaperUpdateDate", type: "string" },
{ name: "type", type: "int" }
]
});
var EpaperContentStore = Ext.create('Ext.data.Store', {
autoDestroy: true, //自動消除
pageSize: pageSize,
model: 'gigade.EpaperContentModel',
proxy: {
type: 'ajax',
url: '/EpaperContent/GetEpaperContentList',
reader: {
type: 'json',
root: 'data',
totalProperty: 'totalCount'
}
}
});
//前面選擇框 選擇之後顯示編輯刪除
var sm = Ext.create('Ext.selection.CheckboxModel', {
listeners: {
selectionchange: function (sm, selections) {
Ext.getCmp("gdEpaper").down('#edit').setDisabled(selections.length == 0);
var row = Ext.getCmp("gdEpaper").getSelectionModel().getSelection();
if (row != "") {
if (row[0].data.epaper_status == 3) {
Ext.getCmp("gdEpaper").down('#edit').setDisabled(true);
}
}
}
}
});
EpaperContentStore.on('beforeload', function () {
Ext.apply(EpaperContentStore.proxy.extraParams,
{
searchCon: Ext.getCmp('searchCon').getValue(),
search_text: Ext.getCmp('search_text').getValue(),
dateCon: Ext.getCmp('dateCon').getValue(),
date_start: Ext.getCmp('timestart').getValue(),
date_end: Ext.getCmp('timeend').getValue(),
activeStatus: Ext.getCmp('activeStatus').getValue(),
sizeCon: Ext.getCmp('sizeCon').getRawValue()
});
});
var EditTpl = new Ext.XTemplate(
'<a href=javascript:TranToDetial("/EpaperContent/EpaperLogList","{epaper_id}")>' + "記錄" + '</a> '
);
Ext.onReady(function () {
var searFrm = Ext.create('Ext.form.Panel', {
id: 'searFrm',
border: 0,
layout: 'anchor',
height: 140,
width: document.documentElement.clientWidth,
items: [
{
xtype: 'fieldcontainer',
layout: 'hbox',
items: [
{
xtype: 'combobox',
store: searchStore,
id: 'searchCon',
fieldLabel: '查詢條件',
displayField: 'searchCondition',
valueField: 'searchValue',
width: 180,
labelWidth: 60,
margin: '5 5 2 2',
forceSelection: false,
editable: false,
value: '0'
},
{
xtype: 'textfield',
fieldLabel: "查詢內容",
width: 180,
labelWidth: 60,
margin: '5 0 2 2',
id: 'search_text',
name: 'search_text',
value: ""
}
]
},
{
xtype: 'fieldcontainer',
layout: 'hbox',
items: [
{
xtype: 'combobox',
id: 'dateCon',
name: 'dateCon',
store: dateStore,
displayField: 'searchCondition',
valueField: 'searchValue',
fieldLabel: '日期條件',
value: '0',
editable: false,
labelWidth: 60,
width: 180,
margin: '0 5 0 2'
},
{
xtype: 'datetimefield', allowBlank: true, id: 'timestart', format: 'Y-m-d H:i:s', name: 'serchcontent', editable: false, labelWidth: 60, time: { hour: 00, min: 00, sec: 00 }, listeners: {
select: function (a, b, c) {
var start = Ext.getCmp("timestart");
var end = Ext.getCmp("timeend");
if (end.getValue() == null) {
end.setValue(setNextMonth(start.getValue(), 1));
} else if (end.getValue() < start.getValue()) {
end.setValue(setNextMonth(start.getValue(), 1));
}
}
}
},
{
xtype: 'displayfield',
value: '~'
},
{
xtype: 'datetimefield', allowBlank: true, id: 'timeend', format: 'Y-m-d H:i:s', editable: false, name: 'serchcontent', time: { hour: 23, min: 59, sec: 59 }, listeners: {
select: function (a, b, c) {
var start = Ext.getCmp("timestart");
var end = Ext.getCmp("timeend");
if ( start.getValue()== null) {
start.setValue(setNextMonth(end.getValue(), -1));
}
else if (end.getValue() < start.getValue()) {
start.setValue(setNextMonth(end.getValue(), -1));
}
}
}
}
]
}
,
{
xtype: 'fieldcontainer',
layout: 'hbox',
items: [
{
xtype: 'combobox',
store: activeStatusStore,
id: 'activeStatus',
fieldLabel: '活動狀態',
displayField: 'activeStatusText',
valueField: 'activeStatusValue',
width: 180,
labelWidth: 60,
margin: '0 5 5 2',
forceSelection: false,
editable: false,
value: '-1'
},
{
xtype: 'combobox',
store: sizeStore,
id: 'sizeCon',
fieldLabel: '尺寸',
displayField: 'sizeText',
valueField: 'sizeValue',
width: 180,
labelWidth: 60,
margin: '0 5 5 2',
forceSelection: false,
editable: false,
value: '0'
}
]
}
],
buttonAlign: 'left',
buttons: [
{
text: SEARCH,
iconCls: 'icon-search',
id: 'btnQuery',
margin: '5 5 2 5',
handler: Query
},
{
text: RESET,
id: 'btn_reset',
margin: '5 0 2 0',
listeners: {
click: function () {
Ext.getCmp('searchCon').setValue('0');
Ext.getCmp('search_text').setValue("");
Ext.getCmp('dateCon').setValue('0');
Ext.getCmp('activeStatus').setValue('-1');
Ext.getCmp('sizeCon').setValue('0');
Ext.getCmp('timestart').setValue(null);
Ext.getCmp('timeend').setValue(null);
}
}
},
],
});
var gdEpaper = Ext.create('Ext.grid.Panel', {
id: 'gdEpaper',
store: EpaperContentStore,
width: document.documentElement.clientWidth,
columnLines: true,
frame: true,
viewConfig: {
enableTextSelection: true,
stripeRows: false,
getRowClass: function (record, rowIndex, rowParams, store) {
return "x-selectable";
}
},
columns: [
{ header: "編號", dataIndex: 'epaper_id', width: 60, align: 'center' },
{ header: '記錄', width: 60, align: 'center', xtype: 'templatecolumn', tpl: EditTpl },
{ header: '上稿者', dataIndex: 'user_username', width: 100, align: 'center' },
{ header: '標題', dataIndex: 'epaper_title', width: 300, align: 'center' },
{ header: "短標題", dataIndex: 'epaper_short_title', width: 100, align: 'center' },
{ header: "排序", dataIndex: 'epaper_sort', width: 80, align: 'center' },
{//0:新建1顯示2隱藏3下檔
header: '狀態', dataIndex: 'epaper_status', width: 150, align: 'center',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
if (record.data.epaper_status == 1) {
return "顯示";
}
if (record.data.epaper_status == 0) {
return "<span style=' color:red'>新建</span>";
}
if (record.data.epaper_status == 2) {
return "<span style=' color:red'>隱藏</span>";
}
if (record.data.epaper_status == 3) {
return "<span style=' color:red'>下檔</span>";
}
}
},
{ header: "尺寸", dataIndex: 'epaper_size', width: 150, align: 'center' },
{
header: '上線時間', dataIndex: 'epaperShowStart', width: 150, align: 'center',
renderer: function (value) {
if (value > Today2()) {
return "<span style='color:red'>" + value + "</span>";
}
else {
return value;
}
}
},
{
header: '下線時間', dataIndex: 'epaperShowEnd', width: 150, align: 'center',
renderer: function (value) {
if (value < Today2()) {
return "<span style='color:red'>" + value + "</span>";
}
else {
return value;
}
}
}
//{ header: BANNERLINKURL, dataIndex: 'fb_description', width: 100, align: 'center' },
//{ header: BANNERLINKMODE, dataIndex: 'epaper_createdate', width: 80, align: 'center', hidden: true },
//{ header: BANNERLINKMODE, dataIndex: 'epaper_updatedate', width: 80, align: 'center' },
//{ header: BANNERSORT, dataIndex: 'epaper_ipfrom', width: 50, align: 'center' },
//{ header: BANNERSTATUS, dataIndex: 'type', width: 100, align: 'center', hidden: true }
],
tbar: [
{ xtype: 'button', text: ADD, id: 'add', iconCls: 'icon-user-add', handler: onAddClick, hidden: true },
{ xtype: 'button', text: EDIT, id: 'edit', hidden: false, iconCls: 'icon-user-edit', disabled: true, handler: onEditClick }
],
bbar: Ext.create('Ext.PagingToolbar', {
store: EpaperContentStore,
pageSize: pageSize,
displayInfo: true,
displayMsg: NOW_DISPLAY_RECORD + ': {0} - {1}' + TOTAL + ': {2}',
emptyMsg: NOTHING_DISPLAY
}),
listeners: {
scrollershow: function (scroller) {
if (scroller && scroller.scrollEl) {
scroller.clearManagedListeners();
scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller);
}
}
},
selModel: sm
});
Ext.create('Ext.container.Viewport', {
layout: 'anchor',
items: [searFrm, gdEpaper],
renderTo: Ext.getBody(),
autoScroll: true,
listeners: {
resize: function () {
gdEpaper.width = document.documentElement.clientWidth;
gdEpaper.height = document.documentElement.clientHeight - 140;
this.doLayout();
}
}
});
ToolAuthority();
if (window.parent.Ext.getCmp('ContentPanel').activeTab.name == 'EpaperContentEdit') {
EpaperContentStore.load({ params: { start: 0, limit: 25 } });
}
});
//添加
onAddClick = function () {
var urlTran = '/EpaperContent/EpaperContentAdd';
var panel = window.parent.parent.Ext.getCmp('ContentPanel');
var copy = panel.down('#detial');
if (copy) {
copy.close();
}
copy = panel.add({
id: 'detial',
title: '新增活動列表頁',
html: window.top.rtnFrame(urlTran),
name: panel.activeTab.title,
closable: true
});
panel.activeTab.close();
panel.setActiveTab(copy);
panel.doLayout();
}
//修改
onEditClick = function () {
var row = Ext.getCmp("gdEpaper").getSelectionModel().getSelection();
if (row.length == 0) {
Ext.Msg.alert(INFORMATION, NO_SELECTION);
} else if (row.length > 1) {
Ext.Msg.alert(INFORMATION, ONE_SELECTION);
} else {
var urlTran = '/EpaperContent/EpaperContentAdd?epaper_id=' + row[0].data.epaper_id;
var panel = window.parent.parent.Ext.getCmp('ContentPanel');
var copy = panel.down('#detial');
if (copy) {
copy.close();
}
copy = panel.add({
id: 'detial',
title: '編輯活動列表頁',
html: window.top.rtnFrame(urlTran),
name: panel.activeTab.title,
closable: true
});
panel.activeTab.close();
panel.setActiveTab(copy);
panel.doLayout();
}
}
function Query(x) {
var searchCon = Ext.getCmp('searchCon').getValue();
var search_text = Ext.getCmp('search_text').getValue();
if (Ext.getCmp('dateCon').getValue() != "0") {
if (Ext.getCmp('timestart').getValue() == ("" || null)) {
Ext.Msg.alert(INFORMATION, "請選擇查詢日期");
return;
}
if (Ext.getCmp('timeend').getValue() == ("" || null)) {
Ext.Msg.alert(INFORMATION, "請選擇查詢日期");
return;
}
}
EpaperContentStore.removeAll();
Ext.getCmp("gdEpaper").store.loadPage(1, {
params: {
searchCon: searchCon,
search_text: search_text,
dateCon: Ext.getCmp('dateCon').getValue(),
date_start: Ext.getCmp('timestart').getValue(),
date_end: Ext.getCmp('timeend').getValue(),
activeStatus: Ext.getCmp('activeStatus').getValue(),
sizeCon: Ext.getCmp('sizeCon').getValue()
}
});
}
setNextMonth = function (source, n) {
var s = new Date(source);
s.setMonth(s.getMonth() + n);
if (n < 0) {
s.setHours(0, 0, 0);
}
else if (n > 0) {
s.setHours(23, 59, 59);
}
return s;
}
function TranToDetial(url, epaper_id) {
var urlTran = url + '?epaperId=' + epaper_id;
var panel = window.parent.parent.Ext.getCmp('ContentPanel');
var copy = panel.down('#detial');
if (copy) {
copy.close();
}
copy = panel.add({
id: 'detial',
title: '活動頁面歷史記錄',
html: window.top.rtnFrame(urlTran),
closable: true
});
panel.setActiveTab(copy);
panel.doLayout();
}
//function Today() {
// var d;
// var s = "";
// d = new Date(); // 创建 Date 对象。
// var year = d.getFullYear();
// var month = d.getMonth() + 1;
// if (month < 10) {
// month = "0" + month;
// }
// var day = d.getDate();
// if (day < 10) {
// day = "0" + day;
// }
// var hour = d.getHours();
// if (hour < 10) {
// hour = "0" + hour;
// }
// var minutes = d.getMinutes();
// if (minutes < 10) {
// minutes = "0" + minutes;
// }
// var sec = d.getSeconds();
// if (sec < 10) {
// sec = "0" + sec;
// }
// s = year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + sec;
// return s; // 返回日期。
//}
//function formatDate(now) {
// var year = now.getFullYear();
// var month = now.getMonth() + 1;
// var date = now.getDate();
// var hour = now.getHours();
// var minute = now.getMinutes();
// var second = now.getSeconds();
// return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
//};
function Today() {
var d;
d = new Date(); // 创建 Date 对象。
d.setDate(d.getDate() + 1);
return d;
}
//時間
function formatDate() {
var d;
d = new Date(); // 创建 Date 对象。
d.setDate(d.getDate() + 1);
return d;
}
function Tomorrow() {
var d;
d = new Date(); // 创建 Date 对象。
d.setDate(d.getDate() + 1);
return d;
}
function Today2() {
var d;
d = new Date(); // 创建 Date 对象。
d.setDate(d.getDate());
return d;
}
//function Today2() {
// var d;
// var s = "";
// d = new Date(); // 创建 Date 对象。
// var year = d.getFullYear();
// var month = d.getMonth() + 1;
// if (month < 10) {
// month = "0" + month;
// }
// var day = d.getDate();
// if (day < 10) {
// day = "0" + day;
// }
// var hour = d.getHours();
// if (hour < 10) {
// hour = "0" + hour;
// }
// var minutes = d.getMinutes();
// if (minutes < 10) {
// minutes = "0" + minutes;
// }
// var sec = d.getSeconds();
// if (sec < 10) {
// sec = "0" + sec;
// }
// s = year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + sec;
// return s; // 返回日期。
//}
|
var express = require('express')
var router = express.Router();
const upload = require('../modules/multer')
const postController = require('../controllers/post')
const authUtil = require('../middlewares/auth').checkToken
// 5. 게시글 등록
router.post('/',authUtil,upload.single('data'),postController.createPost)
// 6. 게시글 불러오기 - 좋아요 순
router.get('/likes/:month',authUtil,postController.getPostArrangedByLikesCount)
// 7. 게시글 불러오기 - 최신순
router.get('/newest/:month',authUtil,postController.getPostArrangedByCreatedAt)
// router.get('/all',authUtil,postController.getAllPost)
// 8. 게시글 수정
router.put('/:postIdx',authUtil,postController.updatePost)
// 9. 게시글 삭제
router.delete('/:postIdx',authUtil,postController.deletePost)
// 10. 게시글 좋아요
router.post('/like/:postIdx',authUtil,postController.createPostLike)
// 11. 게시글 좋아요 해제
router.delete('/dislike/:postIdx',authUtil,postController.deletePostLike)
// 12. 게시글 댓글 달기
router.post('/comment/:postIdx',authUtil,postController.createPostComment)
// 13. 게시글 댓글 수정
router.put('/comment/:postCommentsIdx',authUtil,postController.updatePostComment)
// 14. 게시글 댓글 삭제
router.delete('/comment/:postCommentIdx',authUtil,postController.deletePostComment)
// 15. 게시글 댓글 좋아요
router.post('/comments/like/:postCommentsIdx',authUtil,postController.createPostCommentLike)
// 16. 게시글 댓글 좋아요 해제
router.delete('/comments/dislike/:postCommentsIdx',authUtil,postController.deletePostCommentLike)
// 17. 개별 게시글
router.get('/comments/:postIdx',authUtil,postController.getPostComments)
router.post('/notice/:postIdx',authUtil,postController.createNotice)
// router.post('/notice',authUtil,postController.createNotice)
// router.get('/notice',authUtil,postController.getNotice)
// router.delete('/notice/:noticeIdx',authUtil,postController.deleteNotice)
module.exports = router; |
export const updateStockFilterValue = (value) => {
return {
type: 'UPDATE_STOCK_VALUE',
value: value
};
} |
import { faGithub } from "@fortawesome/free-brands-svg-icons";
import { faExternalLinkAlt } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import React from "react";
import { trabajos } from "../../data/trabajos";
export const Proyectos = () => {
return (
<div className="container">
<h1 className="trabajos__titulo">Proyectos</h1>
<div className="trabajos__contenedor">
{trabajos.map((trabajo) => (
<div className="trabajos__card">
<img
src={trabajo.img}
alt={trabajo.nombre}
className="trabajos__imagen"
/>
<div className="trabajos__info">
<p className="trabajos__nombre">{trabajo.nombre}</p>
<p className="trabajos__descripcion">{trabajo.descripcion}</p>
<div className="trabajos__botones">
<a
className="trabajos__boton-link btn btn-primary"
href={trabajo.direccion}
target="_blank"
rel="noopener noreferrer"
>
<FontAwesomeIcon
className="footer__git"
icon={faExternalLinkAlt}
/>{" "}
Visitar Sitio
</a>
<a
className="trabajos__boton-git btn btn-primary"
href={trabajo.git}
target="_blank"
rel="noopener noreferrer"
>
<FontAwesomeIcon className="footer__git" icon={faGithub} />{" "}
Github
</a>
</div>
</div>
</div>
))}
</div>
</div>
);
};
|
function validateList(...items) {
if(items.indexOf('milk') < 0){ // if array no 'milk'
return [ 'milk',...items]; // add 'milk' to the 'items' list
}
return items;
}
const localFruits = ['banana','watermelon','durian'];
const result = validateList('orange','apple',...localFruits);
console.log(result);
|
import Vue from 'vue'
import Vuex from "vuex"
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 2,
message: ""
},
getters: {
doubleCount: state => state.count * 2,
tripleCount: state => state * 3,
meesage: state => state.message
},
mutations: {
increment(state, number) {
state.count += number
},
decrement(state, number) {
state.count -= number
},
updateMessage(state, newMessage) {
state.message = newMessage
}
},
actions: {
increment(constext, number) {
constext.commit('increment', number)
},
updateMessage({ commit }, newMessage) {
commit("updateMessage", newMessage)
}
},
}) |
import React from "react"
import { Link } from "react-router-dom"
import validator from "validator"
import PropTypes from "prop-types"
import useForm from "../../hooks/useForm"
import {
Button,
Col,
Form,
FormFeedback,
FormGroup,
FormText,
Input,
Row
} from "reactstrap"
const validateUserSignIn = formData => ({
email:
formData.email === ""
? "E-mail cannot be blank"
: !validator.isEmail(formData.email)
? "This E-mail is not valid"
: "",
password:
formData.password === ""
? "Password cannot be blank"
: formData.password.length < 3
? "Password must be at least 3 characters long"
: formData.password.length > 20
? "Password cannot be longer than 20 characters"
: ""
})
const INITIAL_FORM_DATA = {
email: "",
password: ""
}
const INITIAL_FORM_ERRORS = {
email: "",
password: ""
}
const SignInForm = ({ onSubmit }) => {
const {
values, errors, handleChange, handleSubmit, validateForm
} = useForm(
INITIAL_FORM_DATA,
INITIAL_FORM_ERRORS,
validateUserSignIn,
onSubmit
)
return (
<Form className="py-4 px-2" onSubmit={handleSubmit} method="POST">
{/*
<pre>{JSON.stringify(values, null, 4)}</pre>
<pre>{JSON.stringify(errors, null, 4)}</pre>
<pre>{JSON.stringify(Object.values(errors), null, 4)}</pre>
<div>
{`HAS ERRORS: ${
!Object.values(errors).every(error => error === "") ? "True" : "False"
}`}
</div>
*/}
<FormGroup className="mb-4">
<Input
type="text"
name="email"
placeholder="E-mail Address"
value={values.email}
onChange={handleChange}
onKeyUp={validateForm}
invalid={!!errors.email}
/>
<FormFeedback>{errors.email}</FormFeedback>
<FormText>Enter a valid an active e-mail address</FormText>
</FormGroup>
<FormGroup className="mb-4">
<Input
type="password"
name="password"
placeholder="Password"
value={values.password}
onChange={handleChange}
onKeyUp={validateForm}
invalid={!!errors.password}
/>
<FormFeedback>{errors.password}</FormFeedback>
<FormText>Inform your password registered for this account</FormText>
</FormGroup>
<Row>
<Col>
<Button color="primary">Submit</Button>
</Col>
<Col>
<Link to="/signup" className="btn btn-light">
Na account? Register here
</Link>
</Col>
</Row>
</Form>
)
}
SignInForm.propTypes = {
onSubmit: PropTypes.func.isRequired
}
export default SignInForm
|
import "../../Styles/HomePageStyle/Laboratories.css"
import React from 'react';
const Laboratories = () => {
return (
<div className="Laboratories">
<h5>Laboratories</h5>
</div>
);
};
export default Laboratories; |
const Queries = require('../src/helpers/queries')
const assert = require('chai').assert
const ProgressBar = require('progress')
const lxr = require('../lxr.json')
const leanixjs = require('leanix-js')
const dataset = require('./devDataset')
const { Authenticator, GraphQLClient } = leanixjs
const authenticator = new Authenticator(lxr.host, lxr.apitoken)
const graphql = new GraphQLClient(authenticator)
const queries = new Queries(graphql)
describe('The queries', () => {
let { tagGroup, businessCapabilities, applications } = dataset
before(async () => {
await authenticator.start()
})
after(async () => {
await authenticator.stop()
})
it('should delete all workspace factsheets', async () => {
const query = '{allFactSheets{edges{node{id}}}}'
let ids = await graphql
.executeGraphQL(query)
.then(res => res.allFactSheets.edges.map(edge => edge.node.id))
const bar = new ProgressBar(
`Archiving ${ids.length} factSheets [:bar] :rate/fps :percent :etas - :errors errors`,
{ total: ids.length, renderThrottle: 100 }
)
let errors = []
for (let id of ids) {
const query = `mutation($id:ID!,$patches:[Patch]!){updateFactSheet(id:$id,comment:"Delete FS",patches:$patches,validateOnly:false){factSheet{id}}}`
const variables = {
id,
patches: [{ op: 'add', path: '/status', value: 'ARCHIVED' }]
}
await graphql
.executeGraphQL(query, variables)
.catch(() => errors.push(id))
bar.tick({ errors: errors.length })
}
assert(errors.length === 0, 'All factsheets should have been deleted')
})
it('should find the tagGroup "transition phase" and, if existing, delete it and tags ', async () => {
try {
const tagGroup = await queries.fetchTransitionPhaseTagGroup(dataset.tagGroup)
if (tagGroup) await queries.deleteTransitionPhaseTagGroupAndTags(tagGroup)
} catch (err) {
assert.isNull(err)
}
})
it('should create the tag group and tags in the workspace', async () => {
try {
tagGroup = await queries.createTransitionPhaseTagGroupAndTags(dataset.tagGroup)
assert.isObject(tagGroup)
assert.isString(tagGroup.id)
assert.isObject(tagGroup.tags)
assert.hasAllKeys(tagGroup.tags, dataset.tagGroup.tags.map(tag => tag.name))
} catch (err) {
assert.isNull(err)
}
})
it('should create the business capabilities in the workspace', async () => {
try {
businessCapabilities = await queries.createBusinessCapabilities(businessCapabilities)
businessCapabilities = businessCapabilities.reduce((accumulator, bc) => { accumulator[bc.name] = bc; return accumulator }, {})
assert.isObject(businessCapabilities)
assert.hasAllKeys(businessCapabilities, dataset.businessCapabilities.map(bc => bc.name))
} catch (err) {
assert.isNull(err)
}
})
it('should create the applications in the workspace', async () => {
try {
await queries.createDemoApplications(applications)
} catch (err) {
assert.isNull(err)
}
})
})
|
//组件管理器
class ComponentStore{
constructor(){
//如何设置只读
this.modules = {};
};
getById(id){
if(this.isExist(id)){
return this.modules[id];
}else{
console.error('组件名为'+id+'不存在')
return null;
}
};
setById(id,component){
if(this.isExist(id)){
console.error('组件id名'+ id +'重复')
return;
}
this.modules[id] = component;
};
clearById(id){
if(!this.isExist(id)){
console.error('组件名为'+id+'不存在')
return;
};
this.modules[id] = null;
delete this.modules[id];
};
//判断组件是否存在
isExist(id){
return this.modules[id]?true:false;
};
};
window.componentStore = new ComponentStore();
|
$(".use").on("click", function(){
let useCnt = $(this).siblings("input[name=useVaccine]").val();
let resultCnt = $(this).siblings("input[name=vaccineType]").val() - useCnt;
if(resultCnt < 0){
alert("수량이 부족합니다.");
} else{
$(this).siblings("input[name=vaccineType]").val(resultCnt);
}
$(this).siblings("input[name=useVaccine]").val("0");
return false;
})
$(".add").on("click", function(){
let useCnt = $(this).siblings("input[name=addVaccine]").val();
let resultCnt = Number($(this).siblings("input[name=vaccineType]").val()) + Number(useCnt);
$(this).siblings("input[name=vaccineType]").val(resultCnt);
$(this).siblings("input[name=addVaccine]").val("0");
return false;
})
$(".up").on("click", function(){
let resultCnt = Number($(this).siblings("input[name=vaccineType]").val()) + 1;
$(this).siblings("input[name=vaccineType]").val(resultCnt);
return false;
})
$(".down").on("click", function(){
let resultCnt = Number($(this).siblings("input[name=vaccineType]").val()) - 1;
if(resultCnt < 0){
alert("수량이 부족합니다.");
} else{
$(this).siblings("input[name=vaccineType]").val(resultCnt);
}
return false;
}) |
const db = require('../db')
const sequelize = require('sequelize')
const Storage = db.define("Storage", {
name: sequelize.STRING,
position: sequelize.STRING
})
Storage.associate = function(models) {
Storage.hasMany(models.Product, {foreignKey: 'id'})
};
// db.sync()
// .then(()=>{
// console.log("Create Storage successfully...")
// })
module.exports = Storage |
// прерывает цикл - ключевое слово break;
let i = 0;
while (true) {
console.log(i);
i++;
if (i >= 50) break;
}
// перескочить на одну итерацию вперед - continue
for (let i = 0; i < 50; i++) {
if (i % 2 == 0) continue;
console.log(i);
}
// перескочить на одну итерацию вперед - continue
for (let i = 0; i < 50; i++) if (i % 2 != 0) console.log(i);
|
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import GIeditMain from './giEditPortal/GIeditMain'
import MonitorStatus from './MonitorStatus'
import { Prompt } from 'react-router'
export default class SassGIeditScope extends Component {
static propTypes = {
actions: PropTypes.object.isRequired,
}
state = {
when: false
}
componentDidMount(){
document.title = '群管理 | 栗子云'
}
componentWillMount() {
const {naviMetaData,actions} = this.props
if(naviMetaData.flatNaviList!==null){
const isUse = naviMetaData.flatNaviList.find(v => v.code=='GIScope')
if(!isUse){
actions.goTo('/v2/authority?scope=GIScope')
}else if(isUse.target.includes('/v2/NeedOwnScope')){
actions.goTo(isUse.target)
}
}
}
componentDidUpdate(prevProps,prevState){
const {naviMetaData,actions} = this.props
if(naviMetaData.flatNaviList!==null&&prevProps.naviMetaData.flatNaviList===null){
const isUse = naviMetaData.flatNaviList.find(v => v.code=='GIScope')
if(!isUse){
actions.goTo('/v2/authority?scope=GIScope')
}else if(isUse.target.includes('/v2/NeedOwnScope')){
actions.goTo(isUse.target)
}
}
}
changeWhen = (status) => {
this.setState({when: status})
return true
}
render() {
const {userInfo,actions,match} = this.props
const {when} = this.state
return (
<div style ={{height:'100%'}}>
<div className='gc-headBox'>
<MonitorStatus logout = {() => {actions.goTo('/v2/login')}} turnOffws = {actions.turnOffws} userInfo={userInfo}/>
</div>
<GIeditMain changeWhen={this.changeWhen} actions={actions} match={match}/>
<Prompt
when={when}
message="现在退出会丢失已修改信息,是否确认退出?"
/>
</div>
)
}
} |
/**
* Wraps the API used for the game and handles the socketIO connection
*/
var API = function () {
var self = this;
this.socket = io.connect("http://" + document.domain);
this.handlers = {};
this.onceHandlers = {};
// Handle the data returned over the SocketIO
this.socket.on("data", function (data) {
// If the data object has an event member we have
// a valid event message from the server
if (data && data.event) {
var handlers = self.handlers[data.event];
if (handlers != null) {
for (var i = 0; i < handlers.length; i++) {
data.isError ? handlers[i](data) : handlers[i](null, data.result);
}
}
var handlers = self.onceHandlers[data.event];
if (handlers != null) {
while (handlers.length > 0) {
data.isError ? handlers.pop()(data) : handlers.pop()(null, data.result);
}
delete self.onceHandlers[data.event];
}
}
});
};
/**
* Register an event listener callback (will keep receiving messages)
*/
API.prototype.on = function (event, callback) {
if (this.handlers[event] == null) {
this.handlers[event] = [];
}
this.handlers[event].push(callback);
};
/**
* Register an event listener callback for a single instance of the event
*/
API.prototype.once = function (event, callback) {
if (this.onceHandlers[event] == null) {
this.onceHandlers[event] = [];
}
this.onceHandlers[event].push(callback);
};
/**
* Register a new user
*/
API.prototype.register = function (fullName, userName, password, callback) {
// Do basic validation
if (fullName == null || fullName.length == 0) {
return callback(createError("register", "Full name cannot be empty"));
}
if (userName == null || userName.length == 0) {
return callback(createError("register", "User name cannot be empty"));
}
if (password == null || password.length == 0) {
return callback(createError("register", "Password name cannot be empty"));
}
// Register callback
this.once("register", callback);
// Fire message
this.socket.emit("register", {
fullName: fullName,
userName: userName,
password: password
});
};
/**
* Login a user
*/
API.prototype.login = function (userName, password, callback) {
// Do basic validation
if (userName == null || userName.length == 0)
return callback(createError("login", "User name cannot be empty"));
if (password == null || password.length == 0)
return callback(createError("login", "Password name cannot be empty"));
// Register callback
this.once("login", callback);
// Fire message
this.socket.emit("login", {
userName: userName,
password: password
});
};
/**
* Find all available gamers that are active
*/
API.prototype.findAllAvailableGamers = function (callback) {
this.once("findAllAvailableGamers", callback);
this.socket.emit("findAllAvailableGamers", {});
};
/**
* Invite a gamer to a new game
*/
API.prototype.inviteGamer = function (gamer, callback) {
this.once("inviteGamer", callback);
this.socket.emit("inviteGamer", gamer);
};
/**
* Decline an invite to play a game
*/
API.prototype.declineGame = function (invite, callback) {
this.once("declineGame", callback);
this.socket.emit("declineGame", invite);
};
/**
* Accept an invite to play a game
*/
API.prototype.acceptGame = function (invite, callback) {
this.once("acceptGame", callback);
this.socket.emit("acceptGame", invite);
};
/**
* Place a marker on a specific game at a specific location
*/
API.prototype.placeMarker = function (gameId, x, y, callback) {
this.once("placeMarker", callback);
this.socket.emit("placeMarker", {
gameId: gameId
, x: x
, y: y
});
};
/**
* Send a message to a specific gamer on a specific game
*/
API.prototype.sendMessage = function (gameId, message, callback) {
this.once("sendMessage", callback);
this.socket.emit("sendMessage", {gameId: gameId, message: message});
};
/**
* Simple method to create a formated error message that fits the
* format returned from the server
*/
var createError = function (event, err) {
return {
event: event,
ok: false,
isError: true,
error: err
};
};
|
/*
*description:index
*author:fanwei
*date:2014/04/25
*/
define(function(require, exports, module){
var global = require('../global/global');
var until = require('../../../../global/js/global/until');
function Sale() {
}
Sale.prototype = {
init: function() {
this.showPage();
},
showMap: function(l, t, name) {
var map = new BMap.Map("map");
map.centerAndZoom(new BMap.Point(l,t),15);
var marker1 = new BMap.Marker(new BMap.Point(l, t));
map.addOverlay(marker1);
var infoWindow1 = new BMap.InfoWindow(name);
marker1.addEventListener("click", function(){this.openInfoWindow(infoWindow1);});
},
showPage: function() {
var oTplNet,
oNet,
getDataUrl,
_this,
l,
t,
name;
_this = this;
oTplNet = require('../../tpl/build/sale_net/detail');
oNet = $('[sc = sale_net_detail]');
getDataUrl = reqBase + 'vshop/info';
wparam.shop_id = gparam.shop_id;
until.show( oTplNet, oNet, getDataUrl, wparam , function( data ){
l = data.data.shop_longitude;
t = data.data.shop_latitude;
name = data.data.shop_address;
_this.showMap(l, t, name);
});
}
}
var oSale = new Sale();
oSale.init();
}); |
const addNews = require('./addNews');
const getNews = require('./getNews');
module.exports = [
addNews,
getNews
]; |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import '../../App.css';
import SearchField from '../SearchField';
import Suggestion from '../Suggestion';
import ResultSearch from '../ResultSearch';
import LeftPanel from '../LeftPanel';
import * as searchActions from '../../shared/actions/index.js';
import logo from '../../logo.png';
class AppComponent extends Component {
constructor(props) {
super(props);
this.state = { query: 'сеть' };
this.handleChange = this.handleChange.bind(this);
this.onClick = this.onClick.bind(this);
this.onClickSuggestion = this.onClickSuggestion.bind(this);
}
handleChange = name => event => {
let value = event.target.value;
const { searchActions } = this.props;
searchActions.giveQuery(value);
if (value.length % 3 === 0) {
searchActions.getCache(value);
}
};
onClickSuggestion = (value) => {
const { searchActions } = this.props;
searchActions.giveQuery(value);
searchActions.getSearch(value);
searchActions.getCache('');
}
onClick = () => {
const { searchActions, query } = this.props;
searchActions.getSearch(query);
console.log('press button', query)
}
onClickLeftPanel = (value)=>{
const { searchActions } = this.props;
searchActions.getResultGrouping(value)
}
render() {
const { result, cache, query } = this.props;
console.log('result', result)
console.log('cache', cache)
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo"/>
</header>
<div className="App-body">
<LeftPanel onClickLeftPanel={this.onClickLeftPanel}/>
<div className="central-panel">
<SearchField
value={query}
onChange={this.handleChange('query')}
onClick={this.onClick}
/>
<Suggestion cache={cache} onClick={this.onClickSuggestion}/>
<ResultSearch array={result}/>
</div>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
result: state.search.result,
status: state.search.status,
statusText: state.search.statusText,
cache: state.search.cache,
query: state.search.query,
};
}
function mapDispatchToProps(dispatch) {
return {
searchActions: bindActionCreators(searchActions, dispatch),
}
}
//export default AppComponent;
export default connect(mapStateToProps, mapDispatchToProps)(AppComponent);
|
import * as mixins from "codogo-utility-functions";
import styled from "styled-components";
import * as R from "ramda";
import PropTypes from "prop-types";
import React from "react";
// --------------------------------------------------
import { theme, } from "../../../styles";
const Wrapper = styled.div`
${ mixins.bp.sm.min`
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 1em;
` } color: white;
`;
const BoxWrapper = styled.a`
background-color: ${ R.path([ "theme", "nav", ]) };
display: block;
${ mixins.xs`
margin-bottom: 1em;
` };
`;
const paddingTop = "66.7%";
const Image = styled.div`
${ mixins.bgImage }
${ mixins.bp.sm.min`
padding-top: ${ paddingTop };
` }
${ mixins.xs`
padding-top: 50%;
` }
`;
const TextWrapper = styled.div`
${ mixins.bp.sm.min`
padding-top: ${ paddingTop };
position: relative;
` };
`;
const TextInner = styled.div`
${ mixins.bp.sm.min`
${ mixins.contained() }
` } padding: 1em;
`;
const Title = styled.div`
font-family: ${ props => props.theme.font.heading };
font-weight: bold;
font-size: 1.1em;
`;
const Text = styled.div`
font-family: ${ props => props.theme.font.paragraph };
font-size: 0.9em;
`;
const Box = ({ image, title, text, link, }) => (
<BoxWrapper href = { link }>
<Image src = { image && image.url } />
<TextWrapper>
<TextInner>
<Title>{title}</Title>
<Text>{text}</Text>
</TextInner>
</TextWrapper>
</BoxWrapper>
);
const things = [
{
title: "Watch",
text: "Watch things",
image: {
url:
"https://images.pexels.com/photos/220444/pexels-photo-220444.jpeg?h=350&dpr=2&auto=compress&cs=tinysrgb",
},
link: "#",
},
{
title: "Read",
text: "Read things",
image: {
url:
"https://images.pexels.com/photos/220444/pexels-photo-220444.jpeg?h=350&dpr=2&auto=compress&cs=tinysrgb",
},
link: "#",
},
{
title: "Listen",
text: "Listen to things",
image: {
url:
"https://images.pexels.com/photos/220444/pexels-photo-220444.jpeg?h=350&dpr=2&auto=compress&cs=tinysrgb",
},
link: "#",
},
];
export const Boxes = () => (
<Wrapper>{things.map((o, i) => <Box { ...o } key = { i } />)}</Wrapper>
);
|
import { useContext, useEffect } from 'react'
import { toastContext } from '../context/toastContext'
import Icon from './Icon'
const ToastPopup = () => {
const toastCtx = useContext(toastContext)
const renderToastPopups = toasts => {
if (!toasts) return
return toasts.map(t => (
<div
key={t.id}
className="toast__container"
style={{ bottom: `${t.y}px`, right: `${t.x}px` }}
onClick={() => toastCtx.removeToast(t.id)}
>
<Icon name="signup" size="m"></Icon>
<span className="toast__message">{t.message}</span>
<div className="toast__close">
<Icon name="close" size="s"></Icon>
</div>
</div>
))
}
return <>{renderToastPopups(toastCtx.toasts)}</>
}
export default ToastPopup
|
const express = require('express');
const app = express();
const cors = require('cors');
const mongoose = require('mongoose');
const taskRouter = require('./assets/routers/taskRouters');
const memberRouter = require('./assets/routers/memberRouters');
const Task = require('./assets/models/task');
const cron = require('node-cron');
const fs = require('fs');
require('dotenv').config();
const PORT = process.env.PORT|| 8080;
const url = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}/${process.env.DB_NAME}`;
mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('DB connected')
})
.catch(err => {
console.error(err)
});
// JSON request
app.use(cors())
app.use(express.json());
app.use('/members', memberRouter);
app.use('/tasks', taskRouter);
const removeDocuments = cron.schedule('12 55 * * * Wed', async ()=> {
try {
await Task.deleteMany({});
const message = 'Tareas eliminadas del dia: ' + new Date();
await fs.promises.writeFile('logs.log', message, 'utf8')
} catch (error) {
console.error(error)
}
})
removeDocuments.start();
app.get('/', async (req, res) => {
res.json({
error: null,
message: 'Default endpoint'
})
});
app.listen(PORT, (err)=> {
if(err)
console.error(err)
console.log(`Listening server on port ${PORT}`)
}); |
/**
* Speed Container Module
* @module Speed/Container
* @requires react-redux
* @requires {@link module:Speed/Component}
* @requires {@link module:Speed/Actions}
*/
import {connect} from 'react-redux';
import Component from './component';
import {
fetchAllLocationsSpeedRequest,
fetchAllStatisticsRequest,
zoomEnd,
} from './actions';
const mapStateToProps = (state, ownProps) => {
return {
cityCode: state.app.cityCode,
heatmapOptions: state.speed.heatmap,
morningPeakSpeed: state.speed.statistics.morningPeakSpeed,
eveningPeakSpeed: state.speed.statistics.eveningPeakSpeed,
dayAvgSpeed: state.speed.statistics.dayAvgSpeed,
speedTrend: state.speed.statistics.speedTrend,
};
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
fetchAllLocationsSpeedRequest: (payload) => {
dispatch(fetchAllLocationsSpeedRequest(payload));
},
zoomEndHandler: (payload) => {
dispatch(zoomEnd(payload));
},
fetchAllStatisticsRequest: (payload) => {
dispatch(fetchAllStatisticsRequest(payload));
},
};
};
/**
* Connected react component
*/
@connect(mapStateToProps, mapDispatchToProps)
class Container extends Component {
}
/**
* Return redux connected Speed page
*/
export default Container;
|
class Personne {
constructor(prenom, nom, date, lieu, numero, adress, email) {
this.prenom = prenom;
this.nom = nom;
this.date = date;
this.lieu = lieu;
this.numero = numero;
this.adress = adress;
this.email = email;
}
}
function afficher(){
var prenom = document.getElementById('in1').value;
var nom = document.getElementById('in2').value;
var date = document.getElementById('in3').value;
var lieu = document.getElementById('in4').value;
var numero = document.getElementById('in5').value;
var adress = document.getElementById('in6').value;
var email = document.getElementById('in7').value;
let object=new Personne(prenom, nom, date, lieu, numero, adress, email);
var table = document.getElementById("tb");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
var cell7 = row.insertCell(6);
cell1.innerHTML = object.prenom;
cell2.innerHTML = object.nom;
cell3.innerHTML = object.date;
cell4.innerHTML = object.lieu;
cell5.innerHTML = object.numero;
cell6.innerHTML = object.adress;
cell7.innerHTML = object.email;
}
|
import React from "react";
import styles from "../styles/Quote.module.css";
export default function Quote() {
return (
<div className={styles.quoteContainer}>
<blockquote>
Surfing is the most blissful experience you can have on this planet, a
taste of heaven.
</blockquote>
<span className={styles.name}>JOHN MCCARTHY</span>
<span className={styles.line}></span>
</div>
);
}
|
setInterval( "check_hash()", 50 );
var current_hash = window.location.hash;
window.location.hash="0";
var jhistory=new Array();
jhistory[0]=Array("public.php", "page");
var changingHash=false;
function check_hash() {
if(changingHash)return;
if ( window.location.hash != current_hash ) {
current_hash=window.location.hash;
var current_hash1=current_hash.substr(1);
if(!isNaN(current_hash1)&&jhistory.length>current_hash1){
getHttp2(jhistory[current_hash1][0], jhistory[current_hash1][1]);
}
}
}
function getHttp(url, divi){
changingHash=true;
loaded=false;
var nextH=jhistory.length;
jhistory[nextH]=new Array(url, divi);
window.location.hash=nextH;
current_hash=window.location.hash;
changingHash=false;
var httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", url, true);
httpObject.send(null);
httpObject.onreadystatechange = function (){
if(httpObject.readyState == 4){
if(httpObject.responseText=="")document.getElementById(divi).innerHTML = "Error occurred loading page";
else document.getElementById(divi).innerHTML = httpObject.responseText;
loaded=true;
}
}
}
}
function getHttp2(url, divi){
loaded=false;
var httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", url, true);
httpObject.send(null);
httpObject.onreadystatechange = function (){
if(httpObject.readyState == 4){
if(httpObject.responseText=="")document.getElementById(divi).innerHTML = "Error occurred loading page";
else document.getElementById(divi).innerHTML = httpObject.responseText;
loaded=true;
}
}
}
}
var loaded=false;
function getHttpWait(url, div, init){
if(loaded){
if(!init){
getHttp(url, div);
waitLoadScroll();
return;
}
}
setTimeout("getHttpWait('"+url+"', '"+div+"',0)", 50);
}
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else return null;
}
function getUri(httpurl,name, divr) {
var getstr="";
// var getstr =findInputs(document.getElementById(name));
var f=document.getElementsByTagName("input");
for(i=0;i<f.length;i++){
if(f[i].form.id==name){
if (f[i].tagName == "INPUT") {
if (f[i].type == "text"||f[i].type == "hidden") {
getstr += f[i].name + "=" + f[i].value + "&";
}
if (f[i].type == "password") {
getstr += f[i].name + "=" + f[i].value + "&";
}
if (f[i].type == "checkbox") {
if (f[i].checked) {
getstr += f[i].name + "=" + f[i].value + "&";
} else {
getstr += f[i].name + "=&";
}
}
if (f[i].type == "radio") {
if (f[i].checked) {
getstr += f[i].name + "=" + f[i].value + "&";
}
}
}
}
}
f=document.getElementsByTagName("select");
for(i=0;i<f.length;i++){
if(f[i].form.id==name){
getstr += f[i].name + "=" + f[i].options[f[i].selectedIndex].value + "&";
}
}
f=document.getElementsByTagName("textarea");
for(i=0;i<f.length;i++){
if(f[i].form.id==name){
getstr += f[i].name + "=" + f[i].value + "&";
}
}
getHttp2(httpurl+getstr, divr);
}
var cal=false;
function loadcal(){
if(!cal){
loadjs("dayjs.js", "js");
loadjs("daycss.css", "css");
cal=true;
}
}
var slider=false;
function loadslider(){
if(!slider){
loadjs("slider/slider.js", "js");
loadjs("slider/slider.css", "css");
slider=true;
}
}
function waitLoadScroll(){
if(!loaded)setTimeout(waitLoadScroll, 2);
else{
carpeInit();
}
}
function loadjs(filename, filetype){
var fileref
if (filetype=="js"){ //if filename is a external JavaScript file
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype=="css"){ //if filename is an external CSS file
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
function crefresh(){
if( document.refreshForm.check.value == "" )
{
document.refreshForm.check.value = "1";
}
else
{
var current_hash1=current_hash.substr(1);
if(!isNaN(current_hash1)&&jhistory.length>current_hash1){
getHttp2(jhistory[current_hash1][0], jhistory[current_hash1][1]);
}
}
}
function switchImg(id, input){
if(document.getElementById(id).src.substring(document.getElementById(id).src.indexOf("/img/")+5)=="cbe.png"){document.getElementById(id).src="img/cbf.png";
document.getElementById(input).value="1";
}else{
document.getElementById(input).value="0";
document.getElementById(id).src="img/cbe.png";
}
} |
module.exports = {
DiffStream: DiffStream,
PatchStream: PatchStream
};
var stream = require('stream');
var fs = require('fs');
var util = require('util');
var xdelta = require('./build/Release/node_xdelta3.node');
for (var aOpt in xdelta.constants)
module.exports[aOpt] = xdelta.constants[aOpt];
function DiffStream(src, dst, opt) {
stream.Readable.call(this, opt || {});
this.diffObj = new xdelta.XdeltaDiff(src, dst, opt || {});
}
util.inherits(DiffStream, stream.Readable);
DiffStream.prototype._read = function(size) {
var that = this;
that.diffObj.diffChunked(size, function(err, data) {
if (err)
that.emit('error', err);
else
that.push(data);
});
};
function PatchStream(src, dst, opt) {
stream.Writable.call(this, opt || {});
this.patchObj = new xdelta.XdeltaPatch(src, dst, opt || {});
this.on('finish', function () {
var that = this;
that.patchObj.patchChunked(function(err) {
if (err)
that.emit('error', err);
else
that.emit('close');
});
});
}
util.inherits(PatchStream, stream.Writable);
PatchStream.prototype._write = function (chunk, encoding, callback) {
this.patchObj.patchChunked(chunk, callback);
};
|
import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import { default as api } from '../../utils/api'
import store from '../../store'
import router from '../../router'
const user = {
state: {
token: getToken(),
nickname: '',
userId: '',
avatar: '',
role: '',
menus: [],
permissions: []
},
mutations: {
SET_TOKEN: (state, token) => {
state.token = token
},
RESET_TOKEN: (state) => {
state.token = ''
},
SET_USER: (state, userInfo) => {
state.nickname = userInfo.nickname
state.userId = userInfo.userId
state.avatar = userInfo.avatar
state.role = userInfo.roleName
state.menus = userInfo.menuList
state.permissions = userInfo.permissionList
},
RESET_USER: (state) => {
state.token = ''
state.nickname = ''
state.userId = ''
state.avatar = ''
state.role = ''
state.menus = []
state.permissions = []
}
},
actions: {
// 登录
Login({ commit, state }, userInfo) {
const username = userInfo.username.trim()
return new Promise((resolve, reject) => {
login(username, userInfo.password).then(response => {
console.log(response)
const data = response.data
setToken(data.token)
commit('SET_TOKEN', data.token)
resolve()
}).catch(error => {
reject(error)
})
})
},
// 获取用户信息
GetInfo({ commit, state }) {
return new Promise((resolve, reject) => {
getInfo(state.token).then(data => {
// 储存用户信息
commit('SET_USER', data.userPermission)
// 生成路由
const userPermission = data.userPermission
store.dispatch('GenerateRoutes', userPermission).then(() => {
// 生成该用户的新路由json操作完毕之后,调用vue-router的动态新增路由方法,将新路由添加
router.addRoutes(store.getters.addRouters)
})
resolve(data)
}).catch(error => {
reject(error)
})
})
},
// 登出
LogOut({ commit, state }) {
return new Promise((resolve, reject) => {
logout(state.token).then(data => {
commit('RESET_USER')
commit('RESET_TOKEN')
removeToken()
resolve(data)
}).catch(() => {
commit('RESET_USER')
commit('RESET_TOKEN')
removeToken()
resolve()
}).catch(error => {
reject(error)
})
})
},
// 前端 登出
FedLogOut({ commit }) {
return new Promise(resolve => {
commit('RESET_USER')
commit('RESET_TOKEN')
removeToken()
resolve()
})
}
}
}
export default user
|
// JScript 文件
function gotohref() {
var url = 'shop_popinfodaochu.aspx?' + new Date();
var PosID = $("#Txt_PosID").val(); //店铺编号
var ShopName = $("#Txt_ShopName").val(); //店铺简称
var ProID = $("#DDL_Province").val(); //省编号
var CityID = $("#DDL_city").val(); //市编号
var townID = $("#DDL_town").val(); //县编号
var DealerID = $("#ddl_dealer").val(); //一级客户编号
var BoolInstall = "-1"; //是否支持安装
var ShopTypeID = $("#DDL_Shoptype").val(); //店铺类型
var SaleTypeID = $("#SaleTypeID").val(); //销售属性
var StateID = $("#DDL_shopstate").val(); //店铺状态
var fxid = $("#DDL_fx").val(); //直属客户
var department = $("#DDL_DepartMent").val(); //部门
var areaid = $("#DDL_Area").val(); //区域
if (areaid == "0") {
if ($("#hfAreas").val()) {
areaid = $("#hfAreas").val();
}
}
var Citylevel = $("#DDL_Citylevel").val(); //地市级城市级别
var townlevel = $("#DDL_TownLevel").val(); //区县级城市级别
var CusCard = $("#DDL_CoustomerCard").val(); //客户身份
var CusID = $("#txt_CusID").val(); //上级客户编号
var CusLevel = $("#txt_CusName").val(); //上级客户级别
var CusShip = $("#DDL_CustomerShip").val(); //客户产权关系
var ShopLevel = $("#DDL_ShopLevel").val(); //店铺级别
var shopArea = $("#txt_shopArea").val(); //营业面积
var Popseat = $("#DDL_Popseat").val(); //POP类型
var ProductType = $("#DDL_ProductType").val(); //POP故事包大类
var POPline = $("#DDL_POPline").val(); //POP故事包大类
var POParea = $("#txt_POParea").val(); //POP面积
var PfJS = $("#txt_PfJS").val(); //POP橱窗空间进深
var Pfcd = $("#txt_Pfcd").val(); //POP橱窗空间长度
var Pfmj = $("#txt_Pfmj").val(); //POP橱窗空间面积
var supplierID = $("#HidSupplierID").val(); //供应商编号
url = url + "&Posid=" + PosID;
url = url + "&Sname=" + encodeURI(ShopName);
url = url + "&province=" + ProID;
url = url + "&cityid=" + CityID;
url = url + "&dealerid=" + DealerID;
url = url + "&install=" + BoolInstall;
url = url + "&typeid=" + ShopTypeID;
url = url + "&saleid=" + SaleTypeID;
url = url + "&sstate=" + StateID;
url = url + "&Fxid=" + fxid;
url = url + "&department=" + encodeURI(department);
url = url + "&areaid=" + areaid;
url = url + "&Citylevel=" + encodeURI(Citylevel);
url = url + "&townlevel=" + encodeURI(townlevel);
url = url + "&CusCard=" + encodeURI(CusCard);
url = url + "&CusID=" + encodeURI(CusID);
url = url + "&CusLevel=" + encodeURI(CusLevel);
url = url + "&CusShip=" + encodeURI(CusShip);
url = url + "&ShopLevel=" + ShopLevel;
url = url + "&shopArea=" + shopArea;
url = url + "&Popseat=" + encodeURI(Popseat);
url = url + "&ProductType=" + ProductType;
url = url + "&POPline=" + encodeURI(POPline);
url = url + "&POParea=" + POParea;
url = url + "&PfJS=" + PfJS;
url = url + "&Pfcd=" + Pfcd;
url = url + "&Pfmj=" + Pfmj;
url = url + "&townID=" + townID;
url = url + "&supplierID=" + supplierID;
location.href = url;
}
function gotoShophref() {
var url = 'shopinfodaochu.aspx?' + new Date();
var PosID = $("#Txt_PosID").val(); //店铺编号
var ShopName = $("#Txt_ShopName").val(); //店铺简称
var ProID = $("#DDL_Province").val(); //省编号
var CityID = $("#DDL_city").val(); //市编号
var townID = $("#DDL_town").val(); //县编号
var DealerID = $("#ddl_dealer").val(); //一级客户编号
var BoolInstall = "-1"; //是否支持安装
var ShopTypeID = $("#DDL_Shoptype").val(); //店铺类型
var SaleTypeID = $("#SaleTypeID").val(); //销售属性
var StateID = $("#DDL_shopstate").val(); //店铺状态
var fxid = $("#DDL_fx").val(); //直属客户
var department = $("#DDL_DepartMent").val(); //部门
var areaid = $("#DDL_Area").val(); //区域
if (areaid == "0") {
if ($("#hfAreas").val()) {
areaid = $("#hfAreas").val();
}
}
var Citylevel = $("#DDL_Citylevel").val(); //地市级城市级别
var townlevel = $("#DDL_TownLevel").val(); //区县级城市级别
var CusCard = $("#DDL_CoustomerCard").val(); //客户身份
var CusID = $("#txt_CusID").val(); //上级客户编号
var CusLevel = $("#txt_CusName").val(); //上级客户级别
var CusShip = $("#DDL_CustomerShip").val(); //客户产权关系
var ShopLevel = $("#DDL_ShopLevel").val(); //店铺级别
var shopArea = $("#txt_shopArea").val(); //营业面积
var Popseat = $("#DDL_Popseat").val(); //POP类型
var ProductType = $("#DDL_ProductType").val(); //POP故事包大类
var POPline = $("#DDL_POPline").val(); //POP故事包大类
var POParea = $("#txt_POParea").val(); //POP面积
var PfJS = $("#txt_PfJS").val(); //POP橱窗空间进深
var Pfcd = $("#txt_Pfcd").val(); //POP橱窗空间长度
var Pfmj = $("#txt_Pfmj").val(); //POP橱窗空间面积
var supplierID = $("#HidSupplierID").val(); //供应商编号
url = url + "&Posid=" + PosID;
url = url + "&Sname=" + encodeURI(ShopName);
url = url + "&province=" + ProID;
url = url + "&cityid=" + CityID;
url = url + "&dealerid=" + DealerID;
url = url + "&install=" + BoolInstall;
url = url + "&typeid=" + ShopTypeID;
url = url + "&saleid=" + SaleTypeID;
url = url + "&sstate=" + StateID;
url = url + "&Fxid=" + fxid;
url = url + "&department=" + encodeURI(department);
url = url + "&areaid=" + areaid;
url = url + "&Citylevel=" + encodeURI(Citylevel);
url = url + "&townlevel=" + encodeURI(townlevel);
url = url + "&CusCard=" + encodeURI(CusCard);
url = url + "&CusID=" + encodeURI(CusID);
url = url + "&CusLevel=" + encodeURI(CusLevel);
url = url + "&CusShip=" + encodeURI(CusShip);
url = url + "&ShopLevel=" + ShopLevel;
url = url + "&shopArea=" + shopArea;
url = url + "&Popseat=" + encodeURI(Popseat);
url = url + "&ProductType=" + ProductType;
url = url + "&POPline=" + encodeURI(POPline);
url = url + "&POParea=" + POParea;
url = url + "&PfJS=" + PfJS;
url = url + "&Pfcd=" + Pfcd;
url = url + "&Pfmj=" + Pfmj;
url = url + "&townID=" + townID;
url = url + "&supplierID=" + supplierID;
location.href = url;
}
|
import React from 'react';
import { Navbar, Nav} from 'react-bootstrap';
function Header() {
return (
<Navbar collapseOnSelect bg="primary" expand="lg" >
<Navbar.Brand href="#"><img width="80" height="40" alt="Logo" src="https://i.ibb.co/dkw6QvV/pokeapi.png" /></Navbar.Brand>
</Navbar>
)
}
export default Header |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.