text stringlengths 7 3.69M |
|---|
import React, { Component } from 'react';
import { connect } from "react-redux";
import { Redirect } from 'react-router-dom';
import { addAuthentication, removeAuthentication } from "../actions/index";
import axios from 'axios';
function mapDispatchToProps(dispatch) {
return {
addAuthentication: () => dispatch(addAuthentication()),
removeAuthentication: () => dispatch(removeAuthentication())
};
}
class LogoutComponent extends Component {
constructor(props) {
super(props);
}
logout = () => {
axios
.post('/api/auth/logout', { token: localStorage.getItem('token') })
.then(() => {
this.props.removeAuthentication();
localStorage.removeItem('token');
window.location.reload();
})
.catch(err => {
console.error(err);
})
}
render() {
return (
<span {...this.props} onClick={this.logout}>{this.props.children || 'logout'}</span>
)
}
}
class AuthComponent extends Component {
constructor(props) {
super(props);
this.state = {
redirect: null
};
}
componentDidMount() {
const token = localStorage.getItem('token') || '';
if (!token || token === '') {
console.error('No auth data is found!');
if (this.props.failureRedirect) {
this.setState({
redirect: <Redirect to={this.props.failureRedirect} />
});
}
} else {
axios
.post('/api/auth/authorization', {token})
.then(() => {
if (this.props.successRedirect) {
this.setState({
redirect: <Redirect to={this.props.successRedirect} />
});
}
this.props.addAuthentication();
})
.catch(err => {
if (this.props.failureRedirect) {
this.setState({
redirect: <Redirect to={this.props.failureRedirect} />
});
}
this.props.removeAuthentication();
console.error('Failure authentication!');
});
}
}
render() {
return (
<div className="Auth">{this.state.redirect}</div>
);
}
}
const Auth = connect(null, mapDispatchToProps)(AuthComponent);
const LogoutBtn = connect(null, mapDispatchToProps)(LogoutComponent);
export {Auth, LogoutBtn};
|
// function Calc() { //mvc모델
// // --- model ----
// let x = 0;
// let y = 0;
// let result = 0;
// //--- controller -------------
// function btnClick() {
// let inputs = document.querySelectorAll("inputs");
// let xInput = inputs[0];
// let yInput = inputs[1];
// x = parseInt(xInput.value)
// y = parseInt(yInput.value)
// result = x + y;
// }
// function xInpuChange() {
// console.log("x")
// }
// function yInpuChange() {
// console.log("y")
// }
// // ------------------- View -----------------
// //계산기 컴포넌트
// const el = <div id="mvc">
// <label>x:</label>
// <input type="test" value={x} dir="rtl" onChange={xInpuChange}/>
// <label>y:</label>
// <input type="test" value={y} dir="rtl" onChange={yInpuChange}/>
// <input type="button" value="덧셈" onClick={btnClick}/>
// <br/>
// <span>x+y:</span>
// <span>{result}</span>
// </div>;
// }
// ReactDOM.render(<Calc/> , document.querySelector("#root"));
class Calc extends React.Component{
constructor(){
super();
this.state = {
x:10,
y:20,
result:0
};
}
xInputChange(e){
this.setState({
x:e.target.value
})
}
// yInputChange(){
// this.yInputChange({
// y:e.target.value
// })
// }
btnClick(){
//1.객체를 얻어서 값을 얻는 방법
// let inputs = document.querySelectorAll("input");
// let xInput = inputs[0];
// let yInput = inputs[1];
// let x = parseInt(xInput.value)
// let y = parseInt(yInput.value)
// let result = x + y;
// this.setState({result});
//2.리엑트 방식으로 객체를 얻어서 값을 얻는방법(ref로 이름부여)
// let x = parseInt(this.refs.xInput.value)
// let y = parseInt(this.refs.yInput.value)
// let result = x + y;
// this.setState({result});
//3.state를 이용하는 방법
let x = parseInt(this.state.x)
let y = parseInt(this.state.y)
let result = x+y
this.setState({result})
}
render(){
const el = <div id="mvc">
<label>x:</label>
{/* bind통해서 this객체까지 전달 */}
<input ref="xInput" type="text" value={this.state.x} onChange={this.xInputChange.bind(this)} dir="rtl"/>
<label>y:</label>
<input ref="yInput" type="text" value={this.state.y} onChange={(e)=>{this.setState({y:e.target.value})}} dir="rtl"/>
<input type="button" value="덧셈" onClick={this.btnClick.bind(this)}/>
<br/>
<span>x+y:</span>
<span>{this.state.result}</span>
</div>;
return el;
}
}
ReactDOM.render(<Calc/> , document.querySelector("#root"));
|
/**
* Created by kimmy on 2017/3/11.
*/
const common = require('../../until')
const fs = require('fs')
const path = require('path')
const getMsg = async(ctx, next) => {
const today = common.formatDate(new Date(), 'yyyy/MM/dd')
let result = `今天是${today}`
let readFile = new Promise((resolve) => {
fs.readFile(path.resolve(__dirname, './holiday.json'), (err, data) => {
if (err) throw err
const arr = JSON.parse(data)
if (arr[today]) {
result = `今天是${today}, 是${arr[today]}`
}
resolve()
})
})
await readFile
ctx.rest({
code: 0,
data: result
})
}
module.exports = {
getMsg
}
|
import React, { Component } from 'react';
import Validator from 'validator';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Field from './Field/Field';
import addValidationError from '../actions/validationActions';
import { updateRecipientInfo, updateSelectedCountry } from '../actions/transactionActions';
import './recipientInfo.css';
class RecipientInfo extends Component {
onInputChange = ({ fieldName, value, error }) => {
this.props.addValidationError({ fieldName, error }); // Not the best name for this function.. It simply either updates with 'false' or the error message itself, regardless of what it was before.
this.props.updateRecipientInfo({ fieldName, value });
};
onCountryChange = (evt) => {
const [fieldName, value] = [evt.target.name, evt.target.value];
const error = value ? false : 'Veldu land';
this.onInputChange({ fieldName, value, error });
this.props.updateSelectedCountry(evt.target.value);
};
onFormSubmit = (evt) => {
evt.preventDefault();
const url = `http://localhost:3001/api/updateRecipient/${this.props.redirectkey}`;
const myHeaders = new Headers();
myHeaders.set('Content-Type', 'application/json');
const myInit = {
method: 'PUT',
body: JSON.stringify(this.props.recipient),
headers: myHeaders,
};
const request = new Request(url, myInit);
fetch(request)
.then((response) => {
return response.status;
})
.then((response) => {
// If recipient details were updated successfully, then we continue and move on to the next step
// TODO do some more stuff here, maybe add another param ('successful') to the onSubmit function, which LandingPage.js then handles.
if ((response) === 200) {
this.props.onSubmit();
}
})
.catch((error) => {
console.log('fetch unsuccessful, error: ');
console.log(error);
});
};
validate = () => {
const recipient = this.props.recipient;
if (!recipient.fullName) return true;
if (!recipient.address) return true;
if (!recipient.postcode) return true;
// if (this.props.selectedCountry === '' || this.props.selectedCountry === null) return true;
if (!this.props.products.length) return true;
const inputErrors = this.props.inputErrors;
const errMessages = Object.keys(inputErrors).filter(k => inputErrors[k]);
if (errMessages.length) {
for (let i = 0; i < errMessages.length; i++) {
if (errMessages[i] === 'email' || errMessages[i] === 'phone') continue;
return true;
}
}
return false;
};
render() {
// TODO: Uncomment to populate the country selection element when we allow international shipments.
// let countries = [];
// if (this.props.countries) {
// countries = this.props.countries.map((country, i) => {
// return (
// <option key={i} value={country.countryCode}>{country.nameShort}</option>
// );
// });
// }
/*let postcodes = [];
if (this.props.postcodes) {
postcodes = this.props.postcodes.map((postcode) => {
return (
<option key={postcode.postcode} value={postcode.postcode}>{postcode.postcode} {postcode.town}</option>
)
})
}*/
return (
<div className="leftSide col-md-8">
<h1>Upplýsingar um viðtakanda</h1>
<form className="recipientForm" onSubmit={this.onFormSubmit}>
<Field
placeholder="t.d. Jón Jónsson"
label='Fullt nafn'
name="fullName"
value={this.props.recipient.fullName}
onChange={this.onInputChange}
errorState={this.props.inputErrors.fullName}
required
validate={(val) => (val ? false : 'Vantar nafn')}
/>
<br />
<Field
placeholder="t.d. Dúfnahólar 10"
label="Heimilisfang"
name="address"
value={this.props.recipient.address}
onChange={this.onInputChange}
errorState={this.props.inputErrors.address}
required
validate={val => (val ? false : 'Vantar heimilisfang')}
/>
<br />
<Field
placeholder="t.d. 111"
label="Póstnúmer"
name="postcode"
value={this.props.recipient.postcode}
onChange={this.onInputChange}
errorState={this.props.inputErrors.postcode}
required
validate={val => ((Validator.isNumeric(val) && val.length === 3 ) ? false : 'Póstnúmer eru 3 tölustafir')}
/>
<br />
{ /* <div>
<label htmlFor="country">Land</label>
<span className="redAsterix"> *</span>
<br />
<select name="countryCode" id="country" onChange={this.onCountryChange} value={this.props.selectedCountry}>
<option value="">Veldu land</option>
<option value="IS">Ísland</option>
TODO: uncommenta línuna fyrir neðan ef við bætum við sendingum til útlanda
{countries}
</select>
<br />
<span style={{ color: 'red' }}>{ this.props.inputErrors.countryCode }</span>
</div>
<br /> */ }
<div className="recipientContactDetails">Upplýsingar um stöðu sendingar verða sendar á tiltekið tölvupóstfang og/eða í farsíma</div>
<Field
placeholder="t.d. jon@island.is"
label="Tölvupóstfang"
name="email"
value={this.props.recipient.email}
onChange={this.onInputChange}
errorState={this.props.inputErrors.email}
validate={(val) => {
if (val.length === 0) {
return false;
}
if (Validator.isEmail(val)) {
return false;
}
return 'Ekki á réttu formi';
}
}
/>
<br />
<Field
placeholder="t.d. 8671234"
label="Farsími"
name="phone"
value={this.props.recipient.phone}
onChange={this.onInputChange}
errorState={this.props.inputErrors.phone}
validate={(val) => {
// Check if input is empty. If so, all is good.
if (val.length === 0) {
return false;
}
// Check if input consists only of numbers and doesn't exceed 7 digits.
if (Validator.isNumeric(val) && val.length < 8) {
// Check if input is a legit mobile phone number.
if (val.substr(0, 1) !== '6' && val.substr(0, 1) !== '7' && val.substr(0, 1) !== '8') {
return 'Farsímar byrja á 6, 7 eða 8';
}
return false;
}
return 'Símanúmer eru 7 tölustafir';
}
}
/>
<span className="redAsterix">*</span><span>Nauðsynlegt að fylla út</span>
<br />
<input className="btn text-uppercase" type="submit" value="Áfram á næsta skref" disabled={this.validate()} />
</form>
</div>
);
}
}
function mapStateToProps(state) {
return {
inputErrors: state.recipientInfoValidation.inputErrors,
products: state.transactionDetails.products,
selectedCountry: state.transactionDetails.recipientInfo.countryCode,
// selectedPostcode: state.transactionDetails.recipientInfo.postcode,
};
}
function matchDispatchToProps(dispatch) {
return bindActionCreators({
addValidationError,
updateRecipientInfo,
updateSelectedCountry,
}, dispatch);
}
export default connect(mapStateToProps, matchDispatchToProps)(RecipientInfo);
|
import React, { useEffect, useState } from "react";
import "./AddProduct.css";
import axios from "axios";
import {
saveProduct,
getProduct,
deleteProduct
} from "../../../api/productApi";
import ImageUpload from "./imageUpload";
export default function AddProduct(props) {
//one state for everything
const [productData, setProductData] = useState({});
const [dropDownValue, setDropDown] = useState("");
const [files, setFiles] = useState();
const handleDropdown = event => {
let selectedValue = event.target.value;
console.log([...dropDownValue]);
setDropDown(selectedValue);
};
// console.log(productData);
console.log(files);
// handler functions
const handleChange = event => {
event.preventDefault();
const { name, value } = event.target;
// handler function that updates the state
setProductData({
...productData,
[name]: value
// UploadedFile: files
});
};
const handleSubmit = async event => {
event.preventDefault();
const formData = new FormData();
console.log(productData);
const data = {
...productData,
category: dropDownValue
};
formData.append("image", files);
console.log(formData);
const response = await (axios.post(`/api/addProduct`, formData, {
header: { "Content-Type": "multipart/form-data" }
}) && axios.post(`/api/addProduct`, data));
console.log(response.data);
console.log(props.history);
props.history.push("/products");
};
return (
<div className="product-container">
<div className="container add-product-container">
<p className="h2 text-center">Add Product</p>
<form onSubmit={handleSubmit}>
<ImageUpload files={files} setFiles={setFiles} />
<select
name="customSearch"
className="custom-search-select"
onChange={handleDropdown}
>
<option style={{fontFamily: "Comfortaa"}}>Laptops</option>
<option>Phones</option>
<option>Clothes</option>
</select>
<div className="form-group">
<label>Product Name:</label>
<input
className="form-control"
type="text"
name="productName"
onChange={handleChange}
required
placeholder="Enter product name"
/>
<span className="Error" />
</div>
<div className="form-group">
<label>Description:</label>
<input
className="form-control"
type="text"
name="description"
onChange={handleChange}
required
placeholder="Enter Your Description"
/>
<span className="Error" />
</div>
<div className="form-group">
<label>Location:</label>
<input
className="form-control"
type="text"
name="location"
required
onChange={handleChange}
placeholder="Enter Location"
/>
<span className="Error" />
</div>
<div className="form-group">
<label>Price:</label>
<input
className="form-control"
name="price"
type="number"
required
onChange={handleChange}
placeholder="Enter Price"
/>
<span className="Error" />
</div>
<div className="form-grou">
<input
className="btn btn-primary btn-block"
type="submit"
defaultValue="Submit"
/>
</div>
</form>
</div>
</div>
);
}
|
export default {
props: {
// 表单数据对象
parentData: {
type: [Array, Object],
default: () => ({})
},
parentKey: {
type: String,
default: ''
}
},
data() {
return {
propKey: `${this.parentKey || ''}${this.parentKey ? '.' : ''}${this.item.key}`
}
},
methods: {
// input操作
mHandelInput(value) {
if (this.$store.getters['manage/isEdit']) {
this.$set(this.item, 'value', value)
} else {
this.$set(this.parentData, this.item.key, value)
}
}
},
computed: {
// 用于显示的value
mValue() {
if (this.$store.getters['manage/isEdit']) {
return this.item.value
}
return this.parentData[this.item.key]
}
},
created() {
if (!this.$store.getters['manage/isEdit']
&& this.parentData[this.item.key] === undefined
&& this.item.key) {
// 引用类型数据需要深拷贝
if (typeof this.item.value === 'object') {
const data = JSON.parse(JSON.stringify(this.item.value))
this.$set(this.parentData, this.item.key, data)
} else {
this.$set(this.parentData, this.item.key, this.item.value)
}
}
}
}
|
/*
* Copyright 2018 Uber Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const test = require('tape');
const h3 = require('h3-js');
const geojson2h3 = require('../src/geojson2h3');
const DEFAULT_RES = 9;
const {
featureToH3Set,
h3ToFeature,
h3SetToFeature,
h3SetToMultiPolygonFeature,
h3SetToFeatureCollection
} = geojson2h3;
const GEO_PRECISION = 12;
// 89283085507ffff
const HEX_OUTLINE_1 = [
[
[-122.47485823276713, 37.85878356045377],
[-122.47378734444064, 37.860465621984154],
[-122.47504834087829, 37.86196795698972],
[-122.47738022442019, 37.861788207189115],
[-122.47845104316997, 37.86010614563313],
[-122.4771900479571, 37.85860383390307],
[-122.47485823276713, 37.85878356045377]
]
];
// 892830855b3ffff
const HEX_OUTLINE_2 = [
[
[-122.48147295617736, 37.85187534491365],
[-122.48040229236011, 37.85355749750206],
[-122.48166324644575, 37.85505983954851],
[-122.48399486310532, 37.85488000572598],
[-122.48506545734224, 37.85319785312151],
[-122.48380450450253, 37.851695534355315],
[-122.48147295617736, 37.85187534491365]
]
];
const POLYGON = [
[
[-122.26184837431902, 37.8346695948541],
[-122.26299146613795, 37.8315769200876],
[-122.26690391101923, 37.830681442651134],
[-122.2696734085486, 37.83287856171719],
[-122.26853055028259, 37.835971208076515],
[-122.26461796082103, 37.83686676365336],
[-122.26184837431902, 37.8346695948541]
]
];
const POLYGON_CONTIGUOUS = [
[
[-122.25793560913665, 37.835564941293676],
[-122.26184837431902, 37.8346695948541],
[-122.26299146613795, 37.8315769200876],
[-122.26022202614566, 37.82937956347423],
[-122.25630940542779, 37.830274831952494],
[-122.25516608024519, 37.83336753500189],
[-122.25793560913665, 37.835564941293676]
]
];
const POLYGON_NONCONTIGUOUS = [
[
[-122.23511849129424, 37.829458676659385],
[-122.23788784659696, 37.831656795184344],
[-122.24180113856318, 37.83076207598435],
[-122.24294493056115, 37.827669316312495],
[-122.24017566397347, 37.825471247577006],
[-122.2362625166653, 37.82636588872747],
[-122.23511849129424, 37.829458676659385]
]
];
function toLowPrecision(maybeNumber) {
if (typeof maybeNumber === 'number') {
return Number(maybeNumber.toPrecision(GEO_PRECISION));
}
if (Array.isArray(maybeNumber)) {
return maybeNumber.map(toLowPrecision);
}
if (typeof maybeNumber === 'object') {
/* eslint-disable guard-for-in */
for (const key in maybeNumber) {
maybeNumber[key] = toLowPrecision(maybeNumber[key]);
}
}
return maybeNumber;
}
function assertEqualFeatures(assert, feature1, feature2, msg) {
assert.deepEqual(
toLowPrecision(feature1),
toLowPrecision(feature2),
msg || 'Features are equivalent'
);
}
function assertSymmetrical(assert, feature, hexagons) {
assert.deepEqual(
featureToH3Set(feature, DEFAULT_RES).sort(),
hexagons.sort(),
'featureToH3Set matches expected'
);
assertEqualFeatures(
assert,
h3SetToFeature(hexagons),
feature,
'h3SetToFeature matches expected'
);
// not sure this adds anything, but it makes me feel good
assert.deepEqual(
featureToH3Set(h3SetToFeature(hexagons), DEFAULT_RES).sort(),
hexagons.sort(),
'featureToH3Set round-trip matches expected'
);
assertEqualFeatures(
assert,
h3SetToFeature(featureToH3Set(feature, DEFAULT_RES).sort()),
feature,
'h3SetToFeature round-trip matches expected'
);
}
test('Symmetrical - Empty', assert => {
const feature = {
type: 'Feature',
properties: {},
geometry: {
type: 'Polygon',
coordinates: []
}
};
const hexagons = [];
assertSymmetrical(assert, feature, hexagons);
assert.end();
});
test('Symmetrical - One hexagon', assert => {
const hexagons = ['89283082837ffff'];
const vertices = h3.h3ToGeoBoundary(hexagons[0], true);
const feature = {
type: 'Feature',
properties: {},
geometry: {
type: 'Polygon',
coordinates: [
// Note that this is a little brittle; iterating from any
// starting vertex would be correct
[...vertices]
]
}
};
assertSymmetrical(assert, feature, hexagons);
assert.end();
});
test('Symmetrical - Two hexagons', assert => {
const feature = {
type: 'Feature',
properties: {},
geometry: {
type: 'Polygon',
coordinates: [
[
[-122.42778275313196, 37.775989518837726],
[-122.42652309807923, 37.77448508566524],
[-122.42419231791126, 37.7746633251758],
[-122.42312112449315, 37.776346021077586],
[-122.42438078060647, 37.77785047757876],
[-122.42671162907993, 37.777672214849176],
[-122.42797132395157, 37.7791765946462],
[-122.4303021418057, 37.778998255103545],
[-122.4313731964829, 37.77731555898803],
[-122.43011350268344, 37.77581120251896],
[-122.42778275313196, 37.775989518837726]
]
]
}
};
const hexagons = ['89283082833ffff', '89283082837ffff'];
assertSymmetrical(assert, feature, hexagons);
assert.end();
});
test('featureToH3Set - one contained hex', assert => {
const hexagons = ['89283085507ffff'];
const feature = {
type: 'Feature',
properties: {},
geometry: {
type: 'MultiPolygon',
coordinates: HEX_OUTLINE_1
}
};
assert.deepEqual(
featureToH3Set(feature, DEFAULT_RES),
hexagons,
'featureToH3Set matches expected'
);
assert.end();
});
const SMALL_POLY = {
type: 'Feature',
properties: {},
geometry: {
type: 'Polygon',
coordinates: [
[
[-122.26985598997341, 37.83598006884068],
[-122.26836960154117, 37.83702107154188],
[-122.26741606933939, 37.835426338014386],
[-122.26985598997341, 37.83598006884068]
]
]
}
};
test('featureToH3Set - no contained hex centers', assert => {
assert.deepEqual(featureToH3Set(SMALL_POLY, 8), [], 'featureToH3Set matches expected');
assert.end();
});
test('featureToH3Set - no contained hex centers, ensureOutput', assert => {
const hexagons = ['8828308137fffff'];
assert.deepEqual(
featureToH3Set(SMALL_POLY, 8, {ensureOutput: true}),
hexagons,
'featureToH3Set matches expected'
);
assert.end();
});
test('featureToH3Set - Polygon', assert => {
const feature = {
type: 'Feature',
properties: {},
geometry: {
type: 'Polygon',
coordinates: POLYGON
}
};
const hexagons = ['89283081347ffff', '89283081343ffff', '8928308134fffff', '8928308137bffff'];
assert.deepEqual(
featureToH3Set(feature, DEFAULT_RES).sort(),
hexagons.sort(),
'featureToH3Set matches expected'
);
assert.end();
});
test('featureToH3Set - MultiPolygon, duplicates', assert => {
const feature = {
type: 'Feature',
properties: {},
geometry: {
type: 'MultiPolygon',
coordinates: [POLYGON, POLYGON]
}
};
const hexagons = ['89283081347ffff', '89283081343ffff', '8928308134fffff', '8928308137bffff'];
assert.deepEqual(
featureToH3Set(feature, DEFAULT_RES).sort(),
hexagons.sort(),
'featureToH3Set matches expected'
);
assert.end();
});
test('featureToH3Set - MultiPolygon, contiguous', assert => {
const feature = {
type: 'Feature',
properties: {},
geometry: {
type: 'MultiPolygon',
coordinates: [POLYGON, POLYGON_CONTIGUOUS]
}
};
const hexagons = [
'89283081347ffff',
'89283081343ffff',
'8928308134fffff',
'8928308137bffff',
'8928308134bffff',
'8928308ac97ffff',
'8928308135bffff'
];
assert.deepEqual(
featureToH3Set(feature, DEFAULT_RES).sort(),
hexagons.sort(),
'featureToH3Set matches expected'
);
assert.end();
});
test('featureToH3Set - MultiPolygon, non-contiguous', assert => {
const feature = {
type: 'Feature',
properties: {},
geometry: {
type: 'MultiPolygon',
coordinates: [POLYGON, POLYGON_NONCONTIGUOUS]
}
};
const hexagons = [
'89283081347ffff',
'89283081343ffff',
'8928308134fffff',
'8928308137bffff',
'8928308a1b7ffff'
];
assert.deepEqual(
featureToH3Set(feature, DEFAULT_RES).sort(),
hexagons.sort(),
'featureToH3Set matches expected'
);
assert.end();
});
test('featureToH3Set - FeatureCollection', assert => {
const feature = {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: POLYGON
}
},
{
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: POLYGON_CONTIGUOUS
}
}
]
};
const hexagons = [
'89283081347ffff',
'89283081343ffff',
'8928308134fffff',
'8928308137bffff',
'8928308134bffff',
'8928308ac97ffff',
'8928308135bffff'
];
assert.deepEqual(
featureToH3Set(feature, DEFAULT_RES).sort(),
hexagons.sort(),
'featureToH3Set matches expected'
);
assert.end();
});
test('featureToH3Set - resolution 10', assert => {
const parentHex = '89283082837ffff';
const vertices = h3.h3ToGeoBoundary(parentHex, true);
const feature = {
type: 'Feature',
properties: {},
geometry: {
type: 'Polygon',
coordinates: [
[
vertices[2],
vertices[3],
vertices[4],
vertices[5],
vertices[0],
vertices[1],
vertices[2]
]
]
}
};
const resolution = 10;
const expected = h3.uncompact([parentHex], resolution).sort();
assert.equal(expected.length, 7, 'Got expected child hexagons');
assert.deepEqual(
featureToH3Set(feature, resolution).sort(),
expected,
'featureToH3Set matches expected'
);
assert.end();
});
test('featureToH3Set - errors', assert => {
assert.throws(
() => featureToH3Set({}),
/Unhandled type/,
'got expected error for empty object'
);
assert.throws(
() =>
featureToH3Set({
type: 'LineString',
coordinates: []
}),
/Unhandled type/,
'got expected error for non-feature'
);
assert.throws(
() =>
featureToH3Set({
type: 'Feature',
properties: {},
geometry: {
type: 'LineString',
coordinates: []
}
}),
/Unhandled geometry type/,
'got expected error for unknown geometry type'
);
assert.throws(
() =>
featureToH3Set({
type: 'FeatureCollection'
}),
/No features/,
'got expected error for missing features'
);
assert.end();
});
test('h3SetToFeature - MultiPolygon', assert => {
const hexagons = ['8928308137bffff', '8928308a1b7ffff'];
const feature = h3SetToFeature(hexagons);
assert.strictEqual(
feature.geometry.type,
'MultiPolygon',
'MultiPolygon generated for two non-contiguous hexagons'
);
assert.ok(feature.geometry.coordinates.length === 2, 'Generated polygon for each hex');
assert.ok(
feature.geometry.coordinates[0][0][0][0],
'Generated MultiPolygon coordinate structure for first loop'
);
assert.ok(
feature.geometry.coordinates[1][0][0][0],
'Generated MultiPolygon coordinate structure second loop'
);
assert.end();
});
test('h3SetToFeature - Polygon hole', assert => {
const hexagons = [
'89283082877ffff',
'89283082863ffff',
'8928308287bffff',
'89283082847ffff',
'8928308280bffff',
'8928308280fffff'
];
const feature = h3SetToFeature(hexagons);
assert.strictEqual(
feature.geometry.type,
'Polygon',
'Polygon generated for cluster with a hole'
);
assert.strictEqual(feature.geometry.coordinates.length, 2, 'Generated expected loop count');
assert.ok(
feature.geometry.coordinates[0].length > feature.geometry.coordinates[1].length,
'Outer loop is first'
);
assert.strictEqual(feature.geometry.coordinates[1].length, 7, 'Hole has expected coord count');
assert.end();
});
test('h3SetToFeature - two-hole Polygon', assert => {
const hexagons = [
'89283081357ffff',
'89283081343ffff',
'8928308134fffff',
'8928308137bffff',
'89283081373ffff',
'8928308130bffff',
'892830813c3ffff',
'892830813cbffff',
'89283081353ffff',
'8928308131bffff',
'892830813c7ffff'
];
const feature = h3SetToFeature(hexagons);
assert.strictEqual(
feature.geometry.type,
'Polygon',
'Polygon generated for cluster with a hole'
);
assert.strictEqual(feature.geometry.coordinates.length, 3, 'Generated expected loop count');
assert.ok(
feature.geometry.coordinates[0].length > feature.geometry.coordinates[1].length,
'Outer loop is first'
);
assert.strictEqual(feature.geometry.coordinates[1].length, 7, 'Hole has expected coord count');
assert.strictEqual(feature.geometry.coordinates[2].length, 7, 'Hole has expected coord count');
assert.end();
});
test('h3SetToFeature - multi donut', assert => {
const hexagons = [
// donut one
'89283082877ffff',
'89283082863ffff',
'8928308287bffff',
'89283082847ffff',
'8928308280bffff',
'8928308280fffff',
// donut two
'892830829b3ffff',
'892830829bbffff',
'8928308298fffff',
'89283082983ffff',
'89283082997ffff',
'89283095a4bffff'
];
const feature = h3SetToFeature(hexagons);
const coords = feature.geometry.coordinates;
assert.strictEqual(coords.length, 2, 'expected polygon count');
assert.strictEqual(coords[0].length, 2, 'expected loop count for p1');
assert.strictEqual(coords[1].length, 2, 'expected loop count for p2');
assert.strictEqual(coords[0][0].length, 19, 'expected outer coord count p1');
assert.strictEqual(coords[0][1].length, 7, 'expected inner coord count p1');
assert.strictEqual(coords[1][0].length, 19, 'expected outer coord count p2');
assert.strictEqual(coords[1][1].length, 7, 'expected inner coord count p2');
assert.end();
});
test('h3SetToFeature - nested donut', assert => {
const middle = '89283082877ffff';
const hexagons = h3.hexRing(middle, 1).concat(h3.hexRing(middle, 3));
const feature = h3SetToFeature(hexagons);
const coords = feature.geometry.coordinates;
assert.strictEqual(coords.length, 2, 'expected polygon count');
assert.strictEqual(coords[0].length, 2, 'expected loop count for p1');
assert.strictEqual(coords[1].length, 2, 'expected loop count for p2');
assert.strictEqual(coords[0][0].length, 6 * 3 + 1, 'expected outer coord count p1');
assert.strictEqual(coords[0][1].length, 7, 'expected inner coord count p1');
assert.strictEqual(coords[1][0].length, 6 * 7 + 1, 'expected outer coord count p2');
assert.strictEqual(coords[1][1].length, 6 * 5 + 1, 'expected inner coord count p2');
assert.end();
});
test('h3SetToFeature - properties', assert => {
const properties = {
foo: 1,
bar: 'baz'
};
const hexagons = ['500428f003a9f'];
const feature = h3SetToFeature(hexagons, properties);
assert.deepEqual(feature.properties, properties, 'Properties included in feature');
assert.end();
});
test('h3ToFeature', assert => {
const hexagon = '89283082837ffff';
const vertices = h3.h3ToGeoBoundary(hexagon, true);
const feature = {
id: hexagon,
type: 'Feature',
properties: {},
geometry: {
type: 'Polygon',
coordinates: [vertices]
}
};
assert.deepEqual(h3ToFeature(hexagon), feature, 'h3ToFeature matches expected');
assert.end();
});
test('h3SetToMultiPolygonFeature', assert => {
const hexagons = ['89283085507ffff', '892830855b3ffff'];
const feature = {
type: 'Feature',
properties: {},
geometry: {
type: 'MultiPolygon',
coordinates: [HEX_OUTLINE_1, HEX_OUTLINE_2]
}
};
const result = h3SetToMultiPolygonFeature(hexagons);
assertEqualFeatures(assert, result, feature);
assert.deepEqual(
featureToH3Set(result, DEFAULT_RES),
hexagons,
'featureToH3Set round-trip matches expected'
);
assert.end();
});
test('h3SetToMultiPolygonFeature - properties', assert => {
const properties = {
foo: 1,
bar: 'baz'
};
const hexagons = ['89283085507ffff'];
const feature = h3SetToMultiPolygonFeature(hexagons, properties);
assert.deepEqual(feature.properties, properties, 'Properties included in feature');
assert.end();
});
test('h3SetToFeatureCollection', assert => {
const hexagons = ['89283085507ffff', '892830855b3ffff'];
const expected = {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
id: hexagons[0],
properties: {},
geometry: {
type: 'Polygon',
coordinates: HEX_OUTLINE_1
}
},
{
type: 'Feature',
id: hexagons[1],
properties: {},
geometry: {
type: 'Polygon',
coordinates: HEX_OUTLINE_2
}
}
]
};
const result = h3SetToFeatureCollection(hexagons);
assertEqualFeatures(assert, result, expected);
assert.end();
});
test('h3SetToFeatureCollection - properties', assert => {
const hexagons = ['89283085507ffff', '892830855b3ffff'];
const properties = {
'89283085507ffff': {foo: 1},
'892830855b3ffff': {bar: 'baz'}
};
function getProperties(hexAddress) {
return properties[hexAddress];
}
const result = h3SetToFeatureCollection(hexagons, getProperties);
assert.deepEqual(
result.features[0].properties,
properties[hexagons[0]],
'Properties match expected for hexagon'
);
assert.deepEqual(
result.features[1].properties,
properties[hexagons[1]],
'Properties match expected for hexagon'
);
assert.end();
});
|
var x = document.domain;
function checkAll(ele) {
var checkboxes = document.getElementsByTagName('input');
if (ele.checked) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = true;
}
}
} else {
for (var i = 0; i < checkboxes.length; i++) {
console.log(i)
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
}
$('#action').on('change', function(e, item){
var d = document.getElementById("action").value;
if(d == 'create') {
window.location = "http://"+x+"/cert/admin/addpage";
//alert(x);
}
else if(d == 'edit') {
var checkboxes = document.querySelectorAll('input[name="pages"]:checked'), values = [];
Array.prototype.forEach.call(checkboxes, function(el) {
values.push(el.value);
});
window.location = "http://"+x+"/cert/admin/editpage/"+values;
}
else if(d == 'preview'){
var checkboxes = document.querySelectorAll('input[name="pages"]:checked'), values = [];
Array.prototype.forEach.call(checkboxes, function(el) {
values.push(el.value);
});
window.location = "http://"+x+"/cert/admin/pagepreview/"+values;
}
});
$(document).ready(function(){
$("#addmenu").click(function(){
//$("ol").prepend("<li>Prepended item</li>");
// $("#test").append("<li class='dd-item dd3-item' id='test[]' data-id='13'><div class='dd-handle dd3-handle'>Drag</div><div class='dd3-content'>Item 14</div></li>");
var e = document.getElementById("page_type");
var strUser = e.options[e.selectedIndex].value;
if(strUser == 'page') {
$("#pageModal").modal();
var menu = document.getElementById("menuname").value;
document.getElementById('menu-name').value = menu;
} else if(strUser == 'resources') {
$("#resourcesModal").modal();
var menu = document.getElementById("menuname").value;
document.getElementById('menuname-resources').value = menu;
}
else if(strUser == 'disasters') {
$("#disastersModal").modal();
var menu = document.getElementById("menuname").value;
document.getElementById('menuname-disaster').value = menu;
}
});
$("#addmenunoname").click(function(){
var e = document.getElementById("content_type");
var strUser = e.options[e.selectedIndex].value;
if(strUser == 'page') {
$("#nonamepageModal").modal();
}
else if('resources') {
}
});
$("#savemenu").click(function(){
var content = document.getElementById("menulist").innerHTML;
var postData = {
'content' : content,
'community_id' : 0
};
$.post('http://'+x+'/cert/systems/process/admin/savemenu', postData, function(data){
alert(data);
});
});
$("#editmenu").click(function(){
var content = document.getElementById("menulist").innerHTML;
var postData = {
'content' : content,
'community_id' : 0
};
$.post('http://'+x+'/cert/systems/process/admin/editmenu', postData, function(data){
alert(data);
});
});
$("#addresources").click(function(){
//$("#test").append("<li class='dd-item dd3-item' id='test[]' data-id='13'><div class='dd-handle dd3-handle'>Drag</div><div class='dd3-content'>Item 14</div></li>");
var checkboxes = document.querySelectorAll('input[name="resources"]:checked'), values = [];
Array.prototype.forEach.call(checkboxes, function(el) {
values.push(el.value);
});
var post = {
'r_id' : parseInt(values)
};
$.post('http://'+x+'/cert/systems/process/admin/resourcesdetails', post, function(data){
$("#test").append("<li class='dd-item dd3-item' id='test[]' data-id='13'><div class='dd-handle dd3-handle'>Drag</div><div class='dd3-content'>Resources : "+data+"<input type='hidden' name='addcontent[]' id='addcontent' value='resources_"+values+"'></div></li>");
});
});
$("#assignnonamepagemenu").click(function(){
var checkboxes = document.querySelectorAll('input[name="pages"]:checked'), values = [];
Array.prototype.forEach.call(checkboxes, function(el) {
values.push(el.value);
});
var post = {
'r_id' : parseInt(values)
};
$.post('http://'+x+'/cert/systems/process/admin/pagedetails', post, function(data){
$("#menulist").append("<li class='dd-item dd3-item' id='test[]' data-id='13'><div class='dd-handle dd3-handle'>Drag</div><div class='dd3-content'>Page : "+data+"<input type='hidden' name='addcontent[]' id='addcontent' value='page_"+values+"'></div></li>");
//alert(data);
//$("#menulist").append("test");
});
});
$("#assignpagemenu").click(function(){
var checkboxes = document.querySelectorAll('input[name="pages"]:checked'), values = [];
Array.prototype.forEach.call(checkboxes, function(el) {
values.push(el.value);
});
var menuname = document.getElementById('menu-name').value;
var post = {
'r_id' : parseInt(values)
};
$.post('http://'+x+'/cert/systems/process/admin/pagedetails', post, function(data){
$("#menulist").append("<li class='dd-item dd3-item' id='test[]' data-id='13'><div class='dd-handle dd3-handle'>Drag</div><div class='dd3-content'>Page : "+menuname+"<input type='hidden' name='addcontent[]' id='addcontent' value='page_"+values+"'></div></li>");
//alert(data);
//$("#menulist").append("test");
});
});
$("#assignresourcesmenu").click(function(){
var checkboxes = document.querySelectorAll('input[name="resources"]:checked'), values = [];
Array.prototype.forEach.call(checkboxes, function(el) {
values.push(el.value);
});
var menuname = document.getElementById('menuname-resources').value;
var post = {
'r_id' : parseInt(values)
};
$.post('http://'+x+'/cert/systems/process/admin/resourcesdetails', post, function(data){
$("#menulist").append("<li class='dd-item dd3-item' id='test[]' data-id='13'><div class='dd-handle dd3-handle'>Drag</div><div class='dd3-content'>Resources : "+menuname+"<input type='hidden' name='addcontent[]' id='addcontent' value='resources_"+values+"'></div></li>");
//alert(data);
//$("#menulist").append("test");
});
});
$("#assigndisastersmenu").click(function(){
var checkboxes = document.querySelectorAll('input[name="disasters"]:checked'), values = [];
Array.prototype.forEach.call(checkboxes, function(el) {
values.push(el.value);
});
var menuname = document.getElementById('menuname-disaster').value;
var post = {
'r_id' : parseInt(values)
};
$.post('http://'+x+'/cert/systems/process/admin/disasterdetails', post, function(data){
$("#menulist").append("<li class='dd-item dd3-item' id='test[]' data-id='13'><div class='dd-handle dd3-handle'>Drag</div><div class='dd3-content'>Disaster : "+menuname+"<input type='hidden' name='addcontent[]' id='addcontent' value='disaster_"+values+"'></div></li>");
//alert(data);
//$("#menulist").append("test");
});
});
$("#btnaddcontent").click(function(){
var e = document.getElementById("type");
var strUser = e.options[e.selectedIndex].value;
if(strUser == 'resources') {
$("#resourcesModal").modal();
} else if(strUser == 'kits') {
$("#kitsModal").modal();
}
else if(strUser == 'disaster') {
$("#disasterModal").modal();
}
});
$("#savepage").click(function(){
var pagename = document.getElementById("pagename").value;
var postData = {
'pagename' : pagename
};
$.post('http://'+x+'/cert/systems/process/admin/addpage', postData, function(data){
//This should be JSON preferably. but can't get it to work on jsfiddle
//Depending on what your controller returns you can change the action
var content = tinymce.get('elm1').getContent();
var page_id = data;
if(content != '') {
var postData = {
'content' : content,
'id' : page_id,
'type' : 'html'
};
$.post('http://'+x+'/cert/systems/process/admin/addpageresources', postData, function(data){
});
var items = [];
var fields = document.getElementsByName("addcontent[]");
for(var i = 0; i < fields.length; i++) {
//alert(fields[i].value);
var content_array = fields[i].value;
var postData = {
'content' : content_array,
'id' : page_id,
'type' : 'resources'
};
$.post('http://'+x+'/cert/systems/process/admin/addpageresources', postData, function(data){
});
};
}
else {
var fields = document.getElementsByName("addcontent[]");
for(var i = 0; i < fields.length; i++) {
//alert(fields[i].value);
var content_array = fields[i].value;
var postData = {
'content' : content_array,
'id' : page_id,
'type' : 'resources'
};
$.post('http://'+x+'/cert/systems/process/admin/addpageresources', postData, function(data){
});
};
}
window.location = "http://"+x+"/cert/admin/pages";
});
});
});
|
import React from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import _ from 'lodash';
class Authenticate extends React.Component {
constructor() {
super();
this.state = {
register: false,
passwordsMatch: true,
errorMessage: 'Hi there!'
};
}
authenticate() {
let app = this.props.app;
let self = this;
app.authenticate(_.merge({
type: 'local',
}, this.userFromForm())).then((result) => {
self.setState({
errorMessage: 'Hi there!'
});
self.props.onAuthenticate();
}).catch((error) => {
self.setState({
errorMessage: error.message
});
console.error('Error authenticating!', error);
});
}
userFromForm() {
return {
'email': this.refs.email.getValue(),
'password': this.refs.password.getValue()
};
}
register() {
let app = this.props.app;
let self = this;
app.service('users').create(
this.userFromForm()
).then((result) => {
self.setState({
errorMessage: 'Hi there!'
});
self.authenticate();
}).catch((error) => {
console.error('Error authenticating!', error);
});
}
onSubmit(event) {
if (this.state.register) {
this.register();
} else {
this.authenticate();
}
}
toggleRegister() {
this.setState({
register: !this.state.register
});
}
checkPasswords() {
let password1 = this.refs.password.getValue();
let password2 = this.refs.passwordConfirmation.getValue();
console.log(password1, password2);
this.setState({
passwordsMatch: this.state.register && password1 === password2
});
}
render() {
const actions = [
<FlatButton
label={ this.state.register ? "Sign in" : "Register" }
primary={false}
keyboardFocused={false}
onTouchTap={this.toggleRegister.bind(this)}
/>,
<FlatButton
label={ this.state.register ? "Register" : "Sign in" }
primary={true}
keyboardFocused={true}
disabled={ !this.state.passwordsMatch }
onTouchTap={this.onSubmit.bind(this)}
/>,
];
return (
<Dialog
title={ this.state.errorMessage }
actions={actions}
modal={false}
open={true}
onRequestClose={this.onSubmit.bind(this)}>
<TextField ref="email" hintText="email" type="email" />
<TextField ref="password" hintText="Password" type="password" errorText={ this.state.passwordsMatch ? false : "Passwords don't match" } />
{ this.state.register && <TextField ref="passwordConfirmation" hintText="Repeat password" type="password" onBlur={ this.checkPasswords.bind(this) } /> }
</Dialog>
);
}
}
export default Authenticate;
|
import React, { useState, useEffect } from 'react'
import { View, Text, Image, TouchableOpacity, FlatList } from 'react-native'
import { Styles } from "./Style/AddNewReminderStyle"
import { theme, images } from "../../constants"
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from "react-native-responsive-screen"
import { Button } from '@ui-kitten/components'
import { Input, Container, Content, Item, Label, Row, Col, Icon } from 'native-base';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import calendar from '../../constants/calendar';
import { Calendar, CalendarList, Agenda } from 'react-native-calendars';
import moment from 'moment';
import DateTimePicker from '@react-native-community/datetimepicker';
const { icons } = images
export default function opencalendar(props) {
const { navigation } = props
const [dates, setDate] = useState([])
const [times, setTime] = useState([])
const [showClock, setClock] = useState(false)
const [clockId, setClockId] = useState("")
const [clockDate, setClockDate] = useState("")
const selectDate = (val) => {
let d = [];
d.push(...dates, { date: val.timestamp })
setDate(d)
}
const renderTime = ({ item, index }) => {
return (
<Col style={{ marginRight: 10 }} key={index}>
<Button onPress={() => deleteTime(item)} style={{ backgroundColor: '#888' }}>
<Text>{moment(item.time).format("hh:mm a")} </Text>
<Icon name="close" type="FontAwesome" style={{ fontSize: 15, color: '#fff' }}></Icon>
</Button>
</Col>
)
}
const renderDate = ({ item, index }) => {
return (
<Row key={index} style={{ marginTop: 10, borderBottomColor: '#777', borderBottomWidth: 1, paddingBottom: 20 }}>
<Col style={{ marginRight: 10 }}>
<Button onPress={() => deleteDate(item)} style={{ backgroundColor: '#888' }}><Text>{moment(item.date).toDate().toDateString()}{' '}</Text>
<Icon name="close" type="FontAwesome" style={{ fontSize: 15, color: '#fff' }}></Icon>
</Button>
</Col>
<Col style={{ marginRight: 10 }}>
<Button onPress={() => { setClockDate(item.date); setClockId(index); setClock(true) }}>
<Icon name="clock-o" type="FontAwesome" style={{ fontSize: 15, color: '#fff' }}></Icon>
<Text>{' '}{item.time != null ? moment(item.time).format("hh:mm a") : "Add Time"}</Text>
</Button>
</Col>
</Row>
)
}
const deleteDate = (item) => {
dates.splice(dates.indexOf(item), 1);
let d = [...dates]
setDate(d)
}
const deleteTime = (item) => {
times.splice(times.indexOf(item), 1);
let t = [...times]
setTime(t)
}
const selectTime = (event, selectedDate) => {
console.log(selectedDate)
setClock(false)
if (clockId == "all") {
dates.map(dx => {
dx.time = null;
})
setDate([...dates])
setTime([...times,
{
time: selectedDate
}
])
}
else {
setTime([]);
let d = dates[clockId];
d.time = selectedDate
dates.splice(clockId, 1)
setDate([...dates, d])
}
};
const save = () => {
let ReminderDateTimes = [];
if (times.length == 0) {
let d = dates.filter(dx => {
return dx.time == undefined
})
if (d.length > 0) {
alert("One date doesn't have time please select time!")
return
}
dates.map(dx => {
let x = {
ID: null,
MedicalReminderID: null,
ReminderDate: moment(dx.date).format('yyyy-MM-DD'),
ReminderTime: moment(dx.time).format("HH:mm:ss.sss"),
EntityState: 1
};
ReminderDateTimes.push(x)
})
}
else {
times.map(t => {
dates.forEach((d) => {
let x = {
ID: null,
MedicalReminderID: null,
ReminderDate: moment(d.date).format('yyyy-MM-DD'),
ReminderTime: moment(t.time).format("HH:mm:ss.sss"),
EntityState: 1
};
ReminderDateTimes.push(x)
})
})
}
console.log(ReminderDateTimes);
navigation.navigate("AddNewReminder", { ReminderDateTimes })
}
return (
<Container style={{ padding: 10 }}>
<Content>
<Calendar
onDayPress={selectDate}
/>
<Row>
<Col>
<Button onPress={() => {
if (dates.length > 0) {
setClockDate(dates[0].date)
setClockId("all");
setClock(true);
console.log(clockDate);
}
else {
alert("Select Date First")
}
}}>
<Text>Add Same Time For All Selected Dates</Text>
</Button>
</Col>
</Row>
<Row style={{ marginTop: 10, borderBottomColor: '#777', borderBottomWidth: 1, paddingBottom: 20 }}>
<FlatList
data={times}
renderItem={renderTime}
horizontal={true}
/>
</Row>
<FlatList
data={dates}
renderItem={renderDate}
horizontal={false}
/>
<Row style={{ marginTop: 10, paddingBottom: 20 }}>
<Col >
<Button style={{ backgroundColor: '#aaa' }}><Text style={{ color: '#888' }}>Cancel</Text></Button>
</Col>
<Col >
<Button onPress={save}><Text>Save</Text></Button>
</Col>
</Row>
</Content>
{showClock && (
<DateTimePicker
testID="dateTimePicker"
mode="time"
value={clockDate}
is24Hour={false}
display="default"
onChange={selectTime}
/>
)}
</Container>
)
}
|
///////////////////////////////////////////////////////////////////////////////////////////
/////////////变量定义!////////////////////////////////////////////////////////////////
let xxCon; //供方带值
let Dup_Item;
let VB_cNum;
let VB_cPrice;
let VB_cSumprice;
let addGang = []
let ziGang = []
let addLei = []
let yongtu = []
let pinzhong = []
let pinming = []
let TP_CGORDERST_C_TYPENAME = []
///////////////////////////////////////////////////////////////////////////////////////////
let M2S21addIns;
let M1S11addIns;
let S2S31addIns;
let tabledataS1 = []; //用于接收表格数据源
let tabledataS2 = []; //用于接收表格数据源
let tabledataS3 = []; //用于接收表格数据源
let searchdataM1; //每个查询条件form的数据
let searchdataFormM1; //每个查询条件form的实例
let searchdataM2; //每个查询条件form的数据
let searchdataFormM2; //每个查询条件form的实例
let adddata = {}; //添加按钮需要的数据源
let adddata1 = {}; //添加按钮需要的数据源
let addIns; //增加操作时候的模态框实例
let addIns2
let addIns2_form;
let adddatapac = {};
let adddatapo = {};
let adddatapic = {};
let adddatapla = {};
//设置模态框的属性
if (addIns == null) {
addIns = $('#addmotai ').dxPopup({
'visible': false, //设置属性不可见
height: 300, //设置高度
width: 450, //设置宽度
}).dxPopup('instance');
}
if (addIns2 == null) {
addIns2 = $('#addmotai2').dxPopup({
'visible': false, //设置属性不可见
height: 300, //设置高度
width: 450, //设置宽度
}).dxPopup('instance');
}
let change = ''; //区分增加和修改的状态,1为增加;2为修改
let wanchengzhuangtai = []
let shifoujixu = []
let shenhezhuangtai = []
let tijiaozhuangtai = []
let caigoubumen = []
let caigouyuan = []
let cont_supplier = []; //供应商
let contact_Type = [];//合同类型
let comp_Cludecom = []; //签订公司
let jhdd1 = []; //交货地点
let ysdd1 = []; //验收地点
let qdgs = []
let fenpeizhuangtai = []
let caigouzhuangtai = []
let wuzileixing = []
let shenqingbumen = []
let yudengjifalg = []
let yuefen = []
let supplier = [];
let connum = [];
let goodsname = [];
let goodsname2 = [];
let ordernum = [];
let nian = []
//查询区域数据
let validationGroupName = 'validationGroupName';
//当存在不需要与后台通信的数据框,且需要自行添加的选择框
///////////////////////////////////////////////////////////////////////////////////////////
/////////////$function!////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
$(function () {
start() //调用初始化函数
////////////////////////////////////
//////查询Form属性生成/////////////////)
////////////////////////////////////
//以下为查询form的代码
searchdataFormM1 = $('#searchFormM1').dxForm({
formData: searchdataM1,
////当参数小于三个时为五个,大于等于三时统一乘二
////王晶晶给改为自适应编码
colCountByScreen: {
lg: 4,
md: 4,
sm: 2,
xs: 1,
},
//所有查询条件为一组的代码段
itemType: 'group',
items: [{
dataField: 'cConnum',
label: {
text: '合同号'
},
editorOptions: {
showClearButton: true,
}
// editorType: "dxSelectBox",
// editorOptions: {
// dataSource: connum,
// valueExpr: 'cConnum',
// displayExpr: 'cConnum',
// showClearButton: true,
// width: '100%',
// searchEnabled: true,
// }
},
{
dataField: 'cGoodsname',
label: {
text: '货物名称'
},
editorOptions: {
showClearButton: true,
}
// editorType: "dxSelectBox",
// editorOptions: {
// dataSource: goodsname,
// valueExpr: 'cGoodsname',
// displayExpr: 'cGoodsname',
// showClearButton: true,
// width: '100%',
// searchEnabled: true,
// }
},
// {
// dataField: 'cSpec',
// label: {
// text: '规格型号'
// },
// editorOptions: {
// showClearButton: true,
// }
// },
{
dataField: 'cSw10',
label: {
text: '采购员'
},
editorType: 'dxSelectBox',
editorOptions: {
//以上完成对没有联动数据源配置
//以下处理是否存在联动,联动的条件是当前字段的ajax字符串后缀为0时候,代表不因其他调节变化自身的值
dataSource: caigouyuan,
valueExpr: 'cSubitemid',
displayExpr: 'cSubitemdes',
searchEnable: true,
showClearButton: true,
}
},
{
dataField: 'cRemark',
label: {
text: '特殊合同'
},
editorOptions: {
showClearButton: true,
}
// editorType: "dxSelectBox",
// editorOptions: {
// dataSource: connum,
// valueExpr: 'cConnum',
// displayExpr: 'cConnum',
// showClearButton: true,
// width: '100%',
// searchEnabled: true,
// }
},
]
}).dxForm('instance')
//完成对查询条件的自动生成
//以下为查询form的代码
searchdataFormM2 = $('#searchFormM2').dxForm({
formData: searchdataM2,
////当参数小于三个时为五个,大于等于三时统一乘二
////王晶晶给改为自适应编码
colCountByScreen: {
lg: 4,
md: 4,
sm: 2,
xs: 1,
},
//所有查询条件为一组的代码段
itemType: 'group',
items: [
// {
// dataField: 'year',
// label: {
// text: '年'
// },
// editorType: 'dxSelectBox',
// editorOptions: {
// //以上完成对没有联动数据源配置
// //以下处理是否存在联动,联动的条件是当前字段的ajax字符串后缀为0时候,代表不因其他调节变化自身的值
// dataSource: nian,
// valueExpr: 'cSubitemid',
// displayExpr: 'cSubitemdes',
// searchEnable: true,
// showClearButton: true,
// }
// },
// {
// dataField: 'month',
// label: {
// text: '月份'
// },
// editorType: 'dxSelectBox',
// editorOptions: {
// //以上完成对没有联动数据源配置
// //以下处理是否存在联动,联动的条件是当前字段的ajax字符串后缀为0时候,代表不因其他调节变化自身的值
// dataSource: yuefen,
// valueExpr: 'cSubitemid',
// displayExpr: 'cSubitemdes',
// searchEnable: true,
// showClearButton: true,
// }
// },
{
dataField: 'startTime',
label: {
text: '开始时间'
},
editorType: "dxDateBox",
editorOptions: {
width: "100%",
type: "date",
displayFormat: 'yyyy-MM-dd',
value: new Date(),
},
},
{
dataField: 'endTime',
label: {
text: '结束时间'
},
editorType: "dxDateBox",
editorOptions: {
width: "100%",
type: "date",
displayFormat: 'yyyy-MM-dd',
value: new Date(),
},
},
{
dataField: 'cGoodsname',
label: {
text: '货物名称'
},
editorOptions: {
showClearButton: true,
}
// editorType: "dxSelectBox",
// editorOptions: {
// dataSource: goodsname2,
// valueExpr: 'cGoodsname',
// displayExpr: 'cGoodsname',
// showClearButton: true,
// width: '100%',
// searchEnabled: true,
// }
},
// {
// dataField: 'cSpec',
// label: {
// text: '规格型号'
// },
// editorOptions: {
// showClearButton: true,
// }
// },
// {
// dataField: 'cManapply',
// label: {
// text: '请购人'
// },
// editorOptions: {
// showClearButton: true,
// }
// },
{
dataField: 'cOrdernum',
label: {
text: '请购单号'
},
editorOptions: {
showClearButton: true,
}
// editorType: "dxSelectBox",
// editorOptions: {
// dataSource: ordernum,
// valueExpr: 'cOrdernum',
// displayExpr: 'cOrdernum',
// showClearButton: true,
// width: '100%',
// searchEnabled: true,
// }
},
// {
// dataField: 'cComname',
// label: {
// text: '请购项目'
// },
// editorOptions: {
// showClearButton: true,
// }
// },
//采购员
{
dataField: 'cManor',
label: {
text: '采购员'
},
editorType: 'dxSelectBox',
editorOptions: {
//以上完成对没有联动数据源配置
//以下处理是否存在联动,联动的条件是当前字段的ajax字符串后缀为0时候,代表不因其他调节变化自身的值
dataSource: caigouyuan,
valueExpr: 'cSubitemid',
displayExpr: 'cSubitemdes',
searchEnable: true,
showClearButton: true,
}
},
]
}).dxForm('instance')
//完成对查询条件的自动生成
////////////////////////////////////
//////表格属性生成/////////////////)
////////////////////////////////////
//请购单表
$('#dataGridS1').dxDataGrid({
dataSource: tabledataS1,
columnResizingMode: "widget",
editing: {
mode: 'popup',
//allowUpdating: false
},
columnAutoWidth: true,
showBorders: true,
allowColumnResizing: true,
showColumnLines: true,
showRowLines: true,
onCellHoverChanged: '#888',
hoverStateEnabled: true,
noDataText: '',
//允许脚本编写
height: '100%',
width: '100%',
// scrolling: {
// mode: 'virtual'
// },
selection: {
mode: 'multiple'
},
loadPanel: {
enabled: true
},
paging: {
pageSize: 40,
enabled: true,
},
keyDown: true,
pager: {
// showPageSizeSelector: true,
// allowedPageSizes: [5, 10, 20 , 25 ,30],
showInfo: true,
showNavigationButtons: true
},
columns: [{
dataField: 'cOrdernum',
caption: '请购单号',
},
{
dataField: 'cGoodsname',
caption: '物资名称',
width: 120,
alignment: 'center',
},
{
dataField: 'cMustneed',
caption: '采购类型',
calculateDisplayValue: function (rowData) {
let matchedItem = shifoujixu.find(item => item.cSubitemid == rowData.cMustneed);
if (matchedItem == null || matchedItem == undefined) {
return "";
} else {
return matchedItem.cSubitemdes;
}
}
},
{
dataField: 'cSpec',
caption: '规格型号',
width: 120,
alignment: 'center',
},
{
dataField: 'cUnit',
caption: '单位',
},
{
dataField: 'cPrice',
caption: '单价',
},
{
dataField: 'cNum',
caption: '订购数量',
},
// {
// dataField: 'cOrdept',
// caption: '采购部门',
// calculateDisplayValue: function (rowData) {
// let matchedItem = caigoubumen.find(item => item.cSubitemid == rowData.cOrdept);
// if (matchedItem == null || matchedItem == undefined) {
// return "";
// } else {
// return matchedItem.cSubitemdes;
// }
// }
// },
{
dataField: 'cManor',
caption: '采购人',
calculateDisplayValue: function (rowData) {
let matchedItem = caigouyuan.find(item => item.cSubitemid == rowData.cManor);
if (matchedItem == null || matchedItem == undefined) {
return "";
} else {
return matchedItem.cSubitemdes;
}
}
},
// {
// dataField: 'cPhone',
// caption: '采购人联系方式',
// },
// {
// dataField: 'cCludecom',
// caption: '签订公司',
// },
// {
// dataField: 'cSupplier',
// caption: '供应商',
// },
{
dataField: 'cState',
caption: '预登记状态',
calculateDisplayValue: function (rowData) {
let matchedItem = yudengjifalg.find(item => item.cSubitemid == rowData.cState);
if (matchedItem == null || matchedItem == undefined) {
return "";
} else {
return matchedItem.cSubitemdes;
}
}
},
{
dataField: 'cRemark',
caption: '备注',
},
// {
// dataField: 'cCreater',
// caption: '创建人',
// },
// {
// dataField: 'cCreatetime',
// caption: '创建时间',
// dataType: "date",
// format: "yyyy-MM-dd"
// },
// {
// dataField: 'cModifier',
// caption: '修改人',
// },
// {
// dataField: 'cModifytime',
// caption: '修改时间',
// dataType: "date",
// format: "yyyy-MM-dd"
// },
]
});
//合同表
$('#dataGridS2').dxDataGrid({
dataSource: tabledataS2,
editing: {
mode: 'popup',
//allowUpdating: false
},
// keyExpr: 'ID',
//keyExpr: 'cSw02',
columnAutoWidth: true,
showBorders: true,
allowColumnResizing: true,
showColumnLines: true,
showRowLines: true,
onCellHoverChanged: '#888',
hoverStateEnabled: true,
noDataText: '',
//允许脚本编写
height: '100%',
width: '100%',
// scrolling: {
// mode: 'virtual'
// },
selection: {
mode: 'multiple',
// showCheckBoxesMode:'always'
},
loadPanel: {
enabled: true
},
paging: {
pageSize: 40,
enabled: true,
},
keyDown: true,
pager: {
// showPageSizeSelector: true,
// allowedPageSizes: [5, 10, 20 , 25 ,30],
showInfo: true,
showNavigationButtons: true
},
columns: [{
dataField: 'cConnum',
caption: '合同号',
},
{
dataField: 'cConline',
caption: '合同行号',
},
{
dataField: 'cCludecom',
caption: '签订公司',
calculateDisplayValue: function (rowData) {
let matchedItem = qdgs.find(item => item.cSubitemid == rowData.cCludecom);
if (matchedItem == null || matchedItem == undefined) {
return "";
} else {
return matchedItem.cSubitemdes;
}
}
},
{
dataField: 'cSignplace',
caption: '签订地址',
},
{
dataField: 'cSw09',
caption: '送货点',
width: 100,
},
{
dataField: 'cSupplier',
caption: '供应商',
},
{
dataField: 'cSw03',
caption: '物资名称',
},
{
dataField: 'cRemark',
caption: '备注',
},
{
dataField: 'cConmoney',
caption: '合同金额',
},
{
dataField: 'cPayway',
caption: '付款方式',
},
{
dataField: 'cCludetime',
caption: '签订时间',
dataType: "date",
format: "yyyy-MM-dd"
},
{
dataField: 'cDr',
caption: '预计到货时间',
dataType: "date",
format: "yyyy-MM-dd"
},
],
// onCellClick: function (e) {
// if (e.rowType != 'data') {
// return;
// }
// switch (e.column.dataField) {
// case 'cSw02':
// $('#dataGridS2').dxDataGrid('instance').selectRows(tabledataS2.filter(item=>item.cSw02==e.value));
// break;
// case 'cGoodsname':
// $('#dataGridS2').dxDataGrid('instance').selectRows(tabledataS2.filter(item=>item.cGoodsname==e.value));
// break;
// case 'cManapply':
// $('#dataGridS2').dxDataGrid('instance').selectRows(tabledataS2.filter(item=>item.cManapply==e.value));
// break;
// case 'cSpec':
// $('#dataGridS2').dxDataGrid('instance').selectRows(tabledataS2.filter(item=>item.cSpec==e.value));
// break;
// case 'cComname':
// $('#dataGridS2').dxDataGrid('instance').selectRows(tabledataS2.filter(item=>item.cComname==e.value));
// break;
// case 'cOrdernum':
// $('#dataGridS2').dxDataGrid('instance').selectRows(tabledataS2.filter(item=>item.cOrdernum==e.value));
// break;
// default:
// break;
// }
// }
});
////////////////////////////////////////////////////
////生成按钮层//////////////////////////////////////
////////////////////////////////////////////////////
//合同模块的按钮
$('#operateFormM1S1').dxForm({
width: '100%',
colCount: 16,
items: [{
name: 'M1S11Q',
itemType: 'button',
buttonOptions: {
icon: 'search',
text: '查询',
onClick: function () {
M1S11_serDel();
}
}
},
{
name: 'M1S11S',
itemType: 'button',
buttonOptions: {
icon: 'search',
text: '模拟合同',
onClick: function () {
// let url = "http://10.107.3.254:8877/WebReport/ReportServer?reportlet=HT.cpt&op=write" ; //端口和ip根据具体情况设定
// window.open(url);
// let grid = $('#dataGridS1').dxDataGrid('instance');
// let rowsData = grid.getSelectedRowsData()
// let selectedRowKeys = grid.getSelectedRowKeys()
// if (rowsData.length < 1) {
// // Cake.Ui.Toast.showInfo('请选择一条数据。')
// DevExpress.ui.notify('请先查询一条要转合同的数据。', 'info', 3000);
// return;
// }
addIns2 = $('#addmotai2').dxPopup({
fullScreen: true
}).dxPopup('instance')
addIns2.option('title', '模拟合同');
addIns2.show();
Update_moni();
addIns2_form.option('formData', new Object())
// S1S23addIns.getEditor('cSw10').option('value', rowsData[0].cManor)
/// $('#addForm2').dxForm('instance').getEditor('cCludecom').option('value', '青山控股集团股');
let dataGrid = $('#dataGridS1').dxDataGrid('instance').getSelectedRowsData();
$('#addmoni2').dxDataGrid('instance').option('dataSource', dataGrid);
$('#addmoni2').dxDataGrid('instance').refresh()
}
}
},
{
name: 'M1S11_U',
itemType: 'button',
buttonOptions: {
icon: 'save',
text: '转合同',
onClick: function () {
change = '2'
let grid = $('#dataGridS1').dxDataGrid('instance');
let rowsData = grid.getSelectedRowsData()
let selectedRowKeys = grid.getSelectedRowKeys()
if (rowsData.length < 1) {
// Cake.Ui.Toast.showInfo('请选择一条要修改的数据。')
DevExpress.ui.notify('请先查询一条要转合同的数据。', 'info', 3000);
return;
}
if (selectedRowKeys[0].cState == 1) {
// Cake.Ui.Toast.showInfo('一次只能选择一条要修改的数据。')
DevExpress.ui.notify('该数据已经录入合同,不能再次录入。', 'info', 3000);
return;
}
addIns = $('#addmotai').dxPopup({
//模态框增加name
width: 1000,
height: 450
}).dxPopup('instance')
addIns.option('title', '转合同');
addIns.show();
S1S23_Updatefun()
S1S23addIns.option('formData', new Object())
S1S23addIns.getEditor('cSw10').option('value', rowsData[0].cManor)
// S1S23addIns.getEditor('cGoodsname').option('value', rowsData[0].cGoodsname)
}
}
},
{
name: 'M1S11_ZJHT',
itemType: 'button',
buttonOptions: {
icon: 'save',
text: '追加合同',
onClick: function () {
change = '2'
//请购单
let grid = $('#dataGridS1').dxDataGrid('instance');
let rowsData = grid.getSelectedRowsData()
let selectedRowKeys = grid.getSelectedRowKeys()
//合同
let grid2 = $('#dataGridS2').dxDataGrid('instance');
let rowsData2 = grid2.getSelectedRowsData()
let selectedRowKeys2 = grid2.getSelectedRowKeys()
if (rowsData2.length < 1) {
DevExpress.ui.notify('请选择要追加的合同。', 'info', 3000);
return;
}
if (rowsData.length < 1) {
DevExpress.ui.notify('请选择要追加转合同的请购单。', 'info', 3000);
return;
}
S1S23_ZJHT()
}
}
},
{
name: 'M1S11_SCHTWZ',
itemType: 'button',
buttonOptions: {
icon: 'save',
text: '撤销合同',
onClick: function () {
change = '2'
let grid = $('#dataGridS2').dxDataGrid('instance');
let rowsData = grid.getSelectedRowsData()
let selectedRowKeys = grid.getSelectedRowKeys()
if (rowsData.length < 1) {
DevExpress.ui.notify('请选中要撤销合同的物资。', 'info', 3000);
return;
}
S1S23_SCHTWZ()
}
}
},
{
name: 'M1S11_US',
itemType: 'button',
buttonOptions: {
icon: 'save',
text: '特殊合同',
onClick: function () {
change = '2'
let grid = $('#dataGridS1').dxDataGrid('instance');
let rowsData = grid.getSelectedRowsData()
let selectedRowKeys = grid.getSelectedRowKeys()
if (rowsData.length < 1) {
// Cake.Ui.Toast.showInfo('请选择一条要修改的数据。')
DevExpress.ui.notify('请先查询一条要转合同的数据。', 'info', 3000);
return;
}
if (selectedRowKeys[0].cState == 1) {
// Cake.Ui.Toast.showInfo('一次只能选择一条要修改的数据。')
DevExpress.ui.notify('该数据已经录入合同,不能再次录入。', 'info', 3000);
return;
}
addIns = $('#addmotai').dxPopup({
//模态框增加name
width: 1000,
height: 450
}).dxPopup('instance')
addIns.option('title', '转合同');
addIns.show();
S1S23_UpdateSpecial()
S1S23addIns.option('formData', new Object())
S1S23addIns.getEditor('cSw10').option('value', rowsData[0].cManor)
// S1S23addIns.getEditor('cGoodsname').option('value', rowsData[0].cGoodsname)
}
}
},
]
})
//请购单模块的按钮
$('#operateFormS1S2').dxForm({
width: '100%',
colCount: 16,
items: [{
name: 'M1S11Q',
itemType: 'button',
buttonOptions: {
icon: 'search',
text: '查询',
onClick: function () {
before_serDel();
}
}
}]
})
function Update_moni() {
addIns2_form = $('#addForm2').dxForm({
formData: adddata,
validationGroup: validationGroupName,
colCount: 2,
items: [
// {
// colSpan: 1,
// itemType: 'empty',
// },
{
dataField: 'cOutconnum',
label: {
text: '外贸合同号'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
},
validationRules: [{
type: 'required',
message: '必填!'
},
{
type: 'stringLength',
max: 1000,
min: 0,
message: '长度超限,最长为1000!'
},
]
},
{
dataField: 'cConnum',
label: {
text: '合同编号'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
},
validationRules: [{
type: 'required',
message: '必填!'
},
{
type: 'stringLength',
max: 1000,
min: 0,
message: '长度超限,最长为1000!'
},
]
},
{
dataField: 'cCludecom',
label: {
text: '需方'
},
editorType: 'dxSelectBox',
editorOptions: {
dataSource: comp_Cludecom,
valueExpr: 'cCludecom',
displayExpr: 'cCludecom',
searchEnabled: true,
showClearButton: true,
placeholder: '请选择',
onValueChanged: function (e) {
console.log(e.value)
if (e.value == null || e.value == "") {
$('#textarea').dxForm('instance').option("formData", new Object)
return;
}
msg = {
ver: '53cc62f6122a436083ec083eed1dc03d',
session: '42f5c0d7178148938f4fda29460b815a',
tag: {},
data: {
cCludecom: null
},
};
console.log(777777777)
msg.data.cCludecom = e.value;
console.log(msg.data.cCludecom)
$.ajax({
url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/ZZ_01/getCompInfo'),
dataType: 'json', //返回格式为json
async: true, //请求是否异步,默认为异步,这也是ajax重要特性
data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名
type: 'post', //请求方式 get 或者post ,
contentType: 'application/json',
success: function (data) {
console.log(data.data)
// console.log(data.data[0].cCludecom)
console.log(8888888);
//单位名称
$('#textarea').dxForm('instance').getEditor('cCludecom').option('value', data.data[0].cCludecom);
//单位地址
$('#textarea').dxForm('instance').getEditor('cComaddress').option('value', data.data[0].cComaddress);
//电话
$('#textarea').dxForm('instance').getEditor('cComphone').option('value', data.data[0].cComphone);
//传真
$('#textarea').dxForm('instance').getEditor('cComfaxno').option('value', data.data[0].cComfaxno);
//开户行
$('#textarea').dxForm('instance').getEditor('cCombankname').option('value', data.data[0].cCombankname);
//账号
$('#textarea').dxForm('instance').getEditor('cComaccountno').option('value', data.data[0].cComaccountno);
//税号
$('#textarea').dxForm('instance').getEditor('cComtaxnumber').option('value', data.data[0].cComtaxnumber);
//签订地址
$('#addForm2').dxForm('instance').getEditor('cSignplace').option('value', data.data[0].cSw01);
},
error: function () {
DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000);
cake.Ui.LoadPanel.close();
}
})
}
}
},
{
dataField: 'cCludetime',
label: {
text: '签订时间'
},
editorType: 'dxDateBox',
editorOptions: {
displayFormat: 'yyyy-MM-dd',
type: 'datetime',
},
},
{
dataField: 'cSupplier',
label: {
text: '供方'
},
editorType: 'dxSelectBox',
editorOptions: {
dataSource: cont_supplier,
valueExpr: 'cSupplier',
displayExpr: 'cSupplier',
searchEnabled: true,
showClearButton: true,
placeholder: '请选择',
onValueChanged: function (e) {
if (e.value == null || e.value == "") {
$('#textarea2').dxForm('instance').option("formData", new Object)
return;
}
msg = {
ver: '53cc62f6122a436083ec083eed1dc03d',
session: '42f5c0d7178148938f4fda29460b815a',
tag: {},
data: {
cSupplier: null
},
};
msg.data.cSupplier = e.value;
$.ajax({
url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/DZ_08/getSupplierInfo'),
dataType: 'json', //返回格式为json
async: true, //请求是否异步,默认为异步,这也是ajax重要特性
data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名
type: 'post', //请求方式 get 或者post ,
contentType: 'application/json',
success: function (data) {
console.log(data.data)
//单位名称
$('#textarea2').dxForm('instance').getEditor('cSupplier').option('value', data.data[0].cSupplier);
//单位地址
$('#textarea2').dxForm('instance').getEditor('cSupaddress').option('value', data.data[0].cSupaddress);
//电话
$('#textarea2').dxForm('instance').getEditor('cSupphone').option('value', data.data[0].cSupphone);
//传真
$('#textarea2').dxForm('instance').getEditor('cFaxno').option('value', data.data[0].cFaxno);
//开户行
$('#textarea2').dxForm('instance').getEditor('cBankname').option('value', data.data[0].cBankname);
//账号
$('#textarea2').dxForm('instance').getEditor('cAccountno').option('value', data.data[0].cAccountno);
//税号
$('#textarea2').dxForm('instance').getEditor('cTaxnumber').option('value', data.data[0].cTaxnumber);
},
error: function () {
DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000);
cake.Ui.LoadPanel.close();
}
})
}
},
},
{
dataField: 'cSignplace',
label: {
text: '签订地址'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
readOnly: true,
},
},
]
}).dxForm('instance')
let operateFormS2buts = [
/*{
location: "before",
locateInMenu: 'auto',
widget: "dxButton",
options: {
height: "auto",
width: "auto",
icon: 'plus',
text: '添加',
onClick: function () {
$("#addmoni2").dxDataGrid('instance').addRow();
// console.log($("#addmoni2").dxDataGrid('instance')._options.columns.dataField == 'cPrice')
console.log($("#addmoni2").dxDataGrid('instance')._options.columns)
}
}
},*/
{
location: "before",
locateInMenu: 'auto',
widget: "dxButton",
options: {
height: "auto",
width: "auto",
icon: 'remove',
text: '删除',
onClick: function () {
/*let rowsData = $("#addmoni2").dxDataGrid('instance').getSelectedRowsData()[0];
let rowkey = $("#addmoni2").dxDataGrid('instance')._options.dataSource;
rowkey.splice(rowsData);
$("#addmoni2").dxDataGrid('instance').refresh()*/
let rowsData = $("#addmoni2").dxDataGrid('instance').getSelectedRowsData();
let dataSource = $("#addmoni2").dxDataGrid('instance').option('dataSource');
let removeIndex = [];
for (let index = 0; index < dataSource.length; index++) {
if (rowsData.some(element => element == dataSource[index])) {
removeIndex.push(index);
}
}
removeIndex.reverse().forEach(element => dataSource.splice(element, 1));
$("#addmoni2").dxDataGrid('instance').refresh()
}
}
},
{
location: "before",
locateInMenu: 'auto',
widget: "dxButton",
options: {
height: "auto",
width: "auto",
icon: 'plus',
text: '提交',
onClick: function (e) {
let cconnu = $('#addForm2').dxForm('instance').option('formData').cConnum;
if (cconnu == "" || cconnu == undefined || cconnu == null) {
DevExpress.ui.notify('请填写合同编号。', 'error', 3000);
return
}
msg = {
ver: '53cc62f6122a436083ec083eed1dc03d',
session: '42f5c0d7178148938f4fda29460b815a',
tag: {},
data: {
},
};
//合同主表信息
msg.data.tpCgcontractmt = $('#addForm2').dxForm('instance').option('formData');
//合同物资信息
msg.data.tpCgorderRequest = $('#addmoni2').dxDataGrid('instance')._options.dataSource;
//交货期限 ,交货地点
msg.data.delInformation = $('#deadline').dxForm('instance').option('formData');
// console.log(msg.data.delInformation);
//付款方式
msg.data.paywayRequest = $('#pice').dxForm('instance').option('formData');
// console.log(msg.data.paywayRequest);
//供应商
msg.data.tbSupplier = $('#textarea2').dxForm('instance').option('formData');
//需方
msg.data.tbCludecompany = $('#textarea').dxForm('instance').option('formData');
console.log(JSON.stringify(msg))
$.ajax({
//../../tdhc_cgsys//tab/simContract-------
url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/tab/simContract'),
dataType: 'json', //返回格式为json
async: true, //请求是否异步,默认为异步,这也是ajax重要特性
data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名
type: 'post', //请求方式 get 或者post ,
contentType: 'application/json',
success: function (data) {
let select = data.msg
if (data.errcode == 60) {
DevExpress.ui.notify(select, 'info', 3000);
cake.Ui.LoadPanel.close();
}
if (data.errcode == 0) {
DevExpress.ui.notify(select, 'success', 3000);
cake.Ui.LoadPanel.close();
}
M1S11_serDel();
before_serDel();
addIns2.hide();
},
error: function () {
DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000);
}
})
// }
}
}
},
];
$("#addmoni2").dxDataGrid({
// 要将DataGrid绑定到JSON格式的数据,请将数据的URL分配给dataSource选项。
dataSource: "data/customers.json",
dataSource: addGang,
columnAutoWidth: true,
showBorders: true,
allowColumnResizing: true,
showColumnLines: true,
showRowLines: true,
onCellHoverChanged: '#888',
hoverStateEnabled: true,
noDataText: '',
width: '100%',
height: 300,
paging: {
enabled: false
},
editing: {
mode: "batch",
allowUpdating: true
},
selection: {
mode: "multiple"
// mode: "single"
},
loadPanel: {
enabled: true,
text: '请稍等片刻...'
},
onToolbarPreparing: function (e) {
operateFormS2buts.forEach(item => e.toolbarOptions.items.push(item));
},
onEditingStart: function (e) {},
columns: [{
dataField: 'cOrdernum',
caption: '请购单号',
width: 250,
alignment: 'center',
},
/* {
dataField: 'cId',
caption: '主键',
width: 150,
alignment: 'center',
},*/
{
dataField: 'cGoodsname',
caption: '物资名称',
width: 120,
alignment: 'center',
},
{
dataField: 'cSpec',
caption: '规格型号',
width: 120,
alignment: 'center',
},
{
dataField: 'cCustoms',
caption: '报关物资名称',
width: 120,
alignment: 'center',
},
{
dataField: 'cCuspec',
caption: '报关物资规格',
width: 120,
alignment: 'center',
},
{
dataField: 'cUnit',
caption: '单位',
width: 50,
alignment: 'center',
},
{
dataField: 'cNum',
caption: '订购数量',
width: 60,
alignment: 'center',
setCellValue: function (newData, value, currentRowData) {
newData.cNum = value;
console.log(VB_cPrice);
// 数量
VB_cNum = value;
/* if (VB_cPrice == undefined || VB_cPrice == null){
return VB_cPrice == 0
}else{
VB_cNum = null;
VB_cPrice = null
}*/
var cPrice1 = currentRowData.cPrice;//试用
// // 总价
VB_cSumprice = newData.cNum * cPrice1;
newData.cSumprice = newData.cNum * cPrice1;
}
},
{
dataField: 'cPrice',
caption: '含税单价',
width: 100,
alignment: 'center',
setCellValue: function (newData, value, currentRowData) {
newData.cPrice = value;
// 单价
VB_cPrice = value;
/*if (VB_cNum == undefined || VB_cNum == null) {
return VB_cNum == 0
}else{
VB_cNum = null;
VB_cPrice = null
}*/
var cNum2 = currentRowData.cNum;//试用
console.log(cNum2);
// 总价
VB_cSumprice = newData.cPrice * cNum2;
newData.cSumprice = newData.cPrice * cNum2;
}
},
{
dataField: 'cSumprice',
caption: '含税总价',
width: 100,
alignment: 'center',
// allowEditing: false,
},
{
dataField: 'cRemarkc',
caption: '备注',
alignment: 'center',
width: 200,
},
],
summary: {
// 普通列求和
totalItems: [{
column: 'cSumprice', //计算哪列的值
showInColumn: "cOrdernum", //显示在哪列
displayFormat: "合计人民币:{0}", //显示格式
// valueFormat: "currency",
summaryType: "sum" ,//汇总类型--运算方式
customizeText: function (e) {
console.log(e.value)
return '合 计 人 民 币:'+e.value;
}
}],
},
})
//单条修改
function update_fun() {
msg = {
ver: '53cc62f6122a436083ec083eed1dc03d',
session: '42f5c0d7178148938f4fda29460b815a',
tag: {},
data: {
cgQ003S1s2: {
}
},
};
msg.data.cgQ003S1s2 = Dup_Item;
// 单价修改
if (VB_cPrice == null) {
} else {
msg.data.cgQ003S1s2.cPrice = VB_cPrice;
}
// 总价修改
if (VB_cSumprice == null) {
} else {
msg.data.cgQ003S1s2.cSumprice = VB_cSumprice;
}
$.ajax({
url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/CG_q002/modifyTpCgorderst'),
dataType: 'json', //返回格式为json
async: true, //请求是否异步,默认为异步,这也是ajax重要特性
data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名
type: 'post', //请求方式 get 或者post ,
contentType: 'application/json',
success: function (data) {
console.log(data)
// 修改成功后为全局的变量设置为空
// VB_cPricePer = null;
// VB_cSumprice = null;
// VB_cComno = null;
// VB_cOrdertime = null;
// VB_cDeltime = null;
// VB_cAogtime = null;
// VB_cProvider = null;
// VB_cRemark = null;
// M1S11_serDel()
},
error: function () {
DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000);
}
})
}
// 交货期限、交货地点
$('#deadline').dxForm({
formData: adddatapo,
validationGroup: validationGroupName,
colCount: 1,
items: [{
dataField: 'cDelivdate',
label: {
text: '1.交货期限'
},
editorOptions: {
showClearButton: true,
value: '预付款到账之日起*日内。'
},
},
{
dataField: 'cDelivplace',
label: {
text: '2.交货地点'
},
editorType: 'dxSelectBox',
editorOptions: {
dataSource: jhdd1,
valueExpr: 'cSubitemid',
displayExpr: 'cSubitemdes',
searchEnabled: true,
showClearButton: true,
//以上完成对没有联动数据源配置
//以下处理是否存在联动,联动的条件是当前字段的ajax字符串后缀为0时候,代表不因其他调节变化自身的值
// dataSource: variabl,
// valueExpr: 'id',
// displayExpr: 'value',
// showClearButton: true,
placeholder: '请选择',
},
},
]
}).dxForm('instance');
// 付款方式
$('#pice').dxForm({
formData: adddatapic,
validationGroup: validationGroupName,
colCount: 1,
items: [{
dataField: 'cPayway',
label: {
text: '付款方式'
},
editorOptions: {
//以上完成对没有联动数据源配置
//以下处理是否存在联动,联动的条件是当前字段的ajax字符串后缀为0时候,代表不因其他调节变化自身的值
// dataSource: variabl,
// valueExpr: 'id',
// displayExpr: 'value',
// showClearButton: true,
showClearButton: true
},
}, ]
}).dxForm('instance');
// 验收地点
$('#place').dxForm({
formData: adddatapla,
validationGroup: validationGroupName,
colCount: 1,
items: [{
dataField: 'cSignplace',
label: {
text: '1.验收地点'
},
editorType: 'dxSelectBox',
editorOptions: {
dataSource: ysdd1,
valueExpr: 'cSubitemid',
displayExpr: 'cSubitemdes',
searchEnabled: true,
showClearButton: true,
//以上完成对没有联动数据源配置
//以下处理是否存在联动,联动的条件是当前字段的ajax字符串后缀为0时候,代表不因其他调节变化自身的值
// dataSource: variabl,
// valueExpr: 'id',
// displayExpr: 'value',
// showClearButton: true,
placeholder: '请选择',
},
}, ]
}).dxForm('instance');
$('#textarea').dxForm({
// width: "100%",
// height: "200px",
formData: adddata,
validationGroup: validationGroupName,
colCount: 1,
items: [{
dataField: 'cCludecom',
label: {
text: '单位名称'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
readOnly: true,
// value: '青山控股集团有限公司',
},
},
{
dataField: 'cComaddress',
label: {
text: '单位地址'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
readOnly: true,
// value: '浙江省温州市龙湾区龙祥路2666号',
},
},
{
dataField: '',
label: {
text: '法定代表人(或委托代理人)'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
readOnly: true,
},
},
{
dataField: 'cComphone',
label: {
text: '电话'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
readOnly: true,
// value: '13777770869'
},
},
{
dataField: 'cComfaxno',
label: {
text: '传真'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
},
},
{
dataField: 'cCombankname',
label: {
text: '开户银行'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
readOnly: true,
// value: '华夏银行股份有限公司温州分行龙湾支行'
},
},
{
dataField: 'cComaccountno',
label: {
text: '账号'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
readOnly: true,
// value: '4270 2800 0180 8100 0129 29'
},
},
{
dataField: 'cComtaxnumber',
label: {
text: '税号'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
readOnly: true,
// value: '913 303 007 511 762 26P'
},
},
]
}).dxForm('instance')
// $("#textarea2").dxTextArea({
// width: "580px",
// height: "200px",
// placeholder: "供方...."
// })
$('#textarea2').dxForm({
// width: "100%",
// height: "200px",
formData: adddata,
validationGroup: validationGroupName,
colCount: 1,
items: [{
dataField: 'cSupplier',
label: {
text: '单位名称'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
readOnly: true,
},
},
{
dataField: 'cSupaddress',
label: {
text: '单位地址'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
readOnly: true,
},
},
{
dataField: '',
label: {
text: '法定代表人(或委托代理人)'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
readOnly: true,
},
},
{
dataField: 'cSupphone',
label: {
text: '电话'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
readOnly: true,
},
},
{
dataField: 'cFaxno',
label: {
text: '传真'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
readOnly: true,
},
},
{
dataField: 'cBankname',
label: {
text: '开户银行'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
readOnly: true,
},
},
{
dataField: 'cAccountno',
label: {
text: '账号'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
readOnly: true,
},
},
{
dataField: 'cTaxnumber',
label: {
text: '税号'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
readOnly: true,
},
},
]
}).dxForm('instance')
}
function S1S23_Updatefun() {
S1S23addIns = $('#addForm').dxForm({
formData: adddata,
validationGroup: validationGroupName,
colCount: 3,
items: [{
dataField: 'cConnum',
label: {
text: '合同号'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
},
validationRules: [{
type: 'required',
message: '必填!'
}, ]
},
{
dataField: 'cSw03',
label: {
text: '货物名称'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
},
validationRules: [{
type: 'required',
message: '必填!'
}, ]
},
{
dataField: 'cCludecom',
label: {
text: '签订公司'
},
editorType: 'dxSelectBox',
editorOptions: {
//以上完成对没有联动数据源配置
//以下处理是否存在联动,联动的条件是当前字段的ajax字符串后缀为0时候,代表不因其他调节变化自身的值
dataSource: qdgs,
valueExpr: 'cSubitemid',
displayExpr: 'cSubitemdes',
searchEnable: true,
showClearButton: true,
searchEnabled: true,
},
validationRules: [{
type: 'required',
message: '必填!'
}, ]
},
{
dataField: 'cCludetime',
label: {
text: '签订时间'
},
editorType: 'dxDateBox',
editorOptions: {
displayFormat: 'yyyy-MM-dd',
type: 'datetime',
},
validationRules: [{
type: 'required',
message: '必填!'
}, ]
},
{
dataField: 'cSupplier',
label: {
text: '供应商'
},
/*editorType: "dxSelectBox",
editorOptions: {
dataSource: supplier,
valueExpr: 'cSupplier',
displayExpr: 'cSupplier',
showClearButton: true,
width: '100%',
searchEnabled: true,
},*/
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
},
validationRules: [{
type: 'required',
message: '必填!'
}, ]
},
{
dataField: 'cSw10',
label: {
text: '采购员'
},
editorType: 'dxSelectBox',
editorOptions: {
//以上完成对没有联动数据源配置
//以下处理是否存在联动,联动的条件是当前字段的ajax字符串后缀为0时候,代表不因其他调节变化自身的值
dataSource: caigouyuan,
valueExpr: 'cSubitemid',
displayExpr: 'cSubitemdes',
searchEnable: true,
showClearButton: true,
readOnly: true,
},
},
// {
// dataField: 'cGoodsname',
// label: {
// text: '物资名称'
// },
// editorType: 'dxTextBox',
// editorOptions: {
// searchEnable: true,
// showClearButton: true,
// },
// validationRules: [
// {
// type: 'required',
// message: '必填!'
// },
// ]
// },
{
dataField: 'cConmoney',
label: {
text: '合同金额'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
},
validationRules: [{
type: 'required',
message: '必填!'
},
{
type: 'numeric',
message: '请输入数字',
},
]
},
{
dataField: 'cSw01',
label: {
text: '已付款金额'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
},
validationRules: [{
type: 'required',
message: '必填!'
},
{
type: 'numeric',
message: '请输入数字',
},
]
},
// {
// dataField: 'cSw02',
// label: {
// text: '未付款金额'
// },
// editorType: 'dxTextBox',
// editorOptions: {
// searchEnable: true,
// showClearButton: true,
// },
// validationRules: [
// {
// type: 'required',
// message: '必填!'
// },
// ]
// },
{
dataField: 'cPayway',
label: {
text: '付款方式'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
},
validationRules: [{
type: 'required',
message: '必填!'
}, ]
},
{
dataField: 'cDr',
label: {
text: '预计到货时间'
},
editorType: 'dxDateBox',
editorOptions: {
displayFormat: 'yyyy-MM-dd',
type: 'datetime',
},
// validationRules: [{
// type: 'required',
// message: '必填!'
// }, ]
},
{
dataField: 'cGettime',
label: {
text: '最后到货时间'
},
editorType: 'dxDateBox',
editorOptions: {
displayFormat: 'yyyy-MM-dd',
type: 'datetime',
},
},
{
dataField: 'cSw09',
label: {
text: '送货地点'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
},
validationRules: [
// {
// type: 'required',
// message: '必填!'
// },
]
},
]
}).dxForm('instance')
$('#addsure').dxButton({
text: '确定',
icon: 'todo',
validationGroup: validationGroupName,
onClick: function (e) {
let validateResult = e.validationGroup.validate();
if (!validateResult.isValid) {
DevExpress.ui.notify('数据不符合规范', 'info', 3000);
return;
}
msg = {
ver: '53cc62f6122a436083ec083eed1dc03d',
session: '42f5c0d7178148938f4fda29460b815a',
tag: {},
data: {
},
};
let grid = $('#dataGridS1').dxDataGrid('instance');
let rowsData = grid.getSelectedRowsData()
//模态框的值
msg.data.contractID = S1S23addIns.option('formData');
//选中的值
msg.data.contractVoBean = rowsData;
console.log(JSON.stringify(msg));
cake.Ui.LoadPanel.show();
$.ajax({
url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/tab/saveContractt'),
dataType: 'json', //返回格式为json
async: true, //请求是否异步,默认为异步,这也是ajax重要特性
data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名
type: 'post', //请求方式 get 或者post ,
contentType: 'application/json',
success: function (data) {
////console.log.log(data)
let select = data.msg
if (data.errcode == 60) {
DevExpress.ui.notify(select, 'info', 3000);
cake.Ui.LoadPanel.close();
}
if (data.errcode == 0) {
M1S11_serDel()
before_serDel()
DevExpress.ui.notify(select, 'success', 3000);
addIns.hide()
cake.Ui.LoadPanel.close();
} else {
DevExpress.ui.notify(select, 'success', 3000);
cake.Ui.LoadPanel.close();
M1S11_serDel()
}
},
error: function () {
DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000);
cake.Ui.LoadPanel.close();
// Cake.Ui.Toast.showError('网络或服务器故障,请稍后再试。')
//e.cancel=true;
}
})
// $.ajax({
// url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/tab/saveContract'),
// dataType: 'json', //返回格式为json
// async: true, //请求是否异步,默认为异步,这也是ajax重要特性
// data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名
// type: 'post', //请求方式 get 或者post ,
// contentType: 'application/json',
// success: function (data) {
// ////console.log.log(data)
// let select = data.msg
// if (data.errcode == 60) {
// DevExpress.ui.notify(select, 'info', 3000);
// cake.Ui.LoadPanel.close();
// }
// if (data.errcode == 0) {
// M1S11_serDel()
// before_serDel()
// DevExpress.ui.notify(select, 'success', 3000);
// addIns.hide()
// cake.Ui.LoadPanel.close();
// } else {
// DevExpress.ui.notify(select, 'success', 3000);
// cake.Ui.LoadPanel.close();
// M1S11_serDel()
// }
// },
// error: function () {
// DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000);
// cake.Ui.LoadPanel.close();
// // Cake.Ui.Toast.showError('网络或服务器故障,请稍后再试。')
// //e.cancel=true;
// }
// })
}
})
$('#addcansel').dxButton({
text: '取消',
icon: 'remove',
onClick: function () {
addIns.hide()
}
})
}
//特殊转合同模态框
function S1S23_UpdateSpecial() {
S1S23addIns = $('#addForm').dxForm({
formData: adddata,
validationGroup: validationGroupName,
colCount: 3,
items: [{
dataField: 'cConnum',
label: {
text: '合同号'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
},
/*validationRules: [
{
type: 'required',
message: '必填!'
},
]*/
},
{
dataField: 'cRemark',
label: {
text: '特殊合同'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
},
/*validationRules: [
{
type: 'required',
message: '必填!'
},
]*/
},
{
dataField: 'cSw03',
label: {
text: '货物名称'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
},
// validationRules: [
// {
// type: 'required',
// message: '必填!'
// },
// ]
},
{
dataField: 'cCludecom',
label: {
text: '签订公司'
},
editorType: 'dxSelectBox',
editorOptions: {
//以上完成对没有联动数据源配置
//以下处理是否存在联动,联动的条件是当前字段的ajax字符串后缀为0时候,代表不因其他调节变化自身的值
dataSource: qdgs,
valueExpr: 'cSubitemid',
displayExpr: 'cSubitemdes',
searchEnable: true,
showClearButton: true,
searchEnabled: true,
},
// validationRules: [
// {
// type: 'required',
// message: '必填!'
// },
// ]
},
{
dataField: 'cCludetime',
label: {
text: '签订时间'
},
editorType: 'dxDateBox',
editorOptions: {
displayFormat: 'yyyy-MM-dd',
type: 'datetime',
},
// validationRules: [{
// type: 'required',
// message: '必填!'
// }, ]
},
{
dataField: 'cSupplier',
label: {
text: '供应商'
},
/*editorType: "dxSelectBox",
editorOptions: {
dataSource: supplier,
valueExpr: 'cSupplier',
displayExpr: 'cSupplier',
showClearButton: true,
width: '100%',
searchEnabled: true,
},*/
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
},
validationRules: [{
type: 'required',
message: '必填!'
}, ]
},
{
dataField: 'cSw10',
label: {
text: '采购员'
},
editorType: 'dxSelectBox',
editorOptions: {
//以上完成对没有联动数据源配置
//以下处理是否存在联动,联动的条件是当前字段的ajax字符串后缀为0时候,代表不因其他调节变化自身的值
dataSource: caigouyuan,
valueExpr: 'cSubitemid',
displayExpr: 'cSubitemdes',
searchEnable: true,
showClearButton: true,
readOnly: true,
},
},
// {
// dataField: 'cGoodsname',
// label: {
// text: '物资名称'
// },
// editorType: 'dxTextBox',
// editorOptions: {
// searchEnable: true,
// showClearButton: true,
// },
// validationRules: [
// {
// type: 'required',
// message: '必填!'
// },
// ]
// },
{
dataField: 'cConmoney',
label: {
text: '合同金额'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
},
validationRules: [
// {
// type: 'required',
// message: '必填!'
// },
{
type: 'numeric',
message: '请输入数字',
},
]
},
{
dataField: 'cSw01',
label: {
text: '已付款金额'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
},
validationRules: [
// {
// type: 'required',
// message: '必填!'
// },
{
type: 'numeric',
message: '请输入数字',
},
]
},
{
dataField: 'cPayway',
label: {
text: '付款方式'
},
editorType: 'dxTextBox',
editorOptions: {
searchEnable: true,
showClearButton: true,
},
// validationRules: [
// {
// type: 'required',
// message: '必填!'
// },
// ]
},
{
dataField: 'cDr',
label: {
text: '预计到货时间'
},
editorType: 'dxDateBox',
editorOptions: {
displayFormat: 'yyyy-MM-dd',
type: 'datetime',
},
// validationRules: [{
// type: 'required',
// message: '必填!'
// }, ]
},
{
dataField: 'cGettime',
label: {
text: '最后到货时间'
},
editorType: 'dxDateBox',
editorOptions: {
displayFormat: 'yyyy-MM-dd',
type: 'datetime',
},
},
// {
// dataField: 'cSw09',
// label: {
// text: '送货地点'
// },
// editorType: 'dxTextBox',
// editorOptions: {
// searchEnable: true,
// showClearButton: true,
// },
// validationRules: [
// {
// type: 'required',
// message: '必填!'
// },
// ]
// },
]
}).dxForm('instance')
$('#addsure').dxButton({
text: '确定',
icon: 'todo',
validationGroup: validationGroupName,
onClick: function (e) {
let validateResult = e.validationGroup.validate();
if (!validateResult.isValid) {
DevExpress.ui.notify('数据不符合规范', 'info', 3000);
return;
}
msg = {
ver: '53cc62f6122a436083ec083eed1dc03d',
session: '42f5c0d7178148938f4fda29460b815a',
tag: {},
data: {
},
};
let grid = $('#dataGridS1').dxDataGrid('instance');
let rowsData = grid.getSelectedRowsData()
//模态框的值
msg.data.contractID = S1S23addIns.option('formData');
//选中的值
msg.data.contractVoBean = rowsData;
cake.Ui.LoadPanel.show();
$.ajax({
url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/tab/tSaveContractt'),
dataType: 'json', //返回格式为json
async: true, //请求是否异步,默认为异步,这也是ajax重要特性
data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名
type: 'post', //请求方式 get 或者post ,
contentType: 'application/json',
success: function (data) {
////console.log.log(data)
let select = data.msg
if (data.errcode == 60) {
DevExpress.ui.notify(select, 'info', 3000);
cake.Ui.LoadPanel.close();
}
if (data.errcode == 0) {
M1S11_serDel()
before_serDel()
DevExpress.ui.notify(select, 'success', 3000);
addIns.hide()
cake.Ui.LoadPanel.close();
} else {
DevExpress.ui.notify(select, 'success', 3000);
cake.Ui.LoadPanel.close();
M1S11_serDel()
}
},
error: function () {
DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000);
cake.Ui.LoadPanel.close();
// Cake.Ui.Toast.showError('网络或服务器故障,请稍后再试。')
//e.cancel=true;
}
})
// $.ajax({
// url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/tab/tSaveContract'),
// dataType: 'json', //返回格式为json
// async: true, //请求是否异步,默认为异步,这也是ajax重要特性
// data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名
// type: 'post', //请求方式 get 或者post ,
// contentType: 'application/json',
// success: function (data) {
// ////console.log.log(data)
// let select = data.msg
// if (data.errcode == 60) {
// DevExpress.ui.notify(select, 'info', 3000);
// cake.Ui.LoadPanel.close();
// }
// if (data.errcode == 0) {
// M1S11_serDel()
// before_serDel()
// DevExpress.ui.notify(select, 'success', 3000);
// addIns.hide()
// cake.Ui.LoadPanel.close();
// } else {
// DevExpress.ui.notify(select, 'success', 3000);
// cake.Ui.LoadPanel.close();
// M1S11_serDel()
// }
// },
// error: function () {
// DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000);
// cake.Ui.LoadPanel.close();
// // Cake.Ui.Toast.showError('网络或服务器故障,请稍后再试。')
// //e.cancel=true;
// }
// })
}
})
$('#addcansel').dxButton({
text: '取消',
icon: 'remove',
onClick: function () {
addIns.hide()
}
})
}
///////////////////////////////////////////////////////
//Star()请求下拉框、多选框数据、通过请求网址的后缀生成代码
///////////////////////////////////////////////////////
function start() {
//ajax传参用
msg = {
ver: '53cc62f6122a436083ec083eed1dc03d',
session: '42f5c0d7178148938f4fda29460b815a',
tag: {},
data: {}
};
initLoad1()
function initLoad1() {
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {
"cItemid": "WLLX"
}
};
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/CG_A001/selcon"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
result.data.forEach(item => {
wuzileixing.push(item);
});
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
initLoad2()
function initLoad2() {
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {
"cItemid": "BMMC"
}
};
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/CG_A001/selcon"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
result.data.forEach(item => {
shenqingbumen.push(item);
});
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
initLoad3()
function initLoad3() {
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {
"cItemid": "WCZT"
}
};
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/CG_A001/selcon"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
result.data.forEach(item => {
wanchengzhuangtai.push(item);
});
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
initLoad4()
function initLoad4() {
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {
"cItemid": "JXZT"
}
};
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/CG_A001/selcon"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
result.data.forEach(item => {
shifoujixu.push(item);
});
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
initLoad5()
function initLoad5() {
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {}
};
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/CG_CONMT/NUM"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
if (result.data == null) {
} else {
result.data.forEach(item => {
connum.push(item);
});
}
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
initLoad6()
function initLoad6() {
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {}
};
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/CG_CONMT/SUPPLIER"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
if (result.data == null) {
} else {
result.data.forEach(item => {
supplier.push(item);
});
}
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
initLoad7()
function initLoad7() {
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {
"cItemid": "YF"
}
};
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/CG_A001/selcon"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
result.data.forEach(item => {
yuefen.push(item);
});
var date = new Date();
this.year = date.getFullYear(); //当前年份
this.month = date.getMonth() + 1; //当前月份
var i = date.getMonth();
searchdataFormM2.getEditor('month').option('value', yuefen[i].cSubitemid);
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
initLoad66()
function initLoad66() {
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {
"cItemid": "NF"
}
};
//console.log(9)
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/CG_A001/selcon"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
result.data.forEach(item => {
nian.push(item);
});
//console.log(result)
var date = new Date();
this.year = date.getFullYear(); //当前年份
this.month = date.getMonth() + 1; //当前月份
var i = date.getMonth();
// searchdataFormM2.getEditor('year').option('value', nian[1].cSubitemid);
searchdataFormM2.getEditor('year').option('value', getYear());
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
function getYear(){
var date = new Date();
let year = date.getFullYear();//当前年份
console.log(year);
let matchedItem = nian.find(item => item.cSubitemid == year);
if (matchedItem == null || matchedItem == undefined) {
return "";
} else {
//console.log(matchedItem.cSubitemid)
return matchedItem.cSubitemid;
}
}
initLoad8()
function initLoad8() {
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {
"cItemid": "CGY"
}
};
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/CG_A001/selcon"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
result.data.forEach(item => {
caigouyuan.push(item);
});
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
initLoad9()
function initLoad9() {
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {
"cItemid": "QDGS"
}
};
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/CG_A001/selcon"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
result.data.forEach(item => {
qdgs.push(item);
});
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
initLoad91()
//
function initLoad91() {
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {
"cItemid": "JHDD"
}
};
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/CG_A001/selcon"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
result.data.forEach(item => {
jhdd1.push(item);
});
console.log(jhdd1)
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
initLoad92()
function initLoad92() {
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {
"cItemid": "YSDD"
}
};
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/CG_A001/selcon"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
result.data.forEach(item => {
ysdd1.push(item);
});
console.log(ysdd1)
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
initLoad10()
function initLoad10() {
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {}
};
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/CG_q002mt/ORDERNUM"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
if (result.data == null) {
} else {
result.data.forEach(item => {
ordernum.push(item);
});
}
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
initLoad11()
function initLoad11() {
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {}
};
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/CG_q002/GOODSNAMEQ"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
if (result.data == null) {
} else {
result.data.forEach(item => {
goodsname2.push(item);
});
}
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
initLoad12()
function initLoad12() {
//cake.Ui.LoadPanel.show()
// 初始化加载所有下拉框数据
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {
"cItemid": "YDJZT"
}
};
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/CG_A001/selcon"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
/* ////console.log.log(result.data);
yudengjifalg = result.data; */
result.data.forEach(item => {
yudengjifalg.push(item);
});
// 钢种分类
// globecStlGroup.splice(0, globecStlGroup.length);
// cake.Ui.LoadPanel.close()
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
initLoad13()
function initLoad13() {
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {
}
};
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/DZ_08/findSupplierName"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
console.log(result.data);
xxCon = result.data;
if (result.data == null) {
} else {
result.data.forEach(item => {
cont_supplier.push(item);
});
}
// console.log(cont_supplier);
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
initLoad14()
function initLoad14() {
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {
}
};
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/ZZ_01/findCompInfo"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
console.log(result.data);
xxCon = result.data;
if (result.data == null) {
} else {
result.data.forEach(item => {
comp_Cludecom.push(item);
});
}
// console.log(cont_supplier);
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
initLoad16()
function initLoad16() {
//cake.Ui.LoadPanel.show()
// 初始化加载所有下拉框数据
msg = {
ver: "53cc62f6122a436083ec083eed1dc03d",
session: "42f5c0d7178148938f4fda29460b815a",
tag: {},
data: {
}
};
//../../tdhc_cgsys/CG_A001/selcon
$.ajax({
type: "post",
url: Cake.Piper.getAuthUrl("../../tdhc_cgsys/CGC_11/selectContType"),
data: JSON.stringify(msg),
contentType: "application/json",
dataType: "json",
success: function (result) {
console.log(result.data.cgc11M1s1);
result.data.cgc11M1s1.forEach(item => {
contact_Type.push(item);
});
// 钢种分类
// globecStlGroup.splice(0, globecStlGroup.length);
// cake.Ui.LoadPanel.close()
},
error: function () {
cake.Ui.LoadPanel.close()
}
});
}
$.ajax({
url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/CG_Q001/C0061Q'), //请求的url地址
dataType: 'json', //返回格式为json
async: true, //请求是否异步,默认为异步,这也是ajax重要特性
data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名
type: 'post', //请求方式 get 或者post ,
contentType: 'application/json',
success: function (data) {
TP_CGORDERST_C_TYPENAME.splice(0, TP_CGORDERST_C_TYPENAME.length);
data.data.cgQ001C006.forEach(item => TP_CGORDERST_C_TYPENAME.push(item));
// $('#this-grid-container1').dxDataGrid('instance').refresh()
},
error: function () {
DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000);
// Cake.Ui.Toast.showError('网络或服务器故障,请稍后再试。')
//e.cancel=true;
}
})
////////////////////////////////////////////////////////////////////////////////
//寻找查询条件的所有字段,带有后缀请求的,并且尾号为零的,所有下来框的循环生成,
////////////////////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//功能类代码(与button生成代码对应) /////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
// function get_month () {
// var date = new Date();
// this.year = date.getFullYear();//当前年份
// this.month = date.getMonth() + 1;//当前月份
// var i = this.month-1
// let matchedItem1 = yuefen.find(item => item.month != "");
// let matchedItem = yuefen.find(item => item.cSubitemdes == yuefen[0].cSubitemdes);
// if (matchedItem == null || matchedItem == undefined) {
// return "";
// } else {
// return matchedItem.cSubitemid;
// //console.log.log(matchedItem.cSubitemid)
// }
// }
//获取当前月份的天数
function mGetDate(month) {
var date = new Date();
var year = date.getFullYear();
var d = new Date(year, month, 0);
return d.getDate();
}
function before_serDel() {
msg = {
ver: '53cc62f6122a436083ec083eed1dc03d',
session: '42f5c0d7178148938f4fda29460b815a',
tag: {},
data: {}
};
let searchtiao = searchdataFormM2.option('formData')
msg.data.tpCgorderst = [searchdataFormM2.option('formData')];
// var date = new Date();
// this.year = date.getFullYear();
// this.month = date.getMonth() + 1;
// //选择的月份
// var m = msg.data.tpCgorderst[0].month;
// var y = msg.data.tpCgorderst[0].year;
// //获取当前月份的天数
// var days = mGetDate(m); //选择月份的天数
// //console.log.log(days+"天")
// if (m != null) {
// //开始时间
// let startTime = msg.data.tpCgorderst.startTime;
// msg.data.tpCgorderst[0].startTime = new Date(y, m - 1, 1, 0, 0, 0, 0);
// // 结束时间
// let endTime = msg.data.tpCgorderst.endTime;
// msg.data.tpCgorderst[0].endTime = new Date(y, m - 1, days, 23, 59, 59, 999);
// } else {
// //开始时间
// let startTime = msg.data.tpCgorderst.startTime;
// msg.data.tpCgorderst[0].startTime = null;
// // 结束时间
// let endTime = msg.data.tpCgorderst.endTime;
// msg.data.tpCgorderst[0].endTime = null;
// }
//开始时间
let startTime = searchtiao.startTime;
msg.data.tpCgorderst[0].startTime = new Date(startTime.getFullYear(), startTime.getMonth(), startTime.getDate(), 0, 0, 0, 0);
// 结束时间
let endTime = searchtiao.endTime;
msg.data.tpCgorderst[0].endTime = new Date(endTime.getFullYear(), endTime.getMonth(), endTime.getDate(), 23, 59, 59, 999);
console.log(msg.data.tpCgorderst)
$.ajax({
url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/CG_q002/before_serDel'),
dataType: 'json', //返回格式为json
async: true, //请求是否异步,默认为异步,这也是ajax重要特性
data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名
type: 'post', //请求方式 get 或者post ,
contentType: 'application/json',
success: function (data) {
let msgstr = data.msg;
if (data.errcode == 60) {
DevExpress.ui.notify(msgstr, 'info', 3000);
}
////console.log.log(data)
if (data.data == null) {
tabledataS1.splice(0, tabledataS1.length);
$('#dataGridS1').dxDataGrid('instance').option('dataSource', tabledataS1)
return
}
let select;
select = data.data
tabledataS1.splice(0, tabledataS1.length);
select.forEach(item => tabledataS1.push(item));
$('#dataGridS1').dxDataGrid('instance').option('dataSource', tabledataS1)
$('#dataGridS1').dxDataGrid('instance').deselectAll()
$('#dataGridS1').dxDataGrid('instance').refresh()
},
error: function () {
DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000);
// Cake.Ui.Toast.showError('网络或服务器故障,请稍后再试。')
//e.cancel=true;
}
})
}
function S1S23_ZJHT() {
msg = {
ver: '53cc62f6122a436083ec083eed1dc03d',
session: '42f5c0d7178148938f4fda29460b815a',
tag: {},
data: {}
};
//请购单
let grid = $('#dataGridS1').dxDataGrid('instance');
let rowsData = grid.getSelectedRowsData()
//合同
let grid2 = $('#dataGridS2').dxDataGrid('instance');
let rowsData2 = grid2.getSelectedRowsData()
msg.data.orderList = rowsData; //请购单
msg.data.conList = rowsData2; //合同
////console.log.log(msg)
$.ajax({
url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/CG_CONMTT/ZJHT'),
dataType: 'json', //返回格式为json
async: true, //请求是否异步,默认为异步,这也是ajax重要特性
data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名
type: 'post', //请求方式 get 或者post ,
contentType: 'application/json',
success: function (data) {
////console.log.log(data)
let select = data.msg
if (data.errcode == 0) {
M1S11_serDel()
before_serDel()
DevExpress.ui.notify(select, 'success', 3000);
} else {
DevExpress.ui.notify(select, 'success', 3000);
M1S11_serDel()
}
},
error: function () {
DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000);
// Cake.Ui.Toast.showError('网络或服务器故障,请稍后再试。')
//e.cancel=true;
}
})
// $.ajax({
// url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/CG_CONMT/ZJHT'),
// dataType: 'json', //返回格式为json
// async: true, //请求是否异步,默认为异步,这也是ajax重要特性
// data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名
// type: 'post', //请求方式 get 或者post ,
// contentType: 'application/json',
// success: function (data) {
// ////console.log.log(data)
// let select = data.msg
// if (data.errcode == 0) {
// M1S11_serDel()
// before_serDel()
// DevExpress.ui.notify(select, 'success', 3000);
// } else {
// DevExpress.ui.notify(select, 'success', 3000);
// M1S11_serDel()
// }
// },
// error: function () {
// DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000);
// // Cake.Ui.Toast.showError('网络或服务器故障,请稍后再试。')
// //e.cancel=true;
// }
// })
}
function S1S23_SCHTWZ() {
msg = {
ver: '53cc62f6122a436083ec083eed1dc03d',
session: '42f5c0d7178148938f4fda29460b815a',
tag: {},
data: {}
};
//合同
let grid2 = $('#dataGridS2').dxDataGrid('instance');
let rowsData2 = grid2.getSelectedRowsData()
msg.data.conList = rowsData2; //合同
$.ajax({
url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/CG_CONMTT/SCHTWZ'),
dataType: 'json', //返回格式为json
async: true, //请求是否异步,默认为异步,这也是ajax重要特性
data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名
type: 'post', //请求方式 get 或者post ,
contentType: 'application/json',
success: function (data) {
//console.log.log(data)
let select = data.msg
if (data.errcode == 0) {
M1S11_serDel();
before_serDel()
DevExpress.ui.notify(select, 'success', 3000);
} else {
DevExpress.ui.notify(select, 'success', 3000);
M1S11_serDel()
}
},
error: function () {
DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000);
}
})
// $.ajax({
// url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/CG_CONMT/SCHTWZ'),
// dataType: 'json', //返回格式为json
// async: true, //请求是否异步,默认为异步,这也是ajax重要特性
// data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名
// type: 'post', //请求方式 get 或者post ,
// contentType: 'application/json',
// success: function (data) {
// //console.log.log(data)
// let select = data.msg
// if (data.errcode == 0) {
// M1S11_serDel();
// before_serDel()
// DevExpress.ui.notify(select, 'success', 3000);
// } else {
// DevExpress.ui.notify(select, 'success', 3000);
// M1S11_serDel()
// }
// },
// error: function () {
// DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000);
// }
// })
}
function S1S21_Selected() {
}
function M1S11_serDel() {
msg = {
ver: '53cc62f6122a436083ec083eed1dc03d',
session: '42f5c0d7178148938f4fda29460b815a',
tag: {},
data: {}
};
let searchtiao = searchdataFormM1.option('formData')
msg.data = searchdataFormM1.option('formData');
// //开始时间
// let startTime = msg.data.startTime;
// msg.data.startTime = new Date(startTime.getFullYear(), startTime.getMonth(), startTime.getDate(), 0, 0, 0, 0);
// // 结束时间
// let endTime = msg.data.endTime;
// msg.data.endTime = new Date(endTime.getFullYear(), endTime.getMonth(), endTime.getDate(), 23, 59, 59, 999);
////console.log.log(msg)
$.ajax({
url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/CG_CONMT/selectByMTSTT'),
dataType: 'json', //返回格式为json
async: true, //请求是否异步,默认为异步,这也是ajax重要特性
data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名
type: 'post', //请求方式 get 或者post ,
contentType: 'application/json',
success: function (data) {
console.log(data)
let msgstr = data.msg;
if (data.errcode == 20) {
DevExpress.ui.notify(msgstr, 'info', 3000);
}
if (data.data == null) {
tabledataS2.splice(0, tabledataS2.length);
$('#dataGridS2').dxDataGrid('instance').option('dataSource', tabledataS2)
return
}
let select;
select = data.data
tabledataS2.splice(0, tabledataS2.length);
select.forEach(item => tabledataS2.push(item));
$('#dataGridS2').dxDataGrid('instance').option('dataSource', tabledataS2)
$('#dataGridS2').dxDataGrid('instance').deselectAll()
$('#dataGridS2').dxDataGrid('instance').refresh()
},
error: function () {
DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000);
// Cake.Ui.Toast.showError('网络或服务器故障,请稍后再试。')
//e.cancel=true;
}
})
}
// ------------------------------------------
// 添加模态框
noticeEditPopup = $("#notice-edit-popup-container").dxPopup({
deferRendering: false,
title: '预登记',
// width: function () {
// return window.innerWidth - 50;
// },
// height: function () {
// return window.innerHeight - 50;
// },
width: 1000,
height: 500,
}).dxPopup("instance");
// 添加模态框放置的内容
noticeEditForm = $("#notice-edit-form-container").dxForm({
items: [{
itemType: "group",
colCount: 3,
items: [{
dataField: "cSupplier",
label: {
text: '供应商'
},
validationRules: [{
type: 'required',
message: '必填!'
}, ]
},
{
dataField: "cCludecom",
label: {
text: '签订公司'
},
validationRules: [{
type: 'required',
message: '必填!'
}, ]
},
{
itemType: "group",
colCount: 6,
items: [{
colSpan: 2,
itemType: "empty",
},
{
itemType: "button",
buttonOptions: {
icon: "todo",
text: '确定',
onClick: function (e) {
let validateResult = e.validationGroup.validate();
if (!validateResult.isValid) {
DevExpress.ui.notify('数据不符合规范', 'info', 3000);
return;
}
msg = {
ver: '53cc62f6122a436083ec083eed1dc03d',
session: '42f5c0d7178148938f4fda29460b815a',
tag: {},
data: {},
};
let grid = $("#dataGridS1").dxDataGrid("instance");
let rowsData = grid.getSelectedRowsData();
////console.log.log(msg)
if (rowsData.length < 1) {
cake.Ui.toast.show("请至少选择一条数据", "warning")
return
}
msg.data.tpCgorderst = rowsData;
msg.data.tpCgorderbefore = noticeEditForm.option('formData');
////console.log.log(msg)
// 注释1 zsq
//change等于1为添加
$.ajax({
url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/tab/save'),
dataType: 'json', //返回格式为json
async: true, //请求是否异步,默认为异步,这也是ajax重要特性
data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名
type: 'post', //请求方式 get 或者post ,
contentType: 'application/json',
success: function (data) {
let select = data.msg
if (data.errcode == 0) {
before_serDel();
M1S11_serDel();
DevExpress.ui.notify('数据保存成功', 'success', 3000);
noticeEditPopup.hide();
} else {
DevExpress.ui.notify(select, 'warning', 3000);
}
},
error: function () {
DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000);
// Cake.Ui.Toast.showError('网络或服务器故障,请稍后再试。')
//e.cancel=true;
}
})
// noticeEditForm.option("formData", new Object);
}
}
}, {
itemType: "button",
buttonOptions: {
icon: "remove",
text: '取消',
onClick: function () {
noticeEditPopup.hide();
}
}
},
]
}
]
}]
}).dxForm("instance");
// -------------------
//--------------------// 添加--主表--模态框
addEditPopup = $("#add-edit-popup-container").dxPopup({
deferRendering: false,
height: 600,
}).dxPopup("instance");
// 添加--钢种--模态框放置的内容
addEditForm = $("#add-edit-form-container").dxForm({
formData: msg.data,
width: "100%",
items: [{
itemType: "group",
colCount: 3,
items: [{
dataField: "cOrdernum",
label: {
text: "单据编号"
},
editorType: "dxTextBox",
editorOptions: {
// dataSource: addLei,
// displayExpr: "cSubitemdes", //显示表达式
// valueExpr: "cSubitemid", //值的表达式
// placeholder: "-请选择-",
// showClearButton: true,
// width: "100%",
// searchEnabled: true
width: "100%",
placeholder: "",
showClearButton: true
}
},
]
}, {
itemType: "group",
colCount: 6,
items: [{
itemType: "group",
colCount: 6,
itemType: "button",
buttonOptions: {
icon: "search",
text: '查询',
onClick: function () {
// 重赋值
msg1 = {
ver: '53cc62f6122a436083ec083eed1dc03d',
session: '42f5c0d7178148938f4fda29460b815a',
tag: {},
data: {}
};
msg1.data = addEditForm.option("formData");
//console.log.log(msg)
$.ajax({
// url: Cake.Piper.getAuthUrl(requestUrls.addGSteel),
url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/CG_q002mt/SelectMt12'),
dataType: "json", //返回格式为json
async: true, //请求是否异步,默认为异步,这也是ajax重要特性
data: JSON.stringify(msg1), //下拉框的参数值 requestData.getSteel 上面有定义
type: "post", //请求方式 get 或者post ,
contentType: "application/json", //内容类型,一般是指网页中存在的Content-Type,用于定义网络文件的类型和网页的编码,决定浏览器将以什么形式、什么编码读取这个文件,这就是经常看到一些Asp网页点击的结果却是下载到的一个文件或一张图片的原因。
success: function (result) {
// 表格数据
var tab = result.data
// 清空数据
addGang.splice(0, addGang.length);
// 将返回的数据推入到清空的数组中
tab.forEach(item => {
addGang.push(item);
});
// 将推入进的数据进行刷新
let newgrid = $("#addGangGrid").dxDataGrid("instance");
newgrid.refresh();
// noticeEditForm.getEditor('cProdKind').option("dataSource", pinzhong)
},
})
}
}
}, {
itemType: "group",
colCount: 6,
items: [{
colSpan: 2,
itemType: "empty",
},
{
itemType: "button",
buttonOptions: {
icon: "todo",
text: '确定',
onClick: function () {
let grid = $("#addGangGrid").dxDataGrid("instance");
let rowsData = grid.getSelectedRowsData()[0];
let selectedRowKeys = grid.getSelectedRowKeys()
// ////console.log.log(selectedRowKeys)
if (rowsData.length < 1) {
cake.Ui.toast.show("请至少选择一条数据", "warning")
return
}
noticeEditForm.updateData("cOrmtid", rowsData.cId)
// 带出单据编号到添加弹框
noticeEditForm.updateData("cOrdernum", rowsData.cOrdernum)
// 带出申请时间到添加弹框
noticeEditForm.updateData("cTimeapply", rowsData.cTimeapply)
// 带出申请部门到添加弹框
noticeEditForm.updateData("cDeptapply", rowsData.cDeptapply)
// 带出公司名称添加弹框
noticeEditForm.updateData("cComname", rowsData.cComname)
// // 带出收单日期添加弹框
noticeEditForm.updateData("cTimetake", rowsData.cTimetake)
// // 带出申请人到添加弹框
noticeEditForm.updateData("cManapply", rowsData.cManapply)
// // 带出审核状态到添加弹框
noticeEditForm.updateData("cAudittype", rowsData.cAudittype)
// // 带出审核时间到添加弹框
noticeEditForm.updateData("cAudittime", rowsData.cAudittime)
// // 带出审核人到添加弹框
noticeEditForm.updateData("cAuditman", rowsData.cAuditman)
// // 带出提交人到添加弹框
noticeEditForm.updateData("cMitman", rowsData.cMitman)
// // 带出提交时间到添加弹框
noticeEditForm.updateData("cMittime", rowsData.cMittime)
// // 带出提交状态到添加弹框
noticeEditForm.updateData("cMittype", rowsData.cMittype)
// getmidu(rowsData.cStlGrd)
// if (!addEditPopup.validate().isValid) {
// return;
// };
addEditPopup.hide();
}
}
}, {
itemType: "button",
buttonOptions: {
icon: "remove",
text: '取消',
onClick: function () {
addEditPopup.hide();
}
}
}
]
}, ]
},
{
itemType: "group",
items: [{
template: $("#addGangGrid")
},
]
},
]
}).dxForm('instance')
//--------------------// 添加--子表--模态框
ziEditPopup = $("#zi-edit-popup-container").dxPopup({
deferRendering: false,
height: 600,
}).dxPopup("instance");
// 添加--钢种--模态框放置的内容
ziEditForm = $("#zi-edit-form-container").dxForm({
formData: msg.data,
width: "100%",
items: [{
itemType: "group",
colCount: 3,
items: [{
dataField: "cTypename",
label: {
text: "物资类型"
},
editorType: "dxSelectBox",
editorOptions: {
dataSource: TP_CGORDERST_C_TYPENAME,
displayExpr: "cSubitemdes", //显示表达式
valueExpr: "cSubitemid", //值的表达式
placeholder: "-请选择-",
showClearButton: true,
width: "100%",
searchEnabled: true
// width: "100%",
// placeholder: "",
// showClearButton: true
},
},
{
dataField: "cId",
label: {
text: "物资单号"
},
editorType: "dxTextBox",
editorOptions: {
// dataSource: addLei,
// displayExpr: "cSubitemdes", //显示表达式
// valueExpr: "cSubitemid", //值的表达式
// placeholder: "-请选择-",
// showClearButton: true,
// width: "100%",
// searchEnabled: true
width: "100%",
// placeholder: "请选择",
showClearButton: true
}
},
{
dataField: "cGoodsname",
label: {
text: "物资名称"
},
editorType: "dxTextBox",
editorOptions: {
// dataSource: addLei,
// displayExpr: "cSubitemdes", //显示表达式
// valueExpr: "cSubitemid", //值的表达式
// placeholder: "-请选择-",
// showClearButton: true,
// width: "100%",
// searchEnabled: true
width: "100%",
// placeholder: "",
showClearButton: true
}
},
{
dataField: "cMtid",
label: {
text: "请购单号"
},
editorType: "dxTextBox",
editorOptions: {
// dataSource: addLei,
// displayExpr: "cSubitemdes", //显示表达式
// valueExpr: "cSubitemid", //值的表达式
// placeholder: "-请选择-",
// showClearButton: true,
// width: "100%",
// searchEnabled: true
width: "100%",
// placeholder: "",
showClearButton: true
}
},
]
}, {
itemType: "group",
colCount: 6,
items: [{
itemType: "group",
colCount: 6,
itemType: "button",
buttonOptions: {
icon: "search",
text: '查询',
onClick: function () {
// 重赋值
msg = {
ver: '53cc62f6122a436083ec083eed1dc03d',
session: '42f5c0d7178148938f4fda29460b815a',
tag: {},
data: {
// cId:null,
}
};
//脚本执行
// requestData.getSteel.data.cState = $("#selectBox_1").dxSelectBox("instance").option("value");//zsq
// requestData.getSteel.data.date1 = $("#dataBox_1").dxDateBox("instance").option("value");//zsq
// ////console.log.log(addEditForm.option("formData"))
msg.data = ziEditForm.option("formData")
////console.log.log(msg)
$.ajax({
// url: Cake.Piper.getAuthUrl(requestUrls.addGSteel),
url: '../../tdhc_cgsys/CG_q002/selectst',
dataType: "json", //返回格式为json
async: true, //请求是否异步,默认为异步,这也是ajax重要特性
data: JSON.stringify(msg), //下拉框的参数值 requestData.getSteel 上面有定义
type: "post", //请求方式 get 或者post ,
contentType: "application/json", //内容类型,一般是指网页中存在的Content-Type,用于定义网络文件的类型和网页的编码,决定浏览器将以什么形式、什么编码读取这个文件,这就是经常看到一些Asp网页点击的结果却是下载到的一个文件或一张图片的原因。
success: function (result) {
////console.log.log(result)
// 表格数据
var tab = result.data
// 清空数据
ziGang.splice(0, ziGang.length);
// 将返回的数据推入到清空的数组中
tab.forEach(item => {
ziGang.push(item);
});
// 将推入进的数据进行刷新
let newgrid = $("#ziGangGrid").dxDataGrid("instance");
newgrid.refresh();
// noticeEditForm.getEditor('cProdKind').option("dataSource", pinzhong)
},
})
}
}
}, {
itemType: "group",
colCount: 6,
items: [{
colSpan: 2,
itemType: "empty",
},
{
itemType: "button",
buttonOptions: {
icon: "todo",
text: '确定',
onClick: function () {
let grid = $("#ziGangGrid").dxDataGrid("instance");
let rowsData = grid.getSelectedRowsData()[0];
let selectedRowKeys = grid.getSelectedRowKeys()
////console.log.log(selectedRowKeys)
if (rowsData.length < 1) {
cake.Ui.toast.show("请至少选择一条数据", "warning", 3000)
return
}
// 带出钢种到添加弹框
noticeEditForm.updateData("cOrstid", rowsData.cId)
// 带出品名到添加弹框
noticeEditForm.updateData("cGoodsname", rowsData.cGoodsname)
// // 带出是否急需添加弹框
noticeEditForm.updateData("cSw01", rowsData.cSw01)
// // 带出采购人添加弹框
noticeEditForm.updateData("cOrman", rowsData.cManor)
// 带出采购部门添加弹框,
noticeEditForm.updateData("cOrdept", rowsData.cDeptor)
// // 带出"规格型号"添加弹框,
noticeEditForm.updateData("cSpec", rowsData.cSpec)
// // 带出"单位"添加弹框,
noticeEditForm.updateData("cUnit", rowsData.cUnit)
// // 带出"采购人联系方式"添加弹框,
noticeEditForm.updateData("cPhone", rowsData.cPhone)
// getmidu(rowsData.cStlGrd)
// if (!addEditPopup.validate().isValid) {
// return;
// };
ziEditPopup.hide();
}
}
}, {
itemType: "button",
buttonOptions: {
icon: "remove",
text: '取消',
onClick: function () {
ziEditPopup.hide();
}
}
}
]
}, ]
},
{
itemType: "group",
items: [{
template: $("#ziGangGrid")
},
]
},
]
}).dxForm('instance')
$("#addGangGrid").dxDataGrid({
// 要将DataGrid绑定到JSON格式的数据,请将数据的URL分配给dataSource选项。
dataSource: "data/customers.json",
dataSource: addGang,
columnAutoWidth: true,
showBorders: true,
allowColumnResizing: true,
showColumnLines: true,
showRowLines: true,
onCellHoverChanged: '#888',
hoverStateEnabled: true,
noDataText: '',
width: 1200,
height: 350,
paging: {
enabled: false
},
editing: {
mode: "batch",
allowUpdating: false
},
selection: {
mode: "multiple"
},
loadPanel: {
enabled: true,
text: '请稍等片刻...'
},
columns: [{
dataField: 'cId',
caption: '请购单号',
},
{
dataField: 'cComname',
caption: '公司名称',
},
{
dataField: 'cOrdernum',
caption: '单据编号',
},
{
dataField: 'cManapply',
caption: '申请人',
},
{
dataField: 'cDeptapply',
caption: '申请部门',
},
{
dataField: 'cTimeapply',
caption: '申请日期',
},
{
dataField: 'cTimetake',
caption: '收单日期',
},
// {
// dataField: 'cModifier',
// caption: '修改人',
// },
// {
// dataField: 'cModifytime',
// caption: '修改时间',
// },
{
dataField: 'cRemark',
caption: '备注',
},
{
dataField: 'cState',
caption: '状态',
},
// {
// dataField: 'cTimestamp',
// caption: '时间戳',
// },
{
dataField: 'cMittype',
caption: '提交状态',
},
{
dataField: 'cMittime',
caption: '提交时间',
},
// {
// dataField: 'cAudittime',
// caption: '审核时间',
// },
{
dataField: 'cCreatetime',
caption: '创建时间',
},
{
dataField: 'cCreater',
caption: '创建人',
},
{
dataField: 'cAudittype',
caption: '审核状态',
},
{
dataField: 'cAudittime',
caption: '审核时间',
},
{
dataField: 'cAuditman',
caption: '审核人',
},
{
dataField: 'cMitman',
caption: '提交人',
},
]
})
$('#ziGangGrid').dxDataGrid({
dataSource: ziGang,
editing: {
mode: 'popup',
//allowUpdating: false
},
// keyExpr: 'ID',
columnAutoWidth: true,
showBorders: true,
allowColumnResizing: true,
showColumnLines: true,
showRowLines: true,
onCellHoverChanged: '#888',
hoverStateEnabled: true,
noDataText: '',
//允许脚本编写
width: 1200,
height: 450,
paging: {
enabled: false
},
scrolling: {
mode: 'virtual'
},
selection: {
mode: 'multiple'
},
columns: [{
dataField: "cId",
caption: "请购物资单号"
},
{
dataField: "cNo",
caption: "序号"
},
{
dataField: "cMustneed",
caption: "是否急需"
},
{
dataField: "cTypename",
caption: "物资类型"
},
{
dataField: "cGoodsname",
caption: "物资名称"
},
{
dataField: "cSpec",
caption: "规格型号"
},
{
dataField: "cUnit",
caption: "单位"
},
{
dataField: "cNum",
caption: "申报量"
},
{
dataField: "cArrtime",
caption: "要求到货时间"
},
{
dataField: "cCreater",
caption: "创建人"
},
{
dataField: "cCreatetime",
caption: "创建时间"
},
{
dataField: "cModifier",
caption: "修改人"
},
{
dataField: "cModifytime",
caption: "修改时间"
},
{
dataField: "cRemark",
caption: "备注"
},
{
dataField: "cState",
caption: "采购状态"
},
{
dataField: "cDr",
caption: "删除标识"
},
{
dataField: "cTimestamp",
caption: "时间戳"
},
{
dataField: "cSw01",
caption: "提交状态"
},
{
dataField: "cOrdealline",
caption: "采购期限"
},
{
dataField: "cDeptor",
caption: "采购部门"
},
{
dataField: "cManor",
caption: "采购员"
},
{
dataField: "cPhone",
caption: "采购员联系方式"
},
{
dataField: "cAllotstate",
caption: "分配状态"
},
{
dataField: "cAllotman",
caption: "分配人"
},
{
dataField: "cAllottime",
caption: "分配时间"
},
{
dataField: "cPlanor",
caption: "采购进度"
},
{
dataField: "cPolitime",
caption: "报警时间"
},
{
dataField: "cPolinormtime",
caption: "报警标准时间/天"
},
{
dataField: "cMtid",
caption: "请购主表id"
},
{
dataField: "cPlantime",
caption: "采购进度时间"
},
// {
// dataField: "",
// caption: ""
// }
]
});
//Script ------------------------------------
$('#dataGridS1').dxDataGrid({
})
$('#operateFormM1S1').dxForm({
colCount: 16,
})
$('#operateFormM2S2').dxForm({
colCount: 16,
})
}) |
import noteTxt from './note-txt.js'
import noteImg from './note-img.js'
import noteVideo from './note-video.js'
import noteTodos from './note-todos.js'
import { eventBus } from '../../../services/event-bus.js'
export default {
components: {
noteTxt,
noteTodos,
noteImg,
noteVideo
},
props: [],
template: `
<section class="note-add">
<div class="modes-btns-container">
<button title="Note" @click = "cmp = 'noteTxt'">
<i class="far fa-sticky-note"></i>
</button>
<button title="Todo" @click = "cmp = 'noteTodos'">
<i class="fas fa-list"></i>
</button>
<button title="Photo" @click = "cmp = 'noteImg'">
<i class="fas fa-image"></i>
</button>
<button title="Video" @click = "cmp = 'noteVideo'">
<i class="fab fa-youtube"></i>
</button>
</div>
<form @submit.prevent="save">
<component :is="cmp" @setVal="setAns"/>
<button title="Save" class="save-btn">
<i class="fas fa-save"></i>
</button>
</form>
</section>
`,
data() {
return {
note: {
type: '',
isPinned: false,
info: {
title: '',
txt: '',
todos: [],
imgUrl: '',
videoUrl: '',
},
categories: ['notes', 'general:color']
},
cmp: 'noteTxt'
}
},
methods: {
save() {
if (this.note.type === 'noteTodos') this.note.info.todos.pop() //remove last empty line
this.$emit('save', this.note)
eventBus.$emit('cleanInput')
const msg = {
txt: `New note added`,
type: 'success',
action: 'add note',
}
eventBus.$emit('show-msg', msg)
},
setAns(val) {
this.note = JSON.parse(JSON.stringify(val))
},
},
watch: {
'$route.query': {
immediate: true,
handler() {
const query = this.$route.query
if (query.mail) {
this.note.type = 'noteTxt'
this.note.info.title = query.subject
this.note.info.txt = "Sender: " + query.sender + " | " + "To: " + query.to + " | " + query.body
this.save()
this.$router.push('/missKeep')
}
}
}
},
}
|
import React from "react";
export default function Story1() {
return (
<>
<p >
<b id="title">Ruby</b> is a spunky, spirited, bright and beautiful almost 5 year old girl.
She loves fairies, princesses, and everything sparkly. She is a
creative, talented artist, and has a love for dancing, especially
ballet. Ruby loves to sing, and often makes up her own songs as she
paints, cooks, walks and plays. Ruby enjoys cooking and baking with her
mom and taking rides on her scooter with her dad. Most of all, Ruby is a
proud big sister to Jayne.
</p>
</>
);
}
|
import React from 'react';
import axios from 'axios';
import './styles.css';
export default class AdminUpdate extends React.Component {
constructor(props) {
super(props);
this.state = {
conference_detail: [],
approved_details: []
}
}
componentDidMount() {
axios.get('/conference')
.then(response => {
this.setState({ approved_details: response.data.data });
})
}
approve(e, id) {
let status = {
is_approved: true
}
axios.put(`/conference/update-status/${id}`, status)
.then(response => {
alert('Conference status approved!')
window.location.reload();
})
.catch(error => {
console.log(error.message);
alert(error.message)
})
}
reject(e, id) {
let status = {
is_approved: false
}
axios.put(`/conference/update-status/${id}`, status)
.then(response => {
alert('Conference status rejected!')
window.location.reload();
})
.catch(error => {
console.log(error.message);
alert(error.message)
})
}
render() {
return (
<div className="container">
<div className="container">
{this.state.approved_details.length > 0 && this.state.approved_details.map((item, index) => (
<div key={index} className="textStyle">
<div >
<p>Venue : {item.venue}</p>
<p>Dates : {item.venue_dates}</p>
<p>Time : {item.venue_time}</p>
<p>Regstration open : {item.registrationopen_date}</p>
<p>Regstration close : {item.lastregistration_date}</p>
<p>Status : {item.is_approved.toString()}</p>
<div>
<button type="submit" className="button1" onClick={e => this.approve(e, item._id)}>Approve</button>{" "}
<button type="submit" className="button2" onClick={e => this.reject(e, item._id)}>Reject</button>
</div>
</div>
</div>
))}
</div>
</div>
)
}
} |
import { searchAlbums } from "../lib";
global.fetch = require("node-fetch");
const albums = searchAlbums("Incubus");
albums.then(
data =>
data.albums &&
data.albums.items &&
data.albums.items.map(item => console.log(item.name))
);
|
import React, { Component } from 'react'
export default class PersonCard extends Component {
constructor(props){
super(props);
this.state={
new_age: this.props.age
}
}
incAge = () => {
this.setState({new_age: this.state.new_age+1})
}
render() {
const {firstName, lastName, hairColor} = this.props
const {new_age} = this.state
// const {age} = this.props
return (
<div>
<h1>{lastName}, {firstName}</h1>
<p>age: {new_age}</p>
{/* <p>age: {age}</p> */}
<p>Hair Color: {hairColor}</p>
<button onClick={this.incAge}>Birthday Button for {firstName} {lastName}</button>
</div>
)
}
}
|
//start angular module and inject userService
angular.module('blogCtrl', ['blogService'])
.controller('blogController',function(Blog,$scope){
var vm = this;
vm.error = '';
vm.success = false;
vm.inputChange = function(post){
post.metafields.value = post.metafields.value.replace(/ /gi, ',');
};
vm.updateArticle = function(postData){
Blog.update(postData)
.then(function(data){
if(data.data.message){
vm.info = data.data.message;
} else {
postData.metafields.value = data.data.metafield.value;
vm.success = true;
}
setTimeout(function(){
vm.success = false;
vm.info = false;
},5000);
},function(err){
vm.error = err.data.errMessage;
setTimeout(function(){
vm.error = '';
},5000);
});
};
Blog.all()
.then(function(data){
if(data.data.errMessage){
vm.error = data.data.errMessage;
} else {
vm.posts = data.data;
}
});
}); |
import React, { Component } from 'react';
class Chapter extends Component {
render() {
return(
<p>boop</p>
)
}
}
export default Chapter |
/* eslint-disable */
import Vue from 'vue';
import {
mapState
} from 'vuex'
import store from '@/store'
const messenger = {
namespaced: true,
state() {
return {
messenger: 'messenger'
}
},
mutations: {
UPDATESTATE(state, payload) {
state[payload.TOPIC] = payload.value
},
REGISTER(state, payload) {
Vue.set(state, payload.TOPIC, payload.value)
}
},
actions: {},
getters: {}
}
export default {
install(Vue, options = {}) {
// 检测Vuex插件是否安装
if (!Vue._installedPlugins.find(plugin => plugin.Store)) {
throw new Error("To use messenger plugin, you must be installed after the Vuex plugin.")
}
store.registerModule('$_messenger_module', messenger)
// 混合
/* Vue.mixin({
created() {
let $_myOption = this.$options.parent
if ($_myOption === undefined && this.$store) {
this.$store.registerModule('$_messenger_module', messenger)
}
},
}) */
Vue.prototype.$messenger = {
regist(TOPIC, value) {
if (!TOPIC || typeof TOPIC !== 'string' || !TOPIC.trim()) {
throw new Error('请传入需要注册的KEY,且必须为非空string')
}
if (store.state.$_messenger_module[TOPIC]) {
throw new Error(`${TOPIC}已经被注册!`)
}
store.commit('$_messenger_module/REGISTER', {
TOPIC,
value
})
},
publish(TOPIC, value) {
if (!store.state.$_messenger_module.hasOwnProperty(TOPIC)) {
throw new Error(`你还没有注册${TOPIC},请先注册${TOPIC}`)
}
store.commit('$_messenger_module/UPDATESTATE', {
TOPIC,
value
})
},
subscribe() {
console.log('subscribe')
},
unsubscribe() {
console.log('unsubscript')
}
}
}
} |
$(document).ready(() => {
var arr = window.location.search.split('=')
id = arr[arr.length-1];
createChoices()
function createChoices() {
$.get('https://time-synk.herokuapp.com/events/' + id, function(data) {
$('#sentMain').append($('<div>', {class: 'greeting', id: 'greeting'}).text('Please outline your availability across the below times/dates.'))
$('#sentMain').append($('<div>', {class: 'greeting hero', id: 'title'}).text(data.title))
$('#sentMain').append($('<div>', {class: 'greeting', id: 'desctiption'}).text(data.body))
$('#sentMain').append($('<div>', {class: 'voteContainerWhole', id: 'votes'}))
})
.then(() => {
$.get('https://time-synk.herokuapp.com/dates/' + id, function(data) {
console.log(data);
counter = 1
for (i = 0; i < data.length; i++) {
$('#votes').append($('<div>', {class: 'votes voteContianer redColor', id: 'vote' + counter}))
$('#vote' + counter).append($('<div>', {class: 'sendDate vote', id: data[i].id}).text(data[i].date))
$('#vote' + counter).append($('<div>', {class: 'sendStart vote'}).text(data[i].start))
$('#vote' + counter).append($('<div>', {class: 'sendEnd vote'}).text(data[i].end))
counter++
}
})
.then(()=> {
$('#sentMain').append($('<select>'))
$('select').append($('<option>', {id: 'test', text: 'Choose your Name', selected: 'selected'}))
$('#sentMain').append($('<button>', {class: 'sendBackButton', id: 'sendBack'}).text('SEND RESPONSE'))
$.get('https://time-synk.herokuapp.com/events/'+id+'/users', function(data) {
console.log(data);
for (i = 0; i < data.length; i++) {
$('select').append($('<option>', {text: data[i].userName, id: data[i].userID}))
$('select').material_select();
}
})
$('select').material_select();
})
})
}
$(document).on('click', '.sendDate', function() {
console.log('ping');
$(this).parent().toggleClass('greenColor')
})
$(document).on('click', '#sendBack', function() {
if ($('select option:selected').attr('id') === 'test') {
$('#sendBack').text('Please Enter a name')
} else {
var sendObj = {}
$('.votes').each(function() {
$this = $(this)
if ($this.hasClass('greenColor')) {
sendObj.date_id = parseInt($this.find('.sendDate').attr('id'))
sendObj.user_id = parseInt($('select option:selected').attr('id'))
$.post('https://time-synk.herokuapp.com/dates_users', sendObj)
.then((data) => {
console.log('sent');
})
console.log(sendObj);
}
})
$('#sendBack').text('Sent. Thanks.')
$(this).prop('disabled', true)
}
})
})
|
'use strict';
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$exceptionHandler
* @requires $log
*
* @description
* Any uncaught exception in angular expressions is delegated to this service.
* The default implementation simply delegates to `$log.error` which logs it into
* the browser console.
*
* In unit tests, if `angular-mocks.js` is loaded, this service is overriden by
* {@link angular.mock.service.$exceptionHandler mock $exceptionHandler}
*
* @example
*/
var $exceptionHandlerFactory; //reference to be used only in tests
angularServiceInject('$exceptionHandler', $exceptionHandlerFactory = function($log){
return function(e) {
$log.error(e);
};
}, ['$log']);
|
import React from 'react';
import SignupBox from '../comps/Signup';
export default {
title: 'Login Signup/Signup Comps',
};
export const SignupSection = () => (
<SignupBox
LoginPart="Login"
SignupPart="Signup"
UsernamePart="User Name"
FullnamePart="Your Full Name"
YourEmail="Email"
/>
); |
module.exports = function(grunt) {
var config = {};
// Put your JavaScript library dependencies here. e.g. jQuery, underscore,
// etc.
// You'll also have to install them using a command similar to:
// npm install --save jquery
var VENDOR_LIBRARIES = [
"@fortawesome/fontawesome-pro-solid",
"@fortawesome/fontawesome-pro-regular",
"@fortawesome/fontawesome-pro-light",
"@fortawesome/fontawesome-free-brands"
];
config.browserify = {
options: {
browserifyOptions: {
debug: true
}
},
app: {
src: ['js/src/app.js'],
dest: 'js/app.min.js',
options: {
plugin: [
[
'minifyify', {
map: 'app.min.js.map',
output: './js/app.min.js.map'
}
]
],
transform: [
[
'babelify', {
"presets": [
["env", {
"targets": {
"browsers": ["last 2 versions", "ie >= 12"]
}
}]
]
}
]
]
}
},
gallery: {
src: ['js/src/gallery.js'],
dest: 'js/gallery.min.js',
options: {
plugin: [
[
'minifyify', {
map: 'gallery.min.js.map',
output: './js/gallery.min.js.map'
}
]
],
transform: [
[
'babelify', {
"presets": [
["env", {
"targets": {
"browsers": ["last 2 versions", "ie >= 12"]
}
}]
]
}
]
]
}
}
};
// Check if there are vendor libraries and build a vendor bundle if needed
if (VENDOR_LIBRARIES.length) {
config.browserify.app.options = config.browserify.app.options || {};
config.browserify.app.options.exclude = VENDOR_LIBRARIES;
config.browserify.vendor = {
src: [],
dest: 'js/vendor.min.js',
options: {
plugin: [
[
'minifyify', {
map: 'vendor.min.js.map',
output: './js/vendor.min.js.map'
}
],
],
transform: ['rollupify'],
require: VENDOR_LIBRARIES
}
};
}
config.sass = {
options: {
outputStyle: 'compressed',
sourceMap: true,
includePaths: [
'sass/',
'node_modules/lightgallery.js/dist/css/'
]
},
app: {
files: {
'css/base.css': 'sass/base.scss',
'css/styles.css': 'sass/styles.scss',
'css/gallery.css': 'sass/gallery.scss'
}
}
};
config.postcss = {
options: {
map:true,
processors: [
require('autoprefixer')({
browsers: [
'last 2 versions',
'ie >= 12',
'iOS >= 8',
'Safari >= 8'
]
})
]
},
dist: {
src: 'css/*.css'
}
}
config.svgstore = {
options: {
cleanup:true,
cleanupdefs:true
},
min: {
// Target-specific file lists and/or options go here.
src:['img/src/**/*.svg'],
dest:'img/sprite.svg'
},
};
config.watch = {
sass: {
files: ['sass/**/*.scss'],
tasks: ['sass', 'postcss']
},
js: {
files: ['js/src/**/*.js'],
tasks: ['browserify']
},
svg: {
files: ['img/src/**/*.svg'],
tasks: ['svgstore']
}
};
grunt.initConfig(config);
grunt.loadNpmTasks('grunt-svgstore');
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-postcss');
var defaultTasks = [];
defaultTasks.push('svgstore');
defaultTasks.push('sass');
defaultTasks.push('browserify');
defaultTasks.push('postcss');
grunt.registerTask('default', defaultTasks);
};
|
module.exports = function (moneo, mongoosedb) {
// declaration for mongoose Schema
var Schema = mongoosedb.Schema;
// user schema
var BlogpostSchema = new Schema({
id: {
type: Number,
//setting the nodeProperty to true; as this schema property needs to be exported to neo4j graph db
nodeProperty: true
},
title: {
type: String,
//setting the nodeProperty to true; as this schema property needs to be exported to neo4j graph db
nodeProperty: true
},
category: {
type: String,
//setting the nodeProperty to true; as this schema property needs to be exported to neo4j graph db
nodeProperty: true
},
author: {
type: mongoosedb.Schema.Types.ObjectId,
ref: 'User',
//setting the nodeProperty to true; as this schema property needs to be exported to neo4j graph db
nodeProperty: true
}
});
// pushing the data into neo4j graph db
BlogpostSchema.plugin(moneo);
// declaration of mongoose data model
var blogpostmodel = mongoosedb.model('Blogpost', BlogpostSchema);
// running a cypherQuery for the data model this query will fetch all the nodes and return all the nodes.
// blogpostmodel.cypherQuery({ query: 'match (n:Blogpost) return n limit 1' }, function (err, res) {
// console.log("Result of blogpost model " + res);
// });
// blogpostmodel.cypherQuery({ query: 'MATCH (n:Blogpost) WHERE n.category="Fiction" RETURN n' }, function (err, res) {
// var result = res.map(function(item){ return item.n.properties.category }).toString();
// console.log("categories: " + JSON.stringify(result, null, 4));
// // var result2 = result.toString();
// console.log(result);
// });
// data model is returned
return blogpostmodel;
}
|
import React from 'react'
import { View, Text, TouchableOpacity, ImageBackground, Image, Alert } from 'react-native'
import BACKGROUNDCARD from '../../../../assets/background.png'
import LOGO from '../../../../assets/Cópia-de-Tripplanner.png'
import styles from './styles'
const CardTrip = props => {
const { trip, onPress, onLongPres } = props
const imgExist = !!trip.img
return (
<View style={styles.container}>
<TouchableOpacity onLongPress={() => handlerRemoveTrip(onLongPres, trip)} activeOpacity={0.9} onPress={() => onPress(trip)} style={styles.card}>
<ImageBackground imageStyle={{borderRadius: 5}} activeOpacity={0.1} source={imgExist ? {uri: trip.img} : BACKGROUNDCARD} style={styles.card}>
{ checkImg(imgExist, trip, onPress) }
<View style={styles.cardPrice}>
<Text style={styles.price}>R$ {trip.price.toFixed(2)}</Text>
</View>
</ImageBackground>
</TouchableOpacity>
<Text style={styles.nameTrip}>{trip.name}</Text>
</View>
)
}
function handlerRemoveTrip(callback, trip) {
Alert.alert('Atenção', 'Deseja mesmo remover?', [
{text: 'Não'},
{text: 'Sim', onPress: () => callback(trip)},
], {
cancelable: false
})
}
function checkImg(exist, trip, callback) {
if(exist) {
return null
} else {
return (
<Image source={LOGO} resizeMode="contain" style={styles.logo} />
)
}
}
export default CardTrip |
import React from 'react';
import './App.css';
import Post from './Post'
const blogContent = {
title: [
"Dinosaurs are awesome",
],
author: [
"Stealthy Stegosaurus",
],
content: [
"Check out this body property!",
"I can even add more paragraphs and they show up.",
"Look at me go.... I am as cool as a dinosaur."
],
comments: [
"First!",
"T-Rex is the BEST dinosaur!"
]
}
function App() {
return(
<div className="App">
<Post title={blogContent.title} author={blogContent.author} content={blogContent.content} comments={blogContent.comments} />
</div>
)
}
export default App;
|
/*
Localization
*/
module.exports = {
SOCIAL_SIGN: 'Social sign'
} |
import Scene from './app.js';
import mouse from './mouse.js';
import Barba from './barba.js';
import mySwiper from './swiper.js';
const myScene = new Scene(document.querySelectorAll('.background__img'));
myScene.setMySwiper(mySwiper);
new Barba(mySwiper, myScene);
const menuMobile = document.querySelector('.header');
let tobbleMuenu = true;
document.querySelector('.header-mobile__link').addEventListener("click", function(e) {
menuMobile.style.display = tobbleMuenu === false ? "none" : "block";
tobbleMuenu = !tobbleMuenu;
}); |
require('./Global.js')
let Configuration = require('./Configuration.js')
let Processes = require('./Processes')(Configuration.data)
module.exports = new Processes()
|
import { Col, Divider, Row } from 'Components/UI-Library'
import { ROUTER } from 'Constants/CommonConstants'
import React from 'react'
import { Link } from 'react-router-dom'
import './ProductOrder.Style.less'
const ProductOrder = ({ data }) => {
return (
<div className="product-order-wrapper">
{data?.products?.map((item, index) => {
return (
<Row
justify="space-between"
className="product-item"
key={index.toString()}
>
<Col span={12}>
<Row>
<Col span={10}>
<div className="product-image">
<Link to={`${ROUTER.ProductDetail}/${item.id}`}>
<img src={item.image[1]} alt="" />
</Link>
</div>
</Col>
<Col span={14}>
<Link to={`${ROUTER.ProductDetail}/${item.id}`}>
<div className="product-name">{item.name}</div>
</Link>
<div className="product-price">${item.price.toFixed(2)}</div>
<div className="product-color">Color: {item.color}</div>
</Col>
</Row>
</Col>
<Col span={6}>
<Row justify="space-between">
<Col span={12}>x {item.quantity}</Col>
<Col span={12}>${(item.price * item.quantity).toFixed(2)}</Col>
</Row>
</Col>
</Row>
)
})}
<Divider />
<Row justify="end">
<Col span={6}>
<h2 style={{ margin: 0 }}>Total:</h2>
</Col>
<Col>
<h2 style={{ margin: 0 }}>${data.total}</h2>
</Col>
</Row>
<Divider />
</div>
)
}
export default ProductOrder
|
window.onload = function(){
var text = 'This text is only visible if JavaScript files load properly.';
document.getElementById('test-javascript').innerHTML = text;
};
|
define([
'common/collections/user-satisfaction'
],
function (UserSatisfactionCollection) {
describe('UserSatisfactionCollection', function () {
var collection;
describe('parse', function () {
beforeEach(function () {
collection = new UserSatisfactionCollection([], {
valueAttr: 'rating',
min: 1,
max: 5
});
});
it('calculates average scores as a percentage for each entry', function () {
var output = collection.parse({
data: [
{
'rating_1:sum': 1,
'rating_2:sum': 1,
'rating_3:sum': 1,
'rating_4:sum': 1,
'rating_5:sum': 1,
'total:sum': 5
},
{
'rating_1:sum': 1,
'rating_2:sum': 1,
'rating_3:sum': 1,
'rating_4:sum': 1,
'rating_5:sum': 6,
'total:sum': 10
},
{
'rating_1:sum': 6,
'rating_2:sum': 1,
'rating_3:sum': 1,
'rating_4:sum': 1,
'rating_5:sum': 1,
'total:sum': 10
}
]
});
expect(output[0].rating).toEqual(0.5);
expect(output[1].rating).toEqual(0.75);
expect(output[2].rating).toEqual(0.25);
});
it('sets a value of null to unrated periods', function () {
var output = collection.parse({
data: [
{
'rating_1:sum': 0,
'rating_2:sum': 0,
'rating_3:sum': 0,
'rating_4:sum': 0,
'rating_5:sum': 0,
'total:sum': 0
}
]
});
expect(output[0].rating).toEqual(null);
});
it('if trim option is set, removes null elements from start of collection', function () {
collection.options.trim = true;
var output = collection.parse({
data: [
{
'rating_1:sum': 0,
'rating_2:sum': 0,
'rating_3:sum': 0,
'rating_4:sum': 0,
'rating_5:sum': 0,
'total:sum': 0
},
{
'rating_1:sum': 0,
'rating_2:sum': 0,
'rating_3:sum': 0,
'rating_4:sum': 0,
'rating_5:sum': 0,
'total:sum': 0
},
{
'rating_1:sum': 0,
'rating_2:sum': 0,
'rating_3:sum': 0,
'rating_4:sum': 0,
'rating_5:sum': 0,
'total:sum': 0
},
{
'rating_1:sum': 6,
'rating_2:sum': 1,
'rating_3:sum': 1,
'rating_4:sum': 1,
'rating_5:sum': 1,
'total:sum': 10
}
]
});
expect(output.length).toEqual(1);
expect(output[0].rating).toEqual(0.25);
});
it('if trim option is set to a minimum length, removes null elements from start of collection to that length', function () {
collection.options.trim = 2;
var output = collection.parse({
data: [
{
'rating_1:sum': 0,
'rating_2:sum': 0,
'rating_3:sum': 0,
'rating_4:sum': 0,
'rating_5:sum': 0,
'total:sum': 0
},
{
'rating_1:sum': 0,
'rating_2:sum': 0,
'rating_3:sum': 0,
'rating_4:sum': 0,
'rating_5:sum': 0,
'total:sum': 0
},
{
'rating_1:sum': 0,
'rating_2:sum': 0,
'rating_3:sum': 0,
'rating_4:sum': 0,
'rating_5:sum': 0,
'total:sum': 0
},
{
'rating_1:sum': 6,
'rating_2:sum': 1,
'rating_3:sum': 1,
'rating_4:sum': 1,
'rating_5:sum': 1,
'total:sum': 10
}
]
});
expect(output.length).toEqual(2);
expect(output[0].rating).toEqual(null);
expect(output[1].rating).toEqual(0.25);
});
});
describe('mean', function () {
it('calculates a long term average score score for the data set', function () {
collection.reset({
data: [
{
'rating_1:sum': 1,
'rating_2:sum': 1,
'rating_3:sum': 1,
'rating_4:sum': 1,
'rating_5:sum': 1,
'total:sum': 5
},
{
'rating_1:sum': 1,
'rating_2:sum': 1,
'rating_3:sum': 1,
'rating_4:sum': 1,
'rating_5:sum': 6,
'total:sum': 10
},
{
'rating_1:sum': 6,
'rating_2:sum': 1,
'rating_3:sum': 1,
'rating_4:sum': 1,
'rating_5:sum': 1,
'total:sum': 10
}
]
}, { parse: true });
expect(collection.mean('rating')).toEqual(0.5);
});
});
});
}); |
import Route from '@ember/routing/route';
export default Route.extend({
model() {
return [{
isList: true,
x: 1,
y: 0,
width: 1,
height: 1
}, {
isMap: true,
x: 2,
y: 0,
width: 2,
height: 2
}, {
isList: true,
x: 0,
y: 3,
width: 1,
height: 1
}
]
},
actions: {
change(event, items) {
// Here, any changes to the grid items will bubble up.
// console.log(items);
}
}
});
|
const _ = require('lodash')
const moment = require('moment')
const uuid = require('uuid')
const vector = require('../vector')
const Collider = require('../Components/Collider')
const LifeSpan = require('../Components/LifeSpan')
function Arrow({ game, player, input }) {
this.id = uuid.v4()
this.game = game
this.player = player
this.type = 'ARROW'
this.tags = ['PROJECTILE', 'PROJECTILE_PLAYER']
this.sprite = {
name: 'arrow'
}
this.collider = new Collider({ x: 16, y: 32 }, { isFlying: true })
this.collider.with = ['WALL', 'ENEMY']
this.moveSpeed = 800
this.position = vector.create(this.player.position)
this.lifeSpan = new LifeSpan(1)
this.velocity = vector.multiply(vector.direction(this.player.position, input.mouse.position), this.moveSpeed)
}
Arrow.prototype.netInfo = function() {
return {
type: this.type,
id: this.id,
position: this.position,
velocity: this.velocity,
sprite: this.sprite,
}
}
Arrow.prototype.update = function(deltatime) {
if(this.lifeSpan.update(deltatime)) this.game.removeEntity(this)
}
Arrow.prototype.onCollide = function(entity) {
if(entity.tags.indexOf('ENEMY') !== -1) {
entity.dealDamage(10, this.player)
}
this.game.removeEntity(this)
}
module.exports = Arrow
|
import React from 'react';
import About from './About';
import Footer from './Footer';
import NavLinks from './NavLinks';
import Planet from './Planet';
import Quiz from './Quiz';
import ScrollBar from './ScrollBar';
import SpaceImages from './SpaceImages';
import { useAuth } from '../contexts/AuthContext';
const InfoDisplay = ({ selectedPlanet, handleSelected }) => {
const { currentUser } = useAuth();
return (
<div className='info-display-container'>
<div className='content-wrap'>
<h1>Solar System Viewer</h1>
<SpaceImages handleSelected={handleSelected} />
<Planet planet={selectedPlanet} />
</div>
</div>
);
};
export default InfoDisplay;
|
async function getGames() {
const requestGames = await fetch('/api/games');
const gamesData = await requestGames.json();
const data = [];
data.push(gamesData);
console.log(data[0]['data']);
return gamesData;
}
async function NAChart90s() {
const na90sData = await fetch('/api/NAnineties');
const na90sjson = await na90sData.json();
const data=[];
data.push(na90sjson);
console.log(data);
const chart = new CanvasJS.Chart("NAchartContainer", {
animationEnabled: true,
axisX:{
interval: 1,
title: "Genres"
},
axisY:{
title: "Sales (Millions)"
},
data: [{
type: "bar",
name: "companies",
//axisYType: "secondary",
color: "#014D65",
dataPoints: [
{ y: data[0][2]['na_sales'], label: data[0][2]['genre_name'] },
{ y: data[0][1]['na_sales'], label: data[0][1]['genre_name'] },
{ y: data[0][0]['na_sales'], label: data[0][0]['genre_name'] },
]
}]
});
chart.render();
}
async function JPChart90s() {
const jp90sData = await fetch('/api/JPnineties');
const jp90sjson = await jp90sData.json();
const data=[];
data.push(jp90sjson);
console.log(data);
const chart = new CanvasJS.Chart("JPchartContainer", {
animationEnabled: true,
axisX:{
interval: 1,
title: "Genres"
},
axisY:{
title: "Sales (Millions)"
},
data: [{
type: "bar",
name: "companies",
color: "#014D65",
dataPoints: [
{ y: data[0][2]['jp_sales'], label: data[0][2]['genre_name'] },
{ y: data[0][1]['jp_sales'], label: data[0][1]['genre_name'] },
{ y: data[0][0]['jp_sales'], label: data[0][0]['genre_name'] },
]
}]
});
chart.render();
}
function imgfunc90s() {
NAChart90s();
JPChart90s();
}
async function NAChart00s() {
const na00sData = await fetch('/api/NAtwothou');
const na00sjson = await na00sData.json();
const data=[];
data.push(na00sjson);
console.log(data);
const chart = new CanvasJS.Chart("NAchartContainer", {
animationEnabled: true,
axisX:{
interval: 1,
title: "Genres"
},
axisY:{
title: "Sales (Millions)"
},
data: [{
type: "bar",
name: "companies",
color: "#014D65",
dataPoints: [
{ y: data[0][2]['na_sales'], label: data[0][2]['genre_name'] },
{ y: data[0][1]['na_sales'], label: data[0][1]['genre_name'] },
{ y: data[0][0]['na_sales'], label: data[0][0]['genre_name'] },
]
}]
});
chart.render();
}
async function JPChart00s() {
const jp00sData = await fetch('/api/JPtwothou');
const jp00sjson = await jp00sData.json();
const data=[];
data.push(jp00sjson);
console.log(data);
const chart = new CanvasJS.Chart("JPchartContainer", {
animationEnabled: true,
axisX:{
interval: 1,
title: "Genres"
},
axisY:{
title: "Sales (Millions)"
},
data: [{
type: "bar",
name: "companies",
color: "#014D65",
dataPoints: [
{ y: data[0][2]['jp_sales'], label: data[0][2]['genre_name'] },
{ y: data[0][1]['jp_sales'], label: data[0][1]['genre_name'] },
{ y: data[0][0]['jp_sales'], label: data[0][0]['genre_name'] },
]
}]
});
chart.render();
}
function imgfunc00s() {
NAChart00s();
JPChart00s();
}
async function NAChart10s() {
const na10sData = await fetch('/api/NAtwoten');
const na10sjson = await na10sData.json();
const data=[];
data.push(na10sjson);
console.log(data);
const chart = new CanvasJS.Chart("NAchartContainer", {
animationEnabled: true,
axisX:{
interval: 1,
title: "Genres"
},
axisY:{
title: "Sales (Millions)"
},
data: [{
type: "bar",
name: "companies",
//axisYType: "secondary",
color: "#014D65",
dataPoints: [
{ y: data[0][2]['na_sales'], label: data[0][2]['genre_name'] },
{ y: data[0][1]['na_sales'], label: data[0][1]['genre_name'] },
{ y: data[0][0]['na_sales'], label: data[0][0]['genre_name'] },
]
}]
});
chart.render();
}
async function JPChart10s() {
const jp10sData = await fetch('/api/JPtwoten');
const jp10sjson = await jp10sData.json();
const data=[];
data.push(jp10sjson);
console.log(data);
const chart = new CanvasJS.Chart("JPchartContainer", {
animationEnabled: true,
axisX:{
interval: 1,
title: "Genres"
},
axisY:{
title: "Sales (Millions)"
},
data: [{
type: "bar",
name: "companies",
color: "#014D65",
dataPoints: [
{ y: data[0][2]['jp_sales'], label: data[0][2]['genre_name'] },
{ y: data[0][1]['jp_sales'], label: data[0][1]['genre_name'] },
{ y: data[0][0]['jp_sales'], label: data[0][0]['genre_name'] },
]
}]
});
chart.render();
}
function imgfunc10s() {
NAChart10s();
JPChart10s();
}
function naSalestotal(data) {
let na=0;
for (x=0; x< data.length+1; x++) {
na+=data[0][x]['na_sales'];
}
return na;
}
function jpSalestotal(data) {
let jp=0;
for (x=0; x< data.length+1; x++) {
jp+=data[0][x]['jp_sales']
}
return jp;
}
async function allChart() {
const allData = await fetch('/api/games');
const alljson = await allData.json();
const data=[];
data.push(alljson);
const na = naSalestotal(data);
const jp = jpSalestotal(data);
const chart = new CanvasJS.Chart("NAchartContainer", {
animationEnabled: true,
theme: "light2", // "light1", "light2", "dark1", "dark2"
title:{
text: "Regional Market Size"
},
axisY: {
title: "Total Sales (Millions)"
},
data: [{
type: "column",
dataPoints: [
{ y: na, label: "North America" },
{ y: jp, label: "Japan" },
]
}]
});
chart.render();
}
function gamePic() {
const pic = "<img src='/images/gamecontroller.png' alt='A game controller'>"
const jpchart = document.querySelector('#JPchartContainer')
jpchart.innerHTML = pic;
}
function imgfuncall() {
//$("#JPchartContainer").attr("src","..images/gamecontroller.png");
allChart();
gamePic();
}
async function nivoSlider() {
$('#slider').nivoSlider({
effect:'random',
slices:15,
animSpeed:500,
pauseTime:5000
});
}
async function prettyPhoto() {
$("a[rel^='prettyPhoto']").prettyPhoto({animation_speed:'normal', theme:'dark_rounded', social_tools:false, slideshow:false, autoplay_slideshow: false});
$(".image a[rel^='prettyPhoto']").prettyPhoto({animation_speed:'normal', theme:'dark_rounded', social_tools:false, slideshow:false, autoplay_slideshow: false});
}
async function formSub() {
const form = document.querySelector('#contact-form')
const newRec = document.querySelector('#new_record')
//const deleteRec = document.querySelector('#delete_record')
form.addEventListener('submit', async (e) => {
e.preventDefault();
const post = await fetch('/api/developers', {
method: 'POST',
headers: {
'Content-Type':'application/json'
},
body: JSON.stringify({developer_name: newRec.value})
});
});
}
async function upDate() {
const form = document.querySelector('#contact-form2')
const updateRec = document.querySelector('#record_tobe_updated')
const newRec = document.querySelector('#update_record')
form.addEventListener('submit', async (e) => {
e.preventDefault();
const post = await fetch('/api/developers', {
method: 'PUT',
headers: {
'Content-Type':'application/json'
},
body: JSON.stringify({developer_name: newRec.value, developer_team_id: updateRec.value}),
});
});
}
async function delData() {
const form = document.querySelector('#contact-form3');
const deleteName = document.querySelector('#delete_record');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const delName = await fetch('/api/developers', {
method: 'DELETE',
headers: {
'Content-Type':'application/json'
},
body: JSON.stringify({developer_name: deleteName.value}),
});
});
}
async function windowOnload() {
nivoSlider();
prettyPhoto();
formSub();
upDate();
delData();
allChart();
gamePic();
}
window.onload = windowOnload; |
var now = new Date();
var previews = now; //上一次的使用时间
var one_day = 24*60*60*1000;
var tommorow = new Date(now.getTime() + one_day);
var after_tommorrow = new Date(tommorow.getTime() + one_day);
var time = {
year: now.getFullYear(),
month: now.getMonth()+1,
date: now.getDate(),
}
var time_required = deepClone(time);
var offset = 0; //和当前月的偏移
$('.pre').click(() => {
if(offset <= 0) {
alert("到底了!");
}else {
--offset;
--time_required.month;
if(time_required.month <= 0) {
time_required.month = 12;
--time_required.year;
}
initCalendar();
}
})
$('.next').click(() => {
if(offset >= 12) {
alert("只支持添加一年内的事件!");
}else {
++offset;
++time_required.month;
if(time_required.month > 12) {
time_required.month = 1;
++time_required.year;
}
initCalendar();
}
})
function initCalendar() {
$('.day').empty();
$('.info').html(time_required.year+"年"+time_required.month+"月");
var last_day = getMonthDay(time_required.year, time_required.month);
var rest = 7 - last_day.week_day; //月末空白的格子
var line = "</ul>";
var cnt = 7; //一行7格
for(; rest > 0; --rest, --cnt) {
line = "<li class='algin' style='opacity: 0'>-1</li>" + line;
}
for(var date = last_day.date; date > 0; --date, --cnt) {
if(cnt == 0) {
line = "<ul>" + line;
$('.day').prepend(line);
line = "</ul>";
cnt = 7;
}
if(time_required.year == time.year && time_required.month == time.month && date == time.date) {
line = "<li class='align today date'>"+ date +"</li>" + line;
}else {
line = "<li class='align date'>"+ date +"</li>" + line;
}
}
for(; cnt > 0; --cnt) {
line = "<li class='align' style='opacity: 0'>-1</li>" + line;
}
line = "<ul>" + line;
$('.day').prepend(line);
}
var show; //选择了日期后是否在日历图标边显示
$('#calendar').on('click', '.date', (e) => {
date_choosed.year = time_required.year;
date_choosed.month = time_required.month;
date_choosed.date = parseInt($(e.target).html());
date_choosed.choosed = true;
if(show) {
var result = processTime(date_choosed.year, date_choosed.month ,date_choosed.date);
$('.date-choosed').html(result.time_title);
}
hideCalendar();
})
function showCalendar() {
initCalendar();
$('#calendar').css('z-index',999);
if(mouse_position.y < size.height/2) {
$('#calendar').css('left', mouse_position.x);
$('#calendar').css('top', mouse_position.y);
}else {
$('#calendar').css('left', mouse_position.x);
$('#calendar').css('top', mouse_position.y-$('#calendar').innerHeight());
}
$(document).click((e) => {
if($(e.target).id != 'calendar' && $(e.target).parents('.calendar-button-wrapper').length == 0 && $(e.target).parents('#calendar').length == 0) {
hideCalendar();
if(!date_choosed.choosed) {
initDateChoosed();
}
date_choosed.choosed = false;
$(document).unbind('click');
}
})
}
function hideCalendar() {
time_required = deepClone(time);
offset = 0; //清空之前翻日历的偏移量
$('#calendar').css('z-index',-999);
}
$('.calendar-button-wrapper').click(() => {
show = true;
showCalendar();
}) |
const {
browser, page, openBrowser, closeBrowser, goto, dropDown,reload, $, link, listItem, waitFor,
inputField, fileField, textField, image, button, comboBox, checkBox, radioButton, alert,
prompt, confirm, beforeunload, text, click, doubleClick, rightClick, write, press, deleteCookies,
attach, highlight, focus, scrollTo, scrollRight, scrollLeft, scrollUp, scrollDown, below,
hover, screenshot, timeoutSecs, intervalSecs, waitForNavigation, to, into, dismiss, accept,
intercept, toRightOf,setLocation,overridePermissions,evaluate
} = require('taiko');
const assert = require("assert");
beforeSuite(async () => {
await openBrowser({ headless: false }, { args: ["--window-size=2500,1500"] });
await goto("https://in.bookmyshow.com");
});
step("Open the browser", async () => {
await openBrowser({ headless: false }, { args: ["--start-fullscreen"] });
});
step("Navigate to URL", async () => {
// await goto("https://in.bookmyshow.com");
await goto("http://newtours.demoaut.com/");
})
step("Enter the city name <city>", async (city) => {
//await click($("//input[@id='inp_RegionSearch_top']"));
gauge.screenshot();
await click("View All Cities")
gauge.screenshot();
assert.ok(await text("Coimbatore").exists(), "Coimbatore city is not present the page");
gauge.screenshot();
await click(city);
// await press("Enter");
});
step("Search for the movie <movie>", async (movie) => {
await click($("//input[@placeholder='Search for Movies, Events, Plays, Sports and Activities']"));
gauge.screenshot();
await write(movie);
await press("Enter");
});
step("Select the date <date>", async (date) => {
gauge.screenshot();
await click(date,{ navigationTimeout: 10000 });
});
step("Select the theatre <theatre> and the time of the show <time>", async (theatre, time) => {
var movieTime = "//a[@data-showtime-code=" + time + "]"
await deleteCookies();
// sleep.sleep(100);
gauge.screenshot();
await click(time, toRightOf(theatre));
gauge.screenshot();
await click("Accept");
gauge.screenshot();
});
step("Select the number of seats to be booked <seats>", async (seats) => {
var xpath = "//ul[@id='popQty']//li[text()=" + seats + "]";
await click($(xpath));
gauge.screenshot();
await click("Select Seats");
await click($("//a[@id='dismiss']"));
});
step("Say <wish> to <name>", async (wish, name) => {
console.log(wish + " to" + name);
})
step("Close the browser", async () => {
await deleteCookies();
await closeBrowser();
})
afterSuite(async () => {
await deleteCookies();
await closeBrowser();
});
step("Check the ticket for <tickettype>", async (tickettype) => {
assert.ok(await text("Available", below(tickettype)).exists(), "Tickets not available for GOLD");
})
step("Select language <lang>", async (lang) => {
var xpath = "//a[@class='nav-link']";
await click($(xpath));
await click(lang);
});
|
$(function(){
if($.adblock){
$.confirm({
'title' : 'Adblocker active!',
'message' : 'You are running an adblocker extension in your browser. You made a kitten cry. If you wish to continue to this website you might consider disabling it.',
'buttons' : {
'I will!' : {
'class' : 'blue',
'action': function(){
// Do nothing
return;
}
},
'Never!' : {
'class' : 'gray',
'action': function(){
// Redirect to some page
window.location = 'http://tutorialzine.com/';
}
}
}
});
}
});
|
$(document).ready(function(){
$(".fa15").eq(0).addClass("lbjiacsschushi");
$(".fa15").eq(1).addClass("lbjiacss10");
$(".fa15").eq(2).addClass("lbjiacss20");
$(".fa15").eq(3).addClass("lbjiacss30");
});
function showLocation(province , city , town) {
var loc = new Location();
var title = ['省份' , '地级市' , '市、县、区'];
$.each(title , function(k , v) {
title[k] = '<option value="">'+v+'</option>';
})
$('#loc_province').append(title[0]);
$('#loc_city').append(title[1]);
$('#loc_town').append(title[2]);
$('#loc_province').change(function() {
$('#loc_city').empty();
$('#loc_city').append(title[1]);
loc.fillOption('loc_city' , '0,'+$('#loc_province').val());
$('#loc_town').empty();
$('#loc_town').append(title[2]);
//$('input[@name=location_id]').val($(this).val());
})
$('#loc_city').change(function() {
$('#loc_town').empty();
$('#loc_town').append(title[2]);
loc.fillOption('loc_town' , '0,' + $('#loc_province').val() + ',' + $('#loc_city').val());
//$('input[@name=location_id]').val($(this).val());
})
$('#loc_town').change(function() {
$('input[@name=location_id]').val($(this).val());
})
if (province) {
loc.fillOption('loc_province' , '0' , province);
if (city) {
loc.fillOption('loc_city' , '0,'+province , city);
if (town) {
loc.fillOption('loc_town' , '0,'+province+','+city , town);
}
}
} else {
loc.fillOption('loc_province' , '0');
}
}
function lbhanshu(a)
{
//变背景图
if(a==0)
{
$(".fa15").eq(1).removeClass("lbjiacss1");
$(".fa15").eq(2).removeClass("lbjiacss2");
$(".fa15").eq(3).removeClass("lbjiacss3");
$(".fa15").eq(1).addClass("lbjiacss10");
$(".fa15").eq(2).addClass("lbjiacss20");
$(".fa15").eq(3).addClass("lbjiacss30");
for(i=0;i<=2;i++)
{$(".fa16").eq(i).css({"color":"gray"});}
}
if(a==1)
{
$(".fa15").eq(1).removeClass("lbjiacss10");
$(".fa15").eq(1).addClass("lbjiacss1");
$(".fa15").eq(2).removeClass("lbjiacss2");
$(".fa15").eq(3).removeClass("lbjiacss3");
$(".fa15").eq(2).addClass("lbjiacss20");
$(".fa15").eq(3).addClass("lbjiacss30");
$(".fa16").eq(0).css({"color":"red"});
for(i=1;i<=2;i++)
{$(".fa16").eq(i).css({"color":"gray"});}
}
if(a==2)
{
$(".fa15").eq(1).removeClass("lbjiacss10");
$(".fa15").eq(2).removeClass("lbjiacss20");
$(".fa15").eq(1).addClass("lbjiacss1");
$(".fa15").eq(2).addClass("lbjiacss2");
$(".fa15").eq(3).removeClass("lbjiacss3");
$(".fa15").eq(3).addClass("lbjiacss30");
$(".fa16").eq(0).css({"color":"red"});
$(".fa16").eq(1).css({"color":"red"});
$(".fa16").eq(2).css({"color":"gray"});
}
if(a==3)
{
$(".fa15").eq(1).removeClass("lbjiacss10");
$(".fa15").eq(2).removeClass("lbjiacss20");
$(".fa15").eq(3).removeClass("lbjiacss30");
$(".fa15").eq(1).addClass("lbjiacss1");
$(".fa15").eq(2).addClass("lbjiacss2");
$(".fa15").eq(3).addClass("lbjiacss3");
$(".fa16").eq(0).css({"color":"red"});
$(".fa16").eq(1).css({"color":"red"});
$(".fa16").eq(2).css({"color":"red"});
}
//变字体色
}
//上传图片并预览特效
function setImageBackview() {
var imgb=document.getElementById("imgback");
var imgbackview=document.getElementById("backview");
if(imgb.files && imgb.files[0]){
//火狐下,直接设img属性
imgbackview.style.display = 'block';
imgbackview.style.width = '550px';
imgbackview.style.height = '300px';
//imgbackview.src = imgb.files[0].getAsDataURL();
//火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式
imgbackview.src = window.URL.createObjectURL(imgb.files[0]);
}else{
//IE下,使用滤镜
imgb.select();
var imgSrc = document.selection.createRange().text;
var localImagId = document.getElementById("localImag");
//必须设置初始大小
localImagId.style.width = "550px";
localImagId.style.height = "300px";
//图片异常的捕捉,防止用户修改后缀来伪造图片
try{
localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
}catch(e){
alert("您上传的图片格式不正确,请重新选择!");
return false;
}
imgbackview.style.display = 'none';
document.selection.empty();
}
return true;
}
function setImagePreview() {
var docObj=document.getElementById("imgfile");
var imgObjPreview=document.getElementById("preview");
if(docObj.files && docObj.files[0]){
//火狐下,直接设img属性
imgObjPreview.style.display = 'block';
imgObjPreview.style.width = '550px';
imgObjPreview.style.height = '300px';
//imgObjPreview.src = docObj.files[0].getAsDataURL();
//火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式
imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
}else{
//IE下,使用滤镜
docObj.select();
var imgSrc = document.selection.createRange().text;
var localImagId = document.getElementById("localImag");
//必须设置初始大小
localImagId.style.width = "550px";
localImagId.style.height = "300px";
//图片异常的捕捉,防止用户修改后缀来伪造图片
try{
localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
}catch(e){
alert("您上传的图片格式不正确,请重新选择!");
return false;
}
imgObjPreview.style.display = 'none';
document.selection.empty();
}
return true;
} //
$(function(){
$(".admin_shtop201").eq(0).addClass("dlian1h");
$(".admin_shtop201").eq(1).addClass("dlian2g");
$(".admin_shtop201").eq(2).addClass("dlian3g");
$(".admin_shtop201").eq(3).addClass("dlian4g");
$(".admin_shtop201").eq(4).addClass("dlian5g");
});
function tlian(a){
if(a==0)
{
$(".admin_shtop201").eq(0).addClass("dlian1h");
$(".admin_shtop201").eq(0).removeClass("dlian1bh");
$(".admin_shtop201").eq(0).removeClass("dlian1b");
$(".admin_shtop201").eq(1).addClass("dlian2g");
$(".admin_shtop201").eq(1).removeClass("dlian2hg");
$(".admin_shtop201").eq(1).removeClass("dlian2bh");
$(".admin_shtop201").eq(1).removeClass("dlian2b");
$(".admin_shtop201").eq(2).addClass("dlian3g");
$(".admin_shtop201").eq(2).removeClass("dlian3hg");
$(".admin_shtop201").eq(2).removeClass("dlian3bh");
$(".admin_shtop201").eq(2).removeClass("dlian3b");
$(".admin_shtop201").eq(3).addClass("dlian4g");
$(".admin_shtop201").eq(3).removeClass("dlian4hg");
$(".admin_shtop201").eq(3).removeClass("dlian4bh");
$(".admin_shtop201").eq(4).addClass("dlian5g");
$(".admin_shtop201").eq(4).removeClass("dlian5h");
}
if(a==1)
{
$(".admin_shtop201").eq(0).addClass("dlian1bh");
$(".admin_shtop201").eq(0).removeClass("dlian1h");
$(".admin_shtop201").eq(0).removeClass("dlian1b");
$(".admin_shtop201").eq(1).addClass("dlian2hg");
$(".admin_shtop201").eq(1).removeClass("dlian2g");
$(".admin_shtop201").eq(1).removeClass("dlian2bh");
$(".admin_shtop201").eq(1).removeClass("dlian2b");
$(".admin_shtop201").eq(2).addClass("dlian3g");
$(".admin_shtop201").eq(2).removeClass("dlian3hg");
$(".admin_shtop201").eq(2).removeClass("dlian3bh");
$(".admin_shtop201").eq(2).removeClass("dlian3b");
$(".admin_shtop201").eq(3).addClass("dlian4g");
$(".admin_shtop201").eq(3).removeClass("dlian4hg");
$(".admin_shtop201").eq(3).removeClass("dlian4bh");
$(".admin_shtop201").eq(4).addClass("dlian5g");
$(".admin_shtop201").eq(4).removeClass("dlian5h");
}
if(a==2)
{
$(".admin_shtop201").eq(0).addClass("dlian1b");
$(".admin_shtop201").eq(0).removeClass("dlian1h");
$(".admin_shtop201").eq(0).removeClass("dlian1bh");
$(".admin_shtop201").eq(1).addClass("dlian2bh");
$(".admin_shtop201").eq(1).removeClass("dlian2g");
$(".admin_shtop201").eq(1).removeClass("dlian2hg");
$(".admin_shtop201").eq(1).removeClass("dlian2b");
$(".admin_shtop201").eq(2).addClass("dlian3hg");
$(".admin_shtop201").eq(2).removeClass("dlian3g");
$(".admin_shtop201").eq(2).removeClass("dlian3bh");
$(".admin_shtop201").eq(2).removeClass("dlian3b");
$(".admin_shtop201").eq(3).addClass("dlian4g");
$(".admin_shtop201").eq(3).removeClass("dlian4hg");
$(".admin_shtop201").eq(3).removeClass("dlian4bh");
$(".admin_shtop201").eq(4).addClass("dlian5g");
$(".admin_shtop201").eq(4).removeClass("dlian5h");
}
if(a==3)
{
$(".admin_shtop201").eq(0).addClass("dlian1b");
$(".admin_shtop201").eq(0).removeClass("dlian1h");
$(".admin_shtop201").eq(0).removeClass("dlian1bh");
$(".admin_shtop201").eq(1).addClass("dlian2b");
$(".admin_shtop201").eq(1).removeClass("dlian2g");
$(".admin_shtop201").eq(1).removeClass("dlian2hg");
$(".admin_shtop201").eq(1).removeClass("dlian2bh");
$(".admin_shtop201").eq(2).addClass("dlian3bh");
$(".admin_shtop201").eq(2).removeClass("dlian3g");
$(".admin_shtop201").eq(2).removeClass("dlian3hg");
$(".admin_shtop201").eq(2).removeClass("dlian3b");
$(".admin_shtop201").eq(3).addClass("dlian4hg");
$(".admin_shtop201").eq(3).removeClass("dlian4g");
$(".admin_shtop201").eq(3).removeClass("dlian4bh");
$(".admin_shtop201").eq(4).addClass("dlian5g");
$(".admin_shtop201").eq(4).removeClass("dlian5h");
}
if(a==4)
{
$(".admin_shtop201").eq(0).addClass("dlian1b");
$(".admin_shtop201").eq(0).removeClass("dlian1h");
$(".admin_shtop201").eq(0).removeClass("dlian1bh");
$(".admin_shtop201").eq(1).addClass("dlian2b");
$(".admin_shtop201").eq(1).removeClass("dlian2g");
$(".admin_shtop201").eq(1).removeClass("dlian2hg");
$(".admin_shtop201").eq(1).removeClass("dlian2bh");
$(".admin_shtop201").eq(2).addClass("dlian3b");
$(".admin_shtop201").eq(2).removeClass("dlian3g");
$(".admin_shtop201").eq(2).removeClass("dlian3hg");
$(".admin_shtop201").eq(2).removeClass("dlian3bh");
$(".admin_shtop201").eq(3).addClass("dlian4bh");
$(".admin_shtop201").eq(3).removeClass("dlian4g");
$(".admin_shtop201").eq(3).removeClass("dlian4hg");
$(".admin_shtop201").eq(4).addClass("dlian5h");
$(".admin_shtop201").eq(4).removeClass("dlian5g");
}
}
|
import React, { useEffect, useRef, useState } from 'react';
import * as d3 from 'd3';
import yearlyAggregateData from '../../../data/kth_innovation_yearly_data.json';
const RELEVANT_YEARS = ["2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019"];
const yearly_aggregate_data = yearlyAggregateData;
const Infobox = ({ onYearClicked }) => {
const year_choice = onYearClicked;
// set dimensions of the graph
const margin = { top: 0, right: 0, bottom: 0, left: 0 };
const total_width = 330;
const total_height = 260;
const width = total_width - margin.left - margin.right;
const height = total_height - margin.top - margin.bottom;
// state and ref to svg
const svgRef = useRef();
const data = useState([]);
// code runs only if data has been fetched
useEffect(() => {
const dataHasFetched = data !== undefined && data.length !== 0;
const svg = d3.select(svgRef.current)
.attr('width', total_width)
.attr('height', total_height);
svg.selectAll('text').remove();
if (dataHasFetched) {
var prevYearData;
var yearData;
for (let i = 0; i < RELEVANT_YEARS.length; i++) {
if (year_choice === yearly_aggregate_data[i].year) {
if (yearly_aggregate_data[i - 1].year >= 2010) {
prevYearData = yearly_aggregate_data[i - 1];
}
yearData = yearly_aggregate_data[i];
}
}
const largeFont = 28;
const smallSpace = 5;
const largeSpace = 20;
var y = margin.top + largeFont / 2;
svg
.append('text')
.attr("x", width / 2 - 30)
.attr("y", y - 45)
.attr('font-size', 20)
.attr('font-weight', 'bold')
.attr('text-anchor', 'middle')
.text("Statistics for " + onYearClicked + (onYearClicked === 2010 ? '' : " / change from prev. year (" + (onYearClicked - 1) + ")"));
//ideas
var y = margin.top + largeSpace + smallSpace;
var diff = 0;
svg
.append('text')
.attr('class', 'ideastext')
.attr("x", 3 * width / 4)
.attr("y", y)
.attr('font-size', largeFont)
.attr('font-weight', 'bold')
.attr('text-anchor', 'middle')
.text(yearData.ideas);
svg
.append('text')
.attr("x", 3 * width / 4 + 10 + largeFont)
.attr("y", y)
.attr('text-anchor', 'start')
.attr('fill', function () {
if (prevYearData !== undefined) {
diff = yearData.ideas - prevYearData.ideas;
if (prevYearData.ideas > yearData.ideas) {
return 'red';
}
if (prevYearData.ideas < yearData.ideas) {
return 'green';
}
}
return 'black';
})
.text((onYearClicked === 2010 ? '' : diff === 0 ? '0' : diff > 0 ? '+' + diff : diff));
svg
.append('text')
.attr("x", 3 * width / 4 - largeFont)
.attr("y", y)
.attr('text-anchor', 'end')
.text("# of Ideas:");
//researchers
y = y + largeSpace + largeSpace + smallSpace;
svg
.append('text')
.attr('class', 'researcherstext')
.attr("x", 3 * width / 4)
.attr("y", y)
.attr('font-size', largeFont)
.attr('font-weight', 'bold')
.attr('text-anchor', 'middle')
.text(yearData.researchers);
svg
.append('text')
.attr("x", 3 * width / 4 + largeFont + 10)
.attr("y", y)
.attr('text-anchor', 'start')
.attr('fill', function () {
if (prevYearData !== undefined) {
diff = yearData.researchers - prevYearData.researchers;
if (prevYearData.researchers > yearData.researchers) {
return 'red'
}
if (prevYearData.researchers < yearData.researchers) {
return 'green';
}
}
return 'black';
})
.text((onYearClicked === 2010 ? '' : diff === 0 ? '0' : diff > 0 ? '+' + diff : diff));
svg
.append('text')
.attr("x", 3 * width / 4 - largeFont)
.attr("y", y)
.attr('text-anchor', 'end')
.text("# of researcher ideas: ");
//students
y = y + largeSpace + largeSpace + smallSpace;
svg
.append('text')
.attr('class', 'studentstext')
.attr("x", 3 * width / 4)
.attr("y", y)
.attr('font-size', largeFont)
.attr('font-weight', 'bold')
.attr('text-anchor', 'middle')
.text(yearData.students);
svg
.append('text')
.attr("x", 3 * width / 4 + largeFont + 10)
.attr("y", y)
.attr('text-anchor', 'start')
.attr('fill', function () {
if (prevYearData !== undefined) {
diff = yearData.students - prevYearData.students;
if (prevYearData.students > yearData.students) {
return 'red';
}
if (prevYearData.students < yearData.students) {
return 'green';
}
}
return 'black';
})
.text((onYearClicked === 2010 ? '' : diff === 0 ? '(0)' : diff > 0 ? '+' + diff : diff));
svg
.append('text')
.attr("x", 3 * width / 4 - largeFont)
.attr("y", y)
.attr('text-anchor', 'end')
.text("# of student ideas: ");
//fundings
y = y + largeSpace + largeSpace + smallSpace;
svg
.append('text')
.attr('class', 'fundingstext')
.attr("x", 3 * width / 4)
.attr("y", y)
.attr('font-size', largeFont)
.attr('font-weight', 'bold')
.attr('text-anchor', 'middle')
.text(yearData.funding);
svg
.append('text')
.attr("x", 3 * width / 4 + largeFont + 10)
.attr("y", y)
.attr('text-anchor', 'start')
.attr('fill', function () {
if (prevYearData !== undefined) {
diff = yearData.funding - prevYearData.funding;
if (prevYearData.funding > yearData.funding) {
return 'red';
}
if (prevYearData.funding < yearData.funding) {
return 'green';
}
}
return 'black';
})
.text((onYearClicked === 2010 ? '' : diff === 0 ? '0' : diff > 0 ? '+' + diff : diff));
svg
.append('text')
.attr("x", 3 * width / 4 - largeFont)
.attr("y", y)
.attr('text-anchor', 'end')
.text("# of fundings granted:");
//patent applications
y = y + largeSpace + largeSpace + smallSpace;
svg
.append('text')
.attr('class', 'patentstext')
.attr("x", 3 * width / 4)
.attr("y", y)
.attr('font-size', largeFont)
.attr('font-weight', 'bold')
.attr('text-anchor', 'middle')
.text(yearData.patent_applications);
svg
.append('text')
.attr("x", 3 * width / 4 + largeFont + 10)
.attr("y", y)
.attr('text-anchor', 'start')
.attr('fill', function () {
if (prevYearData !== undefined) {
diff = yearData.patent_applications - prevYearData.patent_applications;
if (prevYearData.patent_applications > yearData.patent_applications) {
return 'red';
}
if (prevYearData.patent_applications < yearData.patent_applications) {
return 'green';
}
}
return 'black';
})
.text((onYearClicked === 2010 ? '' : diff === 0 ? '0' : diff > 0 ? '+' + diff : diff));
svg
.append('text')
.attr("x", 3 * width / 4 - largeFont)
.attr("y", y)
.attr('text-anchor', 'end')
.text("# of patent applications:");
//novelty searches
y = y + largeSpace + largeSpace + smallSpace;
svg
.append('text')
.attr('class', 'noveltytext')
.attr("x", 3 * width / 4)
.attr("y", y)
.attr('font-size', largeFont)
.attr('font-weight', 'bold')
.attr('text-anchor', 'middle')
.text(yearData.novelty_searches);
svg
.append('text')
.attr("x", 3 * width / 4 + largeFont + 10)
.attr("y", y)
.attr('text-anchor', 'start')
.attr('fill', function () {
if (prevYearData !== undefined) {
diff = yearData.novelty_searches - prevYearData.novelty_searches;
if (prevYearData.novelty_searches > yearData.novelty_searches) {
return 'red';
}
if (prevYearData.novelty_searches < yearData.novelty_searches) {
return 'green';
}
}
return 'black';
})
.text((onYearClicked === 2010 ? '' : diff === 0 ? '0' : diff > 0 ? '+' + diff : diff));
svg
.append('text')
.attr("x", 3 * width / 4 - largeFont)
.attr("y", y)
.attr('text-anchor', 'end')
.text("# of novelty searches:");
}
return () => {
svg.selectAll("svg").exit().remove();
}
}, [height, width, margin.right, margin.left, margin.top, margin.bottom, data, year_choice]);
return <React.Fragment>
<svg overflow='visible' height={height} width={width} ref={svgRef} />
</React.Fragment>;
};
export default Infobox;
|
module.exports = options => {
return {
id: "backstop_default",
viewports: [
{
label: "phone",
width: 320,
height: 480
},
{
label: "tablet",
width: 768,
height: 1024
},
{
label: "desktop",
width: 1920,
height: 1080
}
],
onBeforeScript: "puppet/onBefore.js",
onReadyScript: "puppet/onReady.js",
scenarios: options.scenarios,
paths: {
bitmaps_reference: "bitmaps_reference",
bitmaps_test: "bitmaps_test",
engine_scripts: "scripts",
html_report: "html_report",
ci_report: "ci_report"
},
report: ["browser"],
engine: "puppeteer",
engineOptions: {
args: ["--no-sandbox"]
},
asyncCaptureLimit: 5,
asyncCompareLimit: 10,
debug: false,
debugWindow: false
}
} |
/**
* 提供一些常用工具
* @type {{getImageWH, getQueryStringByName}}
*/
window.Util = (function () {
/**
* 根据URL,获取图片的宽高
* @param src 图片地址
* @param callback 回调,返回 w h 属性
*/
function getImageWH(src, callback) {
var image = new Image();
image.src = src;
image.onload = function () {
var obj = {
w: image.width,
h: image.height
}
callback && callback(obj);
};
}
/**
* 根据URL,获取视频的宽高
* @param src 视频地址
* @param callback 获取后的回调
*/
function getVideoWH(src, callback) {
var video = document.createElement('video')
video.setAttribute('src', src);
video.oncanplaythrough = function () {
var obj = {
w: this.videoWidth,
h: this.videoHeight
}
callback && callback(obj);
video = null;
};
}
/**
* 根据QueryString参数名称获取值
* @param {[type]} key [key]
*/
function getQueryStringByName(key) {
var result = location.search.match(new RegExp("[\?\&]" + key + "=([^\&]+)", "i"));
if (result == null || result.length < 1) {
return "";
}
return result[1];
}
/**
* 关闭浏览器窗口
* @constructor
*/
function closeWebPage() {
var userAgent = navigator.userAgent;
if (userAgent.indexOf("Firefox") != -1 || userAgent.indexOf("Chrome") != -1) {
window.location.href = "about:blank";
window.opener = null;
window.open("", "_self");
window.close();
} else {
window.opener = null;
window.open("", "_self");
window.close();
}
}
/**
* 鼠标是点击或者移动
* @param selector
* @param cb_tap
* @param cb_move
*/
function Moblie_MoveOrTap($selector, cb_tap, cb_move) {
var flag = false;
$selector.off().on('touchstart touchmove touchend', function (event) {
switch (event.type) {
case 'touchstart':
flag = false;
break;
case 'touchmove':
flag = true;
break;
case 'touchend':
if (!flag) {
cb_tap && cb_tap(event);
} else {
cb_move && cb_move(event);
}
break;
}
})
}
/**
* 判断是否是PC端
*/
function IsPC() {
var userAgentInfo = navigator.userAgent;
var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
var flag = true;
for (var v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) {
flag = false;
break;
}
}
return flag;
}
/**
* 根据 ids 获取数据 (ids : 1_1)
* @param data
* @param ids
*/
function getPointDataByIds(data, ids) {
var _ids = ids.split('_');
var pages = data.pages;
var pointsData = pages[_ids[0]]['points'];
return pointsData[_ids[1]];
}
/**
* 加载样式
* @param path
*/
function loadCSS(path) {
if (!path || path.length === 0) {
throw new Error('argument "path" is required !');
}
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.href = path;
link.rel = 'stylesheet';
link.type = 'text/css';
head.appendChild(link);
}
/**
* 加载脚本
* @param path
*/
function loadJS(path) {
if (!path || path.length === 0) {
throw new Error('argument "path" is required !');
}
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = path;
script.type = 'text/javascript';
head.appendChild(script);
}
/**
* 获取当前脚本文件路径
* @param {any} currentPath
* @returns
*/
function getBasePath(currentPath) {
// 兼容Chrome 和 FF
var currentPath = currentPath || ''
var paths = currentPath.split('/')
paths.pop()
return paths.join('/')
}
/**
* 检查样式里面是否存在某个样式名
* @param string className
* @param array not_allow_drag_class
*/
function hasClass(className, not_allow_drag_class) {
if (!not_allow_drag_class) not_allow_drag_class = []
if (!className) className = ''
for (var i = 0; i < not_allow_drag_class.length; i++) {
if (className.indexOf(not_allow_drag_class[i]) !== -1) {
return true;
}
}
return false;
}
/**
* 移动端拖动
* @param selector
*/
function touchDrag(selector, callback, not_allow_drag_class) {
var moveX, moveY, startX, startY, left = 0, top = 0;
$(selector)
.on("touchstart", function (event) {
if (!hasClass($(event.target).attr('class'), not_allow_drag_class)) {
event.preventDefault();
var touchPros = event.touches[0];
startX = touchPros.clientX;
startY = touchPros.clientY;
if ($(selector).css('left') !== 'auto') {
left = parseFloat($(selector).css('left').replace('px', '').replace('rem', ''))
top = parseFloat($(selector).css('top').replace('px', '').replace('rem', ''))
}
}
})
.on("touchmove", function (event) {
if (!hasClass($(event.target).attr('class'), not_allow_drag_class)) {
event.preventDefault();
var touchPros = event.touches[0];
moveX = touchPros.clientX - startX + left;
moveY = touchPros.clientY - startY + top;
if (callback) callback(event, moveX, moveY)
}
})
}
/**
* PC端拖动
* @param selector
* @param callback
* @param not_allow_drag_class 点击selector里面的字节点,一些子节点点击不允许拖动
*/
function mouseDrag(selector, callback, not_allow_drag_class) {
var moveX, moveY, startX, startY, left = 0, top = 0, flag = false;
$(selector)
.on("mousedown", function (event) {
if (!hasClass($(event.target).attr('class'), not_allow_drag_class)) {
event.preventDefault();
startX = event.clientX;
startY = event.clientY;
if ($(selector).css('left') !== 'auto') {
left = parseFloat($(selector).css('left').replace('px', '').replace('rem', ''))
top = parseFloat($(selector).css('top').replace('px', '').replace('rem', ''))
}
flag = true;
$(document)
.on("mousemove", function (event) {
event.preventDefault();
if (flag) {
moveX = event.clientX - startX + left;
moveY = event.clientY - startY + top;
callback(event, moveX, moveY)
}
})
.on('mouseup', function () {
flag = false;
})
}
})
}
/**
* 兼容PC和移动端的拖动
*/
function drag(selector, callback, not_allow_drag_class) {
mouseDrag(selector, callback, not_allow_drag_class);
touchDrag(selector, callback, not_allow_drag_class);
}
/**
* 把图片转换成base64的数据格式
* gif图会变成静态图
* @param {any} path
* @param {any} callback
*/
function getImageBase64(path, callback) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
var img = new Image();
//指定图片的URL
img.src = path;
img.onload = function (e) {
var width = e.target.width;
var height = e.target.height;
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
var cropStr = canvas.toDataURL("image/png", 0.7)
callback(cropStr)
}
}
/**
* 获取模板
* @param {any} url
* @param {any} callback
*/
function getTpl(url, callback) {
$.ajax({
url: url,
success: function (tpl) {
callback(tpl)
}
})
}
/**
* 从模板文件获取指定的模板(一个文件中有多个模板)
* @param {any} url 模板地址
* @param {string} id 模板的id
* @param {any} callback
*/
function getTplById(url, id, callback) {
$.ajax({
url: url,
success: function (tpl) {
var sub_tpl = $('<div></div>').html(tpl).find('#' + id).html()
callback(sub_tpl)
}
})
}
/**
* 绘制区域的时候使用,避免绘制图形后还触发点击事件
* 鼠标拖动还是点击
* @param {any} selector
* @param {any} onClick
* @param {any} onMove
*/
function MoveOrClick(selector, onClick, onMove) {
var Mouse = {
x: 0,
y: 0,
mousedown: function (event) {
Mouse.y = event.clientY;
Mouse.x = event.clientX;
},
mouseup: function (event) {
if (event.clientX != Mouse.x || event.clientY != Mouse.y) {
if (onMove) {
onMove(event);
}
} else {
console.log('click');
if (onClick) {
onClick(event)
}
}
}
}
$('body').on('mousedown', selector, Mouse.mousedown)
$('body').on('mouseup', selector, Mouse.mouseup);
}
/*16进制颜色转为RGB格式*/
String.prototype.colorRgb = function (sColor) {
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
sColor = this.toLowerCase();
if (sColor && reg.test(sColor)) {
if (sColor.length === 4) {
var sColorNew = "#";
for (var i = 1; i < 4; i += 1) {
sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
}
sColor = sColorNew;
}
//处理六位的颜色值
var sColorChange = [];
for (var i = 1; i < 7; i += 2) {
sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
}
return "RGB(" + sColorChange.join(",") + ")";
} else {
return sColor;
}
};
/**
* 把16进制颜色转换成rgba的颜色
* #000000 + 0.5 = rgba(0,0,0,0.5)
* @param {any} colorStr
* @param {any} opacity
* @returns
*/
function hex2RGBA(colorStr, opacity) {
var rgb = colorStr || '#000000';
var a = opacity || 0;
var matches = rgb.match(/#([\da-f]{2})([\da-f]{2})([\da-f]{2})/i);
var rgba = 'rgba(' + matches.slice(1).map(function (m) { return parseInt(m, 16); }).concat(a) + ')';
return rgba;
}
/**
* 把数字转换成时间
* eg: 81 => 01:21
* @param {any} num
*/
function num2time(num) {
var minute = parseInt(num / 60);
var seconds = num - 60 * minute
if (minute < 10) {
minute = '0' + minute
}
if (seconds < 10) {
seconds = '0' + seconds
}
return minute + ':' + seconds
}
/**
* 把时间字符串转换成数字
* 01:21 => 81
* @param {any} timeStr
*/
function time2num(timeStr) {
if (!timeStr) {
return null
}
var time = 0;
var _times
if (timeStr.indexOf(':') !== -1) {
_times = timeStr.split(':');
} else if (timeStr.indexOf(':') !== -1) {
_times = timeStr.split(':');
}
//把 00:01:21计算成秒 81
var _timesLength = _times.length - 1
for (var j = _timesLength; j >= 0; j--) {
var _time = parseInt(_times[_timesLength - j]) || 0;
switch (j) {
case 2:
time += _time * 3600;
break;
case 1:
time += _time * 60;
break;
case 0:
time += _time;
break;
}
}
return time;
}
/**
* 全屏功能参考
* http://www.cnblogs.com/mq0036/p/5042871.html
*/
function requestFullScreen(element) {
// 判断各种浏览器,找到正确的方法
var requestMethod = element.requestFullScreen || //W3C
element.webkitRequestFullScreen || //Chrome等
element.mozRequestFullScreen || //FireFox
element.msRequestFullScreen; //IE11
if (requestMethod) {
requestMethod.call(element);
}
else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
}
//退出全屏 判断浏览器种类
function exitFullScreen() {
// 判断各种浏览器,找到正确的方法
var exitMethod = document.exitFullscreen || //W3C
document.mozCancelFullScreen || //Chrome等
document.webkitExitFullscreen || //FireFox
document.webkitExitFullscreen; //IE11
if (exitMethod) {
exitMethod.call(document);
}
else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
}
// 设置音频的音频文件路径
function setAudioSource(audio, src) {
var source = ""
source += '<source src="' + src.replace('mp3', 'm3u8') + '">'
source += '<source src="' + src + '">'
$(audio).html("")
$(audio).append(source)
//注意:资源为 srouce格式的,需要重新加载,否则还是播放上一个资源。 这个是和src指定资源的区别
audio.load()
}
/**
* 获取音频地址
* 地址形式为 source
*
* @param {any} audio
*/
function getAudioSource(audio) {
var $sources = $(audio).find('source')
if ($sources < 2) {
return ''
}
return $sources.eq(1).attr('src')
}
/**
* 获取手机系统和浏览器类型
*/
function getBrowserInfo() {
var browser = {
versions: function () {
var u = navigator.userAgent,
app = navigator.appVersion;
return {
trident: u.indexOf('Trident') > -1, //IE内核
presto: u.indexOf('Presto') > -1, //opera内核
webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
iPad: u.indexOf('iPad') > -1, //是否iPad
webApp: u.indexOf('Safari') == -1, //是否web应该程序,没有头部与底部
weixin: u.indexOf('MicroMessenger') > -1, //是否微信 (2015-01-22新增)
qq: u.match(/\sQQ/i) == " qq" //是否QQ
};
}(),
language: (navigator.browserLanguage || navigator.language).toLowerCase()
}
return browser.versions
}
/**
* 获取视频指定时间点的截图
* @param {string} src 视频地址
* @param {int} currentTime 指定时间
* @param {string} output 输出截图的位置
* @param {int} scale 截图的比例
*/
function getVideoImage(src, currentTime, callback, scale) {
scale = scale || 1
var video = document.getElementById('__video_img__')
if (!video) {
video = document.createElement("video")
video.setAttribute('id', '__video_img__')
video.style.display = 'none'
document.body.appendChild(video)
}
if (video.src !== src) {
video.setAttribute('src', src)
video.load()
}
video.currentTime = currentTime
video.addEventListener('loadeddata', function () {
var canvas = document.createElement("canvas")
canvas.width = video.videoWidth * scale
canvas.height = video.videoHeight * scale
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)
var base64 = canvas.toDataURL("image/png")
var data = {
totalTime: video.duration,
currentTime: video.currentTime,
videoWidth: video.videoWidth,
videoHeight: video.videoHeight,
base64: base64
}
if (callback) {
callback(data)
}
});
}
return {
getImageWH: getImageWH,
getVideoWH: getVideoWH,
getQueryStringByName: getQueryStringByName,
closeWebPage: closeWebPage,
Moblie_MoveOrTap: Moblie_MoveOrTap,
IsPC: IsPC,
getPointDataByIds: getPointDataByIds,
loadCSS: loadCSS,
loadJS: loadJS,
getBasePath: getBasePath,
touchDrag: touchDrag,
mouseDrag: mouseDrag,
drag: drag,
getImageBase64: getImageBase64,
getTpl: getTpl,
getTplById: getTplById,
MoveOrClick: MoveOrClick,
hex2RGBA: hex2RGBA,
num2time: num2time,
time2num: time2num,
requestFullScreen: requestFullScreen,
exitFullScreen: exitFullScreen,
setAudioSource: setAudioSource,
getAudioSource: getAudioSource,
getBrowserInfo: getBrowserInfo,
getVideoImage: getVideoImage
}
})()
|
import React from 'react'
import TodolistFormTile from '../components/TodolistFormTile'
class TodolistFormContainer extends React.Component {
constructor(props){
super(props);
this.state = {
title: '',
body: ''
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
this.clearForm = this.clearForm.bind(this)
this.addTodolist = this.addTodolist.bind(this)
}
handleChange(event){
this.setState({
[event.target.name]: event.target.value
})
}
clearForm(){
this.setState({
title: '',
body: ''
})
}
addTodolist(payload, requestType, todolistId){
let request = requestType.toUpperCase()
fetch(`http://127.0.0.1:8000/api/${todolistId}`, {
credentials: 'same-origin',
headers: { 'Accept': 'application/json','Content-Type': 'application/json' },
method: request,
body: JSON.stringify(payload)
})
.then(response => response.json())
.then(res => {
this.setState({
title: res.title,
body: res.body
})
})
}
handleSubmit(requestType, todolistId){
let payload = {
title: this.state.title,
body: this.state.body
}
this.addTodolist(payload, requestType, todolistId)
this.clearForm()
}
render(){
return(
<form onSubmit={() =>
this.handleSubmit(
this.props.requestType,
this.props.todolistId
)}
>
<TodolistFormTile
name="title"
label="Title"
content={this.state.title}
handlerFunction={this.handleChange}
/>
<TodolistFormTile
name="body"
label="Body"
content={this.state.body}
handlerFunction={this.handleChange}
/>
<button type='submit' value='Submit'>{this.props.btn}</button>
</form>
)
}
}
export default TodolistFormContainer;
|
async function getKidName() {
return localStorage.getItem('name');
}
window.onload = async () => {
var kidName = await getKidName();
$("[data-name='kidName']").html(kidName);
} |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { View, StyleSheet, Dimensions } from 'react-native';
import Button from 'react-native-button'
import MapView from 'react-native-maps';
import { fetchRestaurantAPI } from '../actions';
import { connect } from 'react-redux';
import MapRestList from './MapRestList';
class Map extends Component {
componentDidMount() {
this.props.fetchRestaurantAPI()
}
componentWillUnmount() {
this.props.fetchRestaurantAPI()
}
state = {
focusedLocation: {
latitude: 47.607617,
longitude: -122.3347883,
latitudeDelta: 0.0089,
longitudeDelta:
Dimensions.get("window").width /
Dimensions.get("window").height *
0.0089
},
locationChosen: false
};
pickLocationHandler = event => {
const coords = event.nativeEvent.coordinate;
this.map.animateToRegion({
...this.state.focusedLocation,
latitude: coords.latitude,
longitude: coords.longitude
});
this.setState(prevState => {
return {
focusedLocation: {
...prevState.focusedLocation,
latitude: coords.latitude,
longitude: coords.longitude
},
locationChosen: true
};
});
};
getLocationHandler = () => {
navigator.geolocation.getCurrentPosition(pos => {
const coordsEvent = {
nativeEvent: {
coordinate: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude
}
}
};
this.pickLocationHandler(coordsEvent);
},
err => {
console.log(err)
alert("Fetching the position failed, please pick one manually!");
})
}
renderMarkers() {
return this.props.restaurants.map((place, i) => (
<MapRestList key={i} restaurant={place}/>
));
}
render () {
let marker = null;
if (this.state.locationChosen) {
marker =
<MapView.Marker coordinate={this.state.focusedLocation}>
<View style={styles.radius}>
<View style={styles.marker}/>
</View>
</MapView.Marker>;
}
return (
<View style={styles.container}>
<MapView
initialRegion={this.state.focusedLocation}
style={styles.map}
onPress={this.pickLocationHandler}
ref={ref => this.map = ref}
>
{marker}
{this.renderMarkers()}
</MapView>
<View style={styles.button}>
<Button
style={styles.buttonStyle}
onPress={this.getLocationHandler}
>
Locate Me
</Button>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
backgroundColor: '#FACDC2'
},
map: {
width: "100%",
height: 450
},
button: {
margin: 8
},
radius: {
height: 50,
width: 50,
borderRadius: 50 / 2,
overflow: 'hidden',
backgroundColor: 'rgba(0, 122, 255, 0.1)',
borderWidth: 1,
borderColor: 'rgba(0, 122, 255, 0.3)',
alignItems: 'center',
justifyContent: 'center'
},
marker: {
height: 20,
width: 20,
borderWidth: 3,
borderColor: 'white',
borderRadius: 20 / 2,
overflow: 'hidden',
backgroundColor: '#007AFF'
},
buttonStyle: {
padding: 10,
paddingRight: 40,
paddingLeft: 40,
marginTop: 21,
height: 40,
color: 'white',
overflow:'hidden',
borderColor: '#414B6B',
borderWidth: 1,
borderRadius: 5,
backgroundColor: '#414B6B',
}
});
Map.propTypes = {
fetchRestaurantAPI: PropTypes.func,
restaurants: PropTypes.array
}
const mapStateToProps = state => {
return { restaurants: state.restaurants }
}
export default connect(mapStateToProps, { fetchRestaurantAPI })(Map);
// export default Map;
|
import React from "react";
import PropTypes from "prop-types";
import "./Movie.css";
//하나의 변수를 받아올때는 {}이것을 무조건 붙여줘야 된다
//이게 없을경우 하나의 오브젝트를 통째로 받아오는데 id이외의 값들은 전부
//없는것으로 판단되어서 오류는 없고 화면에는 아무것도 표시가 안된다
function Movie({year, title, summary, poster, genres})
{
return (
<div className="movies__movie">
<img className="movie__poster" src={poster} alt={title} title={title}/>
<div className="movies__data">
{/*이런식으로도 스타일 주기 가능 css사용안함*/}
{/* <h3 class="movie__title" style={{backgroundColor:"red"}}>{title}</h3> */}
<h3 className="movie__title">{title}</h3>
<h5 className="movie__year">{title}</h5>
<p className="movie__summary">{summary.slice(0, 140)}...</p>
<ul className="movie__genres">
{genres.map((genre, index) => (
<li key={index} className="genres__genre">Type{index} : {genre}</li>
))}
</ul>
</div>
</div>
);
}
Movie.propTypes =
{
id : PropTypes.number.isRequired,
year : PropTypes.number.isRequired,
title : PropTypes.string.isRequired,
summary : PropTypes.string.isRequired,
poster : PropTypes.string.isRequired,
genres : PropTypes.array.isRequired
};
export default Movie; |
'use strict';
import * as _ from 'lodash';
/**
* Class representing a detect component controller.
*/
class DetectController {
/**
* Initialize the controller.
* @ngInject
* @param {Object} $scope - Table component controller scope.
* @param {Object} ApiProviderService - Api provider HTTP request service.
* @param {Object} ConfigService - Configuration service.
* @param {Object} DialogService - Dialogbox functional service.
* @param {Object} ValidateService - Validation service.
*/
constructor ($scope, ApiProviderService, ConfigService, DialogService, ValidateService) {
this.api = ApiProviderService;
this.config = ConfigService;
this.dialog = DialogService;
this.scope = $scope;
this.validate = ValidateService;
}
/**
* Initialize lifecycle hooks.
*/
$onInit () {
this.detectParams = this.config.getDetectParams();
this.dialogboxParams = this.config.getDialogboxParams();
this.rules = this.validate.getRules();
}
/**
* Detect provider list.
* @param {Event} $event - Button click event.
*/
detectProvider ($event) {
this.api.detectItems(this.detectParams.data)
.then(res => {
this.scope.dialogError = false;
this.showResult($event, res.data);
})
.catch(() => {
this.scope.dialogError = true;
this.showResult($event);
});
}
/**
* Show detect information in dialogbox.
* @param {Event} $event - Button click event.
* @param {Provider} data - Detect provider data.
*/
showResult ($event, data = {}) {
const $scope = this.scope;
$scope.dialogData = _.cloneDeep(data);
$scope.dialogType = this.dialogboxParams.view.type;
$scope.dialogView = this.detectParams.view;
this.dialog.show({
callback: () => {},
event: $event,
scope: $scope
});
}
/**
* Validate detect data parameters.
* @return {Boolean}
*/
validateData () {
return this.validate.isValidData(this.detectParams.data);
}
}
export default DetectController;
|
const Router = require('koa-router')
const router = new Router({prefix:'/user'});
const path = require('path');
const crypto =require('crypto');
let db = require(path.resolve('src', 'models/index'));
let uuid4 = require('uuid/v4');
let validator = require('validator');
const mailgun = require(path.resolve('src', 'common/libs/email') );
const redis = require(path.resolve('src', 'common/libs/redis') );
router.post('/signup', async (ctx, next) => {
let { username, email, first_name, last_name, cell_phone } = ctx.request.body;
ctx.assert(validator.isEmail(email), 400, 'Invalid Email Address');
let required_fields = !!username && !!email;
ctx.assert(required_fields, 400, 'Username and Email are required');
let user;
try{
user = await db.User.create({
uuid: uuid4(),
username: username,
email: email,
password: null,
is_verified: false,
created_at: parseInt(Date.now() / 1000, 10), // 10-digit timestamp
first_name: first_name,
last_name: last_name,
cell_phone: cell_phone
});
}
catch (err){
ctx.throw(400, 'Bad Request')
}
ctx.status = 201;
ctx.body = {
message: 'Welcome to Jekyll Pay!',
data: {
user : {
username: user.username,
email: user.email,
first_name: user.first_name,
last_name: user.last_name,
cell_phone: user.cell_phone
}
}
}
});
router.post('/verify', async (ctx, next)=>{
let { email, username } = ctx.request.body;
let user = await db.User.findOne({where: { email: email, username: username}});
ctx.assert(user, 400, 'Bad Request');
if (user.is_verified){
ctx.status = 200;
ctx.body = { message: "Already Verified!", data: { user: { email:user.email } }};
}else{
//send an email
try {
await mailgun.messages().send({
from: 'Jekyll Pay Message Center <noreply@msg.jekyllpay.com>',
to: user.email,
subject: 'Jekyll Pay User Verify Link',
text: 'Click the link:\n\nhttps://api.jekyllpay.com/user/verify?email='
+ user.email
+ '&code=' + crypto.createHash('md5').update(process.env.USER_VERIFY_KEY + user.email + user.username).digest('hex')
+ '&deadline=' + (Date.now() + 30 * 86400 * 1000)
});
} catch (err) {
ctx.throw(500, 'Internal Server Error' + err);
}
//send email first, and then, incr email_key
let email_key = "jp:send:" + user.email;
let sent = await redis.get(email_key);
if(!sent){
await redis.set(email_key, 1 , 'EX', 86400);
}else if ( sent < 5){
await redis.incr(email_key);
}else{
ctx.throw(429,'Exceed Rate Limit.');
}
ctx.status = 200;
ctx.body = { message: 'Verification Email Sent!' }
}
});
router.get('/verify', async(ctx, next) =>{
let { email, code, deadline } = ctx.request.query;
ctx.assert(!!email && !!code && !!deadline, 400, 'Invalid Verification Link');
ctx.assert(Date.now() < deadline, 400, 'Verification Link has expired!');
let user = await db.User.findOne({where: {email:email}});
ctx.assert(user, 400, 'Bad Request');
if (user.is_verified){
ctx.status = 200;
ctx.body = { message: "Already Verified!", data: { user: { email:user.email } }}
}
else if ( !user.is_verified && code == crypto.createHash('md5').update(process.env.USER_VERIFY_KEY + user.email + user.username).digest('hex')){
user.is_verified = true;
await user.save();
ctx.status = 200;
ctx.body = { message: 'User Verified!', data: { user : {email: user.email, username: user.username}}};
}else{
ctx.status = 400;
ctx.body = { message :"Invalid Verification Link"}
}
})
module.exports = router; |
import React, { Component } from "react";
import QueryServices from "../../services/queryServices";
export default class AllQueries extends Component {
constructor(props) {
super(props);
this.queryService = new QueryServices();
this.state = {
queries: [],
errors: {},
ElementStyle: {
display: "none",
readOnly: true,
disabled: true,
update: false,
},
updateQuery: {
email: props.email,
mobile: props.mobile,
query: props.queries,
status: props.status,
cseRemarks: props.cseRemarks,
},
};
this.handleChange = this.handleInput.bind(this);
}
handleInput(event) {
console.log("fIELD ", event);
}
handleUpdateQuery = (queryUpdate) => {
// console.log(" Delete Called Working ", deleteResult);
//window.location.reload();
console.log("Called ", queryUpdate);
this.queryService.updateQuerys(this.state.queries);
};
handleQueryUpdateEnable = (event) => {
this.setState({
ElementStyle: {
readOnly: false,
disabled: false,
display: "block",
update: true,
},
});
};
componentDidMount() {
this.queryService.getQuerys().then((jsonData) => {
this.setState({
queries: jsonData,
});
});
}
render() {
const { updateQuery } = this.state;
const { email, mobile, query, status, cseRemarks } = updateQuery;
return (
<div className="container-fluid">
<div>
{this.state.queries.map((details, index) => {
return (
<div className="row" key={details.id}>
<React.Fragment key={details.id}>
<div className="card col-md-9" key={details.id}>
<div className="form-group col-md-9" key={details.id}>
<br />
<div className="row">
<h3 key={details.id} className="col-md-7">
{details.name}
</h3>
<p className="col-md-1"></p>
<button
className="btn btn-outline-warning col-md-4"
onClick={() => this.handleQueryUpdateEnable(details)}
>
Update -
<svg
width="16"
height="16"
fill="currentColor"
className="bi bi-pencil-fill"
viewBox="0 0 16 16"
>
<path d="M12.854.146a.5.5 0 0 0-.707 0L10.5 1.793 14.207 5.5l1.647-1.646a.5.5 0 0 0 0-.708l-3-3zm.646 6.061L9.793 2.5 3.293 9H3.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.207l6.5-6.5zm-7.468 7.468A.5.5 0 0 1 6 13.5V13h-.5a.5.5 0 0 1-.5-.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.5-.5V10h-.5a.499.499 0 0 1-.175-.032l-.179.178a.5.5 0 0 0-.11.168l-2 5a.5.5 0 0 0 .65.65l5-2a.5.5 0 0 0 .168-.11l.178-.178z" />
</svg>
</button>
</div>
<br />
<span style={{ color: "green" }}>
{this.state.errors["queryUpdateSuccess"]}
</span>
</div>
<label>User Email</label>
<div className="form-group">
<input
key={details.id}
type="textArea"
className="form-control lead col-md-7"
value={details.email}
readOnly={this.state.ElementStyle.readOnly}
/>
</div>
<div className="form-group">
<label>User's Mobile</label>
<input
key={details.id}
type="text"
className="form-control col-md-7"
value={details.mobile}
readOnly={this.state.ElementStyle.readOnly}
/>
</div>
<div className="form-group">
<label>User's Query</label>
<textarea
key={details.id}
type="text"
className="form-control col-md-7"
value={details.query || query}
readOnly={this.state.ElementStyle.readOnly}
/>
</div>
<div className="form-group">
<label>Query Status</label>
<br />
<select
key={details.id}
className="custom-select col-md-7"
id="inputGroupSelect06"
value={details.status}
disabled={this.state.ElementStyle.disabled}
>
<option defaultValue>Choose...</option>
<option value="active">Active</option>
<option value="inactive">In-Active</option>
</select>
</div>
<div className="form-group">
<label>Closing Remarks</label>
<input
key={details.id}
type="text"
className="form-control col-md-7"
value={details.cseRemarks}
readOnly={this.state.ElementStyle.readOnly}
/>
</div>
<br />
<button
className="btn btn-primary btn-block col-md-7"
style={this.state.ElementStyle}
onClick={this.handleUpdateQuery()}
>
Update Query
</button>
<br />
</div>
<div className="row col-md-10 invisible">S</div>
<div className="row col-md-10 invisible">S</div>
</React.Fragment>
</div>
);
})}
</div>
</div>
);
}
}
|
/* @flow */
'use strict'
import { GraphQLObjectType, GraphQLSchema } from 'graphql'
import * as userMutations from './user/mutations'
import * as userQueries from './user/queries'
import * as courseMutations from './course/mutations'
import * as courseQueries from './course/queries'
// import * as avatarMutations from './avatar/mutations'
console.log(userMutations)
const queryType = new GraphQLObjectType({
name: 'Query',
description: 'All queries',
fields: {
...userQueries,
...courseQueries
}
})
const mutationType = new GraphQLObjectType({
name: 'Mutation',
description: 'All mutations',
fields: {
...userMutations,
...courseMutations
// ...avatarMutations
}
})
export default new GraphQLSchema({
query: queryType,
mutation: mutationType
})
|
var mongoose = require('mongoose');
var quizzTabletteSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
title: mongoose.Schema.Types.String,
type: mongoose.Schema.Types.String,
questions: mongoose.Schema.Types.Mixed,
description: mongoose.Schema.Types.String,
theme: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Theme'
}
});
var QuizzTablette = module.exports = mongoose.model('quizztablette', quizzTabletteSchema);
module.exports.get = function(callback, limit){
QuizzTablette.find(callback).populate('theme', 'name -_id').limit(limit);
}
|
import React from 'react';
const imgStyles = {
width: "100%"
}
export default class Overview extends React.Component {
render() {
return (
<section id="top_content" class="top_cont_outer">
<div class="top_cont_inner">
<div class="top_content">
<div class="row">
<div class="col-xs-5">
<div class="top_left_cont flipInY wow animated">
<h2>Overview</h2>
<p>
Jackhammer is a collaboration tool built with the aim of bridging the gap between security teams, developer teams, and QA teams, and being the facilitator for TPM to understand and track the quality of the code going into production
</p>
</div>
</div>
<div class="col-xs-7">
<img src="/images/new_dashboard_1.png" class="img-responsive" style={imgStyles}/>
</div>
</div>
</div>
</div>
</section>
)
}
}
|
/* eslint-disable */
export function processData(raw) {
const data = { nodes: [], links: [] };
// Convert to JSON
raw = raw.map(d => d.toJSON());
// Set numLinks to zero
raw.forEach(caseObj => {
caseObj._id = caseObj._id.toString();
caseObj.numLinks = 0;
});
// Calculate numLinks
raw.forEach(caseObj => {
caseObj.citedCases.forEach(id => {
const c = getFromArray(raw, "_id", id.toString());
if (c) {
c.numLinks += 1;
caseObj.numLinks += 1;
}
});
});
// Sort and Limit
raw = raw.sort((a, b) => {
return b.score * (b.numLinks + 1) - a.score * (a.numLinks + 1);
});
raw = raw.slice(0, 200);
// Build a network
const nodes = {};
for (let [i, value] of raw.entries()) {
const d = value; //.toJSON();
nodes[value._id] = {
i: i,
name: d.name,
year: d.year,
score: d.score,
numLinks: d.numLinks
};
}
for (let [i, value] of raw.entries()) {
for (let id of value.citedCases) {
if (nodes[id]) {
data.links.push({ source: i, target: nodes[id].i });
}
}
}
data.nodes = Object.keys(nodes).map(function(key) {
return nodes[key];
});
return data;
}
function getFromArray(array, prop, value) {
for (var i = 0; i < array.length; i++) {
if (array[i][prop] === value) return array[i];
}
return null;
}
|
module.exports = (bh) => {
bh.match('price__parts', (ctx) => {
ctx.param('parts', []);
});
};
|
export const WEATHERAPI = 'https://api.openweathermap.org/data/2.5/forecast?q=';
export const WEATHERAPIKEY = '&appid=c8e65a4f40a9f86173cf5e60e03219c8';
export const dayfunc123 = (city) => {
var url = WEATHERAPI + city + WEATHERAPIKEY;
fetch(url)
.then(response =>
{
if ( response.status >= 200 && response.status <299) {
return response.json();
} else {
throw Error(response.statusText);
}
}).then(data => {
}).catch((error) => {
console.log(error);
});
} |
var mapimg;
//center latitude and longtitude
var clat = 0;
var clon= 0;
// 37.5665° N, 126.9780° E (Seoul)
var lat = 37.5665;
var lon = 126.9780;
var zoom = 1;
var earthquakes;
function preload() {
mapimg = loadImage ('https://api.mapbox.com/styles/v1/mapbox/streets-v10/static/0,0,1,0,0/1024x512?access_token=pk.eyJ1IjoibWljaGVsbGVyIiwiYSI6ImNqbGZjeDVqMDB2bnMzcW8zYWh0Ymc4eDUifQ.BvHbebOok873xRy90ZMYhA')
earthquakes = loadStrings ('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.csv');
}
function mercX(lon) {
lon = radians(lon);
var a = (256 / PI) * pow(2,zoom);
var b = lon + PI;
return a*b;
}
function mercY(lat) {
lat = radians(lat);
var a = (256 / PI) * pow(2,zoom);
var b = tan(PI/4+lat/2);
var c = PI - log(b);
return a*c;
}
function setup() {
createCanvas(1024,512);
translate(width/2, height/2);
imageMode(CENTER);
image(mapimg,0,0);
var cx - mercX(clon);
var cy = mercY(clat);
for (var i = 0; i < earthquakes.length; i++) {
var data = earthquakes[i].split(/,/);
console.log(data);
var lat = data[1];
var lon = data[2];
var mag = data[4];
var x = mercX(lon) - cx;
var y = mercY(lat) - cy;
mag = pow(10,mag);
mag = sqrt(mag);
var magmax = sqrt(pow(10,10));
var d = map(mag, 0, magmax, 0, 80);
stroke(255,0,255);
fill(255,0,255,200);
ellipse(x,y,10,10);
}
}
|
//var loaderUtils = require("loader-utils");
/**
* [ 语法转换 ]
* @Author freemenL
* @DateTime 2018-10-25T09:59:02+0800
* @param {[type]} source [description]
* @return {[type]} [description]
*/
function replace(source) {
let template = "import React,{Component,PureComponent,Fragment} from 'react';";
let reg = new RegExp(/\/\/@react/,"g");
return source.replace(reg,template);
}
module.exports = function(source) {
return replace(source);
};
|
const express = require('express')
const Product = require('../models/product')
const router = express.Router()
router.get('/:id', async (req, res) => {
/**
* /GET endpoint
* Retrieve a particular Product data
*/
try {
const product = await Product
.findById(req.params.id)
.select('-__v')
.exec()
res.json(product)
}
catch (err){
res.json({message: err})
}
})
/**
* TODO('Not Implemented')
*/
router.put('/:id', () => {})
router.delete('/:id', () => {})
module.exports = router |
var React = require('react');
var connectToStores = require('alt/utils/connectToStores');
var ErrorDialog = require('./utils/ErrorDialog');
var Router = require('react-router');
var getErrorNotification = function(ErrorActions, ErrorStore) {
var errorNotification = React.createClass({
propTypes: {
errors: React.PropTypes.arrayOf(React.PropTypes.instanceOf(Error)),
},
mixins: [ Router.Navigation ],
statics: {
getStores() {
return [ ErrorStore ];
},
getPropsFromStores() {
return ErrorStore.getState();
},
},
getDefaultProps: function() {
return {
errors: [ ],
};
},
onHide: function() {
ErrorActions.confirmError();
},
onConfirm: function() {
ErrorActions.confirmError();
},
render: function() {
var error = this.props.errors.length && this.props.errors[this.props.errors.length - 1];
const dialog = error ? (<ErrorDialog title="Virhe!" onHide={ this.onHide } onConfirm={ this.onConfirm } error={ error } />) : '';
return (
<div>{ dialog }</div>
);
},
});
return connectToStores(errorNotification);
};
module.exports = getErrorNotification;
|
var dealer = {};
dealer.add = function(args){
var endpoint = "services/dealer.php";
var method = "POST";
utility.data(endpoint,method,args,function(data){
var response = JSON.parse(data);
console.debug(response);
alert(response.result);
control.pagetab('dealer-manager.html');
});
}
dealer.edit = function(args){
var endpoint = "services/dealer.php";
var method = "POST";
utility.data(endpoint,method,args,function(data){
var response = JSON.parse(data);
console.debug(response);
alert(response.result);
control.pagetab('dealer-manager.html');
});
}
dealer.delete = function(){
console.log('call delete');
var endpoint = "services/dealer.php";
var method = "POST";
var args = "";
$('input[name="mark[]"]:checked').each(function(){
var id = $(this).attr('data-id');
args = {'_':new Date().getMilliseconds(),'type':'del' , 'id':id};
utility.service(endpoint,method,args,function(){
$('#row'+id).remove();
});
console.log('delete id='+id);
});
alert('DELETE SUCCESS.');
dealer.loadlist();
}
dealer.reset = function(){
$('#title_th').val('');
$('#title_en').val('');
}
dealer.loaditem = function(id){
$('#id').val(id);
var endpoint = "services/dealer.php";
var method = "GET";
var args = {'_':new Date().getMilliseconds(),'type':'item','id':id};
utility.service(endpoint,method,args,set_view_item);
}
dealer.load = function(){
var endpoint = "services/dealer.php";
var method = "GET";
var args = {'_':new Date().getMilliseconds(),'type':'page'};
utility.service(endpoint,method,args,set_view);
}
dealer.loadlist = function(){
var endpoint = "services/dealer.php";
var method = "GET";
var args = {'_':new Date().getMilliseconds(),'type':'list' ,'couter':$('#counter').val(),'fetch':'20' };
utility.service(endpoint,method,args,set_view_list);
}
function set_view(data){
console.log(data);
if(data.result==undefined) return;
//var item = data.result;
gallery.data = data.result;
$('#title_th').val(personal.data["org.title"].th);
$('#title_en').val(personal.data["org.title"].en);
}
function set_view_item(data){
if(data.result==undefined) return;
$('#title_th').val(data.result.title_th);
$('#title_en').val(data.result.title_en);
$('#province_th').val(data.result.province_th);
$('#province_en').val(data.result.province_en);
$('#zone_th').val(data.result.zone_th);
$('#zone_en').val(data.result.zone_en);
$('#mobile_th').val(data.result.mobile_th);
$('#mobile_en').val(data.result.mobile_en);
$('#link_th').attr('href',"../"+data.result.link_th);
$('#link_en').attr('href',"../"+data.result.link_en);
if(data.result["active"]=="1")
$('#active').prop('checked',true);
}
function set_view_list(data){
//console.debug(data);
var view = $('#data_list');
var item = "";
if(data.result==undefined || data.result=="") {
console.log("dealer-manager > list :: data not found.");
return;
}
var max_item = $('#counter').val();
$.each(data.result,function(i,val){
var param = '?id='+val.id;
var active = val.active == "1" ? "<span class='btn btn-success btn-sm'>Enable</span> ": "<span class='btn btn-danger btn-sm'>Disable</span>";
var date = val.update_date == null ? val.create_date : val.update_date;
item+="<tr id='row"+val.id+"'>";
item+="<td><input type='checkbox' name='mark[]' data-id='"+val.id+"' /></td>";
item+="<td>"+val.id+"</td>";
item+="<td>"+val.title_th+"</td>";
item+="<td>"+val.province_th+"</td>";
item+="<td>"+val.zone_th+"</td>";
item+="<td>"+val.mobile_th+"</td>";
item+="<td>"+ active +"</td>";
item+="<td><span class='btn btn-warning btn-sm' onclick=control.pagetab('dealer-edit.html','"+param+"') >แก้ไข</span></td>";
item+="</tr>";
max_item++;
});
$('#counter').val(max_item);
view.append(item);
}
|
export default class PromiseQueue {
constructor() {
this.queue = [];
this.add = this.add.bind(this);
this.resolve = this.resolve.bind(this);
}
add(item) {
this.queue.push(item);
}
resolve(initial) {
return this.queue.reduce((prev, curr) => {
return prev.then(curr);
}, Promise.resolve(initial))
}
} |
const { Sequelize, DataTypes, Model } = require('sequelize');
const sequelize = new Sequelize('licentaDB', 'root', '', {
dialect: 'mysql'
})
class Child extends Model {}
Child.init({
// Model attributes are defined here
id: {
type: DataTypes.NUMBER,
primaryKey: true
},
id_user: {
type: DataTypes.NUMBER,
foreignKey: true
},
id_parent: {
type: DataTypes.NUMBER,
foreignKey: true
},
id_class: {
type: DataTypes.NUMBER,
foreignKey: true
}
}, {
// Other model options go here
sequelize, // We need to pass the connection instance
modelName: 'Child', // We need to choose the model name
tableName: 'child',
timestamps: false
});
Child.prototype.details = async function() {
const user = await this.getUser();
return {
fullname: user.fullname(),
resultsPath: `/children/${this.id}/results`,
id: this.id
}
}
Child.prototype.fullname = async function() {
const user = await this.getUser();
return user.fullname();
}
Child.prototype.resultsFor = async function(gameId) {
const results = await this.getResults({ where: { id_game: gameId }});
return results.map((result) => {
return {
date: result.date,
score: result.scor
}
});
}
module.exports = Child;
|
export const React = {
createElement: function (tag, attrs, children) {
var element = document.createElement(tag);
for (let name in attrs) {
if (name && attrs.hasOwnProperty(name)) {
let value = attrs[name];
if (name === 'className') {
name = 'class';
}
if (value === true) {
element.setAttribute(name, name);
} else if (value !== false && value != null) {
element.setAttribute(name, value.toString());
}
}
}
for (let i = 2; i < arguments.length; i++) {
let child = arguments[i];
element.appendChild(
child.nodeType == null ?
document.createTextNode(child.toString()) : child);
}
return element;
}
};
// export const React = {
// createElement: function (tag, attrs, ...children) {
// // Custom Components will be functions
// if (typeof tag === 'function') { return tag() }
// // regular html tags will be strings to create the elements
// if (typeof tag === 'string') {
// // fragments to append multiple children to the initial node
// const fragments = document.createDocumentFragment()
// const element = document.createElement(tag)
// children.forEach(child => {
// if (child instanceof HTMLElement) {
// fragments.appendChild(child)
// } else if (typeof child === 'string') {
// const textnode = document.createTextNode(child)
// fragments.appendChild(textnode)
// } else {
// // later other things could not be HTMLElement not strings
// // console.log('not appendable', child);
// }
// })
// element.appendChild(fragments)
// // Merge element with attributes
// Object.assign(element, attrs)
// return element
// }
// }
// } |
var mongoose = require('mongoose');
var fs = require('fs');
var FILE_ENCODING = 'utf-8';
var EOL = '\n';
var config = require('./config.js');
module.exports = function(models){
var PASSWORD_MAXAGE = 864000000; // ten days
var COOKIE_NAME = 'clutter.loggedin';
stackables = {};
// login
stackables.login = function(req, res, callback) {
console.log('login attempt');
console.log(' name: ' + req.body.name);
console.log(' pass: ' + req.body.password);
var query = {'username':req.body.name};
stackables.getUser(query, function(err, user) {
console.log('receiving stackables.getUser response');
if (!err) {
if ( !('password' in user) ) {
callback({'error':'database error. no password on file'}, 500);
} else if ( user.password == req.body.password ) {
console.log('logged in as ' + req.body.name + '(' + user._id + ')');
try {
res.cookie(COOKIE_NAME, user._id, {
signed:true,
maxAge:PASSWORD_MAXAGE
});
callback(null, 200);
} catch(ex) {
console.log(ex);
callback({'error':ex}, 500);
}
} else {
callback({'error':'wrong password'}, 401);
}
} else {
callback({'error':'nonexistent username'}, 401);
}
});
};
stackables.logout = function(req, res, callback) {
console.log('logout');
try {
res.clearCookie(COOKIE_NAME);
callback(null);
} catch (ex) {
console.log(ex);
callback({'error':ex});
}
};
// @function isLoggedInAsAdmin
stackables.isLoggedInAsAdmin = function(req) {
if (!req) throw Error('stackables.getUserIdFromCookie(req) requires non-null argument');
return (req.signedCookies[COOKIE_NAME] == 'admin');
};
// @function isLoggedInAsUser
stackables.isLoggedInAsUser = function(req) {
if (!req) throw Error('stackables.getUserIdFromCookie(req) requires non-null argument');
return (req.signedCookies[COOKIE_NAME]);
};
// @function getUserIdFromCookie
stackables.getUserIdFromCookie = function(req) {
if (!req) throw Error('stackables.getUserIdFromCookie(req) requires non-null argument');
try {
return req.signedCookies[COOKIE_NAME];
} catch(ex) {
return null;
}
};
// Get user id from cookie and wrap in ObjectId object.
// @function getUserObjectIdFromCookie
stackables.getUserObjectIdFromCookie = function(req) {
try {
var id = stackables.getUserIdFromCookie(req);
return new mongoose.Types.ObjectId(id );
} catch(ex) {
console.log(ex);
return null;
}
};
// @function updateUser
stackables.updateUser = function(newData, callback) {
var id = newData._id;
delete newData._id;
models.User.findByIdAndUpdate(id, newData, function(err, data) {
if (!err) {
callback(null, data);
} else {
console.log(err);
callback({'error':'Unable to update user'}, null);
}
});
};
// Add a single stack
stackables.addStack = function(newData, callback) {
console.log('addStack');
console.log('name: ' + newData.name);
var newStack = new models.Stack(newData);
newStack.save(function(err, stack) {
if (!err) {
console.log('successfully added stack');
callback(null, stack);
} else {
console.log(err);
callback({'error':'Failed to add new stack'}, null);
}
});
};
// Update a single stack
stackables.updateStack = function(newData, callback) {
var id = newData._id;
delete newData._id;
models.Stack.findByIdAndUpdate(id, newData, function(err, data) {
if (!err) {
callback(null, data);
} else {
console.log(err);
callback({'error':'Unable to update stack'}, null);
}
});
};
// @function getAllStacks
stackables.getAllStacks = function(userId, callback) {
stackables.getUserById(userId, function(err, user) {
if (!err) {
// extract id array from user object
var idArray = [];
for (var i = 0; i < user.stacks.length; i++ ) {
idArray.push(user.stacks[i].stackId);
}
stackables.getStacksByIdArray(idArray, function(err, stacks) {
if (!err && stacks != null) {
callback(null, stacks);
} else {
callback({'error':'Unable to fetch stacks'}, null);
}
});
} else {
callback({'error':'Unable to get user from database.'}, null);
}
});
};
// @function getStacksByIdArray
stackables.getStacksByIdArray = function(idArray, callback) {
models.Stack.find({'_id': {$in:idArray}}, function(err, stacks) {
if (!err) {
// add isDeleted attr if missing
for(var i = 0; i < stacks.length; i++) {
if(!('isDeleted' in stacks[i])) {
stacks[i].isDeleted = false;
}
}
callback(null, stacks);
} else {
console.log(err);
callback({'error':'Unable to find stacks in database'}, null);
}
});
};
// @function getStackById
stackables.getStackById = function(id, callback) {
models.Stack.findById(id, function(err, data) {
if (!err) {
callback(null, data);
} else {
console.log(err);
callback({'error':'Unable to find stack in database'}, null);
}
});
};
// Add a single note
stackables.addNote = function(req, res) {
//req.body.createdby = stackables.getUserObjectIdFromCookie(req);
req.body.createdby = new mongoose.Types.ObjectId(req.user._id);
console.log('name: ' + req.body.name);
console.log('createdby: ' + req.body.createdby);
var newNote = new models.Note(req.body);
newNote.save(function(err, note) {
if (!err) {
console.log('successfully added note');
res.status(200).send(note);
} else {
console.log(err);
res.status(501).send({'error':err});
}
});
};
// Update a single note
stackables.updateNote = function(req, res) {
var noteId = req.body._id;
delete req.body._id;
// if empty, fill out createdby
if( !('createdby' in req.body) ) {
req.body.createdby = stackables.getUserObjectIdFromCookie(req);
}
console.log('name: ' + req.body.name);
console.log('createdby: ' + req.body.createdby);
console.log('deleted: ' + req.body.deleted);
models.Note.findByIdAndUpdate(noteId, req.body, function(err, doc) {
if (!err) {
console.log('successfully updated');
res.status(200).send(doc);
} else {
console.log(err);
res.status(501).send({'error':err});
}
});
};
// Fetch all non-deleted notes
// Recurse up to 5 times if db connection is not open.
stackables.getAllNotes = function(req, res, attempts) {
//var userObjectId = stackables.getUserObjectIdFromCookie(req);
//var userObjectId = new mongoose.Types.ObjectId(req.user._id);
var userObjectId = req.user._id;
var query = {'deleted':false, 'createdby':userObjectId};
console.log('get all notes created by ' + query.createdby);
models.Note.find( query,undefined,{sort:{'_id':1}}, function(err, notes) {
if(!err) {
console.log('Retrieved ' + notes.length + ' notes from mongo');
res.send(notes);
} else {
res.status(501);
res.send({'error':'Failed to retrieve data from database.'});
}
});
};
// get all archived notes
stackables.getAllArchivedNotes = function(req, res, attempts) {
var userObjectId = stackables.getUserObjectIdFromCookie(req);
var query = {'deleted':true, 'createdby':userObjectId};
console.log('get all notes created by ' + query.createdby);
models.Note.find( query,undefined,{sort:{'_id':1}}, function(err, notes) {
if(!err) {
console.log('Retrieved ' + notes.length + ' archived notes from mongo');
res.send(notes);
} else {
res.status(501);
res.send({'error':'Failed to retrieve data from database.'});
}
});
};
// get notes by stack id
stackables.getNotesByStackId = function(stackId, callback) {
console.log('Fetch notes in stack ' + stackId);
stackables.getStackById(stackId, function(err, stack) {
if (!err) {
console.log('Retrieved stack');
console.log(stack.notes);
stackables.getNotesByIdArray(stack.notes, function(err, notes) {
if (!err) {
var unarchivedNotes = [];
for (var i = 0; i < notes.length; i++) {
if(!notes[i].deleted) {
unarchivedNotes.push(notes[i]);
}
}
callback(null, unarchivedNotes);
} else {
callback(err, null);
}
});
} else {
callback(err, null);
}
});
};
// get notes by id array
stackables.getNotesByIdArray = function(idArray, callback) {
models.Note.find({'_id': {$in:idArray}},undefined,{sort:{'_id':1}}, function(err, notes) {
if (!err) {
callback(null, notes);
} else {
console.log(err);
callback({'error':'Unable to find notes in database'}, null);
}
});
};
// Get note from database
stackables.getNote = function(req, res, attempts) {
var id = req.query.id;
console.log('get note where _id = ' + id);
models.Note.findById( id, function(err, note) {
if(!err) {
console.log('Retrieved successfully!');
res.send(note);
} else {
res.status(501);
res.send({'error':'Failed to retrieve data from database.'});
}
});
}
//Get user from database by id
stackables.getUserById = function(id, callback) {
models.User.findById( id, {'username':true, 'email':true, 'colorScheme':true, 'stacks':true}, function(err, user) {
if(!err && user != null) {
callback(null,user);
} else {
callback({'error':'Failed to retrieve data from database'}, null);
}
});
};
//Get user from database with general query
stackables.getUser = function(query, callback) {
console.log('getUser');
models.User.findOne( query, function(err, user) {
console.log('models.User.findOne response');
if(!err && user != null) {
callback(null, user);
} else {
callback('Failed to retrieve user from database.', null);
}
});
};
return stackables;
};
|
(function() {
var item, _i, _len;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) {
for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor;
child.__super__ = parent.prototype;
return child;
};
describe("LineItem", function() {
beforeEach(function() {
return this.f = new LineItem;
});
it("shoudl have default value of 100 and quantity of 1", function() {
return expect(this.f.getTotalPrice()).toBe(100.00);
});
return it("calculated total price from quantity and item price", function() {
this.f.set({
quantity: 15,
price: 129.99
});
return expect(this.f.getTotalPrice()).toBe(1949.85);
});
});
describe("Invoice", function() {
beforeEach(function() {
return this.f = new Invoice;
});
it("sets the date to current date for newly created", function() {
var d;
d = new Date;
expect(this.f.get('date').getMonth).toBe(d.getMonth);
expect(this.f.get('date').getDay).toBe(d.getDay);
return expect(this.f.get('date').getFullYear).toBe(d.getFullYear);
});
it("should provide formatted date while calling formattedDate()", function() {
this.f2 = new Invoice({
date: new Date('2011-09-03')
});
return expect(this.f2.formattedDate()).toBe('03/09/2011');
});
describe('newly created line items array', function() {
it("should be size of 1", function() {
return expect(this.f.get('line_items').length).toBe(1);
});
return it("with the length of 1 should have item price = 100.00 and quantity = 1", function() {
expect(this.f.get('line_items')[0].get('price')).toBe(100.00);
return expect(this.f.get('line_items')[0].get('quantity')).toBe(1);
});
});
return describe('amount calculations', function() {
return it("should return correct price from all assigned line items", function() {
var items;
items = [
new LineItem({
quantity: 10,
price: 120
}), new LineItem({
quantity: 5,
price: 19.99
})
];
this.f.set({
line_items: items
});
return expect(this.f.getTotalPrice()).toBe(1299.95);
});
});
});
window.InvoicesDouble = (function() {
__extends(InvoicesDouble, Invoices);
function InvoicesDouble() {
InvoicesDouble.__super__.constructor.apply(this, arguments);
}
InvoicesDouble.prototype.localStorage = new Store("invoices-test");
return InvoicesDouble;
})();
window.invoices_test = new InvoicesDouble;
describe("Invoices", function() {
it("should be empty at first", function() {
return expect(invoices_test.length).toBe(0);
});
it("should save attributes successfully", function() {
var attrs;
attrs = {
number: '000001'
};
invoices_test.create(attrs);
return expect(invoices_test.length).toBe(1);
});
return it("should read attributes correctly from locastorage", function() {
return expect(invoices_test.first().get('number')).toBe('000001');
});
});
for (_i = 0, _len = invoices_test.length; _i < _len; _i++) {
item = invoices_test[_i];
item.destroy;
}
}).call(this);
|
const express = require('express');
const Film = require('./Film.js');
const router = express.Router();
// Return a list of all films. (/api/films)
router
.route('/')
.get((req, res) => {
const { producer, released } = req.query;
let query = Film.find()
.sort({ episode: 1 })
.select('episode title planets characters producer release_date')
.populate('characters', `_id name gender height skin_color hair_color eye_color`)
.populate('planets', `name climate terrain gravity diameter`)
if (producer !== undefined) {
const producerFilter = new RegExp(producer, 'i')
query.where({ producer: producerFilter })
}
if (released !== undefined) {
query.where({ release_date: { $regex: released, $options: 'i' }})
}
query.then( films => {
res.status(200).json(films);
})
query.catch( err => {
res.status(500).json({ error: 'Error getting films', err});
})
});
// * order by episode.
// * populate character information.
// * only include: `_id, name, gender, height, skin_color, hair_color and eye_color`.
// * populate planets, include: `name, climate, terrain, gravity and diameter`.
// Find all films produced by _Gary Kurtz_ (/api/films?producer=gary+kurtz)
// Find all films released in _2005_. (/api/films?released=2005)
module.exports = router;
|
const db = require('../../utils/db')
const app = getApp()
Page({
/**
* Page initial data
*/
data: {
movie: {}
},
/**
* Lifecycle function--Called when page load
*/
onLoad: function (options) {
if (options.id) {
this.getMovie(options.id)
}
},
viewReviews () {
wx.navigateTo({
url: '/pages/reviews/reviews?movieId=' + this.data.movie._id,
})
},
addReviewTapped (){
if (this.data.movie.hasReview) {
let reviewId = this.data.movie.reviewId
wx.navigateTo({
url: '/pages/reviews/show/show?id=' + reviewId,
})
} else {
this.askForReviewType()
}
},
askForReviewType() {
wx.setStorage({
key: 'movie',
data: this.data.movie
})
if (!app.globalData.userInfo) {
wx.navigateTo({
url: '/pages/me/me',
})
return
}
wx.showActionSheet({
itemList: ['文字', '音频'],
success(res) {
if (res.tapIndex === 0) {
wx.navigateTo({
url: '/pages/reviews/new/new'
})
} else {
wx.navigateTo({
url: '/pages/reviews/new/new?audio=true'
})
}
},
fail(res) {
console.log(res.errMsg)
}
})
},
getMovie(id) {
wx.showLoading({
title: 'Loading...',
})
db.getMovie(id).then(res => {
wx.hideLoading()
//console.log(result)
const movie = res.result
if (movie) {
if (movie.desc.length > 100) {
movie.desc = movie.desc.substr(0, 100) + '...'
}
this.setData({
movie
})
}
}).catch(err => {
console.error(err)
wx.hideLoading()
})
}
}) |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var whoAreYou = function whoAreYou(person) {
var currentYear = new Date().getFullYear();
var age = currentYear - person.yearOfBirth;
var retString = "\n My name is " + person.name + " " + person.lastName + ".\n I am " + age + " years old.\n My proffesion is " + person.proffesion;
return retString;
};
var person = {
name: "Vlad",
lastName: "Drăculea",
yearOfBirth: 1999,
proffesion: "Lord of Wallachia"
};
var ret = whoAreYou(person);
console.log(ret);
// zadanie1
var num1 = 2;
var num2 = 4;
var sum = num1 + num2;
console.log("\nSuma dw\xF3ch liczb " + num1 + " i " + num2 + " to: " + sum);
// zadanie2
var name = 'Ania';
console.log("\nMoje imi\u0119 i nazwisko to: " + name + " Ma\u0142a");
// zadanie3
var sentence = "\"My\u015Bl\u0119, \u017Ce jest wiele pi\u0119kna\nw posiadaniu problem\xF3w.\nTo jeden ze sposob\xF3w w jaki si\u0119 uczymy\"\nHerbie Hancock";
var tekst = function tekst(sentence) {
console.log(sentence);
$('.cite').text(sentence);
};
tekst(sentence);
// zadanie4
var arr1 = ["Ania", "Ola", "Kasia"];
var fnArr = function fnArr(array) {
var arr2 = [].concat(_toConsumableArray(array));
return arr2;
};
// console.log(fnArr(arr1));
console.log("" + fnArr(arr1));
// zadanie5
function zadanie5() {
var button = {
value: "Send message",
idName: "sendMsg",
width: "100px",
padding: "20px"
};
console.log("\n To jest button.\n Jego szeroko\u015B\u0107 to " + button.width + ".\n Napis, kt\xF3ry na nim widnieje to \"" + button.value + "\"");
var button2 = {
value: "Change message",
idName: "chngMsg",
width: "200px",
padding: "80px"
};
$('.cite').after($('<button>', { id: "" + button2.idName }).css('width', "" + button2.width).css('padding', "" + button2.padding));
}
zadanie5();
/***/ })
/******/ ]); |
$(document).ready(function() {
var n = [0];
var failSafe = true;
// $(".display").text();
function display(str) {
$(".display").text(str);
}
function blurDisplay(str) {
$(".blur-display").text(str);
}
function lastTerm(arr) {
return arr.length - 1;
}
function checkLenOfNum() {
if (parseFloat(n[lastTerm(n)]) > 999999) {
$(".display").css("font-size", "25px");
return;
}
}
// Take integer input from the user
$(".integer div").click(function() {
if (failSafe) {
if (n.length >= 1) {
$("#AC").text("C");
}
n[lastTerm(n)] = parseFloat($(this).text());
if (parseFloat($(".display").text()) != 0) {
n[lastTerm(n)] = (parseFloat($(".display").text() + n[lastTerm(n)]));
}
checkLenOfNum();
display(n[lastTerm(n)]);
console.log(n);
}
});
// Take operator input from the user
$(".operator").click(function() {
$(".display").css("font-size", "75px");
var str = "";
if ($(this).text() != "=") {
failSafe = true;
let operator = $(this).text();
blurDisplay(n[lastTerm(n)]);
if (operator == "×") {
operator = "*";
} else if (operator == "÷") {
operator = "/";
}
n.push(operator, 0);
console.log(operator);
display(0);
checkLenOfNum();
} else {
for (i in n) {
str += n[i];
}
var ans = eval(str);
n = [ans];
failSafe = false;
}
$("#AC").text("AC");
blurDisplay(ans);
display(ans);
});
$(".other-operator").click(function() {
if (failSafe) {
let otherOperator = $(this).text();
if (otherOperator == "±") {
n[lastTerm(n)] = parseFloat($(".display").text()) * (-1);
}
if (otherOperator == "%") {
console.log("divide");
blurDisplay(n[lastTerm(n)]);
display(0);
n.push("*", 100, "/", 0);
failSafe = true;
}
}
});
// Clear button
$("#AC").click(function() {
$(".display").css("font-size", "75px");
if ($(this).text() != "C") {
console.log(n);
location.reload();
}
$(this).text("AC");
n[lastTerm(n)] = 0;
display(0);
});
}); |
import React, { Component } from 'react';
import { Link, NavLink, Route, Switch, withRouter } from 'react-router-dom';
import '../../../node_modules/bootstrap/dist/js/bootstrap.js';
import { GameService } from '../../service';
import Games from '../Game/listgames';
class Home extends Component {
constructor(props) {
super(props);
this.state = {
specialOffer: [],
};
}
render() {
return (
<div className={'bg-dark'}>
<div
id={'carouselExampleIndicators'}
className={'carousel slide'}
data-ride="carousel"
>
<ol className={'carousel-indicators'}>
<li
data-target={'#carouselExampleIndicators'}
data-slide-to={'0'}
className={'active'}
></li>
<li
data-target={'#carouselExampleIndicators'}
data-slide-to="1"
></li>
<li
data-target={'#carouselExampleIndicators'}
data-slide-to="2"
></li>
</ol>
<div className={'carousel-inner'}>
<div className={'carousel-item active'}>
<img
className={'m-auto d-block'}
style={{ height: 40 + 'em', width: 80 + 'em' }}
src={
'https://cdn.cloudflare.steamstatic.com/apps/dota2/images/dota2_social.jpg'
}
alt={'First slide'}
/>
</div>
<div className={'carousel-item'}>
<img
className={'m-auto d-block'}
style={{ height: 40 + 'em', width: 80 + 'em' }}
src="https://www.gametutorials.com/wp-content/uploads/2020/08/cs-go-1170x600.jpg"
alt="Second slide"
/>
</div>
<div className={'carousel-item'}>
<img
className={'m-auto d-block'}
style={{ height: 40 + 'em', width: 80 + 'em' }}
src={
'https://n9e5v4d8.ssl.hwcdn.net/images/longlanding/warframe-metacard.png'
}
alt={'Third slide'}
/>
</div>
</div>
<a
className={'d-flex align-self-end w-25 carousel-control-prev'}
href={'#carouselExampleIndicators'}
role={'button'}
data-slide={'prev'}
>
<span
className={'carousel-control-prev-icon'}
aria-hidden={'true'}
></span>
<span className={'sr-only'}>Previous</span>
</a>
<a
className={'d-flex align-self-baseline w-25 carousel-control-next'}
href={'#carouselExampleIndicators'}
role={'button'}
data-slide={'next'}
>
<span
className={'carousel-control-next-icon'}
aria-hidden={'true'}
></span>
<span className={'sr-only'}>Next</span>
</a>
</div>
<div className={'m-3 p-4'}>
<div className={'row'}>
<div className={'col-md-2'}>
<h4 className={'h4 text-white'}>Special Offer</h4>
</div>
</div>
<div className={'row'}>
<div className={'col-md-10 offset-1'}>
<div className={'d-flex flex-row justify-content-around'}>
{this.state.specialOffer.map((game) => {
return (
<div className={'card'} style={{ width: 18 + 'rem' }}>
<img
className={'card-img-top'}
src={
'https://upload.wikimedia.org/wikipedia/en/thumb/a/a5/Grand_Theft_Auto_V.png/220px-Grand_Theft_Auto_V.png'
}
alt={'Gta v'}
style={{ height: 15 + 'rem' }}
/>
<div className={'card-body'}>
<h5 className={'card-title'}>{game.title}</h5>
<div
className={'d-flex flex-row justify-content-between'}
>
<Link
onClick={() => this.props.handleGameSelect(game)}
to={`/games/${game.id}`}
className={'btn btn-primary px-3 p-2'}
>
visit
</Link>
<h3>{game.price}</h3>
</div>
</div>
</div>
);
})}
</div>
</div>
</div>
</div>
<div className={'row'}>
<div className={'col-md-10 offset-1'}>
<ul className={'nav nav-tabs'}>
<li className={'nav-item'}>
<NavLink
className={'nav-link text-white'}
activeClassName={'active text-dark'}
to={`${this.props.match.url}/popular`}
>
Popular
</NavLink>
</li>
<li className={'nav-item'}>
<NavLink
className={'nav-link text-white'}
activeClassName={'active text-dark'}
to={`${this.props.match.url}/special`}
>
Special Offer
</NavLink>
</li>
<li className={'nav-item'}>
<NavLink
className={'nav-link text-white'}
activeClassName={'active text-dark'}
to={`${this.props.match.url}/alphabetical`}
>
Alphabetical
</NavLink>
</li>
</ul>
<div>
<Switch>
<Route path={`${this.props.match.path}/popular`}>
<Games handleGameSelect={this.props.handleGameSelect} />
</Route>
<Route path={`${this.props.match.path}/special`}>
<Games handleGameSelect={this.props.handleGameSelect} />
</Route>
<Route path={`${this.props.match.path}/alphabetical`}>
<Games handleGameSelect={this.props.handleGameSelect} />
</Route>
</Switch>
</div>
</div>
</div>
</div>
);
}
componentDidMount() {
this.loadAllGames();
}
loadAllGames = () => {
GameService.fetchGames().then((data) => {
this.setState({
specialOffer: data.data.filter((v, i) => i < 4),
});
});
};
}
export default withRouter(Home);
|
angular.module('myApp');
myApp.controller('courseController', function ($scope, $http, $route, courseFactory, $location, $routeParams, $log, uiGmapGoogleMapApi) {
$scope.index = function () {
$location.url('/');
}
function titleCase(str) {
str = str.toLowerCase().split(' ');
for(var i = 0; i < str.length; i++){
str[i] = str[i].split('');
str[i][0] = str[i][0].toUpperCase();
str[i] = str[i].join('');
}
return str.join(' ');
}
//Initiate Google Map
$scope.map = {
center: {
latitude: 47.608013,
longitude: -122.335167
},
zoom: 10,
window: {
marker: {},
show: false,
closeClick: function() {
$(".distanceToMarker").empty();
$(".zoomBtn").css('visibility', 'hidden');
this.show = false;
},
options: {}
}
};
//Initiate Marker Array
$scope.map.markers = [];
var image = "../../static/golf.png";
courseFactory.getCourses($routeParams, function (data) {
$scope.courses = data;
$scope.markers = [];
//Longest Course
$scope.maxYardage;
var maxYardage = 0;
for(var i = 0; i < $scope.courses.length; i++){
if($scope.courses[i].yardage > maxYardage){
maxYardage = $scope.courses[i].yardage;
$scope.maxYardage = $scope.courses[i];
}
}
//Highest USGA Course Rating
$scope.maxRating;
var maxRating = 0;
for(var i = 0; i < $scope.courses.length; i++){
if($scope.courses[i].course_rating > maxRating){
maxRating = $scope.courses[i].course_rating;
$scope.maxRating = $scope.courses[i];
}
}
//Highest USGA Slope
$scope.maxSlope;
var maxSlope = 0;
for(var i = 0; i < $scope.courses.length; i++){
if($scope.courses[i].slope > maxSlope){
maxSlope = $scope.courses[i].slope;
$scope.maxSlope = $scope.courses[i];
}
}
//Set Marker Coordinates
for (var i = 0; i < $scope.courses.length; i++) {
var location = {
courseName: $scope.courses[i].course,
latitude: $scope.courses[i].latitude,
longitude: $scope.courses[i].longitude
}
$scope.markers.push(location);
}
//Generate Markers
for (var j = 0; j < $scope.markers.length; j++) {
var latitude = $scope.markers[j].latitude;
var longitude = $scope.markers[j].longitude;
var courseName = $scope.markers[j].courseName
var marker = {
id: j,
coords: {
latitude: latitude,
longitude: longitude,
},
options: {
draggable: false,
title: courseName,
icon: image
},
events: {
click: function(marker, eventName, model){
$(".distanceToMarker").empty();
$(".zoomBtn").css('visibility', 'visible');
var lat = this.coords.latitude;
var lon = this.coords.longitude;
$scope.map.window.coords = this.coords;
$scope.selectedCourse = this.options.title;
var apiCall = 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat.toString() + '&lon=' + lon.toString() + '&APPID=1d197f40a63bcada712bde3f3fb0d51a&units=imperial';
$http.get(apiCall).then(function (data){
$scope.weather = data;
$scope.temp = $scope.weather.data.main.temp;
$scope.wind = $scope.weather.data.wind.speed;
$scope.forecast = titleCase($scope.weather.data.weather[0].description);
})
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$(".distanceToMarker").html(convertToMiles(gc(position.coords.latitude,position.coords.longitude,lat,lon)).toFixed(2) + " Miles From Current Location");
console.log(convertToMiles(gc(position.coords.latitude,position.coords.longitude,lat,lon)).toFixed(2))
});
}
$scope.map.window.show = true;
}
}
}
$scope.map.markers.push(marker);
}
});
$scope.zoomIn = function() {
$(".zoomBtn").css('visibility', 'hidden');
$scope.map = {
center: {
latitude: $scope.map.window.coords.latitude,
longitude: $scope.map.window.coords.longitude
},
zoom: 15,
window: {
marker: {},
show: false,
closeClick: function() {
$(".distanceToMarker").empty();
$(".zoomBtn").css('visibility', 'hidden');
this.show = false;
},
options: {}
},
markers: $scope.map.markers
};
}
//Get Coordinates To Set Map Center
$scope.getCoords = function() {
courseFactory.getCoords($scope.address, function (coords) {
if(jQuery.isEmptyObject(coords)) {
console.log("no Zip")
} else {
$scope.address = coords;
$scope.map.center = {
latitude: $scope.address[0].latitude,
longitude: $scope.address[0].longitude
}
$scope.address = {};
}
})
}
$scope.showList = function() {
$location.url('/showList')
}
}); |
({
block: 'menu',
mods: { section: 'learning' },
content: [
{ elem: 'title', content: 'Обучение' },
{
elem: 'list',
content: [
{ elem: 'item', url: '/learn_map', title: 'Карта обучения' },
{ elem: 'item', url: '/courses', title: 'Онлайн-курсы' },
{ elem: 'item', url: '/intensive', title: 'Интенсив' },
{ elem: 'item', url: '/pricing', title: 'Подписка' },
{ elem: 'item', url: '/rating', title: 'Рейтинг' }
]
}
]
});
|
/*
* @lc app=leetcode id=152 lang=javascript
*
* [152] Maximum Product Subarray
*/
/**
* @param {number[]} nums
* @return {number}
*/
var maxProduct = function(nums) {
if (nums.length < 2) {
return nums[0];
}
let result = nums[0];
let max = nums[0];
let min = nums[0];
for (let i = 1; i < nums.length; i++) {
let preMax = max;
max = Math.max(nums[i], max * nums[i], min * nums[i]);
min = Math.min(nums[i], preMax * nums[i], min * nums[i]);
(max > result) && (result = max);
}
return result;
};
maxProduct([2,3,-2,4]);
|
import Link from 'next/link';
const Navbar = () => {
return (
<nav className="black">
<div className="nav-wrapper">
<div className="container">
<Link href='/'>
<a className="brand-logo left">
GraphQL | <span className="red-text">Resume</span>
</a>
</Link>
<ul className="right">
<li>
<Link href='/about'>
<a>
About
</a>
</Link>
</li>
</ul>
</div>
</div>
</nav>
)
}
export default Navbar
|
import React, { Fragment } from 'react'
import { NavLink, withRouter } from 'react-router-dom'
import { signout, isAuthenticated } from '../auth/helper/index'
import { useHistory } from 'react-router'
const Navigation = () => {
const history = useHistory()
return (
<div>
<ul className="nav nav-tabs bg">
<li className="nav-item">
<NavLink className="nav-link" to="/" exact>Home</NavLink>
</li>
<li className="nav-item">
<NavLink className="nav-link" to="/cart">Cart</NavLink>
</li>
{isAuthenticated() && isAuthenticated().user.role === 0 && (
<li className="nav-item">
<NavLink className="nav-link" to="/user/dashboard">User Dashboard</NavLink>
</li>
)}
{isAuthenticated() && isAuthenticated().user.role === 1 && (
<li className="nav-item">
<NavLink className="nav-link" to="/admin/dashboard">Admin Dashboard</NavLink>
</li>
)}
{!isAuthenticated() && (
<Fragment>
<li className="nav-item">
<NavLink className="nav-link" to="/signup">Sign Up</NavLink>
</li>
<li className="nav-item">
<NavLink className="nav-link" to="/signin">Sign In</NavLink>
</li>
</Fragment>
)}
{isAuthenticated() && (
<li className="nav-item">
<span className="nav-link text-warning"
onClick={() => {
signout(() => {
history.push('/')
})
}}>
Sign Out
</span>
</li>
)}
</ul>
</div>
)
}
export default withRouter(Navigation)
|
FV = new formValidator();
/**
* Clase con distintos metodos de ayuda de validación de formularios
* Solo aplica los patrones y funciones, no aplica el estilo.
* El estilo se aplica en CSS3 (Ej: input:valid{})
* @returns {formValidator}
*/
function formValidator() {
//privados
/**
* A través del patron ya nos encargamos que HTML5 lo valide automaticamente
* @param {String} id
* @param {String} expresion
* @returns {undefined}
*/
function addValidacionExpress(id, expresion) {
var campo = document.getElementById(id);
campo.pattern = expresion;
}
/**
* SIN ACABAR
* Para campos que no tienen patrones
* @param {String} idCampo
* @param {String} idForm
* @param {function (Input)} funcion Function que devulve true
* en caso de estar correcto el campo y false en caso contrario
* @returns {undefined}
*/
function addValidacionFuncionInput(idCampo, idForm, funcion) {
var campo = document.getElementById(idCampo);
campo.addEventListener("input", function () {
if (funcion(campo)) {
campo.style.borderColor = "green";
campo.style.backgroundColor = "inherit";
} else {
campo.style.borderColor = "red";
campo.style.backgroundColor = "coral";
}
});
campo.addEventListener("blur", function () {
if (!funcion(campo)) {
campo.style.borderColor = "inherit";
campo.style.backgroundColor = "inherit";
}
});
campo.addEventListener("focus", function () {
if (!funcion(campo)) {
campo.style.borderColor = "red";
campo.style.backgroundColor = "coral";
}
});
var form = document.getElementById(idForm);
form.addEventListener("submit", function (ev) {
if (!funcion(campo)) {
ev.preventDefault();
alert("Rellena el campo "+campo.id);
}
});
}
/**
* SIN ACABAR
* Para campos que no tienen patrones
* @param {String} idDiv
* @param {String} idForm
* @param {function (Input)} funcion Function que devulve true
* en caso de estar correcto el campo y false en caso contrario
* @returns {undefined}
*/
function addValidacionFuncionDiv(idDiv, idForm, funcion) {
var div = document.getElementById(idDiv);
div.addEventListener("mouseover", function () {
if (funcion(div)) {
div.style.borderColor = "green";
div.style.backgroundColor = "inherit";
}else{
div.style.borderColor = "red";
div.style.backgroundColor = "coral";
}
});
div.addEventListener("mouseout", function () {
if (funcion(div)) {
div.style.borderColor = "green";
div.style.backgroundColor = "inherit";
}else{
div.style.borderColor = "inherit";
div.style.backgroundColor = "inherit";
}
});
var form = document.getElementById(idForm);
form.addEventListener("submit", function (ev) {
if (!funcion(div)) {
ev.preventDefault();
alert("Rellena el campo "+div.id);
}
});
}
//publicos
/**
* Añade una validacion en linea a un campo de tipo email
* @param {String} id Id del imput Email
* @returns {undefined}
*/
this.addValidarEmail = function (id) {
addValidacionExpress(id, "^\\w+([/\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,4})+$");
};
/**
* Añade una validacion en linea a un campo de Codigo Postal
* @param {String} id
* @returns {undefined}
*/
this.addValidarCP = function (id) {
addValidacionExpress(id, "^([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}$");
};
/**
* Añade una validacion en linea a un campo de teléfono
* @param {String} id
* @returns {undefined}
*/
this.addValidarTelf = function (id) {
addValidacionExpress(id, "^\\+?\\d{1,3}?[- .]?\\(?(?:\\d{2,3})\\)?[- .]?\\d\\d\\d[- .]?\\d\\d\\d\\d$");
};
/**
* Añade una validacion en linea a un campo de Tarjeta de crédito
* @param {String} id
* @returns {undefined}
*/
this.addValidarCreditCard = function (id) {
addValidacionExpress(id, "^((67\\d{2})|(4\\d{3})|(5[1-5]\\d{2})|(6011))(-?\\s?\\d{4}){3}|(3[4,7])\\ d{2}-?\\s?\\d{6}-?\\s?\\d{5}$");
};
/**
* Añade una validacion en linea a un campo de URL
* @param {String} id
* @returns {undefined}
*/
this.addValidarUrl = function (id) {
addValidacionExpress(id, "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\?=.-]*)*\\/?$");
};
/**
* Añade una validacion en linea a un campo de password para
* verificar su fortaleza
* @param {String} id
* @returns {undefined}
*/
this.addValidarPassword = function (id) {
addValidacionExpress(id, "^[a-zA-Z0-9]{5,15}$");
};
/**
* Añade una validacion en linea a un campo de nombre de usuario
* @param {String} id
* @returns {undefined}
*/
this.addValidarNick = function (id) {
addValidacionExpress(id, "^[a-zA-Z0-9\\d_]{3,15}$");
};
/**
* Añade una validacion a un campo de tipo dni
* @param {String} idCampo
* @param {String} idForm
* @returns {undefined}
*/
this.addValidarDNI = function (idCampo, idForm) {
addValidacionFuncionInput(idCampo, idForm, function (campo) {
var dni = campo.value;
var numero = dni.substr(0, dni.length - 1);
var let = dni.substr(dni.length - 1, 1);
numero = numero % 23;
var letra = 'TRWAGMYFPDXBNJZSQVHLCKET';
letra = letra.substring(numero, numero + 1);
if (letra !== let) {
return false;
} else {
return true;
}
});
};
/**
* Añade una validacion a un campo div con drag and drop
* @param {String} idDiv
* @param {String} idForm
* @returns {undefined}
*/
this.addValidarDragAndDrop = function (idDiv, idForm) {
addValidacionFuncionDiv(idDiv, idForm, function (campo) {
var backg = campo.style.backgroundImage;
if (backg === "") {
return false;
} else {
return true;
}
});
};
}
/**
* Añade la función drag and drop a un div para una imagen
* @param {String} id El identificador de un DIV
* @returns {undefined}
*/
function addDragAndDropImage(id) {
var caja = document.getElementById(id);
caja.style.backgroundRepeat = "no-repeat";
caja.style.backgroundSize = "cover";
caja.style.backgroundPosition = "center";
caja.addEventListener('dragover', permitirDrop, false);
caja.addEventListener('drop', drop, false);
function drop(ev) {
ev.preventDefault();
var arch = new FileReader();
arch.addEventListener('load', leer, false);
arch.readAsDataURL(ev.dataTransfer.files[0]);
}
function permitirDrop(ev) {
ev.preventDefault();
}
function leer(ev) {
caja.style.backgroundImage = "url('" + ev.target.result + "')";
}
} |
this["JST"] = this["JST"] || {};
this["JST"]["app/scripts/templates/profile_info.ejs"] = function(obj) {
obj || (obj = {});
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
with (obj) {
__p += ' <div class="right col-sm-8 right-top-block">\n <div class="col-sm-3 namesurname">' +
((__t = ( profileInfo.name )) == null ? '' : __t) +
' ' +
((__t = ( profileInfo.last_name )) == null ? '' : __t) +
'</div>\n <div class="col-sm-6 namesurname2">Deals</div>\n </div>\n <div class="right col-sm-8 right-top-block" style="background-color: #fff;">\n <div class="right-top">\n <div class="col-sm-4 table1" >\n <table class="table borderless">\n <tr>\n <td>Phone:</td>\n ';
_.each(profileInfo.phone, function (phone) { ;
__p += '\n <td>' +
((__t = ( phone.value )) == null ? '' : __t) +
'</td>\n ';
}); ;
__p += '\n </tr>\n <tr>\n <td>Email:</td>\n ';
_.each(profileInfo.email, function (email) { ;
__p += '\n <td>' +
((__t = ( email.value )) == null ? '' : __t) +
'</td>\n ';
}); ;
__p += '\n </tr>\n <tr>\n <td>Added:</td>\n <td>' +
((__t = ( new Date(profileInfo.add_time).toLocaleDateString("en-us", { year: "numeric", month: "short", day: "numeric"}) )) == null ? '' : __t) +
'</td>\n </tr>\n <tr>\n <td>Open Deals:</td>\n <td>' +
((__t = ( profileInfo.open_deals_count )) == null ? '' : __t) +
'</td>\n </tr>\n <tr>\n <td>Next Activity:</td>\n <td> ' +
((__t = ( activityData.nextActivity )) == null ? '' : __t) +
', ' +
((__t = ( new Date(profileInfo.next_activity_date).toLocaleDateString("en-us", { year: "numeric", month: "short", day: "numeric"}) )) == null ? '' : __t) +
'</td>\n </tr>\n <tr>\n <td>Last Activity:</td>\n <td> ' +
((__t = ( activityData.lastActivity )) == null ? '' : __t) +
', ' +
((__t = ( profileInfo.last_activity_date )) == null ? '' : __t) +
'</td>\n </tr>\n \n </table>\n </div>\n <div class="col-sm-6 table2">\n <table class="table table-striped table-bordered">\n <thead>\n <th>Title</th>\n <th>Sum</th>\n </thead>\n <tbody>\n ';
_.each(deals, function (deal) { ;
__p += '\n <tr>\n <td>' +
((__t = ( deal.title)) == null ? '' : __t) +
'</td>\n <td>' +
((__t = ( deal.formatted_value)) == null ? '' : __t) +
'</td>\n </tr>\n ';
}); ;
__p += '\n </tbody>\n </table>\n </div>\n </div>\n </div>';
}
return __p
};
this["JST"]["app/scripts/templates/user.ejs"] = function(obj) {
obj || (obj = {});
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
with (obj) {
__p += '\n\n\n';
_.each(userInfos, function (userInfo) { ;
__p += '\n <li class="list-group-item profile-list" data-profile-id=' +
((__t = ( userInfo.id )) == null ? '' : __t) +
'><strong>' +
((__t = ( userInfo.name )) == null ? '' : __t) +
' ' +
((__t = ( userInfo.last_name )) == null ? '' : __t) +
'</strong><p>' +
((__t = ( userInfo.org_name )) == null ? '' : __t) +
'</p></li>\n';
}); ;
__p += '\n';
}
return __p
}; |
// A VERY IMPORTANT THING ABOUT RETURN,VARIABLE_FUNCTIONS,AND ANOYMOUS FUNCS(EEFI TOO)
var John =(function(){ // A PRIVATE FUNCTION WHO'S ELEMENTS CAN'T BE ACCESSED OUTSIDE IT'S SCOPE CHAIN
var number = 245
return{ // THE VARIABLE JOHN IS RETURNING :- return RETURNS the main value
ans:function(x){ // A METHOD 'ans' WHICH GIVES 'number+x'
console.log(number+x)
}
}
})();
John.ans(3)
// In short John = A value
//RETURN IS 'RETURNING' THE MAIN VALUE |
import React from "react"
export default class Intro extends React.Component
{
render()
{
return (
<div class="columns" style={{marginBottom:'3rem'}}>
<div class="column is-narrow"></div>
<div class="column is-6 content">
<p>
Electronic mail is much older than ARPANET or the Internet. It was never invented; it evolved from very simple beginnings. Going through the history of email has several benefits. First of all, email is one of the popular and longest standing creations of the internet. There are around 3.8 billion email users today and around 293 billion emails gets sent every day globally. There were several attempts to “kill” email. However, the celebrated email alternatives either died down or just didn’t replace email. Despite all the challenges, email still goes strong and is the preferred business communication medium.
</p>
<p>
Early email was just a small advance on what we know these days as a file directory - it just put a message in another user's directory in a spot where they could see it when they logged in. As simple as that. Just like leaving a note on someone's desk.
</p>
<p>
Electronic mail on individual computers had been in existence for nearly a decade before 1971. This form of communication, referred to as "intra-computer email" allowed user communities on solitary, time-shared computers to trade messages with one another. Intra-computer email did not proliferate over any kind of network; it was limited to serving the user population of a single machine. Intra-computer email was "popular among those who were regular time-shared computer users.
</p>
<p>
The email as we know today, had it humble beginning when there was an effort to send messages across the ARPANET network. Let us start from that point - from the beginnings of network email.
</p>
</div>
</div>
);
}
} |
/*
* Extends knockout by adding extra bindings for elements
*/
(function (knockout, $) {
/*
* Usage : <input type='text' data-bind='date: modelProperty' />
*/
ko.bindingHandlers.date = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var value = valueAccessor();
var date = ko.unwrap(value);
$(element)
.attr('data-provide', "datepicker")
.attr('readonly', "") // Prevents the user from inputting their own value
.attr('placeholder', 'Click here to show calendar ...')
.addClass('bs-date-picker') // Prevents the user from inputting their own value
.val(date)
.datepicker({
autoclose: true,
format: 'dd/mm/yyyy',
todateBtn: true,
todayHighlight: true,
startDate: new Date(),
orientation: 'bottom'
})
.on('changeDate', function () {
var changedDate = $(element).val();
value(changedDate);
});
},
update: function (element, valueAccessor) {
var newValue = ko.unwrap(valueAccessor());
if (newValue === null) {
$(element).val(''); // Force to clear the textbox
}
}
};
ko.validation.makeBindingHandlerValidatable('date');
/*
* Google Map
* Usage : <input type='text' data-bind="googleMap: modelProperty, mapElement : '#LocationMap'" />
*/
ko.bindingHandlers.googleMap = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var existingValue = valueAccessor();
var address = ko.unwrap(existingValue);
var $map = $(allBindings.get('mapElement'));
if ($map.length === 0) {
throw "googleMap binding requires a map binding";
}
function assignMapValueToObservable(componentType, observable, propertyName, value) {
if (_.isUndefined(observable)) {
return false;
}
if (componentType === propertyName) {
observable(value);
}
return true;
}
var googleMap = $(element).val(address)
.geocomplete({
country: "AU",
type: ['(regions)'],
map: $map,
markerOptions: {
draggable: false
}
})
.bind('geocode:result', function (event, geoData) {
viewModel.location(geoData["formatted_address"]);
viewModel.locationLatitude(geoData.geometry.location.lat());
viewModel.locationLongitude(geoData.geometry.location.lng());
// Capture every map component
_.each(geoData.address_components, function (comp) {
_.each(comp.types, function (t) {
assignMapValueToObservable(t, viewModel.streetNumber, 'street_number', comp.long_name);
assignMapValueToObservable(t, viewModel.streetName, 'route', comp.long_name);
assignMapValueToObservable(t, viewModel.suburb, 'locality', comp.long_name);
assignMapValueToObservable(t, viewModel.state, 'administrative_area_level_1', comp.long_name);
assignMapValueToObservable(t, viewModel.postCode, 'postal_code', comp.long_name);
assignMapValueToObservable(t, viewModel.country, 'country', comp.long_name);
});
});
});
// Bind the current address if any
if (address) {
googleMap.geocomplete('find', address);
}
}
}
ko.validation.makeBindingHandlerValidatable('googleMap');
/*
* Toggle button
*/
ko.bindingHandlers.toggle = {
init: function (element, valueAccessor) {
var $element = $(element),
observable = valueAccessor();
// Set the current value
if (observable() === true) {
$element.attr('checked', 'checked');
}
$element.bootstrapToggle().on('change', function (e) {
observable($element.prop('checked'));
});
}
}
/*
* Bounce in animation
*/
ko.bindingHandlers.bounceInDown = {
init: function (element, valueAccessor) {
var value = valueAccessor();
$(element).toggle(ko.unwrap(value));
$(element).addClass('animated');
},
update: function (element, valueAccessor) {
var value = valueAccessor();
var isVisible = ko.unwrap(value);
$(element).toggleClass('bounceInDown', isVisible);
$(element).toggle(isVisible);
}
}
/*
* New date selector (with time)
*/
ko.bindingHandlers.datetime = {
init: function (element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().dateTimePickerOptions || {};
options.format = $paramount.jsToDisplayDateFormat;
$(element).datetimepicker(options);
//when a user changes the date, update the view model
ko.utils.registerEventHandler(element, "dp.change", function (event) {
var value = valueAccessor();
if (ko.isObservable(value)) {
if (event.date !== null && !(event.date instanceof Date)) {
value(event.date.toDate());
} else {
value(event.date);
}
}
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
var picker = $(element).data("DateTimePicker");
if (picker) {
picker.destroy();
}
});
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var picker = $(element).data("DateTimePicker");
if (picker) {
var koDate = ko.utils.unwrapObservable(valueAccessor());
//in case return from server datetime i am get in this form for example /Date(93989393)/ then fomat this
//koDate = (typeof (koDate) !== 'object') ? new Date(parseFloat(koDate.replace(/[^0-9]/g, ''))) : koDate;
koDate = $paramount.dateFromServer(koDate);
picker.date(koDate);
}
}
};
/*
* Type Ahead - https://github.com/bassjobsen/Bootstrap-3-Typeahead
*/
ko.bindingHandlers.typeahead = {
init: function (element, valueAccessor, allBindingsAccessor) {
var $element = $(element);
var allBindings = allBindingsAccessor();
var source = ko.utils.unwrapObservable(valueAccessor());
var items = ko.utils.unwrapObservable(allBindings.items) || 8;
var valueChange = function (item) {
if (allBindings.onItemSelected) {
allBindings.onItemSelected(item);
}
return item;
};
var options = {
source: source,
items: items,
updater: valueChange
};
$element
.attr('autocomplete', 'off')
.typeahead(options);
}
};
/*
* This is very important and it is what wires up all our validation
*/
ko.validation.makeBindingHandlerValidatable('datetime');
/*
* Charts
*/
ko.bindingHandlers.chart = {
update: function (element, valueAccessor, allBindings) {
var ctx = element.getContext("2d");
var chartTypeValue = valueAccessor();
var chartType = ko.unwrap(chartTypeValue);
var chartData = ko.unwrap(allBindings.get('data'));
var chart = new Chart(ctx, {
type: chartType,
data: chartData
});
}
}
/*
*
*/
var imageService = new $paramount.ImageService();
ko.bindingHandlers.upload = {
init: function (element, valueAccessor) {
var $rootElement = $(element);
var $uploadElement = $rootElement.find('input[type=file]');
var $progressElement = $rootElement.find('.upload-progress');
$paramount.upload({
url: imageService.getUploadOnlineImageUrl(),
element: $uploadElement,
progressBar: $progressElement,
complete: function (documentId) {
var value = valueAccessor();
value(documentId);
},
error: function (errorMsg) {
console.error('error', errorMsg);
}
});
}
}
})(ko, jQuery); |
const Client = require('./client');
const formatMoney = require('./currency').formatMoney;
const GTM = require('./gtm');
const ChampionRouter = require('./router');
const ChampionSocket = require('./socket');
const State = require('./storage').State;
const url_for = require('./url').url_for;
const Utility = require('./utility');
const template = require('./utility').template;
const Header = (function () {
'use strict';
const hidden_class = 'invisible';
const media_query = window.matchMedia('(max-width: 1199px)');
const init = function() {
ChampionSocket.wait('authorize').then(() => { updatePage(media_query); });
$(function () {
const window_path = window.location.pathname;
const path = window_path.replace(/\/$/, '');
const href = decodeURIComponent(path);
$('.top-nav-menu li a').each(function() {
const target = $(this).attr('href');
if (target === href) {
$(this).addClass('active');
} else {
$(this).removeClass('active');
}
});
media_query.addListener(updatePage);
});
};
const updatePage = (mq) => {
if (mq.matches) {
mobileMenu();
} else {
desktopMenu();
}
userMenu();
if (!Client.is_logged_in()) {
$('#top_group').removeClass('logged-in').find('.logged-out').removeClass(hidden_class);
$('.trading-platform-header').removeClass(hidden_class);
}
};
const mobileMenu = function() {
const $menu_dropdown = $('.nav-menu-dropdown');
$('#mobile-menu > ul').height($(window).innerHeight());
$(window).on('orientationchange resize', () => {
$('#mobile-menu > ul').height($(window).innerHeight());
});
$('.nav-menu:not(.selected-account)').unbind('click').on('click', function(e) {
e.stopPropagation();
if ($('.nav-menu-dropdown.slide-in').length) {
Utility.slideOut($menu_dropdown);
} else {
Utility.slideIn($menu_dropdown);
}
});
$(document).off('click.mobileMenu').on('click.mobileMenu', function(e) {
e.stopPropagation();
if ($('.nav-menu-dropdown.slide-in').length) {
Utility.slideOut($menu_dropdown);
}
});
$('.nav-dropdown-toggle').off('click').on('click', function(e) {
e.stopPropagation();
$(this).next().toggleClass(hidden_class);
});
if (!Client.is_logged_in()) {
$('#topbar, #header').find('.logged-out').removeClass(hidden_class);
return;
}
$('#topbar, #header').find('.logged-in').removeClass(hidden_class);
};
const desktopMenu = function() {
const $all_accounts = $('#all-accounts');
$all_accounts.find('li.has-sub > a').off('click').on('click', function(e) {
e.stopPropagation();
$(this).siblings('ul').toggleClass(hidden_class);
});
if (!Client.is_logged_in()) return;
$(window).off('resize.updateBody').on('resize.updateBody', updateBody);
updateBody();
$('#header .logged-in').removeClass(hidden_class);
$all_accounts.find('.account > a').removeClass('menu-icon');
const language = $('#select_language');
$('.nav-menu').unbind('click').on('click', function(e) {
e.stopPropagation();
Utility.animateDisappear(language);
if (+$all_accounts.css('opacity') === 1) {
Utility.animateDisappear($all_accounts);
} else {
Utility.animateAppear($all_accounts);
}
});
$(document).off('click.desktopMenu').on('click.desktopMenu', function(e) {
e.stopPropagation();
Utility.animateDisappear($all_accounts);
});
};
const updateBody = () => {
$('#champion-container').css('margin-top', $('#top_group').height());
};
const userMenu = function() {
if (!Client.is_logged_in()) return;
if (!Client.is_virtual()) {
displayAccountStatus();
}
setMetaTrader();
const selectedTemplate = (text, value, icon) => (
`<div class="hidden-lg-up">
<span class="selected" value="${value}">
<li><span class="nav-menu-icon pull-left ${icon}"></span>${text}</li>
</span>
<div class="separator-line-thin-gray hidden-lg-down"></div>
</div>`
);
const switchTemplate = (text, value, icon, type, item_class) => (
`<a href="javascript:;" value="${value}" class="${item_class}">
<li>
<span class="hidden-lg-up nav-menu-icon pull-left ${icon}"></span>
<div>${text}</div>
<div class="hidden-lg-down account-type">${type}</div>
</li>
<div class="separator-line-thin-gray hidden-lg-down"></div>
</a>`
);
const is_mt_pages = State.get('is_mt_pages');
let loginid_select = is_mt_pages ? selectedTemplate('MetaTrader 5', '', 'fx-mt5-icon') : '';
Client.get('loginid_array').forEach((login) => {
if (!login.disabled) {
const curr_id = login.id;
const type = `(Binary ${login.real ? 'Real' : 'Virtual'} Account)`;
const icon = login.real ? 'fx-real-icon' : 'fx-virtual-icon';
const is_current = curr_id === Client.get('loginid');
// default account
if (is_current && !is_mt_pages) {
$('.main-account .account-type').html(type);
$('.main-account .account-id').html(curr_id);
loginid_select += selectedTemplate(curr_id, curr_id, icon);
} else if (is_mt_pages && login.real && Client.is_virtual()) {
switchLoginId(curr_id);
return;
}
loginid_select += switchTemplate(curr_id, curr_id, icon, type, is_current ? (is_mt_pages ? 'mt-show' : 'invisible') : '');
}
});
$('.login-id-list').html(loginid_select);
if (!Client.has_real()) {
$('#all-accounts .upgrade').removeClass(hidden_class);
}
$('.login-id-list a').off('click').on('click', function(e) {
e.preventDefault();
$(this).attr('disabled', 'disabled');
switchLoginId($(this).attr('value'));
if (State.get('is_mt_pages')) {
State.remove('is_mt_pages');
ChampionRouter.forward(url_for('user/settings'));
}
});
};
const setMetaTrader = () => {
const is_mt_pages = State.get('is_mt_pages');
$('#header, #footer').find('.mt-hide')[is_mt_pages ? 'addClass' : 'removeClass'](hidden_class);
$('#header, #footer').find('.mt-show')[is_mt_pages ? 'removeClass' : 'addClass'](hidden_class);
};
const displayNotification = (message) => {
const $msg_notification = $('#msg_notification');
$msg_notification.html(message);
if ($msg_notification.is(':hidden')) $msg_notification.slideDown(500, updateBody);
};
const hideNotification = () => {
const $msg_notification = $('#msg_notification');
if ($msg_notification.is(':visible')) $msg_notification.slideUp(500, () => { $msg_notification.html(''); });
};
const displayAccountStatus = () => {
ChampionSocket.wait('authorize').then(() => {
let get_account_status,
status,
has_mt_account = false;
const riskAssessment = () => (get_account_status.risk_classification === 'high' || has_mt_account) &&
/financial_assessment_not_complete/.test(status);
const messages = {
authenticate: () => template('Please [_1]authenticate your account[_2] to lift your withdrawal and trading limits.',
[`<a href="${url_for('user/authenticate')}">`, '</a>']),
risk: () => template('Please complete the [_1]financial assessment form[_2] to lift your withdrawal and trading limits.',
[`<a href="${url_for('user/profile')}#assessment">`, '</a>']),
tnc: () => template('Please [_1]accept the updated Terms and Conditions[_2] to lift your withdrawal and trading limits.',
[`<a href="${url_for('user/tnc-approval')}">`, '</a>']),
unwelcome: () => template('Your account is restricted. Kindly [_1]contact customer support[_2] for assistance.',
[`<a href="${url_for('contact')}">`, '</a>']),
};
const validations = {
authenticate: () => get_account_status.prompt_client_to_authenticate,
risk : () => riskAssessment(),
tnc : () => Client.should_accept_tnc(),
unwelcome : () => /(unwelcome|(cashier|withdrawal)_locked)/.test(status),
};
const check_statuses = [
{ validation: validations.tnc, message: messages.tnc },
{ validation: validations.risk, message: messages.risk },
{ validation: validations.authenticate, message: messages.authenticate },
{ validation: validations.unwelcome, message: messages.unwelcome },
];
ChampionSocket.wait('website_status', 'get_account_status', 'get_settings', 'get_financial_assessment').then(() => {
get_account_status = State.get(['response', 'get_account_status', 'get_account_status']) || {};
status = get_account_status.status;
ChampionSocket.wait('mt5_login_list').then((response) => {
if (response.mt5_login_list.length) {
has_mt_account = true;
}
const notified = check_statuses.some((object) => {
if (object.validation()) {
displayNotification(object.message());
return true;
}
return false;
});
if (!notified) hideNotification();
});
});
});
};
const switchLoginId = (loginid) => {
if (!loginid || loginid.length === 0 || loginid === Client.get('loginid')) {
return;
}
const token = Client.get_token(loginid);
if (!token || token.length === 0) {
ChampionSocket.send({ logout: 1 });
return;
}
// cleaning the previous values
Client.clear_storage_values();
// set cookies: loginid, token
Client.set('loginid', loginid);
Client.set_cookie('loginid', loginid);
Client.set_cookie('token', token);
GTM.setLoginFlag();
$('.login-id-list a').removeAttr('disabled');
window.location.reload();
};
const updateBalance = (response) => {
if (response.error) {
console.log(response.error.message);
return;
}
const balance = response.balance.balance;
Client.set('balance', balance);
const currency = response.balance.currency;
if (!currency) {
return;
}
const view = formatMoney(balance, currency);
$('.account-balance').text(view).css('visibility', 'visible');
};
return {
init : init,
displayAccountStatus: displayAccountStatus,
updateBalance : updateBalance,
};
})();
module.exports = Header;
|
import React from 'react';
import { ThemeContext } from '../../ThemeProvider';
export const withThemeSwitch = ComposedComponent => props => (
<ThemeContext.Consumer>
{values => <ComposedComponent {...props} {...values} />}
</ThemeContext.Consumer>
);
export default withThemeSwitch;
|
import React, { Component } from 'react';
import { Form, Input, Button } from 'antd';
import { createForm } from 'rc-form';
import models from '../../models/index';
import Message from '../../utils/message/index';
import './index.less';
const { tableDataModel } = models;
const formItemLayout = {
labelCol: {
xs: { span: 12 },
sm: { span: 4 }
},
wrapperCol: {
xs: { span: 12 },
sm: { span: 20 }
}
};
@createForm()
class addData extends Component {
addData = () => {
this.props.form.validateFields((error, value) => {
if (!!error) {
Message.error(error);
}
tableDataModel.addTableData(value);
Message.info('添加数据成功!');
});
};
render() {
return (
<div className={'add-data-form'}>
<Form {...formItemLayout}>
{tableDataModel.tableTitleData.map((item, index) => {
const { getFieldDecorator } = this.props.form;
const { title, key } = item;
return (
<Form.Item key={key} label={title}>
{getFieldDecorator(key, {
rules: [
{
required: true,
message: 'Please input your data!'
}
]
})(<Input />)}
</Form.Item>
);
})}
</Form>
<Button className={'submit-btn'} onClick={this.addData}>
添加
</Button>
</div>
);
}
}
export default addData;
|
/*
* @Author: xr
* @Date: 2021-04-09 23:10:07
* @LastEditors: xr
* @LastEditTime: 2021-04-19 17:13:45
* @version: v1.0.0
* @Descripttion: 功能说明
* @FilePath: \api\services\admin.js
*/
const Sequelize = require('sequelize');
const connection = require('./connection')
const adminTable = connection.define('admin', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
username: {
type: Sequelize.STRING,
allowNull: false,
defaultValue: ''
},
password: {
type: Sequelize.STRING,
allowNull: false,
defaultValue: ''
},
avatar: {
type: Sequelize.STRING,
allowNull: false,
defaultValue: ''
}
});
const getAdminMenus = (id) => {
return new Promise((resolve, reject) => {
connection.query(`select
role.menus
from power left join role on role.id=power.roleid left join admin on admin.id=power.adminid where admin.id= :id`, {
replacements: { id: id }, type: connection.QueryTypes.SELECT
}).then((data) => {
resolve(Array.from(new Set(data.map(c => c.menus).join(',').split(','))));
})
})
}
const getAdminByUsername = (username) => {
return new Promise((resolve, reject) => {
adminTable.findOne({
where: {
username: { [Sequelize.Op.eq]: username }
}
}).then((data) => {
resolve(data)
})
})
}
const getAdminPage = ({
p = 1, ps = 10, username = '', sort = 'id desc'
}) => {
return new Promise((resolve, reject) => {
let sorts = sort.replace(/\s{1,}/g, ' ').replace(/^\s|\s$/g, '').split(' ');
let where = {};
if (username) {
where['username'] = { [Sequelize.Op.like]: '%' + username + '%' };
}
adminTable.findAndCountAll({
order: [sorts],
limit: Number(ps),
offset: (p - 1) * ps,
where: where
}).then((res) => {
resolve(res);
});
})
}
const deleteAdmin = (id = 0) => {
return new Promise((resolve, reject) => {
adminTable.destroy({
where: {
id: id
}
}).then((res) => {
resolve(res);
});
})
}
const updateAdmin = (id = 0, username = '', avatar = '') => {
return new Promise((resolve, reject) => {
console.log(id, username, avatar);
adminTable.update({
username: username,
avatar: avatar
}, {
where: {
id: id
}
}).then((res) => {
resolve(res);
});
})
}
const addAdmin = (username = '', password = '', avatar = '') => {
return new Promise((resolve, reject) => {
adminTable.create({
username: username,
password: password,
avatar: avatar,
}).then((res) => {
resolve(res);
});
})
}
module.exports = {
adminTable,
getAdminByUsername,
getAdminMenus,
getAdminPage,
deleteAdmin,
updateAdmin,
addAdmin
}; |
var ObjectID = require('mongodb').ObjectID;
function removeElement(db,req,res){
var idToRemove = req.query.id;
var collection = db.collection('tasks');
collection.deleteOne({
_id:ObjectID(idToRemove)
},function(){
res.end();
});
}
module.exports = removeElement; |
require("./global")
console.log(saudacao.nome)
saudacao.nome = " Bem vindo mane"
console.log(saudacao.nome) |
/**
* Created by lipeiwei on 16/10/4.
*/
import React from 'react';
import {
TouchableOpacity,
Image,
Animated,
StyleSheet,
Dimensions
} from 'react-native';
import {getNavigator} from '../route';
const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'transparent',
alignItems: 'center',
justifyContent: 'center'
},
image: {
height: windowHeight / 3 * 2,
width: windowWidth
}
});
class ImageViewer extends React.Component {
constructor(props) {
super(props);
this.onPress = this.onPress.bind(this);
}
render() {
return (
<TouchableOpacity style={styles.container} activeOpacity={1} onPress={this.onPress}>
<Image style={styles.image} resizeMode="contain" source={this.props.source}/>
</TouchableOpacity>
);
}
onPress() {
getNavigator().pop();
}
}
export default ImageViewer; |
declare module 'react-redux' {
declare function connect() : any
}
|
function idValidation(oSrc, args) {
var id = args.Value;
var checkDigit = id % 10;
id = parseInt(id /10);
var sum = idSum(id);
var isValid = checkId(sum, checkDigit);
args.IsValid = isValid;
}
function idSum(id) {
if (id > 99999999)
return -1;
var mulArr = [2, 1, 2, 1, 2, 1, 2, 1];
var sum = 0;
for (var i = 0 ; i < 8; i++) {
var temp = (id % 10) * mulArr[i];
if (temp > 9) {
temp = parseInt(temp % 10) + parseInt((temp / 10) % 10);
}
sum += temp;
id = parseInt(id / 10);
}
return sum;
}
function checkId(sum, digit) {
if ((sum + digit) % 10 == 0)
return true;
if ((sum - digit) % 10 == 0)
return true;
return false;
}
function DateValidation(oSrc, args) {
var date = args.Value;
userYear = date[0]+date[1]+date[2]+date[3];
var today = new Date();
var years = today.getFullYear() - userYear;
args.IsValid = years > 17 ? true : false;
}
function nameValidation(oSrc, args) {
var inputTxt = args.Value;
var letters = /^[A-Za-zא-ת]+$/;
if (inputTxt.value.match(letters)) {
args.IsValid = true;
}
else {
alert("message");
args.IsValid = false;
}
}
function phoneNumberValidation(oSrc, args) {
var phoneNumber = String(args.Value);
if (phoneNumber.length != 10) {
oSrc.innerText = "מספר טלפון לא תקין";
args.IsValid = false;
return;
}
if (phoneNumber[0] != '0' || phoneNumber[1] != '5') {
args.IsValid = false;
oSrc.innerText = "זהו לא מספר טלפון ישראלי";
return;
}
args.IsValid = true;
oSrc.errormessage = "";
} |
const actions = require('./actions')
module.exports = {
reduxMiddleware: () => ({
onConnect: ctx => {
console.log('redux middleware connect')
ctx.action = actions.connect()
ctx.dispatch = (action) => {
action = { ...action, meta: { ...action.meta, createdAt: Date.now() } }
ctx.send(JSON.stringify(action))
}
},
onMessage: (ctx) => {
console.log('redux middleware process')
let action
try {
action = JSON.parse(ctx.message)
} catch (err) {
console.log('it is not object', ctx.message)
return
}
console.log('store action to ctx', action)
ctx.action = action
}
})
}
|
Page({
/**
* 页面的初始数据
*/
data: {
actionSheetHidden:true,
modalHidden:true,
toastHidden:true,
loadingHidden:true,
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
click:function(){
this.setData({actionSheetHidden:false}),
this.setData({modalHidden:false}),
this.setData({toastHidden:false}),
this.setData({loadingHidden:false})
// loading 在1.5秒后自动消失
var that = this;
setTimeout(function(){
that.setData({loadingHidden:true})
},1500)
},
actionSheetChange:function(){
this.setData({actionSheetHidden: true})
},
itemClick:function(event){
console.log(event)
},
modalConfirm:function(){
this.setData({modalHidden:true})
},
modalCancel: function () {
this.setData({modalHidden:true})
},
toastChange:function(){
this.setData({toastHidden:true})
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
}) |
import React from "react";
import { Block, Card, CardHeader, Link, CardContent, List, ListItem, CardFooter, ListInput, Col } from 'framework7-react';
import crypto from 'crypto-js';
import { dict } from "../../Dict";
import Moment from 'react-moment';
import JDate from 'jalali-date';
import 'moment-timezone';
import 'moment/locale/fa';
const Works = (props) => {
function chip(status) {
if (status) {
return (
<div>
<div className="chip" >
<div className="chip-media" style={{ backgroundColor: status.color }} >
<i className="icon f7-icons if-not-md">plus_circle</i>
<i className="icon material-icons md-only"></i>
</div>
<div className="chip-label">{status.title}</div>
</div>
</div>
)
} else {
return (<div>{dict.add_stauts}</div>)
}
}
if (props.task) {
return (
<Card>
<CardHeader>
{dict.works}
<Link href={'/works/new/' + props.task.id}><i className="ml-5 fa fa-plus"></i> {dict.new}</Link>
</CardHeader>
<CardContent>
<List mediaList >
{props.task.works.map((work) =>
<ListItem
className='work-media'
link={"/works/" + work.id}
title={work.title}
after={chip(work.status)}
text={work.details}
>
</ListItem>
)}
</List>
</CardContent>
<CardFooter>
+
</CardFooter>
</Card>
)
} else {
return (<ul></ul>)
}
}
export default Works;
|
import { Vec3 } from './vec3.js';
/**
* A 3x3 matrix.
*
* @category Math
*/
class Mat3 {
/**
* Matrix elements in the form of a flat array.
*
* @type {Float32Array}
*/
data = new Float32Array(9);
/**
* Create a new Mat3 instance. It is initialized to the identity matrix.
*/
constructor() {
// Create an identity matrix. Note that a new Float32Array has all elements set
// to zero by default, so we only need to set the relevant elements to one.
this.data[0] = this.data[4] = this.data[8] = 1;
}
/**
* Creates a duplicate of the specified matrix.
*
* @returns {this} A duplicate matrix.
* @example
* const src = new pc.Mat3().translate(10, 20, 30);
* const dst = src.clone();
* console.log("The two matrices are " + (src.equals(dst) ? "equal" : "different"));
*/
clone() {
/** @type {this} */
const cstr = this.constructor;
return new cstr().copy(this);
}
/**
* Copies the contents of a source 3x3 matrix to a destination 3x3 matrix.
*
* @param {Mat3} rhs - A 3x3 matrix to be copied.
* @returns {Mat3} Self for chaining.
* @example
* const src = new pc.Mat3().translate(10, 20, 30);
* const dst = new pc.Mat3();
* dst.copy(src);
* console.log("The two matrices are " + (src.equals(dst) ? "equal" : "different"));
*/
copy(rhs) {
const src = rhs.data;
const dst = this.data;
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = src[3];
dst[4] = src[4];
dst[5] = src[5];
dst[6] = src[6];
dst[7] = src[7];
dst[8] = src[8];
return this;
}
/**
* Copies the contents of a source array[9] to a destination 3x3 matrix.
*
* @param {number[]} src - An array[9] to be copied.
* @returns {Mat3} Self for chaining.
* @example
* const dst = new pc.Mat3();
* dst.set([0, 1, 2, 3, 4, 5, 6, 7, 8]);
*/
set(src) {
const dst = this.data;
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = src[3];
dst[4] = src[4];
dst[5] = src[5];
dst[6] = src[6];
dst[7] = src[7];
dst[8] = src[8];
return this;
}
/**
* Reports whether two matrices are equal.
*
* @param {Mat3} rhs - The other matrix.
* @returns {boolean} True if the matrices are equal and false otherwise.
* @example
* const a = new pc.Mat3().translate(10, 20, 30);
* const b = new pc.Mat3();
* console.log("The two matrices are " + (a.equals(b) ? "equal" : "different"));
*/
equals(rhs) {
const l = this.data;
const r = rhs.data;
return ((l[0] === r[0]) &&
(l[1] === r[1]) &&
(l[2] === r[2]) &&
(l[3] === r[3]) &&
(l[4] === r[4]) &&
(l[5] === r[5]) &&
(l[6] === r[6]) &&
(l[7] === r[7]) &&
(l[8] === r[8]));
}
/**
* Reports whether the specified matrix is the identity matrix.
*
* @returns {boolean} True if the matrix is identity and false otherwise.
* @example
* const m = new pc.Mat3();
* console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity"));
*/
isIdentity() {
const m = this.data;
return ((m[0] === 1) &&
(m[1] === 0) &&
(m[2] === 0) &&
(m[3] === 0) &&
(m[4] === 1) &&
(m[5] === 0) &&
(m[6] === 0) &&
(m[7] === 0) &&
(m[8] === 1));
}
/**
* Sets the matrix to the identity matrix.
*
* @returns {Mat3} Self for chaining.
* @example
* m.setIdentity();
* console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity"));
*/
setIdentity() {
const m = this.data;
m[0] = 1;
m[1] = 0;
m[2] = 0;
m[3] = 0;
m[4] = 1;
m[5] = 0;
m[6] = 0;
m[7] = 0;
m[8] = 1;
return this;
}
/**
* Converts the matrix to string form.
*
* @returns {string} The matrix in string form.
* @example
* const m = new pc.Mat3();
* // Outputs [1, 0, 0, 0, 1, 0, 0, 0, 1]
* console.log(m.toString());
*/
toString() {
return '[' + this.data.join(', ') + ']';
}
/**
* Generates the transpose of the specified 3x3 matrix.
*
* @param {Mat3} [src] - The matrix to transpose. If not set, the matrix is transposed in-place.
* @returns {Mat3} Self for chaining.
* @example
* const m = new pc.Mat3();
*
* // Transpose in place
* m.transpose();
*/
transpose(src = this) {
const s = src.data;
const t = this.data;
if (s === t) {
let tmp;
tmp = s[1]; t[1] = s[3]; t[3] = tmp;
tmp = s[2]; t[2] = s[6]; t[6] = tmp;
tmp = s[5]; t[5] = s[7]; t[7] = tmp;
} else {
t[0] = s[0];
t[1] = s[3];
t[2] = s[6];
t[3] = s[1];
t[4] = s[4];
t[5] = s[7];
t[6] = s[2];
t[7] = s[5];
t[8] = s[8];
}
return this;
}
/**
* Converts the specified 4x4 matrix to a Mat3.
*
* @param {import('./mat4.js').Mat4} m - The 4x4 matrix to convert.
* @returns {Mat3} Self for chaining.
*/
setFromMat4(m) {
const src = m.data;
const dst = this.data;
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = src[4];
dst[4] = src[5];
dst[5] = src[6];
dst[6] = src[8];
dst[7] = src[9];
dst[8] = src[10];
return this;
}
/**
* Set the matrix to the inverse of the specified 4x4 matrix.
*
* @param {import('./mat4.js').Mat4} src - The 4x4 matrix to invert.
* @returns {Mat3} Self for chaining.
*
* @ignore
*/
invertMat4(src) {
const s = src.data;
const a0 = s[0];
const a1 = s[1];
const a2 = s[2];
const a4 = s[4];
const a5 = s[5];
const a6 = s[6];
const a8 = s[8];
const a9 = s[9];
const a10 = s[10];
const b11 = a10 * a5 - a6 * a9;
const b21 = -a10 * a1 + a2 * a9;
const b31 = a6 * a1 - a2 * a5;
const b12 = -a10 * a4 + a6 * a8;
const b22 = a10 * a0 - a2 * a8;
const b32 = -a6 * a0 + a2 * a4;
const b13 = a9 * a4 - a5 * a8;
const b23 = -a9 * a0 + a1 * a8;
const b33 = a5 * a0 - a1 * a4;
const det = a0 * b11 + a1 * b12 + a2 * b13;
if (det === 0) {
this.setIdentity();
} else {
const invDet = 1 / det;
const t = this.data;
t[0] = b11 * invDet;
t[1] = b21 * invDet;
t[2] = b31 * invDet;
t[3] = b12 * invDet;
t[4] = b22 * invDet;
t[5] = b32 * invDet;
t[6] = b13 * invDet;
t[7] = b23 * invDet;
t[8] = b33 * invDet;
}
return this;
}
/**
* Transforms a 3-dimensional vector by a 3x3 matrix.
*
* @param {Vec3} vec - The 3-dimensional vector to be transformed.
* @param {Vec3} [res] - An optional 3-dimensional vector to receive the result of the
* transformation.
* @returns {Vec3} The input vector v transformed by the current instance.
*/
transformVector(vec, res = new Vec3()) {
const m = this.data;
const x = vec.x;
const y = vec.y;
const z = vec.z;
res.x = x * m[0] + y * m[3] + z * m[6];
res.y = x * m[1] + y * m[4] + z * m[7];
res.z = x * m[2] + y * m[5] + z * m[8];
return res;
}
/**
* A constant matrix set to the identity.
*
* @type {Mat3}
* @readonly
*/
static IDENTITY = Object.freeze(new Mat3());
/**
* A constant matrix with all elements set to 0.
*
* @type {Mat3}
* @readonly
*/
static ZERO = Object.freeze(new Mat3().set([0, 0, 0, 0, 0, 0, 0, 0, 0]));
}
export { Mat3 };
|
import { FaBars, FaSearch, FaShoppingCart, FaUserPlus } from "react-icons/fa";
import { Link } from "react-router-dom";
import Logo from "../images/logo.png";
const Header = () => {
return (
<header className="header flex items-center justify-between py-3 xl:mx-20">
<div className="menu-btn flex">
<div className="mx-4">
<FaBars />
</div>
<div>
<FaSearch />
</div>
</div>
<div className="logo">
<div>
<Link to="/">
<img src={Logo} alt="Microsoft" />
</Link>
</div>
<ul>
<li>
<Link to="/microsoft-365">Microsoft 365</Link>
</li>
<li>
<Link to="/office">Office</Link>
</li>
<li>Windows</li>
<li>Surface</li>
<li>Xbox</li>
<li>Deals</li>
<li>Support</li>
</ul>
</div>
<div className="cart flex">
<div>
<FaShoppingCart />
</div>
<div className="mx-4">
<FaUserPlus />
</div>
</div>
<div className="sign-in">
<ul>
<li>All Microsoft</li>
<li>Search</li>
<li>Cart</li>
<li>Sign In</li>
</ul>
</div>
</header>
);
};
export default Header;
|
import React, { Component } from 'react';
import {Redirect,Link} from "react-router-dom";
export class Bride extends Component
{
constructor(props) {
super(props);
let calage="";
const {value:{BrideDateofbirth}}=this.props;
this.state={
calage:""
}
if(BrideDateofbirth!==""&&BrideDateofbirth!==undefined)
{
var today = new Date(),
date = today.getFullYear();
var birthDate = new Date(BrideDateofbirth);
var getyear=birthDate.getFullYear();
calage=date-getyear;
this.state.calage=calage;
}
else{
return
}
}
state={
bridenameerror:"",
BrideNationalityerror:"",
brideresidentialerror:"",
bridereligionserror:"",
bridecasteerror:"",
BrideDateofbirtherror:"",
brideemployernameerror:"",
bridedesignationerror:"",
bridemaritalstatuserror:"",
bridemobilenumbererror:"",
bridewhatsapperror:"",
brideemailerror:"",
bridepassporterror:"",
Street3error:"",
District3error:"",
State3error:"",
Taluk3error:"",
Pincode3error:"",
Country3error:"",
Village3error:"",
}
continue=e=>{
e.preventDefault();
const isValid=this.validateForm();
if(isValid){
this.props.nextStep();
}
};
back = e => {
e.preventDefault();
this.props.prevStep();
};
validateForm=()=>{
let isValid = true;
var today = new Date(),
date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
const {value:{bridename,BrideNationality,brideresidential,bridereligion,bridecaste,BrideDateofbirth,brideemployername,
bridedesignation,bridemaritalstatus,bridemobilenumber,bridewhatsapp,brideemail,Street3,Village3,Taluk3,District3,
State3,Country3,Pincode3,bridepassport}}=this.props;
let bridenameerror = "";
let BrideNationalityerror = "";
let brideresidentialerror="";
let bridereligionerror="";
let bridecasteerror="";
let BrideDateofbirtherror="";
let brideemployernameerror="";
let bridedesignationerror="";
let bridemaritalstatuserror="";
let bridemobilenumbererror="";
let bridewhatsapperror="";
let brideemailerror="";
let bridepassporterror="";
let Street3error="";
let District3error="";
let State3error="";
let Taluk3error="";
let Pincode3error="";
let Country3error="";
let Village3error="";
if(bridename===""||bridename===undefined)
{
bridenameerror="Please select name of the groom";
isValid=false;
}
else{
if(!bridename.match(/^[a-zA-Z ]*$/))
{
bridenameerror="Please enter alphabet characters only";
isValid=false;
}
}
if(BrideNationality===""||BrideNationality===undefined)
{
BrideNationalityerror="Please enter nationality";
isValid=false;
}
else{
if(!BrideNationality.match(/^[a-zA-Z ]*$/))
{
BrideNationalityerror="Please enter alphabet characters only";
isValid=false;
}
}
if(brideresidential===""||brideresidential===undefined||brideresidential==="0")
{
brideresidentialerror="Please select residential status";
isValid=false;
}
if(bridereligion===""||bridereligion===undefined||bridereligion==="0")
{
bridereligionerror="Please select religion";
isValid=false;
}
if(bridecaste===""||bridecaste===undefined)
{
bridecasteerror="Please enter caste";
isValid=false;
}
else{
if(!bridecaste.match(/^[a-zA-Z ]*$/))
{
bridecasteerror="Please enter alphabet characters only";
isValid=false;
}
}
if(BrideDateofbirth===""||BrideDateofbirth===undefined)
{
BrideDateofbirtherror="Please select dob";
isValid=false;
}
else
{
let calage="";
var current = new Date(),
date = current.getFullYear();
var birthDate = new Date(BrideDateofbirth);
var getyear=birthDate.getFullYear();
calage=date-getyear;
if(calage < 18)
{
BrideDateofbirtherror="Please select valid dob";
isValid=false;
}
else if(calage==="0")
{
BrideDateofbirtherror="Please select valid dob";
isValid=false;
}
else{
}
}
if(brideemployername===""||brideemployername===undefined)
{
brideemployernameerror="Please enter employername";
isValid=false;
}
else{
if(!brideemployername.match(/^[a-zA-Z ]*$/))
{
brideemployernameerror="Please enter alphabet characters only";
isValid=false;
}
}
if(bridedesignation===""||bridedesignation===undefined)
{
bridedesignationerror="Please enter employername";
isValid=false;
}
else
{
if(!bridedesignation.match(/^[a-zA-Z ]*$/))
{
bridedesignationerror="Please enter alphabet characters only";
isValid=false;
}
}
if(bridemaritalstatus===""||bridemaritalstatus===undefined||bridemaritalstatus==="0")
{
bridemaritalstatuserror="Please enter maritalstatus";
isValid=false;
}
if(bridemobilenumber===""||bridemobilenumber===undefined)
{
bridemobilenumbererror="Please enter mobilenumber";
isValid=false;
}
else{
if(!bridemobilenumber.match(/^[0-9]{10}$/))
{
bridemobilenumbererror="Ivalid phonenumber";
isValid=false;
}
}
if(bridewhatsapp===""||bridewhatsapp===undefined)
{
bridewhatsapperror="Please enter whatsappnumber";
isValid=false;
}
else{
if(!bridewhatsapp.match(/^[0-9]{10}$/))
{
bridewhatsapperror="Ivalid whatsappnumber";
isValid=false;
}
}
if(brideemail===""||brideemail===undefined)
{
brideemailerror="Please enter whatsappnumber";
isValid=false;
}
else{
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
if(!pattern.test(brideemail))
{
brideemailerror="Ivalid email address";
isValid=false;
}
}
if(bridepassport===""||bridepassport===undefined)
{
bridepassporterror="Please enter passportnumber";
isValid=false;
}
if(Street3===""||Street3===undefined)
{
Street3error="Please enter street";
isValid=false;
}
if(Village3===""||Village3===undefined)
{
Village3error="Please enter village";
isValid=false;
}
if(Taluk3===""||Taluk3===undefined)
{
Taluk3error="Please enter village";
isValid=false;
}
if(District3===""||District3===undefined)
{
District3error="Please enter district";
isValid=false;
}
if(State3===""||State3===undefined)
{
State3error="Please enter state";
isValid=false;
}
if(Country3===""||Country3===undefined)
{
Country3error="Please enter country";
isValid=false;
}
if(Pincode3===""||Pincode3===undefined)
{
Pincode3error="Please enter pincode";
isValid=false;
}
this.setState({bridenameerror,BrideNationalityerror,brideresidentialerror,bridereligionerror,bridecasteerror,BrideDateofbirtherror,brideemployernameerror,
bridedesignationerror,bridemaritalstatuserror,bridemobilenumbererror,bridewhatsapperror,brideemailerror,Street3error,Village3error,Taluk3error,District3error,
State3error,Country3error,Pincode3error,bridepassporterror})
return isValid;
}
datecal=e=>
{
let calage="";
const {value:{BrideDateofbirth}}=this.props;
if(BrideDateofbirth!==""&&BrideDateofbirth!==undefined)
{
var today = new Date(),
date = today.getFullYear();
var birthDate = new Date(BrideDateofbirth);
var getyear=birthDate.getFullYear();
calage=date-getyear;
this.setState({calage})
}
else{
return
}
}
closeform=e=>
{
window.localStorage.clear();
this.setState({referrer: '/sign-in'});
}
render()
{
const {referrer} = this.state;
if (referrer) return <Redirect to={referrer} />;
var fname=localStorage.getItem('firstname');
var lname=localStorage.getItem('lastname');
const {value,inputChange}=this.props;
const {value:{bridename,BrideNationality,brideresidential,bridereligion,bridecaste,BrideDateofbirth,brideemployername,
bridedesignation,bridemaritalstatus,bridemobilenumber,bridewhatsapp,brideemail,Street3,Village3,Taluk3,District3,
State3,Country3,Pincode3,bridepassport}}=this.props;
return(
<div >
<div class="header_design w-100">
<div class="row float-right m-3" style={{marginRight:"20px"}}> <b style={{marginTop: "7px"}}><label >Welcome {fname }</label></b> <button style={{marginTop: "-7px"}} className="btn btn-primary" onClick={() => this.closeform()} style={{marginToptop: "-7px"}}>logout</button></div>
<div class="text-black">
<div class="text-black">
<div class="border-image p-4"></div> </div>
</div> </div>
<div class="body_UX">
<div class="body_color_code m-4">
<div className="img_logo"></div>
<br></br>
<br></br><br></br>
<div class="box m-4">
<div className="form-container ">
<br></br>
<h1>Details of Bride </h1>
<br></br>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label>Name of the Bride<span style={{color:"red"}}> *</span> </label>
<input type="text" className="input" name="bridename" value={value.bridename} onChange={inputChange('bridename')} />
<p style={{color:"red"}}>{this.state.bridenameerror}</p>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Nationality<span style={{color:"red"}}> *</span> </label>
<input type="bridenation" className="input" name="bridenationality" value={value.BrideNationality} onChange={inputChange('BrideNationality')} />
<p style={{color:"red"}}>{this.state.BrideNationalityerror}</p>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Residential Status in India<span style={{color:"red"}}> *</span> </label>
<select className="input" name="brideresidential" value={value.brideresidential} onChange={inputChange('brideresidential')} >
<option value="0">Select residential status</option>
<option value="1">Resident</option>
<option value="2">NRI</option>
<option value="3">PIO</option>
<option value="4">OCI</option>
</select>
<p style={{color:"red"}}>{this.state.brideresidentialerror}</p>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Relegion<span style={{color:"red"}}> *</span> </label>
<select className="input" name="bridereligion" value={value.bridereligion} onChange={inputChange('bridereligion')} >
<option value="0">Select religion</option>
<option value="1">Hindu</option>
<option value="2">Muslim</option>
<option value="3">Christian</option>
<option value="4">Jain</option>
<option value="5">Buddhist</option>
<option value="6">Seikh</option>
</select>
<p style={{color:"red"}}>{this.state.bridereligionerror}</p>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label>Caste<span style={{color:"red"}}> *</span> </label>
<input type="text" className="input" name="bridecaste" value={value.bridecaste} onChange={inputChange('bridecaste')} />
<p style={{color:"red"}}>{this.state.bridecasteerror}</p>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Date of Birth<span style={{color:"red"}}> *</span> </label>
<input type="date" className="input" onChange={this.handleChangeStartDate} name="BrideDateofbirth" value={value.BrideDateofbirth} onChange={inputChange('BrideDateofbirth')} ></input>
<p style={{color:"red"}}>{this.state.BrideDateofbirtherror}</p>
</div>
</div>
<div class="col-md-3">
<label>Age</label>
<p>{this.state.calage}</p>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Name of the Employer<span style={{color:"red"}}> *</span> </label>
<input type="text" className="input" name="brideemployername" onClick={this.datecal} value={value.brideemployername} onChange={inputChange('brideemployername')} />
<p style={{color:"red"}}>{this.state.brideemployernameerror}</p>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label>Designation<span style={{color:"red"}}> *</span> </label>
<input type="text" className="input" name="bridedesignation" value={value.bridedesignation} onChange={inputChange('bridedesignation')} />
<p style={{color:"red"}}>{this.state.bridedesignationerror}</p>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Marital Status Before Marriage<span style={{color:"red"}}> *</span> </label>
<select className="input" name="bridemaritalstatus" value={value.bridemaritalstatus} onChange={inputChange('bridemaritalstatus')}>
<option value="0">Select marital status</option>
<option value="1">BACHELOR</option>
<option value="2">DIVORCE</option>
<option value="3">WIDOWER</option>
<option value="4">MARRIED</option>
</select>
<p style={{color:"red"}}>{this.state.bridemaritalstatuserror}</p>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Mobile Number<span style={{color:"red"}}> *</span></label>
<input type="mobile" className="input" name="bridemobilenumber" value={value.bridemobilenumber} onChange={inputChange('bridemobilenumber')}/>
<p style={{color:"red"}}>{this.state.bridemobilenumbererror}</p>
</div>
</div>
<div class="col-md-3">
<div className="form-group">
<label>Whatsapp Number<span style={{color:"red"}}> *</span></label>
<input type="whatsapp" className="input" name="bridewhatsapp" value={value.bridewhatsapp} onChange={inputChange('bridewhatsapp')} />
<p style={{color:"red"}}>{this.state.bridewhatsapperror}</p>
</div>
</div>
</div>
<div className="row">
<div class="col-md-3">
<label>Email Address<span style={{color:"red"}}> *</span></label>
<input type="text" className="input" name="brideemail" value={value.brideemail} onChange={inputChange('brideemail')} />
<p style={{color:"red"}}>{this.state.brideemailerror}</p>
</div>
</div>
<br></br>
<div class="row"><div class="col-md-12"> <label >Residential Address<span style={{color:"red"}}> *</span></label></div></div>
<div class="row">
<br></br>
<div class="col-md-3">
<label>Street<span style={{color:"red"}}> *</span></label>
<input type="text" className="input" name="Street3" value={value.Street3} onChange={inputChange('Street3')} />
<p style={{color:"red"}}>{this.state.Street3error}</p>
</div>
<div class="col-md-3">
<label>Village<span style={{color:"red"}}> *</span></label>
<input type="text" className="input" name="Village3" value={value.Village3} onChange={inputChange('Village3')} />
<p style={{color:"red"}}>{this.state.Village3error}</p>
</div>
<div class="col-md-3">
<label>Taluk<span style={{color:"red"}}> *</span></label>
<input type="text" className="input" name="Taluk3" value={value.Taluk3} onChange={inputChange('Taluk3')} />
<p style={{color:"red"}}>{this.state.Taluk3error}</p>
</div>
<div class="col-md-3">
<label>District<span style={{color:"red"}}> *</span></label>
<input type="text" className="input" name="District3" value={value.District3} onChange={inputChange('District3')} />
<p style={{color:"red"}}>{this.state.District3error}</p>
</div>
</div>
<br></br>
<div class="row">
<div class="col-md-3">
<label>State<span style={{color:"red"}}> *</span></label>
<input type="text" className="input" name="State3" value={value.State3} onChange={inputChange('State3')} />
<p style={{color:"red"}}>{this.state.State3error}</p>
</div>
<div class="col-md-3">
<label>Country<span style={{color:"red"}}> *</span></label>
<input type="text" className="input" name="Country3" value={value.Country3} onChange={inputChange('Country3')} />
<p style={{color:"red"}}>{this.state.Country3error}</p>
</div>
<div class="col-md-3">
<label>Pincode<span style={{color:"red"}}> *</span></label>
<input type="text" className="input" name="Pincode3" value={value.Pincode3} onChange={inputChange('Pincode3')} />
<p style={{color:"red"}}>{this.state.Pincode3error}</p>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Passport Number<span style={{color:"red"}}> *</span></label>
<input type="text" className="input" name="bridepassport" value={value.bridepassport} onChange={inputChange('bridepassport')}/>
<p style={{color:"red"}}>{this.state.bridepassporterror}</p>
</div>
</div>
</div>
<br></br>
</div>
</div>
<div className="row">
<div className="col-md-6">
<button className="pev m-4" onClick={this.back}>Previous</button>
</div>
<div className="col-md-6">
<div className="text-right">
<button className="next m-4" onClick={this.continue}>Next</button>
</div>
</div>
</div><br></br><br></br> <br></br><br></br> <br></br>
</div>
</div>
</div>
)
}
}
export default Bride |
// Why Array
var friend1 = 'Farhad Hossen'
var friend2 = 'Siam'
var friend3 = 'Fardeen Rahman'
var friend4 = 'Jubaier Rahman'
var friend5 = 'Sakib Al Islam'
var friend6 = 'Shakif'
// Array Declartion
// var friends = [
// 'Farhad Hossen',
// 'Siam',
// 'Fardeen',
// 'Jubaier',
// 'Sakib',
// 'Shakif'
// ];
// console.log(friends)
// Array Access
// console.log(friends[0])
// console.log(friends[1])
// console.log(friends[2])
// console.log(friends[3])
// console.log(friends[4])
// Array Index
// Array Elemnts
// console.log(friends.length)
// for(i = 0; i < friends.length; i++) {
// console.log(i, friends[i])
// }
// Access Arrlay Elents with For Loops
// for(i in friends) console.log(friends[i])
// for(i of friends) console.log(i)
// Object + Array
// var student1 = {
// roll: 1,
// firstName: 'Sakib',
// lastName: 'Sultan'
// }
var students = [
{
roll: 1,
firstName: 'Sakib',
lastName: 'Sultan',
subjects: ['English', 'Bangla', 'Match', 'Science']
},
{
roll: 2,
firstName: 'Farhad',
lastName: 'Hossen'
},
{
roll: 3,
firstName: 'Hasan',
lastName: 'Sharif'
},
{
roll: 4,
firstName: 'Mohidul',
lastName: 'Islam'
}
]
console.log(students[0].subjects[0])
// for(student of students) {
// console.log(student.roll, student.firstName)
// } |
import $ from '../../core/renderer';
import { noop } from '../../core/utils/common';
import { getWindow, hasWindow } from '../../core/utils/window';
import domAdapter from '../../core/dom_adapter';
import { isNumeric, isFunction, isDefined, isObject as _isObject, type } from '../../core/utils/type';
import { each } from '../../core/utils/iterator';
import _windowResizeCallbacks from '../../core/utils/resize_callbacks';
import { extend } from '../../core/utils/extend';
import { BaseThemeManager } from '../core/base_theme_manager';
import DOMComponent from '../../core/dom_component';
import { changes, replaceInherit } from './helpers';
import { parseScalar as _parseScalar } from './utils';
import warnings from './errors_warnings';
import { Renderer } from './renderers/renderer';
import _Layout from './layout';
import devices from '../../core/devices';
import eventsEngine from '../../events/core/events_engine';
import { when } from '../../core/utils/deferred';
import { createEventTrigger, createResizeHandler, createIncidentOccurred } from './base_widget.utils';
var _floor = Math.floor;
var _log = warnings.log;
var OPTION_RTL_ENABLED = 'rtlEnabled';
var SIZED_ELEMENT_CLASS = 'dx-sized-element';
var _option = DOMComponent.prototype.option;
function getTrue() {
return true;
}
function getFalse() {
return false;
}
function areCanvasesDifferent(canvas1, canvas2) {
return !(canvas1.width === canvas2.width && canvas1.height === canvas2.height && canvas1.left === canvas2.left && canvas1.top === canvas2.top && canvas1.right === canvas2.right && canvas1.bottom === canvas2.bottom);
}
function defaultOnIncidentOccurred(e) {
if (!e.component._eventsStrategy.hasEvent('incidentOccurred')) {
_log.apply(null, [e.target.id].concat(e.target.args || []));
}
}
function pickPositiveValue(values) {
return values.reduce(function (result, value) {
return value > 0 && !result ? value : result;
}, 0);
} // TODO - Changes handling
// * Provide more validation - something like
// _changes: [{
// code: "THEME",
// options: ["theme"],
// type: "option",
// handler: function () {
// this._setThemeAndRtl();
// }
// }, {
// code: "CONTAINER_SIZE",
// options: ["size", "option"],
// type: "layout",
// handler: function () {
// this._updateSize();
// }
// }]
var getEmptyComponent = function getEmptyComponent() {
var emptyComponentConfig = {
_initTemplates() {},
ctor(element, options) {
this.callBase(element, options);
var sizedElement = domAdapter.createElement('div');
var width = options && isNumeric(options.width) ? options.width + 'px' : '100%';
var height = options && isNumeric(options.height) ? options.height + 'px' : this._getDefaultSize().height + 'px';
domAdapter.setStyle(sizedElement, 'width', width);
domAdapter.setStyle(sizedElement, 'height', height);
domAdapter.setClass(sizedElement, SIZED_ELEMENT_CLASS);
domAdapter.insertElement(element, sizedElement);
}
};
var EmptyComponent = DOMComponent.inherit(emptyComponentConfig);
var originalInherit = EmptyComponent.inherit;
EmptyComponent.inherit = function (config) {
for (var field in config) {
if (isFunction(config[field]) && field.substr(0, 1) !== '_' && field !== 'option' || field === '_dispose' || field === '_optionChanged') {
config[field] = noop;
}
}
return originalInherit.call(this, config);
};
return EmptyComponent;
};
function callForEach(functions) {
functions.forEach(c => c());
}
var isServerSide = !hasWindow();
function sizeIsValid(value) {
return isDefined(value) && value > 0;
}
var baseWidget = isServerSide ? getEmptyComponent() : DOMComponent.inherit({
_eventsMap: {
'onIncidentOccurred': {
name: 'incidentOccurred'
},
'onDrawn': {
name: 'drawn'
}
},
_getDefaultOptions: function _getDefaultOptions() {
return extend(this.callBase(), {
onIncidentOccurred: defaultOnIncidentOccurred
});
},
_useLinks: true,
_init: function _init() {
var that = this;
that._$element.children('.' + SIZED_ELEMENT_CLASS).remove();
that.callBase.apply(that, arguments);
that._changesLocker = 0;
that._optionChangedLocker = 0;
that._asyncFirstDrawing = true;
that._changes = changes();
that._suspendChanges();
that._themeManager = that._createThemeManager();
that._themeManager.setCallback(function () {
that._requestChange(that._themeDependentChanges);
});
that._renderElementAttributes();
that._initRenderer(); // Shouldn't "_useLinks" be passed to the renderer instead of doing 3 checks here?
var linkTarget = that._useLinks && that._renderer.root; // There is an implicit relation between `_useLinks` and `loading indicator` - it uses links
// Though this relation is not ensured in code we will immediately know when it is broken - `loading indicator` will break on construction
linkTarget && linkTarget.enableLinks().virtualLink('core').virtualLink('peripheral');
that._renderVisibilityChange();
that._attachVisibilityChangeHandlers();
that._toggleParentsScrollSubscription(this._isVisible());
that._initEventTrigger();
that._incidentOccurred = createIncidentOccurred(that.NAME, that._eventTrigger);
that._layout = new _Layout(); // Such solution is used only to avoid writing lots of "after" for all core elements in all widgets
// May be later a proper solution would be found
linkTarget && linkTarget.linkAfter('core');
that._initPlugins();
that._initCore();
linkTarget && linkTarget.linkAfter();
that._change(that._initialChanges);
},
_createThemeManager() {
return new BaseThemeManager(this._getThemeManagerOptions());
},
_getThemeManagerOptions() {
return {
themeSection: this._themeSection,
fontFields: this._fontFields
};
},
_initialChanges: ['LAYOUT', 'RESIZE_HANDLER', 'THEME', 'DISABLED'],
_initPlugins: function _initPlugins() {
var that = this;
each(that._plugins, function (_, plugin) {
plugin.init.call(that);
});
},
_disposePlugins: function _disposePlugins() {
var that = this;
each(that._plugins.slice().reverse(), function (_, plugin) {
plugin.dispose.call(that);
});
},
_change: function _change(codes) {
this._changes.add(codes);
},
_suspendChanges: function _suspendChanges() {
++this._changesLocker;
},
_resumeChanges: function _resumeChanges() {
var that = this;
if (--that._changesLocker === 0 && that._changes.count() > 0 && !that._applyingChanges) {
that._renderer.lock();
that._applyingChanges = true;
that._applyChanges();
that._changes.reset();
that._applyingChanges = false;
that._changesApplied();
that._renderer.unlock();
if (that._optionsQueue) {
that._applyQueuedOptions();
}
that.resolveItemsDeferred(that._legend ? [that._legend] : []);
that._optionChangedLocker++;
that._notify();
that._optionChangedLocker--;
}
},
resolveItemsDeferred(items) {
this._resolveDeferred(this._getTemplatesItems(items));
},
_collectTemplatesFromItems(items) {
return items.reduce((prev, i) => {
return {
items: prev.items.concat(i.getTemplatesDef()),
groups: prev.groups.concat(i.getTemplatesGroups())
};
}, {
items: [],
groups: []
});
},
_getTemplatesItems(items) {
var elements = this._collectTemplatesFromItems(items);
var extraItems = this._getExtraTemplatesItems();
return {
items: extraItems.items.concat(elements.items),
groups: extraItems.groups.concat(elements.groups),
launchRequest: [extraItems.launchRequest],
doneRequest: [extraItems.doneRequest]
};
},
_getExtraTemplatesItems() {
return {
items: [],
groups: [],
launchRequest: () => {},
doneRequest: () => {}
};
},
_resolveDeferred(_ref) {
var {
items,
launchRequest,
doneRequest,
groups
} = _ref;
var that = this;
that._setGroupsVisibility(groups, 'hidden');
if (that._changesApplying) {
that._changesApplying = false;
callForEach(doneRequest);
return;
}
var syncRendering = true;
when.apply(that, items).done(() => {
if (syncRendering) {
that._setGroupsVisibility(groups, 'visible');
return;
}
callForEach(launchRequest);
that._changesApplying = true;
var changes = ['LAYOUT', 'FULL_RENDER'];
if (that._asyncFirstDrawing) {
changes.push('FORCE_FIRST_DRAWING');
that._asyncFirstDrawing = false;
} else {
changes.push('FORCE_DRAWING');
}
that._requestChange(changes);
that._setGroupsVisibility(groups, 'visible');
});
syncRendering = false;
},
_setGroupsVisibility(groups, visibility) {
groups.forEach(g => g.attr({
visibility: visibility
}));
},
_applyQueuedOptions: function _applyQueuedOptions() {
var that = this;
var queue = that._optionsQueue;
that._optionsQueue = null;
that.beginUpdate();
each(queue, function (_, action) {
action();
});
that.endUpdate();
},
_requestChange: function _requestChange(codes) {
this._suspendChanges();
this._change(codes);
this._resumeChanges();
},
_applyChanges: function _applyChanges() {
var that = this;
var changes = that._changes;
var order = that._totalChangesOrder;
var i;
var ii = order.length;
for (i = 0; i < ii; ++i) {
if (changes.has(order[i])) {
that['_change_' + order[i]]();
}
}
},
_optionChangesOrder: ['EVENTS', 'THEME', 'RENDERER', 'RESIZE_HANDLER'],
_layoutChangesOrder: ['ELEMENT_ATTR', 'CONTAINER_SIZE', 'LAYOUT'],
_customChangesOrder: ['DISABLED'],
_change_EVENTS: function _change_EVENTS() {
this._eventTrigger.applyChanges();
},
_change_THEME: function _change_THEME() {
this._setThemeAndRtl();
},
_change_RENDERER: function _change_RENDERER() {
this._setRendererOptions();
},
_change_RESIZE_HANDLER: function _change_RESIZE_HANDLER() {
this._setupResizeHandler();
},
_change_ELEMENT_ATTR: function _change_ELEMENT_ATTR() {
this._renderElementAttributes();
this._change(['CONTAINER_SIZE']);
},
_change_CONTAINER_SIZE: function _change_CONTAINER_SIZE() {
this._updateSize();
},
_change_LAYOUT: function _change_LAYOUT() {
this._setContentSize();
},
_change_DISABLED: function _change_DISABLED() {
var renderer = this._renderer;
var root = renderer.root;
if (this.option('disabled')) {
this._initDisabledState = root.attr('pointer-events');
root.attr({
'pointer-events': 'none',
filter: renderer.getGrayScaleFilter().id
});
} else {
if (root.attr('pointer-events') === 'none') {
root.attr({
'pointer-events': isDefined(this._initDisabledState) ? this._initDisabledState : null,
'filter': null
});
}
}
},
_themeDependentChanges: ['RENDERER'],
_initRenderer: function _initRenderer() {
var that = this; // Canvas is calculated before the renderer is created in order to capture actual size of the container
that._canvas = that._calculateCanvas();
that._renderer = new Renderer({
cssClass: that._rootClassPrefix + ' ' + that._rootClass,
pathModified: that.option('pathModified'),
container: that._$element[0]
});
that._renderer.resize(that._canvas.width, that._canvas.height);
},
_disposeRenderer: function _disposeRenderer() {
this._renderer.dispose();
},
_getAnimationOptions: noop,
render: function render() {
this._requestChange(['CONTAINER_SIZE']);
var visible = this._isVisible();
this._toggleParentsScrollSubscription(visible);
!visible && this._stopCurrentHandling();
},
_toggleParentsScrollSubscription: function _toggleParentsScrollSubscription(subscribe) {
var $parents = $(this._renderer.root.element).parents();
var scrollEvents = 'scroll.viz_widgets';
if (devices.real().platform === 'generic') {
$parents = $parents.add(getWindow());
}
this._proxiedTargetParentsScrollHandler = this._proxiedTargetParentsScrollHandler || function () {
this._stopCurrentHandling();
}.bind(this);
eventsEngine.off($().add(this._$prevRootParents), scrollEvents, this._proxiedTargetParentsScrollHandler);
if (subscribe) {
eventsEngine.on($parents, scrollEvents, this._proxiedTargetParentsScrollHandler);
this._$prevRootParents = $parents;
}
},
_stopCurrentHandling: noop,
_dispose: function _dispose() {
var that = this;
that.callBase.apply(that, arguments);
that._toggleParentsScrollSubscription(false);
that._removeResizeHandler();
that._layout.dispose();
that._eventTrigger.dispose();
that._disposeCore();
that._disposePlugins();
that._disposeRenderer();
that._themeManager.dispose();
that._themeManager = that._renderer = that._eventTrigger = null;
},
_initEventTrigger: function _initEventTrigger() {
var that = this;
that._eventTrigger = createEventTrigger(that._eventsMap, function (name) {
return that._createActionByOption(name);
});
},
_calculateCanvas: function _calculateCanvas() {
var that = this;
var size = that.option('size') || {};
var margin = that.option('margin') || {};
var defaultCanvas = that._getDefaultSize() || {};
var getSizeOfSide = (size, side) => {
if (sizeIsValid(size[side]) || !hasWindow()) {
return 0;
}
var elementSize = that._$element[side]();
return elementSize <= 1 ? 0 : elementSize;
};
var elementWidth = getSizeOfSide(size, 'width');
var elementHeight = getSizeOfSide(size, 'height');
var canvas = {
width: size.width <= 0 ? 0 : _floor(pickPositiveValue([size.width, elementWidth, defaultCanvas.width])),
height: size.height <= 0 ? 0 : _floor(pickPositiveValue([size.height, elementHeight, defaultCanvas.height])),
left: pickPositiveValue([margin.left, defaultCanvas.left]),
top: pickPositiveValue([margin.top, defaultCanvas.top]),
right: pickPositiveValue([margin.right, defaultCanvas.right]),
bottom: pickPositiveValue([margin.bottom, defaultCanvas.bottom])
}; // This for backward compatibility - widget was not rendered when canvas is empty.
// Now it will be rendered but because of "width" and "height" of the root both set to 0 it will not be visible.
if (canvas.width - canvas.left - canvas.right <= 0 || canvas.height - canvas.top - canvas.bottom <= 0) {
canvas = {
width: 0,
height: 0
};
}
return canvas;
},
_updateSize: function _updateSize() {
var that = this;
var canvas = that._calculateCanvas();
that._renderer.fixPlacement();
if (areCanvasesDifferent(that._canvas, canvas) || that.__forceRender
/* for charts */
) {
that._canvas = canvas;
that._recreateSizeDependentObjects(true);
that._renderer.resize(canvas.width, canvas.height);
that._change(['LAYOUT']);
}
},
_recreateSizeDependentObjects: noop,
_getMinSize: function _getMinSize() {
return [0, 0];
},
_getAlignmentRect: noop,
_setContentSize: function _setContentSize() {
var canvas = this._canvas;
var layout = this._layout;
var rect = canvas.width > 0 && canvas.height > 0 ? [canvas.left, canvas.top, canvas.width - canvas.right, canvas.height - canvas.bottom] : [0, 0, 0, 0];
rect = layout.forward(rect, this._getMinSize());
var nextRect = this._applySize(rect) || rect;
layout.backward(nextRect, this._getAlignmentRect() || nextRect);
},
_getOption: function _getOption(name, isScalar) {
var theme = this._themeManager.theme(name);
var option = this.option(name);
return isScalar ? option !== undefined ? option : theme : extend(true, {}, theme, option);
},
_setupResizeHandler: function _setupResizeHandler() {
var that = this;
var redrawOnResize = _parseScalar(this._getOption('redrawOnResize', true), true);
if (that._resizeHandler) {
that._removeResizeHandler();
}
that._resizeHandler = createResizeHandler(function () {
if (redrawOnResize) {
that._requestChange(['CONTAINER_SIZE']);
} else {
that._renderer.fixPlacement();
}
});
_windowResizeCallbacks.add(that._resizeHandler);
},
_removeResizeHandler: function _removeResizeHandler() {
if (this._resizeHandler) {
_windowResizeCallbacks.remove(this._resizeHandler);
this._resizeHandler.dispose();
this._resizeHandler = null;
}
},
// This is actually added only to make loading indicator pluggable. This is bad but much better than entire loading indicator in BaseWidget.
_onBeginUpdate: noop,
beginUpdate: function beginUpdate() {
var that = this; // The "_initialized" flag is checked because first time "beginUpdate" is called in the constructor.
if (that._initialized && that._isUpdateAllowed()) {
that._onBeginUpdate();
that._suspendChanges();
}
that.callBase.apply(that, arguments);
return that;
},
endUpdate: function endUpdate() {
this.callBase();
this._isUpdateAllowed() && this._resumeChanges();
return this;
},
option: function option(name) {
var that = this; // NOTE: `undefined` has to be returned because base option setter returns `undefined`.
// `argument.length` and `isObject` checks are copypaste from Component.
if (that._initialized && that._applyingChanges && (arguments.length > 1 || _isObject(name))) {
that._optionsQueue = that._optionsQueue || [];
that._optionsQueue.push(that._getActionForUpdating(arguments));
} else {
return _option.apply(that, arguments);
}
},
_getActionForUpdating: function _getActionForUpdating(args) {
var that = this;
return function () {
_option.apply(that, args);
};
},
// For quite a long time the following method were abstract (from the Component perspective).
// Now they are not but that basic functionality is not required here.
_clean: noop,
_render: noop,
_optionChanged: function _optionChanged(arg) {
var that = this;
if (that._optionChangedLocker) {
return;
}
var partialChanges = that.getPartialChangeOptionsName(arg);
var changes = [];
if (partialChanges.length > 0) {
partialChanges.forEach(pc => changes.push(that._partialOptionChangesMap[pc]));
} else {
changes.push(that._optionChangesMap[arg.name]);
}
changes = changes.filter(c => !!c);
if (that._eventTrigger.change(arg.name)) {
that._change(['EVENTS']);
} else if (changes.length > 0) {
that._change(changes);
} else {
that.callBase.apply(that, arguments);
}
},
_notify: noop,
_changesApplied: noop,
_optionChangesMap: {
size: 'CONTAINER_SIZE',
margin: 'CONTAINER_SIZE',
redrawOnResize: 'RESIZE_HANDLER',
theme: 'THEME',
rtlEnabled: 'THEME',
encodeHtml: 'THEME',
elementAttr: 'ELEMENT_ATTR',
disabled: 'DISABLED'
},
_partialOptionChangesMap: {},
_partialOptionChangesPath: {},
getPartialChangeOptionsName: function getPartialChangeOptionsName(changedOption) {
var that = this;
var fullName = changedOption.fullName;
var sections = fullName.split(/[.]/);
var name = changedOption.name;
var value = changedOption.value;
var options = this._partialOptionChangesPath[name];
var partialChangeOptionsName = [];
if (options) {
if (options === true) {
partialChangeOptionsName.push(name);
} else {
options.forEach(op => {
fullName.indexOf(op) >= 0 && partialChangeOptionsName.push(op);
});
if (sections.length === 1) {
if (type(value) === 'object') {
that._addOptionsNameForPartialUpdate(value, options, partialChangeOptionsName);
} else if (type(value) === 'array') {
if (value.length > 0 && value.every(item => that._checkOptionsForPartialUpdate(item, options))) {
value.forEach(item => that._addOptionsNameForPartialUpdate(item, options, partialChangeOptionsName));
}
}
}
}
}
return partialChangeOptionsName.filter((value, index, self) => self.indexOf(value) === index);
},
_checkOptionsForPartialUpdate: function _checkOptionsForPartialUpdate(optionObject, options) {
return !Object.keys(optionObject).some(key => options.indexOf(key) === -1);
},
_addOptionsNameForPartialUpdate: function _addOptionsNameForPartialUpdate(optionObject, options, partialChangeOptionsName) {
var optionKeys = Object.keys(optionObject);
if (this._checkOptionsForPartialUpdate(optionObject, options)) {
optionKeys.forEach(key => options.indexOf(key) > -1 && partialChangeOptionsName.push(key));
}
},
_visibilityChanged: function _visibilityChanged() {
this.render();
},
_setThemeAndRtl: function _setThemeAndRtl() {
this._themeManager.setTheme(this.option('theme'), this.option(OPTION_RTL_ENABLED));
},
_getRendererOptions: function _getRendererOptions() {
return {
rtl: this.option(OPTION_RTL_ENABLED),
encodeHtml: this.option('encodeHtml'),
animation: this._getAnimationOptions()
};
},
_setRendererOptions: function _setRendererOptions() {
this._renderer.setOptions(this._getRendererOptions());
},
svg: function svg() {
return this._renderer.svg();
},
getSize: function getSize() {
var canvas = this._canvas || {};
return {
width: canvas.width,
height: canvas.height
};
},
isReady: getFalse,
_dataIsReady: getTrue,
_resetIsReady: function _resetIsReady() {
this.isReady = getFalse;
},
_drawn: function _drawn() {
var that = this;
that.isReady = getFalse;
if (that._dataIsReady()) {
that._renderer.onEndAnimation(function () {
that.isReady = getTrue;
});
}
that._eventTrigger('drawn', {});
}
});
export default baseWidget;
replaceInherit(baseWidget); |
import firebase from 'firebase'
import axios from 'axios'
const ENDPOINT = process.env.REACT_APP_BACKEND_URL;
class API {
static getVideoURL(code) {
return "https://media.w3.org/2010/05/sintel/trailer_hd.mp4"
}
static async getCharityProjects() {
let charityProjects = await fetch(`${ENDPOINT}/charity_projects`, {
method: 'GET'
});
return charityProjects.json()
}
static async getCharityProject(id){
let charityProject = await fetch(`${ENDPOINT}/charity_projects/${id}`, {
method: 'GET'
});
if(charityProject.status !== 200) throw Error;
return charityProject.json()
}
static uploadVideo(data, callback) {
return new Promise((accept, reject) => {
let file = data.get('file');
let storage = firebase.storage();
let storageRef = storage.ref();
let uploadTask = storageRef.child(`videos/${file.name}`).put(file);
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, null, (error) => {
reject(error)
}, () => {
uploadTask.snapshot.ref.getDownloadURL()
.then(url => {
accept(url)
})
})
});
}
static async makeDonation(data) {
console.log(data);
await axios.post(`${ENDPOINT}/donations`, data);
}
static async getGift(token) {
let gift = await axios.get(`${ENDPOINT}/gifts`, {
params: {
token: token
}
});
return gift.data
}
static async getQuestionnaire(id) {
let questionnaire = await axios.get(`${ENDPOINT}/questionnaires/${id}`)
return questionnaire.data
}
}
export default API |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { carsShowAll, carsUpdate } from '../actions';
import Car from './Car'
import EditedCar from './EditedCar'
const carsAPI = 'http://rawlovel.test/api/cars'
class CarList extends Component {
constructor(props) {
super(props)
this.state = {
isEdited: false,
ind: 0,
value: ''
}
this.switchEditedCar = this.switchEditedCar.bind(this)
}
componentDidMount() {
this.props.showAll(carsAPI);
}
switchEditedCar(ind){
if (this.state.isEdited && ind !== this.state.ind) {
this.props.update(carsAPI, {id: this.props.cars[parseInt(ind)].id, name: this.state.value})
this.setState({isEdited:false})
}
if (!this.state.isEdited) this.setState({isEdited:true, ind})
}
render() {
if (this.props.hasError) {
return <p>Sorry! There was an error loading the items</p>;
}
if (this.props.isPending) {
return <p>Loading…</p>;
}
return (
<ul>
{this.props.cars.map((car, ind) => (
(ind == this.state.ind && this.state.isEdited) ?
<EditedCar key={ind} ind={ind} onUpdate={(ind, value)=>this.setState({ind, value})}/> :
<Car key={ind} ind={ind} editCar={this.switchEditedCar} name={car.name}/>
))}
</ul>
);
}
}
CarList.propTypes = {
showAll: PropTypes.func.isRequired,
cars: PropTypes.array.isRequired,
hasError: PropTypes.bool.isRequired,
isPending: PropTypes.bool.isRequired
};
const mapStateToProps = (state) => {
return {
cars: state.cars,
hasError: state.carsRequestError,
isPending: state.carsRequestPending
};
};
const mapDispatchToProps = (dispatch) => {
return {
showAll: (url) => dispatch(carsShowAll(url)),
update: (url, payload) => dispatch(carsUpdate(url, payload))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(CarList); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.