text
stringlengths 65
6.05M
| lang
stringclasses 8
values | type
stringclasses 2
values | id
stringlengths 64
64
|
|---|---|---|---|
import _ from "lodash";
// import Plugin from "@ckeditor/ckeditor5-core/src/plugin";
import {modelAttrName, createCommentElement, viewAttrName} from "./commands/element";
import CreateCommand from "./commands/create";
import DeleteCommand from "./commands/delete";
import ReflowCommand from "./commands/reflow";
import UnselectCommand from "./commands/unselect";
import ActivateCommand from "./commands/activate";
import {downcastAttributeToElement} from "@ckeditor/ckeditor5-engine/src/conversion/downcast-converters";
import {upcastElementToAttribute} from "@ckeditor/ckeditor5-engine/src/conversion/upcast-converters";
// import bindTwoStepCaretToAttribute from "@ckeditor/ckeditor5-engine/src/utils/bindtwostepcarettoattribute";
export default function CommentsEngine (editor) {
console.log("from kit!");
editor.model.schema.extend("$text", {allowAttributes: modelAttrName});
editor.conversion
.for("downcast")
.add(downcastAttributeToElement({model: modelAttrName, view: createCommentElement}));
editor.conversion
.for("upcast")
.add(upcastElementToAttribute({
view: {
name: "span",
attributes: {
[viewAttrName]: true,
},
},
model: {
key: modelAttrName,
value: viewElement => viewElement.getAttribute(viewAttrName),
},
}));
// bindTwoStepCaretToAttribute(editor.editing.view, editor.model, this, modelAttrName);
// Create linking commands.
editor.commands.add("comments:create", new CreateCommand(editor));
editor.commands.add("comments:delete", new DeleteCommand(editor));
editor.commands.add("comments:activate", new ActivateCommand(editor));
editor.commands.add("comments:unselect", new UnselectCommand(editor));
const cmdReflow = new ReflowCommand(editor);
editor.commands.add("comments:reflow", cmdReflow);
editor.editing.view.on("render", _.throttle(() => cmdReflow.execute(), 300));
}
|
JavaScript
|
CL
|
4a31e6198780baa51f805ed6d0e825aa03b972a46f6c15fefaff03a207d5609d
|
import 'react-native';
import React from 'react';
import renderer from 'react-test-renderer';
import Enzyme from 'enzyme';
import {shallow} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import toJson from 'enzyme-to-json'; //added this line
import Create from './Create';
Enzyme.configure({ adapter: new Adapter() });
describe('Testing Creating component', () => {
it('renders as expected', () => {
const setRouteLeaveHook = jest.fn();
const wrapper = shallow(
<Create.WrappedComponent params={{router:
setRouteLeaveHook}}/>
);
expect(wrapper.state().st).toEqual("");
});
});
|
JavaScript
|
CL
|
ade6653fb6fb13d81e9266da4033f3262f5f1191e134d68285b5668b21cf7668
|
'use strict';
/////////////////////////////////////
/* Problem 1 (this is your demo that we'll solve in class)
Write a function called sum() that takes in two numbers as arguments and then returns an array where the first element is the sum of those numbers, and the second element is a concatenated string that EXACTLY follows this example and uses the values that were input into the function:
"The sum of 4 and 7 is 11."
Test this function by hand in the console to get it working, and when you think it is finished, uncomment the call for the testSum() function below and check the console to see if the test passes.*/
// Write your code here
function sum(a, b) {
let arr = [];
let sumAnswer = a + b;
arr[0] = sumAnswer
let result = 'The sum of '+a+' and '+b+' is '+sumAnswer+'.'
arr[1] = result;
return arr;
}
console.log(sum(4,7));
// Here is the test for sum(); uncomment it to run it
testSum(4, 7);
// Once you get the test passing, do an a-c-p cycle and synchronize the code between GitHub and your laptop. Don't forget to create a new branch for your work on the next question!
/////////////////////////////////////
/* Problem 2
Write a function called multiply() that takes in two numbers as arguments and returns an array where the first element is the product of those numbers, and the second element is a string that EXACTLY follows this example and uses the values that were input into the function:
"The product of 5 and 9 is 45."
Test this function by hand in the console to get it working, and when you think it is finished, uncomment the call for the testMultiply() function and see if the test passes.*/
// Write your code here
function multiply(a, b) {
let multiArr = [];
let theAns = a * b;
multiArr[0] = theAns;
multiArr[1] = 'The product of ' +a+ ' and '+b+' is '+theAns+'.'
return multiArr;
}
console.log(multiply(5,9));
// Here is the test for multiply(); uncomment it to run it
testMultiply(5, 9);
// Once you get the test passing, do an a-c-p cycle and synchronize the code between GitHub and your laptop. Don't forget to create a new branch for your work on the next question!
/////////////////////////////////////
/* Problem 3
Write a function called sumAndMultiply() that takes in three numbers as separate arguments and returns an array where the first element is the sum of those three numbers, the second element is the product of those three numbers, and the third and fourth elements are strings that EXACTLY follow this example and use the values that were input into the function:
Third element: "4 and 7 and 5 sum to 16."
Fourth element: "The product of 4 and 7 and 5 is 140."
IMPORTANT DETAIL: You may not use the arithmetic operators + and * in this function. To do addition, use your sum() function, and to do multiplication, use your multiply() function that you've already created. You're going to have to be resourceful to figure out how to do this. However, you may continue to use the + operator for string concatenation.
Test this function by hand in the console to get it working, and when you think it is finished, uncomment the call for the testSumAndMultiply() function and see if the test passes.*/
// Write your code here
function sumAndMultiply(a, b, c) {
let sumAndMultiplyArr = []
let aAndB = sum(a, b)[0];
let lastSum = sum(aAndB, c)[0];
sumAndMultiplyArr[0] = lastSum;
let aMultiB = multiply(a, b)[0];
let lastMulti = multiply(aMultiB, c)[0];
sumAndMultiplyArr[1] = lastMulti;
sumAndMultiplyArr[2] = ''+a+' and '+b+' and '+c+' sum to '+lastSum+'.';
sumAndMultiplyArr[3] = 'The product of '+a+' and '+b+' and '+c+' is '+lastMulti+'.';
return sumAndMultiplyArr;
}
console.log(sumAndMultiply(4,7,5));
// Here is the test for sumAndMultiply(); uncomment it to run it
testSumAndMultiply(4, 7, 5);
// Once you get the test passing, do an a-c-p cycle and synchronize the code between GitHub and your laptop. Don't forget to create a new branch for your work on the next question!
/////////////////////////////////////
/* Problem 4
Write a function called sumArray() that takes in an array of numbers as its single argument and then returns an array where the first element is the sum of the numbers in the array, and the second element is a string that EXACTLY follows this example and uses the values that were input into the function:
"2,3,4 was passed in as an array of numbers, and 9 is their sum."
IMPORTANT DETAIL: You may not use the arithmetic operator + in this function. To do addition, use your sum() function that you've already created. You're going to have to be resourceful to figure out how to do this. However, you may continue to use the + operator for string concatenation.
Test this function by hand in the console to get it working, and when you think it is finished, uncomment the call for the testSumArray() function and see if the test passes.*/
// Write your code here
let testArray = [2, 3, 4]; //eslint-disable-line
function sumArray(sumArr) {
let retArr = [];
let aAndB = sum((sumArr[0]), (sumArr[1]));
aAndB = aAndB[0];
let lastSum = sum(aAndB, sumArr[2])[0];
retArr[0] = lastSum;
retArr[1] = ''+sumArr[0]+','+sumArr[1]+','+sumArr[2]+' was passed in as an array of numbers, and '+lastSum+' is their sum.';
return retArr;
}
console.log(sumArray(testArray));
// Here is the test for sumArray(); uncomment it to run it
testSumArray(testArray);
// Once you get the test passing, do an a-c-p cycle and synchronize the code between GitHub and your laptop. Don't forget to create a new branch for your work on the next question!
/////////////////////////////////////
/* Problem 5
Write a function called multiplyArray() that takes an array of numbers as its argument and returns an array whose first element is the product of those numbers, and the second element is a string that EXACTLY follows this example and uses the values that were input into the function:
"The numbers 2,3,4 have a product of 24."
IMPORTANT DETAIL: You may not use the arithmetic operator * in this function. To do multiplication, use your multiply() function that you've already created. You're going to have to be resourceful to figure out how to do this. This function should handle an array containing three elements. However, you may continue to use the + operator for string concatenation.
Test this function by hand in the console to get it working, and when you think it is finished, uncomment the call for the testMultiplyArray() function and see if the test passes.*/
// Write your code here
let multArr = [2,3,4];
function multiplyArray(multArr) {
let lastArray = [];
let aMultiplyB = multiply((multArr[0]), (multArr[1]));
aMultiplyB = aMultiplyB[0];
let lastProd = multiply(aMultiplyB, multArr[2]);
lastProd = lastProd[0];
lastArray[0] = lastProd;
lastArray[1] = 'The numbers '+multArr[0]+','+multArr[1]+','+multArr[2]+' have a product of '+lastProd+'.';
return lastArray;
}
console.log(multiplyArray(multArr));
// Here is the test for multiplyArray(); uncomment it to run it
testMultiplyArray(testArray);
// Once you get the test passing, do an a-c-p cycle and synchronize the code between GitHub and your laptop.
// You're done! Submit the link to the repo following the instructions in Canvas. Or, try out the stretch goal below...
// Don't forget to create a new branch for your work on the next question, if you attempt it.
/////////////////////////////////////
/* STRETCH GOAL: Problem 6
Write a function called multiplyAnyArray() that takes an array of numbers of any length as its argument and returns an array whose first element is the product of those numbers, and the second element is a string that EXACTLY follows this example and concatenates a message using the arguments that were passed into the function:
"The numbers 1,2,3,4,5 have a product of 120."
IMPORTANT DETAIL: You may not use the arithmetic operator * in this function. To do multiplication, use your multiply() function that you've already created. You're going to have to be resourceful to figure out how to do this. However, you may continue to use the + operator for string concatenation.
This function should be dynamic, accepting an array of any length.
Test this function by hand in the console to get it working, and when you think it is finished, uncomment the call for the testMultiplyAnyArray() function and see if the test passes.*/
// Write your code here
let testDynamicArray = [1, 2, 3, 4, 5]; //eslint-disable-line
function multiplyAnyArray(dynamicArray) {
let lastArray = [];
let num = dynamicArray.length;
let product;
let index = dynamicArray[0];
for (let i = 1; i < num + 1; i++) {
product = multiply(index, i);
index = product[0];
}
lastArray[0] = index;
lastArray[1] = ('The numbers '+dynamicArray+' have a product of '+index+'.')
return lastArray;
}
console.log(multiplyAnyArray(testDynamicArray));
// Here is the test for multiplyArray(); uncomment it to run it
testMultiplyAnyArray(testDynamicArray);
// Once you get the test passing, do an a-c-p cycle and synchronize the code between GitHub and your laptop. You're done! Submit the link to the repo following the instructions in Canvas.
|
JavaScript
|
CL
|
7deb6706b1a98e8cedebb2234c5fadd48d680d3567b31cc3b6512b3a9880f9a6
|
/**
* Copyright (c) 2012-2015 Netflix, Inc. All rights reserved.
*
* 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.
*/
/**
* <p>The user authentication data provides proof of user identity.</p>
*
* <p>Specific user authentication mechanisms should define their own user
* authentication data types.</p>
*
* <p>User authentication data is represented as
* {@code
* userauthdata = {
* "#mandatory" : [ "scheme"., "authdata" ],
* "scheme" : "string",
* "authdata" : object
* }} where
* <ul>
* <li>{@code scheme} is the user authentication scheme</li>
* <li>{@code authdata} is the scheme-specific authentication data</li>
* </ul></p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
var UserAuthenticationData;
var UserAuthenticationData$parse;
(function() {
/**
* JSON key user authentication scheme.
* @const
* @type {string}
*/
var KEY_SCHEME = "scheme";
/**
* JSON key user authentication data.
* @const
* @type {string}
*/
var KEY_AUTHDATA = "authdata";
UserAuthenticationData = util.Class.create({
/**
* Create a new user authentication data object with the specified user
* authentication scheme.
*
* @param {UserAuthenticationScheme} scheme the user authentication scheme.
* @constructor
* @interface
*/
init: function init(scheme) {
// The properties.
var props = {
scheme: { value: scheme, writable: false, configurable: false },
};
Object.defineProperties(this, props);
},
/**
* Returns the scheme-specific user authentication data. This method is
* expected to succeed unless there is an internal error.
*
* @return {Object} the authentication data JSON representation.
* @throws MslEncodingException if there was an error constructing the
* JSON representation.
*/
getAuthData: function() {},
/**
* @param {Object} that the object with which to compare.
* @return {boolean} true if this object is equal to that object.
*/
equals: function equals(that) {
if (this === that) return true;
if (!(that instanceof UserAuthenticationData)) return false;
return this.scheme == that.scheme;
},
/** @inheritDoc */
toJSON: function toJSON() {
var result = {};
result[KEY_SCHEME] = this.scheme.name;
result[KEY_AUTHDATA] = this.getAuthData();
return result;
},
});
/**
* <p>Construct a new user authentication data instance of the correct type
* from the provided JSON object.</p>
*
* <p>A master token may be required for certain user authentication
* schemes.</p>
*
* @param {MslContext} ctx MSL context.
* @param {MasterToken} masterToken the master token associated with the user
* authentication data. May be {@code null}.
* @param {Object} userAuthJO the JSON object.
* @param {{result: function(UserAuthenticationData), error: function(Error)}}
* callback the callback functions that will receive the user
* authentication data or any thrown exceptions.
* @return {UserAuthenticationData} the user authentication data concrete instance.
* @throws MslEncodingException if there is an error parsing the JSON.
* @throws MslUserAuthException if there is an error instantiating the user
* authentication data.
* @throws MslCryptoException if there is an error with the entity
* authentication data cryptography.
*/
UserAuthenticationData$parse = function UserAuthenticationData$parse(ctx, masterToken, userAuthJO, callback) {
AsyncExecutor(callback, function() {
var schemeName = userAuthJO[KEY_SCHEME];
var authdata = userAuthJO[KEY_AUTHDATA];
// Verify user authentication data.
if (typeof schemeName !== 'string' ||
typeof authdata !== 'object')
{
throw new MslEncodingException(MslError.JSON_PARSE_ERROR, "userauthdata " + JSON.stringify(userAuthJO));
}
// Verify user authentication scheme.
var scheme = ctx.getUserAuthenticationScheme(schemeName);
if (!scheme)
throw new MslUserAuthException(MslError.UNIDENTIFIED_USERAUTH_SCHEME, schemeName);
// Construct an instance of the concrete subclass.
var factory = ctx.getUserAuthenticationFactory(scheme);
if (!factory)
throw new MslUserAuthException(MslError.USERAUTH_FACTORY_NOT_FOUND, scheme.name);
factory.createData(ctx, masterToken, authdata, callback);
});
};
})();
|
JavaScript
|
CL
|
56420e387ee1467eb885902c24d921695056d4c454ed4607c00c9606866ae360
|
import React from 'react';
import { BrowserRouter, Switch, Route, withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { Typography, Grid } from '@material-ui/core';
import { withStyles } from '@material-ui/core/styles';
import styles from '../styles/deliveryStyles';
import Items from './Items';
import Menu from './Menu';
import { items } from './food_and_drinks';
import { addToOrder } from '../actions';
const mapStateToProps = function (store) {
return {
order: store.order
};
};
const mapDispatchToProps = dispatch => ({
addToOrder: el => {
dispatch(addToOrder(el));
// el.display = 'none'
}
})
class Delivery extends React.Component {
render() {
const { classes, history, match } = this.props;
return (
<BrowserRouter>
<div className={classes.root}>
<Menu match={match} history={history} />
<main className={classes.content}>
<Switch>
<Route path={`${match.path}/:name`} component={Items}/>
<Route path="*" component={ ()=> (
<div>
<Typography variant='h4' className={classes.header} gutterBottom>
Click items to add:
</Typography>
<Grid container spacing={8} justify="center" className={classes.container}>
{items.map((item) => (
item.contents.map((el) => (
<Grid item
key={el.text}
style={{width: `${el.space}`, cursor: 'pointer'}}
role='button'
tabIndex="0"
onClick={() => this.props.addToOrder(el)}>
<Typography variant="h2" style={{ backgroundColor: `${el.backgroundColor}`}}
className={classes.text}>
{el.text}
</Typography>
</Grid>
))
))}
</Grid>
</div>
)} />
</Switch>
</main>
</div>
</BrowserRouter>
);
}
}
export default withStyles(styles)(
withRouter(
connect(mapStateToProps, mapDispatchToProps)(Delivery)
)
);
|
JavaScript
|
CL
|
860f10cd4fb2c4b5fc904d54ee376aec7499af50a9e7652e94a1af27f1ae1dc1
|
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const TSLintPlugin = require('tslint-webpack-plugin')
const { s3BasePathFromEnv } = require('./helper')
const { baseWebpack } = require('./webpack.base.config')
const baseProdWebpack = {
mode: 'production',
}
module.exports = [
{
...baseWebpack,
...baseProdWebpack,
entry: ['@babel/polyfill', './src/lib/client-entry.tsx'],
target: 'web',
output: {
filename: 'client.[hash:8].js',
path: path.resolve(__dirname, '..', 'dist'),
publicPath: `/${s3BasePathFromEnv()}`,
libraryTarget: 'umd',
},
plugins: [
new TSLintPlugin({
files: [
'./src/**/*.ts',
'./src/**/*.tsx',
],
force: true,
fix: true,
typeCheck: true,
}),
new HtmlWebpackPlugin({
title: 'Hot Module Replacement',
template: './src/index.html',
}),
],
},
{
...baseWebpack,
...baseProdWebpack,
entry: './src/lib/server-entry.tsx',
target: 'node',
output: {
filename: 'server-bundle.js',
path: path.resolve(__dirname, '..', 'dist'),
libraryTarget: 'umd',
},
},
]
|
JavaScript
|
CL
|
c9c1a2241c3fca14c49794aedc2c492bd3d583b05e30a871e0989b0e568e0a01
|
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _stream = require("stream");
var _duplexify = _interopRequireDefault(require("duplexify"));
var _merge = _interopRequireDefault(require("merge2"));
var _unzip = _interopRequireDefault(require("../fs/unzip"));
var _parseFile = _interopRequireDefault(require("./parseFile"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Outputs GeoJSON Features
// fromZip is for formats where gdal reads from the unzipped folder
var _default = ({
fileFilter,
parser = _parseFile.default
}) => {
const inStream = new _stream.PassThrough();
const outStream = (0, _merge.default)({
objectMode: true
});
const out = _duplexify.default.obj(inStream, outStream); // start the work
function _ref(f) {
try {
outStream.add(parser(f));
} catch (err) {
out.destroy(err);
}
}
(0, _unzip.default)(inStream, {
fileFilter
}).then(({
files,
done
}) => {
if (files.length === 0) {
out.destroy(new Error('Invalid file, nothing found!'));
return;
}
(0, _stream.finished)(out, done);
files.forEach(_ref);
}).catch(err => {
inStream.emit('error', err); // triggers destroy of everything
});
return out;
};
exports.default = _default;
module.exports = exports.default;
|
JavaScript
|
CL
|
fca6c4ee7d743c507779f4bc34ddd56fbd4355e56f27620284654938291070c6
|
import React, {Component, Fragment} from 'react';
import queryString from "query-string";
import {environments as environmentsData} from "../../config/sample-data";
import * as constants from "../../config/constants/environments";
import ButtonIcon from "../../components/common/ButtonIcon";
import Divider from "../../components/common/Divider";
import DefaultProductCard from "../../components/dashboard/DefaultProductCard";
import ActionBar from "../../components/ActionBar";
import SimulationService from "../../services/SimulationService";
import EnvironmentService from "../../services/EnvironmentService";
import _ from "lodash";
import LoadingBox from "../../components/common/LoadingBox";
class EnvironmentIndex extends Component {
constructor(props) {
super(props);
const {search} = this.getFiltersFromQueryString();
this.state = {
environments: [],
display: 'grid',
filters: {
search: search || ''
},
isFetching: false
}
this.initialSearch = search;
}
componentDidMount() {
this.getEnvironments();
}
componentDidUpdate(prevProps, prevState, snapshot) {
const {search} = this.getFiltersFromQueryString();
const {location} = this.props;
// set state values based on change in query string due to navigation
if ((location.search !== prevProps.location.search) &&
(location.pathname === prevProps.location.pathname)) {
this.setState({filters: {search: search || ''}})
}
if (!_.isEqual(prevState.filters, this.state.filters)) {
this.getEnvironments();
}
}
getEnvironments() {
const {search} = this.state.filters;
this.setState({
isFetching: true
});
EnvironmentService.getEnvironments(search)
.then((response) => {
this.setState({
environments: response.data
});
})
.finally(() => {
this.setState({
isFetching: false
});
});
}
getFiltersFromQueryString() {
const filters = queryString.parse(this.props.location.search);
return {search: filters.search};
}
setFilter(filterType, value) {
const query = queryString.stringify({
...queryString.parse(this.props.location.search),
[filterType]: value
});
this.props.history.push({
pathname: this.props.location.path,
search: query
});
this.setState(prevState => ({filters: {...prevState.filters, [filterType]: value}}));
}
applySearch = (value) => {
this.setFilter('search', value);
}
changeDisplay(display) {
this.setState({display});
}
renderEnvironments() {
return this.state.environments.map((environment) => {
const {id, name, thumbnail, description} = environment;
return (
<DefaultProductCard {...{key: id, id, name, thumbnail, description}}/>
);
});
}
renderActionButtons() {
return (
<Fragment>
<ButtonIcon type="primary" size="lg" outline={this.state.display !== 'grid'} onClick={() => this.changeDisplay('grid')}>
<i className="fas fa-th-large"/>
</ButtonIcon>
<ButtonIcon type="primary" size="lg" outline={this.state.display !== 'list'} onClick={() => this.changeDisplay('list')}>
<i className="fas fa-list-ul"/>
</ButtonIcon>
</Fragment>
);
}
render() {
return (
<Fragment>
<ActionBar initialSearch={this.initialSearch} onSearchSubmit={this.applySearch}>
{this.renderActionButtons()}
</ActionBar>
<div className={`default-product-content ${(this.state.display === 'grid') ? 'grid' : 'list-display'}`}>
<div className='default-product-holder'>
{(this.state.isFetching) &&
<LoadingBox/>
}
{(!this.state.isFetching) &&
this.renderEnvironments()
}
</div>
</div>
</Fragment>
);
}
}
export default EnvironmentIndex;
|
JavaScript
|
CL
|
1692fb461966ad642f3b02e33c72cccf35b92bf4d360d17e39a712a18d2962e3
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// TODO(b/169279800): Pull out test code that media app and help app have in
// common.
/**
* Promise that signals the guest is ready to receive test messages (in addition
* to messages handled by receiver.js).
* @type {!Promise<undefined>}
*/
const testMessageHandlersReady = new Promise(resolve => {
window.addEventListener('DOMContentLoaded', () => {
guestMessagePipe.registerHandler('test-handlers-ready', resolve);
});
});
/**
* Runs the given `testCase` in the guest context.
* @param {string} testCase
*/
async function runTestInGuest(testCase) {
/** @type {!TestMessageRunTestCase} */
const message = {testCase};
await testMessageHandlersReady;
await guestMessagePipe.sendMessage('run-test-case', message);
}
|
JavaScript
|
CL
|
658c08a2d3011f00d2e33d2f7b96f68231b0a364c082b5aff5c4e70d8ed3169b
|
import React, {Component} from 'react';
import {Platform, StatusBar, StyleSheet, Text, View} from 'react-native';
import { Tabs } from './router';
import {LoginStack} from './router';
import {createRootNavigator} from './router';
import LoadingScreen from './screens/LoadingScreen.js';
import firebase from 'react-native-firebase';
console.disableYellowBox = true;
type Props = {};
export default class App extends Component<Props> {
constructor() {
super();
this.state = {
loading: true,
};
}
/**
* When the App component mounts, we listen for any authentication
* state changes in Firebase.
* Once subscribed, the 'user' parameter will either be null
* (logged out) or an Object (logged in)
*/
componentDidMount() {
this.authSubscription = firebase.auth().onAuthStateChanged((user) => {
this.setState({
loading: false,
user,
});
});
}
/**
* Don't forget to stop listening for authentication state changes
* when the component unmounts.
*/
componentWillUnmount() {
this.authSubscription();
}
render() {
// The application is initialising
if (this.state.loading) return null;
const Layout = createRootNavigator(this.state.user);
return (
<View style={{flex:1}}>
<StatusBar barStyle="light-content" />
<Layout />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
|
JavaScript
|
CL
|
ad0d1222b6fba0493725980defa58c6c4a760c8a741ff4688a1c8f26b088de58
|
const router = require('express').Router();
const db = require('../util/db');
const util = require('../util/util');
const inputCleaningFunctions = require('../util/inputCleaningFunctions');
const tableName = 'requestForm';
const specialFieldTypeNamesAndValueFormats = {
checkbox: 'array',
multiselect: 'array'
};
/**
* @swagger
*
* definitions:
* NewRequestForm:
* type: object
* required:
* - formTypeId
* properties:
* formTypeId:
* type: integer
* formStatusName:
* type: string
* formStatusId:
* type: integer
* rowId:
* type: integer
* RequestForm:
* allOf:
* - $ref: '#/definitions/NewRequestForm'
* - type: object
* - properties:
* id:
* type: integer
* formStatusName:
* type: string
* GetRequestForm:
* allOf:
* - $ref: '#/definitions/RequestForm'
* - type: object
* - properties:
* fields:
* type: array
* items:
* allOf:
* - $ref: '#/definitions/GetField'
* - type: object
* - properties:
* typeName:
* type: string
* categoryName:
* type: string
* formStatus:
* type: string
* created_at:
* type: string
* format: date-time
* updated_at:
* type: string
* format: date-time
* deleted_at:
* type: string
* format: date-time
* NewFormField:
* type: object
* required:
* - fieldId
* - value
* properties:
* fieldId:
* type: integer
* value:
* type: string
* FormField:
* allOf:
* - $ref: '#/definitions/RequestForm'
* - type: object
* - required:
* - requestFormId
* - properties:
* requestFormId:
* type: integer
*/
/**
* @swagger
* /api/request-form:
* get:
* summary: Returns request forms
* produces:
* - application/json
* tags:
* - requestForms
* responses:
* 200:
* description: Request forms
* schema:
* type: array
* items:
* $ref: '#/definitions/GetRequestForm'
*/
router.get('/', async (req, res, next) => {
let sql = `SELECT
form.*,
status.name AS formStatus,
ftrf.requestFormId,
formType.name AS formType,
GROUP_CONCAT(f.id ORDER BY c.sortOrder, f.sortOrder, c.name, f.name, f.id) as fieldIds
FROM fieldtorequestform ftrf
JOIN requestForm form ON (ftrf.requestFormId = form.id)
JOIN requestFormStatus status ON (form.formStatusId = status.id)
JOIN requestFormType formType ON (form.formTypeId = formType.id)
JOIN field f ON (ftrf.fieldId = f.id)
JOIN fieldCategory c ON (f.categoryId = c.id)
WHERE form.deleted_at IS NULL
AND formType.deleted_at IS NULL
GROUP BY ftrf.requestFormId
ORDER BY form.created_at DESC`;
let formData;
try {
formData = await db.query(sql);
} catch (e) {
next(e);
return;
}
sql = `SELECT
f.*,
t.name AS typeName,
ftrf.requestFormId,
ftrf.value,
c.required AS categoryRequired
FROM field f
JOIN fieldType t ON (f.typeId = t.id)
JOIN fieldCategory c ON (f.categoryId = c.id)
JOIN fieldToRequestForm ftrf ON (ftrf.fieldId = f.id)
LEFT JOIN autocompleteOptions ao ON (ao.fieldId = f.id AND ao.deleted_at IS NULL)
WHERE f.deleted_at IS NULL
AND c.deleted_at IS NULL
AND ftrf.deleted_at IS NULL
GROUP BY f.id, ftrf.requestFormId
ORDER BY c.sortOrder, f.sortOrder, c.name, f.name, f.id`;
let fieldData;
try {
fieldData = await db.query(sql);
} catch (e) {
next(e);
return;
}
const fieldMap = {};
for (let i = 0; i < fieldData.length; i++) {
const field = fieldData[i];
fieldMap[`${field.requestFormId}-${field.id}`] = util.cleanFormFieldForOutput(field);
}
for (let i = 0; i < formData.length; i++) {
const form = formData[i];
const { requestFormId, fieldIds } = form;
const fields = [];
const fieldIdsArray = fieldIds.split(',');
for (let j = 0; j < fieldIdsArray.length; j++) {
const key = `${requestFormId}-${fieldIdsArray[j]}`;
fields.push(fieldMap[key]);
}
form.fields = util.cleanFieldsForOutput(fields);
delete form.fieldIds;
}
res.send(formData);
});
const getSmallRequestFormSummary = async (id) => {
return new Promise(async (resolve, reject) => {
let sql = `SELECT
f.id,
f.categoryId,
f.name,
f.sortOrder,
f.dependentOnId,
form.formStatusId,
s.name AS formStatusName,
f.dependentOnValue,
f.elementOptions,
c.sortOrder AS categorySortOrder,
c.name AS categoryName,
ftrf.value,
t.name AS typeName,
formType.name AS formTypeName
FROM requestForm form
JOIN requestFormStatus s ON (form.formStatusId = s.id)
JOIN requestFormType formType ON (form.formTypeId = formType.id)
JOIN fieldCategory c ON (formType.id = c.formTypeId)
JOIN field f ON (c.id = f.categoryId AND f.forTableFieldId IS NULL)
JOIN fieldType t ON (f.typeId = t.id)
LEFT JOIN fieldToRequestForm ftrf ON (ftrf.requestFormId = form.id AND ftrf.fieldId = f.id AND ftrf.deleted_at IS NULL)
WHERE form.id = ?
GROUP BY f.id
ORDER BY c.sortOrder, f.sortOrder, c.name, f.name, f.id`;
let params = [id];
let fields, formStatusId, formStatusName;
try {
const results = await db.query(sql, params);
if (results.length === 0) {
reject(404);
return;
}
formStatusId = results[0].formStatusId;
formStatusName = results[0].formStatusName;
fields = await util.fillInFieldExtrasAndCleanFields(results, true);
} catch (e) {
reject(e);
return;
}
const formData = { id, fields, formStatusName, formStatusId };
resolve(formData);
});
};
const getRequestFormById = async (id) => {
return new Promise(async (resolve, reject) => {
let sql = `SELECT
f.*,
status.name AS formStatus,
c.sortOrder AS categorySortOrder,
c.name AS categoryName,
ftrf.value,
t.name AS typeName,
ao.fieldId IS NOT NULL AS hasAutocompleteOptions,
columns.id IS NOT NULL AS hasTableColumns,
formType.name AS formTypeName
FROM requestForm form
JOIN requestFormStatus status ON (form.formStatusId = status.id)
JOIN requestFormType formType ON (form.formTypeId = formType.id)
JOIN fieldCategory c ON (formType.id = c.formTypeId)
JOIN field f ON (c.id = f.categoryId AND f.deleted_at IS NULL)
JOIN fieldType t ON (f.typeId = t.id)
LEFT JOIN fieldToRequestForm ftrf ON (ftrf.requestFormId = form.id AND ftrf.fieldId = f.id AND ftrf.deleted_at IS NULL)
LEFT JOIN autocompleteOptions ao ON (ao.fieldId = f.id AND ao.deleted_at IS NULL)
LEFT JOIN field columns ON (f.id = columns.forTableFieldId AND columns.deleted_at IS NULL)
WHERE form.id = ? AND f.forTableFieldId IS NULL
GROUP BY f.id
ORDER BY c.sortOrder, f.sortOrder, c.name, f.name, f.id`;
let params = [id];
let fields, formStatus;
try {
const results = await db.query(sql, params);
if (results.length === 0) {
reject(404);
return;
}
formStatus = results[0].formStatus;
fields = await util.fillInFieldExtrasAndCleanFields(results, true, id);
} catch (e) {
reject(e);
return;
}
const formData = { id, fields, formStatus };
resolve(formData);
});
};
const fieldIdHasValidValue = (fieldId, value, typeName, autocompleteFieldIdsAndOptions, fieldIdsAndOptions, res) => {
let validValues = null;
if (autocompleteFieldIdsAndOptions && autocompleteFieldIdsAndOptions[fieldId]) {
validValues = autocompleteFieldIdsAndOptions[fieldId].split(',').map(a => a.replace('\"', '"'));
} else if (fieldIdsAndOptions && fieldIdsAndOptions[fieldId]) {
validValues = inputCleaningFunctions.outputArrayFunc(fieldIdsAndOptions[fieldId]);
}
if (validValues) {
const specialValueFormat = specialFieldTypeNamesAndValueFormats[typeName];
if (specialValueFormat) {
if (specialValueFormat === 'array') {
for (let i = 0; i < value.length; i++) {
const v = value[i];
if (!validValues.includes(v)) {
res.status(400).send(`Value ${v} is not valid for field ID ${fieldId}`);
return false;
}
}
}
} else if (!validValues.includes(value)) {
res.status(400).send(`Value ${value} is not valid for field ID ${fieldId}`);
return false;
}
}
return true;
};
const insertIntoHistoryTable = (requestFormId, formState, updatedBy = null, changes = null) => {
const insertValues = { requestFormId, formState: JSON.stringify(formState) };
if (updatedBy)
insertValues.updatedBy = updatedBy;
if (changes)
insertValues.changes = JSON.stringify(changes);
const keys = Object.keys(insertValues);
const sql = `INSERT INTO requestFormHistory (${keys.join(',')}) VALUES (${'?,'.repeat(keys.length - 1)}?)`;
try {
db.query(sql, Object.values(insertValues));
} catch (e) {
console.error("Error inserting into history table:");
console.error(e);
}
};
/**
* @swagger
* /api/request-form/{requestFormId}:
* get:
* summary: Returns a request form
* produces:
* - application/json
* tags:
* - requestForms
* parameters:
* - in: path
* name: requestFormId
* schema:
* type: integer
* responses:
* 200:
* description: Request form
* schema:
* $ref: '#/definitions/GetRequestForm'
*/
router.get('/:requestFormId', (req, res, next) => {
const truthy = util.requiredKeysAreTruthy(req.params, ['requestFormId']);
if (!truthy.success) {
res.status(400).send(truthy.error);
return;
}
getRequestFormById(req.params.requestFormId).then(formData => {
res.send(formData);
}).catch(e => {
if (e === 404)
res.status(404).send(`Form with ID ${id} not found`);
else
next(e);
});
});
/**
* @swagger
* /api/request-form:
* post:
* summary: Creates a request form
* produces:
* - application/json
* tags:
* - requestForms
* parameters:
* - in: body
* name: requestForm
* description: The request form to create. If field type is checkbox or multiselect, value should be an array of strings. Otherwise, it should be a string. Only formStatusId or formStatusName is required, not both, if a status is passed in. If saving a table row value, the data should be a field ID key, then an object with keys rowId and value.
* schema:
* type: object
* properties:
* formStatusId:
* type: integer
* formStatusName:
* type: string
* formTypeId:
* type: integer
* fields:
* type: object
* example: {"3":"Bees' Knees", "44": {"rowId": 2, "value": "Eye of Newt"}}
* properties:
* fieldId:
* type: string
* responses:
* 200:
* description: Request form
* schema:
* $ref: '#/definitions/GetRequestForm'
*/
router.post('/', async (req, res, next) => {
const truthy = util.requiredKeysAreTruthy(req.body, ['formTypeId', 'fields']);
if (!truthy.success) {
res.status(400).send(truthy.error);
return;
}
const { formTypeId, fields } = req.body;
let { formStatusId, formStatusName } = req.body;
const allFieldIdStatements = [];
let sql, params;
// If a status is passed in, check if it's valid
if (!formStatusName && !formStatusId) {
formStatusName = 'Draft';
}
if (formStatusName || formStatusId) {
sql = `SELECT * FROM requestFormStatus `;
if (formStatusId) {
sql += `WHERE id = ?`;
params = [formStatusId];
} else {
sql += `WHERE name = ?`;
params = [formStatusName];
}
try {
const results = await db.query(sql, params);
if (!results || !results.length) {
res.status(400).send(`Form ${formStatusId ? `status ID ${formStatusId}` : `status name ${formStatusName}`} is not valid`);
return;
} else if (!formStatusId) {
formStatusId = results[0].id;
}
} catch (e) {
next(e);
return;
}
}
// Make sure this data is valid
const fieldIds = Object.keys(fields);
params = [];
const passedColumnFieldIds = [];
for (let i = 0; i < fieldIds.length; i++) {
const fieldId = fieldIds[i];
allFieldIdStatements.push(`SELECT ? AS id FROM DUAL`);
params.push(fieldId);
if (fields[fieldId].rowId) {
passedColumnFieldIds.push(fieldId);
}
}
sql = `SELECT
GROUP_CONCAT(IF(validFields.id IS NULL, fieldIds.id, NULL)) AS invalid,
GROUP_CONCAT(IF(validFields.id IS NOT NULL, CONCAT('"', validFields.id, '":"', validFields.typeName, '"'), NULL)) AS fieldTypes,
GROUP_CONCAT(IF(validFields.id IS NOT NULL, CONCAT('"', validFields.id, '":"', REPLACE(validFields.options, '"', '\"'), '"'), NULL)) AS options,
GROUP_CONCAT(IF(validFields.id IS NOT NULL AND validFields.typeName = 'autocomplete', CONCAT('"', validFields.id, '":"', validFields.optKey, '"'), NULL)) AS autocompleteFieldIds,
GROUP_CONCAT(IF(validFields.id IS NOT NULL AND validFields.forTableFieldId IS NOT NULL, validFields.id, NULL)) AS columnFieldIds
FROM (${allFieldIdStatements.join(' UNION ')}) fieldIds
LEFT JOIN (
SELECT DISTINCT f.id, t.name AS typeName, f.options, GROUP_CONCAT(REPLACE(ao.optKey, '"', '\"')) AS optKey, f.forTableFieldId
FROM field f
JOIN fieldType t ON (f.typeId = t.id)
JOIN fieldCategory c ON (f.categoryId = c.id AND c.formTypeId = ? AND c.deleted_at IS NULL)
LEFT JOIN autocompleteOptions ao ON (f.id = ao.fieldId AND ao.deleted_at IS NULL)
GROUP BY f.id
) validFields ON (validFields.id = fieldIds.id)
LIMIT 1
`;
params.push(formTypeId);
let fieldIdsAndTypeNames, fieldIdsAndOptions, autocompleteFieldIdsAndOptions;
try {
const results = await db.query(sql, params);
const infoRow = results[0];
if (infoRow.invalid) {
res.status(400).send(`Field ID(s) ${infoRow.invalid} is not a valid field for this form type`);
return;
} else {
const { fieldTypes, options, autocompleteFieldIds, columnFieldIds } = infoRow;
if (passedColumnFieldIds.length) {
for (let i = 0; i < passedColumnFieldIds.length; i++) {
let fId = passedColumnFieldIds[i];
if (!columnFieldIds.includes(fId)) {
res.status(400).send(`Field ID ${fId} is not a column field and should not have a rowId value with it`);
return;
}
}
}
fieldIdsAndTypeNames = JSON.parse(`{${fieldTypes}}`);
if (options)
fieldIdsAndOptions = JSON.parse(`{${options}}`);
if (autocompleteFieldIds)
autocompleteFieldIdsAndOptions = JSON.parse(`{${autocompleteFieldIds}}`);
}
} catch (e) {
next(e);
return;
}
// The field IDs and status are valid, continue
try {
const insertFormData = { formTypeId };
if (formStatusId)
insertFormData.formStatusId = formStatusId;
let results = await db.insert(tableName, insertFormData);
const requestFormId = results.insertId;
const deleteFormRecord = () => {
db.query(`DELETE FROM ?? WHERE id = ?`, [tableName, requestFormId]);
};
// Check incoming values for validity with field options
const cleanedData = [];
for (let i = 0; i < fieldIds.length; i++) {
const fieldId = fieldIds[i];
let value, rowId;
if (fields[fieldId].rowId) {
rowId = fields[fieldId].rowId;
value = fields[fieldId].value;
} else
value = fields[fieldId];
if (!fieldIdHasValidValue(fieldId, value, fieldIdsAndTypeNames[fieldId], autocompleteFieldIdsAndOptions, fieldIdsAndOptions, res)) {
deleteFormRecord();
return;
}
cleanedData.push(util.cleanFormFieldForInput({ fieldId, value, rowId, typeName: fieldIdsAndTypeNames[fieldId], requestFormId }));
}
// Insert the field data
try {
await db.insert('fieldToRequestForm', cleanedData);
getRequestFormById(requestFormId).then(formData => {
res.send(formData);
getSmallRequestFormSummary(requestFormId).then(d => {
insertIntoHistoryTable(requestFormId, d);
}).catch(e => { });
}).catch(e => {
if (e === 404)
res.status(404).send(`Form with ID ${id} not found`);
else
next(e);
});
} catch (e) {
next(e);
return;
}
} catch (e) {
next(e);
return;
}
});
/**
* @swagger
* /api/request-form/{requestFormId}:
* put:
* summary: Updates a request form
* produces:
* - application/json
* tags:
* - requestForms
* parameters:
* - in: path
* name: requestFormId
* schema:
* type: integer
* - in: body
* name: requestForm
* description: The request form to update. The body should be an object where the key is the field ID and the value is the value. If saving a table row, the data should be a field ID key, then an object with keys rowId and value. To delete values, put the IDs in an array (see example below).
* schema:
* type: object
* example: {"3":"Bees' Knees", "44": {"rowId": 2, "value": "Eye of Newt"}, "deletes": ["22", "1", {"tableId": "6", "rowId": "2"}]}
* properties:
* value:
* type: string
* responses:
* 200:
* description: Request form
* schema:
* $ref: '#/definitions/GetRequestForm'
*/
router.put('/:requestFormId', async (req, res, next) => {
const truthy = util.requiredKeysAreTruthy(req.params, ['requestFormId']);
if (!truthy.success) {
res.status(400).send(truthy.error);
return;
}
const { requestFormId } = req.params;
const { fields, deletes } = req.body;
const allFieldIdStatements = [];
let sql, params;
// If a status is passed in, check if it's valid
let formStatusId = fields ? fields.formStatusId : null;
const formStatusName = fields ? fields.formStatusName : null;
if (fields) {
delete fields.formStatusId;
delete fields.formStatusName;
}
if (formStatusName || formStatusId) {
sql = `SELECT
f.formStatusId IS NOT NULL AS currentStatus,
s.*
FROM requestFormStatus s
LEFT JOIN requestForm f ON (s.id = f.formStatusId AND f.id = ?) `;
if (formStatusId) {
sql += `WHERE s.id = ? `;
params = [requestFormId, formStatusId];
} else {
sql += `WHERE s.name = ? `;
params = [requestFormId, formStatusName];
}
sql += `LIMIT 1`;
try {
const results = await db.query(sql, params);
if (!results || !results.length) {
res.status(400).send(`Form ${formStatusId ? `status ID ${formStatusId}` : `status name ${formStatusName}`} is not valid`);
return;
} else if (!formStatusId) {
formStatusId = results[0].id;
}
if (results[0].currentStatus) {
formStatusId = undefined;
}
} catch (e) {
next(e);
return;
}
}
// Check which fields are new, which are being updated, and which are invalid for this form
params = [];
let updates, inserts;
const fieldIds = fields ? Object.keys(fields) : [];
if (fieldIds.length) {
let passedColumnFieldIds = [];
for (let i = 0; i < fieldIds.length; i++) {
const fieldId = fieldIds[i];
if (isNaN(fieldId))
continue;
allFieldIdStatements.push(`SELECT ? AS id FROM DUAL`);
params.push(fieldId);
if (fields[fieldId].rowId) {
passedColumnFieldIds.push(fieldId);
}
}
sql = `SELECT
GROUP_CONCAT(IF(validFields.id IS NULL, fieldIds.id, NULL)) AS invalidFields,
GROUP_CONCAT(IF(validFields.id IS NOT NULL, CONCAT('"', validFields.id, '":"', REPLACE(validFields.options, '"', '\"'), '"'), NULL)) AS options,
GROUP_CONCAT(IF(fieldsWithValues.id IS NOT NULL, CONCAT('"', fieldIds.id, '":"', REPLACE(fieldsWithValues.typeName, '"', '\"'), '"'), NULL)) AS updateFields,
GROUP_CONCAT(IF(fieldsWithValues.id IS NOT NULL AND fieldsWithValues.rowId IS NOT NULL, CONCAT('"', fieldIds.id, '":{', fieldsWithValues.jsonFormatRows, '}'), NULL)) AS columnAndRowValues,
GROUP_CONCAT(IF(fieldsWithValues.id IS NOT NULL AND fieldsWithValues.rowId IS NULL, CONCAT('"', fieldIds.id, '":"', REPLACE(REPLACE(fieldsWithValues.value, '"', '\"'), ';', '\;'), '"'), NULL)) AS currentUpdateValues,
GROUP_CONCAT(IF(fieldsWithValues.id IS NULL AND validFields.id IS NOT NULL, CONCAT('"', fieldIds.id, '":"', REPLACE(validFields.typeName, '"', '\"'), '"'), NULL)) AS insertFields,
GROUP_CONCAT(IF(validFields.id IS NOT NULL AND validFields.typeName = 'autocomplete', CONCAT('"', validFields.id, '":"', validFields.optKey, '"'), NULL)) AS autocompleteFieldIds,
GROUP_CONCAT(IF(validFields.id IS NOT NULL AND validFields.forTableFieldId IS NOT NULL, validFields.id, NULL)) AS columnFieldIds
FROM (${allFieldIdStatements.join(' union ')}) fieldIds
LEFT JOIN (
SELECT DISTINCT f.id, t.name AS typeName, IF(ftrf.rowId = 0 OR ftrf.rowId IS NULL, NULL, GROUP_CONCAT('"', ftrf.rowId, '":"', REPLACE(REPLACE(ftrf.value, '"', '\"'), ';', '\;'), '"')) AS jsonFormatRows, ftrf.value, IF(ftrf.rowId = 0, NULL, ftrf.rowId) AS rowId
FROM field f
JOIN fieldType t ON (f.typeId = t.id)
JOIN fieldCategory c ON (f.categoryId = c.id)
JOIN requestForm form ON (form.formTypeId = c.formTypeId AND form.id = ?)
JOIN fieldToRequestForm ftrf ON (f.id = ftrf.fieldId AND form.id = ftrf.requestFormId)
GROUP BY f.id
) fieldsWithValues ON (fieldIds.id = fieldsWithValues.id)
LEFT JOIN (
SELECT DISTINCT f.id, form.id AS formId, t.name AS typeName, f.options, GROUP_CONCAT(REPLACE(ao.optKey, '"', '\"')) AS optKey, f.forTableFieldId
FROM field f
JOIN fieldType t ON (f.typeId = t.id)
JOIN fieldCategory c ON (f.categoryId = c.id)
JOIN requestForm form ON (form.formTypeId = c.formTypeId AND form.id = ?)
LEFT JOIN autocompleteOptions ao ON (f.id = ao.fieldId AND ao.deleted_at IS NULL)
GROUP BY f.id
) validFields ON (fieldIds.id = validFields.id)
GROUP BY validFields.formId`;
params.push(requestFormId, requestFormId);
try {
const results = await db.query(sql, params);
const row = results[0];
if (row.invalidFields) {
res.status(400).send(`Field ID(s) ${row.invalidFields} is not a valid field for this form type`);
return;
}
let fieldIdsAndOptions, autocompleteFieldIdsAndOptions;
if (row.columnFieldIds && passedColumnFieldIds.length) {
const { columnFieldIds } = row;
for (let i = 0; i < passedColumnFieldIds.length; i++) {
let fId = passedColumnFieldIds[i];
if (!columnFieldIds.includes(fId)) {
res.status(400).send(`Field ID ${fId} is not a column field and should not have a rowId value with it`);
return;
}
}
}
if (row.options)
fieldIdsAndOptions = JSON.parse(`{${row.options}}`);
if (row.autocompleteFieldIds)
autocompleteFieldIdsAndOptions = JSON.parse(`{${row.autocompleteFieldIds}}`);
let updateFields, insertFields, columnAndRowValues;
if (row.updateFields)
updateFields = JSON.parse(`{${row.updateFields}}`);
if (row.insertFields)
insertFields = JSON.parse(`{${row.insertFields}}`);
if (row.columnAndRowValues)
columnAndRowValues = JSON.parse(`{${row.columnAndRowValues}}`);
if (columnAndRowValues) {
const fieldIds = Object.keys(columnAndRowValues);
for (let i = 0; i < fieldIds.length; i++) {
const fieldId = fieldIds[i];
const currentRowValues = columnAndRowValues[fieldId];
const passedRowId = fields[fieldId].rowId;
const typeName = updateFields[fieldId];
const value = util.cleanFormFieldForInput({ value: fields[fieldId].value, typeName }).value;
delete updateFields[fieldId];
const field = { typeName, value: fields[fieldId].value, rowId: passedRowId, requestFormId, fieldId };
if (!currentRowValues[passedRowId]) {
if (!inserts)
inserts = [];
inserts.push(field);
} else if (currentRowValues[passedRowId] !== value) {
if (!updates)
updates = [];
updates.push(field);
}
}
}
if (updateFields) {
if (!updates)
updates = [];
const updateFieldIds = Object.keys(updateFields);
const currentValues = row.currentUpdateValues ? JSON.parse(`{${row.currentUpdateValues}}`) : {};
for (let i = 0; i < updateFieldIds.length; i++) {
const fieldId = updateFieldIds[i];
const typeName = updateFields[fieldId];
const value = fields[fieldId];
const cleanedValue = util.cleanFormFieldForInput({ value, typeName }).value;
if (currentValues[fieldId] && value !== currentValues[fieldId]) {
if (!fieldIdHasValidValue(fieldId, value, typeName, autocompleteFieldIdsAndOptions, fieldIdsAndOptions, res)) {
return;
}
updates.push({
requestFormId,
fieldId,
typeName,
value: cleanedValue
});
}
}
}
if (insertFields) {
if (!inserts)
inserts = [];
const insertFieldIds = Object.keys(insertFields);
for (let i = 0; i < insertFieldIds.length; i++) {
const fieldId = insertFieldIds[i];
const typeName = insertFields[fieldId];
let value, rowId;
if (fields[fieldId].rowId) {
rowId = fields[fieldId].rowId;
value = fields[fieldId].value;
} else
value = fields[fieldId];
if (!fieldIdHasValidValue(fieldId, value, typeName, autocompleteFieldIdsAndOptions, fieldIdsAndOptions, res)) {
return;
}
inserts.push({
requestFormId,
fieldId,
typeName,
rowId,
value: util.cleanFormFieldForInput({ value, typeName }).value
});
}
}
} catch (e) {
next(e);
return;
}
}
const promisesArray = [];
if (updates && updates.length) {
try {
promisesArray.push(db.multiUpdate('fieldToRequestForm', updates.map(util.cleanFormFieldForInput), { whereFields: ['requestFormId', 'fieldId', 'rowId'] }));
} catch (e) {
next(e);
return;
}
}
if (inserts && inserts.length) {
try {
promisesArray.push(db.insert('fieldToRequestForm', inserts.map(util.cleanFormFieldForInput)));
} catch (e) {
next(e);
return;
}
}
if (deletes && deletes.length) {
const baseSql = `UPDATE fieldToRequestForm SET deleted_at = NOW() WHERE requestFormId = ? AND fieldId = ?`;
const baseParams = [requestFormId];
for (let i = 0; i < deletes.length; i++) {
const d = deletes[i];
let sql = baseSql;
let params = [...baseParams];
if (typeof d === "object") {
sql += ' AND rowId = ?';
params.push(d.tableId);
params.push(d.rowId);
} else {
params.push(d);
}
try {
promisesArray.push(db.query(sql, params));
} catch (e) {
next(e);
return;
}
}
}
if (formStatusId) {
try {
promisesArray.push(db.update('requestForm', requestFormId, { formStatusId }));
} catch (e) {
next(e);
return;
}
}
Promise.all(promisesArray)
.then(r => {
getRequestFormById(requestFormId).then(formData => {
res.send(formData);
if (inserts || updates || formStatusId) {
// TODO include who created request
const updatedBy = null;
let changes = null;
if (inserts && inserts.length) {
changes = { inserts };
}
if (updates && updates.length) {
if (!changes)
changes = {};
changes.updates = updates;
}
if (formStatusId) {
if (!changes)
changes = {};
if (!changes.updates)
changes.updates = [];
changes.updates.push({ formStatusId });
}
if (changes) {
try {
getSmallRequestFormSummary(requestFormId).then(d => {
insertIntoHistoryTable(requestFormId, d, updatedBy, changes);
}).catch(e => { });
} catch (e) {
next(e);
return;
}
}
}
}).catch(e => {
if (e === 404)
res.status(404).send(`Form with ID ${id} not found`);
else
next(e);
});
}).catch(next);
});
/**
* @swagger
* /api/request-form/{requestFormId}:
* delete:
* summary: Deletes a request form type
* produces:
* - application/json
* tags:
* - requestForms
* parameters:
* - name: requestFormId
* in: path
* schema:
* type: integer
* required: true
* responses:
* 200:
* description: Success confirmation
* schema:
* type: string
* properties:
* success:
* type: boolean
*/
router.delete('/:requestFormId', (req, res, next) => {
util.commonDelete(tableName, 'requestFormId', req, res, next)
.then(async () => {
const requestFormId = req.params.requestFormId;
const sql = `SELECT deleted_at FROM requestForm WHERE id = ?`;
let formData;
try {
formData = await db.query(sql, requestFormId);
} catch (e) {
console.error('Could not fetch deleted_at time: ', e);
return;
}
if (!formData || !formData.length) {
console.error(`Could not find form data to insert into deletion history table with ID ${requestFormId}`);
return;
}
// TODO add updatedBy
const updatedBy = null;
const changes = { deleted_at: formData[0].deleted_at };
getSmallRequestFormSummary(requestFormId).then(d => {
insertIntoHistoryTable(requestFormId, d, updatedBy, changes);
}).catch(e => { });
}).catch();
});
module.exports = {
endpoint: '/api/request-form',
router
};
|
JavaScript
|
CL
|
5716d0e71e54331bfd62f80f18b573eab5210dcdc6c1674ffc5ab0a0e48c1c48
|
import Node from './node';
import Matcher from './matching/matcher';
const ALWAYS_TRUE = () => true;
/*
* Small penalty applied when a SubNode matches. This helps the algorithm
* prefer less parser matches. So if a parser P1 can match (A | A B) and
* another one P1 matches (B) this penalty helps cases where P1 is followed
* by an optional P2 to match P1 before before P1 P2.
*/
const PARSER_PENALTY = 0.001;
/**
* Node that points to a sub-graph that should be evaluated as part of another
* graph. This type of node will resolve all variants it can starting from the
* current token working forwards.
*
* Given the tokens `T1 T2 T3 T4 T5 T6` and a match starting at T2 this node
* may return with variants that span `T2` and `T2 T3` in which case the next
* nodes will be evaluated both against both matches, so it will be invoked
* once starting from `T3` and once from `T4`.
*/
export default class SubNode extends Node {
constructor(roots, options, filter) {
super();
this.filter = filter || ALWAYS_TRUE;
if(roots instanceof Matcher) {
// Roots is actually a matcher, copy the graph from the matcher
this.roots = roots.nodes;
this.state = roots._cache;
} else {
this.roots = roots;
this.state = options.state || this;
}
this.supportsPartial = options.supportsPartial || false;
this.name = options.name || null;
this.skipPunctuation = options.skipPunctuation || false;
this.supportsFuzzy = options.supportsFuzzy || false;
}
match(encounter) {
if(this.state.currentIndex === encounter.currentIndex) {
/*
* If this node is called with the same index again we skip
* evaulating.
*/
return;
}
if(! encounter.token() && encounter.options.partial) {
if(this.recursive) {
/**
* If this evaluating a recursive match on a partial encounter
* skip it.
*/
return;
}
if(! this.supportsPartial) {
/**
* Partial match for nothing without support for it. Assume
* we will match in the future.
*/
return;
}
}
// Set the index we were called at
const previousIndex = this.state.currentIndex;
this.state.currentIndex = encounter.currentIndex;
const variants = [];
const branchIntoVariants = variants0 => {
let promise;
if(variants0.length === 0) {
if(encounter.options.partial && ! this.supportsPartial && this.partialFallback) {
promise = encounter.next(0.0, encounter.tokens.length - encounter.currentIndex, this.partialFallback);
} else {
promise = Promise.resolve();
}
} else {
promise = Promise.resolve();
for(let i=0; i<variants0.length; i++) {
const v = variants0[i];
if(v.data !== null && ! this.filter(v.data)) {
continue;
}
promise = promise.then(() => {
return encounter.next(
v.score - PARSER_PENALTY,
v.index - encounter.currentIndex,
v.data
);
});
}
}
return promise.then(() => {
this.state.currentIndex = previousIndex;
});
};
// Check the cache
const cache = encounter.cache();
let cached = cache.get(this.roots);
if(cached) {
return branchIntoVariants(cached);
}
const baseScore = encounter.currentScore;
const onMatch = match => {
let result = match.data;
if(result !== null && typeof result !== 'undefined') {
if(this.mapper) {
result = this.mapper(result, encounter);
}
} else {
result = null;
}
variants.push({
index: match.index,
score: encounter.currentScore - baseScore,
data: result
});
// Back-track to allow following nodes to also handle any trailing tokens
const previousNonSkipped = encounter.previousNonSkipped();
if(previousNonSkipped !== match.index) {
variants.push({
index: previousNonSkipped,
score: encounter.currentScore - baseScore,
data: result
});
}
};
// Memorize if we are running a partial match
const supportsPartial = encounter.supportsPartial;
const supportsFuzzy = encounter.supportsFuzzy;
const skipPunctuation = encounter.skipPunctuation;
return encounter.branchWithOnMatch(onMatch, () => {
encounter.supportsPartial = this.supportsPartial;
encounter.supportsFuzzy = this.supportsFuzzy;
encounter.skipPunctuation = this.skipPunctuation;
return encounter.branchInto(this.roots);
}).then(() => {
// Switch back to previous supported values
encounter.supportsPartial = supportsPartial;
encounter.supportsFuzzy = supportsFuzzy;
encounter.skipPunctuation = skipPunctuation;
cache.set(this.roots, variants);
return branchIntoVariants(variants);
});
}
equals(other) {
function arrayEquals(a, b) {
if(a.length !== b.length) return false;
for(let i=0; i<a.length; i++) {
if(a !== b) return false;
}
return true;
}
return other instanceof SubNode
&& arrayEquals(this.roots, other.roots)
&& this.filter === other.filter;
}
toString() {
return 'SubGraph[' + (this.name || this.roots) + ']';
}
toDot() {
if(this.name === 'Self') {
return 'shape=circle, label=""';
} else {
return 'shape=rectangle, label="' + (this.name || '') + '"';
}
}
}
|
JavaScript
|
CL
|
76284b653d977f5533814e397e7f342836a08b4f6261a749b1670aa5453b38f2
|
/**
* The MdHub uses messages sent via window.postMessage to
* talk with each module.
*/
class PostMessage {
constructor(MdHub) {
this._MdHub = MdHub;
this.lastMessage = null;
// IE 8 and 9 can only sent postMessages with string data
this.sendAsString = false;
}
/**
* Verify if the actual browser can only sent postMessage using string data
* @return {Boolean}
*/
checkSendAsString() {
if (navigator.appVersion.indexOf('MSIE 8') !== -1 || navigator.appVersion.indexOf('MSIE 9') !== -1) {
this.sendAsString = true;
}
}
/**
* Handler for postMessage:message event
* @param {Object} event postMessage event data
*/
receive(event) {
var data;
var hash;
// Data of the message
var message = event.data;
var promise;
var self = this;
if (this.sendAsString) {
message = JSON.parse(event.data);
}
if (!message || message.type !== 'command' && message.type !== 'event') {
return;
}
// If the message target is the current instance
if (message.to === 'broadcast' || message.to === this._MdHub.module.name) {
if (message.type === 'command') {
// If the message is secure, recover the data from sessionStorage
if (message.secure && this._MdHub.hasStorage()) {
hash = message.data;
data = sessionStorage.getItem(hash);
// The sessionStorage can be implemented asynchronously by the browser
// Wait 100ms for the data
if (data === undefined || data === null || data === 'undefined') {
setTimeout(function recallReceive() {
self.receive(event);
}, 100);
return;
}
if (data !== undefined && data !== 'undefined') {
message.data = JSON.parse(data);
} else {
message.data = null;
}
sessionStorage.removeItem(hash);
}
// It's the response of a command sent
if (message.callback) {
promise = this._MdHub.command.callbacks[message.id];
if (promise) {
// The response can be delivered first than the callback definition
if (typeof promise[message.callback] !== 'function') {
setTimeout(function interval() {
if (typeof promise[message.callback] === 'function') {
promise[message.callback].call(this, message.data, message);
}
delete this._MdHub.command.callbacks[message.id];
}, 1);
} else {
promise[message.callback].call(this, message.data, message);
delete this._MdHub.command.callbacks[message.id];
}
}
} else {
// Rejects the command if the module doesn't exists
// @TODO: Console Warn
if (! this._MdHub.command.list[message.name]) {
this._MdHub.command.reject(message);
return;
}
// Call the comand callback
this._MdHub.command.list[message.name].call(this, message.data, function success(result) {
self._MdHub.command.resolve(message, result);
}, function error(result) {
self._MdHub.command.reject(message, result);
});
}
} else if (message.type === 'event') {
this._MdHub.event.call(message.name, message.data, message);
}
} else if (message.from !== this._MdHub.module.name && this._MdHub.mode === 'server') {
this._MdHub.postMessage.send(message);
if (message.type === 'event') {
this._MdHub.event.call(message.name, message.data, message);
}
}
}
/**
* Send a postMessage
* @param {Object} message
*/
send(message) {
let i;
let messageData = message;
let target = messageData.to;
let targetWindow = {};
// On client mode, send the postMessage to the MdHub Server
if (this._MdHub.mode === 'client') {
messageData.from = this._MdHub.module.name;
if (!messageData.id) {
messageData.id = ++this._MdHub.command.commandId;
}
if (messageData.data && messageData.data.callbacks) {
delete messageData.data.callbacks;
}
// Store the last message sent
// Useful for debugging
this.lastMessage = messageData;
// If the module has callback for beforeMessageSend, call it
if (this._MdHub.module.callbacks && this._MdHub.module.callbacks.hasOwnProperty('beforeMessageSend') && this._MdHub.module.callbacks.beforeMessageSend) {
this._MdHub.module.callbacks.beforeMessageSend.call(this, messageData);
}
// MdHub Server not found
if (window.parent.window === window) return;
if (this.sendAsString) {
messageData = JSON.stringify(messageData);
}
window.parent.window.postMessage(messageData, '*');
return;
}
// On server mode, if the message has a target, send to it
if (target) {
if (this.sendAsString) {
messageData = JSON.stringify(messageData);
}
// If the target is the server, broadcast the message
if (target === 'hub') {
window.postMessage(messageData, '*');
return;
}
// If the target doesn't exists, reject the message
if (! this._MdHub.module.list[target]) {
this._MdHub.command.reject(messageData);
return;
}
targetWindow = this._MdHub.module.list[target].window.contentWindow;
if (targetWindow) {
targetWindow.postMessage(messageData, '*');
}
return;
}
messageData.to = 'broadcast';
if (this.sendAsString) {
messageData = JSON.stringify(messageData);
}
// If the message doesn't has a target, broadcast it
for (i in this._MdHub.module.list) {
targetWindow = this._MdHub.module.list[i].window.contentWindow;
if (targetWindow) {
targetWindow.postMessage(messageData, '*');
}
}
}
}
export default PostMessage;
|
JavaScript
|
CL
|
d4e7ef6f198c2d9b4323840357f34b17c7be8423f06ab2640473eb7c6deebf0f
|
import { SimpleStorage } from '@cogitojs/demo-app-contracts'
import { EthereumForSimpleStorage } from 'test-helpers'
import { proxiesFromBlobs } from './proxiesFromBlobs'
describe('proxiesFromBlobs', () => {
let blobs
let web3
const setupContractsBlobs = () => {
const baseName = SimpleStorage().contractName
blobs = [1, 2, 3].map(i => {
return { ...SimpleStorage(), contractName: `${baseName}-${i}` }
})
}
const stubWeb3 = () => {
web3 = {
currentProvider: {}
}
}
beforeEach(() => {
setupContractsBlobs()
stubWeb3()
})
it('each proxy is keyed by the contract name', async () => {
const proxies = proxiesFromBlobs(blobs, web3)
const expectedKeys = blobs.map(b => b.contractName)
expect(Object.keys(proxies)).toEqual(expectedKeys)
})
it('returns an empty object if an empty array of blobs is provided', () => {
expect(proxiesFromBlobs([], web3)).toEqual({})
})
it('returns an empty object if blobs argument is undefined', () => {
expect(proxiesFromBlobs(undefined, web3)).toEqual({})
})
it('returns an empty object if web3 is not provided', () => {
expect(proxiesFromBlobs(blobs)).toEqual({})
})
describe('given deployed contracts', () => {
let ethereum
beforeEach(async () => {
console.log = jest.fn()
ethereum = await EthereumForSimpleStorage.setup({ contractsBlobs: blobs })
})
afterEach(() => {
console.log.mockRestore()
})
const increment = async (proxy, index) => {
const contractInstance = await proxy.deployed()
await contractInstance.increase(index + 1, { from: ethereum.address })
return (await contractInstance.read()).toNumber()
}
it('takes a list with contract JSON blobs and returns object with proxies', async () => {
const proxies = proxiesFromBlobs(ethereum.deployedJSONs, ethereum.cogitoWeb3)
// this is a bit tricky - cogito-web3-provider requires that that transactions from the same address
// are submitted synchronously - otherwise we will get problems with nonces
// TODO: we should document it in the cogito-web3-provider documentation
const increments = await Object.values(proxies).reduce(async (promise, proxy, index) => {
const increments = await promise
return [ ...increments, await increment(proxy, index) ]
}, Promise.resolve([]))
expect(increments).toEqual([1, 2, 3])
})
})
})
|
JavaScript
|
CL
|
59e8eb09151703975e9bafd3dc8296f2264b29bc6d09ee25a240dc7d55bad5f3
|
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
/**
* devServer
*
* @param {Objects} options - options for webpack-dev-server
* @return {Object} webpack-dev-server configuration object
*/
exports.devServer = function(options) {
return {
devServer: {
// Enable history API fallback
historyApiFallback: true,
// Enable Hot Module Replacement
hot: true,
inline: true,
// Display errors only
stats: 'errors-only',
// Parse host and port options
host: options.host,
port: options.port
}
};
};
/**
* setupSass
*
* @param {Object} paths for source folder
* @return {Object} Webpack module loader config object
*/
exports.setupCss = function(paths) {
return {
module: {
loaders: [
{
test: /\.css$/,
loaders: [
'style',
'css',
'resolve-url'
],
include: paths
}
]
}
};
};
/**
* Minify config
*
* @return {Object} config
*/
exports.minify = function() {
return {
plugins: [
new webpack.optimize.UglifyJsPlugin({
beautify: false,
comments: false,
compress: {
warnings: false,
drop_console: true
},
mangle: {
except: ['$'],
screw_ie8: true,
keep_fname: true
}
})
]
};
};
/**
* Define env variable
*
* @param {String} key
* @param {String} value
* @return {Set} set env variables
*/
exports.setFreeVariable = function(key, value) {
const env = {};
env[key] = JSON.stringify(value);
return {
plugins: [
new webpack.DefinePlugin(env)
]
};
};
/**
* extractBundle - Split bundle (app.js / vendors)
*
* @param {Object} options [description]
* @return {Set} config
*/
exports.extractBundle = function(options) {
const entry = {};
entry[options.name] = options.entries;
return {
entry: entry,
plugins: [
new webpack.optimize.CommonsChunkPlugin({
names: [options.name, 'manifest']
})
]
};
};
/**
* clean build dir before build
*
* @param {String} path - path to clean
* @return {Set} set option
*/
exports.clean = function(path) {
return {
plugins: [
new CleanWebpackPlugin([path], {
root: process.cwd()
})
]
};
};
/**
* extractCSS
*
* @param {String} paths
* @return {Set} module loader
*/
exports.extractCSS = function(paths) {
return {
module: {
loaders: [
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style', 'css'),
include: paths
}
]
},
plugins: [
new ExtractTextPlugin('/assets/css/[name].[chunkhash].css')
]
};
};
/**
* setupBabelHot
*
* @param {String} paths
* @return {Set} module loader
*/
exports.setupBabel = function(paths) {
return {
module: {
loaders: [
{
test: /\.(js|jsx)$/,
loaders: ['react-hot', 'babel?presets[]=es2015,presets[]=stage-0,presets[]=react'],
exclude: /(node_modules|bower_components)/,
include: paths
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
};
};
/**
* setupBabelBuild
*
* @param {String} paths
* @return {Set} module loader
*/
exports.setupBabelBuild = function(paths) {
return {
module: {
loaders: [
{
test: /\.(js|jsx)$/,
loaders: ['babel?presets[]=es2015,presets[]=stage-0,presets[]=react'],
exclude: /(node_modules|bower_components)/,
include: paths
}
]
}
};
};
/**
* setupImage
*
* @param {String} paths
* @return {Set} module loader
*/
exports.setupImage = function(paths) {
return {
module: {
loaders: [
{
test: /\.(jpg|png|gif|jpeg)$/,
loaders: [
'file?name=[path][name].[hash].[ext]&context=./app'
],
include: paths
},
{
test: /\.(svg)$/,
loader: "file?name=[path][name].[ext]&context=./app"
}
]
}
};
};
/**
* setupFonts
*
* @param {String} paths
* @return {Set} module loader
*/
exports.setupFonts = function(paths) {
return {
module: {
loaders: [
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'file?name=[path][name].[hash].[ext]&context=./app',
include: paths
}
]
}
};
};
|
JavaScript
|
CL
|
b1095d6257a5d8143c0722dd01cc1d36a5c4c347eb45a1d2b9b9318a5fd2eeaf
|
const { db, failsafe } = require('../utils/db');
const request = require('request-promise');
const { to: pWrapper } = require('await-to-js');
const debug = require('../utils/debug');
const retry = require('p-retry');
const path = require('path');
const indexer = require('../init/indexer');
const { unraw } = require('unraw');
const nl2br = require('nl2br');
const checkForRequests = require('../checks/requests');
const checkForFlags = require('../checks/flags');
const downloadFile = require('../utils/download');
const Promise = require('bluebird');
const { default: pq } = require('p-queue');
const queue = new pq({ concurrency: 10 });
const requestOptions = (key) => {
return {
json: true,
headers: {
cookie: `FANBOXSESSID=${key}`,
origin: 'https://fanbox.cc'
}
};
};
const fileRequestOptions = (key) => {
return {
encoding: null,
headers: {
cookie: `FANBOXSESSID=${key}`,
origin: 'https://fanbox.cc'
}
};
};
async function scraper (id, key, url = 'https://api.fanbox.cc/post.listSupporting?limit=50') {
const log = debug('kemono:importer:status:' + id);
const [err1, fanbox] = await pWrapper(retry(() => request.get(url, requestOptions(key)), {
onFailedAttempt: error => {
if (error.statusCode === 401) throw error;
}
}));
if (err1 && err1.statusCode === 401) {
return log('Error: Invalid session key');
} else if (err1 && err1.statusCode) {
return log(`Error: Status code ${err1.statusCode} when contacting Pixiv Fanbox API.`);
} else if (err1) {
return log(err1);
}
Promise.map(fanbox.body.items, async (post) => {
if (!post.body) return log(`Skipping ID ${post.id}: Locked`); // locked content; nothing to do
const banExists = await queue.add(() => db('dnp').where({ id: post.user.userId, service: 'fanbox' }));
if (banExists.length) return log(`Skipping ID ${post.id}: user ${post.user.userId} is banned`);
await queue.add(() => checkForFlags({
service: 'fanbox',
entity: 'user',
entityId: post.user.userId,
id: post.id
}));
await queue.add(() => checkForRequests({
service: 'fanbox',
userId: post.user.userId,
id: post.id
}));
const postExists = await queue.add(() => db('booru_posts').where({ id: post.id, service: 'fanbox' }));
if (postExists.length) return;
log(`Importing ID ${post.id}`);
const inactivityTimer = setTimeout(() => log(`Warning: Post ${post.id} may be stalling`), 120000);
const model = {
id: post.id,
user: post.user.userId,
service: 'fanbox',
title: unraw(post.title),
content: nl2br(unraw(await parseBody(post.body, key, {
id: post.id,
user: post.user.userId
}), true)),
embed: {},
shared_file: false,
added: new Date().toISOString(),
published: post.publishedDatetime,
edited: null,
file: {},
attachments: []
};
const filesLocation = '/files/fanbox';
const attachmentsLocation = '/attachments/fanbox';
if (post.body.images) {
await Promise.mapSeries(post.body.images, async (image, index) => {
const location = index === 0 && !model.file.name ? filesLocation : attachmentsLocation;
const store = index === 0 && !model.file.name ? fn => {
model.file.name = `${image.id}.${image.extension}`;
model.file.path = `${location}/${post.user.userId}/${post.id}/${fn}`;
} : fn => {
model.attachments.push({
id: image.id,
name: `${image.id}.${image.extension}`,
path: `${attachmentsLocation}/${post.user.userId}/${post.id}/${fn}`
});
};
await downloadFile({
ddir: path.join(process.env.DB_ROOT, `${location}/${post.user.userId}/${post.id}`),
name: `${image.id}.${image.extension}`
}, Object.assign({
url: unraw(image.originalUrl)
}, fileRequestOptions(key)))
.then(res => store(res.filename));
});
}
if (post.body.files) {
await Promise.mapSeries(post.body.files, async (file, index) => {
const location = index === 0 && !model.file.name ? filesLocation : attachmentsLocation;
const store = index === 0 && !model.file.name ? fn => {
model.file.name = `${file.name}.${file.extension}`;
model.file.path = `${location}/${post.user.userId}/${post.id}/${fn}`;
} : fn => {
model.attachments.push({
id: file.id,
name: `${file.name}.${file.extension}`,
path: `${attachmentsLocation}/${post.user.userId}/${post.id}/${fn}`
});
};
await downloadFile({
ddir: path.join(process.env.DB_ROOT, `${location}/${post.user.userId}/${post.id}`),
name: `${file.name}.${file.extension}`
}, Object.assign({
url: unraw(file.url)
}, fileRequestOptions(key)))
.then(res => store(res.filename));
});
}
clearTimeout(inactivityTimer);
log(`Finished importing ID ${post.id}`);
await queue.add(() => db('booru_posts').insert(model));
}, { concurrency: 5 });
if (fanbox.body.nextUrl) {
scraper(id, key, fanbox.body.nextUrl);
} else {
log('Finished scanning posts.');
indexer();
}
}
async function parseBody (body, key, opts) {
// https://github.com/Nandaka/PixivUtil2/blob/master/PixivModelFanbox.py#L213
const bodyText = body.text || body.html || '';
let concatenatedText = '';
if (body.video) {
concatenatedText += ({
youtube: `
<a href="https://www.youtube.com/watch?v=${body.video.videoId}" target="_blank">
<div class="embed-view">
<h3 class="subtitle">(YouTube)</h3>
</div>
</a>
<br>
`,
vimeo: `
<a href="https://vimeo.com/${body.video.videoId}" target="_blank">
<div class="embed-view">
<h3 class="subtitle">(Vimeo)</h3>
</div>
</a>
<br>
`,
soundcloud: `
<a href="https://soundcloud.com/${body.video.videoId}" target="_blank">
<div class="embed-view">
<h3 class="subtitle">(Soundcloud)</h3>
</div>
</a>
<br>
`
})[body.video.serviceProvider];
}
if (body.blocks) {
await Promise.mapSeries(body.blocks, async (block) => {
switch (block.type) {
case 'p': {
concatenatedText += block.text ? `${unraw(block.text)}<br>` : '';
break;
}
case 'image': {
const imageInfo = body.imageMap[block.imageId];
await downloadFile({
ddir: path.join(process.env.DB_ROOT, '/inline/fanbox'),
name: `${imageInfo.id}.${imageInfo.extension}`
}, Object.assign({
url: unraw(imageInfo.originalUrl)
}, fileRequestOptions(key)))
.then(res => {
concatenatedText += `<img src="/inline/fanbox/${res.filename}"><br>`;
});
break;
}
case 'file': {
const fileInfo = body.fileMap[block.fileId];
await downloadFile({
ddir: path.join(process.env.DB_ROOT, `/attachments/fanbox/${opts.user}/${opts.id}`),
name: unraw(`${fileInfo.name || fileInfo.id}.${fileInfo.extension}`)
}, Object.assign({
url: unraw(fileInfo.url)
}, fileRequestOptions(key)))
.then(res => {
concatenatedText += `<a href="/attachments/fanbox/${opts.user}/${opts.id}/${res.filename}" target="_blank">Download ${res.filename}</a><br>`;
});
break;
}
case 'embed': {
const embedInfo = body.embedMap[block.embedId];
const embed = ({
twitter: `
<a href="https://twitter.com/_/status/${embedInfo.contentId}" target="_blank">
<div class="embed-view">
<h3 class="subtitle">(Twitter)</h3>
</div>
</a>
<br>
`,
youtube: `
<a href="https://www.youtube.com/watch?v=${embedInfo.contentId}" target="_blank">
<div class="embed-view">
<h3 class="subtitle">(YouTube)</h3>
</div>
</a>
<br>
`,
fanbox: `
<a href="https://www.pixiv.net/fanbox/${embedInfo.contentId}" target="_blank">
<div class="embed-view">
<h3 class="subtitle">(Fanbox)</h3>
</div>
</a>
<br>
`,
vimeo: `
<a href="https://vimeo.com/${embedInfo.contentId}" target="_blank">
<div class="embed-view">
<h3 class="subtitle">(Vimeo)</h3>
</div>
</a>
<br>
`,
google_forms: `
<a href="https://docs.google.com/forms/d/e/${embedInfo.contentId}/viewform?usp=sf_link" target="_blank">
<div class="embed-view">
<h3 class="subtitle">(Google Forms)</h3>
</div>
</a>
<br>
`,
soundcloud: `
<a href="https://soundcloud.com/${embedInfo.contentId}" target="_blank">
<div class="embed-view">
<h3 class="subtitle">(Soundcloud)</h3>
</div>
</a>
<br>
`
})[embedInfo.serviceProvider];
concatenatedText += embed;
break;
}
}
});
}
return `${bodyText}<br>${concatenatedText}`;
}
module.exports = data => {
debug('kemono:importer:fanbox:' + data.id)('Starting Pixiv Fanbox import...');
failsafe.set(data.id, JSON.stringify({ importer: 'fanbox', data: data }), 'EX', 1800);
scraper(data.id, data.key);
};
|
JavaScript
|
CL
|
6bdd4969d9acbfe22915fcb06697b8be4204f30fc09450e2e1b7ecf086053b66
|
/*
* Flipdish Open API v1.0
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: v1.0
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
*
* Swagger Codegen version: 2.4.19
*
* Do not edit the class manually.
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/Field'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./Field'));
} else {
// Browser globals (root is window)
if (!root.Flipdish) {
root.Flipdish = {};
}
root.Flipdish.FieldGroup = factory(root.Flipdish.ApiClient, root.Flipdish.Field);
}
}(this, function(ApiClient, Field) {
'use strict';
/**
* The FieldGroup model module.
* @module model/FieldGroup
* @version 1.0.0
*/
/**
* Constructs a new <code>FieldGroup</code>.
* Field group
* @alias module:model/FieldGroup
* @class
* @param Name {String} Name
* @param Position {Number} Position <remarks>Position order in the field groups to display</remarks>
*/
var exports = function(Name, Position) {
this.Name = Name;
this.Position = Position;
};
/**
* Constructs a <code>FieldGroup</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/FieldGroup} obj Optional instance to populate.
* @return {module:model/FieldGroup} The populated <code>FieldGroup</code> instance.
*/
exports.constructFromObject = function(data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('Name'))
obj.Name = ApiClient.convertToType(data['Name'], 'String');
if (data.hasOwnProperty('Description'))
obj.Description = ApiClient.convertToType(data['Description'], 'String');
if (data.hasOwnProperty('Tooltip'))
obj.Tooltip = ApiClient.convertToType(data['Tooltip'], 'String');
if (data.hasOwnProperty('Position'))
obj.Position = ApiClient.convertToType(data['Position'], 'Number');
if (data.hasOwnProperty('Fields'))
obj.Fields = ApiClient.convertToType(data['Fields'], [Field]);
}
return obj;
}
/**
* Name
* @member {String} Name
*/
exports.prototype.Name = undefined;
/**
* Description
* @member {String} Description
*/
exports.prototype.Description = undefined;
/**
* Tooltip <remarks>Displays on text hover</remarks>
* @member {String} Tooltip
*/
exports.prototype.Tooltip = undefined;
/**
* Position <remarks>Position order in the field groups to display</remarks>
* @member {Number} Position
*/
exports.prototype.Position = undefined;
/**
* Fields
* @member {Array.<module:model/Field>} Fields
*/
exports.prototype.Fields = undefined;
return exports;
}));
|
JavaScript
|
CL
|
567b48128ec7336c1538b5872b32008d7d19d2c5015fda279f2c0724e5ccac00
|
const E2eHelpers = require('../../../../platform/testing/e2e/helpers');
const Timeouts = require('../../../../platform/testing/e2e/timeouts');
const PageHelpers = require('./feedback-tool-helpers');
const testData = require('./schema/maximal-test.json');
const FormsTestHelpers = require('../../../../platform/testing/e2e/form-helpers');
const manifest = require('../../feedback-tool/manifest.json');
module.exports = E2eHelpers.createE2eTest(client => {
PageHelpers.initApplicationSubmitMock();
client
.openUrl(`${E2eHelpers.baseUrl}${manifest.rootUrl}`)
.waitForElementVisible('body', Timeouts.normal)
.waitForElementVisible('.schemaform-title', Timeouts.slow)
.click('.schemaform-start-button');
E2eHelpers.overrideVetsGovApi(client);
FormsTestHelpers.overrideFormsScrolling(client);
E2eHelpers.expectNavigateAwayFrom(client, '/introduction');
// Applicant relationship
client
.waitForElementPresent(
'input[name="root_onBehalfOf"][value="Myself"]',
Timeouts.normal,
)
.axeCheck('.main');
PageHelpers.completeRelationshipInformation(client, testData.data);
client.click('.form-progress-buttons .usa-button-primary');
E2eHelpers.expectNavigateAwayFrom(client, '/applicant-relationship');
// Applicant information
client
.waitForElementVisible('input[name="root_fullName_first"]', Timeouts.normal)
.axeCheck('.main');
PageHelpers.completeApplicantInformation(client, testData.data);
client.click('.form-progress-buttons .usa-button-primary');
E2eHelpers.expectNavigateAwayFrom(client, '/applicant-information');
// Service information
client
.waitForElementVisible('select[name="root_serviceBranch"]', Timeouts.normal)
.axeCheck('.main');
PageHelpers.completeServiceInformation(client, testData.data);
client.click('.form-progress-buttons .usa-button-primary');
E2eHelpers.expectNavigateAwayFrom(client, '/service-information');
// Contact information
client
.waitForElementVisible(
'select[name="root_address_country"]',
Timeouts.normal,
)
.axeCheck('.main');
PageHelpers.completeContactInformation(client, testData.data);
client.click('.form-progress-buttons .usa-button-primary');
E2eHelpers.expectNavigateAwayFrom(client, '/contact-information');
// Benefit information
client
.waitForElementPresent(
'input[name="root_educationDetails_programs_chapter33"]',
Timeouts.normal,
)
.axeCheck('.main');
PageHelpers.completeBenefitInformation(client, testData.data);
client.click('.form-progress-buttons .usa-button-primary');
E2eHelpers.expectNavigateAwayFrom(client, '/benefits-information');
// School information
client
.waitForElementPresent('input[type="checkbox"]', Timeouts.normal)
.axeCheck('.main');
PageHelpers.completeSchoolInformation(client, testData.data);
client.click('.form-progress-buttons .usa-button-primary');
E2eHelpers.expectNavigateAwayFrom(client, '/school-information');
// Issue information
client
.waitForElementPresent(
'input[name="root_issue_recruiting"]',
Timeouts.normal,
)
.axeCheck('.main');
PageHelpers.completeIssueInformation(client, testData.data);
client.click('.form-progress-buttons .usa-button-primary');
E2eHelpers.expectNavigateAwayFrom(client, '/issue-information');
// Review and submit page
client
.waitForElementVisible(
'label[name="privacyAgreementAccepted-label"]',
Timeouts.slow,
)
.pause(1000)
.click('input[type="checkbox"]')
.axeCheck('.main')
.click('.form-progress-buttons .usa-button-primary');
client.pause(5000);
client.expect
.element('.js-test-location')
.attribute('data-location')
.to.not.contain('/review-and-submit')
.before(Timeouts.submission);
// Confirmation page
client.waitForElementVisible('.confirmation-page-title', Timeouts.normal);
client.axeCheck('.main');
client.end();
});
|
JavaScript
|
CL
|
e64ad48b8f71b79c69b38282adb19fd7a03af7665066195d96da899212dd66db
|
(global["webpackJsonp"] = global["webpackJsonp"] || []).push([["pages/picture/picture"],{
/***/ 63:
/*!************************************************************************************!*\
!*** F:/uni-app/xiaochengxu/myUniapp/main.js?{"page":"pages%2Fpicture%2Fpicture"} ***!
\************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(createPage) {__webpack_require__(/*! uni-pages */ 4);
var _vue = _interopRequireDefault(__webpack_require__(/*! vue */ 2));
var _picture = _interopRequireDefault(__webpack_require__(/*! ./pages/picture/picture.vue */ 64));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
createPage(_picture.default);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@dcloudio/uni-mp-weixin/dist/index.js */ 1)["createPage"]))
/***/ }),
/***/ 64:
/*!*****************************************************************!*\
!*** F:/uni-app/xiaochengxu/myUniapp/pages/picture/picture.vue ***!
\*****************************************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _picture_vue_vue_type_template_id_c0f1f9f8___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./picture.vue?vue&type=template&id=c0f1f9f8& */ 65);
/* harmony import */ var _picture_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./picture.vue?vue&type=script&lang=js& */ 67);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _picture_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _picture_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _picture_vue_vue_type_style_index_0_lang_less___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./picture.vue?vue&type=style&index=0&lang=less& */ 69);
/* harmony import */ var _download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/runtime/componentNormalizer.js */ 10);
var renderjs
/* normalize component */
var component = Object(_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__["default"])(
_picture_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"],
_picture_vue_vue_type_template_id_c0f1f9f8___WEBPACK_IMPORTED_MODULE_0__["render"],
_picture_vue_vue_type_template_id_c0f1f9f8___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"],
false,
null,
null,
null,
false,
_picture_vue_vue_type_template_id_c0f1f9f8___WEBPACK_IMPORTED_MODULE_0__["components"],
renderjs
)
component.options.__file = "pages/picture/picture.vue"
/* harmony default export */ __webpack_exports__["default"] = (component.exports);
/***/ }),
/***/ 65:
/*!************************************************************************************************!*\
!*** F:/uni-app/xiaochengxu/myUniapp/pages/picture/picture.vue?vue&type=template&id=c0f1f9f8& ***!
\************************************************************************************************/
/*! exports provided: render, staticRenderFns, recyclableRender, components */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_picture_vue_vue_type_template_id_c0f1f9f8___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--16-0!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/webpack-uni-mp-loader/lib/template.js!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-uni-app-loader/page-meta.js!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!./picture.vue?vue&type=template&id=c0f1f9f8& */ 66);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_picture_vue_vue_type_template_id_c0f1f9f8___WEBPACK_IMPORTED_MODULE_0__["render"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_picture_vue_vue_type_template_id_c0f1f9f8___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "recyclableRender", function() { return _download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_picture_vue_vue_type_template_id_c0f1f9f8___WEBPACK_IMPORTED_MODULE_0__["recyclableRender"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "components", function() { return _download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_picture_vue_vue_type_template_id_c0f1f9f8___WEBPACK_IMPORTED_MODULE_0__["components"]; });
/***/ }),
/***/ 66:
/*!************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--16-0!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/template.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-uni-app-loader/page-meta.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!F:/uni-app/xiaochengxu/myUniapp/pages/picture/picture.vue?vue&type=template&id=c0f1f9f8& ***!
\************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! exports provided: render, staticRenderFns, recyclableRender, components */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "recyclableRender", function() { return recyclableRender; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "components", function() { return components; });
var components
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
}
var recyclableRender = false
var staticRenderFns = []
render._withStripped = true
/***/ }),
/***/ 67:
/*!******************************************************************************************!*\
!*** F:/uni-app/xiaochengxu/myUniapp/pages/picture/picture.vue?vue&type=script&lang=js& ***!
\******************************************************************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_picture_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/babel-loader/lib!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--12-1!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/webpack-uni-mp-loader/lib/script.js!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!./picture.vue?vue&type=script&lang=js& */ 68);
/* harmony import */ var _download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_picture_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_picture_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_picture_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_picture_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony default export */ __webpack_exports__["default"] = (_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_picture_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0___default.a);
/***/ }),
/***/ 68:
/*!*************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/babel-loader/lib!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--12-1!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/script.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!F:/uni-app/xiaochengxu/myUniapp/pages/picture/picture.vue?vue&type=script&lang=js& ***!
\*************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(uni) {Object.defineProperty(exports, "__esModule", { value: true });exports.default = void 0; //
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var _default =
{
data: function data() {
return {
scrollTop: 0,
current: 0,
navList: [
{ title: '家具生活', id: 1 },
{ title: '古典美女', id: 2 },
{ title: '明星帅哥', id: 3 },
{ title: '明星美女', id: 4 },
{ title: '朋友聚会', id: 5 },
{ title: '年级聚会', id: 6 },
{ title: '班级联系', id: 7 },
{ title: '青村可爱', id: 8 },
{ title: '房价山治', id: 9 },
{ title: '周末玩耍', id: 10 },
{ title: '学习进步', id: 11 },
{ title: '心想事成', id: 12 },
{ title: '梦想成真', id: 13 },
{ title: '勤奋学习', id: 14 },
{ title: '呵呵呵呵', id: 15 }],
detailsList: [
{ dir: '我是很漂亮的美女,我也非常的性感和迷人,同时我也很友好,喜欢交朋友', url: '../../static/images/pic1.png', id: 1 },
{ dir: '我是很漂亮的美女,我也非常的性感和迷人,同时我也很友好,喜欢交朋友', url: '../../static/images/pic2.png', id: 2 },
{ dir: '我是很漂亮的美女,我也非常的性感和迷人,同时我也很友好,喜欢交朋友', url: '../../static/images/pic3.png', id: 3 },
{ dir: '我是很漂亮的美女,我也非常的性感和迷人,同时我也很友好,喜欢交朋友', url: '../../static/images/pic4.png', id: 4 },
{ dir: '我是很漂亮的美女,我也非常的性感和迷人,同时我也很友好,喜欢交朋友', url: '../../static/images/pic5.png', id: 5 },
{ dir: '我是很漂亮的美女,我也非常的性感和迷人,同时我也很友好,喜欢交朋友', url: '../../static/images/picture.png', id: 6 }] };
},
methods: {
itemClick: function itemClick(idx) {
this.current = idx;
this.detailsList[idx] && this.detailsList.push(this.detailsList[idx]);
},
imgClick: function imgClick(idx) {
// console.log(this.detailsList.map(item => item.url))
uni.previewImage({
current: idx,
urls: this.detailsList.map(function (item) {return item.url;}) });
} } };exports.default = _default;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@dcloudio/uni-mp-weixin/dist/index.js */ 1)["default"]))
/***/ }),
/***/ 69:
/*!***************************************************************************************************!*\
!*** F:/uni-app/xiaochengxu/myUniapp/pages/picture/picture.vue?vue&type=style&index=0&lang=less& ***!
\***************************************************************************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_10_oneOf_1_0_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_10_oneOf_1_1_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_10_oneOf_1_2_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_10_oneOf_1_3_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_less_loader_dist_cjs_js_ref_10_oneOf_1_4_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_10_oneOf_1_5_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_picture_vue_vue_type_style_index_0_lang_less___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/mini-css-extract-plugin/dist/loader.js??ref--10-oneOf-1-0!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/css-loader/dist/cjs.js??ref--10-oneOf-1-1!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/loaders/stylePostLoader.js!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--10-oneOf-1-2!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/postcss-loader/src??ref--10-oneOf-1-3!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/less-loader/dist/cjs.js??ref--10-oneOf-1-4!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--10-oneOf-1-5!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!../../../../../download/HBuilderX.3.1.8.20210406.full/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!./picture.vue?vue&type=style&index=0&lang=less& */ 70);
/* harmony import */ var _download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_10_oneOf_1_0_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_10_oneOf_1_1_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_10_oneOf_1_2_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_10_oneOf_1_3_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_less_loader_dist_cjs_js_ref_10_oneOf_1_4_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_10_oneOf_1_5_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_picture_vue_vue_type_style_index_0_lang_less___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_10_oneOf_1_0_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_10_oneOf_1_1_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_10_oneOf_1_2_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_10_oneOf_1_3_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_less_loader_dist_cjs_js_ref_10_oneOf_1_4_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_10_oneOf_1_5_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_picture_vue_vue_type_style_index_0_lang_less___WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_10_oneOf_1_0_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_10_oneOf_1_1_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_10_oneOf_1_2_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_10_oneOf_1_3_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_less_loader_dist_cjs_js_ref_10_oneOf_1_4_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_10_oneOf_1_5_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_picture_vue_vue_type_style_index_0_lang_less___WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_10_oneOf_1_0_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_10_oneOf_1_1_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_10_oneOf_1_2_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_10_oneOf_1_3_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_less_loader_dist_cjs_js_ref_10_oneOf_1_4_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_10_oneOf_1_5_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_picture_vue_vue_type_style_index_0_lang_less___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony default export */ __webpack_exports__["default"] = (_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_10_oneOf_1_0_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_10_oneOf_1_1_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_10_oneOf_1_2_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_10_oneOf_1_3_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_less_loader_dist_cjs_js_ref_10_oneOf_1_4_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_10_oneOf_1_5_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_download_HBuilderX_3_1_8_20210406_full_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_picture_vue_vue_type_style_index_0_lang_less___WEBPACK_IMPORTED_MODULE_0___default.a);
/***/ }),
/***/ 70:
/*!***********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/mini-css-extract-plugin/dist/loader.js??ref--10-oneOf-1-0!./node_modules/css-loader/dist/cjs.js??ref--10-oneOf-1-1!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--10-oneOf-1-2!./node_modules/postcss-loader/src??ref--10-oneOf-1-3!./node_modules/less-loader/dist/cjs.js??ref--10-oneOf-1-4!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--10-oneOf-1-5!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!F:/uni-app/xiaochengxu/myUniapp/pages/picture/picture.vue?vue&type=style&index=0&lang=less& ***!
\***********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
if(false) { var cssReload; }
/***/ })
},[[63,"common/runtime","common/vendor"]]]);
//# sourceMappingURL=../../../.sourcemap/mp-weixin/pages/picture/picture.js.map
|
JavaScript
|
CL
|
e627ce8b36f20d89a2690d21035aeb2c6f7bbe5319538a50023b1f35336c8cf4
|
import _ from 'lodash/fp';
import localForage from 'localforage';
import queryString from 'query-string';
import { fetchJson } from 'utils/fetch';
import { getExp } from 'utils/exp';
import { achievements, initialAchievementState } from 'utils/achievements';
import { parseDate } from 'utils/date';
import { getScoreWithoutBonus } from 'utils/score';
import WorkerProfilesProcessing from 'workerize-loader!utils/workers/profilesPostProcess'; // eslint-disable-line import/no-webpack-loader-syntax
import * as profilesProcessing from 'utils/workers/profilesPostProcess';
import { HOST } from 'constants/backend';
import { DEBUG } from 'constants/env';
import { RANK_FILTER } from 'constants/leaderboard';
const LOADING = `TOP/LOADING`;
const STOP_LOADING = `TOP/STOP_LOADING`;
const SUCCESS = `TOP/SUCCESS`;
const ERROR = `TOP/ERROR`;
const SET_FILTER = `TOP/SET_FILTER`;
const RESET_FILTER = `TOP/RESET_FILTER`;
const RANKING_CHANGE_SET = `TOP/RANKING_CHANGE_SET`;
const PROFILES_UPDATE = `TOP/PROFILES_UPDATE`;
const highscoresUrl = process.env.REACT_APP_SOCKET
? 'results/highscores/trusted'
: 'results/highscores';
export const defaultFilter = {
rank: RANK_FILTER.SHOW_ALL,
};
const initialState = {
isLoading: false,
isLoadingRanking: false,
data: [],
filter: defaultFilter,
players: {},
profiles: {},
results: [],
resultInfo: {},
sharedCharts: {},
};
export const gradeComparator = {
'?': 0,
F: 1,
D: 2,
'D+': 3,
C: 4,
'C+': 5,
B: 6,
'B+': 7,
A: 8,
'A+': 9,
S: 10,
SS: 11,
SSS: 12,
};
const tryFixIncompleteResult = (result, maxTotalSteps) => {
if (!maxTotalSteps) {
return;
}
const infos = [result.perfect, result.great, result.good, result.bad, result.miss];
let fixableIndex = -1,
absentNumbersCount = 0,
localStepSum = 0;
for (let i = 0; i < 5; ++i) {
if (!_.isNumber(infos[i])) {
fixableIndex = i;
absentNumbersCount++;
} else {
localStepSum += infos[i];
}
}
if (absentNumbersCount === 1) {
result[['perfect', 'great', 'good', 'bad', 'miss'][fixableIndex]] =
maxTotalSteps - localStepSum;
}
};
const guessGrade = (result) => {
if (result.misses === 0 && result.bads === 0 && result.goods === 0) {
if (result.greats === 0) {
return 'SSS';
} else {
return 'SS';
}
}
return result.grade;
};
const mapResult = (res, players, chart) => {
if (typeof res.recognition_notes === 'undefined') {
// Short result, minimum info, only for ELO calculation
// Will be replaced with better result later
return {
id: res.id,
isUnknownPlayer: players[res.player].arcade_name === 'PUMPITUP',
isIntermediateResult: true,
sharedChartId: res.shared_chart,
playerId: res.player,
nickname: players[res.player].nickname,
nicknameArcade: players[res.player].arcade_name,
date: res.gained,
dateObject: parseDate(res.gained),
grade: res.grade,
isExactDate: !!res.exact_gain_date,
score: res.score,
scoreRaw: getScoreWithoutBonus(res.score, res.grade),
isRank: !!res.rank_mode,
};
}
// Full best result
let _r = {
isUnknownPlayer: players[res.player].arcade_name === 'PUMPITUP',
isIntermediateResult: false,
sharedChartId: res.shared_chart,
id: res.id,
playerId: res.player,
nickname: players[res.player].nickname,
nicknameArcade: players[res.player].arcade_name,
originalChartMix: res.original_mix,
originalChartLabel: res.original_label,
originalScore: res.original_score,
date: res.gained,
dateObject: parseDate(res.gained),
grade: res.grade !== '?' ? res.grade : guessGrade(res),
isExactDate: !!res.exact_gain_date,
score: res.score,
scoreRaw: getScoreWithoutBonus(res.score, res.grade),
scoreIncrease: res.score_increase,
calories: res.calories && res.calories / 1000,
perfect: res.perfects,
great: res.greats,
good: res.goods,
bad: res.bads,
miss: res.misses,
combo: res.max_combo,
mods: res.mods_list,
isRank: !!res.rank_mode,
isHJ: (res.mods_list || '').split(' ').includes('HJ'),
isMachineBest: res.recognition_notes === 'machine_best',
isMyBest: res.recognition_notes === 'personal_best',
};
tryFixIncompleteResult(_r, chart.maxTotalSteps);
const perfects = Math.sqrt(_r.perfect) * 10;
const acc = perfects
? Math.floor(
((perfects * 100 + _r.great * 85 + _r.good * 60 + _r.bad * 20 + _r.miss * -25) /
(perfects + _r.great + _r.good + _r.bad + _r.miss)) *
100
) / 100
: null;
const accRaw = _r.perfect
? Math.floor(
((_r.perfect * 100 + _r.great * 85 + _r.good * 60 + _r.bad * 20 + _r.miss * -25) /
(_r.perfect + _r.great + _r.good + _r.bad + _r.miss)) *
100
) / 100
: null;
_r.accuracy = acc < 0 ? 0 : accRaw === 100 ? 100 : acc && +acc.toFixed(2);
_r.accuracyRaw = _.toNumber(_r.accuracy);
return _r;
};
const getMaxRawScore = (score) => {
return ((score.scoreRaw / score.accuracy) * 100) / (score.isRank ? 1.2 : 1);
};
const initializeProfile = (result, profiles, players) => {
const id = result.playerId;
const resultsByLevel = _.fromPairs(Array.from({ length: 28 }).map((x, i) => [i + 1, []]));
profiles[id] = {
name: result.nickname,
nameArcade: result.nicknameArcade,
resultsByGrade: {},
resultsByLevel,
firstResultDate: result.dateObject,
lastResultDate: result.dateObject,
count: 0,
battleCount: 0,
countAcc: 0,
grades: { F: 0, D: 0, C: 0, B: 0, A: 0, S: 0, SS: 0, SSS: 0 },
sumAccuracy: 0,
rankingHistory: [],
ratingHistory: [],
lastPlace: null,
lastBattleDate: 0,
region: players[id].region,
};
profiles[id].achievements = _.flow(
_.keys,
_.map((achName) => [
achName,
{ ...(achievements[achName].initialState || initialAchievementState) },
]),
_.fromPairs
)(achievements);
profiles[id].exp = 0;
};
const getProfileInfoFromResult = (result, chart, profiles) => {
const profile = profiles[result.playerId];
profile.count++;
if (result.accuracy) {
profile.countAcc++;
profile.sumAccuracy += result.accuracy;
}
profile.grades[result.grade.replace('+', '')]++;
if (chart.chartType !== 'COOP' && result.isBestGradeOnChart) {
profile.resultsByGrade[result.grade] = [
...(profile.resultsByGrade[result.grade] || []),
{ result, chart },
];
profile.resultsByLevel[chart.chartLevel] = [
...(profile.resultsByLevel[chart.chartLevel] || []),
{ result, chart },
];
}
if (result.isExactDate && profile.lastResultDate < result.dateObject) {
profile.lastResultDate = result.dateObject;
}
profile.achievements = _.mapValues.convert({ cap: false })((achState, achName) => {
return achievements[achName].resultFunction(result, chart, achState, profile);
}, profile.achievements);
profile.exp += getExp(result, chart);
};
const processData = (data, tracklist) => {
const { players, results, shared_charts } = data;
//// Initialization
// Init for TOP
const mappedResults = [];
const getTopResultId = (result) => `${result.sharedChartId}-${result.playerId}-${result.isRank}`;
const getBestGradeResultId = (result) => `${result.sharedChartId}-${result.playerId}`;
const topResults = {}; // Temp object
const bestGradeResults = {}; // Temp object
const top = {}; // Main top scores pbject
// Battles for ELO calculation
const battles = [];
// Profiles for every player
let profiles = {};
// Loop 1
for (let resRaw of results) {
if (!players[resRaw.player]) {
// Player of this result was not found in list of players. Ignoring this result like it doesn't exist
continue;
}
const sharedChartId = resRaw.shared_chart;
// Initialize Song
if (!top[sharedChartId]) {
const sharedChart = shared_charts[sharedChartId];
const label = _.toUpper(sharedChart.chart_label);
const [chartType, chartLevel] = label.match(/(\D+)|(\d+)/g);
top[sharedChartId] = {
song: sharedChart.track_name,
chartLabel: label,
chartLevel,
chartType,
duration: sharedChart.duration,
sharedChartId: sharedChartId,
maxTotalSteps: sharedChart.max_total_steps,
results: [],
allResultsIds: [],
};
}
// Getting current chart and result (mapped)
const chartTop = top[sharedChartId];
const result = mapResult(resRaw, players, chartTop);
mappedResults.push(result);
// Inserting result into TOP
const topResultId = getTopResultId(result);
const currentTopResult = topResults[topResultId];
if (!currentTopResult || currentTopResult.score < result.score) {
if (currentTopResult) {
const oldScoreIndex = chartTop.results.indexOf(currentTopResult);
if (oldScoreIndex !== -1) {
chartTop.results.splice(oldScoreIndex, 1);
}
}
const newScoreIndex = _.sortedLastIndexBy((r) => -r.score, result, chartTop.results);
if (!result.isUnknownPlayer || newScoreIndex === 0) {
chartTop.results.splice(newScoreIndex, 0, result);
chartTop.latestScoreDate = result.date;
chartTop.allResultsIds.push(result.playerId);
topResults[topResultId] = result;
}
if (!result.isUnknownPlayer) {
chartTop.results.forEach((enemyResult) => {
if (
!enemyResult.isUnknownPlayer &&
enemyResult.isRank === result.isRank &&
enemyResult.playerId !== result.playerId &&
result.score &&
enemyResult.score
) {
battles.push([result, enemyResult, chartTop]);
}
});
}
}
// Getting best grade of player on this chart
if (!result.isIntermediateResult) {
const bestGradeResultId = getBestGradeResultId(result);
const currentBestGradeRes = bestGradeResults[bestGradeResultId];
if (
!currentBestGradeRes ||
gradeComparator[currentBestGradeRes.grade] <= gradeComparator[result.grade]
) {
// Using <= here, so newer scores always win and rewrite old scores
currentBestGradeRes && (currentBestGradeRes.isBestGradeOnChart = false);
result.isBestGradeOnChart = true;
bestGradeResults[bestGradeResultId] = result;
}
}
}
// Loop 2, when the TOP is already set up
for (let chartId in top) {
const chart = top[chartId];
chart.maxScore = null;
for (let result of chart.results) {
if (!result.isRank) {
if (result.accuracy) {
const maxScoreCandidate = getMaxRawScore(result, chart);
if (chart.maxScore < maxScoreCandidate) {
chart.maxScore = maxScoreCandidate;
}
} else if (chart.maxScore && chart.maxScore < result.score) {
chart.maxScore = result.score;
}
}
// Getting some info about players
if (!result.isUnknownPlayer && !result.isIntermediateResult) {
if (!profiles[result.playerId]) {
initializeProfile(result, profiles, players);
}
getProfileInfoFromResult(result, chart, profiles);
}
}
}
return { mappedResults, profiles, sharedCharts: top, battles };
};
export default function reducer(state = initialState, action) {
switch (action.type) {
case LOADING:
return {
...state,
isLoading: true,
};
case STOP_LOADING:
return {
...state,
isLoading: false,
};
case ERROR:
return {
...state,
isLoading: false,
error: action.error,
data: initialState.data,
players: initialState.players,
profiles: initialState.profiles,
results: initialState.results,
sharedCharts: initialState.sharedCharts,
scoreInfo: {},
};
case SUCCESS:
return {
...state,
isLoading: false,
isLoadingRanking: true,
data: action.data,
players: action.players,
profiles: action.profiles,
results: action.results,
sharedCharts: action.sharedCharts,
originalData: action.originalData,
scoreInfo: {},
};
case PROFILES_UPDATE:
return {
...state,
isLoadingRanking: false,
profiles: action.profiles,
resultInfo: action.resultInfo,
sharedCharts: action.sharedCharts,
data: _.values(action.sharedCharts),
};
case SET_FILTER:
return {
...state,
filter: action.filter,
};
case RESET_FILTER:
return {
...state,
filter: defaultFilter,
};
case RANKING_CHANGE_SET:
const hasPrevList = !_.isEmpty(action.listPrev);
return {
...state,
profiles: _.mapValues((playerOriginal) => {
const player = {
...playerOriginal,
prevRating: _.get(playerOriginal.id, action.rankingsPointsMap),
};
if (!hasPrevList) {
return player; // First time opening this thing and we didn't have any previous data
}
if (!_.includes(player.id, action.listPrev)) {
return { ...player, change: 'NEW' };
} else if (!_.includes(player.id, action.listNow)) {
// Should NEVER happen, idk if this is possible
return { ...player, change: '?' };
} else {
return {
...player,
change: _.indexOf(player.id, action.listPrev) - _.indexOf(player.id, action.listNow),
};
}
}, state.profiles),
};
default:
return state;
}
}
export const fetchResults = () => {
return async (dispatch, getState) => {
dispatch({ type: LOADING });
try {
const data = await dispatch(
fetchJson({
url: `${HOST}/${highscoresUrl}`,
})
);
if (data.error) {
throw new Error(data.error);
}
// HACKS for test
// data.results = _.dropRight(500, data.results);
// data.results = _.dropRight(9500, data.results);
// console.log(1, data.results);
// data.results = _.filter((res) => res.gained < '2020-07-05 00:00:00', data.results);
// data.results = _.filter(res => res.gained < '2020-03-12 16:55:00', data.results);
// data.results = _.filter(res => res.gained < '2020-03-12 16:34:51', data.results);
// console.log(2, data.results);
dispatch(processResultsData(data));
} catch (error) {
console.log(error);
dispatch({ type: ERROR, error });
}
};
};
export const appendNewResults = (lastDate) => {
return async (dispatch, getState) => {
const { originalData, sharedCharts } = getState().results;
if (!lastDate) {
return dispatch(fetchResults());
}
dispatch({ type: LOADING });
try {
const data = await dispatch(
fetchJson({
url: `${HOST}/${highscoresUrl}?${queryString.stringify({ start_date: lastDate })}`,
})
);
if (data.error) {
throw new Error(data.error);
}
const appendedResults = _.filter((result) => {
const currentResults = sharedCharts[result.shared_chart];
if (!currentResults) {
return true;
}
const oldResult = _.find(
(old) =>
old.id === result.id ||
(old.playerId === result.player && old.isRank === !!result.rank_mode),
currentResults.results
);
if (!oldResult) {
if (result.player === 1 && currentResults.results[0].score > result.score) {
return false;
}
return true;
}
if (oldResult.id === result.id || oldResult.score >= result.score) {
return false;
}
return true;
}, data.results);
console.log('Received results:', data, '; Will append:', appendedResults);
if (!_.isEmpty(appendedResults)) {
const mergedData = {
players: data.players,
results: [...originalData.results, ...appendedResults],
shared_charts: { ...originalData.shared_charts, ...data.shared_charts },
};
dispatch(processResultsData(mergedData));
} else {
dispatch({ type: STOP_LOADING });
}
} catch (error) {
console.log(error);
dispatch({ type: ERROR, error });
}
};
};
const processResultsData = (data) => {
return async (dispatch, getState) => {
const { tracklist } = getState();
const { sharedCharts, mappedResults, profiles, battles } = processData(data, tracklist);
dispatch({
type: SUCCESS,
data: _.values(sharedCharts),
players: _.flow(
_.toPairs,
_.map(([id, player]) => ({ ...player, id: _.toInteger(id) }))
)(data.players),
results: mappedResults,
profiles,
sharedCharts,
originalData: data,
});
// Parallelized calculation of ELO and profile data
const input = { sharedCharts, profiles, tracklist, battles, debug: DEBUG };
let promise, worker;
if (window.Worker) {
worker = new WorkerProfilesProcessing();
promise = worker.getProcessedProfiles(input);
} else {
promise = new Promise((res) => res(profilesProcessing.getProcessedProfiles(input)));
}
const output = await promise;
DEBUG && console.log(output.logText);
DEBUG &&
console.log(
'Processed profiles:',
Object.values(output.profiles)
.filter((q) => q.pp)
.sort((a, b) => b.pp.pp - a.pp.pp)
);
// console.log(output.sharedCharts);
// let byLevel = _.groupBy((ch) => ch.chartLevel, _.values(output.sharedCharts));
// function getSD(array) {
// const n = array.length;
// const mean = array.reduce((a, b) => a + b) / n;
// return Math.sqrt(array.map((x) => Math.pow(x - mean, 2)).reduce((a, b) => a + b) / n);
// }
// byLevel = _.mapValues((charts) => {
// return {
// avgLevel: _.meanBy((ch) => ch.interpolatedDifficulty || Number(ch.chartLevel), charts),
// deviation: getSD(charts.map((ch) => ch.interpolatedDifficulty || Number(ch.chartLevel))),
// charts,
// };
// }, byLevel);
// console.log(byLevel);
// console.log(
// _.values(byLevel)
// .map((q) => `${q.avgLevel}\t${q.deviation}`)
// .join('\n')
// );
dispatch({
type: PROFILES_UPDATE,
...output,
});
dispatch(calculateRankingChanges(output.profiles));
if (worker) worker.terminate();
};
};
export const setFilter = (filter) => ({
type: SET_FILTER,
filter,
});
export const resetFilter = () => ({
type: RESET_FILTER,
});
const getListOfNames = _.map('id');
const getMapOfRatings = _.flow(
_.map((q) => [q.id, q.rating]),
_.fromPairs
);
export const calculateRankingChanges = (profiles) => {
return async (dispatch, getState) => {
try {
const ranking = _.orderBy('ratingRaw', 'desc', _.values(profiles));
const [lastChangedRanking, lastChangedRankingPoints, lastFetchedRanking] = await Promise.all([
localForage.getItem('lastChangedRanking_v3'),
localForage.getItem('lastChangedRankingPoints_v3'),
localForage.getItem('lastFetchedRanking_v3'),
]);
const listNow = getListOfNames(ranking);
const listLastFetched = getListOfNames(lastFetchedRanking);
const listLastChanged = getListOfNames(lastChangedRanking);
const mapPointsNow = getMapOfRatings(ranking);
const mapPointsLastFetched = getMapOfRatings(lastFetchedRanking);
const mapPointsLastChanged = getMapOfRatings(lastChangedRankingPoints);
let rankingsPointsMap = mapPointsLastChanged;
// console.log(listNow, listLastFetched, listLastChanged);
// console.log(mapPointsNow, mapPointsLastFetched, mapPointsLastChanged);
if (!_.isEqual(mapPointsNow, mapPointsLastFetched)) {
// Between this fetch and last fetch there was a CHANGE in ranking
localForage.setItem('lastChangedRankingPoints_v3', lastFetchedRanking);
rankingsPointsMap = mapPointsLastFetched;
}
let listPrev = listLastChanged;
if (!_.isEqual(listNow, listLastFetched)) {
// Between this fetch and last fetch there was a CHANGE in ranking
localForage.setItem('lastChangedRanking_v3', lastFetchedRanking);
listPrev = listLastFetched;
}
dispatch({
type: RANKING_CHANGE_SET,
listNow,
listPrev,
rankingsPointsMap,
});
localForage.setItem('lastFetchedRanking_v3', ranking);
} catch (error) {
console.warn('Cannot get ranking from local storage', error);
}
};
};
|
JavaScript
|
CL
|
9e7de281204823a33e3ea00c88d0b3e23b2f277200b6069d7830284ffb1bafa1
|
import { getLastItem } from "./array";
import { isArray, isNumber, isObject } from "./assertion";
import { fromEntries, objectKeys } from "./object";
export var breakpoints = Object.freeze(["base", "sm", "md", "lg", "xl", "2xl"]);
export function mapResponsive(prop, mapper) {
if (isArray(prop)) {
return prop.map(item => {
if (item === null) {
return null;
}
return mapper(item);
});
}
if (isObject(prop)) {
return objectKeys(prop).reduce((result, key) => {
result[key] = mapper(prop[key]);
return result;
}, {});
}
if (prop != null) {
return mapper(prop);
}
return null;
}
export function objectToArrayNotation(obj, bps) {
if (bps === void 0) {
bps = breakpoints;
}
var result = bps.map(br => {
var _obj$br;
return (_obj$br = obj[br]) != null ? _obj$br : null;
});
while (getLastItem(result) === null) {
result.pop();
}
return result;
}
export function arrayToObjectNotation(values, bps) {
if (bps === void 0) {
bps = breakpoints;
}
var result = {};
values.forEach((value, index) => {
var key = bps[index];
if (value == null) return;
result[key] = value;
});
return result;
}
export function isResponsiveObjectLike(obj, bps) {
if (bps === void 0) {
bps = breakpoints;
}
var keys = Object.keys(obj);
return keys.length > 0 && keys.every(key => bps.includes(key));
}
/**
* @note
* The code below is the recommended way to analyze breakpoints
* related stuff. Avoid using functions above, it'll be removed in the
* next major
*/
var analyzeCSSValue = value => {
var num = parseFloat(value.toString());
var unit = value.toString().replace(String(num), "");
return {
unitless: !unit,
value: num,
unit
};
};
export var px = value => {
if (value == null) return value;
var {
unitless
} = analyzeCSSValue(value);
return unitless || isNumber(value) ? value + "px" : value;
};
var sortByBreakpointValue = (a, b) => parseInt(a[1], 10) > parseInt(b[1], 10) ? 1 : -1;
var sortBps = breakpoints => fromEntries(Object.entries(breakpoints).sort(sortByBreakpointValue));
function normalize(breakpoints) {
var sorted = sortBps(breakpoints);
return Object.assign(Object.values(sorted), sorted);
}
function keys(breakpoints) {
var value = Object.keys(sortBps(breakpoints));
return new Set(value);
}
function subtract(value) {
if (!value) return value;
value = px(value);
var factor = value.endsWith("px") ? -1 : // the equivalent of 1px in em using a 16px base
-0.0635;
return isNumber(value) ? "" + (value + factor) : value.replace(/([0-9]+\.?[0-9]*)/, m => "" + (parseFloat(m) + factor));
}
function queryString(min, max) {
var query = [];
if (min) query.push("@media screen and (min-width: " + px(min) + ")");
if (query.length > 0 && max) query.push("and");
if (max) query.push("@media screen and (max-width: " + px(max) + ")");
return query.join(" ");
}
export function analyzeBreakpoints(breakpoints) {
var _breakpoints$base;
if (!breakpoints) return null;
breakpoints.base = (_breakpoints$base = breakpoints.base) != null ? _breakpoints$base : "0px";
var normalized = normalize(breakpoints);
var queries = Object.entries(breakpoints).sort(sortByBreakpointValue).map((_ref, index, entry) => {
var _entry;
var [breakpoint, minW] = _ref;
var [, maxW] = (_entry = entry[index + 1]) != null ? _entry : [];
maxW = parseFloat(maxW) > 0 ? subtract(maxW) : undefined;
return {
breakpoint,
minW,
maxW,
maxWQuery: queryString(null, maxW),
minWQuery: queryString(minW),
minMaxQuery: queryString(minW, maxW)
};
});
var _keys = keys(breakpoints);
var _keysArr = Array.from(_keys.values());
return {
keys: _keys,
normalized,
isResponsive(test) {
var keys = Object.keys(test);
return keys.length > 0 && keys.every(key => _keys.has(key));
},
asObject: sortBps(breakpoints),
asArray: normalize(breakpoints),
details: queries,
media: [null, ...normalized.map(minW => queryString(minW)).slice(1)],
toArrayValue(test) {
if (!isObject(test)) {
throw new Error("toArrayValue: value must be an object");
}
var result = _keysArr.map(bp => {
var _test$bp;
return (_test$bp = test[bp]) != null ? _test$bp : null;
});
while (getLastItem(result) === null) {
result.pop();
}
return result;
},
toObjectValue(test) {
if (!Array.isArray(test)) {
throw new Error("toObjectValue: value must be an array");
}
return test.reduce((acc, value, index) => {
var key = _keysArr[index];
if (key != null && value != null) acc[key] = value;
return acc;
}, {});
}
};
}
/**
* since breakpoints are defined as custom properties on an array, you may
* `Object.keys(theme.breakpoints)` to retrieve both regular numeric indices
* and custom breakpoints as string.
*
* This function returns true given a custom array property.
*/
export var isCustomBreakpoint = maybeBreakpoint => Number.isNaN(Number(maybeBreakpoint));
//# sourceMappingURL=responsive.js.map
|
JavaScript
|
CL
|
5307ab51593556fb430ccd361740bc836ae0949cb90063f260dd7a2a3c69035f
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
// css
import styles from './MenuPage.module.css';
// redux
import getMenu from '../../redux/operations/menuOperations';
import {
getLoader,
getModal,
getModalSignUp,
getModalLogIn,
getModalBasket,
} from '../../redux/selectors/selectors';
// components
import SignUp from '../../components/SignUp/SignUp';
import Modal from '../../components/Modal/Modal';
import LogIn from '../../components/LogIn/LogIn';
import Loader from '../../components/Loader/Loader';
import Menu from '../../components/Menu/Menu';
import Basket from '../../components/Basket/Basket';
import SwimButtons from '../../components/SwimButtons/SwimButtons';
// helpers
import { getCategoryFromUrl } from '../../helpers/helpers';
const backgrounds = {
ukraine: styles.backgroundUkraine,
italia: styles.backgroundItaly,
georgia: styles.backgroundGeorgia,
japan: styles.backgroundJapan,
pizza: styles.backgroundPizza,
};
class MenuPage extends Component {
state = {};
static propTypes = {
menuRequest: PropTypes.func.isRequired,
location: PropTypes.shape({ search: PropTypes.string.isRequired })
.isRequired,
modal: PropTypes.bool.isRequired,
signup: PropTypes.bool.isRequired,
login: PropTypes.bool.isRequired,
loader: PropTypes.bool.isRequired,
basket: PropTypes.bool.isRequired,
};
componentDidMount() {
const {
menuRequest,
location: { search },
} = this.props;
menuRequest(search);
}
render() {
const {
modal,
signup,
login,
loader,
basket,
location: { search },
} = this.props;
const wrapperStyles = [
styles.wrapper,
backgrounds[getCategoryFromUrl(search)],
];
return (
<>
{loader ? (
<Loader />
) : (
<div className={wrapperStyles.join(' ')}>
<div className={styles.swimButtons}>
<SwimButtons />
</div>
<div className={styles.content}>
<Menu cuisine={getCategoryFromUrl(search)} />
<div className={styles.busketContainer}>
<Basket />
</div>
</div>
{modal && (
<Modal>
{signup && <SignUp />}
{login && <LogIn />}
{basket && <Basket />}
</Modal>
)}
</div>
)}
</>
);
}
}
const mSTP = state => ({
modal: getModal(state),
signup: getModalSignUp(state),
login: getModalLogIn(state),
loader: getLoader(state),
basket: getModalBasket(state),
});
const mDTP = dispatch => ({
menuRequest: category => dispatch(getMenu(category)),
});
export default connect(mSTP, mDTP)(MenuPage);
|
JavaScript
|
CL
|
d4b01a69dc2203703bc8830cf314e748f3577d70bd65ad74f7edc694b1a99d90
|
//=============================================================================
// Name: ser_io (ser.io)
//
// Auth: Vicente Iborra
//
// Desc: This file/namespace holds a number of classes which are used to
// abstract out some of the EA specific I/O concerns.
//=============================================================================
!INC Local Scripts.EAConstants-JScript
!INC Ser-Scripts-Src.ser
(function() {
var lns = ser.namespace('io');
//=============================================================================
// Desc: A utility class to encapsulate outputting to a string array as a
// console. The main reason for this class is for testing purposes.
//=============================================================================
lns.ArrayConsole = function() {
this.currentIdx = 0;
this.output = new Array();
}
//-------------------------------------------------------------------------
// Desc: This method outputs the given string to the current line on the
// console output. For the ArrayConsole implementation of a console,
// the text is appended to the current line being output.
//
// Args: text (I) Text being output.
//
// Retn: None
//-------------------------------------------------------------------------
lns.ArrayConsole.prototype.write = function(text) {
if (!this.output[this.currentIdx]) {
this.output[this.currentIdx] = "";
}
this.output[this.currentIdx] = this.output[this.currentIdx] + text;
}
//-------------------------------------------------------------------------
// Desc: This method outputs the given string to the next line on the
// console output. For the ArrayConsole implementation of a console,
// the text is added as the next line being output.
//
// Args: text (I) Text being output.
//
// Retn: None
//-------------------------------------------------------------------------
lns.ArrayConsole.prototype.writeLine = function(text) {
this.output[this.currentIdx] = text;
this.currentIdx++;
}
//=============================================================================
// Desc: A utility class to encapsulate outputting to a file based console.
//=============================================================================
lns.FileConsole = function() {}
lns.FileConsole.prototype.DEFAULT_OUTPUT_FILE_PATH = "C:\\file.txt";
lns.FileConsole.prototype.outputFilePath = lns.FileConsole.prototype.DEFAULT_OUTPUT_FILE_PATH;
lns.FileConsole.prototype.fileHandle = null;
lns.FileConsole.prototype.ensureFileIsOpen = function() {
if (this.fileHandle == null) {
var fileSystemObject = new ActiveXObject( "Scripting.FileSystemObject" );
this.fileHandle = fileSystemObject.OpenTextFile(this.outputFilePath, 8, true);
}
}
lns.FileConsole.prototype.write = function(text) {
this.ensureFileIsOpen();
this.fileHandle.Write(text);
}
lns.FileConsole.prototype.writeLine = function(line) {
this.ensureFileIsOpen();
this.fileHandle.WriteLine(line);
}
//=============================================================================
// Desc: A utility class to encapsulate outputting to the EA Output window
//=============================================================================
lns.EaOutputConsole = function() {
this.partialLine = "";
}
lns.EaOutputConsole.prototype.isOutputVisible = false;
lns.EaOutputConsole.prototype.ensureOutputIsVisible = function() {
if (!this.isOutputVisible) {
Repository.EnsureOutputVisible( "Script" );
this.isOutputVisible = true;
}
}
lns.EaOutputConsole.prototype.write = function(text) {
this.partialLine = text;
}
lns.EaOutputConsole.prototype.writeLine = function(line) {
var outputLine = "";
// Make sure we can see the
this.ensureOutputIsVisible();
// Take care of any partial lines
if (this.partialLine != "") {
outputLine += this.partialLine;
this.partialLine = "";
}
// Catch null values
if (line == null) {
outputLine += "";
}
// Finally make sure the line given is output
else {
outputLine += line;
}
// And output it
Session.Output(outputLine);
}
lns.EaOutputConsole.prototype.clear = function() {
Repository.ClearOutput("Script");
}
}());
|
JavaScript
|
CL
|
34358bc4e14d58fb2356c7423c16b06907b1ce7ee529078f21b8635d2abad198
|
import React, { Children, Fragment } from 'react';
import PropTypes from 'prop-types';
import { css } from '@emotion/react';
import splitUsing from '../utils/splitUsing';
import splitWhen from '../utils/splitWhen';
import { isMdxType } from '../utils/mdx';
import usePageLayout from '../hooks/usePageLayout';
const BREAKPOINTS = {
SINGLE_COLUMN: '1240px',
RELATED_CONTENT: '1520px',
};
const SideBySide = ({ className, children, type }) => {
const types = Array.isArray(type) ? type : [type];
const childObjects = Children.toArray(children);
const rendersRightColumn = childObjects.some((child) =>
types.some(
(type) =>
isMdxType(child, type) ||
isMdxType(child, type, { nestedWithin: 'span' })
)
);
const sections = splitUsing(childObjects, (child) =>
types.some(
(type) =>
isMdxType(child, type) ||
isMdxType(child, type, { nestedWithin: 'span' })
)
).map((section) =>
splitWhen(section, (child) =>
types.some(
(type) =>
isMdxType(child, type) ||
isMdxType(child, type, { nestedWithin: 'span' })
)
)
);
const pageLayout = usePageLayout();
return (
<div
css={css`
display: grid;
grid-template-columns: repeat(2, calc(50% - 0.5rem));
grid-gap: 1rem;
p:last-child {
margin-bottom: 0;
}
@media (max-width: ${BREAKPOINTS[pageLayout]}) {
grid-template-columns: minmax(0, 1fr);
}
`}
className={className}
>
{sections.map(([left, right], idx) => (
<Fragment key={idx}>
<div
css={
!rendersRightColumn &&
css`
grid-column: span 2;
`
}
>
{left}
</div>
{rendersRightColumn && <div>{right}</div>}
</Fragment>
))}
</div>
);
};
SideBySide.propTypes = {
children: PropTypes.node.isRequired,
type: PropTypes.oneOfType([
PropTypes.string,
PropTypes.arrayOf(PropTypes.string),
]).isRequired,
className: PropTypes.string,
};
export default SideBySide;
|
JavaScript
|
CL
|
1fc3536609e16872a370e3ea0ccd3e0e4de32ba87ad1c279c4c61162b01167ff
|
/*!
* async-exec-cmd <https://github.com/tunnckoCore/async-exec-cmd>
*
* Copyright (c) 2015 Charlike Mike Reagent, contributors.
* Released under the MIT license.
*/
/* jshint asi:true */
'use strict'
var test = require('assertit')
var cmd = require('./index')
test('should throw when only function is given', function (done) {
function fixture () {
cmd(function _cb (err) {
/* istanbul ignore next */
err = err || ''
})
}
test.throws(fixture, Error)
done()
})
test('should throw "should have `callback` (non empty callback)"', function () {
test('when only object is given', function (done) {
function fixture () {
cmd({stdio: 'inherit'})
}
test.throws(fixture, Error)
done()
})
test('when array is given', function (done) {
function fixture () {
cmd(['--save', 'bluebird'])
}
test.throws(fixture, Error)
done()
})
test('when array and object are given', function (done) {
function fixture () {
cmd(['--save', 'bluebird'], {stdio: 'inherit'})
}
test.throws(fixture, Error)
done()
})
test('when callback with empty body', function (done) {
function fixture () {
cmd('npm install --save is-glob', function _cb () {})
}
test.throws(fixture, Error)
done()
})
})
test('should have Error in callback', function () {
test('when process could not be spawned', function (done) {
cmd('jkdshfkj4hkjh435', function _cb (err) {
test.ok(err instanceof Error)
done()
})
})
})
test('should have TypeError in callback', function () {
test('when object and callback given', function (done) {
cmd({stdio: 'inherit'}, function _cb (err) {
test.ok(err instanceof TypeError)
done()
})
})
test('when array and callback are given', function (done) {
cmd(['--save', 'bluebird'], function _cb (err) {
test.ok(err instanceof TypeError)
done()
})
})
test('when array, object and callback are given', function (done) {
cmd(['--save', 'bluebird'], {stdio: 'inherit'}, function _cb (err) {
test.ok(err instanceof TypeError)
done()
})
})
test('when object, array and callback are given', function (done) {
cmd({stdio: 'inherit'}, ['--save', 'bluebird'], function _cb (err) {
test.ok(err instanceof TypeError)
done()
})
})
})
test('should return `stream` and have `.kill` method when executed', function (done) {
var cp = cmd('npm version', function _cb (err) {
/* istanbul ignore next */
err = err || ''
})
test.equal(typeof cp.kill, 'function')
done()
})
test('should have empty res and err null when opts.stdio is inherit', function (done) {
cmd('npm install --save is-glob', {stdio: 'inherit'}, function _cb (err, res, code) {
test.equal(err, null)
test.equal(code, 0) // status code
test.equal(typeof res, 'string') // response
test.equal(res.length, 0)
done()
})
})
function cmdErrorTest (err, res, code, buf, done) {
test.equal(res, undefined)
test.equal(buf, undefined)
test.equal(code, 1)
test.equal(err.status, 1)
test.equal(err.name, 'CommandError')
done()
}
test('should have CommandError in callback when', function () {
test('asyncExecCmd("npm", cb)', function (done) {
cmd('npm', function _cb (err, res, code, buf) {
cmdErrorTest(err, res, code, buf, done)
})
})
test('asyncExecCmd("npm", opts, cb)', function (done) {
cmd('npm', {stdio: [null, null, null]}, function _cb (err, res, code, buf) {
cmdErrorTest(err, res, code, buf, done)
})
})
})
test('should accept single command and arguments in array', function () {
test("asyncExecCmd('npm', ['i', '--save', 'is-glob'], cb)", function (done) {
cmd('npm', ['install', '--save', 'is-glob'],
function _cb (err, res, code) {
test.equal(err, null)
test.equal(code, 0)
test.equal(typeof res, 'string')
test.ok(res.length > 0)
done()
})
})
test("asyncExecCmd('npm', ['uni', '--save', 'is-glob'], opts, cb)", function (done) {
cmd('npm', ['uninstall', '--save', 'is-glob'], {stdio: [null, null, null]},
function _cb (err, res, code) {
test.equal(err, null)
test.equal(code, 0)
test.equal(typeof res, 'string')
test.ok(res.length > 0)
done()
})
})
})
test('should accept multiple words in `cmd` and `args` in array', function () {
test('should recieve CommandError if unknown subcommand given', function (done) {
cmd('npm unknown', function _cb (err, res, code, buffer) {
test.equal(res, undefined)
test.equal(buffer, undefined)
test.equal(code, 1)
test.equal(err.status, 1)
test.equal(err.name, 'CommandError')
done()
})
})
test('should work when asyncExecCmd("npm install", ["node-foo", "node-bar"], opts, cb)', function (done) {
var opts = {stdio: [null, null, null]}
var args = ['node-foo', 'node-bar']
cmd('npm install', args, opts, function _cb (err, res, code) {
test.equal(err, null)
test.equal(code, 0)
test.equal(typeof res, 'string')
test.ok(res.length > 0)
done()
})
})
})
|
JavaScript
|
CL
|
bd98f1b07be30c2c02f217a7557c62bcea6c10c1e89144a2e446b64fa0e894e2
|
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Vuex from 'vuex'
import store from './store'
import { Toast, Loading } from 'vant'
import axios from '~common/assets/js/axios'
import queens from 'queens-unipus'
import 'queens-unipus/lib/index.css'
import './assets/style/default.css'
import '~common/assets/css/default.css'
// import VConsole from 'vconsole'
// const Tool = new VConsole()
// Vue.prototype.$vconsole = Tool
if (process.env.NODE_ENV !== 'production') {
require('./mockData/mockData.js')
}
Vue.use(Toast)
Vue.use(Loading)
Vue.use(queens)
Vue.use(Vuex)
Vue.config.productionTip = false
Vue.prototype.$axios = axios
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
|
JavaScript
|
CL
|
fce14283158be2c3d00df8bc4f4444fe82d71c9251a75070577e8fdc7832dbc3
|
({
doInit : function(component, event, helper) {
try
{
var isFlow = component.get("v.isFlow");
var objectDataMap = component.get("v.objectDataMap");
helper.doInitMethodApex(component,event,helper); //both setup and maintenance
//END francesca.ribezzi 16/07/19
if(isFlow){
//START francesca.ribezzi 16/07/19 adding addressMapping to set isMaintenance value - performance merge:
var addressMapping = JSON.stringify(component.get("v.addressMapping"));
var addressMappingObj = JSON.parse(addressMapping);
if(!$A.util.isEmpty(addressMappingObj.isMaintenance)){
var isTrueSet = (addressMappingObj.isMaintenance == 'true');
component.set('v.isMaintenance',isTrueSet);
}
console.log("addressMapping: " +JSON.stringify(component.get("v.addressMapping")));
// START - 2019/05/14 - salvatore.pianura - Sostituzione Terminale
var listOfId = component.get("v.objectDataMap.TerminalIdsChanged");
component.set("v.listOfTerminalIdAvaiable",listOfId);
// END - 2019/05/14 - salvatore.pianura - Sostituzione Terminale
// Daniele Gandini <daniele.gandini@accenture.com> - 22/05/2019 - TerminalsReplacement - START
var isReplacement = component.get("v.objectDataMap.isReplacement");
component.set("v.isReplacement", isReplacement);
console.log("isreplacement tech details? " + isReplacement);
// Daniele Gandini <daniele.gandini@accenture.com> - 22/05/2019 - TerminalsReplacement - END
/*SIMONE MISANI 08/03/2019*/
/*var yearConstitutionCompanyNull = $A.util.isEmpty(objectDataMap.merchant.OB_Year_constitution_company__c);
if(yearConstitutionCompanyNull) {
component.set("v.objectDataMap.merchant.OB_Year_constitution_company__c", null);
}*/
// Daniele Gandini <daniele.gandini@accenture.com> - 19/06/2019 - Logic for maintenance remove case - START
helper.checkProfileLoggedUser_helper(component, event, helper);
helper.offerModify_Helper(component, event, helper);
// Daniele Gandini <daniele.gandini@accenture.com> - 19/06/2019 - Logic for maintenance remove case - END
}
var isMaintenance = component.get("v.isMaintenance");
console.log("isMaintenance: " + isMaintenance);
//27/07/19 francesca.ribezzi removinf block code from here -> going into doInitMethodApex
// Daniele Gandini <daniele.gandini@accenture.com> - 17/05/2019 - TerminalsReplacement - START
if(isReplacement){
objectDataMap.confirmOperationalData=true;
component.set("v.objectDataMap",objectDataMap);
var listOfId = component.get("v.objectDataMap.TerminalIdsChanged");
component.set("v.listOfTerminalIdAvaiable",listOfId);
helper.checkProfileLoggedUser_helper(component, event, helper);
helper.populateMapForTerminalId_Helper(component, event, helper);
helper.retrieveSiaCodes_Helper(component, event, helper);
var operationalDataToHide = component.find("confirmOperationaDataId");
$A.util.addClass(operationalDataToHide, 'slds-hide');
console.log('isFlow: ' + isFlow + 'isMaintenance: ' + isMaintenance);
console.log("objectDataMap.itemsInRemove:" + JSON.stringify(component.get("v.objectDataMap.itemsInRemove")));
}
// Daniele Gandini <daniele.gandini@accenture.com> - 17/05/2019 - TerminalsReplacement - END
//START francesca.ribezzi 09/07/19 call createFakeContextOutput everytime
var orderId = component.get("v.orderId");
if($A.util.isEmpty(orderId)){
orderId = objectDataMap.Configuration.Id;
}
component.set("v.orderId",orderId);
if(isMaintenance){
//start antonio.vatrano 12/06/2019 r1f2-247
var businessModel = (component.get('v.objectDataMap.bankProfile.OB_Business_Model_Acquiring__c') == 'Bancario')? true : false;
var gt = (component.get('v.objectDataMap.bankProfile.OB_GT__c') == 'Nexi') ? true : false;
var applicantNEXI = (component.get('v.objectDataMap.bankProfile.OB_Applicant_RAC_Code_SIA__c') == 'Nexi') ? true : false;
var applicantBANCA = (component.get('v.objectDataMap.bankProfile.OB_Applicant_RAC_Code_SIA__c') != 'Nexi') ? true : false;
var conditionBanca = businessModel && gt && applicantBANCA ;
var conditionNexi = applicantNEXI;
component.set('v.conditionBanca',conditionBanca);
component.set('v.conditionNexi',conditionNexi);
//End antonio.vatrano 12/06/2019 r1f2-247
helper.currentUse(component, event, helper);// simone misani R1F2-115 15/05/2019
//D.F. _ Manage Rac Sia v4 _ START
component.set('v.isMaintenanceRac',true);
//francesca.ribezzi 26/07/19 deleting checkterminals
//D.F. _ END
}
//26/07/19 francesca.ribezzi moving this helper here
helper.getReportType(component,helper ,event ); //both setup and maintenance
// helper.splitOrderItemPOS(component,event);
//START francesca.ribezzi 11/07/19 call getOrderData and then createFakeContextOutput here instead of splitOrderItemPOS
helper.getOrderData(component,event,orderId);
} catch(err){
console.log('GENERIC_ERROR_DOINIT: ' + err.message );
}
},
//LUBRANO 16/01/2019 Libreria Log
logInit: function(component){
_utils.logInit(component.getName());
},
/*
*@author francesca.ribezzi
*@date 31/07/2019
*@task checkRedBorder - setting red border to empty required fields - WN-211
*@history 31/07/2019 Method created
*/
checkRedBorder: function(component, event, helper){
var input = event.target;
helper.handleRedBorderErrors(component,event, input);
},
//this is called when an attribute value is changed. it fires an event that calls onUpdateContext function:
onChangeAttributeValuePOS: function(component, event, helper){
//_utils.debug("into onChangeAttributeValuePOS");
var attributeIndex = JSON.stringify(event.target.id);
var listOfItems = component.get("v.posList");
var parentIndex = document.getElementById(event.target.id).name;
var pos1 = attributeIndex.indexOf("_")+1;
var length1 = attributeIndex.indexOf("_",pos1)-1;
var tempStr = attributeIndex.substr(length1);
//19/07/19 francesca.ribezzi - performance
var isMaintenance = component.get("v.isMaintenance");
attributeIndex = tempStr.substr(0,tempStr.indexOf('_'));//firstIndex+'_'+index+'_POS'
//RESET Error Message if updating terminal ID
var attName = document.getElementById(attributeIndex+'_attName').textContent;
var itemToUpdate = listOfItems[parentIndex];
var errMsg= document.getElementById(event.target.id+'_Error');
var contextOutput = component.get("v.contextOutput");
itemToUpdate.listOfAttributes[attributeIndex].fields.value = event.target.value;
//START francesca.ribezzi 18/07/19 chaning action - performance
var newValue = itemToUpdate.listOfAttributes[attributeIndex].fields.value;
var oldValue = itemToUpdate.listOfAttributes[attributeIndex].fields.Old_Value__c;
//francesca.ribezzi 04/09/19 - wn-349 - adding check on action:
var enAction = itemToUpdate.childItems[attributeIndex].fields.action;
if(isMaintenance){
if(newValue != oldValue && enAction == 'None'){
itemToUpdate.listOfAttributes[attributeIndex].fields.NE__Action__c = 'Change';
itemToUpdate.listOfAttributes[attributeIndex].fields.action = 'Change';
//START francesca.ribezzi 03/09/19- WN-3128 - changing childItem's action as well
itemToUpdate.fields.NE__Action__c = 'Change';
itemToUpdate.fields.action = 'Change';
//END francesca.ribezzi 03/09/19 - WN-3128
}
if($A.util.isEmpty(oldValue)){
oldValue = newValue;
}
}
//END francesca.ribezzi 18/07/19
//START francesca.ribezzi 31/07/19 - WN-211
var name = itemToUpdate.listOfAttributes[attributeIndex].fields.name;
var setRequiredToAll = 'Yes';
if(name == 'APP' || name == 'URL' || name == 'Paymail'){
if(!$A.util.isEmpty(newValue)){
setRequiredToAll = 'No';
}
}
for(var i = 0; i < itemToUpdate.listOfAttributes.length;i++){
var name = itemToUpdate.listOfAttributes[i].fields.name;
if(name == 'APP' || name == 'URL' || name == 'Paymail'){
//obj[name] = value;
itemToUpdate.listOfAttributes[i].fields.required = setRequiredToAll;
}
}
//END francesca.ribezzi 31/07/19 - WN-211
//francesca.ribezzi - removing error class from input:
component.set("v.itemToUpdate", itemToUpdate);
//francesca.ribezzi 08/07/19 setting posList as not calling onUpdateContext anymore
component.set("v.posList", listOfItems);
errMsg.innerHTML = '';
// francesca.ribezzi 01/08/19 setting red border to empty required fields - WN-211
// helper.handleRedBorderErrors(component,event);
},
onChangeAttributeValuePOSPickList: function(component, event, helper){
//_utils.debug("into onChangeAttributeValuePOSPicklist")
var listOfItems = component.get("v.posList");
//LUBRANO -- 2019/02/23 gestione attribute/parent index index
var attributeIndex = event.getSource().get("v.name"); //11/07/19 francesca.ribezzi getting attribute with event.getSource - api version
attributeIndex = attributeIndex.replace(/"\""/g, "");
//var attributeIndex = JSON.stringify(event.target.name);
//_utils.debug("attributeIndex: " + attributeIndex);
var indexArray = attributeIndex.split('_');
var parentIndex = indexArray[0];
attributeIndex = indexArray[1];
var itemToUpdate = listOfItems[parseInt(parentIndex)];
var contextOutput = component.get("v.contextOutput");
//19/07/19 francesca.ribezzi - performance
var isMaintenance = component.get("v.isMaintenance");
itemToUpdate.listOfAttributes[attributeIndex].fields.value = event.getSource().get("v.value"); //11/07/19 francesca.ribezzi getting value with event.getSource - api version
////_utils.debug("attribute changed: " +itemToUpdate.listOfAttributes[attributeIndex] );
//START francesca.ribezzi 18/07/19 chaning action - performance
var newValue = itemToUpdate.listOfAttributes[attributeIndex].fields.value;
var oldValue = itemToUpdate.listOfAttributes[attributeIndex].fields.Old_Value__c;
//francesca.ribezzi 04/09/19 - wn-349 - adding check on action:
var enAction = itemToUpdate.listOfAttributes[attributeIndex].fields.action;
if(isMaintenance){
if(newValue != oldValue && enAction == 'None'){
itemToUpdate.listOfAttributes[attributeIndex].fields.NE__Action__c = 'Change';
itemToUpdate.listOfAttributes[attributeIndex].fields.action = 'Change';
//START francesca.ribezzi 03/09/19- WN-3128 - changing childItem's action as well
itemToUpdate.fields.NE__Action__c = 'Change';
itemToUpdate.fields.action = 'Change';
//END francesca.ribezzi 03/09/19 - WN-3128
}
if($A.util.isEmpty(oldValue)){
oldValue = newValue;
}
}
//END francesca.ribezzi 18/07/19
if(itemToUpdate.listOfAttributes[attributeIndex].fields.name == 'SimCard'){
//francesca.ribezzi 04/09/19 - WN-349 - adding this node in order to insert simcard order item
itemToUpdate.listOfAttributes[attributeIndex].fields.rootOrderItem = itemToUpdate.fields.id;
itemToUpdate.listOfAttributes[attributeIndex].fields.Old_Value__c = newValue; //gianluigi.virga 04/11/2019 - PRODOB-526
}
//START francesca.ribezzi 31/07/19 - WN-211
var name = itemToUpdate.listOfAttributes[attributeIndex].fields.name;
var setRequiredToAll = 'Yes';
if(name == 'APP' || name == 'URL' || name == 'Paymail'){
if(!$A.util.isEmpty(newValue)){
setRequiredToAll = 'No';
}
}
for(var i = 0; i < itemToUpdate.listOfAttributes.length;i++){
var name = itemToUpdate.listOfAttributes[i].fields.name;
if(name == 'APP' || name == 'URL' || name == 'Paymail'){
//obj[name] = value;
itemToUpdate.listOfAttributes[i].fields.required = setRequiredToAll;
}
}
//END francesca.ribezzi 31/07/19 - WN-211
component.set("v.itemToUpdate", itemToUpdate);
component.set("v.isEnd",false);
//itemToUpdate.childItems[attributeIndex].fields.OB_enablement__c = status;
//francesca.ribezzi 08/07/19 setting listOfItems as not calling onUpdateContext anymore
component.set("v.posList", listOfItems);
component.set("v.configurePicklist",true);
component.set("v.needConfig",true);
// francesca.ribezzi 01/08/19 setting red border to empty required fields - WN-211
//helper.handleRedBorderErrors(component,event);
//START gianluigi.virga 25/07/2019 - PRODOB-161
if(itemToUpdate.listOfAttributes[attributeIndex].fields.name == $A.get("$Label.c.OB_SimCard")){
if((itemToUpdate.listOfAttributes[attributeIndex].fields.action != $A.get("$Label.c.OB_ActionNone") && itemToUpdate.listOfAttributes[attributeIndex].fields.value != null && itemToUpdate.listOfAttributes[attributeIndex].fields.value != undefined && itemToUpdate.listOfAttributes[attributeIndex].fields.value != '')
|| (itemToUpdate.listOfAttributes[attributeIndex].fields.action == $A.get("$Label.c.OB_ActionNone"))){
itemToUpdate.listOfAttributes[attributeIndex].fields.simCardIsValid = true;
}else{
itemToUpdate.listOfAttributes[attributeIndex].fields.simCardIsValid = false;
}
}
if(itemToUpdate.listOfAttributes[attributeIndex].fields.name == $A.get("$Label.c.OB_Property")){
if((itemToUpdate.listOfAttributes[attributeIndex].fields.action != $A.get("$Label.c.OB_ActionNone") && itemToUpdate.listOfAttributes[attributeIndex].fields.value != null && itemToUpdate.listOfAttributes[attributeIndex].fields.value != undefined && itemToUpdate.listOfAttributes[attributeIndex].fields.value != '')
|| (itemToUpdate.listOfAttributes[attributeIndex].fields.action == $A.get("$Label.c.OB_ActionNone"))){
itemToUpdate.listOfAttributes[attributeIndex].fields.thirdPartyPropertyIsValid = true;
}else{
itemToUpdate.listOfAttributes[attributeIndex].fields.thirdPartyPropertyIsValid = false;
}
}
//END gianluigi.virga 25/07/2019 - PRODOB-161
},
onChangeItemValuePOS: function(component, event, helper){
//_utils.debug("into onChangeItemValuePOS");
var attributeIndex = event.target.id;
var listOfItems = component.get("v.posList");
var itemToUpdate = listOfItems[parseInt(attributeIndex)];
var contextOutput = component.get("v.contextOutput");
itemToUpdate.fields.OB_Description__c = event.srcElement.value;
component.set("v.itemToUpdate", itemToUpdate);
////_utils.debug("itemToUpdate: ",itemToUpdate);
//francesca.ribezzi 08/07/19 setting listOfItems as not calling onUpdateContext anymore
component.set("v.posList", listOfItems);
},
onCheck: function(component, event, helper){
//_utils.debug("into onCheck");
//
component.set("v.isEnd",false);
//09/07/19 francesca.ribezzi using event.getSource().get("v.id") instead of event.target.id -> not working here
var attributeIndex = JSON.stringify(event.getSource().get("v.id"));
var listOfItems = component.get("v.posList");
// var parentIndex = document.getElementById(event.target.id).name;
//var parentIndex = event.currentTarget.getAttribute('data-item');
var parentIndex = attributeIndex.substr(1, attributeIndex.indexOf('_')-1);
//_utils.debug("parentIndex: " + parentIndex);
var acq1 = attributeIndex.indexOf("_")+1;
var length1 = attributeIndex.indexOf("_",acq1)-1;
var tempStr = attributeIndex.substr(length1);
attributeIndex = tempStr.substr(0,tempStr.indexOf('_'));
// attributeIndex = parseInt(attributeIndex.split('_').pop());
//_utils.debug("attributeIndex "+attributeIndex);
var itemToUpdate = listOfItems[parseInt(parentIndex)];
var contextOutput = component.get("v.contextOutput");
//_utils.debug("itemToUpdate ",itemToUpdate);
var status;
//09/07/19 francesca.ribezzi using event.getSource().get("v.checked") : event.target.checked not working here
if(event.getSource().get("v.checked")){
status = "Y";
}
else{
status = "N";
}
//francesca.ribezzi 10/07/19 setting enablement on childItem:
itemToUpdate.childItems[attributeIndex].fields.OB_enablement__c = status;
//START 19/07/19 francesca.ribezzi - performance
var isMaintenance = component.get("v.isMaintenance");
var oldEnablement = itemToUpdate.childItems[attributeIndex].fields.OB_Old_Enablement__c;
var newEnablement = itemToUpdate.childItems[attributeIndex].fields.OB_enablement__c;
//END 19/07/19 francesca.ribezzi
//START francesca.ribezzi 31/07/19 - WN-228
var enAction = itemToUpdate.childItems[attributeIndex].fields.action;
if(oldEnablement != newEnablement && enAction == 'None'){
itemToUpdate.childItems[attributeIndex].fields.NE__Action__c = 'Change';
itemToUpdate.childItems[attributeIndex].fields.action = 'Change';
}//26/08/19 francesca.ribezzi - WN-284 - if action is add, do not change it
if($A.util.isEmpty(oldEnablement)){
oldEnablement = newEnablement;
}
//END francesca.ribezzi 31/07/19 - WN-228
component.set("v.itemChildCheck",status);
component.set("v.itemChildToUpdate",itemToUpdate.childItems[attributeIndex]);
component.set("v.itemToUpdate", itemToUpdate);
////_utils.debug("itemToUpdate: ",itemToUpdate);
//francesca.ribezzi 08/07/19 setting listOfItems as not calling onUpdateContext anymore
component.set("v.posList", listOfItems);
component.set("v.needConfig",true);
},
//this is called when an attribute value is changed. it fires an event that calls onUpdateContext function:
onChangeAttributeValueBancomat: function(component, event, helper){
//_utils.debug("into onChangeAttributeValueBancomat");
var attributeIndex = JSON.stringify(event.target.id);
var listOfItems = component.get("v.bancomatList");
var parentIndex = document.getElementById(event.target.id).name;
var Bancomat1 = attributeIndex.indexOf("_")+1;
var length1 = attributeIndex.indexOf("_",Bancomat1)-1;
var tempStr = attributeIndex.substr(length1);
attributeIndex = tempStr.substr(0,tempStr.indexOf('_'));//firstIndex+'_'+index+'_Bancomat'
var errMsg = document.getElementById(event.target.id+'Error');
//19/07/19 francesca.ribezzi - performance
var isMaintenance = component.get("v.isMaintenance");
var itemToUpdate = listOfItems[parentIndex];
var inputNumNameMap = {};
//francesca.ribezzi - creating map to check the correct input value length for each field:
inputNumNameMap['Codice SIA'] = 7;
inputNumNameMap['Codice Stabilimento SIA'] = 5;
inputNumNameMap['Progressivo SIA'] = 3;
if(itemToUpdate != null){
var contextOutput = component.get("v.contextOutput");
itemToUpdate.listOfAttributes[attributeIndex].fields.value = event.target.value;
////_utils.debug("attribute changed: " +itemToUpdate.listOfAttributes[attributeIndex] );
var inputValue = event.target.value;
//match the regex /^[0-9]+$/
if(/^[0-9]+$/.test(event.target.value)){
var nameToCheck = itemToUpdate.listOfAttributes[attributeIndex].fields.name;
if(inputValue.length == inputNumNameMap[nameToCheck]){
document.getElementById(event.target.id).classList.remove("borderError");
itemToUpdate.listOfAttributes[attributeIndex].fields.value = event.target.value;
//START francesca.ribezzi 18/07/19 chaning action - performance
var newValue = itemToUpdate.listOfAttributes[attributeIndex].fields.value;
var oldValue = itemToUpdate.listOfAttributes[attributeIndex].fields.Old_Value__c;
//francesca.ribezzi 04/09/19 - wn-349 - adding check on action:
var enAction = itemToUpdate.listOfAttributes[attributeIndex].fields.action;
if(isMaintenance){
if(newValue != oldValue && enAction == 'None'){
itemToUpdate.listOfAttributes[attributeIndex].fields.NE__Action__c = 'Change';
itemToUpdate.listOfAttributes[attributeIndex].fields.action = 'Change';
//START francesca.ribezzi 03/09/19- WN-3128 - changing childItem's action as well
itemToUpdate.fields.NE__Action__c = 'Change';
itemToUpdate.fields.action = 'Change';
//END francesca.ribezzi 03/09/19 - WN-3128
}
if($A.util.isEmpty(oldValue)){
oldValue = newValue;
}
}
//END francesca.ribezzi 18/07/19
component.set("v.itemToUpdate", itemToUpdate);
//_utils.debug("itemToUpdate: ",itemToUpdate);
errMsg.innerHTML = '';
}else{
if(inputValue.length == 0){
errMsg.innerHTML = '';
document.getElementById(event.target.id).classList.remove("borderError");
}else{
errMsg.innerHTML = $A.get("$Label.c.OB_invalidValue");
document.getElementById(event.target.id).classList.add("borderError");
}
}
}
else{
//show error message!!!
errMsg.innerHTML = $A.get("$Label.c.OB_invalidValue");
event.target.value = '';
document.getElementById(event.target.id).classList.add("borderError");
}
//francesca.ribezzi 08/07/19 setting contextOutput as not calling onUpdateContext anymore
component.set("v.bancomatList", listOfItems);
}
},
onChangeAttributeValueBancomatPickList: function(component, event, helper){
//_utils.debug("into onChangeAttributeValueBancomatPicklist")
var listOfItems = component.get("v.bancomatList");
var attributeIndex = JSON.stringify(event.target.name);
//_utils.debug("attributeIndex: " + attributeIndex);
var parentIndex = attributeIndex.substring(1, attributeIndex.indexOf('_'));
var bancomat1 = attributeIndex.indexOf("_")+1;
var length1 = attributeIndex.indexOf("_", bancomat1)-1;
var tempStr = attributeIndex.substr(length1);
attributeIndex = tempStr.substr(0,tempStr.indexOf('_'));
//attributeIndex = parseInt(attributeIndex.split('_').pop());
//19/07/19 francesca.ribezzi - performance
var isMaintenance = component.get("v.isMaintenance");
var itemToUpdate = listOfItems[parseInt(parentIndex)];
var contextOutput = component.get("v.contextOutput");
itemToUpdate.listOfAttributes[attributeIndex].fields.value = event.target.value;
////_utils.debug("attribute changed: " +itemToUpdate.listOfAttributes[attributeIndex] );
//START francesca.ribezzi 18/07/19 chaning action - performance
var newValue = itemToUpdate.listOfAttributes[attributeIndex].fields.value;
var oldValue = itemToUpdate.listOfAttributes[attributeIndex].fields.Old_Value__c;
//francesca.ribezzi 04/09/19 - wn-349 - adding check on action:
var enAction = itemToUpdate.listOfAttributes[attributeIndex].fields.action;
if(isMaintenance){
if(newValue != oldValue && enAction == 'None'){
itemToUpdate.listOfAttributes[attributeIndex].fields.NE__Action__c = 'Change';
itemToUpdate.listOfAttributes[attributeIndex].fields.action = 'Change';
//START francesca.ribezzi 03/09/19- WN-3128 - changing childItem's action as well
itemToUpdate.fields.NE__Action__c = 'Change';
itemToUpdate.fields.action = 'Change';
//END francesca.ribezzi 03/09/19 - WN-3128
}
if($A.util.isEmpty(oldValue)){
oldValue = newValue;
}
}
//END francesca.ribezzi 18/07/19
component.set("v.itemToUpdate", itemToUpdate);
// //_utils.debug("itemToUpdate: ",itemToUpdate);
//francesca.ribezzi 08/07/19 setting bancomatList as not calling onUpdateContext anymore
component.set("v.bancomatList", listOfItems);
},
//this is called when an attribute value is changed. it fires an event that calls onUpdateContext function:
onChangeAttributeValueACQ: function(component, event, helper){
//_utils.debug("into onChangeAttributeValueACQ")
var attributeIndex = JSON.stringify(event.target.id);
//_utils.debug("attributeIndex: " + attributeIndex);
var listOfItems = component.get("v.acquiringList");
var parentIndex = document.getElementById(event.target.id).name;
var acq1 = attributeIndex.indexOf("_")+1;
var length1 = attributeIndex.indexOf("_",acq1)-1;
var tempStr = attributeIndex.substr(length1);
attributeIndex = tempStr.substr(0,tempStr.indexOf('_'));
var itemToUpdate = listOfItems[parentIndex];
var errMsg= document.getElementById(event.target.id+'_Error');
if(itemToUpdate != null){
var contextOutput = component.get("v.contextOutput");
itemToUpdate.listOfAttributes[attributeIndex].fields.value = event.target.value;
var attName = itemToUpdate.listOfAttributes[attributeIndex].fields.name;
//match the regex
if(/^[0-9]*([,][0-9]{1,3}|)$/.test(event.target.value)){
if(attName == 'Codice Convenzione'){
if(event.target.value.length != 10 && event.target.value.length != 0){
document.getElementById(event.target.id).classList.add("borderError");
errMsg.innerHTML = $A.get("$Label.c.OB_TenCharsError");
}else{
errMsg.innerHTML = '';
document.getElementById(event.target.id).classList.remove("borderError");
component.set("v.itemToUpdate", itemToUpdate);
//_utils.debug("itemToUpdate: ",itemToUpdate);
}
}else{
document.getElementById(event.target.id).classList.remove("borderError");
errMsg.innerHTML = '';
component.set("v.itemToUpdate", itemToUpdate);
//_utils.debug("itemToUpdate: ",itemToUpdate);
}
}
else{
event.target.value = '';
errMsg.innerHTML = $A.get("$Label.c.OB_invalidValue");
document.getElementById(event.target.id).classList.add("borderError");
}
//francesca.ribezzi 08/07/19 setting acquiringList as not calling onUpdateContext anymore
component.set("v.acquiringList", listOfItems);
}
},
onChangeAttributeValueVAS: function(component, event, helper){
//_utils.debug("into onChangeAttributeValueVAS");
var attributeIndex = JSON.stringify(event.target.id);
var listOfItems = component.get("v.vasList");
var parentIndex = document.getElementById(event.target.id).name;
var vas1 = attributeIndex.indexOf("_")+1;
var length1 = attributeIndex.indexOf("_",vas1)-1;
var tempStr = attributeIndex.substr(length1);
attributeIndex = tempStr.substr(0,tempStr.indexOf('_'));//firstIndex+'_'+index+'_VAS'
var errMsg = document.getElementById(event.target.id+'Error');
var itemToUpdate = listOfItems[parentIndex];
//19/07/19 francesca.ribezzi - performance
var isMaintenance = component.get("v.isMaintenance");
if(itemToUpdate != null){
var contextOutput = component.get("v.contextOutput");
itemToUpdate.listOfAttributes[attributeIndex].fields.value = event.target.value;
////_utils.debug("attribute changed: " +itemToUpdate.listOfAttributes[attributeIndex] );
if(/^[0-9]*([,][0-9]{1,3}|)$/.test(event.target.value)){
//START francesca.ribezzi 18/07/19 chaning action - performance
var newValue = itemToUpdate.listOfAttributes[attributeIndex].fields.value;
var oldValue = itemToUpdate.listOfAttributes[attributeIndex].fields.Old_Value__c;
//francesca.ribezzi 04/09/19 - wn-349 - adding check on action:
var enAction = itemToUpdate.listOfAttributes[attributeIndex].fields.action;
if(isMaintenance){
if(newValue != oldValue && enAction == 'None'){
itemToUpdate.listOfAttributes[attributeIndex].fields.NE__Action__c = 'Change';
itemToUpdate.listOfAttributes[attributeIndex].fields.NE__Action__c = 'Change';
//START francesca.ribezzi 03/09/19- WN-3128 - changing childItem's action as well
itemToUpdate.fields.NE__Action__c = 'Change';
itemToUpdate.fields.action = 'Change';
//END francesca.ribezzi 03/09/19 - WN-3128
}
if($A.util.isEmpty(oldValue)){
oldValue = newValue;
}
}
//END francesca.ribezzi 18/07/19
//francesca.ribezzi - removing error class from input:
errMsg.innerHTML = '';
var inputValue = event.target.value;
if(inputValue.length > 0){
document.getElementById(event.target.id).classList.remove("borderError");
}
//START francesca.ribezzi 18/07/19 chaning action - performance
var newValue = itemToUpdate.listOfAttributes[attributeIndex].fields.value;
var oldValue = itemToUpdate.listOfAttributes[attributeIndex].fields.Old_Value__c;
//francesca.ribezzi 04/09/19 - wn-349 - adding check on action:
var enAction = itemToUpdate.listOfAttributes[attributeIndex].fields.action;
if(isMaintenance){
if(newValue != oldValue && enAction == 'None'){
itemToUpdate.listOfAttributes[attributeIndex].fields.NE__Action__c = 'Change';
itemToUpdate.listOfAttributes[attributeIndex].fields.NE__Action__c = 'Change';
//START francesca.ribezzi 03/09/19- WN-3128 - changing childItem's action as well
itemToUpdate.fields.NE__Action__c = 'Change';
itemToUpdate.fields.action = 'Change';
//END francesca.ribezzi 03/09/19 - WN-3128
}
if($A.util.isEmpty(oldValue)){
oldValue = newValue;
}
}
//END francesca.ribezzi 18/07/19
component.set("v.itemToUpdate", itemToUpdate);
//_utils.debug("itemToUpdate: ",itemToUpdate);
}
else{
errMsg.innerHTML = 'Enter a valid value.';
event.target.value = '';
document.getElementById(event.target.id).classList.add("borderError");
}
//francesca.ribezzi 08/07/19 setting vasList as not calling onUpdateContext anymore
component.set("v.vasList", listOfItems);
}
//component.set("v.itemToUpdate", itemToUpdate);
},
onChangeAttributeValueVASPickList: function(component, event, helper){
//_utils.debug("into onChangeAttributeValueVASPicklist")
var listOfItems = component.get("v.vasList");
var attributeIndex = JSON.stringify(event.target.name);
//_utils.debug("attributeIndex: " + attributeIndex);
var parentIndex = attributeIndex.substring(1, attributeIndex.indexOf('_'));
var vas1 = attributeIndex.indexOf("_")+1;
var length1 = attributeIndex.indexOf("_", vas1)-1;
var tempStr = attributeIndex.substr(length1);
attributeIndex = tempStr.substr(0,tempStr.indexOf('_'));
//attributeIndex = parseInt(attributeIndex.split('_').pop());
var itemToUpdate = listOfItems[parseInt(parentIndex)];
var contextOutput = component.get("v.contextOutput");
//19/07/19 francesca.ribezzi - performance
var isMaintenance = component.get("v.isMaintenance");
itemToUpdate.listOfAttributes[attributeIndex].fields.value = event.target.value;
//START francesca.ribezzi 18/07/19 chaning action - performance
var newValue = itemToUpdate.listOfAttributes[attributeIndex].fields.value;
var oldValue = itemToUpdate.listOfAttributes[attributeIndex].fields.Old_Value__c;
//francesca.ribezzi 04/09/19 - wn-349 - adding check on action:
var enAction = itemToUpdate.listOfAttributes[attributeIndex].fields.action;
if(isMaintenance){
if(newValue != oldValue && enAction == 'None'){
itemToUpdate.listOfAttributes[attributeIndex].fields.NE__Action__c = 'Change';
itemToUpdate.listOfAttributes[attributeIndex].fields.action = 'Change';
//START francesca.ribezzi 03/09/19- WN-3128 - changing childItem's action as well
itemToUpdate.fields.NE__Action__c = 'Change';
itemToUpdate.fields.action = 'Change';
//END francesca.ribezzi 03/09/19 - WN-3128
}
if($A.util.isEmpty(oldValue)){
oldValue = newValue;
}
}
//END francesca.ribezzi 18/07/19
////_utils.debug("attribute changed: " +itemToUpdate.listOfAttributes[attributeIndex] );
component.set("v.itemToUpdate", itemToUpdate);
// //_utils.debug("itemToUpdate: ",itemToUpdate);
//francesca.ribezzi 08/07/19 setting contextOutput as not calling onUpdateContext anymore
component.set("v.vasList", listOfItems);
},
doInitAfter: function(component, event, helper) {
console.log('INIT AFTER');
//console.log('call init:' + component.get('v.callInit'));
console.log("t0 doInitAfter: " + performance.now());
var t0 = performance.now();
var objectDataMap = component.get('v.objectDataMap');
// Daniele Gandini <daniele.gandini@accenture.com> - 19/06/2019 - Logic for maintenance remove case - START
helper.removeCase_Helper(component, event, helper);
// Daniele Gandini <daniele.gandini@accenture.com> - 19/06/2019 - Logic for maintenance remove case - END
console.log('@@@@ ObjectDatamap doinitafter: ' + JSON.stringify(objectDataMap));
var isNewVisaMastercard = component.get('v.isNewVisaMastercard');
try
{
//g.s. 14/02/2019 - if there is the OB_HeaderInternational__c , set it with merchant name - end
console.log('@@@@ Nel try del doInitAfter');
// DG - 14/02/2019 - 1341 - START
// Vars to have row time from timestamp
var opening = objectDataMap.pv.OB_Opening_Time__c/1000/3600;
var closing = objectDataMap.pv.OB_Ending_Time__c/1000/3600;
var breakStart = objectDataMap.pv.OB_Break_Start_Time__c/1000/3600;
var breakEnd = objectDataMap.pv.OB_Break_End_Time__c/1000/3600;
// Vars to have right time values
// OPENING
var openingHours = Math.floor(opening);
var openingMinutes = ((opening - (Math.floor(opening)))*60/100);
var openingTime = (openingHours + openingMinutes).toFixed(2);
// CLOSURE
var closingHours = Math.floor(closing);
var closingMinutes = ((closing - (Math.floor(closing)))*60/100);
var closingTime = (closingHours + closingMinutes).toFixed(2);
// BREAK START
var breakStartHours = Math.floor(breakStart);
var breakStartMinutes = ((breakStart - (Math.floor(breakStart)))*60/100);
var breakStartTime = (breakStartHours + breakStartMinutes).toFixed(2);
// BREAK END
var breakEndHours = Math.floor(breakEnd);
var breakEndMinutes = ((breakEnd - (Math.floor(breakEnd)))*60/100);
var breakEndTime = (breakEndHours + breakEndMinutes).toFixed(2);
if(objectDataMap.pv.OB_Opening_Time__c){
objectDataMap.pv.OB_Opening_Time__c = openingTime;
}
if(objectDataMap.pv.OB_Ending_Time__c){
objectDataMap.pv.OB_Ending_Time__c = closingTime;
}
if(objectDataMap.pv.OB_Break_Start_Time__c){
objectDataMap.pv.OB_Break_Start_Time__c = breakStartTime;
}
if(objectDataMap.pv.OB_Break_End_Time__c){
objectDataMap.pv.OB_Break_End_Time__c = breakEndTime;
}
// DG - 14/02/2019 - 1341 - END
/*console.log('objectDataMap.merchant.OB_Year_constitution_company__c BEFORE'+objectDataMap.merchant.OB_Year_constitution_company__c);
//SET YEAR OF CONSTITUTION
/* if( objectDataMap.merchant.OB_Year_constitution_company__c == undefined ||
objectDataMap.merchant.OB_Year_constitution_company__c == '' ||
objectDataMap.merchant.OB_Year_constitution_company__c == 0 ) {
console.log('sono nell if');
objectDataMap.merchant.OB_Year_constitution_company__c = null;
// component.set('v.objectDataMap.unbind.yearOfConstitutionCompany' ,'test');
}
// else{
// component.set('v.objectDataMap.unbind.yearOfConstitutionCompany' , objectDataMap.merchant.OB_Year_constitution_company__c);
// }
component.set('v.objectDataMap.unbind.yearOfConstitutionCompany' , objectDataMap.merchant.OB_Year_constitution_company__c);*/
//set value for rule at next step -->show/hide description vat not present
if(objectDataMap.merchant.OB_VAT_Not_Present__c==true){
//console.log('iNTO IF TRUE');
component.set( 'v.objectDataMap.unbind.VAT_notPresent_Main', 'true');
}else if(objectDataMap.merchant.OB_VAT_Not_Present__c==false){
//console.log('iNTO IF FALSE');
component.set( 'v.objectDataMap.unbind.VAT_notPresent_Main', 'false');
}
//set value for rule at next step-->manage no profit field
//IF LEGAL FORM IS NO PROFIT
if(objectDataMap.merchant.OB_Legal_Form_Code__c == 'ORG_NO_PROFIT')
{
component.set('v.objectDataMap.unbind.OB_Legal_Form_Main' , 'NOPROFIT');
if(objectDataMap.merchant.OB_No_Profit_Recipient_Class__c=='Altro'){
component.set('v.objectDataMap.unbind.OB_No_Profit_Recipient_Class__c','Altro');
}
}
// //console.log('OBJECT_DATA_MAP_DOINIT_UNBIND' + JSON.stringify(component.get('v.objectDataMap.unbind') ));
//********************IBAN SECTION - START ********************//
//valuate if there is a new visa/mastercard and JCB/UPI
var isNewPOS , isNewVisaMastercard , isNewJCB , isNewUPI , isPOSAtt_unatt;
for(var key in objectDataMap.orderItem)
{
// //console.log('KEy: ' + key);
// //console.log('NODE_IN_MAP: ' + JSON.stringify(objectDataMap.orderItem[key]));
for(var i=0; i<(objectDataMap.orderItem[key]).length; i++)
{
if(key == 'ACQUIRING' && objectDataMap.orderItem[key][i].NE__ProdId__r.OB_Codice_sfdc__c == 'VISAMASTERCARD' && objectDataMap.orderItem[key][i].NE__Action__c == 'Add') //davide.franzini - 14/06/2019 - R1F2-283
{
isNewVisaMastercard=true;
component.set('v.isNewVisaMastercard' , true);
}
if(key == 'ACQUIRING' && objectDataMap.orderItem[key][i].NE__ProdId__r.OB_Codice_sfdc__c == 'UPI' && objectDataMap.orderItem[key][i].NE__Action__c == 'Add') //davide.franzini - 14/06/2019 - R1F2-283
{
isNewUPI=true;
}
if(key == 'ACQUIRING' && objectDataMap.orderItem[key][i].NE__ProdId__r.OB_Codice_sfdc__c == 'JCB' && objectDataMap.orderItem[key][i].NE__Action__c == 'Add') //davide.franzini - 14/06/2019 - R1F2-283
{
isNewJCB=true;
}
if(key == 'POS' && objectDataMap.orderItem[key][i].NE__Action__c == 'Add') //davide.franzini - 14/06/2019 - R1F2-283
{
isNewPOS = true;
}
if(key == 'POS' && (objectDataMap.orderItem[key][i].NE__ProdId__r.OB_Codice_sfdc__c=='POS_TERZI_ATTENDED'|| objectDataMap.orderItem[key][i].NE__ProdId__r.OB_Codice_sfdc__c=='POS_TERZI_UNATTENDED'))
{
isPOSAtt_unatt=true;
}
}
}
var bankABI = $A.util.isUndefinedOrNull(component.get("v.objectDataMap.user.OB_ABI__c")) ? component.get("v.objectDataMap.bank.OB_ABI__c") :component.get("v.objectDataMap.user.OB_ABI__c"), ////START - elena.preteni 18/07/2019 F3 ABI CAB Selection missing nodes OB_ABI__c in user
CAB = component.get("v.objectDataMap.user.OB_CAB__c");
//16/07/19 francesca.ribezzi setting bankABI attribute to generate terminal id:
component.set('v.bankABI', bankABI);
//if there is an new POS, a new visa/mastercard and there isn't JCB or UPI show IBAN
if((isNewPOS==true || isNewVisaMastercard==true)/*&&(isNewUPI!=true || isNewJCB!=true )*/)
{
//console.log('SHOW_IBAN');
component.set('v.showIBANSection' , true);
component.find('headerInternational').set('v.disabled' , false);
}
//if there is a new POS attended or anattended show the preliminary verification code
if(isPOSAtt_unatt==true)
{
component.set('v.objectDataMap.prelimVerifCodeRO' , false);//DEFAULT IS TRUE
}
var showIBANSection = component.get('v.showIBANSection');
//console.log('BANK PROFILE BEFORE IBAN: ' + JSON.stringify(objectDataMap.bankProfile));
//if i have IBAN section, replace same logic of setup flow - start
//START - elena.preteni 28/08/2019 CAB editabile added condition (component.get("v.objectDataMap.isOperation") && component.get("v.objectDataMap.isSetup")) to if
if(showIBANSection==true || (component.get("v.objectDataMap.isOperation") && component.get("v.objectDataMap.isSetup")) )
{
//END - elena.preteni 28/08/2019 CAB editabile added condition (component.get("v.objectDataMap.isOperation") && component.get("v.objectDataMap.isSetup")) to if
//g.s. 14/02/2019 - if there is the OB_HeaderInternational__c , set it with merchant name - start
component.set('v.objectDataMap.BillingProfilePOS.OB_HeaderInternational__c' , objectDataMap.merchant.Name);
//START - elena.preteni 18/07/2019 F3 ABI CAB Selection CAB editabile
if(component.get("v.objectDataMap.isOperation") && component.get("v.objectDataMap.isSetup")){
component.set("v.objectDataMap.BillingProfilePOS.OB_CABCode__c", '' );
component.set("v.disabledCab",false);
//START - elena.preteni 28/08/2019 R1F3-11 make field disabed
component.set("v.ibanDisabled",false);
//END - elena.preteni 28/08/2019 R1F3-11 make field disabed
component.set("v.objectDataMap.BillingProfilePOS.OB_ABICode__c", bankABI );
component.set("v.disabledAbi",true);
}else{
if(objectDataMap.bankProfile.OB_AccountHolder__c==true){
//console.log('ACCOUNT_HOLDER_TRUE');
component.set("v.objectDataMap.BillingProfilePOS.OB_CABCode__c", CAB );
component.set("v.disabledCab",true);
component.set("v.objectDataMap.BillingProfilePOS.OB_ABICode__c", bankABI );
component.set("v.disabledAbi",true);
}else{
//console.log('ACCOUNT_HOLDER_FALSE');
if(isNewPOS && isNewVisaMastercard){ //11/10/19 francesca.ribezzi WN-604 - disable iban if there are a new pos and a new vm
component.set("v.ibanDisabled",true);
}else{
component.set("v.disabledCab",false);
component.set("v.disabledAbi",false);
component.set("v.objectDataMap.BillingProfilePOS.OB_CABCode__c" , '');
component.set("v.objectDataMap.BillingProfilePOS.OB_ABICode__c" , '');
//START francesca.ribezzi 17/07/19 moving this code below inside else and not outside - performance merge
component.set('v.objectDataMap.BillingProfilePOS.OB_EuroControlCode__c' , '');
component.set('v.objectDataMap.BillingProfilePOS.OB_CINCode__c' , '');
component.set('v.objectDataMap.BillingProfilePOS.OB_Bank_Account_Number__c' , '');
//END francesca.ribezzi 17/07/19
}
}
}
//END - elena.preteni 18/07/2019 F3 ABI CAB Selection CAB editabile
}
//if i have IBAN section, replace same logic of setup flow - end
//if i have IBAN section, replace same logic of setup flow
// //console.log('SHOW_IBAN: ' + component.get('v.showIBANSection'));
//******************** IBAN SECTION - END ********************//
//********************REPORT TYPE SECTION - START ********************//
//only if there is a new visa/mastercard show picklist
// check && isNewPOS!=true && isNewUPI!=true && isNewJCB!=true
//START francesca.ribezzi 11/09/19 - R1F3-48 - if it is setup, setting reportTypeRO in doInitMethod server-side method
if(component.get("v.isMaintenance")){
if(isNewVisaMastercard==true){
component.set('v.objectDataMap.reportTypeRO' , false);
}else{
component.set('v.objectDataMap.reportTypeRO' , true);
}
}
//END francesca.ribezzi 11/09/19 - R1F3-48
//********************REPORT TYPE SECTION - END ********************//
//********************PRELIMINARY VERIFICATION CODE & SETT TYPE - START ********************//
for(var key in objectDataMap.orderItem)
{
//console.log('KEy: ' + key);
// //console.log('NODE_IN_MAP: ' + JSON.stringify(objectDataMap.orderItem[key]));
for(var i=0; i<(objectDataMap.orderItem[key]).length; i++)
{
// //console.log('NODE_INNER_MAP: ' + JSON.stringify(objectDataMap.orderItem[key][i].NE__ProdId__r.OB_Codice_sfdc__c));
if(key == 'POS' && (objectDataMap.orderItem[key][i].NE__ProdId__r.OB_Codice_sfdc__c=='POS_TERZI_ATTENDED'|| objectDataMap.orderItem[key][i].NE__ProdId__r.OB_Codice_sfdc__c=='POS_TERZI_UNATTENDED'))
{
// //console.log('POS_ATTENDED');
component.set('v.objectDataMap.prelimVerifCodeRO' , false);//DEFAULT IS TRUE
}
if(key == 'ACQUIRING' && objectDataMap.orderItem[key][i].NE__ProdId__r.OB_Acquirer__c == 'NEXI' )
{
// //console.log('ACQUIRING LIST: ' + JSON.stringify(objectDataMap.orderItem[key]));
component.set('v.objectDataMap.isNEXI' , true);
// NEXI-256 Marta Stempien <marta.stempien@accenture.com> 05/08/2019, Deleted setting v.settlementType - deleted attribute
}
}
}
//********************PRELIMINARY VERIFICATION CODE & SETT TYPE - START ********************//
var keyToUse= !$A.util.isEmpty(objectDataMap.keyToUse)? JSON.parse(objectDataMap.keyToUse) : null; //francesca.ribezzi 18/10/19 - parsing keyToUse node bacause it is a String!
for(var key in objectDataMap.orderItem)
{
//elena.preteni - start - 30/01/2019
for(var i=0; i<(objectDataMap.orderItem[key]).length; i++)
{
if(isNewVisaMastercard && objectDataMap.orderItem[key][i].NE__ProdId__r.OB_Acquirer__c == 'NEXI'){
// //console.log('OBJDATAMAP_KEYTOUSE: ' + objectDataMap.keyToUse);
if(keyToUse.servicePointCode != null && keyToUse.Processor == 'EQUENS')
{
// //console.log('PROCESSOR_EQUENS');
if( keyToUse.OBInternationalSettlementMethod != null )
{
// //console.log('INT_SETT_METHOD_NOTNULL');
if(objectDataMap.bankProfile.OB_Circuit__c == 'Pagobancomat bancario')
{
// //console.log('BANKPROFILE_PAGOBANCOMAT_BANCARIO');
component.set('v.objectDataMap.interSettMethRO',true);
objectDataMap.Configuration.OB_PBSettlementMethod__c = keyToUse.OBPBSettlementMethod;
objectDataMap.Configuration.OB_InternationalSettlementMethod__c =keyToUse.OBInternationalSettlementMethod;
}
if(objectDataMap.bankProfile.OB_Circuit__c == 'Pagobancomat sub-licenza')
{
// //console.log('BANKPROFILE_PAGOBANCOMAT_SUBLICENZA');
if(objectDataMap.orderItem[key][i].NE__Root_Order_Item__c == null && objectDataMap.orderItem[key][i].NE__ProdId__r.RecordType.DeveloperName == 'Pagobancomat')
{
if(objectDataMap.Configuration.OB_PBSettlementMethod__c != undefined && objectDataMap.Configuration.OB_PBSettlementMethod__c !=null)
{
// //console.log('SETT_MET_NOTNULL');
objectDataMap.viewSettMeth = true;
objectDataMap.settMethRO = false;
}
else if(objectDataMap.orderItem[key][i].RecordType.DeveloperName=='Pagobancomat')
{
// //console.log('DEVNAME==PAGOBANCOMAT');
component.set('v.objectDataMap.interSettMethRO',true);
objectDataMap.Configuration.OB_PBSettlementMethod__c = keyToUse.OBPBSettlementMethod;
objectDataMap.Configuration.OB_InternationalSettlementMethod__c =keyToUse.OBInternationalSettlementMethod;
}
else
{
// //console.log('DEVNAME!=PAGOBANCOMAT');
component.set('v.objectDataMap.interSettMethRO',true);
objectDataMap.Configuration.OB_PBSettlementMethod__c = keyToUse.OBPBSettlementMethod;
objectDataMap.Configuration.OB_InternationalSettlementMethod__c = keyToUse.OBInternationalSettlementMethod;
}
}
}
}
}
//var valueNetto = 'BANCA (ACCREDITATO AL NETTO DELLE COMMISSIONI)';
//var valueLordo = 'BANCA (ACCREDITATO AL LORDO DELLE COMMISSIONI)';
var valueNetto = 'ACCREDITO AL NETTO DELLE COMMISSIONI';
var valueLordo = 'ACCREDITO AL LORDO DELLE COMMISSIONI';
if(keyToUse.servicePointCode != null && keyToUse.Processor == 'SIA')
{
// //console.log('EQUENS_SIA');
if( keyToUse.OBInternationalSettlementMethod != null )
{
component.set('v.objectDataMap.interSettMethRO',true);
objectDataMap.Configuration.OB_PBSettlementMethod__c = keyToUse.OBInternationalSettlementMethod;
objectDataMap.Configuration.OB_InternationalSettlementMethod__c =keyToUse.OBInternationalSettlementMethod;
}
else
{
if( objectDataMap.bankProfile.OB_SettlementType__c == 'Prepagato')
{
// //console.log('SETT_PREPAGATO');
component.set('v.objectDataMap.interSettMethRO',true);
keyToUse.OBInternationalSettlementMethod=valueNetto;
objectDataMap.Configuration.OB_PBSettlementMethod__c = valueNetto;
objectDataMap.Configuration.OB_InternationalSettlementMethod__c =valueNetto;
}
if( objectDataMap.bankProfile.OB_SettlementType__c == 'Postpagato')
{
// //console.log('SETT_POSTPAGATO');
component.set('v.objectDataMap.showPicklistPostpagato',true);
component.get('v.postPagatoPickList').push(valueNetto);
component.get('v.postPagatoPickList').push(valueLordo);
objectDataMap.Configuration.OB_PBSettlementMethod__c = component.get('v.settMethodPostPagatoValue');
objectDataMap.Configuration.OB_InternationalSettlementMethod__c =component.get('v.settMethodPostPagatoValue');;
}
}
}
if(typeof keyToUse.servicePointCode === undefined || keyToUse.servicePointCode == null)
{
// //console.log('SERVICEPOINTCODE_NULL');
if( objectDataMap.bankProfile.OB_SettlementType__c == 'Prepagato')
{
// //console.log('SETT_PREPAGATO');
component.set('v.objectDataMap.interSettMethRO',true);
keyToUse.OBInternationalSettlementMethod =valueLordo;
objectDataMap.Configuration.OB_PBSettlementMethod__c = valueLordo;
objectDataMap.Configuration.OB_InternationalSettlementMethod__c =valueLordo;
}
if( objectDataMap.bankProfile.OB_SettlementType__c == 'Postpagato')
{
// //console.log('SETT_POSTPAGATO');
component.set('v.objectDataMap.showPicklistPostpagato',true);
component.get('v.postPagatoPickList').push(valueNetto);
component.get('v.postPagatoPickList').push(valueLordo);
objectDataMap.Configuration.OB_PBSettlementMethod__c = component.get('v.settMethodPostPagatoValue');
objectDataMap.Configuration.OB_InternationalSettlementMethod__c =component.get('v.settMethodPostPagatoValue');;
}
}
}
}
//elena.preteni - end - 30/01/201
}
//component.set("v.Spinner", false);
console.log('showIBANSection before calling confirm btn funct: ' + component.get('v.showIBANSection'));
//16/07/19 francesca.ribezzi adding else condition - performance merge
component.set("v.loadComponent", true);
//26/07/19 francesca.ribezzi calling checkTerminalsIBAN before confirmCreationBillingProfilesHelper
component.set('v.objectDataMap',objectDataMap ); // antonio.vatrano 05/09/2019 WN-290
if(isNewVisaMastercard && !isNewPOS){ //francesca.ribezzi 18/10/19
component.set("v.ibanDisabled", false);
}else{
helper.checkTerminalsIBAN(component,event);
}
}catch(err){
component.set("v.Spinner", false);
console.log('DOINTI_AFTER_ERROR: ' + err.message);
}
var t1 = performance.now();
console.log("Call doInitAfter took " + (t1 - t0) + " milliseconds.");
},
/* NEW STUFF */
fieldCheck : function(component, event, helper) // onchange
{
// 25-09-2018-Salvatore P.-Check if fields are of max length and focus on next input
var inputId = event.getSource().getLocalId();
var inputValue = component.find(inputId).get("v.value");
var maxLengthInput = component.find(inputId).get("v.maxlength");
//francesca.ribezzi 28/08/19 - R1F3-7 - declaring variables:
var nextInput;
var nextInput2;
try
{
inputValue=inputValue.toUpperCase();
}
catch(err)
{
//_utils.debug('err.message: ' + err.message);
}
if(inputId == 'euroControlCode')
{
component.set("v.objectDataMap.BillingProfilePOS.OB_EuroControlCode__c",inputValue);
//francesca.ribezzi 28/08/19 - R1F3-7 - chaning document.getElementById to component.find
nextInput=component.find('cin');
if(maxLengthInput==inputValue.length)
{
nextInput.focus();
}
}
else if(inputId == 'cin')
{
component.set("v.objectDataMap.BillingProfilePOS.OB_CINCode__c",inputValue);
//francesca.ribezzi 28/08/19 - R1F3-7 - chaning document.getElementById to component.find
nextInput=component.find('abi');
nextInput2=component.find('cab');
if(maxLengthInput==inputValue.length)
{
var disabledAbi = component.get("v.disabledAbi");
if(disabledAbi == false)
{
nextInput.focus();
}
else
{
nextInput2.focus();
}
}
}
else if(inputId == 'abi')
{
component.set("v.objectDataMap.BillingProfilePOS.OB_ABICode__c",inputValue);
//francesca.ribezzi 28/08/19 - R1F3-7 - chaning document.getElementById to component.find
nextInput=component.find('cab');
if(maxLengthInput==inputValue.length)
{
nextInput.focus();
}
}
else if(inputId == 'cab')
{
component.set("v.objectDataMap.BillingProfilePOS.OB_CABCode__c",inputValue);
//francesca.ribezzi 28/08/19 - R1F3-7 - chaning document.getElementById to component.find
nextInput=component.find('bankAccountNumber');
if(maxLengthInput==inputValue.length)
{
nextInput.focus();
}
}
else if(inputId == 'bankAccountNumber')
{
component.set("v.objectDataMap.BillingProfilePOS.OB_Bank_Account_Number__c",inputValue);
//francesca.ribezzi 28/08/19 - R1F3-7 - chaning document.getElementById to component.find
nextInput=component.find('headerInternational');
if(maxLengthInput==inputValue.length)
{
// nextInput.focus();
}
}
},
completeIban : function(component,event,helper) //onblur
{
// 25-09-2018-Salvatore P.-Check mandatory fields and validations
var inputId = event.getSource().getLocalId();
//26/0/19 francesca.ribezzi get input:
var input = component.find(inputId);
//_utils.debug("INPUD ID: "+inputId);
var inputValue = component.find(inputId).get("v.value");
var errorId = 'errorId' + inputId;
var errorIdValidation = 'errorId' + inputId;
var errorCustomLabel = '';
var myDiv;
var arrayIban = [];
var arrayConverted = [];
var countryCodeValue = component.get("v.objectDataMap.BillingProfilePOS.OB_CountryCode__c");
var euroControlCodeValue = component.get("v.objectDataMap.BillingProfilePOS.OB_EuroControlCode__c");
var cinCodeValue = component.get("v.objectDataMap.BillingProfilePOS.OB_CINCode__c");
var abiCodeValue = component.get("v.objectDataMap.BillingProfilePOS.OB_ABICode__c");
var cabCodeValue = component.get("v.objectDataMap.BillingProfilePOS.OB_CABCode__c");
var bankAccountNumberValue = component.get("v.objectDataMap.BillingProfilePOS.OB_Bank_Account_Number__c");
var ibanComplete = countryCodeValue + euroControlCodeValue + cinCodeValue + abiCodeValue + cabCodeValue + bankAccountNumberValue;
var ibanLength = ibanComplete.length;
//francesca.ribezzi 28/08/19 - R1F3-7 - setting error message to blank:
input.setCustomValidity('');
if(inputId == 'euroControlCode')
{
var countryCode = component.find("countryCode").get("v.value");
if(countryCode=="IT")
{
component.set("v.objectDataMap.BillingProfilePOS.OB_CountryCode__c","IT");
}
var typeInputValue = isNaN(inputValue);
component.set("v.objectDataMap.BillingProfilePOS.OB_EuroControlCode__c", '');
if(!inputValue)
{
if(document.getElementById(errorIdValidation))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorIdValidation).remove();
}
//_utils.debug("control if fields value is null (onblur)");
$A.util.addClass(input , 'slds-has-error'); //francesca.ribezzi 26/0719 changing comp
errorCustomLabel = $A.get("$Label.c.MandatoryField");
//francesca.ribezzi 28/08/19 setting standard custom validation error for lightning input
//instead of using custom javascript!
input.setCustomValidity(errorCustomLabel);
/*myDiv = document.createElement('div');
myDiv.setAttribute('id',errorId);
myDiv.setAttribute('style','color:rgb(194, 57, 52); position: absolute; z-index: 1;');
var errorMessage = document.createTextNode(errorCustomLabel);
myDiv.appendChild(errorMessage);
var divAfter = component.find(inputId).getElement();
divAfter.after(myDiv);*/
}
else if(inputValue.length > 0 && inputValue.length != 2 || typeInputValue==true)
{
if(document.getElementById(errorId))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorId).remove();
}
$A.util.addClass(input, 'slds-has-error'); //francesca.ribezzi 26/0719 changing comp
errorCustomLabel = $A.get("$Label.c.TwoDigitLength");
//francesca.ribezzi 28/08/19 setting standard custom validation error for lightning input
//instead of using custom javascript!
input.setCustomValidity(errorCustomLabel);
/*myDiv = document.createElement('div');
myDiv.setAttribute('id',errorIdValidation);
myDiv.setAttribute('style','color:rgb(194, 57, 52); position: absolute; z-index: 1;');
var errorMessage = document.createTextNode(errorCustomLabel);
myDiv.appendChild(errorMessage);
var divAfter = component.find(inputId).getElement();
divAfter.after(myDiv);*/
}
else
{
if(document.getElementById(errorId))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorId).remove();
}
component.set("v.objectDataMap.BillingProfilePOS.OB_EuroControlCode__c", inputValue);
//_utils.debug("euroControlCode value in object data map: ",component.get("v.objectDataMap.BillingProfilePOS.OB_EuroControlCode__c"));
if(ibanLength == 27)
{
helper.validateIban(component,event,helper,inputId);
}
}
}
else if(inputId == "cin")
{
var typeInputValue = isNaN(inputValue);
component.set("v.objectDataMap.BillingProfilePOS.OB_CINCode__c", '');
if(!inputValue)
{
if(document.getElementById(errorIdValidation))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorIdValidation).remove();
}
//_utils.debug("control if fields value is null (onblur)");
$A.util.addClass(input , 'slds-has-error'); //francesca.ribezzi 26/0719 changing comp
errorCustomLabel = $A.get("$Label.c.MandatoryField");
//_utils.debug("ERROR CUSTOM Label: "+errorCustomLabel);
//francesca.ribezzi 28/08/19 -R1F3-7 - setting standard custom validation error for lightning input
//instead of using custom javascript!
input.setCustomValidity(errorCustomLabel);
/*myDiv = document.createElement('div');
myDiv.setAttribute('id',errorId);
myDiv.setAttribute('style','color:rgb(194, 57, 52); position: absolute; z-index: 1;');
var errorMessage = document.createTextNode(errorCustomLabel);
myDiv.appendChild(errorMessage);
var divAfter = component.find(inputId).getElement();
divAfter.after(myDiv);*/
}
else if(inputValue.length > 0 && inputValue.length != 1 || typeInputValue==false)
{
if(document.getElementById(errorId))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorId).remove();
}
$A.util.addClass(input , 'slds-has-error'); //francesca.ribezzi 26/0719 changing comp
errorCustomLabel = $A.get("$Label.c.OneCharLength");
//francesca.ribezzi 28/08/19 setting - R1-F3-7 - standard custom validation error for lightning input
//instead of using custom javascript!
input.setCustomValidity(errorCustomLabel);
/*myDiv = document.createElement('div');
myDiv.setAttribute('id',errorIdValidation);
myDiv.setAttribute('style','color:rgb(194, 57, 52); position: absolute; z-index: 1;');
var errorMessage = document.createTextNode(errorCustomLabel);
myDiv.appendChild(errorMessage);
var divAfter = component.find(inputId).getElement();
divAfter.after(myDiv);*/
}
else
{
if(document.getElementById(errorId))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorId).remove();
}
component.set("v.objectDataMap.BillingProfilePOS.OB_CINCode__c", inputValue);
//_utils.debug("cin value in object data map: ",component.get("v.objectDataMap.BillingProfilePOS.OB_CINCode__c"));
if(ibanLength == 27)
{
helper.validateIban(component,event,helper,inputId);
}
}
}
else if(inputId == "abi")
{
var typeInputValue = isNaN(inputValue);
component.set("v.objectDataMap.BillingProfilePOS.OB_ABICode__c", '');
if(!inputValue)
{
if(document.getElementById(errorIdValidation))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorIdValidation).remove();
}
//_utils.debug("control if fields value is null (onblur)");
$A.util.addClass(input , 'slds-has-error'); //francesca.ribezzi 26/0719 changing comp
errorCustomLabel = $A.get("$Label.c.MandatoryField");
//_utils.debug("ERROR CUSTOM Label: "+errorCustomLabel);
//francesca.ribezzi 28/08/19 setting - R1-F3-7 - standard custom validation error for lightning input
//instead of using custom javascript!
input.setCustomValidity(errorCustomLabel);
/*myDiv = document.createElement('div');
myDiv.setAttribute('id',errorId);
myDiv.setAttribute('style','color:rgb(194, 57, 52); position: absolute; z-index: 1;');
var errorMessage = document.createTextNode(errorCustomLabel);
myDiv.appendChild(errorMessage);
var divAfter = component.find(inputId).getElement();
divAfter.after(myDiv);*/
}
else if(inputValue.length > 0 && inputValue.length != 5 || typeInputValue==true)
{
if(document.getElementById(errorId))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorId).remove();
}
$A.util.addClass(input , 'slds-has-error'); //francesca.ribezzi 26/0719 changing comp
errorCustomLabel = $A.get("$Label.c.FiveDigitLength");
//francesca.ribezzi 28/08/19 setting - R1-F3-7 - standard custom validation error for lightning input
//instead of using custom javascript!
input.setCustomValidity(errorCustomLabel);
/*myDiv = document.createElement('div');
myDiv.setAttribute('id',errorIdValidation);
myDiv.setAttribute('style','color:rgb(194, 57, 52); position: absolute; z-index: 1;');
var errorMessage = document.createTextNode(errorCustomLabel);
myDiv.appendChild(errorMessage);
var divAfter = component.find(inputId).getElement();
divAfter.after(myDiv);*/
}
else
{
if(document.getElementById(errorId))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorId).remove();
}
component.set("v.objectDataMap.BillingProfilePOS.OB_ABICode__c", inputValue);
//_utils.debug("abi value in object data map: ",component.get("v.objectDataMap.BillingProfilePOS.OB_ABICode__c"));
if(ibanLength == 27 && component.get("v.disabledAbi")==false)
{
helper.validateIban(component,event,helper,inputId);
}
}
}
else if(inputId == "cab")
{
var typeInputValue = isNaN(inputValue);
component.set("v.objectDataMap.BillingProfilePOS.OB_CABCode__c", '');
if(!inputValue)
{
if(document.getElementById(errorIdValidation))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorIdValidation).remove();
}
//_utils.debug("control if fields value is null (onblur)");
$A.util.addClass(input, 'slds-has-error'); //francesca.ribezzi 26/0719 changing comp
errorCustomLabel = $A.get("$Label.c.MandatoryField");
//_utils.debug("ERROR CUSTOM Label: "+errorCustomLabel);
//francesca.ribezzi 28/08/19 setting - R1-F3-7 - standard custom validation error for lightning input
//instead of using custom javascript!
input.setCustomValidity(errorCustomLabel);
/*myDiv = document.createElement('div');
myDiv.setAttribute('id',errorId);
myDiv.setAttribute('style','color:rgb(194, 57, 52); position: absolute; z-index: 1;');
var errorMessage = document.createTextNode(errorCustomLabel);
myDiv.appendChild(errorMessage);
var divAfter = component.find(inputId).getElement();
divAfter.after(myDiv);*/
}
else if(inputValue.length > 0 && inputValue.length != 5 || typeInputValue==true)
{
if(document.getElementById(errorId))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorId).remove();
}
$A.util.addClass(input, 'slds-has-error'); //francesca.ribezzi 26/0719 changing comp
errorCustomLabel = $A.get("$Label.c.FiveDigitLength");
//francesca.ribezzi 28/08/19 setting - R1-F3-7 - standard custom validation error for lightning input
//instead of using custom javascript!
input.setCustomValidity(errorCustomLabel);
/*myDiv = document.createElement('div');
myDiv.setAttribute('id',errorIdValidation);
myDiv.setAttribute('style','color:rgb(194, 57, 52); position: absolute; z-index: 1;');
var errorMessage = document.createTextNode(errorCustomLabel);
myDiv.appendChild(errorMessage);
var divAfter = component.find(inputId).getElement();
divAfter.after(myDiv);*/
}
else
{
if(document.getElementById(errorId))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorId).remove();
}
component.set("v.objectDataMap.BillingProfilePOS.OB_CABCode__c", inputValue);
//_utils.debug("cab value in object data map: ",component.get("v.objectDataMap.BillingProfilePOS.OB_CABCode__c"));
if(ibanLength == 27)
{
helper.validateIban(component,event,helper,inputId);
}
}
}
else if(inputId == "bankAccountNumber")
{
component.set("v.objectDataMap.BillingProfilePOS.OB_Bank_Account_Number__c", inputValue);
var typeInputValue = false;
if( /[^a-zA-Z0-9]/.test(inputValue))
{
typeInputValue = true;
}
if(!inputValue)
{
if(document.getElementById(errorIdValidation))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorIdValidation).remove();
}
//_utils.debug("control if fields value is null (onblur)");
$A.util.addClass(input , 'slds-has-error'); //francesca.ribezzi 26/0719 changing comp
errorCustomLabel = $A.get("$Label.c.MandatoryField");
//_utils.debug("ERROR CUSTOM Label: "+errorCustomLabel);
//francesca.ribezzi 28/08/19 setting - R1-F3-7 - standard custom validation error for lightning input
//instead of using custom javascript!
input.setCustomValidity(errorCustomLabel);
/*myDiv = document.createElement('div');
myDiv.setAttribute('id',errorId);
myDiv.setAttribute('style','color:rgb(194, 57, 52); position: absolute; z-index: 1;');
var errorMessage = document.createTextNode(errorCustomLabel);
myDiv.appendChild(errorMessage);
var divAfter = component.find(inputId).getElement();
divAfter.after(myDiv);*/
}
else if(inputValue.length > 0 && inputValue.length != 12 || typeInputValue==true)
{
if(document.getElementById(errorId))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorId).remove();
}
$A.util.addClass(input, 'slds-has-error'); //francesca.ribezzi 26/0719 changing comp
errorCustomLabel = $A.get("$Label.c.TwelveDigitLength");
//francesca.ribezzi 28/08/19 setting - R1-F3-7 - standard custom validation error for lightning input
//instead of using custom javascript!
input.setCustomValidity(errorCustomLabel);
/*myDiv = document.createElement('div');
myDiv.setAttribute('id',errorIdValidation);
myDiv.setAttribute('style','color:rgb(194, 57, 52); position: absolute; z-index: 1;');
var errorMessage = document.createTextNode(errorCustomLabel);
myDiv.appendChild(errorMessage);
//var divAfter = component.find(inputId).getElement(); //26/07/19 francesca.ribezzi - commenting cause of api version
//divAfter.after(myDiv);*/
}
else if(document.getElementById(errorId))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorId).remove();
}
component.set("v.objectDataMap.BillingProfilePOS.OB_Bank_Account_Number__c", inputValue);
//_utils.debug("bankAccountNumber value in object data map: ",component.get("v.objectDataMap.BillingProfilePOS.OB_Bank_Account_Number__c"));
if(ibanLength == 27)
{
helper.validateIban(component,event,helper,inputId);
}
}
else if(inputId == 'headerInternational')
{
component.set("v.objectDataMap.BillingProfilePOS.OB_HeaderInternational__c", inputValue);
var typeInputValue = false;
if(/^[a-zA-Z0-9()""?!&% $£=^ °\/\\.'']+$/.test(inputValue))
{
typeInputValue = true;
}
if(!inputValue)
{
if(document.getElementById(errorIdValidation))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorIdValidation).remove();
}
$A.util.addClass(component.find(input) , 'slds-has-error'); //francesca.ribezzi 26/0719 changing comp
errorCustomLabel = $A.get("$Label.c.MandatoryField");
//francesca.ribezzi 28/08/19 setting - R1-F3-7 - standard custom validation error for lightning input
//instead of using custom javascript!
input.setCustomValidity(errorCustomLabel);
/*myDiv = document.createElement('div');
myDiv.setAttribute('id',errorId);
myDiv.setAttribute('style','color:rgb(194, 57, 52); position: absolute; z-index: 1;');
var errorMessage = document.createTextNode(errorCustomLabel);
myDiv.appendChild(errorMessage);
var divAfter = component.find(inputId).getElement();
divAfter.after(myDiv);*/
}
else if(typeInputValue==false)
{
if(document.getElementById(errorId))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorId).remove();
}
$A.util.addClass(component.find(input) , 'slds-has-error'); //francesca.ribezzi 26/0719 changing comp
errorCustomLabel = $A.get("$Label.c.errorSpecialCharacter");
//francesca.ribezzi 28/08/19 setting - R1-F3-7 - standard custom validation error for lightning input
//instead of using custom javascript!
input.setCustomValidity(errorCustomLabel);
/*myDiv = document.createElement('div');
myDiv.setAttribute('id',errorIdValidation);
myDiv.setAttribute('style','color:rgb(194, 57, 52); position: absolute; z-index: 1;');
var errorMessage = document.createTextNode(errorCustomLabel);
myDiv.appendChild(errorMessage);
var divAfter = component.find(inputId).getElement();
divAfter.after(myDiv);*/
}
else
{
if(document.getElementById(errorId))
{
//francesca.ribezzi 28/08/19 -R1F3-7 removing error message if any
input.setCustomValidity("");
document.getElementById(errorId).remove();
}
component.set("v.objectDataMap.BillingProfilePOS.OB_HeaderInternational__c", inputValue);
}
}
},
// ID 155, Doris Dongmo <doris.tatiana.dongmo@accenture.com>, 08/04/2019 Start
controlIsSpecialCharacter:function(component,event,helper){
var inputIdVar = component.find('prelimVerifCode');
var inputValue = inputIdVar.get("v.value");
var errorIdValidation = 'errorId' + inputIdVar;
var typeInputValue = false;
// ID 155, Doris Dongmo <doris.tatiana.dongmo@accenture.com>, 03/05/2019, update regex
if(/^[a-zA-Z0-9()?@_:\-!&% $+ \/°.'',]+$/.test(inputValue) )
{
typeInputValue = true;
}
if(!inputValue)
{
// BOOLEAN TO SHOW ERROR MESSAGE - BOOLEAN TO HIDE SPECIAL CHARACTER ERROR MESSAGE - ADD CLASS
helper.controlIsSpecialCharacterHelper(component, true,false,inputIdVar);
}
else if(typeInputValue==false)
{
// BOOLEAN TO HIDE ERROR MESSAGE - BOOLEAN TO SHOW SPECIAL CHARACTER ERROR MESSAGE - ADD CLASS
helper.controlIsSpecialCharacterHelper(component, false,true,inputIdVar);
component.set("v.objectDataMap.errorDateMap."+errorIdValidation, true);
}
else
{
// BOOLEAN TO HIDE ERROR MESSAGE - BOOLEAN TO HIDE SPECIAL CHARACTER ERROR MESSAGE - REMOVE CLASS
helper.controlIsSpecialCharacterHelper(component, false, false,inputIdVar);
component.set("v.objectDataMap.errorDateMap."+errorIdValidation, false);
}
},
//ID 155, Doris Dongmo <doris.tatiana.dongmo@accenture.com>, 08/04/2019 .....END
setPickListValue : function(component,event,helper)
{ var currentId = event.getSource().getLocalId();
// 25-09-2018-Salvatore P.-Set of picklist value
component.set("v.objectDataMap.Configuration.OB_Report_Type__c", component.get("v.objectDataMap.OrderHeader.OB_Report_Type__c"));
$A.util.removeClass(component.find(currentId) , 'slds-has-error');
//RECREATE THE SAME ID OF ERROR MESSAGE
var errorId = 'errorId'+ currentId;
if(document.getElementById(errorId)!=null){
document.getElementById(errorId).remove();
}
//START francesca.ribezzi 18/07/19 deleting confirmOperationData button
// helper.confirmCreationBillingProfilesHelper(component,event);
},
setRedBorderoperationalData: function(component, event, helper)
{
helper.setRedBorderHelper(component,event);
},
/* START micol.ferrari 01/10/2018 - CREATION OF BILLING PROFILES */
confirmCreationBillingProfiles: function(component, event, helper)
{
try{
helper.confirmCreationBillingProfilesHelper(component,event);
}catch(err){
console.log('ERROR_MESSAGE_CALL_HELPER: ' + err.message);
}
},
/* END micol.ferrari 01/10/2018 - CREATION OF BILLING PROFILES */
picklistPrepagatoChange: function(component, event, helper) {
var currentId = event.getSource().getLocalId();
var postPagatoValue = component.get("v.settMethodPostPagatoValue");
component.set("v.objectDataMap.Configuration.OB_PBSettlementMethod__c", postPagatoValue);
component.set("v.objectDataMap.Configuration.OB_InternationalSettlementMethod__c", postPagatoValue);
$A.util.removeClass(component.find(currentId) , 'slds-has-error');
//RECREATE THE SAME ID OF ERROR MESSAGE
var errorId = 'errorId'+ currentId;
if(document.getElementById(errorId)!=null){
//_utils.debug("errorID . " + errorId);
document.getElementById(errorId).remove();
}
//START francesca.ribezzi 18/07/19 deleting confirmOperationData button
// helper.confirmCreationBillingProfilesHelper(component,event);
},
removeRedBorder: function (component, event , helper){
helper.removeRedBorder(component, event , helper);
},
notBlank: function (component, event , helper){
var dateValue = event.getSource().get("v.value");
var currentId = event.getSource().getLocalId();
//_utils.debug('dateValue:: '+dateValue);
if(!dateValue){
component.find(currentId).set("v.value", component.get("v.orderCreatedDate"));
} else {
helper.removeRedBorderDate(component, event , helper);
//START francesca.ribezzi 18/07/19 deleting confirmOperationData button
// helper.confirmCreationBillingProfilesHelper(component,event);
}
},
//francesca.ribezzi - checking if the value is a terminal id and if it is correct:
/* checkInputValue: function(component, event, helper) {
//_utils.debug("into checkInputValue");
var value = event.target.value;//event.getSource().get("v.value");
var attributeIndex = JSON.stringify(event.target.id);
var listOfItems = component.get("v.posList");
var parentIndex = document.getElementById(event.target.id).name;
//_utils.debug("parentIndex: " + parentIndex);
var pos1 = attributeIndex.indexOf("_")+1;
var length1 = attributeIndex.indexOf("_",pos1)-1;
var tempStr = attributeIndex.substr(length1);
attributeIndex = tempStr.substr(0,tempStr.indexOf('_'));
var attName = document.getElementById(attributeIndex+'_attName').textContent;
var itemToUpdate = listOfItems[parentIndex];
var errMsg= document.getElementById(event.target.id+'_ErrorTerminalId');
//checking if this is the terminal id:
// if(value.length > 2){
if(value.length != 8){
errMsg.innerHTML= 'Terminal ID must be 8 characters long.';
}
// }
},*/
onChangeAttributeValueTerminalId: function(component, event, helper){
try{ //francesca.ribezzi 26/09/19 - WN-500 - adding try catch
//francesca.ribezzi - new list composed by vas and pos with terminal ids:
var terminaIdItemsMap = component.get("v.terminaIdItemsMap");
var itemId = document.getElementById(event.target.id).name;
var mapItemIdSuccessTerminalCall = component.get("v.mapItemIdSuccessTerminalCall");
//RESET Error Message if updating terminal ID
var itemToUpdate = terminaIdItemsMap[itemId];
var errMsg= document.getElementById(event.target.id+'_ErrorTerminalId');
//checking if this is the terminal id:
//francesca.ribezzi - removing error class from input:
var inputValue = event.target.value;
if(/^[0-9]*([,][0-9]{1,3}|)$/.test(event.target.value)){
if(inputValue.length == 8){
document.getElementById(event.target.id).classList.remove("borderError");
//START francesca.ribezzi 26/09/19 - WN-500 - removing attributeIndex and setting the term id value:
for(var i = 0; i<itemToUpdate.listOfAttributes.length; i++ ){
if(itemToUpdate.listOfAttributes[i].fields.name == 'Terminal Id'){
itemToUpdate.listOfAttributes[i].fields.value = event.target.value;
break;
}
}
//END francesca.ribezzi 26/09/19 - WN-500
component.set("v.itemToUpdate", itemToUpdate);
//francesca.ribezzi 30/09/19 update terminaIdItemsMap:
component.set("v.terminaIdItemsMap", terminaIdItemsMap);
errMsg.innerHTML = '';
}else{
if(inputValue.length == 0){
errMsg.innerHTML = '';
document.getElementById(event.target.id).classList.remove("borderError");
}else{
errMsg.innerHTML = $A.get("$Label.c.OB_EightCharError");
document.getElementById(event.target.id).classList.add("borderError");
}
}
}
else{
var errorMessage = $A.get("$Label.c.OB_invalidValue");
errMsg.innerHTML = errorMessage;
//event.target.value = '';
document.getElementById(event.target.id).classList.add("borderError");
}
mapItemIdSuccessTerminalCall[itemToUpdate.fields.id] = false;
component.set("v.mapItemIdSuccessTerminalCall", mapItemIdSuccessTerminalCall);
}catch(err){
console.log('ERROR - onChangeAttributeValueTerminalId: ' + err.message );
}
},
// Daniele Gandini <daniele.gandini@accenture.com> - 20/05/2019 - TerminalsReplacement - Logic for getting termId from selectList and set into attribute field - START
setTermId : function(component,event,helper){
//francesca.ribezzi 15/07/19 changing event.target.value into event.getSource cause of API version.
var attributeIndex = event.getSource().get("v.name"); // POS index
var termIdValue = event.getSource().get("v.value"); // termId
console.log("term id = " + termIdValue);
var contextOutput = component.get("v.contextOutput");
var mapItemIdSuccessTerminalCall = component.get("v.mapItemIdSuccessTerminalCall");
var listOfItems = [];
listOfItems = component.get("v.posList");
console.log("posList: " + JSON.stringify(listOfItems));
attributeIndex = JSON.stringify(event.getSource().get("v.name"));
attributeIndex = attributeIndex.substr(0,attributeIndex.indexOf('-'));
var itemName = attributeIndex.split("_").pop(); //VAS or POS
attributeIndex = attributeIndex.substr(1,attributeIndex.indexOf('_')-1);
var termIdMap = component.get("v.termIdMap");
// create a list with term id values already used in a POS to check them
var termIdUsed = [];
console.log("termIdUsed" + JSON.stringify(termIdUsed));
var itemToUpdate = listOfItems[parseInt(attributeIndex)];
for(var j = 0; j < itemToUpdate.listOfAttributes.length; j++){
if(itemToUpdate.listOfAttributes[j].fields.name == 'Terminal Id'){
itemToUpdate.listOfAttributes[j].fields.value = termIdValue; //22/07/19 francesca.ribezzi changing event.target.value into event.getSource cause of API version.
// component.set("v.Spinner",false);
break;
}
}
termIdMap[attributeIndex] = termIdValue;
component.set("v.termIdMap", termIdMap);
console.log("updated term id map: " + JSON.stringify(component.get("v.termIdMap")));
component.set("v.posList",listOfItems);
var siaCodesFromTerminals = component.get("v.siaCodesFromTerminals");
for( var key in siaCodesFromTerminals){
for(var j = 0; j < itemToUpdate.listOfAttributes.length; j++){
if(key == itemToUpdate.listOfAttributes[j].fields.value){
for(var k in siaCodesFromTerminals[key]){
for(var i = 0; i < itemToUpdate.listOfAttributes.length; i++){
if(itemToUpdate.listOfAttributes[i].fields.name == k){
itemToUpdate.listOfAttributes[i].fields.value = siaCodesFromTerminals[key][k];
console.log('itemToUpdate.listOfAttributes[j].fields.value'+itemToUpdate.listOfAttributes[i].fields.value);
}
}
}
console.log('mappa sia'+ JSON.stringify(siaCodesFromTerminals[key]));
}
}
}
// component.set("v.isEnd", true);
mapItemIdSuccessTerminalCall[itemToUpdate.fields.id] = true;
component.set("v.itemToUpdate", itemToUpdate);
//francesca.ribezzi 10/07/19 deleting this event - not needed anymore
/*var changeAttributeEvent = $A.get("e.NE:Bit2win_Event_AttributeChanged");
changeAttributeEvent.setParams({
'itemChanged': itemToUpdate,
'Context_Output':contextOutput
});
changeAttributeEvent.fire();*/
// Daniele Gandini <daniele.gandini@accenture.com> - 20/05/2019 - TerminalsReplacement - Logic for getting termId from selectList and set into attribute field - START
},
// Doris D. ...25/03/2019... ::::::: Start//
open : function (component,event,helper){
component.set("v.showMessage", true);
},
close : function (component,event,helper){
component.set("v.showMessage", false);
},
//D.F. _ 26-03-2019 ManageRacSia v4 _ START
showIbanSelModal: function(component, event, helper) {
component.set("v.showIbanSelModal", true);
},
closeIbanSelModal: function(component, event, helper) {
component.set("v.showIbanSelModal",false);
},
getSelectedIBAN: function(component, event, helper) {
helper.getSelectedOption(component, event);
},
//D.F. _ END
/*
*@author francesca.ribezzi
*@date 31/07/2019
*@defect WN-211
*@description passing goNext attribute to ManageRacSIA component to set red border on invalid inputs once next button is clicked:
*@history 31/07/2019 Method created
*/
goNextStep : function(component, event, helper) {
component.set("v.goNext", true);
},
/*
*@author francesca.ribezzi
*@date 26/09/2019
*@defect WN-368
*@description method used to check if the inserted preliminary verification code is a correct value
*@history 26/09/2019 Method created
*/
onChangePrelimVerifCode : function(component, event, helper) {
var input = component.find('prelimVerifCode');
var value = component.find("prelimVerifCode").get("v.value");
if (value.length == 7 && !isNaN(value)){ //if it's numeric and its length is 7 --> OK!
input.setCustomValidity("");
component.set("v.objectDataMap.OrderHeader.OB_PreliminaryVerificationCode__c", value);
$A.util.removeClass(input, 'slds-has-error');
component.set("v.isOkPrelimVerifCode", true);
}else{
var errorLabel = $A.get("$Label.c.OB_enterSevenChar");
input.setCustomValidity(errorLabel);
$A.util.addClass(input, 'slds-has-error');
component.set("v.isOkPrelimVerifCode", false);
}
},
/*
* Author : Morittu Andrea
* Date : 07-Nov-2019
* Task : EVO_Backlog 143
* Description : On change function Promo amex lightning select
*/
onChangePromoloyaltyOffer : function(component, event, helper) {
var currentOptionSelection = component.find('PromoLoyaltyOffer').get('v.value');
if(!$A.util.isEmpty(currentOptionSelection)) {
helper.promoLoyaltySelection_Helper(component, event, helper, currentOptionSelection);
}
},
})
|
JavaScript
|
CL
|
7cdef58574852202d73f903297305fd181f031bb40d95ab1579ddd46a91c6de5
|
module.exports = {
extends: '@ultimaker/stylelint-config/scss',
rules: {
// To be removed once @extends are gone
'at-rule-blacklist': null,
// To be removed once line-heights are unitless
'declaration-property-unit-blacklist': null,
// Only here to supress nesting-depth warnings
'max-nesting-depth': null,
// see: https://stylelint.io/user-guide/rules/no-descending-specificity
'no-descending-specificity': null,
// These can be removed once AutoPrefixer in used in consuming projects
'property-no-vendor-prefix': null,
'value-no-vendor-prefix': null,
},
};
|
JavaScript
|
CL
|
a26f9113bf9b9b405ed735699a03977a0a00fc9c9cccc79e4d8ebdea94369dfe
|
import React, {useState} from 'react';
import {connect, useSelector} from 'react-redux'
import {useFirestoreConnect, isLoaded, isEmpty, firestoreConnect} from 'react-redux-firebase'
import {makeStyles} from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import CircularProgress from '@material-ui/core/CircularProgress';
import Button from '@material-ui/core/Button';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import AddProjectModal from '../components/addProjectModal';
import DeleteProjectsModal from '../components/deleteProjectsModal';
import Layout from '../components/layout';
import {Checkbox} from '@material-ui/core';
import {fieldSort} from '../utils/fieldSort';
import {compose} from 'redux';
function buildProjectsTable(projects, classes, idsToDelete, setIdsToDelete) {
if (isEmpty(projects)) return (
<p style={{textAlign: 'center', marginTop: 40}}>There are no projects to display, try adding one above.</p>
);
return (
<Paper className={classes.root}>
<Table className={classes.table} aria-label="projects table">
<TableHead>
<TableRow>
<TableCell className={classes.checkBoxColumn}>
<Checkbox
indeterminate={idsToDelete.length > 0 && idsToDelete.length < projects.length}
checked={idsToDelete.length === projects.length}
onChange={() => idsToDelete.length === projects.length
? setIdsToDelete([])
: setIdsToDelete(projects.map(project => project.id))
}
/>
</TableCell>
<TableCell>Name</TableCell>
<TableCell>Email</TableCell>
<TableCell>Address</TableCell>
</TableRow>
</TableHead>
<TableBody>
{projects.sort(fieldSort('name')).map(project => (
<TableRow key={project.name}>
<TableCell className={classes.checkBoxColumn}>
<Checkbox
checked={idsToDelete.includes(project.id)}
onChange={() => idsToDelete.includes(project.id)
? setIdsToDelete([...idsToDelete].filter(id => id !== project.id))
: setIdsToDelete([...idsToDelete, project.id])
}
/>
</TableCell>
<TableCell>{project.name}</TableCell>
<TableCell>{project.email}</TableCell>
<TableCell>{project.address}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
);
}
function Projects({auth}) {
const useStyles = makeStyles({
root: {
width: '100%',
overflowX: 'auto',
marginBottom: 20
},
table: {
minWidth: 500,
backgroundColor: '#f2f2f2'
},
headerContainer: {
display: 'inline-flex',
justifyContent: 'space-between',
width: '100%',
alignItems: 'center'
},
deleteButton: {
height: 40,
color: 'red',
marginRight: 10,
borderColor: 'red',
'&:hover': {
background: 'lightred'
}
},
checkBoxColumn: {
width: 50
}
});
const classes = useStyles();
const [addProjectOpen, setAddProjectOpen] = useState(false);
const [deleteProjectOpen, setDeleteProjectOpen] = useState(false);
const [idsToDelete, setIdsToDelete] = useState([]);
const handleClickOpenAddProject = () => {
setAddProjectOpen(true);
};
const handleCloseAddProject = () => {
setAddProjectOpen(false);
};
const handleClickOpenDeleteProject = () => {
setDeleteProjectOpen(true);
};
const handleCloseDeleteProject = () => {
setDeleteProjectOpen(false);
};
const projects = useSelector(state => state.firestore.ordered.projects);
return (
<Layout>
<div className={classes.headerContainer}>
<h1 style={{flexGrow: 1}}>Projects</h1>
{idsToDelete.length > 0 && (
<Button className={classes.deleteButton} variant="outlined" onClick={handleClickOpenDeleteProject}>
Delete Selected
</Button>
)}
<Button style={{height: 40}} variant="outlined" onClick={handleClickOpenAddProject}>
+ Add Project
</Button>
</div>
{!isLoaded(projects)
? <CircularProgress/>
: buildProjectsTable(
projects,
classes,
idsToDelete,
setIdsToDelete
)
}
{isLoaded(auth) && (
<AddProjectModal
open={addProjectOpen}
handleClose={handleCloseAddProject}
auth={auth}
/>
)}
<DeleteProjectsModal
open={deleteProjectOpen}
handleClose={handleCloseDeleteProject}
idsToDelete={idsToDelete}
setIdsToDelete={setIdsToDelete}
/>
</Layout>
);
}
const mapStateToProps = (state) => {
return {
auth: state.firebase.auth,
projects: state.firestore.ordered.projects
}
};
export default compose(
connect(mapStateToProps),
firestoreConnect((props) => {
if (!props.auth.uid) return [];
return [
{
collection: 'projects',
where: ['uid', '==', props.auth.uid]
}
]
})
)(Projects);
|
JavaScript
|
CL
|
afc4bf2c671babf2209fe157304f62f55d6ed2ecdc6968b14dd202c62b1c10e2
|
import { combineReducers } from 'redux';
import * as reducers from './reducers';
const rootReducer = combineReducers({
authentication: reducers.authentication
});
export default rootReducer;
|
JavaScript
|
CL
|
7a5838e1af3a8e1b49f14cae46fbc618969498e94ad5af2b047f669b3c9766c8
|
'use strict';
/*
This is used by electron to setup the application.
It spawns an extra browser window loading `index.html`.
*/
var electron = require('electron');
/*
Hooks for serving files
*/
// This is kind of a middle-ware, establising a hook on file requests
// asking configured hook to handle the file request
// and falling back to just serve the plain file if no hook has
// handled the request
var fileUtils = require('electron-utils/file');
var FileHooks = fileUtils.FileHooks;
// bundles js files using browserify
var BrowserifyHook = fileUtils.BrowserifyHook;
// compiles a less file into css
var LessHook = fileUtils.LessHook;
// provides convenient access to packages in node_modules
var VendorHook = fileUtils.VendorHook;
var app = electron.app;
var protocol = electron.protocol;
var shell = electron.shell;
var BrowserWindow = electron.BrowserWindow;
var win;
function createWindow(url) {
win = new BrowserWindow({
width: 1000,
height: 800,
useContentSize: true,
autoHideMenuBar: true,
});
win.loadURL(url);
// Open the DevTools?
// win.webContents.openDevTools();
// it is important to dereference the created window object
win.on('closed', function() {
win = null;
});
}
app.on('ready', function() {
new FileHooks({
rootDir: __dirname,
hooks: [
new BrowserifyHook({
es6: true,
jsx: true,
cache: true
}),
new LessHook(),
new VendorHook()
]
}).register(protocol);
// the application will be served from the file system
createWindow("file:///");
// make sure that external links are not opened within
// the native application
win.webContents.on('will-navigate', function(e, url) {
if (!url.startsWith('file://')) {
e.preventDefault();
shell.openExternal(url);
}
});
});
// Quit when all windows are closed.
app.on('window-all-closed', function() {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function() {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow();
}
});
// this is used by client-server examples
var server = require('./server/server');
var PORT = 4444;
server.listen(PORT);
|
JavaScript
|
CL
|
98ed371e9fbd418a3aad7aa811ed074a70241d10f1f5496d100c903d6aecd8f7
|
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Layout from '../components/layout';
import { makeFeedsRequest } from '../actions/feeds.actions';
import { filterDistinctChannelIds } from '../helpers/utils';
import { serverActions } from '../actions/server.actions';
class Home extends React.Component {
componentDidMount(){
const { makeFeedsRequest, collections, getAllForUser } = this.props;
if( this.props.user && this.props.user.user ) { //if user locally saved
getAllForUser()
}
makeFeedsRequest( filterDistinctChannelIds(collections) );
}
componentDidUpdate(prevProps){
const { makeFeedsRequest, collections, getAllForUser } = this.props;
const prevFeeds = filterDistinctChannelIds(prevProps.collections);
const currFeeds = filterDistinctChannelIds(collections);
// prevFeeds !== currFeeds is always evaluating to true, since this happens every update i'm just going to check for add / remove
if(prevFeeds.length !== currFeeds.length){
console.log("updated");
makeFeedsRequest( currFeeds );
}
}
render(){
return (
<Layout loggedIn={this.props.loggedIn}/>
)
}
}
// may add wrapper component in between home and layout in order to use logged in status to fetch collections + feeds
// i think feed requests may be sent by collections that needs them
const mapStateToProps = state => {
const { loggingIn, loggedIn, user } = state.authentication;
console.log(state);
return {
loggingIn,
loggedIn,
user,
collections: state.collections
};
};
const mapDispatchToProps = (dispatch) => {
const getAllForUser = serverActions.getAllForUser;
return bindActionCreators({
makeFeedsRequest,
getAllForUser
}, dispatch)
};
export default connect(mapStateToProps, mapDispatchToProps)(Home);
|
JavaScript
|
CL
|
5057cc05647c4aab48f1957b1fddf1a643b059a9fba427f4198a136f07572292
|
'use strict';
///////////////////////////////////////
// Modal window
const modal = document.querySelector('.modal');
const overlay = document.querySelector('.overlay');
const btnCloseModal = document.querySelector('.btn--close-modal');
const btnsOpenModal = document.querySelectorAll('.btn--show-modal');
const nav = document.querySelector('.nav');
const openModal = function (event) {
event.preventDefault();
modal.classList.remove('hidden');
overlay.classList.remove('hidden');
};
const closeModal = function () {
modal.classList.add('hidden');
overlay.classList.add('hidden');
};
//Old schol
// for (let i = 0; i < btnsOpenModal.length; i++)
// btnsOpenModal[i].addEventListener('click', openModal);
btnsOpenModal.forEach(btn => btn.addEventListener('click',openModal));
btnCloseModal.addEventListener('click', closeModal);
overlay.addEventListener('click', closeModal);
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && !modal.classList.contains('hidden')) {
closeModal();
}
});
////////////////////////////////////////////////////////////
//scrolling buttons move div
const btnScrollTo = document.querySelector('.btn--scroll-to');
const section1 = document.querySelector('#section--1');
btnScrollTo.addEventListener('click', function (event) {
const s1coods = section1.getBoundingClientRect();
console.log(s1coods);
console.log(event.target.getBoundingClientRect()); //las medidas son relativas al veuport visible.
//Estas son las cordenadas desde la parte superior hasta el punto donde se hace scroll en el viewport
console.log('Current scroll (X/Y)', window.pageXOffset, pageYOffset);
console.log(
'height/width viewport',
document.documentElement.clientHeight,
document.documentElement.clientWidth
);
//Scrolling
//Old schol: Se teia que tener nocion de las distancias entre los objetos, para ajustar las cordenadas de determiando elemento para ir a ese punto.
// window.scroll(
// s1coods.left + window.pageXOffset,
// s1coods.top + window.pageYOffset
// )
// window.scrollTo({
// left: s1coods.left + window.pageXOffset,
// top: s1coods.top + window.pageYOffset,
// behavior: 'smooth'
// });
//New blood
section1.scrollIntoView({ behavior: 'smooth'});
})
//////////////////////////////////////////////////////////////
///////Page navogation.
//Esta es una solucion pero no es la mejor
// document.querySelectorAll('.nav__link').forEach(function (elements) {
// elements.addEventListener('click', function(event) {
// event.preventDefault();
// // console.log('Link');
// const id = this.getAttribute('href');
// console.log(id);
// document.querySelector(id).scrollIntoView({behavior:'smooth'});
// });
// });
//Event delegation power bubbling.
//1. add event listener to common parent element
//2. Determine what element originated the event
document.querySelector('.nav__links').addEventListener('click',function (event) {
event.preventDefault();
//Matching strategy : ignora los demas clicks y solo esta prestando atencion al click sobre la condicion.
if (event.target.classList.contains('nav__link')) {
console.log('LINK');
const id = event.target.getAttribute('href');
console.log(id);
document.querySelector(id).scrollIntoView({behavior:'smooth'})};
})
//Tabbed component
const tabs = document.querySelectorAll('.operations__tab');
const tabsContainer = document.querySelector('.operations__tab-container');
const tabsContent = document.querySelectorAll('.operations__content');
//Event delegation power bubbling.
//1. add event listener to common parent element
//2. Determine what element originated the event
tabsContainer.addEventListener('click', function (event) {
const clicked = event.target.closest('.operations__tab');
console.log(clicked);
//Guard clause
//Aqui si se ahce click fuera de los botones nuestro guardia retornara la funcion imediatamente.
if(!clicked) return
//Remove active classes and constent area
tabs.forEach(tab => tab.classList.remove('operations__tab--active'));
tabsContent.forEach(content =>
content.classList.remove('operations__content--active'));
//Active tab
clicked.classList.add('operations__tab--active');
//Active content area
console.log(clicked.dataset.tab);
document.querySelector(`.operations__content--${clicked.dataset.tab}`).classList.add('operations__content--active');
})
//Menu fade animation
//Refactoring coding: mira lo que se esta repitiendo y crea una funcion para ello ------DRY
const handleHover = function (event) {
console.log(this, event.currentTarget);
if (event.target.classList.contains('nav__link')) {
const link = event.target;
const siblings = link.closest('.nav').querySelectorAll('.nav__link');
const logo = link.closest('.nav').querySelector('img');
siblings.forEach(element => {
if (element !== link) element.style.opacity = this;
});
logo.style.opacity = this;
}
};
//Call back in actions.
//Passing "argument" into handler
//the handler function only pass one parameter.
nav.addEventListener('mouseover', handleHover.bind(0.5));
nav.addEventListener('mouseout', handleHover.bind(1));
//Sticky navigation
//No es muy recomendable llamar el objeto window, pero aja
//Queremos que la barra de navegacion aparesce justo despues de atravezar toda la primera seccion.
// const initialCoords = section1.getBoundingClientRect();
// console.log(initialCoords);
// //Esto es una pesima idea para el rendimiento pues scroll llama en cada momento la accion y aja.
// window.addEventListener('scroll', function () {
// console.log(window.scrollY); // la posicion de la ventana desde la parte superior.
// window.scrollY > initialCoords.top ? nav.classList.add('sticky') : nav.classList.remove('sticky');
// })
//Sticky navigation: INTERSECTION OBSERVER API
// const obsCallback = function (entries, observe) {
// entries.forEach(entry => {
// console.log(entry);
// })
// };
// const obsOptions = {
// root:null,
// threshold: [0, 0.2],
// };
// const observer = new IntersectionObserver(obsCallback, obsOptions);
// observer.observe(section1);
const header = document.querySelector('.header');
const navHeight = nav.getBoundingClientRect().height;
// console.log(navHeight);
const stickyNav = function (entries) {
const [entry] = entries;
// console.log(entry);
!entry.isIntersecting
? nav.classList.add('sticky')
: nav.classList.remove('sticky');
}
const headerObserver = new IntersectionObserver(stickyNav,{
root:null, //Poque estamos interesados en el veouport.
threshold:0,
rootMargin:`-${navHeight}px` //lo hacemos para que justo antes de crusar al proximo elemento esa porcion del ancho se vea copada por la barra de navegacion sin importar la resolucion de pantallas.
});
headerObserver.observe(header);
// Reveal sections
const allSections = document.querySelectorAll('.section');
const revealSection = function (entries, observer) {
const [entry] = entries;
if(!entry.isIntersecting) return;
entry.target.classList.remove('section--hidden');
observer.unobserve(entry.target); //Me jora el performanse
}
const sectionsObserver = new IntersectionObserver(revealSection,{
root:null,
threshold:0.15,
});
allSections.forEach(section => {
sectionsObserver.observe(section);
//TODO: RECUERDA DESCOMENTAR ESTO
section.classList.add('section--hidden');
});
//Lazy loading images
const imgTargets = document.querySelectorAll('img[data-src]');
// console.log(imgTargets);
const loadImg = function (entries, observer) {
const [entry] = entries;
// console.log(entries);
if(!entry.isIntersecting) return;
//Replace src with data-src
entry.target.src = entry.target.dataset.src;
entry.target.addEventListener('load', function () {
entry.target.classList.remove('lazy-img');
});
observer.unobserve(entry.target);
};
const imgObserver = new IntersectionObserver(loadImg,{
root:null,
threshold:0,
rootMargin: '200px',
});
imgTargets.forEach( img => imgObserver.observe(img));
// Slider.
const slider = function () {
const slides = document.querySelectorAll('.slide');
const btnLeft = document.querySelector('.slider__btn--left');
const btnRight = document.querySelector('.slider__btn--right');
const dotContainer = document.querySelector('.dots');
// const slider = document.querySelector('.slider');
// slider.style.transform = 'scale(0.4) translateX(-800px)';
// slider.style.overflow = 'visible';
let curSlide = 0;
const maxSlide = slides.length;
//FUNCTIONS
//template dots
const createDots = function () {
slides.forEach(function ( _,i) {
dotContainer.insertAdjacentHTML('beforeend', `<button class="dots__dot" data-slide=${i}></button>`);
});
};
const actiavateDot = function (slide) {
document.querySelectorAll('.dots__dot').forEach(dot => dot. classList.remove('dots__dot--active'));
document
.querySelector(`.dots__dot[data-slide="${slide}"]`)
.classList.add('dots__dot--active');
}
// slides.forEach((s, i ) => (s.style.transform = `translateX($ {100 * i}%)`));
//0%, 100%, 200%, 300%;
const goToSlide = function (slide) {
slides.forEach((s,i) => {
(s.style.transform = `translateX(${100 * (i - slide)}%)`)
});
}
//Nxt slide
const nextSlide = function () {
if(curSlide === maxSlide -1 ){
curSlide = 0;
}else{
curSlide++;
}
goToSlide(curSlide);
actiavateDot(curSlide);
}
const prevSlide = function () {
if(curSlide === 0){
curSlide = maxSlide - 1;
}else{
curSlide--;
}
goToSlide(curSlide);
actiavateDot(curSlide);
}
const init = function() {
goToSlide(0);
createDots();
actiavateDot(0);
}
init();
//Event handlers.
btnRight.addEventListener('click', nextSlide
//Ahora bien como funciona esto: hora recuerda que desplazarte a sobre los elementos es basicamente cambiar el valor de transfomr: trasleteX() y asi podramos lograr que se desplace
// if(curSlide === maxSlide -1 ){
// curSlide = 0;
// }else{
// curSlide++;
// }
// slides.forEach((s, i) => (s.style.transform = `translateX($ {100 * (i - curSlide)}%)`));
//Refactori
);
// curSlide =1: -100%, 0%, 100%, 200%
btnLeft.addEventListener('click', prevSlide);
//Implementar desplazamiento con las flechas del teclado
document.addEventListener('keydown', function (event) {
console.log(event); // test para mirar las keys de las teclas key: "ArrowRight", key: "ArrowLeft"
if(event.key === 'ArrowLeft') prevSlide();
event.key === 'ArrowRight' && nextSlide();
});
dotContainer.addEventListener('click',function (event) {
if(event.target.classList.contains('dots__dot')){
// console.log('DOT');
const {slide} = event.target.dataset;
goToSlide(slide);
actiavateDot(slide);
}
})
};
slider();
//Esto es algo muy comun de hacer incluso, los elementos que seleccionamos para trabajar con el DOM se pueden pasar en un objeto que los contenga todos COOLLLLLLLLL .
///////////////////////////////////////////////////
///////////////////////////////////////////////////
///////////////////////////////////////////////////
/////////////////////////////////////////////
////////////////////////////////////////////
//Learning SELECTING, CREATING AND DELETING ELEMENTS.
/*
//Selecting elments
console.log(document.documentElement); //Todo el html
console.log(document.head);
console.log(document.body);
const header = document.querySelector('.header');
const allSection = document.querySelectorAll('.section')
// console.log(allSection); //NodeList(4) array: no uedes eliminar elmentos.
document.getElementById('section--1');
const allButtons = document.getElementsByTagName( 'button' );
// console.log(allButtons); // TMLCollection array: puedes eliminar elementos desde el DOM
console.log(document.getElementsByClassName('btn'));
//Creating and indertting elements
//.insertAdjancentHTML : la que mas le gusta a jonas.
const message = document.createElement('div');
message.classList.add('cookie-message');
// message.textContent = 'We use cookied for improved functionality and analytics.';
message.innerHTML = 'We use cookied for improved functionality and analytics. <button class="btn btn--close-cookie">Go it! </button> ';
header.prepend(message);
// header.append(message);
//crear una copia del mismo elemento y insetarlo
// header.append(message.cloneNode(true));
// header.before(message);
// header.after(message);
//Delate elements
document.querySelector('.btn--close-cookie').addEventListener('click',function () {
message.remove();
})
//Styles
message.style.backgroundColor = '#37383d';
message.style.width = '120%';
console.log(message.style.color); //No tenemos respuesta por que esta propiedad no ha sido definida.
console.log(message.style.backgroundColor);
console.log(getComputedStyle(message).color);
message.style.height = Number.parseFloat(getComputedStyle(message).height, 10) + 30 + 'px';
//manipular varibales css
document.documentElement.style.setProperty('--color-primary', 'tomato');
//Attributes (class, id, src, href, etc)
const logo = document.querySelector('.nav__logo');
console.log(logo.alt);
console.log(logo.src);
//Non-standar
console.log(logo.designer) // No se mostrata pues no es uno de los atributos que se esperaria estar en la etiqueta img.
logo.alt = 'Beautiful minimalist logo';
//se peude agregar
console.log(logo.getAttribute('desinger')); //Obtiene el valor del atributo buscado
logo.setAttribute('company', 'Bankist');
console.log(logo.src); //ruta absoluta
console.log(logo.getAttribute('src'));//Ruta relativa
const link = document.querySelector('.nav__link--btn');
console.log(link.href);
console.log(link.getAttribute('href'));
//Data attributes
console.log(logo.dataset.versionNumber);
*/
//////////////////////////////////////////////////////////
//////Types of Events and Event Handlers.
/*
const h1 = document.querySelector('h1');
h1.addEventListener('mouseenter', function (event) {
alert('addEventListener: Gread! you are reading the heading :D');
})
//Old school for handler events
h1.onmouseenter = function (event) {
alert('addEventListener: Gread! you are reading the heading :D');
}
*/
/////////////////////////////////////////////////////////////
//////Event Propagation in Practice
/*
//Color aleatorio
//rgb(0-255, 0-255, 0-255)
const randomInt = (min, max) => Math.floor( Math.random() * (max - min + 1) + min );
const randomColor = () => `rgb(${randomInt(0, 255)}, ${randomInt(0, 255)}, ${randomInt(0, 255)})`;
// console.log(randomColor(0, 255));
document.querySelector('.nav__link').addEventListener('click', function (event) {
console.log('LINK', event.target, event.currentTarget); //Donde ocurre el click.
console.log(event.currentTarget === this);
this.style.backgroundColor = randomColor();
//Stop propagation
// event.stopPropagation();
})
document
.querySelector('.nav__links')
.addEventListener('click', function (event) {
console.log('CONTAINER', event.target, event.currentTarget);
console.log(event.currentTarget === this);
this.style.backgroundColor = randomColor();
});
document
.querySelector('.nav')
.addEventListener('click', function (event) {
console.log('NAV', event.target, event.currentTarget);
console.log(event.currentTarget === this);
this.style.backgroundColor = randomColor();
});
*/
//////////////////////////////////////////////////////////
///////DOM Traversing
/*
const h1 = document.querySelector('h1');
console.log('========Going downward: children');
//Going downward: child:selecciona todos los elementos con la clase destaca los almacena en un array no importa que tan profundo este el lo encontrara
console.log(h1.querySelectorAll('.highlight'));
console.log(h1.childNodes);
h1.firstElementChild.style.color = 'white';
h1.lastElementChild.style.color = 'tomato';
console.log('========Going upward: parenst');
//Going upwards: parents.
console.log(h1.parentNode);
console.log(h1.parentElement);
h1.closest('.header').style.background = 'var(--gradient-secondary)';
h1.closest('h1').style.background = 'var(--gradient-primary)';
console.log('==========Going sidways: siblings');
//Going sidways: siblings
console.log(h1.previousElementSibling);
console.log(h1.nextElementSibling);
console.log(h1.previousSibling);
console.log(h1.nextSibling);
//Todos los elementos hermano de un elemento incluido el propio elemento
console.log(h1.parentElement.children);
[...h1.parentElement.children].forEach(function (el) {
if(el !== h1 ) el.style.transform = 'scale(0.5)';
});
*/
//Lifecyde DOM evenst
document.addEventListener('DOMContentLoaded', function (event) {
console.log( 'HTML parsed and DOM tree built !' ,event);
})
window.addEventListener('load', function (event) {
console.log('Page fully loaded', event);
});
// window.addEventListener('beforeunload', function (event) {
// event.preventDefault();
// console.log(event);
// event.returnValue = '';
// })
|
JavaScript
|
CL
|
be058044518cc6d4def932d1cab60d58ac027a609dff3cc69f544f43c1fe2b1a
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import TeamMemberCard from './presentational/TeamMemberCard'
import NumberDisplay from './presentational/NumberDisplay'
import { WidthProvider, Responsive } from "react-grid-layout";
import { saveLayoutToLocalStorage, getLayoutFromLocalStorage } from '../utils/utils';
import { selectBasicContributorData } from '../reducers';
const ResponsiveReactGridLayout = WidthProvider(Responsive);
const layoutname = 'member-layout';
let originalLayouts = getLayoutFromLocalStorage(layoutname, 'layouts') || {};
class MemberProfile extends Component {
constructor(props) {
super(props);
this.state = {
layouts: JSON.parse(JSON.stringify(originalLayouts))
};
}
static get defaultProps() {
return {
className: "layout",
cols: { lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 },
rowHeight: 30
}
};
onLayoutChange(layout, layouts) {
saveLayoutToLocalStorage(layoutname, 'layouts', layouts);
this.setState({ layouts: layouts });
}
componentWillMount() {
originalLayouts = getLayoutFromLocalStorage(layoutname, 'layouts') || [];
this.setState({ layouts: JSON.parse(JSON.stringify(originalLayouts)) });
}
render() {
let member = this.props.teamMembers.filter(member => member.login === this.props.match.params.memberId)[0];
return(
<div className="app-page">
<h2>TeamMemberId: {this.props.match.params.memberId}</h2>
<ResponsiveReactGridLayout
className="layout"
cols={{ lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 }}
rowHeight={30}
layouts={this.state.layouts}
onLayoutChange={(layout, layouts) =>
this.onLayoutChange(layout, layouts)
}
>
<div className='box' key="1" data-grid={{ w: 3, h: 9, x: 0, y: 0, minW: 0, minH: 0 }}>
<div className="chart">
<TeamMemberCard taigaId={member.taigaId} githubId={member.login} name={member.login} pictureUrl={member.avatar_url}/>
</div>
</div>
<div className='box' key="3" data-grid={{ w: 2, h: 5, x: 3, y: 0, minW: 0, minH: 0 }}>
<NumberDisplay number={member.totalCommits} statistic="Total Commits"/>
</div>
</ResponsiveReactGridLayout>
</div>
);
}
}
/**
* mapStateToProps
* maps state in redux store (right)
* to component props property (left)
*/
const mapStateToProps = state => {
return {
teamMembers: selectBasicContributorData(state)
}
}
export default connect(mapStateToProps)(MemberProfile)
|
JavaScript
|
CL
|
27c48794c26cba25a2dea5609cfd1faaa03082d0103467055b77c83d3508d9f9
|
/*
This file is part of mongojs. It is subject to the licence terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/KisanHub/mongojs/master/COPYRIGHT. No part of mongojs, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
Copyright © 2015 The developers of mongojs. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/KisanHub/mongojs/master/COPYRIGHT.
*/
var BsonWriter = MongoModule.BsonWriter.BsonWriter
var BsonWriterOverflowException = MongoModule.BsonWriter.BsonWriterOverflowException
var BsonReader = MongoModule.BsonReader.BsonReader
var QueryMessage = MongoModule.Messages.QueryMessage
var InsertMessage = MongoModule.Messages.InsertMessage
var UpdateMessage = MongoModule.Messages.UpdateMessage
var DeleteMessage = MongoModule.Messages.DeleteMessage
var DocumentBsonValue = MongoModule.BsonValues.DocumentBsonValue
var ObjectIdBsonValue = MongoModule.BsonValues.ObjectIdBsonValue
var fromStrictJavascript = MongoModule.BsonValues.fromStrictJavascript
var readMessage = MongoModule.Messages.Message.readMessage
ClassModule.Object.extend
(
module,
function Connection(url, credential, couldNotAuthenticateCallback, authenticatedCallback, writeConcern, sendBufferInitialSize, webSocketProtocolName)
{
this.super(Connection)
this.writeConcern = ClassModule.default(writeConcern, module.WriteConcerns.ACKNOWLEDGED)
// 128Kb
this.sendBufferInitialSize = ClassModule.default(sendBufferInitialSize, 2 << 16)
this.__webSocket = newWebSocket
(
this,
url,
ClassModule.default(webSocketProtocolName, 'binary')
)
this.__resultHandlerTuples = newResultHandlerTuples()
this.__partialMessageBuffer = new ArrayBuffer(0)
this.__partialMessageBufferOffset = 0
this.__beforeOpenSendQueue = []
this.maximumBatchSize = module.maximumBatchSize
this.maximumDocumentSize = module.maximumDocumentSize
this.maximumMessageSize = module.maximumMessageSize
var self = this
function initialiseAfterOpen()
{
var adminDb = new module.AdminDatabase(self)
adminDb.isMaster(function isMasterCallback(serverType, maximumBatchSize, maximumDocumentSize, maximumMessageSize)
{
self.serverType = serverType
self.maximumBatchSize = maximumBatchSize
self.maximumDocumentSize = maximumDocumentSize
self.maximumMessageSize = maximumMessageSize
adminDb.buildInfo(function buildInfoCallback(majorVersion, minorVersion, revisionVersion)
{
self.majorVersion = majorVersion
self.minorVersion = minorVersion
self.revisionVersion = revisionVersion
if (self.serverType.isReplicaSetMemberArbiter)
{
couldNotAuthenticateCallback(-1, 'Server Type isReplicaSetMemberArbiter')
return
}
self.authenticate(credential, couldNotAuthenticateCallback, function interceptAuthenticationCallback(database)
{
database.getLastError(null, null, false, false, function getLastErrorCallback(connectionId, n, syncMillis, writtenTo, err)
{
self.connectionId = connectionId
authenticatedCallback(database)
})
})
})
})
}
initialiseAfterOpen()
},
function authenticate(credential, couldNotAuthenticateCallback, authenticatedCallback)
{
credential.authenticate(this, couldNotAuthenticateCallback, authenticatedCallback)
},
function getLastError(database, callback)
{
this.writeConcern.getLastError(database, callback)
},
function __opened()
{
var self = this
this.__beforeOpenSendQueue.forEach(function(tuple)
{
self.__write(tuple.fullCollectionName, tuple.resultHandler, tuple.message)
})
delete this.__beforeOpenSendQueue
this.send = this.__write
},
function __write(fullCollectionName, resultHandler, message)
{
var bufferSize = this.sendBufferInitialSize
var buffer
var writer
var messageLength
do
{
buffer = new ArrayBuffer(bufferSize)
writer = new BsonWriter(buffer)
try
{
messageLength = message.writeBson(writer)
}
catch (e)
{
if (e instanceof BsonWriterOverflowException)
{
bufferSize *= 2
continue
}
console.warn(e.stack)
throw e
}
break
}
while(true)
if (resultHandler !== null)
{
this.__resultHandlerTuples[message.requestIdInt32] =
{
fullCollectionName: fullCollectionName,
resultHandler: resultHandler
}
}
var actualDataToSend = buffer.slice(0, messageLength)
this.__webSocket.send(actualDataToSend)
return this
},
function __receive(arrayBufferData)
{
this.__partialMessageBuffer = concatenateArrayBuffers(this.__partialMessageBuffer, arrayBufferData, this.__partialMessageBufferOffset)
this.__partialMessageBufferOffset = 0
var reader = new BsonReader(this.__partialMessageBuffer)
var message
var resultHandler
while(reader.hasCompleteMessageAvailable())
{
message = readMessage(reader)
message.process(this, this.__resultHandlerTuples)
}
this.__partialMessageBufferOffset = reader.offset
},
function database(databaseName)
{
return new module.Database(this, databaseName)
},
function adminDatabase()
{
return new module.AdminDatabase(this)
},
function sendCommand(resultHandler, databaseName, unwrappedCommandDocument)
{
// -1 => Return no more than one document, then close the cursor
// 0 => Database default batchSize
// +ve => batch size
return this.sendQuery(resultHandler, databaseName, '$cmd', false, 0, -1, null, unwrappedCommandDocument)
},
function sendQuery(resultHandler, databaseName, collectionName, isSlaveOk, numberToSkipInt32, numberToReturnInt32, returnFieldsSelectorDocument, queryDocument)
{
// same for every kind of message (eg OP_INSERT)
var fullCollectionName = databaseName + '.' + collectionName
var requestIdInt32 = this.__resultHandlerTuples.nextRequestId()
var responseToInt32 = 0
// happens on primary (ie READ_PREFERENCE == primary => isSlaveOk == false)
var flagsInt32 = (isSlaveOk ? 1 << 2 : 0)
return this.send
(
fullCollectionName,
resultHandler,
new QueryMessage
(
requestIdInt32,
responseToInt32,
flagsInt32,
fullCollectionName,
numberToSkipInt32,
numberToReturnInt32,
fromStrictJavascript(queryDocument),
(returnFieldsSelectorDocument === null) ? null : fromStrictJavascript(returnFieldsSelectorDocument)
)
)
},
function sendInsert(databaseName, collectionName, continueOnError, insertDocuments)
{
var fullCollectionName = databaseName + '.' + collectionName
var requestIdInt32 = this.__resultHandlerTuples.nextRequestId()
var responseToInt32 = 0
var flagsInt32 = continueOnError ? 1 : 0
return this.send
(
fullCollectionName,
null,
new InsertMessage
(
requestIdInt32,
responseToInt32,
flagsInt32,
fullCollectionName,
insertDocuments.map(function addObjectIdToInsertDocument(insertDocument)
{
var objectId = ObjectIdBsonValue.generateNewObjectId()
if (insertDocument instanceof DocumentBsonValue)
{
insertDocument.value._id = objectId
}
else
{
insertDocument._id = objectId.toStrictJavaScriptValue()
}
return fromStrictJavascript(insertDocument)
})
)
)
},
function sendUpdate(databaseName, collectionName, isUpsert, isMulti, filterDocument, updateDocument)
{
var fullCollectionName = databaseName + '.' + collectionName
var requestIdInt32 = this.__resultHandlerTuples.nextRequestId()
var responseToInt32 = 0
var flagsInt32 = 0
if (isUpsert)
{
flagsInt32 |= 1
}
if (isMulti)
{
flagsInt32 |= 2
}
return this.send
(
fullCollectionName,
null,
new UpdateMessage
(
requestIdInt32,
responseToInt32,
0,
fullCollectionName,
flagsInt32,
fromStrictJavascript(filterDocument),
fromStrictJavascript(updateDocument)
)
)
},
function sendDelete(databaseName, collectionName, isSingleRemove, filterDocument)
{
var fullCollectionName = databaseName + '.' + collectionName
var requestIdInt32 = this.__resultHandlerTuples.nextRequestId()
var responseToInt32 = 0
var flagsInt32 = isSingleRemove ? 1 : 0
return this.send
(
fullCollectionName,
null,
new DeleteMessage
(
requestIdInt32,
responseToInt32,
0,
fullCollectionName,
flagsInt32,
fromStrictJavascript(filterDocument)
)
)
},
// Replaced int __opened() with a send that just calls write
function send(fullCollectionName, resultHandler, message)
{
this.__beforeOpenSendQueue.push
({
fullCollectionName: fullCollectionName,
resultHandler: resultHandler,
message: message
})
return this
}
)
function concatenateArrayBuffers(buffer0, buffer1, fromOffsetBuffer0)
{
var buffer0Length = buffer0.byteLength - fromOffsetBuffer0
var buffer1Length = buffer1.byteLength
var totalLength = buffer0Length + buffer1Length
var concatenatedUint8Array = new Uint8Array(totalLength)
concatenatedUint8Array.set(new Uint8Array(buffer0, fromOffsetBuffer0), 0)
concatenatedUint8Array.set(new Uint8Array(buffer1), buffer0Length)
return concatenatedUint8Array.buffer
}
function newWebSocket(connection, url, protocol)
{
var webSocket = new WebSocket(url, [protocol])
webSocket.binaryType = 'arraybuffer'
webSocket.onopen = (function(connection)
{
// inside an event, 'this' is... the webSocket
return function(event)
{
connection.__opened()
}
})(connection);
webSocket.onmessage = (function(connection)
{
return function(messageEvent)
{
connection.__receive(messageEvent.data)
}
})(connection);
// TODO: disconnect and reconnect, fail all existing requests with outstanding replies
webSocket.onerror = (function(connection)
{
return function(event)
{
console.warn('Error with WebSocket')
}
})(connection);
return webSocket
}
function newResultHandlerTuples()
{
var handlers = []
handlers.nextRequestIdCounter = 1
handlers.nextRequestId = function nextRequestId()
{
var nextRequestId = this.nextRequestIdCounter
this.nextRequestIdCounter += 1
return nextRequestId
}
return handlers
}
|
JavaScript
|
CL
|
4841066c52e1fd6ffcaa6a7e0dc6db5f19a2fbfd3ccd988bcc3468cbee48d33b
|
import {TemplateGatherer} from 'src/common/template-gatherer';
import {ControlProperties} from 'src/common/control-properties';
import {TemplatingEngine} from 'aurelia-templating';
import {initialize} from 'aurelia-pal-browser';
import {Container} from 'aurelia-dependency-injection';
import {KendoConfigBuilder} from 'src/config-builder';
describe('TemplateGatherer', () => {
let sut;
let container;
let configBuilder;
let templatingEngine;
let controlProperties;
beforeEach(() => {
initialize();
controlProperties = {
getTemplateProperties: jasmine.createSpy()
};
container = new Container();
configBuilder = new KendoConfigBuilder();
container.registerInstance(KendoConfigBuilder, configBuilder);
container.registerInstance(ControlProperties, controlProperties);
templatingEngine = container.get(TemplatingEngine);
sut = templatingEngine.createViewModelForUnitTest(TemplateGatherer);
});
it('throws error when template prop is not supported', () => {
let templateProps = ['template'];
let templates = [{
for: 'unknownTemplate'
}];
let target = {};
let controlName = 'kendoScheduler';
controlProperties.getTemplateProperties.and.returnValue(templateProps);
expect(() => sut.useTemplates(target, controlName, templates)).toThrow(new Error('Invalid template property name: "unknownTemplate", valid values are: template'));
});
it('throws errors when templating support is not enabled', () => {
let templateProps = ['template'];
let templates = [{
for: undefined
}];
let target = {};
let controlName = 'kendoScheduler';
controlProperties.getTemplateProperties.and.returnValue(templateProps);
expect(() => sut.useTemplates(target, controlName, templates)).toThrow(new Error('Templating support is not enabled. Call .kendoTemplateSupport() in main.js or import common/template via require'));
});
it('ignores undefined/null templates', () => {
let templateProps = ['template'];
let templates = [{
for: 'template',
template: undefined
}];
let target = {};
let controlName = 'kendoScheduler';
controlProperties.getTemplateProperties.and.returnValue(templateProps);
sut.useTemplates(target, controlName, templates);
expect(target.hasOwnProperty('template')).toBe(false);
});
it('wraps template in function if kendoTemplate is false', () => {
let templateProps = ['template'];
let templates = [{
for: 'template',
template: 'abcd',
kendoTemplate: false
}];
let target = {};
let controlName = 'kendoScheduler';
controlProperties.getTemplateProperties.and.returnValue(templateProps);
sut.useTemplates(target, controlName, templates);
expect(typeof target.kTemplate).toBe('function');
expect(target.kTemplate()).toBe('abcd');
});
it('doesn\'t wrap template in function if kendoTemplate is true', () => {
let templateProps = ['template'];
let templates = [{
for: 'template',
template: 'abcd',
kendoTemplate: true
}];
let target = {};
let controlName = 'kendoScheduler';
controlProperties.getTemplateProperties.and.returnValue(templateProps);
sut.useTemplates(target, controlName, templates);
expect(target.kTemplate).toBe('abcd');
});
it('support modification of template via callback provided by user', () => {
let callback = jasmine.createSpy();
configBuilder.withTemplateCallback(callback);
let templateProps = ['template'];
let templates = [{
for: 'template',
template: 'abcd'
}];
let target = {};
let controlName = 'kendoScheduler';
controlProperties.getTemplateProperties.and.returnValue(templateProps);
sut.useTemplates(target, controlName, templates);
expect(callback).toHaveBeenCalledWith(target, templates[0], templates[0].template);
});
it('support templates in nested objects', () => {
let templateProps = ['template'];
let templates = [{
for: 'editable.template',
template: 'abcd'
}];
let target = {};
let controlName = 'kendoScheduler';
controlProperties.getTemplateProperties.and.returnValue(templateProps);
sut.useTemplates(target, controlName, templates);
expect(target.kEditable.template()).toBe('abcd');
});
});
|
JavaScript
|
CL
|
f1a444443af7326bf5edc844f7215289fafeb31a177e2d6f2d5afb1c3a4ecaf7
|
import React, { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { useHistory, useParams } from "react-router-dom";
import onClickOutside from "react-onclickoutside";
import { Link, animateScroll as scroll } from "react-scroll";
import MenuModal from "src/modules/menu/components/common/menuModal";
import SwipeMessage from "src/modules/menu/components/common/swipeMessage";
import MenuDetails from "src/modules/menu/components/menuDesktopLayout/menuDetails";
import PriceSummary from "src/modules/menu/components/menuDesktopLayout/priceSummary";
import {
resetFoodPlanRequest,
itemCountRequest,
} from "src/modules/menu/redux/action";
import DayAndDateDetails from "src/modules/menu/components/menuDesktopLayout/dayAndDateDetails";
import Footer from "src/modules/menu/components/common/footer";
import { getShortedDateAndTime } from "src/Utils/menu";
import {
allDayList,
isAccessToken,
removeAllDaysData,
setData,
} from "src/Utils/localStorageUtil";
import { PATH } from "src/constants/path";
import "./index.scss";
function MenuDesktopLayout(props) {
const {
dayListMenus: newUpdatedMenuList,
sideDishDetails,
setSideDishDetails,
handleSelectExtraDish,
handelAddExtra,
handleRemoveDishes,
menuListDots,
} = props;
const [modalPage, setModalPage] = useState(false);
const [swipeMessage, setSwipMessage] = useState(false);
const dispatch = useDispatch();
const router = useHistory();
const QuestionnairesStatus = useSelector((state) => state.Questionnaires);
const handleBack = () => {
router.push(PATH.QUESTIONNAIRES);
};
const selectDay = useParams();
const handleSetActive = (to) => {
router.push(`/menu/${to}`);
};
const handleModalClose = () => {
setModalPage(false);
setTimeout(() => setSwipMessage(true), 2000);
};
useEffect(() => {
removeAllDaysData();
dispatch(resetFoodPlanRequest());
setTimeout(() => setModalPage(true), 2000);
}, []);
const handleNext = () => {
if (isAccessToken()) {
router.push({
pathname: PATH.CHECKOUT,
state: { isMenu: true },
});
} else {
router.push(`/menu/${selectDay.day}/login`);
}
};
const handleCloseSwipMessage = () => {
setSwipMessage(false);
};
const SelectedDayList = Object.keys(newUpdatedMenuList);
const NavList = allDayList.filter((val) => SelectedDayList.includes(val));
const handleFoodSwipe = (day, selectedday) => {
setData(true, "isSwipe");
props.handleSwipeDish(
newUpdatedMenuList[day]?.[selectedday],
`${selectedday}`,
day
);
};
MenuDesktopLayout.handleClickOutside = (e) => {
if (e.target.id == "side_dishes_list") {
console.log("open");
} else {
setSideDishDetails({
...sideDishDetails,
id: "",
type: "",
isOpen: false,
currentday: "",
});
}
};
const handleItemCount = (
foodId,
day,
mealId,
type,
mealtime,
mealName,
mealPrice
) => {
const payloadData = {
foodId,
day,
mealId,
type,
mealtime,
mealName,
mealPrice,
};
dispatch(itemCountRequest(payloadData));
};
return (
<>
<MenuModal show={modalPage} handleModalClose={handleModalClose} />
{NavList.length ? (
<div>
{swipeMessage && !modalPage ? (
<SwipeMessage handleCloseSwipMessage={handleCloseSwipMessage} />
) : null}
</div>
) : null}
{getShortedDateAndTime(newUpdatedMenuList).map((val, i) => {
return (
<div key={i}>
<Link
activeClass='active'
to={val.day}
spy={true}
smooth={true}
hashSpy={true}
delay={500}
isDynamic={false}
onSetActive={handleSetActive}
ignoreCancelEvents={false}
></Link>
<div id={val.day}>
<DayAndDateDetails day={val?.day} date={val.date} />
{newUpdatedMenuList[val.day]?.Breakfast && (
<MenuDetails
foodType='Breakfast'
foodData={val}
menuItemsList={newUpdatedMenuList[val.day]?.Breakfast}
swipeSelection={props?.swipeData}
handleSwipeDish={props.handleSwipeDish}
selectedMealTypes={QuestionnairesStatus.mealType}
handleRemoveDishes={handleRemoveDishes}
handleItemCount={handleItemCount}
additionalFoodItem={sideDishDetails}
handleFoodSwipe={handleFoodSwipe}
handelAddExtra={handelAddExtra}
handleSelectExtraDish={handleSelectExtraDish}
paginationedList={menuListDots?.breakfastDots}
/>
)}
{newUpdatedMenuList[val.day]?.Lunch && (
<MenuDetails
foodType='Lunch'
foodData={val}
menuItemsList={newUpdatedMenuList[val.day]?.Lunch}
swipeSelection={props?.swipeData}
handleSwipeDish={props.handleSwipeDish}
selectedMealTypes={QuestionnairesStatus.mealType}
handleRemoveDishes={handleRemoveDishes}
handleItemCount={handleItemCount}
additionalFoodItem={sideDishDetails}
handleFoodSwipe={handleFoodSwipe}
handelAddExtra={handelAddExtra}
handleSelectExtraDish={handleSelectExtraDish}
paginationedList={menuListDots?.lunchDots}
/>
)}
{newUpdatedMenuList[val.day]?.Dinner && (
<MenuDetails
foodType='Dinner'
foodData={val}
menuItemsList={newUpdatedMenuList[val.day]?.Dinner}
swipeSelection={props?.swipeData}
handleSwipeDish={props.handleSwipeDish}
selectedMealTypes={QuestionnairesStatus.mealType}
handleRemoveDishes={handleRemoveDishes}
handleItemCount={handleItemCount}
additionalFoodItem={sideDishDetails}
handleFoodSwipe={handleFoodSwipe}
handelAddExtra={handelAddExtra}
handleSelectExtraDish={handleSelectExtraDish}
paginationedList={menuListDots?.dinnerDots}
/>
)}
</div>
</div>
);
})}
<Footer handleNext={handleNext} handleBack={handleBack} />
<div className='total_price_container'>
<PriceSummary
totalPrice={newUpdatedMenuList.totalAmount}
handleCheckout={handleNext}
/>
</div>
</>
);
}
const clickOutsideConfig = {
handleClickOutside: () => MenuDesktopLayout.handleClickOutside,
};
export default onClickOutside(MenuDesktopLayout, clickOutsideConfig);
|
JavaScript
|
CL
|
36395c9dd13648b71494588b89343ae51a962466621a9312155a16c4b42f377b
|
'use strict';
/**
* __________________JS template for popup__________________
*
* It will be wrapped with an anonymous function with
* that is called after loading this file
*/
/**
* It overloads and extends the instance of parent PopupObject
*
* @see _common/js/popup-object.js
*/
Object.assign(
$Popup, {
clickHereLinkSelector: '#click-here-link',
clickHereLinkElement: null,
/**
* @see _common/js/popup-object.js:79
*/
onInit: function onInit() {
$Popup.clickHereLinkElement = $Popup.contentElement.querySelector($Popup.clickHereLinkSelector);
if ($Popup.clickHereLinkElement) {
$utils.addEventHandler($Popup.clickHereLinkElement, 'click', function(event) {
$Popup.markAsShowed();
if ($Popup.clickHereLinkElement.href === document.location.href) {
$Popup.close();
event.preventDefault();
return false;
}
return true;
});
}
},
/**
* @see _common/js/popup-object.js:168
*
* this - context of button element
*/
onAcceptButtonClick: function onAcceptButtonClick(event) {
$Popup.markAsShowed();
},
/**
*
*/
markAsShowed: function markAsShowed() {
if (
$utils.isString(window.GLOBAL.countryByIP)
&& window.GLOBAL.countryByIP.length
) {
$utils.cookie(
'lastNotifiedUnsupportedCountry',
window.GLOBAL.countryByIP,
{
'domain': window.GLOBAL.mainDomain || document.domain,
'path': '/'
}
);
}
$utils.consoleLog(
'lastNotifiedUnsupportedCountry = ' +
$utils.cookie('lastNotifiedUnsupportedCountry')
);
}
}
);
|
JavaScript
|
CL
|
dcb4030e93a54bc68875e2f4fdc6f9c7cf29a57297a01f3fde390fd2d7adfc56
|
/**
* Transcriptor
*/
var APP_NAME = 'Transcriptor'
var GC_API_KEY = '__PASTE_YOUR_KEY_HERE__'
var LABEL_ENQ = '#GAS/transcriptor-enq'
var LABEL_DEQ = '#GAS/transcriptor-deq'
var RECIPIENT_ADDRESS = 'example+ml@gmail.com'
var REPLY_TO_ADDRESS = 'example+transcriptor@gmail.com'
/**
* Specify the language used in target audio files
* https://cloud.google.com/speech-to-text/docs/languages
*/
var LANG_CODE = 'en-US'
var CACHE_INVALIDATION = false
/**
* Walk through the target emails
* https://developers.google.com/apps-script/reference/gmail/
*/
// eslint-disable-next-line no-unused-vars
function main () {
var targetLabel = GmailApp.getUserLabelByName(LABEL_ENQ)
var notifiedLabel = GmailApp.getUserLabelByName(LABEL_DEQ)
var threads = targetLabel.getThreads().reverse()
for (var i in threads) {
var thread = threads[i]
var messages = thread.getMessages()
var transcripts = []
ensureEmailQuota()
// TODO: Support dead letter queue and retry feature
thread.removeLabel(targetLabel)
for (var j in messages) {
transcripts.push(transcribe(messages[j]).join('\n\n'))
}
var result = [
transcripts.join('\n\n---\n\n'),
thread.getPermalink(),
ScriptApp.getService().getUrl()
]
Logger.log(result)
send(thread.getId(), result.join('\n\n'))
thread.addLabel(notifiedLabel)
}
Logger.log('Done.')
}
/**
* @param {GmailMessage} message
* @returns {[String]} Transcripts
*/
function transcribe (message) {
var attachments = message.getAttachments()
var transcripts = []
for (var i in attachments) {
transcripts.push(recognize(attachments[i]))
}
transcripts.push(message.getPlainBody())
return transcripts
}
/**
* https://developers.google.com/apps-script/reference/cache/cache
* @param {Blob} message
* @returns {String} The most confident transcript
*/
function recognize (blob) {
var cache = CacheService.getScriptCache()
var audio = Utilities.base64EncodeWebSafe(blob.getBytes())
var cacheKey = generateKey(audio)
if (CACHE_INVALIDATION) {
cache.removeAll([cacheKey])
}
var content = cache.get(cacheKey)
if (content == null) {
content = fetch(audio)
cache.put(cacheKey, content, 6 * 60 * 60)
}
var res = JSON.parse(content)
Logger.log(res)
if (res.hasOwnProperty('results') && res['results'].length > 0 && res['results'][0]['alternatives'].length > 0) {
return res['results'][0]['alternatives'][0]['transcript']
}
return '__NO_TRANSCRIPT__'
}
/**
* https://cloud.google.com/speech-to-text/docs/basics
* https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app
* @param {String} audio
* @returns {String} content in JSON
*/
function fetch (audio) {
var data = {
'config': {
'languageCode': LANG_CODE,
'enableWordTimeOffsets': false
},
'audio': {
'content': audio
}
}
Logger.log(data)
try {
var response = UrlFetchApp.fetch('https://speech.googleapis.com/v1/speech:recognize?key=' + GC_API_KEY, {
method: 'POST',
contentType: 'application/json; charset=utf-8',
payload: JSON.stringify(data)
})
Logger.log(response)
return response.getContentText()
} catch (e) {
Logger.log(e.message)
throw e
}
}
/**
* @param {String} target
*/
function generateKey (target) {
return Utilities.base64EncodeWebSafe(Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_1, target))
}
/**
* https://developers.google.com/apps-script/reference/mail/mail-app
*/
function ensureEmailQuota () {
var quota = MailApp.getRemainingDailyQuota()
Logger.log('Remaining email quota: ' + quota)
if (quota <= 0) {
throw new Error('Aborting script. Wait for the email quota on tomorrow.')
}
}
/**
* @param {String} subject
* @param {String} body
*/
function send (subject, body) {
MailApp.sendEmail({
name: APP_NAME,
replyTo: REPLY_TO_ADDRESS,
to: RECIPIENT_ADDRESS,
subject: ['[' + APP_NAME + ']', subject].join(' '),
body: body
})
}
|
JavaScript
|
CL
|
b21dd151ba25f8fe17581a31d40966cea0546c70f6151e5932f5f8a5372c00b9
|
'use strict'
let readline = require('readline');
/**
* Text based input and output wrapper.
*/
class View {
/**
* @param {NodeJS.Socket} reader
* @param {NodeJS.Socket} writer
*/
constructor(reader, writer) {
this.reader = reader;
this.writer = writer;
this._cli = readline.createInterface({
input: reader,
output: writer
});
}
/**
* Waits for a message and then calls the callback passing the message ínto it.
* @param {Function} callback
*/
read(callback) {
if (typeof callback !== 'function') throw new TypeError('callback must be a function');
this._cli.question('enter command: ', callback);
}
/**
* Outputs a message.
* @param {*} message
*/
show(message) {
this._cli.write(message);
}
/**
* Outputs an error message.
* @param {*} message an error message
*/
showError(message) {
this.show('! ' + (message || 'unknown error')+'\n');
}
/**
* Closes input and output.
*/
destroy() {
this._cli.close();
}
}
module.exports = View;
|
JavaScript
|
CL
|
452c3f9d47ce56831e78a61be6a4c1bda31441bad3a19558e49ceb1d3aea333c
|
//This is an example code for Navigation Drawer with Custom Side bar//
import React, { Component } from 'react';
//import react in our code.
import {
View,
StyleSheet,
Dimensions,
Image,
TouchableOpacity,
Platform,
Text,
Settings,
} from 'react-native';
// import all basic components
import { Icon } from 'react-native-elements'
//For React Navigation 4+
import {createAppContainer} from 'react-navigation';
import {createDrawerNavigator} from 'react-navigation-drawer';
import {createStackNavigator} from 'react-navigation-stack';
//Import all the screens
import MandorBrandList from "./MandorBrandList"
import MandorHome from "./MandorHome"
import MandorMessages from "./MandorMessages"
import MandorSettings from "./MandorSettings"
import MandorPost from "./MandorPost"
import MandorLogout from "./MandorLogout"
//Import Custom Sidebar
import CustomSidebarMenu from './CustomSidebarMenu';
import PostList from './posts/PostList';
import CreatePost from './posts/CreatePost';
global.currentScreenIndex = 0;
//Navigation Drawer Structure for all screen
class NavigationDrawerStructure extends Component {
constructor() {
super();
this.state = {
uid: ''
}
}
signOut = () => {
firebase.auth().signOut().then(() => {
this.props.navigation.navigate('Login')
})
.catch(error => this.setState({ errorMessage: error.message }))
}
//Top Navigation Header with Donute Button
toggleDrawer = () => {
//Props to open/close the drawer
this.props.navigationProps.toggleDrawer();
};
render() {
return (
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity onPress={this.toggleDrawer.bind(this)}>
{/*Donute Button Image */}
<Image
source={require('../assets/drawer.png')}
style={{ width: 25, height: 25, marginLeft: 20 }}
/>
</TouchableOpacity>
</View>
);
}
}
//Stack Navigator for the First Option of Navigation Drawer
const MandorHome_Activity = createStackNavigator({
//All the screen from the First Option will be indexed here
First: {
screen: MandorHome,
navigationOptions: ({ navigation }) => ({
title: 'Hey Mandor',
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: '#FF9800',
},
headerTintColor: '#fff',
}),
},
});
//Stack Navigator for the Second Option of Navigation Drawer
const MandorMessages_Activity = createStackNavigator({
//All the screen from the Second Option will be indexed here
Second: {
screen: MandorMessages,
navigationOptions: ({ navigation }) => ({
title: 'Messages',
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerRight: (
<Icon
raised
name='arrow-left'
type='font-awesome'
onPress={() => {navigation.goBack(null)}}
/>
),
headerStyle: {
backgroundColor: '#FF9800',
},
headerTintColor: '#fff',
}),
},
});
//Stack Navigator for the Third Option of Navigation Drawer
const MandorSettings_Activity = createStackNavigator({
//All the screen from the Third Option will be indexed here
Third: {
screen: MandorSettings,
navigationOptions: ({ navigation }) => ({
title: 'Settings',
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerRight: (
<Icon
raised
name='arrow-left'
type='font-awesome'
onPress={() => {navigation.goBack(null)}}
/>
),
headerStyle: {
backgroundColor: '#FF9800',
},
headerTintColor: '#fff',
}),
},
});
//Stack Navigator for the Third Option of Navigation Drawer
const MandorPost_Activity = createStackNavigator({
//All the screen from the Third Option will be indexed here
Fourth: {
screen: MandorPost,
navigationOptions: ({ navigation }) => ({
title: 'Post',
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerRight: (
<Icon
raised
name='arrow-left'
type='font-awesome'
onPress={() => {navigation.goBack(null)}}
/>
),
headerStyle: {
backgroundColor: '#FF9800',
},
headerTintColor: '#fff',
}),
},
});
//Stack Navigator for the Third Option of Navigation Drawer
const MandorBrandList_Activity = createStackNavigator({
//All the screen from the Third Option will be indexed here
Five: {
screen: MandorBrandList,
navigationOptions: ({ navigation }) => ({
title: 'Brands',
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerRight: (
<Icon
raised
name='arrow-left'
type='font-awesome'
onPress={() => {navigation.goBack(null)}}
/>
),
headerStyle: {
backgroundColor: '#FF9800',
},
headerTintColor: '#fff',
}),
},
});
//Stack Navigator for the Third Option of Navigation Drawer
const MandorLogout_Activity = createStackNavigator({
//All the screen from the Third Option will be indexed here
Five: {
screen: MandorLogout,
navigationOptions: ({ navigation }) => ({
title: 'Brands',
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerRight: (
<Icon
raised
name='arrow-left'
type='font-awesome'
onPress={() => {navigation.goBack(null)}}
/>
),
headerStyle: {
backgroundColor: '#FF9800',
},
headerTintColor: '#fff',
}),
},
});
//Stack Navigator for the Third Option of Navigation Drawer
const MandorPostList_Activity = createStackNavigator({
//All the screen from the Third Option will be indexed here
Six: {
screen: PostList,
navigationOptions: ({ navigation }) => ({
title: 'Post List',
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerRight: (
<Icon
raised
name='arrow-left'
type='font-awesome'
onPress={() => {navigation.goBack(null)}}
/>
),
headerStyle: {
backgroundColor: '#FF9800',
},
headerTintColor: '#fff',
}),
},
});
const MandorCreatePost_Activity = createStackNavigator({
//All the screen from the Third Option will be indexed here
Six: {
screen: CreatePost,
navigationOptions: ({ navigation }) => ({
title: 'Create Post',
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerRight: (
<Icon
raised
name='arrow-left'
type='font-awesome'
onPress={() => {navigation.goBack(null)}}
/>
),
headerStyle: {
backgroundColor: '#FF9800',
},
headerTintColor: '#fff',
}),
},
});
export default class MandorIndex extends React.Component {
render() {
return (
<React.Fragment>
<AppContainer />
</React.Fragment>
);
}
}
//Drawer Navigator Which will provide the structure of our App
const DrawerNavigatorExample = createDrawerNavigator(
{
//Drawer Optons and indexing
MandorHome: {
screen: MandorHome_Activity,
navigationOptions: {
drawerLabel: 'Home',
},
},
MandorMessages: {
screen: MandorMessages_Activity,
navigationOptions: {
drawerLabel: 'Messages',
},
},
MandorSettings: {
screen: MandorSettings_Activity,
navigationOptions: {
drawerLabel: 'Settings',
},
},
MandorPost: {
screen: MandorPost_Activity,
navigationOptions: {
drawerLabel: 'Post',
},
},
MandorBrands: {
screen: MandorBrandList_Activity,
navigationOptions: {
drawerLabel: 'Brands',
},
},
MandorLogout: {
screen: MandorLogout_Activity,
navigationOptions: {
drawerLabel: 'Logout',
},
},
NavScreen7: {
screen: MandorPostList_Activity,
navigationOptions: {
drawerLabel: 'Post List',
},
},
NavScreen8: {
screen: MandorCreatePost_Activity,
navigationOptions: {
drawerLabel: 'Create Post',
},
},
},
{
//For the Custom sidebar menu we have to provide our CustomSidebarMenu
contentComponent: CustomSidebarMenu,
//Sidebar width
drawerWidth: Dimensions.get('window').width - 130,
}
);
const AppContainer = createAppContainer(DrawerNavigatorExample);
|
JavaScript
|
CL
|
fdbddbbd0694dadf38dbee52b8809ca3280abaaf9719aa7e5963143faec33b73
|
#!/usr/bin/env node
const readline = require('readline');
const utils = require('./utils');
const output = require('./output'); // Small utility for conveniently writing to stdout by Mike Bostock
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
// Initial start time to be measured against when the stream is closed
const duration = process.hrtime();
// Report issued on end
const totalReport = {
throughputRate: 0,
totalBytes: 0,
timeElapsed: 0, // In seconds
linesRead: 0
}
rl.on('line', function (line) {
const lineTime = process.hrtime();
const lineBuf = Buffer.from(line, 'utf8');
// Report issued per line
const lineReport = {
bytes: 0,
timeElapsed: 0
}
// Store the current total bytes to be referenced in subsequent lines
totalReport.totalBytes += lineReport.bytes = lineBuf.byteLength;
totalReport.linesRead++;
// Measure the time since starting the timer
lineReport.timeElapsed = utils.time.getSecondsFromHRTime(process.hrtime(lineTime));
output(lineReport);
})
rl.on('close', function () {
// Allow the user to skip the human readable output
if (!utils.parseCLIArgs('--pure', process.argv)) {
// Measure the totals
totalReport.timeElapsed = utils.time.getSecondsFromHRTime(process.hrtime(duration));
totalReport.throughputRate = `${totalReport.totalBytes / totalReport.timeElapsed} bytes/sec`;
const humanReport =
`
The input took ${totalReport.timeElapsed} seconds to process
at a rate of ${totalReport.throughputRate} bytes per second.
There were ${totalReport.linesRead} lines
at a total of ${totalReport.totalBytes} bytes.
`;
process.stdout.write(humanReport);
}
});
|
JavaScript
|
CL
|
cae3c92976f0483947471852d0d2ff8fe80c7e2b4bf6694ef47133bba704cdd1
|
import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import router from 'umi/router';
import Link from 'umi/link';
import {
Row,
Col,
Card,
Form,
Input,
Select,
Icon,
Button,
Dropdown,
Menu,
DatePicker,
Modal,
Steps,
Radio,
Divider,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardFormRow from '@/components/StandardFormRow';
import StandarInfoData from '@/components/StandarInfoData';
import AdvancedTable from '@/components/AdvancedTable';
import styles from './MemberList.less';
const FormItem = Form.Item;
const { Step } = Steps;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const owners = [
{
id: 'wzj',
name: '我自己',
},
{
id: 'wjh',
name: '吴家豪',
},
{
id: 'zxx',
name: '周星星',
},
{
id: 'zly',
name: '赵丽颖',
},
{
id: 'ym',
name: '姚明',
},
];
@Form.create()
class AddMemberForm extends PureComponent {
constructor(props) {
super(props);
this.state = {
formVals: {
name: '',
sex: '',
phone: '',
//birthday:'',
target: '0',
template: '0',
frequency: 'month',
headimgurl: 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png',
card_number: '',
membership_uuid: null,
coaches_uuid: [],
wechat: '',
email: '',
id_card: '',
company: '',
source_uuid: '',
},
currentStep: 0,
};
this.formLayout = {
labelCol: { span: 5 },
wrapperCol: { span: 15 },
};
}
handleNext = currentStep => {
const { form, handleAddMember } = this.props;
const { formVals: oldValue } = this.state;
form.validateFields((err, fieldsValue) => {
if (err) return;
const formVals = { ...oldValue, ...fieldsValue };
this.setState(
{
formVals,
},
() => {
if (currentStep < 3) {
this.forward();
} else {
handleAddMember(formVals)
//handleUpdate(formVals);
}
},
);
});
};
backward = () => {
const { currentStep } = this.state;
this.setState({
currentStep: currentStep - 1,
});
};
forward = () => {
const { currentStep } = this.state;
this.setState({
currentStep: currentStep + 1,
});
};
renderContent = (currentStep, formVals) => {
const { form } = this.props;
if (currentStep === 1) {
return [
<FormItem key="headimgurl" {...this.formLayout} label="人脸拍照">
{form.getFieldDecorator('headimgurl', {
initialValue: formVals.headimgurl,
})(
<div className={styles.operList}>
<div className={styles.avatar}>
<img src="https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png"/>
</div>
<div className={styles.btns}>
<Button type="primary">拍摄</Button>
<Button>上传</Button>
</div>
<Input type="hidden"/>
</div>,
)}
</FormItem>,
<FormItem key="card_number" {...this.formLayout} label="实体卡号">
{form.getFieldDecorator('card_number', {
initialValue: formVals.card_number,
})(
<div className={styles.cardInfo}>
<div className={styles.inp}>
<Input defaultValue={formVals.card_number} placeholder="请输入实体卡号"/>
<Button type="primary">刷卡</Button>
</div>
<p className={styles.msg}>
手动输入或通过读卡器、刷卡器录入卡号
</p>
</div>,
)}
</FormItem>,
<FormItem key="fingerprint" {...this.formLayout} label="指纹信息">
{form.getFieldDecorator('fingerprint', {
initialValue: formVals.fingerprint,
})(
<div className={styles.cardInfo}>
<div className={styles.inp}>
<Input disabled={true} style={{ textAlign: 'center' }} value="未采集"/>
<Button type="primary">采集</Button>
</div>
<p className={styles.msg}>
点击采集,根据提示完成指纹录入
</p>
</div>,
)}
</FormItem>,
];
}
if (currentStep === 2) {
return [
<StandardFormRow title="维护会籍" labelCol={5} wrapperCol={15} key="1">
<FormItem key="membership_uuid">
{form.getFieldDecorator('membership_uuid', {
initialValue: formVals.membership_uuid,
})(
<Select
showSearch
optionFilterProp="children"
style={{ width: '100%' }}
placeholder="请选择会籍"
>
{owners.map(owner => (
<Option key={owner.id} value={owner.id}>
{owner.name}
</Option>
))}
</Select>,
)}
</FormItem>
<p className={styles.msg}>
仅为方便管理,与业绩划分并无直接关系最多可选1位会籍
</p>
</StandardFormRow>,
<StandardFormRow title="维护教练" labelCol={5} wrapperCol={15} key="2">
<FormItem key="coaches_uuid">
{form.getFieldDecorator('coaches_uuid', {
initialValue: formVals.coaches_uuid,
})(
<Select
mode="multiple"
style={{ width: '100%' }}
placeholder="请选择教练"
>
{owners.map(owner => (
<Option key={owner.id} value={owner.id}>
{owner.name}
</Option>
))}
</Select>,
)}
<p className={styles.msg}>
仅为方便管理,与业绩划分并无直接关系不限数量
</p>
</FormItem>
</StandardFormRow>,
];
}
if (currentStep === 3) {
return [
<FormItem key="wechat" {...this.formLayout} label="微信">
{form.getFieldDecorator('wechat', {
initialValue: formVals.wechat,
})(<Input placeholder="请输入微信号"/>)}
</FormItem>,
<FormItem key="email" {...this.formLayout} label="邮箱">
{form.getFieldDecorator('email', {
initialValue: formVals.email,
})(<Input placeholder="请输入邮箱号"/>)}
</FormItem>,
<FormItem key="id_card" {...this.formLayout} label="身份证号">
{form.getFieldDecorator('id_card', {
initialValue: formVals.id_card,
})(<Input placeholder="请输入身份证号"/>)}
</FormItem>,
<FormItem key="company" {...this.formLayout} label="所在单位">
{form.getFieldDecorator('company', {
initialValue: formVals.company,
})(<Input placeholder="请输入所在单位"/>)}
</FormItem>,
<FormItem key="source_uuid" {...this.formLayout} label="来源渠道">
{form.getFieldDecorator('source_uuid', {
initialValue: formVals.source_uuid,
})(<Input placeholder="请输入来源渠道"/>)}
</FormItem>,
];
}
return [
<FormItem key="name" {...this.formLayout} label="姓名">
{form.getFieldDecorator('name', {
rules: [{ required: true, message: '请输入姓名' }],
initialValue: formVals.name,
})(<Input placeholder="请输入姓名"/>)}
</FormItem>,
<FormItem key="sex" {...this.formLayout} label="性别">
{form.getFieldDecorator('sex', {
rules: [{ required: true, message: '请选择性别' }],
initialValue: formVals.sex,
})(
<RadioGroup>
<Radio value="1">男</Radio>
<Radio value="2">女</Radio>
</RadioGroup>,
)}
</FormItem>,
<FormItem key="birthday" {...this.formLayout} label="生日">
{form.getFieldDecorator('birthday', {
initialValue: formVals.birthday && moment(moment(formVals.birthday), 'YYYY-MM-DD'),
})(
<DatePicker
style={{ width: '100%' }}
format="YYYY-MM-DD"
placeholder="请选择出生日期"
/>,
)}
</FormItem>,
<FormItem key="phone" {...this.formLayout} label="手机号码">
{form.getFieldDecorator('phone', {
rules: [{ required: true, message: '请输入手机号码' }],
initialValue: formVals.phone,
})(<Input placeholder="请输入手机号码"/>)}
</FormItem>,
];
};
renderFooter = currentStep => {
const { handleModalVisible } = this.props;
if (currentStep === 1 || currentStep === 2) {
return [
<Button key="back" style={{ float: 'left' }} onClick={this.backward}>
上一步
</Button>,
<Button key="cancel" onClick={() => handleModalVisible()}>
取消
</Button>,
<Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
下一步
</Button>,
];
}
if (currentStep === 3) {
return [
<Button key="back" style={{ float: 'left' }} onClick={this.backward}>
上一步
</Button>,
<Button key="cancel" onClick={() => handleModalVisible()}>
取消
</Button>,
<Button key="submit" type="primary" onClick={() => this.handleNext(currentStep)}>
完成
</Button>,
];
}
return [
<Button key="cancel" onClick={() => handleModalVisible()}>
取消
</Button>,
<Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
下一步
</Button>,
];
};
render() {
const { modalVisible, handleModalVisible } = this.props;
const { currentStep, formVals } = this.state;
return (
<Modal
className={styles.memberModal}
width={550}
bodyStyle={{ padding: '32px 40px 48px' }}
destroyOnClose
title="新增会员"
maskClosable={false}
visible={modalVisible}
footer={this.renderFooter(currentStep)}
onCancel={() => handleModalVisible()}
>
<Steps style={{ marginBottom: 28 }} size="small" current={currentStep}>
<Step title="基本"/>
<Step title="打卡"/>
<Step title="维护"/>
<Step title="更多"/>
</Steps>
{this.renderContent(currentStep, formVals)}
</Modal>
);
}
}
@Form.create()
class EditMemberForm extends PureComponent {
constructor(props) {
super(props);
}
renderContent = () => {
const { form } = this.props;
return (
<div className={styles.editForm}>
<div className={styles.card}>
<p className={styles.title}>基本信息</p>
<Row gutter={16}>
<Col lg={12} sm={24}>
<StandardFormRow title="姓名" labelCol={6} wrapperCol={18}>
<FormItem key="membership">
{form.getFieldDecorator('membership', {
initialValue: '',
})(<Input placeholder="请输入姓名"/>)}
</FormItem>
</StandardFormRow>
</Col>
<Col lg={12} sm={24}>
<StandardFormRow title="性别" labelCol={6} wrapperCol={18}>
<FormItem key="sex">
{form.getFieldDecorator('sex', {
initialValue: '1',
})(
<Select
style={{ width: '100%' }}
placeholder="请选择性别"
>
<Option key="1" value="1">
男
</Option>
<Option key="2" value="2">
女
</Option>
</Select>,
)}
</FormItem>
</StandardFormRow>
</Col>
</Row>
<Row gutter={16}>
<Col lg={12} sm={24}>
<StandardFormRow title="生日" labelCol={6} wrapperCol={18}>
<FormItem key="born">
{form.getFieldDecorator('born', {})(
<DatePicker
style={{ width: '100%' }}
format="YYYY-MM-DD"
placeholder="请选择出生日期"
/>,
)}
</FormItem>
</StandardFormRow>
</Col>
<Col lg={12} sm={24}>
<StandardFormRow title="手机号" labelCol={6} wrapperCol={18}>
<FormItem key="phone">
{form.getFieldDecorator('phone', {
initialValue: '',
})(
<Input placeholder="请输入手机号码"/>,
)}
</FormItem>
</StandardFormRow>
</Col>
</Row>
</div>
<div className={styles.card}>
<p className={styles.title}>打卡信息</p>
<Row gutter={16}>
<Col lg={12} sm={24}>
<StandardFormRow title="人脸拍照" labelCol={6} wrapperCol={18}>
<FormItem key="photo">
{form.getFieldDecorator('photo', {
initialValue: '',
})(
<Input type="hidden"/>,
)}
</FormItem>
<div className={styles.operList}>
<div className={styles.avatar}>
<img src="https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png"/>
</div>
<div className={styles.btns}>
<Button type="primary">拍摄</Button>
<Button>上传</Button>
</div>
</div>
</StandardFormRow>
</Col>
</Row>
<Row gutter={16}>
<Col lg={12} sm={24}>
<StandardFormRow title="实体卡号" labelCol={6} wrapperCol={18}>
<div className={styles.cardBox}>
<FormItem key="card">
{form.getFieldDecorator('card', {
initialValue: '',
})(
<Input placeholder="请输入实体卡号"/>,
)}
</FormItem>
<Button>刷卡</Button>
</div>
<p className={styles.msg}>手动输入或通过读卡器、刷卡器录入卡号</p>
</StandardFormRow>
</Col>
<Col lg={12} sm={24}>
<StandardFormRow title="指纹信息" labelCol={6} wrapperCol={18}>
<div className={styles.cardBox}>
<FormItem key="fingerprint">
{form.getFieldDecorator('fingerprint', {
initialValue: '未采集',
})(
<Input disabled={true} style={{ textAlign: 'center' }}/>,
)}
</FormItem>
<Button>采集</Button>
</div>
<p className={styles.msg}>点击采集,根据提示完成指纹录入</p>
</StandardFormRow>
</Col>
</Row>
</div>
<div className={styles.card}>
<p className={styles.title}>维护信息</p>
<Row gutter={16}>
<Col lg={12} sm={24}>
<StandardFormRow title="维护会籍" labelCol={5} wrapperCol={18}>
<FormItem key="membership">
{form.getFieldDecorator('membership', {
initialValue: '',
})(
<Select
showSearch
optionFilterProp="children"
style={{ width: '100%' }}
placeholder="请选择会籍"
>
{owners.map(owner => (
<Option key={owner.id} value={owner.id}>
{owner.name}
</Option>
))}
</Select>,
)}
</FormItem>
<p className={styles.msg}>
仅为方便管理,与业绩划分并无直接关系最多可选1位会籍
</p>
</StandardFormRow>
</Col>
<Col lg={12} sm={24}>
<StandardFormRow title="维护教练" labelCol={5} wrapperCol={18}>
<FormItem key="coach">
{form.getFieldDecorator('coach', {
initialValue: [],
})(
<Select
mode="multiple"
style={{ width: '100%' }}
placeholder="请选择教练"
>
{owners.map(owner => (
<Option key={owner.id} value={owner.id}>
{owner.name}
</Option>
))}
</Select>,
)}
<p className={styles.msg}>
仅为方便管理,与业绩划分并无直接关系不限数量
</p>
</FormItem>
</StandardFormRow>
</Col>
</Row>
</div>
<div className={styles.card}>
<p className={styles.title}>更多信息</p>
<Row gutter={16}>
<Col lg={12} sm={24}>
<StandardFormRow title="微信" labelCol={5} wrapperCol={18}>
<FormItem key="wx">
{form.getFieldDecorator('wx', {
initialValue: '',
})(<Input placeholder="请输入微信号"/>)}
</FormItem>
</StandardFormRow>
</Col>
<Col lg={12} sm={24}>
<StandardFormRow title="身份证号" labelCol={5} wrapperCol={18}>
<FormItem key="IDcard">
{form.getFieldDecorator('IDcard', {
initialValue: '',
})(<Input placeholder="请输入身份证号"/>)}
</FormItem>
</StandardFormRow>
</Col>
</Row>
<Row gutter={16}>
<Col lg={12} sm={24}>
<StandardFormRow title="邮箱" labelCol={5} wrapperCol={18}>
<FormItem key="email">
{form.getFieldDecorator('email', {
initialValue: '',
})(<Input placeholder="请输入邮箱"/>)}
</FormItem>
</StandardFormRow>
</Col>
<Col lg={12} sm={24}>
<StandardFormRow title="所在单位" labelCol={5} wrapperCol={18}>
<FormItem key="company">
{form.getFieldDecorator('company', {
initialValue: '',
})(<Input placeholder="请请输入所在单位"/>)}
</FormItem>
</StandardFormRow>
</Col>
</Row>
<Row gutter={16}>
<Col lg={12} sm={24}>
<StandardFormRow title="来源渠道" labelCol={5} wrapperCol={18}>
<FormItem key="channel">
{form.getFieldDecorator('channel', {
initialValue: '',
})(<Input placeholder="请输入来源渠道"/>)}
</FormItem>
</StandardFormRow>
</Col>
</Row>
</div>
</div>
);
};
handleSubmit(e) {
const _this = this;
e.preventDefault();
const { form } = this.props;
form.validateFields((err, fieldsValue) => {
if (!err) {
console.log(fieldsValue);
}
});
}
render() {
const { editModalVisible, handleEditModalVisible } = this.props;
return (
<Modal
width={750}
bodyStyle={{ padding: '32px 40px 48px' }}
destroyOnClose
title="编辑会员"
maskClosable={false}
visible={editModalVisible}
onOk={this.handleSubmit.bind(this)}
onCancel={() => handleEditModalVisible()}
>
{this.renderContent()}
</Modal>
);
}
}
@connect(({ member, loading }) => ({
member,
loading: loading.models.member,
}))
@Form.create()
class MemberList extends PureComponent {
state = {
expandForm: false,
modalVisible: false,
editModalVisible: false,
form_values: [],
page: 1,
pageSize: 10,
};
columns = [ //sortUp 1:默认不排序 2:升序 3:降序
{
title: '会员基本信息',
hasSort: false,
children: [
{
title: '姓名',
sortUp: 1,
hasSort: true,
sort_column: 'name',
},
{
title: '年龄',
sortUp: 1,
hasSort: true,
sort_column: 'age',
},
],
},
{
title: '会员卡号',
hasSort: false,
children: [
{
title: '录入时间',
sortUp: 1,
hasSort: true,
sort_column: 'created_at',
},
],
},
{
title: '到期时间',
hasSort: true,
sortUp: 1,
sort_column: 'expire',
children: [
{
title: '维护会籍',
hasSort: false,
},
],
},
{
title: '剩余课时',
hasSort: true,
sortUp: 1,
sort_column: 'has_course_count',
children: [
{
title: '维护教练',
hasSort: false,
},
],
},
{
title: '上次打卡',
hasSort: true,
sortUp: 1,
sort_column: 'last_sign_time',
},
{
title: '上次消课',
hasSort: true,
sortUp: 1,
sort_column: 'last_in_class_time',
},
{
title: '消费总额',
hasSort: true,
sortUp: 1,
sort_column: 'total_amount',
},
{
title: '操作',
},
];
componentDidMount() {
this.queryMemberList({
page: 1,
page_size: this.state.pageSize,
sort_column:'created_at',
sort_mode:'desc'
});
}
//获取会员列表
queryMemberList(params) {
const { dispatch } = this.props;
dispatch({
type: 'member/fetch',
payload: params,
});
}
toggleForm = () => {
const { expandForm } = this.state;
this.setState({
expandForm: !expandForm,
});
};
renderSimpleForm() {
const {
form: { getFieldDecorator },
} = this.props;
return (
<Form
onKeyDown={(e)=>{
e.keyCode == 13 && e.preventDefault()
}}
onSubmit={this.handleSearch.bind(this)}
layout="inline">
<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
<Col md={8} sm={24}>
<FormItem label="姓名">
{getFieldDecorator('name')(<Input placeholder="请输入搜索姓名"/>)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<FormItem label="手机号">
{getFieldDecorator('phone')(<Input placeholder="请输入搜索手机号"/>)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<span className={styles.submitButtons}>
<Button type="primary" htmlType="submit">
查询
</Button>
<a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
展开 <Icon type="down"/>
</a>
</span>
</Col>
</Row>
</Form>
);
}
renderAdvancedForm() {
const {
form: { getFieldDecorator },
} = this.props;
return (
<Form
onKeyDown={(e)=>{
e.keyCode == 13 && e.preventDefault()
}}
onSubmit={this.handleSearch.bind(this)}
layout="inline">
<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
<Col md={8} sm={24}>
<FormItem label="姓名">
{getFieldDecorator('name')(<Input placeholder="请输入搜索姓名"/>)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<FormItem label="手机号">
{getFieldDecorator('phone')(<Input placeholder="请输入搜索手机号"/>)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<FormItem label="会员卡">
{getFieldDecorator('card_number')(<Input placeholder="请输入搜索会员卡号"/>)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<FormItem label="会籍">
{getFieldDecorator('membership_name')(<Input placeholder="请输入搜索会籍"/>)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<FormItem label="教练">
{getFieldDecorator('coaches_name')(<Input placeholder="请输入搜索教练"/>)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<span className={styles.submitButtons}>
<Button type="primary" htmlType="submit">
查询
</Button>
<a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
收起 <Icon type="down"/>
</a>
</span>
</Col>
</Row>
</Form>
);
}
renderForm() {
const { expandForm } = this.state;
return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
}
//提交搜索
handleSearch(e) {
e.preventDefault();
const {
form: { validateFields },
} = this.props;
validateFields((err, values) => {
if (!err) {
this.setState({
form_values: values,
});
this.queryMemberList({
page: 1,
page_size: this.state.pageSize,
sort_column:'created_at',
sort_mode:'desc',
...values,
});
this.refs.advancedTable.handleReset();
}
});
}
handleModalVisible = flag => {
this.setState({
modalVisible: !!flag,
});
};
handleEditModalVisible = flag => {
this.setState({
editModalVisible: !!flag,
});
};
renderMenu() {
return (
<Menu>
<Menu.Item>
<span onClick={this.handleEditModalVisible.bind(this, true)}>编辑</span>
</Menu.Item>
<Menu.Item>
<span>删除</span>
</Menu.Item>
</Menu>
);
}
renderTbody(item) {
const { match } = this.props;
const coaches = item.coaches_name ? item.coaches_name.split(',') : '';
return (
<tr key={item.uuid}>
<td>
{this.renderMemberInfo(item.headimgurl, item.name, item.age, item.phone)}
</td>
<td>
<div className={styles.messInfo}>
<p>{item.card_number}</p>
<p className={styles.inTime}>{moment(item.created_at * 1000).format('YYYY-MM-DD')}</p>
</div>
</td>
<td>
<div className={styles.dateInfo}>
<p className={styles.date}>{item.expire ? moment(item.expire * 1000).format('YYYY-MM-DD') : '无会籍卡'}</p>
<p className={styles.title}>{item.membership_name}</p>
</div>
</td>
<td>
<div className={styles.dateInfo}>
<p className={styles.date}>剩余{item.has_course_count ? item.has_course_count : 0}节</p>
<p
className={styles.title}>{coaches.length > 1 ? coaches[0] + '教练等' + coaches.length + '人' : coaches[0]}</p>
</div>
</td>
<td>
<div className={styles.messInfo}>
<p>{item.lastClock}</p>
<p className={styles.inTime}>{item.last_sign_time ? moment(item.last_sign_time * 1000).format('YYYY-MM-DD') : ''}</p>
</div>
</td>
<td>
<div className={styles.messInfo}>
<p>{item.lastClass}</p>
<p className={styles.inTime}>{item.last_in_class_time ? moment(item.last_in_class_time * 1000).format('YYYY-MM-DD') : ''}</p>
</div>
</td>
<td>
¥{item.total_amount ? item.total_amount : 0}
</td>
<td>
<div className={styles.opers}>
<Link to={`${match.url}/detail/sign`}>详情</Link>
<Divider type="vertical"/>
<Dropdown overlay={this.renderMenu()}>
<a className="ant-dropdown-link" href="javascript:;">
更多 <Icon type="down"/>
</a>
</Dropdown>
</div>
</td>
</tr>
);
}
renderMemberInfo(avatar, name, age, phone) {
return (
<div className={styles.memberInfo}>
<p className={styles.avatar}>
<img src={avatar}/>
</p>
<div className={styles.baseInfo}>
<p className={styles.title}>
<span>{name}</span>
<span>{age}</span>
</p>
<p className={styles.subTitle}>{phone}</p>
</div>
</div>
);
}
//分页
onPageChange(page, pageSize, sorter) {
const { form_values } = this.state;
this.queryMemberList({
page,
page_size: pageSize,
sort_column: sorter.sort_column ? sorter.sort_column : "created_at",
sort_mode: sorter.sortUp === 2 ? 'asc' : sorter.sortUp === 3 ? 'desc' : 'desc',
...form_values,
});
}
handleAddMember(fields){
console.log(fields)
}
render() {
const { modalVisible, editModalVisible } = this.state;
const {
member: { response },
loading,
} = this.props;
const paginationProps = {
showSizeChanger: true,
showQuickJumper: true,
current: response.paginator.page,
total: response.paginator.total_count,
};
const addMemberMethods = {
handleModalVisible: this.handleModalVisible,
handleAddMember:this.handleAddMember,
handleUpdate: this.handleUpdate,
};
const editMemberMethods = {
handleEditModalVisible: this.handleEditModalVisible,
};
return (
<PageHeaderWrapper className={styles.memberContent}>
<div className={styles.standardList}>
<Card bordered={false}>
<Row>
<Col xl={5} lg={8} md={8} sm={12} xs={24}>
<StandarInfoData title="会员总数" number="245" subTitle1="男134" subTitle2="女166" bordered/>
</Col>
<Col xl={5} lg={8} md={8} sm={12} xs={24}>
<StandarInfoData title="未过期会员" number="245" subTitle1="已过期58" bordered/>
</Col>
<Col xl={5} lg={8} md={8} sm={12} xs={24}>
<StandarInfoData title="私教会员" number="245" subTitle1="非私教会员100" bordered/>
</Col>
<Col xl={4} lg={8} md={8} sm={12} xs={24}>
<StandarInfoData title="90天内即将过期" number="245" subTitle1="30天内过期12" bordered/>
</Col>
<Col xl={5} lg={8} md={8} sm={12} xs={24}>
<StandarInfoData title="剩余课时1-15节" number="245" subTitle1="剩余0节会员25"/>
</Col>
</Row>
</Card>
</div>
<Card bordered={false}>
<div className={styles.tableListForm}>{this.renderForm()}</div>
<div className={styles.tableListOperator}>
<Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
新建
</Button>
<AdvancedTable
ref="advancedTable"
loading={loading}
columns={this.columns}
data={response.members}
pagination={paginationProps}
onPageChange={this.onPageChange.bind(this)}>
<tbody>
{
response.members.map(item => {
return (
this.renderTbody(item)
);
})
}
</tbody>
</AdvancedTable>
</div>
</Card>
<AddMemberForm
{...addMemberMethods}
modalVisible={modalVisible}
/>
<EditMemberForm
{...editMemberMethods}
editModalVisible={editModalVisible}
/>
</PageHeaderWrapper>
);
}
}
export default MemberList;
|
JavaScript
|
CL
|
c8b5000442285b2b30f2c2392c8664b278eb24333eea8a7d5cdeca46f657c296
|
const webpack = require ('webpack');//引入webpack
const opn = require ('opn');//打开浏览器
const merge = require ('webpack-merge');//webpack配置文件合并
const path = require ('path');
const baseWebpackConfig = require ('./webpack.base.conf');//基础配置
let config = merge (baseWebpackConfig, {
output: {
path: path.resolve (__dirname, '../../build'),
filename: 'js/bundle.js',
chunkFilename: "js/[name]-[id].js",
publicPath: ''
},
plugins: [
/*设置开发环境*/
new webpack.DefinePlugin ({
'process.env': {
NODE_ENV: JSON.stringify ('development'),
}
}),
/*设置热更新*/
new webpack.HotModuleReplacementPlugin (),
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: [
'babel-loader',
],
include: [
path.resolve (__dirname, "../../app"),
path.resolve (__dirname, "../../entryBuild")
],
exclude: [
path.resolve (__dirname, "../../node_modules")
],
}
]
},
/*设置api转发*/
devServer: {
host: 'localhost',
port: 8080,
hot: true,
inline: true,
contentBase: path.resolve (__dirname, '../../build'),
historyApiFallback: true,
disableHostCheck: true,
proxy: [
{
context: ['/api/**', '/u/**'],
target: 'http://localhost:8080/',
secure: false
}
],
/*打开浏览器 并打开本项目网址*/
after () {
opn ('http://localhost:' + this.port);
}
}
});
module.exports = config;
|
JavaScript
|
CL
|
26bb1c7e9d2411f63bc959f46e9a4a9a11af427435edfb408ecb7167e49d89e8
|
/// <reference types="cypress" />
describe('VO management with role VO admin', () => {
const dbVoName = 'test-e2e-vo-from-db';
const dbGroupName = 'test-group-from-db';
const dbApplicationItemTextFieldName = 'input-test';
const dbVoManager = 'vo-manager-2';
const dbUser = 'test';
const addedAttribute = 'notification-default-language';
before(() => {
cy.login('VO_MANAGER', 'voManager');
});
beforeEach(() => {
cy.visit('home')
.get(`[data-cy=access-item-button]`)
.click()
});
it('test create vo', () => {
cy.intercept('**/vosManager/createVo/**')
.as('createVo')
.intercept('**/vosManager/getEnrichedVoById**')
.as('getVoById')
.get('[data-cy=new-vo-button]')
.click()
.get('[data-cy=vo-name-input]')
.type('test-e2e-vo', {force: true})
.get('[data-cy=vo-shortname-input]')
.type('test-e2e-vo', {force: true})
.get('[data-cy=create-vo-button]')
.click()
.wait('@createVo')
.wait('@getVoById')
// assert that the vo was created
.get('[data-cy=notification-message]')
.contains('New organization was successfully created')
.should('exist');
});
it('test add attribute', () => {
cy.intercept('**/attributesManager/setAttributes/vo')
.as('setAttributes')
.get('[data-cy=filter-input]')
.type(dbVoName, {force: true})
.get(`[data-cy=${dbVoName}]`)
.click()
.get('[data-cy=attributes]')
.click()
.get('[data-cy=add-attributes]')
.click()
// get attribute Notification default language
.get(`[data-cy=${addedAttribute}-value]`)
.type('en', {force: true})
.intercept('**/attributesManager/getAttributes/vo**')
.as('getAttributes')
.get('[data-cy=save-selected-attributes]')
.click()
.wait('@setAttributes')
.wait('@getAttributes')
// assert that attribute exists
.get('[data-cy=filter-input]')
.type('notification default language', {force: true})
.get(`[data-cy=${addedAttribute}-value]`)
.should('exist');
});
it('test delete attribute', () => {
cy.intercept('**/attributesManager/removeAttributes/**')
.as('removeAttributes')
.get('[data-cy=filter-input]')
.type(dbVoName, {force: true})
.get(`[data-cy=${dbVoName}]`)
.click()
.get('[data-cy=attributes]')
.click()
// get attribute Link to AUP
.get('[data-cy=filter-input]')
.type('link to aup', {force: true})
.get('[data-cy=link-to-aup-checkbox]')
.click()
.get('[data-cy=remove-attributes]')
.click()
.intercept('**/attributesManager/getAttributes/vo**')
.as('getAttributes')
.get('[data-cy=delete-attributes]')
.click()
.wait('@removeAttributes')
.wait('@getAttributes')
// assert that attribute exists
.get('[data-cy=link-to-aup-checkbox]')
.should('not.exist');
});
it('test add vo member', () => {
cy.intercept('**/membersManager/addMemberCandidates')
.as('addMemberCandidates')
.get('[data-cy=filter-input]')
.type(dbVoName, {force: true})
.get(`[data-cy=${dbVoName}]`)
.click()
.get('[data-cy=members]')
.click()
.get('[data-cy=add-members]')
.should('have.attr', 'color', 'accent') // check if the button is enabled (due to the force click below)
.click({ force: true })
.get('[data-cy=search-members]')
.find('[data-cy=filter-input]')
.type(`${dbUser}`, {force: true})
.get(`[data-cy=${dbUser}-checkbox]`)
.click()
.intercept('**/membersManager/getMembersPage')
.as('getMembers')
.get('[data-cy=add-button]')
.click()
.wait('@addMemberCandidates')
.wait('@getMembers')
// assert that member was created
.get('[data-cy=filter-input]')
.type(dbUser, {force: true})
.get(`[data-cy=${dbUser}-checkbox]`)
.should('exist');
});
it('test remove vo member', () => {
cy.intercept('**/membersManager/deleteMembers**')
.as('deleteMembers')
.get('[data-cy=filter-input]')
.type(dbVoName, {force: true})
.get(`[data-cy=${dbVoName}]`)
.click()
.get('[data-cy=members]')
.click()
.get('[data-cy=filter-input]')
.type(dbVoManager, {force: true})
.intercept('**/membersManager/getMembersPage')
.as('getMembers')
.wait('@getMembers')
.get(`[data-cy=${dbVoManager}-checkbox]`)
.click()
.get('[data-cy=remove-members]')
.should('have.attr', 'color', 'warn') // check if the button is enabled (due to the force click below)
.click({ force: true })
.get('[data-cy=remove-members-dialog]')
.click()
.wait('@deleteMembers')
.wait('@getMembers')
// assert that member was removed
.get(`[data-cy=${dbVoManager}-checkbox]`)
.should('not.exist');
});
it('test add group', () => {
cy.intercept('**/groupsManager/createGroup/**')
.as('createGroup')
.get('[data-cy=filter-input]')
.type(dbVoName, {force: true})
.get(`[data-cy=${dbVoName}]`)
.click()
.get('[data-cy=groups]')
.click()
.get('[data-cy=create-group-button]')
.click()
.get('[data-cy=group-name]')
.type('test-group', {force: true})
.get('[data-cy=group-description]')
.type('test-group-description', {force: true})
.get('[data-cy=create-group-button-dialog]')
.click()
.wait('@createGroup')
.intercept('**/groupsManager/getAllRichGroupsWithAttributesByNames**')
.as('getGroups')
.wait('@getGroups')
// assert that group was created
.get('[data-cy=filter-input]')
.type('test-group', {force: true})
.get('[data-cy=test-group-checkbox]')
.should('exist');
});
it('test remove group', () => {
cy.intercept('**/groupsManager/deleteGroups')
.as('deleteGroups')
.get('[data-cy=filter-input]')
.type(dbVoName, {force: true})
.get(`[data-cy=${dbVoName}]`)
.click()
.get('[data-cy=groups]')
.click()
.get('[data-cy=filter-input]')
.type(dbGroupName, {force: true})
.get(`[data-cy=${dbGroupName}-checkbox]`)
.click()
.get('[data-cy=delete-group-button]')
.click()
.get('[data-cy=delete-button-dialog]')
.click()
.wait('@deleteGroups')
.intercept('**/groupsManager/getAllRichGroupsWithAttributesByNames**')
.as('getGroups')
.wait('@getGroups')
// assert that group was deleted
.get(`[data-cy=${dbGroupName}-checkbox]`)
.should('not.exist');
});
context('Advanced settings', () => {
beforeEach(() => {
cy.get('[data-cy=filter-input]')
.type(dbVoName, {force: true})
.get(`[data-cy=${dbVoName}]`)
.click()
.get('[data-cy=advanced-settings]')
.click()
})
// TODO fix - randomly failing due to a bug with privileges
it.skip('test create vo application form item', () => {
cy.intercept('**/registrarManager/updateFormItems/**')
.as('addFormItem')
.get('[data-cy=application-form]')
.click()
.get('[data-cy=add-form-item]')
.click()
.get('[data-cy=item-short-name]')
.type('Header', {force: true})
.get('[data-cy=add-form-item-button-dialog]')
.click()
.get('[data-cy=edit-form-item-button-dialog]')
.click()
.intercept('**/registrarManager/getFormItems/vo**')
.as('getFormItems')
.get('[data-cy=save-application-form]')
.click()
.wait('@addFormItem')
.wait('@getFormItems')
.get('[data-cy=refresh-button]')
.click()
.wait('@getFormItems')
// assert that form item exists
.get('[data-cy=header-delete]')
.should('exist');
});
// TODO fix - randomly failing due to a bug with privileges
it.skip('test delete vo application form item', () => {
cy.intercept('**/registrarManager/updateFormItems/**')
.as('deleteFormItem')
.intercept('**/registrarManager/getFormItems/vo**')
.as('getFormItems')
.get('[data-cy=application-form]')
.click()
.wait('@getFormItems')
.get(`[data-cy=${dbApplicationItemTextFieldName}-delete]`)
.click()
.get('[data-cy=delete-application-form-item-dialog]')
.click()
.get('[data-cy=save-application-form]')
.click()
.wait('@deleteFormItem')
.get('[data-cy=refresh-button]')
.click()
// assert that form item doesn't exist
.get(`[data-cy=${dbApplicationItemTextFieldName}-delete]`)
.should('not.exist');
});
it('test add vo manager', () => {
cy.intercept('**/authzResolver/setRole/**')
.as('setRole')
.get('[data-cy=managers]')
.click()
.get('[data-cy=add-manager-button]')
.click()
.get('[data-cy=search-manager-input]')
.type(`${dbUser}`, {force: true})
.get('[data-cy=search-manager-button]')
.click()
.get(`[data-cy=${dbUser}-checkbox]`)
.click()
.get('[data-cy=add-manager-button-dialog]')
.click()
.intercept('**/authzResolver/getRichAdmins**')
.as('getRichAdmins')
.wait('@setRole')
.wait('@getRichAdmins')
// assert that manager was added
.get(`[data-cy=${dbUser}-checkbox]`)
.should('exist');
});
it('test remove vo manager', () => {
cy.intercept('**/authzResolver/unsetRole/**')
.as('unsetRole')
.get('[data-cy=managers]')
.click()
.get(`[data-cy=${dbVoManager}-checkbox]`)
.click()
.get('[data-cy=remove-manager-button]')
.click()
.intercept('**/authzResolver/getRichAdmins**')
.as('getRichAdmins')
.get('[data-cy=remove-manager-button-dialog]')
.click()
.wait('@unsetRole')
.wait('@getRichAdmins')
// assert that manager doesn't exist
.get(`[data-cy=${dbVoManager}-checkbox]`)
.should('not.exist');
});
});
});
|
JavaScript
|
CL
|
02b5540b3982698e0dd5503fc811ef8efa63a96b534b6a8b72d8e15ad771e43a
|
/******/ (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 = 2);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
*
* @param {string} selector
* @param {window.HTMLElement} target
* @returns {window.HTMLElement}
*/
var $ = function $(selector, target) {
return (target || document).querySelector(selector);
};
/**
*
* @param {string} selector
* @param {window.HTMLElement} target
* @returns {Array.<HTMLElement>}
*/
var $$ = function $$(selector, target) {
return (target || document).querySelectorAll(selector) || [];
};
exports.$ = $;
exports.$$ = $$;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Проверяет, есть ли тач у устройства
* @returns {void}
*/
function isTouchDevice() {
return !!('ontouchstart' in window);
}
exports.default = isTouchDevice;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
__webpack_require__(3);
__webpack_require__(4);
var _events = __webpack_require__(5);
var _events2 = _interopRequireDefault(_events);
var _imageWithGestures = __webpack_require__(6);
var _imageWithGestures2 = _interopRequireDefault(_imageWithGestures);
var _dom = __webpack_require__(0);
var _isTouchDevice = __webpack_require__(1);
var _isTouchDevice2 = _interopRequireDefault(_isTouchDevice);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Главный контейнер для карточек
var parent = (0, _dom.$)('.cards-container');
// Обход всех объектов данных
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = _events2.default.events[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var elementData = _step.value;
var type = findType(elementData);
var element = makeClone(type);
setIcon(element, elementData);
setAttr(element, elementData, 'title');
setAttr(element, elementData, 'source');
setAttr(element, elementData, 'time');
setDescription(element, elementData);
if (type === 'average-card-buttons') setButtons(element, elementData);
if (type === 'average-card-music') setMusic(element, elementData);
if (type === 'average-card-temperature') setTemperatureAndHumidity(element, elementData);
// Убрал из-за трудностей вопределении оргинального размера для 2 задания
// if (type === 'large-card-critical') setImage(element, elementData);
parent.appendChild(element);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
checkTitles();
var cardsWithPhoto = (0, _dom.$$)('.card_large.card_critical');
// Инициализация объектов класса управления жестов для карточек с изображениями
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = cardsWithPhoto[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var cardWithPhoto = _step2.value;
new _imageWithGestures2.default(cardWithPhoto);
}
// Если устройство поддерживает тач, убираем ховер с карточек
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
if ((0, _isTouchDevice2.default)()) {
setMobileClasses();
}
/**
* Определяю тип карточки исходя из входных данных
* @param {object} el
* @returns {string}
*/
function findType(el) {
if (el.size === 's') return 'small-card-normal';
if (el.data && el.data.temperature) return 'average-card-temperature';
if (el.size === 'm' && el.data && el.data.track) return 'average-card-music';
if (el.size === 'm' && el.data && el.data.buttons) return 'average-card-buttons';
if (el.type === 'critical' && el.size === 'm') return 'average-card-critical';
if (el.type === 'critical' && el.size === 'l') return 'large-card-critical';
if (el.data && el.data.type === 'graph') return 'large-card-normal';
throw new Error('can not find type of element');
}
/**
* Устанавливает значение выбранного поля в карточке
* @param {window.HTMLElement} el
* @param {object} data
* @param {string} attr
* @returns {void}
*/
function setAttr(el, data, attr) {
var elem = (0, _dom.$)('.card__' + attr, el);
elem.innerHTML = data[attr];
}
/**
* Получаем пути для адаптивных изображений
* @param {string} src
* @returns {object}
*/
function getImageData(src) {
var dotPosition = src.indexOf('.');
var name = src.slice(0, dotPosition);
var extension = src.slice(dotPosition);
var srcset = '' + name + extension + ' 320w, ' + name + '2x' + extension + ' 480w, ' + name + '3x' + extension + ' 800w';
var sizes = '(max-width: 320px) 280px, (max-width: 480px) 440px, 800px';
return {
srcset: srcset,
sizes: sizes
};
}
/**
* Устанавливает пути для изображения
* @param {window.HTMLElement} el
* @param {object} data
* @returns {void}
*/
function setImage(el, data) {
var imageEl = (0, _dom.$)('.card__picture-line', el);
var src = 'images/' + data.data.image;
var imageData = getImageData(src);
imageEl.setAttribute('srcset', imageData.srcset);
imageEl.setAttribute('sizes', imageData.sizes);
imageEl.setAttribute('src', src);
}
/**
* Устанавливает описание выбранного поля
* @param {window.HTMLElement} el
* @param {object} data
* @returns {void}
*/
function setDescription(el, data) {
var desc = (0, _dom.$)('.card__description-line', el);
if (data.description) desc.innerHTML = data.description;else desc.style.display = 'none';
}
/**
* Устанавливает температуру и влажность
* @param {window.HTMLElement} el
* @param {object} data
* @returns {void}
*/
function setTemperatureAndHumidity(el, data) {
var tempEl = (0, _dom.$)('.card__temperature-inner', el);
tempEl.innerHTML = data.data.temperature + ' C';
var humidityEl = (0, _dom.$)('.card__humidity', el);
humidityEl.innerHTML = data.data.humidity + '%';
}
/**
* Устанавливает значение кнопок
* @param {window.HTMLElement} el
* @param {object} data
* @returns {void}
*/
function setButtons(el, data) {
var buttonYes = (0, _dom.$)('.card__button_yes', el);
var buttonNo = (0, _dom.$)('.card__button_no', el);
buttonYes.innerHTML = data.data.buttons[0];
buttonNo.innerHTML = data.data.buttons[1];
}
/**
* Устанавливает значение пути для иконок
* @param {window.HTMLElement} el
* @param {object} data
* @returns {void}
*/
function setIcon(el, data) {
var iconEl = (0, _dom.$)('.card__icon', el);
iconEl.setAttribute('src', './images/' + data.icon + '.svg');
}
/**
* Устанавливает поля карточки с музыкальным плеером
* @param {window.HTMLElement} el
* @param {object} data
* @returns {void}
*/
function setMusic(el, data) {
var coverEl = (0, _dom.$)('.card__albumcover', el);
coverEl.setAttribute('src', data.data.albumcover);
var name = (0, _dom.$)('.card__music-name', el);
name.innerHTML = data.data.artist + ' - ' + data.data.track.name;
var length = (0, _dom.$)('.card__music-length', el);
length.innerHTML = data.data.track.length;
var volume = (0, _dom.$)('.card__music-volume', el);
volume.innerHTML = data.data.volume + '%';
}
/**
* Создает клон выбранного шаблона
* @param {string} template
* @returns {window.HTMLElement}
*/
function makeClone(template) {
var fragment = (0, _dom.$)('#' + template).content;
var el = document.importNode(fragment, true);
return el;
}
/**
* Проверяет высоту загололовка, если она больше 2 строк возвращает false
* @param {window.HTMLElement} element
* @returns {boolean}
*/
function checkHeight(element) {
var styles = getComputedStyle(element);
if (Math.ceil(parseFloat(styles.fontSize)) * 1.2 * 2 < element.offsetHeight) return false;else return true;
}
/**
* Проеряет заголовки на высоту, обрезает и ставит три точки, если заголовок больше 2 строк
* @returns {void}
*/
function checkTitles() {
var titles = (0, _dom.$$)('.card__title');
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = titles[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var title = _step3.value;
if (!checkHeight(title)) {
title.innerHTML = title.innerHTML + '...';
while (!checkHeight(title)) {
title.innerHTML = title.innerHTML.slice(0, -4) + '...';
}
}
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
}
/**
* Устанавливает класс всем карточкам, чтобы убрать действие hover
* @returns {void}
*/
function setMobileClasses() {
var cards = (0, _dom.$$)('.card');
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = cards[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var card = _step4.value;
card.classList.add('card_mobile');
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
}
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
/*!
* PEP v0.4.3 | https://github.com/jquery/PEP
* Copyright jQuery Foundation and other contributors | http://jquery.org/license
*/
(function (global, factory) {
true ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.PointerEventsPolyfill = factory());
}(this, function () { 'use strict';
/**
* This is the constructor for new PointerEvents.
*
* New Pointer Events must be given a type, and an optional dictionary of
* initialization properties.
*
* Due to certain platform requirements, events returned from the constructor
* identify as MouseEvents.
*
* @constructor
* @param {String} inType The type of the event to create.
* @param {Object} [inDict] An optional dictionary of initial event properties.
* @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
*/
var MOUSE_PROPS = [
'bubbles',
'cancelable',
'view',
'detail',
'screenX',
'screenY',
'clientX',
'clientY',
'ctrlKey',
'altKey',
'shiftKey',
'metaKey',
'button',
'relatedTarget',
'pageX',
'pageY'
];
var MOUSE_DEFAULTS = [
false,
false,
null,
null,
0,
0,
0,
0,
false,
false,
false,
false,
0,
null,
0,
0
];
function PointerEvent(inType, inDict) {
inDict = inDict || Object.create(null);
var e = document.createEvent('Event');
e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false);
// define inherited MouseEvent properties
// skip bubbles and cancelable since they're set above in initEvent()
for (var i = 2, p; i < MOUSE_PROPS.length; i++) {
p = MOUSE_PROPS[i];
e[p] = inDict[p] || MOUSE_DEFAULTS[i];
}
e.buttons = inDict.buttons || 0;
// Spec requires that pointers without pressure specified use 0.5 for down
// state and 0 for up state.
var pressure = 0;
if (inDict.pressure && e.buttons) {
pressure = inDict.pressure;
} else {
pressure = e.buttons ? 0.5 : 0;
}
// add x/y properties aliased to clientX/Y
e.x = e.clientX;
e.y = e.clientY;
// define the properties of the PointerEvent interface
e.pointerId = inDict.pointerId || 0;
e.width = inDict.width || 0;
e.height = inDict.height || 0;
e.pressure = pressure;
e.tiltX = inDict.tiltX || 0;
e.tiltY = inDict.tiltY || 0;
e.twist = inDict.twist || 0;
e.tangentialPressure = inDict.tangentialPressure || 0;
e.pointerType = inDict.pointerType || '';
e.hwTimestamp = inDict.hwTimestamp || 0;
e.isPrimary = inDict.isPrimary || false;
return e;
}
/**
* This module implements a map of pointer states
*/
var USE_MAP = window.Map && window.Map.prototype.forEach;
var PointerMap = USE_MAP ? Map : SparseArrayMap;
function SparseArrayMap() {
this.array = [];
this.size = 0;
}
SparseArrayMap.prototype = {
set: function(k, v) {
if (v === undefined) {
return this.delete(k);
}
if (!this.has(k)) {
this.size++;
}
this.array[k] = v;
},
has: function(k) {
return this.array[k] !== undefined;
},
delete: function(k) {
if (this.has(k)) {
delete this.array[k];
this.size--;
}
},
get: function(k) {
return this.array[k];
},
clear: function() {
this.array.length = 0;
this.size = 0;
},
// return value, key, map
forEach: function(callback, thisArg) {
return this.array.forEach(function(v, k) {
callback.call(thisArg, v, k, this);
}, this);
}
};
var CLONE_PROPS = [
// MouseEvent
'bubbles',
'cancelable',
'view',
'detail',
'screenX',
'screenY',
'clientX',
'clientY',
'ctrlKey',
'altKey',
'shiftKey',
'metaKey',
'button',
'relatedTarget',
// DOM Level 3
'buttons',
// PointerEvent
'pointerId',
'width',
'height',
'pressure',
'tiltX',
'tiltY',
'pointerType',
'hwTimestamp',
'isPrimary',
// event instance
'type',
'target',
'currentTarget',
'which',
'pageX',
'pageY',
'timeStamp'
];
var CLONE_DEFAULTS = [
// MouseEvent
false,
false,
null,
null,
0,
0,
0,
0,
false,
false,
false,
false,
0,
null,
// DOM Level 3
0,
// PointerEvent
0,
0,
0,
0,
0,
0,
'',
0,
false,
// event instance
'',
null,
null,
0,
0,
0,
0
];
var BOUNDARY_EVENTS = {
'pointerover': 1,
'pointerout': 1,
'pointerenter': 1,
'pointerleave': 1
};
var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined');
/**
* This module is for normalizing events. Mouse and Touch events will be
* collected here, and fire PointerEvents that have the same semantics, no
* matter the source.
* Events fired:
* - pointerdown: a pointing is added
* - pointerup: a pointer is removed
* - pointermove: a pointer is moved
* - pointerover: a pointer crosses into an element
* - pointerout: a pointer leaves an element
* - pointercancel: a pointer will no longer generate events
*/
var dispatcher = {
pointermap: new PointerMap(),
eventMap: Object.create(null),
captureInfo: Object.create(null),
// Scope objects for native events.
// This exists for ease of testing.
eventSources: Object.create(null),
eventSourceList: [],
/**
* Add a new event source that will generate pointer events.
*
* `inSource` must contain an array of event names named `events`, and
* functions with the names specified in the `events` array.
* @param {string} name A name for the event source
* @param {Object} source A new source of platform events.
*/
registerSource: function(name, source) {
var s = source;
var newEvents = s.events;
if (newEvents) {
newEvents.forEach(function(e) {
if (s[e]) {
this.eventMap[e] = s[e].bind(s);
}
}, this);
this.eventSources[name] = s;
this.eventSourceList.push(s);
}
},
register: function(element) {
var l = this.eventSourceList.length;
for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
// call eventsource register
es.register.call(es, element);
}
},
unregister: function(element) {
var l = this.eventSourceList.length;
for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
// call eventsource register
es.unregister.call(es, element);
}
},
contains: /*scope.external.contains || */function(container, contained) {
try {
return container.contains(contained);
} catch (ex) {
// most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
return false;
}
},
// EVENTS
down: function(inEvent) {
inEvent.bubbles = true;
this.fireEvent('pointerdown', inEvent);
},
move: function(inEvent) {
inEvent.bubbles = true;
this.fireEvent('pointermove', inEvent);
},
up: function(inEvent) {
inEvent.bubbles = true;
this.fireEvent('pointerup', inEvent);
},
enter: function(inEvent) {
inEvent.bubbles = false;
this.fireEvent('pointerenter', inEvent);
},
leave: function(inEvent) {
inEvent.bubbles = false;
this.fireEvent('pointerleave', inEvent);
},
over: function(inEvent) {
inEvent.bubbles = true;
this.fireEvent('pointerover', inEvent);
},
out: function(inEvent) {
inEvent.bubbles = true;
this.fireEvent('pointerout', inEvent);
},
cancel: function(inEvent) {
inEvent.bubbles = true;
this.fireEvent('pointercancel', inEvent);
},
leaveOut: function(event) {
this.out(event);
this.propagate(event, this.leave, false);
},
enterOver: function(event) {
this.over(event);
this.propagate(event, this.enter, true);
},
// LISTENER LOGIC
eventHandler: function(inEvent) {
// This is used to prevent multiple dispatch of pointerevents from
// platform events. This can happen when two elements in different scopes
// are set up to create pointer events, which is relevant to Shadow DOM.
if (inEvent._handledByPE) {
return;
}
var type = inEvent.type;
var fn = this.eventMap && this.eventMap[type];
if (fn) {
fn(inEvent);
}
inEvent._handledByPE = true;
},
// set up event listeners
listen: function(target, events) {
events.forEach(function(e) {
this.addEvent(target, e);
}, this);
},
// remove event listeners
unlisten: function(target, events) {
events.forEach(function(e) {
this.removeEvent(target, e);
}, this);
},
addEvent: /*scope.external.addEvent || */function(target, eventName) {
target.addEventListener(eventName, this.boundHandler);
},
removeEvent: /*scope.external.removeEvent || */function(target, eventName) {
target.removeEventListener(eventName, this.boundHandler);
},
// EVENT CREATION AND TRACKING
/**
* Creates a new Event of type `inType`, based on the information in
* `inEvent`.
*
* @param {string} inType A string representing the type of event to create
* @param {Event} inEvent A platform event with a target
* @return {Event} A PointerEvent of type `inType`
*/
makeEvent: function(inType, inEvent) {
// relatedTarget must be null if pointer is captured
if (this.captureInfo[inEvent.pointerId]) {
inEvent.relatedTarget = null;
}
var e = new PointerEvent(inType, inEvent);
if (inEvent.preventDefault) {
e.preventDefault = inEvent.preventDefault;
}
e._target = e._target || inEvent.target;
return e;
},
// make and dispatch an event in one call
fireEvent: function(inType, inEvent) {
var e = this.makeEvent(inType, inEvent);
return this.dispatchEvent(e);
},
/**
* Returns a snapshot of inEvent, with writable properties.
*
* @param {Event} inEvent An event that contains properties to copy.
* @return {Object} An object containing shallow copies of `inEvent`'s
* properties.
*/
cloneEvent: function(inEvent) {
var eventCopy = Object.create(null);
var p;
for (var i = 0; i < CLONE_PROPS.length; i++) {
p = CLONE_PROPS[i];
eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i];
// Work around SVGInstanceElement shadow tree
// Return the <use> element that is represented by the instance for Safari, Chrome, IE.
// This is the behavior implemented by Firefox.
if (HAS_SVG_INSTANCE && (p === 'target' || p === 'relatedTarget')) {
if (eventCopy[p] instanceof SVGElementInstance) {
eventCopy[p] = eventCopy[p].correspondingUseElement;
}
}
}
// keep the semantics of preventDefault
if (inEvent.preventDefault) {
eventCopy.preventDefault = function() {
inEvent.preventDefault();
};
}
return eventCopy;
},
getTarget: function(inEvent) {
var capture = this.captureInfo[inEvent.pointerId];
if (!capture) {
return inEvent._target;
}
if (inEvent._target === capture || !(inEvent.type in BOUNDARY_EVENTS)) {
return capture;
}
},
propagate: function(event, fn, propagateDown) {
var target = event.target;
var targets = [];
// Order of conditions due to document.contains() missing in IE.
while (target !== document && !target.contains(event.relatedTarget)) {
targets.push(target);
target = target.parentNode;
// Touch: Do not propagate if node is detached.
if (!target) {
return;
}
}
if (propagateDown) {
targets.reverse();
}
targets.forEach(function(target) {
event.target = target;
fn.call(this, event);
}, this);
},
setCapture: function(inPointerId, inTarget, skipDispatch) {
if (this.captureInfo[inPointerId]) {
this.releaseCapture(inPointerId, skipDispatch);
}
this.captureInfo[inPointerId] = inTarget;
this.implicitRelease = this.releaseCapture.bind(this, inPointerId, skipDispatch);
document.addEventListener('pointerup', this.implicitRelease);
document.addEventListener('pointercancel', this.implicitRelease);
var e = new PointerEvent('gotpointercapture');
e.pointerId = inPointerId;
e._target = inTarget;
if (!skipDispatch) {
this.asyncDispatchEvent(e);
}
},
releaseCapture: function(inPointerId, skipDispatch) {
var t = this.captureInfo[inPointerId];
if (!t) {
return;
}
this.captureInfo[inPointerId] = undefined;
document.removeEventListener('pointerup', this.implicitRelease);
document.removeEventListener('pointercancel', this.implicitRelease);
var e = new PointerEvent('lostpointercapture');
e.pointerId = inPointerId;
e._target = t;
if (!skipDispatch) {
this.asyncDispatchEvent(e);
}
},
/**
* Dispatches the event to its target.
*
* @param {Event} inEvent The event to be dispatched.
* @return {Boolean} True if an event handler returns true, false otherwise.
*/
dispatchEvent: /*scope.external.dispatchEvent || */function(inEvent) {
var t = this.getTarget(inEvent);
if (t) {
return t.dispatchEvent(inEvent);
}
},
asyncDispatchEvent: function(inEvent) {
requestAnimationFrame(this.dispatchEvent.bind(this, inEvent));
}
};
dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher);
var targeting = {
shadow: function(inEl) {
if (inEl) {
return inEl.shadowRoot || inEl.webkitShadowRoot;
}
},
canTarget: function(shadow) {
return shadow && Boolean(shadow.elementFromPoint);
},
targetingShadow: function(inEl) {
var s = this.shadow(inEl);
if (this.canTarget(s)) {
return s;
}
},
olderShadow: function(shadow) {
var os = shadow.olderShadowRoot;
if (!os) {
var se = shadow.querySelector('shadow');
if (se) {
os = se.olderShadowRoot;
}
}
return os;
},
allShadows: function(element) {
var shadows = [];
var s = this.shadow(element);
while (s) {
shadows.push(s);
s = this.olderShadow(s);
}
return shadows;
},
searchRoot: function(inRoot, x, y) {
if (inRoot) {
var t = inRoot.elementFromPoint(x, y);
var st, sr;
// is element a shadow host?
sr = this.targetingShadow(t);
while (sr) {
// find the the element inside the shadow root
st = sr.elementFromPoint(x, y);
if (!st) {
// check for older shadows
sr = this.olderShadow(sr);
} else {
// shadowed element may contain a shadow root
var ssr = this.targetingShadow(st);
return this.searchRoot(ssr, x, y) || st;
}
}
// light dom element is the target
return t;
}
},
owner: function(element) {
var s = element;
// walk up until you hit the shadow root or document
while (s.parentNode) {
s = s.parentNode;
}
// the owner element is expected to be a Document or ShadowRoot
if (s.nodeType !== Node.DOCUMENT_NODE && s.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
s = document;
}
return s;
},
findTarget: function(inEvent) {
var x = inEvent.clientX;
var y = inEvent.clientY;
// if the listener is in the shadow root, it is much faster to start there
var s = this.owner(inEvent.target);
// if x, y is not in this root, fall back to document search
if (!s.elementFromPoint(x, y)) {
s = document;
}
return this.searchRoot(s, x, y);
}
};
var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
var map = Array.prototype.map.call.bind(Array.prototype.map);
var toArray = Array.prototype.slice.call.bind(Array.prototype.slice);
var filter = Array.prototype.filter.call.bind(Array.prototype.filter);
var MO = window.MutationObserver || window.WebKitMutationObserver;
var SELECTOR = '[touch-action]';
var OBSERVER_INIT = {
subtree: true,
childList: true,
attributes: true,
attributeOldValue: true,
attributeFilter: ['touch-action']
};
function Installer(add, remove, changed, binder) {
this.addCallback = add.bind(binder);
this.removeCallback = remove.bind(binder);
this.changedCallback = changed.bind(binder);
if (MO) {
this.observer = new MO(this.mutationWatcher.bind(this));
}
}
Installer.prototype = {
watchSubtree: function(target) {
// Only watch scopes that can target find, as these are top-level.
// Otherwise we can see duplicate additions and removals that add noise.
//
// TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
// a removal without an insertion when a node is redistributed among
// shadows. Since it all ends up correct in the document, watching only
// the document will yield the correct mutations to watch.
if (this.observer && targeting.canTarget(target)) {
this.observer.observe(target, OBSERVER_INIT);
}
},
enableOnSubtree: function(target) {
this.watchSubtree(target);
if (target === document && document.readyState !== 'complete') {
this.installOnLoad();
} else {
this.installNewSubtree(target);
}
},
installNewSubtree: function(target) {
forEach(this.findElements(target), this.addElement, this);
},
findElements: function(target) {
if (target.querySelectorAll) {
return target.querySelectorAll(SELECTOR);
}
return [];
},
removeElement: function(el) {
this.removeCallback(el);
},
addElement: function(el) {
this.addCallback(el);
},
elementChanged: function(el, oldValue) {
this.changedCallback(el, oldValue);
},
concatLists: function(accum, list) {
return accum.concat(toArray(list));
},
// register all touch-action = none nodes on document load
installOnLoad: function() {
document.addEventListener('readystatechange', function() {
if (document.readyState === 'complete') {
this.installNewSubtree(document);
}
}.bind(this));
},
isElement: function(n) {
return n.nodeType === Node.ELEMENT_NODE;
},
flattenMutationTree: function(inNodes) {
// find children with touch-action
var tree = map(inNodes, this.findElements, this);
// make sure the added nodes are accounted for
tree.push(filter(inNodes, this.isElement));
// flatten the list
return tree.reduce(this.concatLists, []);
},
mutationWatcher: function(mutations) {
mutations.forEach(this.mutationHandler, this);
},
mutationHandler: function(m) {
if (m.type === 'childList') {
var added = this.flattenMutationTree(m.addedNodes);
added.forEach(this.addElement, this);
var removed = this.flattenMutationTree(m.removedNodes);
removed.forEach(this.removeElement, this);
} else if (m.type === 'attributes') {
this.elementChanged(m.target, m.oldValue);
}
}
};
function shadowSelector(v) {
return 'body /shadow-deep/ ' + selector(v);
}
function selector(v) {
return '[touch-action="' + v + '"]';
}
function rule(v) {
return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }';
}
var attrib2css = [
'none',
'auto',
'pan-x',
'pan-y',
{
rule: 'pan-x pan-y',
selectors: [
'pan-x pan-y',
'pan-y pan-x'
]
}
];
var styles = '';
// only install stylesheet if the browser has touch action support
var hasNativePE = window.PointerEvent || window.MSPointerEvent;
// only add shadow selectors if shadowdom is supported
var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot;
function applyAttributeStyles() {
if (hasNativePE) {
attrib2css.forEach(function(r) {
if (String(r) === r) {
styles += selector(r) + rule(r) + '\n';
if (hasShadowRoot) {
styles += shadowSelector(r) + rule(r) + '\n';
}
} else {
styles += r.selectors.map(selector) + rule(r.rule) + '\n';
if (hasShadowRoot) {
styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n';
}
}
});
var el = document.createElement('style');
el.textContent = styles;
document.head.appendChild(el);
}
}
var pointermap = dispatcher.pointermap;
// radius around touchend that swallows mouse events
var DEDUP_DIST = 25;
// left, middle, right, back, forward
var BUTTON_TO_BUTTONS = [1, 4, 2, 8, 16];
var HAS_BUTTONS = false;
try {
HAS_BUTTONS = new MouseEvent('test', { buttons: 1 }).buttons === 1;
} catch (e) {}
// handler block for native mouse events
var mouseEvents = {
POINTER_ID: 1,
POINTER_TYPE: 'mouse',
events: [
'mousedown',
'mousemove',
'mouseup',
'mouseover',
'mouseout'
],
register: function(target) {
dispatcher.listen(target, this.events);
},
unregister: function(target) {
dispatcher.unlisten(target, this.events);
},
lastTouches: [],
// collide with the global mouse listener
isEventSimulatedFromTouch: function(inEvent) {
var lts = this.lastTouches;
var x = inEvent.clientX;
var y = inEvent.clientY;
for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) {
// simulated mouse events will be swallowed near a primary touchend
var dx = Math.abs(x - t.x);
var dy = Math.abs(y - t.y);
if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) {
return true;
}
}
},
prepareEvent: function(inEvent) {
var e = dispatcher.cloneEvent(inEvent);
// forward mouse preventDefault
var pd = e.preventDefault;
e.preventDefault = function() {
inEvent.preventDefault();
pd();
};
e.pointerId = this.POINTER_ID;
e.isPrimary = true;
e.pointerType = this.POINTER_TYPE;
return e;
},
prepareButtonsForMove: function(e, inEvent) {
var p = pointermap.get(this.POINTER_ID);
// Update buttons state after possible out-of-document mouseup.
if (inEvent.which === 0 || !p) {
e.buttons = 0;
} else {
e.buttons = p.buttons;
}
inEvent.buttons = e.buttons;
},
mousedown: function(inEvent) {
if (!this.isEventSimulatedFromTouch(inEvent)) {
var p = pointermap.get(this.POINTER_ID);
var e = this.prepareEvent(inEvent);
if (!HAS_BUTTONS) {
e.buttons = BUTTON_TO_BUTTONS[e.button];
if (p) { e.buttons |= p.buttons; }
inEvent.buttons = e.buttons;
}
pointermap.set(this.POINTER_ID, inEvent);
if (!p || p.buttons === 0) {
dispatcher.down(e);
} else {
dispatcher.move(e);
}
}
},
mousemove: function(inEvent) {
if (!this.isEventSimulatedFromTouch(inEvent)) {
var e = this.prepareEvent(inEvent);
if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
e.button = -1;
pointermap.set(this.POINTER_ID, inEvent);
dispatcher.move(e);
}
},
mouseup: function(inEvent) {
if (!this.isEventSimulatedFromTouch(inEvent)) {
var p = pointermap.get(this.POINTER_ID);
var e = this.prepareEvent(inEvent);
if (!HAS_BUTTONS) {
var up = BUTTON_TO_BUTTONS[e.button];
// Produces wrong state of buttons in Browsers without `buttons` support
// when a mouse button that was pressed outside the document is released
// inside and other buttons are still pressed down.
e.buttons = p ? p.buttons & ~up : 0;
inEvent.buttons = e.buttons;
}
pointermap.set(this.POINTER_ID, inEvent);
// Support: Firefox <=44 only
// FF Ubuntu includes the lifted button in the `buttons` property on
// mouseup.
// https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
e.buttons &= ~BUTTON_TO_BUTTONS[e.button];
if (e.buttons === 0) {
dispatcher.up(e);
} else {
dispatcher.move(e);
}
}
},
mouseover: function(inEvent) {
if (!this.isEventSimulatedFromTouch(inEvent)) {
var e = this.prepareEvent(inEvent);
if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
e.button = -1;
pointermap.set(this.POINTER_ID, inEvent);
dispatcher.enterOver(e);
}
},
mouseout: function(inEvent) {
if (!this.isEventSimulatedFromTouch(inEvent)) {
var e = this.prepareEvent(inEvent);
if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
e.button = -1;
dispatcher.leaveOut(e);
}
},
cancel: function(inEvent) {
var e = this.prepareEvent(inEvent);
dispatcher.cancel(e);
this.deactivateMouse();
},
deactivateMouse: function() {
pointermap.delete(this.POINTER_ID);
}
};
var captureInfo = dispatcher.captureInfo;
var findTarget = targeting.findTarget.bind(targeting);
var allShadows = targeting.allShadows.bind(targeting);
var pointermap$1 = dispatcher.pointermap;
// This should be long enough to ignore compat mouse events made by touch
var DEDUP_TIMEOUT = 2500;
var CLICK_COUNT_TIMEOUT = 200;
var ATTRIB = 'touch-action';
var INSTALLER;
// handler block for native touch events
var touchEvents = {
events: [
'touchstart',
'touchmove',
'touchend',
'touchcancel'
],
register: function(target) {
INSTALLER.enableOnSubtree(target);
},
unregister: function() {
// TODO(dfreedman): is it worth it to disconnect the MO?
},
elementAdded: function(el) {
var a = el.getAttribute(ATTRIB);
var st = this.touchActionToScrollType(a);
if (st) {
el._scrollType = st;
dispatcher.listen(el, this.events);
// set touch-action on shadows as well
allShadows(el).forEach(function(s) {
s._scrollType = st;
dispatcher.listen(s, this.events);
}, this);
}
},
elementRemoved: function(el) {
el._scrollType = undefined;
dispatcher.unlisten(el, this.events);
// remove touch-action from shadow
allShadows(el).forEach(function(s) {
s._scrollType = undefined;
dispatcher.unlisten(s, this.events);
}, this);
},
elementChanged: function(el, oldValue) {
var a = el.getAttribute(ATTRIB);
var st = this.touchActionToScrollType(a);
var oldSt = this.touchActionToScrollType(oldValue);
// simply update scrollType if listeners are already established
if (st && oldSt) {
el._scrollType = st;
allShadows(el).forEach(function(s) {
s._scrollType = st;
}, this);
} else if (oldSt) {
this.elementRemoved(el);
} else if (st) {
this.elementAdded(el);
}
},
scrollTypes: {
EMITTER: 'none',
XSCROLLER: 'pan-x',
YSCROLLER: 'pan-y',
SCROLLER: /^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/
},
touchActionToScrollType: function(touchAction) {
var t = touchAction;
var st = this.scrollTypes;
if (t === 'none') {
return 'none';
} else if (t === st.XSCROLLER) {
return 'X';
} else if (t === st.YSCROLLER) {
return 'Y';
} else if (st.SCROLLER.exec(t)) {
return 'XY';
}
},
POINTER_TYPE: 'touch',
firstTouch: null,
isPrimaryTouch: function(inTouch) {
return this.firstTouch === inTouch.identifier;
},
setPrimaryTouch: function(inTouch) {
// set primary touch if there no pointers, or the only pointer is the mouse
if (pointermap$1.size === 0 || (pointermap$1.size === 1 && pointermap$1.has(1))) {
this.firstTouch = inTouch.identifier;
this.firstXY = { X: inTouch.clientX, Y: inTouch.clientY };
this.scrolling = false;
this.cancelResetClickCount();
}
},
removePrimaryPointer: function(inPointer) {
if (inPointer.isPrimary) {
this.firstTouch = null;
this.firstXY = null;
this.resetClickCount();
}
},
clickCount: 0,
resetId: null,
resetClickCount: function() {
var fn = function() {
this.clickCount = 0;
this.resetId = null;
}.bind(this);
this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT);
},
cancelResetClickCount: function() {
if (this.resetId) {
clearTimeout(this.resetId);
}
},
typeToButtons: function(type) {
var ret = 0;
if (type === 'touchstart' || type === 'touchmove') {
ret = 1;
}
return ret;
},
touchToPointer: function(inTouch) {
var cte = this.currentTouchEvent;
var e = dispatcher.cloneEvent(inTouch);
// We reserve pointerId 1 for Mouse.
// Touch identifiers can start at 0.
// Add 2 to the touch identifier for compatibility.
var id = e.pointerId = inTouch.identifier + 2;
e.target = captureInfo[id] || findTarget(e);
e.bubbles = true;
e.cancelable = true;
e.detail = this.clickCount;
e.button = 0;
e.buttons = this.typeToButtons(cte.type);
e.width = (inTouch.radiusX || inTouch.webkitRadiusX || 0) * 2;
e.height = (inTouch.radiusY || inTouch.webkitRadiusY || 0) * 2;
e.pressure = inTouch.force || inTouch.webkitForce || 0.5;
e.isPrimary = this.isPrimaryTouch(inTouch);
e.pointerType = this.POINTER_TYPE;
// forward modifier keys
e.altKey = cte.altKey;
e.ctrlKey = cte.ctrlKey;
e.metaKey = cte.metaKey;
e.shiftKey = cte.shiftKey;
// forward touch preventDefaults
var self = this;
e.preventDefault = function() {
self.scrolling = false;
self.firstXY = null;
cte.preventDefault();
};
return e;
},
processTouches: function(inEvent, inFunction) {
var tl = inEvent.changedTouches;
this.currentTouchEvent = inEvent;
for (var i = 0, t; i < tl.length; i++) {
t = tl[i];
inFunction.call(this, this.touchToPointer(t));
}
},
// For single axis scrollers, determines whether the element should emit
// pointer events or behave as a scroller
shouldScroll: function(inEvent) {
if (this.firstXY) {
var ret;
var scrollAxis = inEvent.currentTarget._scrollType;
if (scrollAxis === 'none') {
// this element is a touch-action: none, should never scroll
ret = false;
} else if (scrollAxis === 'XY') {
// this element should always scroll
ret = true;
} else {
var t = inEvent.changedTouches[0];
// check the intended scroll axis, and other axis
var a = scrollAxis;
var oa = scrollAxis === 'Y' ? 'X' : 'Y';
var da = Math.abs(t['client' + a] - this.firstXY[a]);
var doa = Math.abs(t['client' + oa] - this.firstXY[oa]);
// if delta in the scroll axis > delta other axis, scroll instead of
// making events
ret = da >= doa;
}
this.firstXY = null;
return ret;
}
},
findTouch: function(inTL, inId) {
for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) {
if (t.identifier === inId) {
return true;
}
}
},
// In some instances, a touchstart can happen without a touchend. This
// leaves the pointermap in a broken state.
// Therefore, on every touchstart, we remove the touches that did not fire a
// touchend event.
// To keep state globally consistent, we fire a
// pointercancel for this "abandoned" touch
vacuumTouches: function(inEvent) {
var tl = inEvent.touches;
// pointermap.size should be < tl.length here, as the touchstart has not
// been processed yet.
if (pointermap$1.size >= tl.length) {
var d = [];
pointermap$1.forEach(function(value, key) {
// Never remove pointerId == 1, which is mouse.
// Touch identifiers are 2 smaller than their pointerId, which is the
// index in pointermap.
if (key !== 1 && !this.findTouch(tl, key - 2)) {
var p = value.out;
d.push(p);
}
}, this);
d.forEach(this.cancelOut, this);
}
},
touchstart: function(inEvent) {
this.vacuumTouches(inEvent);
this.setPrimaryTouch(inEvent.changedTouches[0]);
this.dedupSynthMouse(inEvent);
if (!this.scrolling) {
this.clickCount++;
this.processTouches(inEvent, this.overDown);
}
},
overDown: function(inPointer) {
pointermap$1.set(inPointer.pointerId, {
target: inPointer.target,
out: inPointer,
outTarget: inPointer.target
});
dispatcher.enterOver(inPointer);
dispatcher.down(inPointer);
},
touchmove: function(inEvent) {
if (!this.scrolling) {
if (this.shouldScroll(inEvent)) {
this.scrolling = true;
this.touchcancel(inEvent);
} else {
inEvent.preventDefault();
this.processTouches(inEvent, this.moveOverOut);
}
}
},
moveOverOut: function(inPointer) {
var event = inPointer;
var pointer = pointermap$1.get(event.pointerId);
// a finger drifted off the screen, ignore it
if (!pointer) {
return;
}
var outEvent = pointer.out;
var outTarget = pointer.outTarget;
dispatcher.move(event);
if (outEvent && outTarget !== event.target) {
outEvent.relatedTarget = event.target;
event.relatedTarget = outTarget;
// recover from retargeting by shadow
outEvent.target = outTarget;
if (event.target) {
dispatcher.leaveOut(outEvent);
dispatcher.enterOver(event);
} else {
// clean up case when finger leaves the screen
event.target = outTarget;
event.relatedTarget = null;
this.cancelOut(event);
}
}
pointer.out = event;
pointer.outTarget = event.target;
},
touchend: function(inEvent) {
this.dedupSynthMouse(inEvent);
this.processTouches(inEvent, this.upOut);
},
upOut: function(inPointer) {
if (!this.scrolling) {
dispatcher.up(inPointer);
dispatcher.leaveOut(inPointer);
}
this.cleanUpPointer(inPointer);
},
touchcancel: function(inEvent) {
this.processTouches(inEvent, this.cancelOut);
},
cancelOut: function(inPointer) {
dispatcher.cancel(inPointer);
dispatcher.leaveOut(inPointer);
this.cleanUpPointer(inPointer);
},
cleanUpPointer: function(inPointer) {
pointermap$1.delete(inPointer.pointerId);
this.removePrimaryPointer(inPointer);
},
// prevent synth mouse events from creating pointer events
dedupSynthMouse: function(inEvent) {
var lts = mouseEvents.lastTouches;
var t = inEvent.changedTouches[0];
// only the primary finger will synth mouse events
if (this.isPrimaryTouch(t)) {
// remember x/y of last touch
var lt = { x: t.clientX, y: t.clientY };
lts.push(lt);
var fn = (function(lts, lt) {
var i = lts.indexOf(lt);
if (i > -1) {
lts.splice(i, 1);
}
}).bind(null, lts, lt);
setTimeout(fn, DEDUP_TIMEOUT);
}
}
};
INSTALLER = new Installer(touchEvents.elementAdded, touchEvents.elementRemoved,
touchEvents.elementChanged, touchEvents);
var pointermap$2 = dispatcher.pointermap;
var HAS_BITMAP_TYPE = window.MSPointerEvent &&
typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number';
var msEvents = {
events: [
'MSPointerDown',
'MSPointerMove',
'MSPointerUp',
'MSPointerOut',
'MSPointerOver',
'MSPointerCancel',
'MSGotPointerCapture',
'MSLostPointerCapture'
],
register: function(target) {
dispatcher.listen(target, this.events);
},
unregister: function(target) {
dispatcher.unlisten(target, this.events);
},
POINTER_TYPES: [
'',
'unavailable',
'touch',
'pen',
'mouse'
],
prepareEvent: function(inEvent) {
var e = inEvent;
if (HAS_BITMAP_TYPE) {
e = dispatcher.cloneEvent(inEvent);
e.pointerType = this.POINTER_TYPES[inEvent.pointerType];
}
return e;
},
cleanup: function(id) {
pointermap$2.delete(id);
},
MSPointerDown: function(inEvent) {
pointermap$2.set(inEvent.pointerId, inEvent);
var e = this.prepareEvent(inEvent);
dispatcher.down(e);
},
MSPointerMove: function(inEvent) {
var e = this.prepareEvent(inEvent);
dispatcher.move(e);
},
MSPointerUp: function(inEvent) {
var e = this.prepareEvent(inEvent);
dispatcher.up(e);
this.cleanup(inEvent.pointerId);
},
MSPointerOut: function(inEvent) {
var e = this.prepareEvent(inEvent);
dispatcher.leaveOut(e);
},
MSPointerOver: function(inEvent) {
var e = this.prepareEvent(inEvent);
dispatcher.enterOver(e);
},
MSPointerCancel: function(inEvent) {
var e = this.prepareEvent(inEvent);
dispatcher.cancel(e);
this.cleanup(inEvent.pointerId);
},
MSLostPointerCapture: function(inEvent) {
var e = dispatcher.makeEvent('lostpointercapture', inEvent);
dispatcher.dispatchEvent(e);
},
MSGotPointerCapture: function(inEvent) {
var e = dispatcher.makeEvent('gotpointercapture', inEvent);
dispatcher.dispatchEvent(e);
}
};
function applyPolyfill() {
// only activate if this platform does not have pointer events
if (!window.PointerEvent) {
window.PointerEvent = PointerEvent;
if (window.navigator.msPointerEnabled) {
var tp = window.navigator.msMaxTouchPoints;
Object.defineProperty(window.navigator, 'maxTouchPoints', {
value: tp,
enumerable: true
});
dispatcher.registerSource('ms', msEvents);
} else {
Object.defineProperty(window.navigator, 'maxTouchPoints', {
value: 0,
enumerable: true
});
dispatcher.registerSource('mouse', mouseEvents);
if (window.ontouchstart !== undefined) {
dispatcher.registerSource('touch', touchEvents);
}
}
dispatcher.register(document);
}
}
var n = window.navigator;
var s;
var r;
var h;
function assertActive(id) {
if (!dispatcher.pointermap.has(id)) {
var error = new Error('InvalidPointerId');
error.name = 'InvalidPointerId';
throw error;
}
}
function assertConnected(elem) {
var parent = elem.parentNode;
while (parent && parent !== elem.ownerDocument) {
parent = parent.parentNode;
}
if (!parent) {
var error = new Error('InvalidStateError');
error.name = 'InvalidStateError';
throw error;
}
}
function inActiveButtonState(id) {
var p = dispatcher.pointermap.get(id);
return p.buttons !== 0;
}
if (n.msPointerEnabled) {
s = function(pointerId) {
assertActive(pointerId);
assertConnected(this);
if (inActiveButtonState(pointerId)) {
dispatcher.setCapture(pointerId, this, true);
this.msSetPointerCapture(pointerId);
}
};
r = function(pointerId) {
assertActive(pointerId);
dispatcher.releaseCapture(pointerId, true);
this.msReleasePointerCapture(pointerId);
};
} else {
s = function setPointerCapture(pointerId) {
assertActive(pointerId);
assertConnected(this);
if (inActiveButtonState(pointerId)) {
dispatcher.setCapture(pointerId, this);
}
};
r = function releasePointerCapture(pointerId) {
assertActive(pointerId);
dispatcher.releaseCapture(pointerId);
};
}
h = function hasPointerCapture(pointerId) {
return !!dispatcher.captureInfo[pointerId];
};
function applyPolyfill$1() {
if (window.Element && !Element.prototype.setPointerCapture) {
Object.defineProperties(Element.prototype, {
'setPointerCapture': {
value: s
},
'releasePointerCapture': {
value: r
},
'hasPointerCapture': {
value: h
}
});
}
}
applyAttributeStyles();
applyPolyfill();
applyPolyfill$1();
var pointerevents = {
dispatcher: dispatcher,
Installer: Installer,
PointerEvent: PointerEvent,
PointerMap: PointerMap,
targetFinding: targeting
};
return pointerevents;
}));
/***/ }),
/* 4 */
/***/ (function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
'events': [{
'type': 'info',
'title': 'Еженедельный отчет по расходам ресурсов',
'source': 'Сенсоры потребления',
'time': '19:00, Сегодня',
'description': 'Так держать! За последнюю неделю вы потратили на 10% меньше ресурсов, чем неделей ранее.',
'icon': 'stats',
'data': {
'type': 'graph',
'values': [{
'electricity': [['1536883200', 115], ['1536969600', 117], ['1537056000', 117.2], ['1537142400', 118], ['1537228800', 120], ['1537315200', 123], ['1537401600', 129]]
}, {
'water': [['1536883200', 40], ['1536969600', 40.2], ['1537056000', 40.5], ['1537142400', 41], ['1537228800', 41.4], ['1537315200', 41.9], ['1537401600', 42.6]]
}, {
'gas': [['1536883200', 13], ['1536969600', 13.2], ['1537056000', 13.5], ['1537142400', 13.7], ['1537228800', 14], ['1537315200', 14.2], ['1537401600', 14.5]]
}]
},
'size': 'l'
}, {
'type': 'info',
'title': 'Дверь открыта',
'source': 'Сенсор входной двери',
'time': '18:50, Сегодня',
'description': null,
'icon': 'key',
'size': 's'
}, {
'type': 'info',
'title': 'Уборка закончена',
'source': 'Пылесос',
'time': '18:45, Сегодня',
'description': null,
'icon': 'robot-cleaner',
'size': 's'
}, {
'type': 'info',
'title': 'Новый пользователь',
'source': 'Роутер',
'time': '18:45, Сегодня',
'description': null,
'icon': 'router',
'size': 's'
}, {
'type': 'info',
'title': 'Изменен климатический режим',
'source': 'Сенсор микроклимата',
'time': '18:30, Сегодня',
'description': 'Установлен климатический режим «Фиджи»',
'icon': 'thermal',
'size': 'm',
'data': {
'temperature': 24,
'humidity': 80
}
}, {
'type': 'critical',
'title': 'Невозможно включить кондиционер',
'source': 'Кондиционер',
'time': '18:21, Сегодня',
'description': 'В комнате открыто окно, закройте его и повторите попытку',
'icon': 'ac',
'size': 'm'
}, {
'type': 'info',
'title': 'Музыка включена',
'source': 'Яндекс.Станция',
'time': '18:16, Сегодня',
'description': 'Сейчас проигрывается:',
'icon': 'music',
'size': 'm',
'data': {
'albumcover': 'https://avatars.yandex.net/get-music-content/193823/1820a43e.a.5517056-1/m1000x1000',
'artist': 'Florence & The Machine',
'track': {
'name': 'Big God',
'length': '4:31'
},
'volume': 80
}
}, {
'type': 'info',
'title': 'Заканчивается молоко',
'source': 'Холодильник',
'time': '17:23, Сегодня',
'description': 'Кажется, в холодильнике заканчивается молоко. Вы хотите добавить его в список покупок?',
'icon': 'fridge',
'size': 'm',
'data': {
'buttons': ['Да', 'Нет']
}
}, {
'type': 'info',
'title': 'Зарядка завершена',
'source': 'Оконный сенсор',
'time': '16:22, Сегодня',
'description': 'Ура! Устройство «Оконный сенсор» снова в строю!',
'icon': 'battery',
'size': 's'
}, {
'type': 'critical',
'title': 'Пылесос застрял',
'source': 'Сенсор движения',
'time': '16:17, Сегодня',
'description': 'Робопылесос не смог сменить свое местоположение в течение последних 3 минут. Похоже, ему нужна помощь.',
'icon': 'cam',
'data': {
'image': 'bitmap.png'
},
'size': 'l'
}, {
'type': 'info',
'title': 'Вода вскипела',
'source': 'Чайник',
'time': '16:20, Сегодня',
'description': null,
'icon': 'kettle',
'size': 's'
}]
};
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _dom = __webpack_require__(0);
var _isTouchDevice = __webpack_require__(1);
var _isTouchDevice2 = _interopRequireDefault(_isTouchDevice);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var MIN_ROTATE_ANGLE = 0.6;
var MIN_SCALE_DISTANСE = 30;
/**
* class управления жестами на картинке
*/
var ImageWithGestures = function () {
/**
*
* @param {window.HTMLElement} cardWithImage
*/
function ImageWithGestures(cardWithImage) {
_classCallCheck(this, ImageWithGestures);
this.infoLine = (0, _dom.$)('.card__onlitouch-line', cardWithImage);
this.zoomEl = (0, _dom.$)('.card__zoom-value', cardWithImage);
this.lightEl = (0, _dom.$)('.card__light-value', cardWithImage);
this.scrollbar = (0, _dom.$)('.card__scrollbar', cardWithImage);
this.canvas = (0, _dom.$)('#canvas_image', cardWithImage);
this.ctx = this.canvas.getContext('2d');
this.mobile = (0, _isTouchDevice2.default)();
this.imageContainer = (0, _dom.$)('.card__image-container', cardWithImage);
this.image = (0, _dom.$)('.card__picture-line-zoom', cardWithImage);
this.prevX = 0;
this.scale = 2;
this.type = null;
this.scaleCounter = 0;
this.angles = null;
this.coords = null;
this.brightness = 1;
this.eventsCash = [];
this.prevDiff = -1;
this.prevAngle = -1;
this.limit = 0;
this.width = 0;
this.x = 0;
this.init();
}
/**
* Функция обновляет значение скроллбара
* @returns {void}
*/
_createClass(ImageWithGestures, [{
key: 'updateScrollBar',
value: function updateScrollBar() {
this.scrollbar.style.transform = 'translateX(' + this.x / this.limit * (this.width - this.width / this.scale) + 'px)';
this.scrollbar.style.width = 100 / this.scale + '%';
}
/**
* Устанавливает значение transform translate в случае жеста одним пальцем
* @param {number} limit - максимальное значение translate
* @param {number} size - размер контейнера изображения
* @returns {void}
*/
}, {
key: 'updateTranslate',
value: function updateTranslate() {
this.ctx.drawImage(this.image, this.x * this.scale, 0);
this.updateScrollBar();
}
/**
* Обновляет значение transform scale
* @returns {void}
*/
}, {
key: 'updateScale',
value: function updateScale() {
this.limit = (this.image.naturalWidth / this.scale - this.image.naturalWidth) / this.scale;
this.canvas.width = this.image.naturalWidth * 1 / this.scale;
this.canvas.height = this.image.naturalHeight * 1 / this.scale;
if (this.x < this.limit) {
this.x = this.limit;
}
this.ctx.drawImage(this.image, this.x * this.scale, 0);
this.updateScrollBar();
if (this.mobile) this.zoomEl.innerHTML = Math.round(this.scale * 100) + '%';
}
/**
* Обновляет значение яркости
* @returns {void}
*/
}, {
key: 'updateBrightness',
value: function updateBrightness() {
this.canvas.style.filter = 'brightness(' + this.brightness + ')';
if (this.mobile) this.lightEl.innerHTML = Math.round(this.brightness * 100) + '%';
}
/**
* Добавляет событие в кеш
* @param {window.event} ev
* @returns {void}
*/
}, {
key: 'onPoinerDown',
value: function onPoinerDown(ev) {
this.imageContainer.setPointerCapture(ev.pointerId);
this.eventsCash.push(ev);
}
/**
*
* @param {window.event} ev
* @returns {void}
*/
}, {
key: 'onPointerMove',
value: function onPointerMove(ev) {
// Обновляем кэш если событие уже было в нем
for (var i = 0; i < this.eventsCash.length; i++) {
if (ev.pointerId == this.eventsCash[i].pointerId) {
this.eventsCash[i] = ev;
break;
}
}
// если в кеше два события то обрабатываем жесты для 2 пальцев
if (this.eventsCash.length == 2) {
var touchPointA = this.eventsCash[0];
var touchPointB = this.eventsCash[1];
// определяем значение центра между двумя пальцами и сохраняем координаты начального положения если их еще не было
if (this.coords === null) {
this.coords = {
center: {
clientX: (touchPointA.clientX + touchPointB.clientX) / 2,
clientY: (touchPointA.clientY + touchPointB.clientY) / 2
},
first: {
clientX: touchPointA.clientX,
clientY: touchPointA.clientY
},
second: {
clientX: touchPointB.clientX,
clientY: touchPointB.clientY
}
};
}
// находим текущее расстояние между двумя точками
var curDiff = Math.sqrt(Math.pow(touchPointA.clientX - touchPointB.clientX, 2) + Math.pow(touchPointA.clientY - touchPointB.clientY, 2));
// находим текущий угл относительно изначального положения пальцев
var angleA = findAngle(this.coords.center, this.coords.first, touchPointA);
var angleB = findAngle(this.coords.center, this.coords.second, touchPointB);
// находим среднее изменение угла
var curAngle = (angleA + angleB) / 2;
/*
если изменение обоих углов больше 0.2 то определяем тип текущего жеста как изменение яркости,
если расстояние между пальцами изменилось на 30, то определяем жест как scale
*/
if (Math.abs(angleA) > MIN_ROTATE_ANGLE || Math.abs(angleB) > MIN_ROTATE_ANGLE && !this.type) {
this.type = 'brightness';
} else if (Math.abs(this.scaleCounter) > MIN_SCALE_DISTANСE && !this.type) {
this.type = 'scale';
}
// вычисляем текущее значение изменения расстояния и прибавляем в счетчик
if (this.prevDiff > 0) {
this.scaleCounter += curDiff - this.prevDiff;
// если значение типа события определено как scale вычисляем текущее значение
if (this.type === 'scale') {
var value = this.scale + (curDiff - this.prevDiff) / 100;
if (value > 1) {
this.scale = value;
} else {
this.scale = 1;
}
this.updateScale();
}
}
// если значение типа события определено как brightness вычисляем текущее значение
if (this.type === 'brightness') {
this.brightness = this.brightness + (curAngle - this.prevAngle) / 2.5;
this.updateBrightness();
}
this.prevAngle = curAngle;
this.prevDiff = curDiff;
}
// если одно касание, обрабатываем жест перемещения
if (this.eventsCash.length == 1) {
var _touchPointA = this.eventsCash[0];
var cur = _touchPointA.clientX;
var _value = this.x + cur - this.prevX;
if (this.prevX > 0) {
this.x = Math.min(Math.max(_value, this.limit), 0);
this.updateTranslate();
}
this.prevX = cur;
}
}
/**
*
* @param {window.event} ev
* @returns {void}
*/
}, {
key: 'onPointerUp',
value: function onPointerUp(ev) {
// удаляем событие из кеша
this.removeEvent(ev);
// если касаний меньше двух, обнуляем значения
if (this.eventsCash.length < 2) {
this.prevDiff = -1;
this.coords = null;
this.scaleCounter = null;
this.type = null;
}
// если касаний меньше одного, обнуляем значения
if (this.eventsCash.length < 1) {
this.prevX = -1;
}
}
/**
*
* @param {window.event} ev
* @returns {void}
*/
}, {
key: 'removeEvent',
value: function removeEvent(ev) {
for (var i = 0; i < this.eventsCash.length; i++) {
if (this.eventsCash[i].pointerId == ev.pointerId) {
this.eventsCash.splice(i, 1);
break;
}
}
}
/**
* инициируем листнеры
* @returns {void}
*/
}, {
key: 'init',
value: function init() {
var _this = this;
if (this.mobile) this.infoLine.style.display = 'flex';
this.image.addEventListener('load', function () {
var styles = getComputedStyle(_this.canvas);
_this.width = parseFloat(styles.width);
_this.updateScale();
});
this.imageContainer.addEventListener('pointerdown', this.onPoinerDown.bind(this));
this.imageContainer.addEventListener('pointerup', this.onPointerUp.bind(this));
this.imageContainer.addEventListener('pointercancel', this.onPointerUp.bind(this));
this.imageContainer.addEventListener('pointerleave', this.onPointerUp.bind(this));
this.imageContainer.addEventListener('pointermove', this.onPointerMove.bind(this));
}
}]);
return ImageWithGestures;
}();
/**
* вычисляет значение угла по 3 точкам
* @param {object} center
* @param {object} point1
* @param {object} point2
* @returns {object}
*/
exports.default = ImageWithGestures;
function findAngle(center, point1, point2) {
var OA = {
x: point1.clientX - center.clientX,
y: point1.clientY - center.clientY
};
var OB = {
x: point2.clientX - center.clientX,
y: point2.clientY - center.clientY
};
var angle = Math.atan2(OA.x * OB.y - OA.y * OB.x, OA.x * OB.x + OA.y * OB.y);
return angle;
}
/***/ })
/******/ ]);
|
JavaScript
|
CL
|
14266c85c47c97697d1362426d05b980113904ea48b5978833277770b51d570e
|
/*
Software License Agreement (Apache 2.0)
Copyright (c) 2020, The MITRE Corporation.
All rights reserved.
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
https://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.
This project was developed by The MITRE Corporation.
If this code is used in a deployment or embedded within another project,
it is requested that you send an email to opensource@mitre.org in order to
let us know where this software is being used.
*/
// Look for elements with event handlers as attributes like: <button onclick=js()/>
// When the whole page is loaded, go back and look at attributes. (Can't figure out how else to do this yet.)
function demod_collectEventAttributes() {
// Get all items with an event attribute.
// Which is faster, one xpath query or several?
// Use the following line to get all elements with event listeners at once.
//xpath = "//*[@" + demod_eventTypes.join(" or @") + "]";
// For each event type, get all the elements that have that event type.
for (let eventType of demod_eventTypes) {
let xpath = "//*[@on" + eventType + "]";
let res = document.evaluate(xpath, document.body, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (let nodeIndex = 0; nodeIndex < res.snapshotLength; nodeIndex++) {
demod_addEventListener(res.snapshotItem(nodeIndex), eventType);
}
}
}
demod_collectEventAttributes();
|
JavaScript
|
CL
|
f622c4e202705461248e474b84608c82c9f8d69b475da8addf7e3f6562160314
|
import React, { Component } from 'react';
import { SwipeableDrawer } from '@material-ui/core';
import classes from './index.module.css';
import Navigation from '../../components/Navigation';
import { connect } from 'react-redux';
import * as actions from '../../store/actions';
import Toolbar from '../../components/Toolbar';
import AccountNavigation from '../../components/Navigation/AccountNavigation';
import { Route, Switch } from 'react-router-dom';
import Login from '../User/Login';
import GuestGuard from '../../hoc/GuestGuard';
import Register from '../User/Register';
import Spinner from '../../components/UI/Spinner';
import CategoryProducts from '../Customer/CategoryProducts';
import CustomerProduct from '../Customer/CustomerProduct';
export class Layout extends Component {
state = {
categoryDrawerOpen: false,
accountDrawerOpen: false,
}
onDrawerToggleHandler = drawerStateKey => () => {
this.setState(prevState => ({ [drawerStateKey]: !prevState[drawerStateKey] }));
}
componentDidMount() {
this.props.fetchCategories();
const token = localStorage.getItem('token');
if (token) {
this.props.autoLogin(token);
}
}
render() {
let navigation = null;
if (this.props.categories) {
const navigationItems = this.props.categories.map(category => {
return {
name: category.name,
link: `/categories/${category.id}/products`,
key: `categories-${category.id}-products`,
}
});
navigation = (
<Navigation onClose={this.onDrawerToggleHandler('categoryDrawerOpen')} items={navigationItems} />
);
}
return (
<React.Fragment>
{this.props.loading ? <Spinner /> : null}
<Toolbar
onOpenCategoryDrawer={this.onDrawerToggleHandler('categoryDrawerOpen')}
onOpenAccountDrawer={this.onDrawerToggleHandler('accountDrawerOpen')}
/>
<SwipeableDrawer
onClose={this.onDrawerToggleHandler('categoryDrawerOpen')}
open={this.state.categoryDrawerOpen}
anchor="left"
onOpen={this.onDrawerToggleHandler('categoryDrawerOpen')}>
{navigation}
</SwipeableDrawer>
<SwipeableDrawer
onClose={this.onDrawerToggleHandler('accountDrawerOpen')}
open={this.state.accountDrawerOpen}
anchor="right"
onOpen={this.onDrawerToggleHandler('accountDrawerOpen')}>
<AccountNavigation
onClose={this.onDrawerToggleHandler('accountDrawerOpen')}
authenticated={this.props.authenticated}
logout={this.props.logout} />
</SwipeableDrawer>
<div className={classes.Content}>
<Switch>
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />
<Route path="/categories/:categoryId/products/:productId" component={CustomerProduct} />
<Route path="/categories/:id/products" component={CategoryProducts} />
</Switch>
</div>
</React.Fragment>
);
}
}
const mapStateToProps = state => ({
categories: state.categories.categories,
loadingCategories: state.categories.fetchingCategories,
authenticated: state.auth.user !== null,
loading: state.auth.fetching,
});
const mapDispatchToProps = dispatch => ({
fetchCategories: () => dispatch(actions.fetchCategories()),
autoLogin: (token) => dispatch(actions.authenticateUserByToken(token)),
logout: () => dispatch(actions.logout())
});
export default connect(mapStateToProps, mapDispatchToProps)(Layout);
|
JavaScript
|
CL
|
029bbced63ac9486ec1c7d8184c67f6fcc929368c1f1bce46b3528f66cdb9db3
|
var phone = require('./locales/common/phone');
/**
* namespace ngFaker.phone
*/
function Phone(ngFaker) {
/**
* returns a random phone number
*
* @method phoneNumber
* @returns {string} random phone number
* @param {{intl: boolean}} options the options for generating a phone number.
* If it is true, we add an international prefix to the number.
*
*/
this.phoneNumber = function (options) {
var phoneNumber;
if (options && options.intl) {
phoneNumber = '+234';
} else {
phoneNumber = '0';
}
for (var i = 0; i < 10; i++) {
phoneNumber += ngFaker.random.number({ min: 0, max: 9 });
}
return phoneNumber;
};
/**
* returns a random GSM service provider in Nigeria
*
* @method serviceProvider
* @returns {string} random service provider
*/
this.serviceProvider = function () {
return ngFaker.random.arrayElement(phone.service_providers);
};
}
module.exports = Phone;
|
JavaScript
|
CL
|
70280004174c33deb1c77571fdfc2056bab2fddf692514b5075a2f6c2f43a7b8
|
import React, { Component, PropTypes } from "react";
import { composeWithTracker } from "react-komposer";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { ReactionCore } from "meteor/reactioncommerce:core";
import ProductImageGallery from "../components/productDetail/images/ProductImageGallery";
import * as mediaActions from "../actions/media";
const getMedia = id => {
const mediaArray = ReactionCore.Collections.Media.find({
"metadata.variantId": id
}, {
sort: {
"metadata.priority": 1
}
});
return mediaArray.fetch();
//return mediaArray.map(media => {
// return {
// _id: media._id,
// name: media.name(),
// url: media.url({
// uploading: "/resources/placeholder.gif",
// storing: "/resources/placeholder.gif",
// store: "large"
// }),
// thumb: media.url({ store: "thumbnail" })
// };
//});
};
// const ProductImageGalleryContainer = props => <ProductImageGallery {...props} />;
class ProductImageGalleryContainer extends Component {
componentWillUnmount() {
// cleanup product store state
this.props.mediaActions.destroyMedia();
}
render() {
return <ProductImageGallery {...this.props} />;
}
}
ProductImageGalleryContainer.propTypes = {
lightbox: PropTypes.shape({
lightboxIsOpen: PropTypes.bool,
currentImage: PropTypes.number
}).isRequired,
media: PropTypes.array,
mediaActions: PropTypes.shape({
uploadMedia: PropTypes.func,
removeMedia: PropTypes.func,
syncMedia: PropTypes.func,
moveMedia: PropTypes.func,
destroyMedia: PropTypes.func,
toggleLightbox: PropTypes.func,
showNextLightbox: PropTypes.func,
showPrevLightbox: PropTypes.func
}),
mediaIdsArray: PropTypes.arrayOf(PropTypes.string),
product: PropTypes.object.isRequired,
selectedVariant: PropTypes.object
};
function mapStateToProps(state) {
return {
mediaIdsArray: state.shop.product.mediaIdsArray,
lightbox: state.shop.product.lightbox
};
}
function mapDispatchToProps(dispatch) {
return {
mediaActions: bindActionCreators(mediaActions, dispatch)
//productActions: bindActionCreators(productActions, dispatch)
};
}
function composer(props, onData) {
// TODO: Maybe we need subscribe to product Media here.
//const handle = Meteor.subscribe("Media");
//if (handle.ready()) {
if (ReactionCore.Subscriptions.Media.ready()) {
// sometimes `selectedVariant` is not ready to this moment
if (props.selectedVariant) {
const media = getMedia(props.selectedVariant._id);
onData(null, { media });
}
}
}
const ProductImageGalleryContainerWithData = composeWithTracker(
composer
)(ProductImageGalleryContainer);
export default connect(
mapStateToProps,
mapDispatchToProps
)(ProductImageGalleryContainerWithData);
|
JavaScript
|
CL
|
1667e2ced6ae6070d0cb2ffdbc60265834d57eef4009baa787a2198217f2ff35
|
/**
* A view pager that allows for pagination in the horizontal direction.
* Right now, there are a number of limitations built into the system. Namely:
* - It only supports pagination in the horizontal direction.
* - It supports exactly two pages.
*/
const React = require('react');
const ReactDOM = require('react-dom');
const {connect} = require('react-redux');
const {StyleSheet} = require('aphrodite');
const {View} = require('../fake-react-native-web');
const {row} = require('./styles');
const {setPageWidthPx} = require('../actions');
const {childrenPropType} = require('./prop-types');
const ViewPager = React.createClass({
propTypes: {
// Whether the page should animate to its next specified position.
animateToPosition: React.PropTypes.bool,
children: childrenPropType,
onPageWidthPxChange: React.PropTypes.func.isRequired,
translateX: React.PropTypes.number.isRequired,
},
getInitialState() {
return {
animationDurationMs: 0,
};
},
componentDidMount() {
window.addEventListener("resize", this._onResize);
this._pagerContainer = ReactDOM.findDOMNode(this);
this._shouldMeasureContainer = true;
},
componentWillReceiveProps(newProps) {
// NOTE(charlie): We can't measure the container immediately in
// componentDidMount, as the layout pass hasn't occurred yet.
if (this._shouldMeasureContainer) {
this._updatePageWidth();
this._shouldMeasureContainer = false;
}
// Compute the appropriate animation length, if the pager should
// animate to its next position.
let animationDurationMs;
if (newProps.animateToPosition) {
const finalTranslateX = newProps.translateX;
const prevTranslateX = this.props.translateX;
// We animate at a rate of 1 pixel per millisecond, and thus we can
// use the displacement as the animation duration.
animationDurationMs = Math.abs(finalTranslateX - prevTranslateX);
} else {
animationDurationMs = 0;
}
this.setState({
animationDurationMs,
});
},
componentWillUnmount() {
window.removeEventListener("resize", this._onResize);
},
_updatePageWidth() {
// Instead of immediately calculating the width, we give time for the
// parent keypad to be rerendered. This can be removed once the new
// layout for landscape screens is introduced, where there is only
// one page.
setTimeout(() => {
if (this.isMounted()) {
this.props.onPageWidthPxChange(
this._pagerContainer.offsetWidth);
}
});
},
_onResize() {
// Whenever the page resizes, we need to force an update to recompute
// the width of the view pager's pages.
// Throttle resize events -- taken from:
// https://developer.mozilla.org/en-US/docs/Web/Events/resize
if (this._resizeTimeout == null) {
this._resizeTimeout = setTimeout(() => {
this._resizeTimeout = null;
// Notify that the pager width has changed.
this._updatePageWidth();
}, 66);
}
},
render() {
const {translateX, children} = this.props;
const {animationDurationMs} = this.state;
const pagerStyle = [row, styles.twoPagePager];
const transform = {
msTransform: `translate3d(${translateX}px, 0, 0)`,
WebkitTransform: `translate3d(${translateX}px, 0, 0)`,
transform: `translate3d(${translateX}px, 0, 0)`,
};
const animate = animationDurationMs ? {
msTransitionProperty: 'transform',
WebkitTransitionProperty: 'transform',
transitionProperty: 'transform',
msTransitionDuration: `${animationDurationMs}ms`,
WebkitTransitionDuration: `${animationDurationMs}ms`,
transitionDuration: `${animationDurationMs}ms`,
msTransitionTimingFunction: 'ease-out',
WebkitTransitionTimingFunction: 'ease-out',
transitionTimingFunction: 'ease-out',
} : {};
const dynamicStyle = {
...transform,
...animate,
};
return <View>
<View style={pagerStyle} dynamicStyle={dynamicStyle}>
{children}
</View>
</View>;
},
});
const styles = StyleSheet.create({
twoPagePager: {
width: '200%',
// Note: By default, <View> sets a `maxWidth` of 100% to fix some
// Flexbox bugs. We have to override to acheive our desired width of
// 200%.
maxWidth: '200%',
},
});
const mapStateToProps = (state) => {
const {animateToPosition, currentPage, dx, pageWidthPx} = state.pager;
return {
animateToPosition,
translateX: -currentPage * pageWidthPx + dx,
};
};
const mapDispatchToProps = (dispatch) => {
return {
onPageWidthPxChange: (pageWidthPx) => {
dispatch(setPageWidthPx(pageWidthPx));
},
};
};
module.exports = connect(mapStateToProps, mapDispatchToProps)(ViewPager);
|
JavaScript
|
CL
|
520bfe1f0a00cef10da7d687148e1f1d28d3c4ecdda964e58e487712397c1617
|
/* Import styles */
import "@assets/common/Tabs.scss";
/* Import framework */
import React from "react";
/* Import custom components */
import TabsPane from "@app/common/Tabs/TabsPane";
import TabsLink from "@app/common/Tabs/TabsLink";
/**
* Renders a navigation tabs.
*
* @param {Array} children
* @returns {string}
*/
const renderNav = children => {
return (
<div className="tabs-nav">
{ children.filter(child => child.type === TabsPane).map((child, index) => (
<TabsLink key={ index } route={ child.props.route } label={ child.props.label }/>
)) }
</div>
);
};
const collectPanes = (children, result = []) => {
children.forEach(child => {
if (child.type === TabsPane) {
result.push(child);
return;
}
let object = child.props.children;
if (typeof child.props.component === "function") {
let component = child.props.component();
if (React.isValidElement(component)) {
object = component.props.children;
}
}
if (object && typeof object === "object") {
if (React.isValidElement(object)) {
object = [object];
}
collectPanes(object, result);
}
});
return result;
};
/**
* Renders component.
*
* @param {Array} children
*
* @returns {string}
* @constructor
*/
const Tabs = ({ children }) => {
const panes = collectPanes([children]);
return (
<div className="tabs">
<div className="tabs__nav">{ renderNav(panes) }</div>
<div className="tabs__content">
{ children }
</div>
</div>
);
};
export default Tabs;
|
JavaScript
|
CL
|
034b0593463a28dd2cdeaf70e406a5f9a580683d9d49a4a04d1c300a7489e090
|
const ethers = require('ethers');
const {
DepoCrowdsaleContract,
DepoCrowdsaleContractWithWallet
} = require('./config-blockchain.js');
const WalletService = require("./wallet-services");
const constants = require('./constants.json');
class CrowdsaleService {
static async getOwner() {
return await DepoCrowdsaleContract.owner();
}
static async getWhitelister() {
return await DepoCrowdsaleContract.whitelister();
}
static async getKYCId(address) {
let KYC_id = await DepoCrowdsaleContract.whitelist(address);
if (KYC_id === constants.emptyBytes) {
return "";
}
return ethers.utils.toUtf8String(KYC_id)
}
static async getCurrentTokensForEther() {
let tokens = await DepoCrowdsaleContract.getTokensForWei("1000000000000000000"); // 1 ETH in Wei
return tokens;
}
static async isWhitelisted(address) {
let KYC_id = await this.getKYCId(address);
return KYC_id !== ""
}
static async whitelistAddress(privateKey, address, KYC_id) {
let wallet = await WalletService.initWalletFromPrivateKey(privateKey);
await this.validateWhitelisting(wallet.address);
let DepoCrowdsaleContractWallet = DepoCrowdsaleContractWithWallet(wallet);
const KYC_id_bytes = ethers.utils.toUtf8Bytes(KYC_id);
const options = {gasPrice: constants.gasPrice};
return await DepoCrowdsaleContractWallet.addToWhitelist(address, KYC_id_bytes, options);
}
static async whitelistMultipleAddresses(privateKey, addresses, KYC_ids) {
let wallet = await WalletService.initWalletFromPrivateKey(privateKey);
await this.validateWhitelisting(wallet.address);
await this.validateMultiWhitelisting(addresses, KYC_ids);
let DepoCrowdsaleContractWallet = DepoCrowdsaleContractWithWallet(wallet);
let KYC_Ids_bytesArray = [];
for (let i = 0; i < addresses.length; i++) {
KYC_Ids_bytesArray.push(ethers.utils.toUtf8Bytes(KYC_ids[i]));
}
const options = {gasPrice: constants.gasPrice};
return await DepoCrowdsaleContractWallet.addManyToWhitelist(addresses, KYC_Ids_bytesArray, options);
}
static async validateWhitelisting(whitelister) {
let whitelisterAllowed = await this.getWhitelister();
if (whitelisterAllowed !== whitelister) {
throw new Error("The wallet trying to whitelist has no permissions")
}
}
static async validateMultiWhitelisting(addresses, KYC_ids) {
if (addresses.length !== KYC_ids.length) {
throw new Error("Addresses and KYC_IDs should be the same length")
}
if (addresses.length > constants.maxArraysLength) {
throw new Error("Arrays are too large for one transaction, split it in more")
}
}
}
module.exports = CrowdsaleService;
|
JavaScript
|
CL
|
4e7bf8c264fdd8f0642296ea3a9071ca5dda969a345d7ce72df091c2fe879955
|
#!/usr/bin/env node
const path = require('path');
// eslint-disable-next-line import/no-extraneous-dependencies
const Terser = require('terser');
const { cli, searchFiles, UTF8, ...fs } = require('./utils');
// Parse CLI options and arguments.
const { args, options } = cli(['cwd']);
// Use the --cwd CLI option if one was given, otherwise use `process.cwd()`.
const cwd = options.cwd ? path.resolve(options.cwd) : process.cwd();
// First argument: file search pattern.
const pattern = args[0];
// Second argument: path to the output directory.
const outputDir = path.resolve(args[1]);
/**
* Minifies an ES Module file.
*
* @function minifyESModule
* @param {string} source Path to the ES module file.
* @param {string} destination Path to the output minified file.
* @returns {Promise}
*/
async function minifyESModule(source, destination) {
const code = await fs.readFile(source, UTF8);
const result = Terser.minify(code, { module: true });
if (result.error) {
// eslint-disable-next-line
console.error(`Error minifying ${ source }`);
throw result.error;
}
// Create containing output directory.
await fs.mkdir(path.dirname(destination), { recursive: true });
// Write minified source code to `destination`.
await fs.writeFile(destination, result.code, UTF8);
}
(async function run() {
// Search for files in `cwd` that match the given `pattern` (do NOT follow symlinks).
const files = await searchFiles(pattern, { cwd, follow: false });
// Minify each file and create an array of promises.
const promises = files.map((file) => {
const src = path.resolve(cwd, file);
const dest = path.resolve(outputDir, file);
return minifyESModule(src, dest);
});
// Wait until all promises are resolved before ending execution.
await Promise.all(promises);
}());
|
JavaScript
|
CL
|
edbc2c34bd96e1083b86d17954d866ba95fc0edc7cc7eecf557ec64ae875729a
|
/**
* @module @justinc/combine-validations
*/
const curry = require('lodash.curry')
/**
* A Validation is a value of [Folktale](http://docs.folktalejs.org/en/latest/index.html)'s
* [Validation](http://docs.folktalejs.org/en/latest/api/data/validation/Validation.html) type.
* @typedef {Object} Validation
*/
/**
* As of v2, combine-validations takes the Validation ADT implementation to use as an argument.
* This function is curried.
* @param {Validation} [Validation] The Validation ADT to use
* @param {Iterable<Validation>} [iterableOfValidations=[]] The validations to combine
* @return {Validation} The combined Validations as a single Validation
* @see Validation
*/
const combineValidations = (Validation) => {
const Success = Validation.Success
return (validationsIterator = []) => {
const validationsArray = Array.from(validationsIterator)
if (validationsArray.length === 0) return Success([])
return validationsArray.reduce(
(acc, validation) => acc.ap(validation),
Success(curry((...successes) => successes, validationsArray.length))
)
}
}
module.exports = combineValidations
|
JavaScript
|
CL
|
82da3902580c68ed582bf24feb2ec35f22aa4e0c2236c04bc71ddb2a5a703a9e
|
//~~~~~~~~~~~~~~~~~~~~~~~~~~SETUP~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//Require routes
var express = require("express");
//require mongoose
var mongoose = require("mongoose");
//Require scraping stuff (fun fun fun)
var axios = require("axios");
var cheerio = require("cheerio");
//Grab models
var db = require("./models/article");
//set up express
var app = express();
//var dbConnection = process.env.MONGODB_URI || "mongodb://localhost/webScraper";
var dbConnection = "mongodb://localhost/webScraper";
// // Use morgan logger for logging requests
// app.use(logger("dev"));
//Set up express for data parsing
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
//Static directory
app.use(express.static("app/public"));
//Express Handlebars Stuff
var exphb = require("express-handlebars");
//Tells express to use handlebars
app.engine("handlebars", exphb({ defaultLayout: "main" }));
app.set("view engine", "handlebars");
// Make public a static folder
app.use(express.static("public"));
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~End set up~~~~~~~~~~~~~~~~~~~~~~~~~~
// Connect to the Mongo DB
mongoose.connect(dbConnection, {
useNewUrlParser: true
});
app.get("/scrape", function(req, res) {
// First, we grab the body of the html with axios
axios.get("https://thehardtimes.net/harddrive/").then(function(response) {
// Then, we load that into cheerio and save it to $ for a shorthand selector
var $ = cheerio.load(response.data);
// Now, we grab every h2 within an article tag, and do the following:
$("article h2").each(function(i, element) {
// Save an empty result object
var result = {};
// Add the text and href of every link, and save them as properties of the result object
result.title = $(this)
.children("a")
.text();
result.link = $(this)
.children("a")
.attr("href");
result.summary = $(this)
.children("p")
.text();
// Create a new Article using the `result` object built from scraping
db.Article.create(result)
.then(function(dbArticle) {
// View the added result in the console
console.log(dbArticle);
})
.catch(function(err) {
// If an error occurred, log it
console.log(err);
});
});
// Send a message to the client
res.send("Scrape Complete");
});
});
|
JavaScript
|
CL
|
8687ecb8f8dbf75c12841cab9a43ed4ec4bfbee88840e44c4afc5b14068a95b6
|
//> This file is part of Ymacs, an Emacs-like editor for the Web
//> http://www.ymacs.org/
//>
//> Copyright (c) 2009-2012, Mihai Bazon, Dynarch.com. All rights reserved.
//>
//> Redistribution and use in source and binary forms, with or without
//> modification, are permitted provided that the following conditions are
//> met:
//>
//> * Redistributions of source code must retain the above copyright
//> notice, this list of conditions and the following disclaimer.
//>
//> * Redistributions in binary form must reproduce the above copyright
//> notice, this list of conditions and the following disclaimer in
//> the documentation and/or other materials provided with the
//> distribution.
//>
//> * Neither the name of Dynarch.com nor the names of its contributors
//> may be used to endorse or promote products derived from this
//> software without specific prior written permission.
//>
//> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
//> EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
//> IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//> PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE
//> FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
//> CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
//> SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
//> INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
//> CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//> ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
//> THE POSSIBILITY OF SUCH DAMAGE.
// @require ymacs-tokenizer.js
Ymacs_Tokenizer.define("markdown", function(stream, tok) {
var PARSER = { next: next, copy: copy };
function copy() {
var context = restore.context = {
};
function restore() {
return PARSER;
};
return restore;
};
function foundToken(c1, c2, type) {
tok.onToken(stream.line, c1, c2, type);
};
function next() {
stream.checkStop();
var tmp;
if (stream.col == 0 && (tmp = stream.lookingAt(/^(#+)/))) {
foundToken(0, stream.col = stream.lineLength(), "markdown-heading" + tmp[0].length);
}
else if (stream.line > 0 && stream.col == 0 && (tmp = stream.lookingAt(/^[=-]+$/)) && /\S/.test(stream.lineText(stream.line - 1))) {
tmp = tmp[0].charAt(0) == "=" ? 1 : 2;
tmp = "markdown-heading" + tmp;
tok.onToken(stream.line - 1, 0, stream.lineLength(stream.line - 1), tmp);
foundToken(0, stream.col = stream.lineLength(), tmp);
}
else if (stream.col == 0 && (tmp = stream.lookingAt(/^[>\s]*/))) {
tmp = tmp[0].replace(/\s+/g, "").length;
if (tmp > 3)
tmp = "";
tmp = "markdown-blockquote" + tmp;
foundToken(0, stream.col = stream.lineLength(), tmp);
}
else {
foundToken(stream.col, ++stream.col, null);
}
};
return PARSER;
});
Ymacs_Buffer.newMode("markdown_mode", function() {
var tok = this.tokenizer;
this.setTokenizer(new Ymacs_Tokenizer({ buffer: this, type: "markdown" }));
return function() {
this.setTokenizer(tok);
};
});
|
JavaScript
|
CL
|
1200fafbadb2d8df55597dcc6fe96d2f2b3b39b2aa1926471b87bd7a32216a1e
|
// Import general dependencies
const _ = require('lodash');
const { v4: uuid } = require('uuid');
// Load and register the skip feature
require('@cypress/skip-test/support');
// Import commands.js
require('./commands/commands');
// Import api commands.js
require('./commands/api-commands');
// Import fixture commands.js
require('./commands/fixture-commands');
// Import fixture commands.js
require('./commands/storefront-api-commands');
// Import fixture commands.js
require('./commands/system-commands');
Cypress.on('uncaught:exception', (err, runnable) => {
// returning false here prevents Cypress from
// failing the test
return false;
});
before(() => {
cy.activateShopwareTheme();
});
Cypress.Screenshot.defaults({
capture: 'viewport',
});
|
JavaScript
|
CL
|
2c2b236c069d05af73235c2ea3ecf261faa28ee1f43063ad63d35fb1d878f54a
|
import React, { Component } from 'react';
// Create new context
const MyContext = React.createContext();
// Create the Provider that will pass down state and methods to the rest of the application.
class MyProvider extends Component {
state = {
name: '10up',
age: 8,
};
render() {
return (
<MyContext.Provider value={{
state: this.state,
addYear: () => this.setState({
age: this.state.age + 1
})
}}>
{this.props.children}
</MyContext.Provider>
)
}
}
// Create the consumer that will consume the data provided by the Provider.
class Company extends Component {
render() {
return(
<div className="company">
<MyContext.Consumer>
{(context) => (
//Fragment added here since you can only return one child
<>
<p>Welcome to {context.state.name}</p>
<p>We are {context.state.age} years old!</p>
<button onClick={context.addYear}>Add Year</button>
</>
)}
</MyContext.Consumer>
</div>
)
}
}
// We'll nest our Consumer inside another component just to show that we don't need to pass props to each component.
const Companies = () => (
<div>
<Company />
</div>
)
class App extends Component {
render() {
return (
// Ensure the provider wraps all the components you want to share data between.
<MyProvider>
<div className="App">
<Companies />
</div>
</MyProvider>
);
}
}
export default App;
|
JavaScript
|
CL
|
976131ebc247e263d952d4dbcd402f1d594209ed03f97c34efd438bbc8612dca
|
renderContent({"book":{"id":1990,"name":"斗罗大陆3龙王传说","keywords":"斗罗大陆3龙王传说,斗罗大陆3龙王传说最新章节","description":"斗罗大陆3龙王传说最新章节由网友提供,《斗罗大陆3龙王传说》情节跌宕起伏、扣人心弦,是一本情节与文笔俱佳的玄幻小说,爱看小说免费提供斗罗大陆3龙王传说最新清爽干净的文字章节在线阅读。","author":"唐家三少","brief":"伴随着魂导科技的进步,斗罗大陆上的人类征服了海洋,又发现了两片大陆。魂兽也随着人类魂师的猎杀无度走向灭亡,沉睡无数年的魂兽之王在星斗大森林最后的净土苏醒,它要带领仅存的族人,向人类复仇!唐舞麟立志要成为一名强大的魂师,可当武魂觉醒时,苏醒的,却是……旷世之才,龙王之争,我们的龙王传说,将由此开始。","category":"玄幻奇幻","status":"完成","last_update_time":"2018-08-24 07:57:05","last_chapter_name":"第一千九百八十一章 永冻冰封!","created_at":"2019-09-21 20:38:05","updated_at":"2019-10-15 20:36:21","cover_image":"\/images\/7bc102e2bcca2640164b1b46a92b95ef.jpg"},"chapter":{"id":1360270,"bookid":1990,"chapterid":"\/59_59883\/3452799.html","name":"第四百六十四章 殿主","part_name":"","created_at":"2019-10-02 14:32:58","updated_at":"2019-10-02 14:32:58"},"content":"唐舞麟心头一震,唐门史莱克城主管?唐门内部分级非常明确,首先是执事一层,分为щww][lā唐舞麟自己现在已经是六级执事了。只有到九级执事之后,唐门贡献再达到一个高度,才能成为主管,主管分为三级,见习主管,外堂主管和内堂主管。唐舞麟听舞长空说过,以舞长空现在的修为以及二字斗铠师的境界,也只是到了内堂主管这个层次。主管之上,才是真正的唐门高层,各堂的堂主,以及总管。<br \/> <br \/> 每一个唐门分部都有一个总管,一般来说,总管的地位和各堂堂主是一样的。<br \/> <br \/> 唐门主要有内堂和外堂,还有一个斗罗殿。其中斗罗殿地位最高。是整个唐门的管理机构。敏堂、御堂、力堂为外三堂,内堂又分为三个堂口,执法堂,斗魂堂和供奉堂。<br \/> <br \/> 内三堂人数很少,各有职能。外三堂主要对外,包括经营唐门产业之类。<br \/> <br \/> 唐门弟子并没有特别硬性的规定已经要在唐门工作。尤其是像唐舞麟他们这些年龄二十岁以下的唐门弟子,只有一个要求,那就是好好修炼、提升自身。<br \/> <br \/> 升入主管级别之后,才有资格进入内堂,执事只能在外三堂工作。待遇是非常高的。<br \/> <br \/> 而各个分部总管直接对唐门最高机构斗罗殿负责。地位等同于外堂堂主。<br \/> <br \/> 眼前这位,虽然是总管,可他的地位就不是等同外堂堂主这么简单了,因为他是唐门总部这边的总管啊!虽然唐舞麟不知道他的具体地位能够达到什么程度,但想来绝不会低,一定是唐门真正的高层。<br \/> <br \/> “您好,郭总管。”唐舞麟恭敬的向郭萧絮行礼。<br \/> <br \/> 郭萧絮微微一笑,“果然是少年才俊。很不错。你们前些天在日月皇家魂师学院的比赛,我看到了。表现的可圈可点。你们代表的不只是史莱克,在你们六人之中,有五人都是咱们唐门弟子。经斗罗殿特批,本门将会给予你们一些奖励,以鼓励你们继续努力修炼,再攀高峰。”<br \/> <br \/> 还有奖励?唐舞麟一听眼睛就亮了。<br \/> <br \/> “谢谢郭总管。”唐舞麟有些雀跃的说道,他毕竟才只有十四岁啊!<br \/> <br \/> 郭萧絮微微一笑,“你们每个人可以任选一门唐门绝学免费学习,同时,再额外奖励每人一万贡献点。但这笔贡献点你们只能消费,不计入总贡献点。”所为不计入总贡献点,指的是不能提升他们的执事等级。可就算如此,一万唐门贡献点也能买好多东西了,唐舞麟加上自己手上的贡献点,就足以购买他先前找到的两种适用灵物,这简直是雪中送炭啊!<br \/> <br \/> “你们三人先选择,回去之后让叶星澜和许小言也来一趟。”<br \/> <br \/> “是,谢谢您。”徐笠智和谢邂听到声音也早就过来了。送贡献点又可以挑选唐门绝学这种好事儿,怎能不让他们兴奋呢?<br \/> <br \/> 目前为止,唐舞麟学习的唐门绝学包括紫极魔瞳、玄天功、控鹤擒龙这三种。<br \/> <br \/> 徐笠智学到的是玄玉手、控鹤擒龙和玄天功这三种。还有一些零散的暗器手法。<br \/> <br \/> 谢邂学的是玄天功、鬼影迷踪步,两种。<br \/> <br \/> 许小言是玄天功、紫极魔瞳,两种。<br \/> <br \/> 叶星澜学的是玄天功、鬼影迷踪步、玄玉手三种。<br \/> <br \/> 如果能够再多学一种唐门绝学的话,无疑都是对他们战力极大的提升。<br \/> <br \/> 唐舞麟毫不犹豫的选了鬼影迷踪步。<br \/> <br \/> 伴随着实力的增强,他在战场上的灵活性已经成为了制约自己实力的巨大问题,他不擅长远程攻击,只有金龙恐爪勉强能算是中距离攻击而已。<br \/> <br \/> 有了鬼影迷踪步,就会极大程度的增强他的灵活性,至于玄玉手的话,他有金龙爪,作用不大。<br \/> <br \/> 徐笠智选了紫极魔瞳,以提升自己的精神力。<br \/> <br \/> 谢邂选的也是紫极魔瞳。<br \/> <br \/> 他们未来都到了要增加第二魂灵的时刻,有紫极魔瞳提前提升精神力,到时候选择魂灵就会轻松得多,而当精神力达到一定程度之后,紫极魔瞳还有一定的精神攻击能力。再加上眼力增强对于实战也同样很有作用。<br \/> <br \/> 除了作为基础的玄天功之外,唐舞麟他们私下综合评定过,最有用的,其实就是紫极魔瞳了。<br \/> <br \/> 唐舞麟没有急于购买那两种灵物,因为他怕自己回去之后不方便保存。所以准备等到找到另外两种之后,再来唐门换取。他向郭萧絮提出,要保留那两种领悟的兑换权力,花费了一千贡献点,先预订了下来。<br \/> <br \/> 唐舞麟三人兴高采烈的走了,郭萧絮回到内间。<br \/> <br \/> 不大的会议室装修的古香古色,简单的几个摆件如果仔细看,都是能令人震撼的宝贝。<br \/> <br \/> 郭萧絮走到一个座位坐了下来。此时,会议室桌子旁边,一共坐了还有六个人。<br \/> <br \/> 坐在主位上的,是一名看上去只有二十多岁的青年,一头长长的黑发披散在肩膀上,双眸却泛着淡银色的光彩。<br \/> <br \/> “怎么样?”坐在郭萧絮对面的是一名光头男子,如果唐舞麟看到他,一定会一眼就认出来,这位正是他曾经见过,并且帮过他的那位赵堂主。<br \/> <br \/> 郭萧絮微微一笑,“光哥你别着急啊!听我慢慢说。”<br \/> <br \/> 赵堂主抹了一把自己的大光头,“再叫我外号,收拾你。”<br \/> <br \/> 郭萧絮不在意的道:“这几个年轻人很不错。唐舞麟确实是特殊。我认为可以在四环之后吸收入斗魂堂重点培养。徐笠智是罕见的食物系魂师,也很不错。谢邂整体看稍微弱了一点,但双生武魂还是有优势的,他更多的是需要我们进行引导。我看,四环之后,都可以吸收到斗魂堂。”<br \/> <br \/> 主位上的青年点了点头,“大家说说,都有什么意见。”这位青年的声音非常悦耳,柔和却并不柔媚,带着淡淡的磁性,在他开口的时候,在场其他六人明显坐直了几分,面露恭敬之色。<br \/> <br \/> 一名身材壮硕的中年人道:“我没什么意见。只是,不经过外堂就直接进入内堂。这个流程上是不是有点太快了。我觉得,先来我们御堂锻炼一段时间,也没什么不好。”<br \/> <br \/> 光头赵堂主哼了一声,“你们御堂干的都是打杂的事儿,就算到外三堂,也是在我们力堂更合适一些。”<br \/> <br \/> “好了。”主位上的青年道:“美玉虽然需要雕琢,但也不能浪费时间,就进斗魂堂吧。小郭,他们我就交给你了。资源可以相对倾斜。舞长空那小家伙应该距离三字斗铠师不远了,等他达到三字斗铠级别,准许其加入供奉堂,银绶带。”<br \/> <br \/> “是,殿主。”郭萧絮站起身,恭敬的说道。<br \/> <br \/> “好了。今天就这样。我还要回学院那边。最近邪魂师开始出没,让各地唐门留意,一经发觉,斗魂堂负责清洗。”青年淡淡的说道。<br \/> <br \/> “是。”<br \/> <br \/> 伴随着青年的起身,所有人都随之站了起来,“恭送殿主。”<br \/> <br \/> 房间内的光线似乎暗淡了一下,那位被称之为殿主的青年下一瞬已经消失的无影无踪。<br \/> <br \/> ……(未完待续。)\r\n<\/br>\r\n<\/br>\n<\/br>\r\n<\/br>","pre":{"id":1360269,"bookid":1990,"chapterid":"\/59_59883\/3452731.html","name":"第四百六十三章 唐门总部","part_name":"","created_at":"2019-10-02 14:32:55","updated_at":"2019-10-02 14:32:55"},"next":{"id":1360271,"bookid":1990,"chapterid":"\/59_59883\/3452933.html","name":"第四百六十五、四百六十六章 古月,你坦白吧","part_name":"","created_at":"2019-10-02 14:33:00","updated_at":"2019-10-02 14:33:00"}})
|
JavaScript
|
CL
|
10868d5e1dc1874c5b4e277d31e18a3df3a630577cf61071d073ffd1ea2f7f58
|
/**
* Check if the given array or object is empty.
*/
export function isEmpty(data) {
if (Array.isArray(data)) {
return data.length === 0;
}
return Object.keys(data).length === 0;
}
/**
* Iterates over own enumerable string keyed properties of an object and
* invokes `iteratee` for each property.
*/
export function forOwn(object, iteratee) {
Object.keys(object).forEach(function (key) { return iteratee(object[key], key, object); });
}
/**
* Creates an object with the same keys as object and values generated by
* running each own enumerable string keyed property of object thru
* iteratee. The iteratee is invoked with three arguments:
* (value, key, object).
*/
export function mapValues(object, iteratee) {
var newObject = Object.assign({}, object);
return Object.keys(object).reduce(function (records, key) {
records[key] = iteratee(object[key], key, object);
return records;
}, newObject);
}
/**
* Creates an object composed of the object properties predicate returns
* truthy for. The predicate is invoked with two arguments: (value, key).
*/
export function pickBy(object, predicate) {
return Object.keys(object).reduce(function (records, key) {
var value = object[key];
if (predicate(value, key)) {
records[key] = value;
}
return records;
}, {});
}
/**
* Creates an array of elements, sorted in specified order by the results
* of running each element in a collection thru each iteratee.
*/
export function orderBy(collection, keys, directions) {
var index = -1;
var result = collection.map(function (value) {
var criteria = keys.map(function (key) {
return typeof key === 'function' ? key(value) : value[key];
});
return { criteria: criteria, index: ++index, value: value };
});
return baseSortBy(result, function (object, other) {
return compareMultiple(object, other, directions);
});
}
/**
* Creates an object composed of keys generated from the results of running
* each element of collection thru iteratee.
*/
export function groupBy(collection, iteratee) {
return collection.reduce(function (records, record) {
var key = iteratee(record);
if (records[key] === undefined) {
records[key] = [];
}
records[key].push(record);
return records;
}, {});
}
/**
* The base implementation of `_.sortBy` which uses `comparer` to define the
* sort order of `array` and replaces criteria objects with their
* corresponding values.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
/**
* Used by `orderBy` to compare multiple properties of a value to another
* and stable sort them.
*
* If `orders` is unspecified, all values are sorted in ascending order.
* Otherwise, specify an order of "desc" for descending or "asc" for
* ascending sort order of corresponding values.
*/
function compareMultiple(object, other, orders) {
var objCriteria = object.criteria;
var othCriteria = other.criteria;
var length = objCriteria.length;
var ordersLength = orders.length;
var index = -1;
while (++index < length) {
var result = compareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) {
return result;
}
var order = orders[index];
return result * (order === 'desc' ? -1 : 1);
}
}
return object.index - other.index;
}
/**
* Compares values to sort them in ascending order.
*/
function compareAscending(value, other) {
if (value !== other) {
if (value > other) {
return 1;
}
if (value < other) {
return -1;
}
}
return 0;
}
export default {
isEmpty: isEmpty,
forOwn: forOwn,
groupBy: groupBy,
mapValues: mapValues,
orderBy: orderBy,
pickBy: pickBy
};
//# sourceMappingURL=Utils.js.map
|
JavaScript
|
CL
|
a27efe8704d7b0d1b2780ffaf8a9d960049b743292380756f944dc0860a9e6a4
|
/**
* A simple dependency graph
*/
/**
* Helper for creating a Topological Sort using Depth-First-Search on a set of edges.
*
* Detects cycles and throws an Error if one is detected (unless the "circular"
* parameter is "true" in which case it ignores them).
*
* @param edges The set of edges to DFS through
* @param leavesOnly Whether to only return "leaf" nodes (ones who have no edges)
* @param result An array in which the results will be populated
* @param circular A boolean to allow circular dependencies
*/
function createDFS(edges, leavesOnly, result, circular) {
var visited = {};
return function (start) {
if (visited[start]) {
return;
}
var inCurrentPath = {};
var currentPath = [];
var todo = []; // used as a stack
todo.push({ node: start, processed: false });
while (todo.length > 0) {
var current = todo[todo.length - 1]; // peek at the todo stack
var processed = current.processed;
var node = current.node;
if (!processed) {
// Haven't visited edges yet (visiting phase)
if (visited[node]) {
todo.pop();
continue;
} else if (inCurrentPath[node]) {
// It's not a DAG
if (circular) {
todo.pop();
// If we're tolerating cycles, don't revisit the node
continue;
}
currentPath.push(node);
throw new DepGraphCycleError(currentPath);
}
inCurrentPath[node] = true;
currentPath.push(node);
var nodeEdges = edges[node];
// (push edges onto the todo stack in reverse order to be order-compatible with the old DFS implementation)
for (var i = nodeEdges.length - 1; i >= 0; i--) {
todo.push({ node: nodeEdges[i], processed: false });
}
current.processed = true;
} else {
// Have visited edges (stack unrolling phase)
todo.pop();
currentPath.pop();
inCurrentPath[node] = false;
visited[node] = true;
if (!leavesOnly || edges[node].length === 0) {
result.push(node);
}
}
}
};
}
/**
* Simple Dependency Graph
*/
var DepGraph = (exports.DepGraph = function DepGraph(opts) {
this.nodes = {}; // Node -> Node/Data (treated like a Set)
this.outgoingEdges = {}; // Node -> [Dependency Node]
this.incomingEdges = {}; // Node -> [Dependant Node]
this.circular = opts && !!opts.circular; // Allows circular deps
});
DepGraph.prototype = {
/**
* The number of nodes in the graph.
*/
size: function () {
return Object.keys(this.nodes).length;
},
/**
* Add a node to the dependency graph. If a node already exists, this method will do nothing.
*/
addNode: function (node, data) {
if (!this.hasNode(node)) {
// Checking the arguments length allows the user to add a node with undefined data
if (arguments.length === 2) {
this.nodes[node] = data;
} else {
this.nodes[node] = node;
}
this.outgoingEdges[node] = [];
this.incomingEdges[node] = [];
}
},
/**
* Remove a node from the dependency graph. If a node does not exist, this method will do nothing.
*/
removeNode: function (node) {
if (this.hasNode(node)) {
delete this.nodes[node];
delete this.outgoingEdges[node];
delete this.incomingEdges[node];
[this.incomingEdges, this.outgoingEdges].forEach(function (edgeList) {
Object.keys(edgeList).forEach(function (key) {
var idx = edgeList[key].indexOf(node);
if (idx >= 0) {
edgeList[key].splice(idx, 1);
}
}, this);
});
}
},
/**
* Check if a node exists in the graph
*/
hasNode: function (node) {
return this.nodes.hasOwnProperty(node);
},
/**
* Get the data associated with a node name
*/
getNodeData: function (node) {
if (this.hasNode(node)) {
return this.nodes[node];
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* Set the associated data for a given node name. If the node does not exist, this method will throw an error
*/
setNodeData: function (node, data) {
if (this.hasNode(node)) {
this.nodes[node] = data;
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* Add a dependency between two nodes. If either of the nodes does not exist,
* an Error will be thrown.
*/
addDependency: function (from, to) {
if (!this.hasNode(from)) {
throw new Error("Node does not exist: " + from);
}
if (!this.hasNode(to)) {
throw new Error("Node does not exist: " + to);
}
if (this.outgoingEdges[from].indexOf(to) === -1) {
this.outgoingEdges[from].push(to);
}
if (this.incomingEdges[to].indexOf(from) === -1) {
this.incomingEdges[to].push(from);
}
return true;
},
/**
* Remove a dependency between two nodes.
*/
removeDependency: function (from, to) {
var idx;
if (this.hasNode(from)) {
idx = this.outgoingEdges[from].indexOf(to);
if (idx >= 0) {
this.outgoingEdges[from].splice(idx, 1);
}
}
if (this.hasNode(to)) {
idx = this.incomingEdges[to].indexOf(from);
if (idx >= 0) {
this.incomingEdges[to].splice(idx, 1);
}
}
},
/**
* Return a clone of the dependency graph. If any custom data is attached
* to the nodes, it will only be shallow copied.
*/
clone: function () {
var source = this;
var result = new DepGraph();
var keys = Object.keys(source.nodes);
keys.forEach(function (n) {
result.nodes[n] = source.nodes[n];
result.outgoingEdges[n] = source.outgoingEdges[n].slice(0);
result.incomingEdges[n] = source.incomingEdges[n].slice(0);
});
return result;
},
/**
* Get an array containing the direct dependencies of the specified node.
*
* Throws an Error if the specified node does not exist.
*/
directDependenciesOf: function (node) {
if (this.hasNode(node)) {
return this.outgoingEdges[node].slice(0);
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* Get an array containing the nodes that directly depend on the specified node.
*
* Throws an Error if the specified node does not exist.
*/
directDependantsOf: function (node) {
if (this.hasNode(node)) {
return this.incomingEdges[node].slice(0);
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* Get an array containing the nodes that the specified node depends on (transitively).
*
* Throws an Error if the graph has a cycle, or the specified node does not exist.
*
* If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned
* in the array.
*/
dependenciesOf: function (node, leavesOnly) {
if (this.hasNode(node)) {
var result = [];
var DFS = createDFS(
this.outgoingEdges,
leavesOnly,
result,
this.circular
);
DFS(node);
var idx = result.indexOf(node);
if (idx >= 0) {
result.splice(idx, 1);
}
return result;
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* get an array containing the nodes that depend on the specified node (transitively).
*
* Throws an Error if the graph has a cycle, or the specified node does not exist.
*
* If `leavesOnly` is true, only nodes that do not have any dependants will be returned in the array.
*/
dependantsOf: function (node, leavesOnly) {
if (this.hasNode(node)) {
var result = [];
var DFS = createDFS(
this.incomingEdges,
leavesOnly,
result,
this.circular
);
DFS(node);
var idx = result.indexOf(node);
if (idx >= 0) {
result.splice(idx, 1);
}
return result;
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* Construct the overall processing order for the dependency graph.
*
* Throws an Error if the graph has a cycle.
*
* If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned.
*/
overallOrder: function (leavesOnly) {
var self = this;
var result = [];
var keys = Object.keys(this.nodes);
if (keys.length === 0) {
return result; // Empty graph
} else {
if (!this.circular) {
// Look for cycles - we run the DFS starting at all the nodes in case there
// are several disconnected subgraphs inside this dependency graph.
var CycleDFS = createDFS(this.outgoingEdges, false, [], this.circular);
keys.forEach(function (n) {
CycleDFS(n);
});
}
var DFS = createDFS(
this.outgoingEdges,
leavesOnly,
result,
this.circular
);
// Find all potential starting points (nodes with nothing depending on them) an
// run a DFS starting at these points to get the order
keys
.filter(function (node) {
return self.incomingEdges[node].length === 0;
})
.forEach(function (n) {
DFS(n);
});
// If we're allowing cycles - we need to run the DFS against any remaining
// nodes that did not end up in the initial result (as they are part of a
// subgraph that does not have a clear starting point)
if (this.circular) {
keys
.filter(function (node) {
return result.indexOf(node) === -1;
})
.forEach(function (n) {
DFS(n);
});
}
return result;
}
},
/**
* Get an array of nodes that have no dependants (i.e. nothing depends on them).
*/
entryNodes: function () {
var self = this;
return Object.keys(this.nodes).filter(function (node) {
return self.incomingEdges[node].length === 0;
});
}
};
// Create some aliases
DepGraph.prototype.directDependentsOf = DepGraph.prototype.directDependantsOf;
DepGraph.prototype.dependentsOf = DepGraph.prototype.dependantsOf;
/**
* Cycle error, including the path of the cycle.
*/
var DepGraphCycleError = (exports.DepGraphCycleError = function (cyclePath) {
var message = "Dependency Cycle Found: " + cyclePath.join(" -> ");
var instance = new Error(message);
instance.cyclePath = cyclePath;
Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
if (Error.captureStackTrace) {
Error.captureStackTrace(instance, DepGraphCycleError);
}
return instance;
});
DepGraphCycleError.prototype = Object.create(Error.prototype, {
constructor: {
value: Error,
enumerable: false,
writable: true,
configurable: true
}
});
Object.setPrototypeOf(DepGraphCycleError, Error);
|
JavaScript
|
CL
|
c0e2cfe19dd00ce146737e67d785044553e1fd3d624ab3154f1e61a011dc5d66
|
/**
* @file contract method
* @author atom-yang
*/
import {
getAddressObjectFromRep,
getRepForAddress,
getHashObjectFromHex,
getRepForHash,
getTransaction,
Transaction
} from '../util/proto';
import {
isBoolean,
isFunction,
noop,
uint8ArrayToHex
} from '../util/utils';
import {
inputAddressFormatter
} from '../util/formatters';
import wallet from '../wallet';
const isWrappedBytes = (resolvedType, name) => {
if (!resolvedType.name || resolvedType.name !== name) {
return false;
}
if (!resolvedType.fieldsArray || resolvedType.fieldsArray.length !== 1) {
return false;
}
return resolvedType.fieldsArray[0].type === 'bytes';
};
function getFieldPaths(checker, resolvedType, path) {
if (!resolvedType) {
return [];
}
if (checker(resolvedType)) {
return [path];
}
const paths = [];
resolvedType.resolve();
if (!resolvedType.fieldsArray) {
return paths;
}
resolvedType.fieldsArray.forEach(field => {
paths.push(getFieldPaths(checker, field.resolve().resolvedType, path.concat([field.name])));
});
return paths;
}
// eslint-disable-next-line max-len
const isValidPath = (paths = []) => paths.length > 0 && paths.filter(path => typeof path === 'string' && path.length > 0).length === paths.length;
const getFieldKeys = (paths = []) => {
let result = [];
// eslint-disable-next-line no-restricted-syntax
for (const path of paths) {
if (Array.isArray(path) && isValidPath(path)) {
result.push(path);
} else {
const p = getFieldKeys(path);
if (p.length > 0) {
result = [...result, ...p];
}
}
}
return result;
};
// reformatter is executed when parents are not empty
const reformat = (obj, forSelf, paths, reformatter) => {
if (forSelf) {
return reformatter(obj);
}
if (!paths || paths.length === 0) {
return obj;
}
const fieldKeys = getFieldKeys(paths);
fieldKeys.forEach(path => {
let parent = obj;
for (let i = 0; i < path.length - 1; i++) {
parent = parent[path[i]];
if (!parent) break;
}
if (parent) {
const name = path[path.length - 1];
const target = parent[name];
if (target) {
parent[name] = reformatter(target);
}
}
});
return obj;
};
const isAddress = resolvedType => isWrappedBytes(resolvedType, 'Address');
const getAddressFieldPaths = (resolvedType, path = []) => getFieldPaths(isAddress, resolvedType, path);
const maybeUglifyAddress = (obj, forSelf, paths) => reformat(obj, forSelf, paths, target => {
if (typeof target === 'string') {
return getAddressObjectFromRep(inputAddressFormatter(target));
}
if (Array.isArray(target)) {
return target.map(h => getAddressObjectFromRep(inputAddressFormatter(h)));
}
return target;
});
export const maybePrettifyAddress = (obj, forSelf, paths) => reformat(obj, forSelf, paths, target => {
if (Array.isArray(target)) {
return target.map(h => getRepForAddress(h));
}
if (typeof target !== 'string') {
return getRepForAddress(target);
}
return target;
});
const isHash = resolvedType => isWrappedBytes(resolvedType, 'Hash');
const getHashFieldPaths = (resolvedType, path = []) => getFieldPaths(isHash, resolvedType, path);
const maybeUglifyHash = (obj, forSelf, paths) => reformat(obj, forSelf, paths, target => {
if (typeof target === 'string') {
return getHashObjectFromHex(target);
}
if (Array.isArray(target)) {
return target.map(h => getHashObjectFromHex(h));
}
return target;
});
const maybePrettifyHash = (obj, forSelf, paths) => reformat(obj, forSelf, paths, target => {
if (Array.isArray(target)) {
return target.map(h => getRepForHash(h));
}
if (typeof target !== 'string') {
return getRepForHash(target);
}
return target;
});
const unpackSpecifiedTypeData = ({
data,
dataType
}) => {
const buffer = Buffer.from(data, 'hex');
const decoded = dataType.decode(buffer);
const result = dataType.toObject(decoded, {
enums: String, // enums as string names
longs: String, // longs as strings (requires long.js)
bytes: String, // bytes as base64 encoded strings
defaults: true, // includes default values
arrays: true, // populates empty arrays (repeated fields) even if defaults=false
objects: true, // populates empty objects (map fields) even if defaults=false
oneofs: true // includes virtual oneof fields set to the present field's name
});
return result;
};
export default class ContractMethod {
constructor(chain, method, contractAddress, walletInstance) {
this._chain = chain;
this._method = method;
const { resolvedRequestType, resolvedResponseType } = method;
this._inputType = resolvedRequestType;
this._outputType = resolvedResponseType;
this._inputTypeAddressFieldPaths = getAddressFieldPaths(this._inputType);
this._outputTypeAddressFieldPaths = getAddressFieldPaths(this._outputType);
this._inputTypeHashFieldPaths = getHashFieldPaths(this._inputType);
this._outputTypeHashFieldPaths = getHashFieldPaths(this._outputType);
this._isInputTypeAddress = isAddress(this._inputType);
this._isInputTypeHash = isHash(this._inputType);
this._isOutputTypeAddress = isAddress(this._outputType);
this._isOutputTypeHash = isHash(this._outputType);
this._name = method.name;
this._contractAddress = contractAddress;
this._wallet = walletInstance;
this.sendTransaction = this.sendTransaction.bind(this);
this.unpackPackedInput = this.unpackPackedInput.bind(this);
this.packInput = this.packInput.bind(this);
this.unpackOutput = this.unpackOutput.bind(this);
this.bindMethodToContract = this.bindMethodToContract.bind(this);
this.run = this.run.bind(this);
this.request = this.request.bind(this);
this.callReadOnly = this.callReadOnly.bind(this);
this.getSignedTx = this.getSignedTx.bind(this);
this.getRawTx = this.getRawTx.bind(this);
}
packInput(input) {
if (!input) {
return null;
}
let result = maybeUglifyAddress(input, this._isInputTypeAddress, this._inputTypeAddressFieldPaths);
result = maybeUglifyHash(result, this._isInputTypeHash, this._inputTypeHashFieldPaths);
const message = this._inputType.fromObject(result);
return this._inputType.encode(message).finish();
}
unpackPackedInput(inputPacked) {
if (!inputPacked) {
return null;
}
let result = unpackSpecifiedTypeData({
data: inputPacked,
dataType: this._inputType
});
result = maybePrettifyAddress(result, this._isInputTypeAddress, this._inputTypeAddressFieldPaths);
return maybePrettifyHash(result, this._isInputTypeHash, this._inputTypeHashFieldPaths);
}
unpackOutput(output) {
if (!output) {
return null;
}
let result = unpackSpecifiedTypeData({
data: output,
dataType: this._outputType
});
result = maybePrettifyAddress(result, this._isOutputTypeAddress, this._outputTypeAddressFieldPaths);
return maybePrettifyHash(result, this._isOutputTypeHash, this._outputTypeHashFieldPaths);
}
handleTransaction(height, hash, encoded) {
const rawTx = this.getRawTx(height, hash, encoded);
let tx = wallet.signTransaction(rawTx, this._wallet.keyPair);
tx = Transaction.encode(tx).finish();
if (tx instanceof Buffer) {
return tx.toString('hex');
}
return uint8ArrayToHex(tx);
}
prepareParametersAsync(args) {
const filterArgs = args.filter(arg => !isFunction(arg) && !isBoolean(arg.sync));
const encoded = this.packInput(filterArgs[0]);
return this._chain.getChainStatus().then(status => {
const { BestChainHeight, BestChainHash } = status;
return this.handleTransaction(BestChainHeight, BestChainHash, encoded);
});
}
prepareParameters(args) {
const filterArgs = args.filter(arg => !isFunction(arg) && !isBoolean(arg.sync));
const encoded = this.packInput(filterArgs[0]);
const { BestChainHeight, BestChainHash } = this._chain.getChainStatus({
sync: true
});
return this.handleTransaction(BestChainHeight, BestChainHash, encoded);
}
prepareParametersWithBlockInfo(args) {
const filterArgs = args.filter(arg => !isFunction(arg) && !isBoolean(arg.sync));
const encoded = this.packInput(filterArgs[0]);
const { height, hash } = filterArgs[1]; // blockInfo
return this.handleTransaction(height, hash, encoded);
}
sendTransaction(...args) {
const argsObject = this.extractArgumentsIntoObject(args);
if (argsObject.isSync) {
const parameters = this.prepareParameters(args);
return this._chain.sendTransaction(parameters, {
sync: true
});
}
// eslint-disable-next-line arrow-body-style
return this.prepareParametersAsync(args).then(parameters => {
return this._chain.sendTransaction(parameters, argsObject.callback);
});
}
callReadOnly(...args) {
const argsObject = this.extractArgumentsIntoObject(args);
if (argsObject.isSync) {
const parameters = this.prepareParameters(args);
return this.unpackOutput(this._chain.callReadOnly(parameters, {
sync: true
}));
}
// eslint-disable-next-line arrow-body-style
return this.prepareParametersAsync(args).then(parameters => {
return this._chain.callReadOnly(parameters, (error, result) => {
argsObject.callback(error, this.unpackOutput(result));
}).then(this.unpackOutput);
});
}
extractArgumentsIntoObject(args) {
const result = {
callback: noop,
isSync: false
};
if (args.length === 0) {
// has no callback, default to be async mode
return result;
}
if (isFunction(args[args.length - 1])) {
result.callback = args[args.length - 1];
}
args.forEach(arg => {
if (isBoolean((arg.sync))) {
result.isSync = arg.sync;
}
});
return result;
}
// getData(...args) {
getSignedTx(...args) {
const filterArgs = args.filter(arg => !isFunction(arg) && !isBoolean(arg.sync));
if (filterArgs[1]) {
const { height, hash } = filterArgs[1]; // blockInfo
if (hash && height) {
return this.prepareParametersWithBlockInfo(args);
}
throw Error('The second param is the height & hash of a block');
}
return this.prepareParameters(args);
}
getRawTx(blockHeightInput, blockHashInput, packedInput) {
const rawTx = getTransaction(this._wallet.address, this._contractAddress, this._name, packedInput);
rawTx.refBlockNumber = blockHeightInput;
const blockHash = blockHashInput.match(/^0x/) ? blockHashInput.substring(2) : blockHashInput;
rawTx.refBlockPrefix = (Buffer.from(blockHash, 'hex')).slice(0, 4);
return rawTx;
}
request(...args) {
const { callback } = this.extractArgumentsIntoObject(args);
const params = this.prepareParameters(args);
return {
method: 'broadcast_tx',
callback,
params,
format: this.unpackOutput
};
}
run(...args) {
return this.sendTransaction(...args);
}
bindMethodToContract(contract) {
const { run } = this;
run.request = this.request;
run.call = this.callReadOnly;
run.inputTypeInfo = this._inputType.toJSON();
run.inputType = this._inputType;
run.outputTypeInfo = this._outputType.toJSON();
run.outputType = this._outputType;
run.unpackPackedInput = this.unpackPackedInput;
run.packInput = this.packInput;
run.sendTransaction = this.sendTransaction;
run.getSignedTx = this.getSignedTx;
run.getRawTx = this.getRawTx;
// eslint-disable-next-line no-param-reassign
contract[this._name] = run;
}
}
|
JavaScript
|
CL
|
dcc9e187d5b8441a207dbd8562e81441e4e54c8635a57b5404e4a5f999e8031d
|
/**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:carlos@adaptive.me>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:ferran.vila.conesa@gmail.com>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } }
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
///<reference path="APIBean.ts"/>
var Adaptive;
(function (Adaptive) {
/**
@class Adaptive.ContactTag
@extends Adaptive.APIBean
Structure representing the assigned tags data elements of a contact.
@author Francisco Javier Martin Bueno
@since v2.0
@version 1.0
*/
var ContactTag = (function (_super) {
__extends(ContactTag, _super);
/**
@method constructor
Constructor used by the implementation
@param {string} tagValue Value of the tag
@param {string} tagName Name of the tag
@since v2.0
*/
function ContactTag(tagName, tagValue) {
_super.call(this);
this.tagName = tagName;
this.tagValue = tagValue;
}
Object.defineProperty(ContactTag.prototype, "tagNameProperty", {
/**
@property {string} tagName
The tagName of the Tag The 'tagNameProperty' is registered with the ECMAScript 5 Object.defineProperty() for the class field 'tagName'.
*/
get: function () {
return this.tagName;
},
set: function (tagName) {
this.tagName = tagName;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ContactTag.prototype, "tagValueProperty", {
/**
@property {string} tagValue
The tagValue of the Tag The 'tagValueProperty' is registered with the ECMAScript 5 Object.defineProperty() for the class field 'tagValue'.
*/
get: function () {
return this.tagValue;
},
set: function (tagValue) {
this.tagValue = tagValue;
},
enumerable: true,
configurable: true
});
/**
@method
Returns the tagName of the Tag
@return {string} tagName
@since v2.0
*/
ContactTag.prototype.getTagName = function () {
return this.tagName;
};
/**
@method
Set the tagName of the Tag
@param {string} tagName Name of the tag
@since v2.0
*/
ContactTag.prototype.setTagName = function (tagName) {
this.tagName = tagName;
};
/**
@method
Returns the tagValue of the Tag
@return {string} tagValue
@since v2.0
*/
ContactTag.prototype.getTagValue = function () {
return this.tagValue;
};
/**
@method
Set the tagValue of the Tag
@param {string} tagValue Value of the tag
@since v2.0
*/
ContactTag.prototype.setTagValue = function (tagValue) {
this.tagValue = tagValue;
};
/**
@method
@static
Convert JSON parsed object to typed equivalent.
@param {Object} object JSON parsed structure of type Adaptive.ContactTag.
@return {Adaptive.ContactTag} Wrapped object instance.
*/
ContactTag.toObject = function (object) {
var result = new ContactTag(null, null);
if (object != null) {
// Assign values to bean fields.
result.tagName = object.tagName;
result.tagValue = object.tagValue;
}
return result;
};
/**
@method
@static
Convert JSON parsed object array to typed equivalent.
@param {Object} object JSON parsed structure of type Adaptive.ContactTag[].
@return {Adaptive.ContactTag[]} Wrapped object array instance.
*/
ContactTag.toObjectArray = function (object) {
var resultArray = new Array();
if (object != null) {
for (var i = 0; i < object.length; i++) {
resultArray.push(ContactTag.toObject(object[i]));
}
}
return resultArray;
};
return ContactTag;
})(Adaptive.APIBean);
Adaptive.ContactTag = ContactTag;
})(Adaptive || (Adaptive = {}));
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
//# sourceMappingURL=ContactTag.js.map
|
JavaScript
|
CL
|
ea7ac07e7cbcd75e240cf12938101c748a044bbbf731ba89302e5040f5e9735e
|
import {
CheckBoxMesh,
CheckBoxSprite,
ClickableMesh,
ClickableSprite,
MouseEventManager,
RadioButtonManager,
RadioButtonMesh,
StateMaterialSet,
} from "..";
import {
AmbientLight,
BoxGeometry,
Color,
MeshBasicMaterial,
PerspectiveCamera,
Scene,
SpriteMaterial,
TextureLoader,
WebGLRenderer,
} from "three";
const W = 1280;
const H = 900;
let renderer;
let scene;
let camera;
const onDomContentsLoaded = () => {
// シーンを作成
scene = new Scene();
camera = new PerspectiveCamera(45, W / H, 1, 400);
camera.position.set(0, 0, 100);
scene.add(camera);
const renderOption = {
canvas: document.getElementById("webgl-canvas"),
antialias: true,
};
renderer = new WebGLRenderer(renderOption);
renderer.setClearColor(new Color(0x000000));
renderer.setSize(W, H);
renderer.setPixelRatio(window.devicePixelRatio);
//平行光源オブジェクト(light)の設定
const ambientLight = new AmbientLight(0xffffff, 1.0);
scene.add(ambientLight);
//マウスイベントの取得開始
const manager = new MouseEventManager(scene, camera, renderer.domElement);
testButton();
testCheckbox();
testSprite();
testSelectableSprite();
testRadio();
render();
};
/**
* Mesh用のマテリアルセットを新規に取得する。
* @returns {StateMaterialSet}
*/
const getMaterialSet = () => {
return new StateMaterialSet({
normal: getMeshMaterial(0.6),
over: getMeshMaterial(0.8),
down: getMeshMaterial(1.0),
normalSelect: getMeshMaterial(0.6, 0xffff00),
overSelect: getMeshMaterial(0.8, 0xffff00),
downSelect: getMeshMaterial(1.0, 0xffff00),
});
};
const getMeshMaterial = (opacity, color) => {
if (color == null) color = 0xffffff;
return new MeshBasicMaterial({
color: color,
opacity: opacity,
transparent: true,
});
};
/**
* スプライト用のマテリアルセットを新規に生成する。
*/
const getSpriteMaterialSet = () => {
return new StateMaterialSet({
normal: getSpriteMaterial("./btn045_01.png", 1.0),
over: getSpriteMaterial("./btn045_02.png", 1.0),
down: getSpriteMaterial("./btn045_03.png", 1.0),
normalSelect: getSpriteMaterial("./btn045_01.png", 0.5),
overSelect: getSpriteMaterial("./btn045_02.png", 0.5),
downSelect: getSpriteMaterial("./btn045_03.png", 0.5),
});
};
/**
* スプライト用マテリアルを生成する
* @param img マップ画像URL
* @param opacity 透過度
* @param color カラー
* @returns {SpriteMaterial}
*/
const getSpriteMaterial = (img, opacity, color) => {
if (color == null) color = 0xffffff;
return new SpriteMaterial({
map: new TextureLoader().load(img),
color: color,
opacity: opacity,
transparent: true,
});
};
const testButton = () => {
const geometry = new BoxGeometry(3, 3, 3);
const clickable = new ClickableMesh({
geo: geometry,
material: getMaterialSet(),
});
clickable.position.set(-10, 20, 0);
scene.add(clickable);
};
const testCheckbox = () => {
const geometry = new BoxGeometry(3, 3, 3);
const clickable = new CheckBoxMesh({
geo: geometry,
material: getMaterialSet(),
});
clickable.position.set(0, 20, 0);
scene.add(clickable);
};
const testSprite = () => {
const clickable = new ClickableSprite(getSpriteMaterialSet());
alignSprite(clickable, 10);
};
const testSelectableSprite = () => {
const selectable = new CheckBoxSprite(getSpriteMaterialSet());
alignSprite(selectable, 20);
};
const alignSprite = (sprite, x) => {
sprite.position.set(x, 20, 0);
const scale = 4.0;
sprite.scale.set(scale, scale, scale);
scene.add(sprite);
};
const testRadio = () => {
const geometry = new BoxGeometry(3, 3, 3);
const initButton = (x, buttonValue) => {
const button = new RadioButtonMesh({
geo: geometry,
material: getMaterialSet(),
});
button.position.set(x, -10, 0);
button.model.value = buttonValue;
scene.add(button);
return button;
};
const manager = new RadioButtonManager();
manager.addButton(
initButton(-10, "button01"),
initButton(0, Math.PI),
initButton(10, { value01: 1, value02: 2 })
);
manager.addButton(initButton(20, undefined));
manager.addEventListener("select", (e) => {
console.log(e.model.value);
});
};
const render = () => {
renderer.render(scene, camera);
requestAnimationFrame(render);
};
/**
* DOMContentLoaded以降に初期化処理を実行する
*/
window.onload = onDomContentsLoaded;
|
JavaScript
|
CL
|
b70dce35dd7e048bcaff33b0e7404a7f23a0f920f127b1f78a98418e1235d583
|
const spawn = require('child_process').spawnSync;
const spawnAsync = require('child_process').spawn;
const process = require('process');
const Bottleneck = require("bottleneck/es5");
function getClientIp(req) { // https://stackoverflow.com/a/14382990/619493
var ipAddress;
// Amazon EC2 / Heroku workaround to get real client IP
var forwardedIpsStr = req.header('x-forwarded-for');
if (forwardedIpsStr) {
// 'x-forwarded-for' header may return multiple IP addresses in
// the format: "client IP, proxy 1 IP, proxy 2 IP" so take the
// the first one
var forwardedIps = forwardedIpsStr.split(',');
ipAddress = forwardedIps[0];
}
if (!ipAddress) {
// Ensure getting client IP address still works in
// development environment
ipAddress = req.connection.remoteAddress;
}
return ipAddress;
};
var appRouter = function (app) {
const revision_pattern = new RegExp("^[0-9a-fA-F]+$");
const cwd = process.env.PWD; // process.cwd();
const sync_limiter = new Bottleneck({
maxConcurrent: 1,
highWater: 1,
minTime: 1000*60*5 // 5 minutes
});
const spawn_options = {
cwd: process.env.SNIPPETBIN_DATA_DIR || "/app/data",
maxBuffer: 1024*1024,
windowsHide: true
};
app.get("/test", function(req, res) {
const pwd = spawn('pwd', [], spawn_options);
res.status(200).send(`Welcome to our restful API\n pwd = ${pwd.stdout} cwd = ${cwd}\n` +
`${JSON.stringify(req.headers)}`);
});
app.get("/load_file/:revision", function(req, res) {
//Sanitize input
if (!revision_pattern.test(req.params.revision)){
res.status(400).send({"code": -1, "message": `Revision ${req.params.revision} is invalid`});
return;
}
// Call git command
const load_file = spawn(cwd + "/scripts/load_file.sh", ["-r", req.params.revision], spawn_options);
// Register spawn events
if (load_file.error){
res.status(400).send({"code": 0, "message": load_file.error});
}
else if (load_file.status == 0){
// First line contains the history, the rest contain the text
const stdout = load_file.stdout.toString().trim();
const pos = stdout.indexOf("\n");
const first_line = stdout.substring(0,pos);
const text = stdout.substring(pos+1);
const history = first_line.split(" ");
res.status(200).send({"history": history, "text": text});
} else {
// Handle non zero return value from spawn
res.status(400).send({"code": load_file.status, "message": load_file.stderr.toString()});
}
});
app.post("/save_file/", function(req, res) {
//Sanitize input
if (req.body.original_revision && !revision_pattern.test(req.body.original_revision)){
res.status(400).send({"code": -1, "message": `Original revision ${req.body.original_revision} is invalid`});
return;
}
// Create commit message from HTTP headers
const ip = getClientIp(req);
const commit_msg =
`IP: ${ip}\n`+
`Origin: ${req.headers["origin"]}\n` +
`Referer: ${req.headers["referer"]}\n` +
`Browser: ${req.headers["user-agent"]}\n` +
`Language: ${req.headers["accept-language"]}\n`+
`Country: Unknown\n` +
`Region: Unknown\n` +
`City: Unknown\n`;
// Call git command
const original_revision_arg = req.body.original_revision? ["-r", req.body.original_revision]: [];
const save_file = spawn(cwd + "/scripts/save_file.sh", ["-c", commit_msg].concat(original_revision_arg),
Object.assign({"input":req.body.text}, spawn_options));
if (save_file.error){
res.status(400).send({"code": 0, "message": save_file.error.toString()});
}
else if (save_file.status == 0){
res.status(200).send({"revision" : save_file.stdout.toString().trim()});
// Schedule database sync
sync_limiter.schedule(() => {
console.log("Syncing...");
sync = spawnAsync(cwd + "/scripts/sync.sh", [], spawn_options);
sync.stderr.pipe(process.stdout);
sync.stdout.pipe(process.stdout);
return new Promise(resolve => sync.on("exit", code => {
console.log("Sync completed with code " + code);
resolve();
}));
}).catch((err)=>{
console.log("Sync was cancelled: "+err);
});
} else {
// Handle non zero return value from spawn
res.status(400).send({"code": save_file.status, "message": save_file.stderr.toString()});
}
});
}
module.exports = appRouter;
|
JavaScript
|
CL
|
8b1a023416de4f121611d1e191fe53bc2dc5b9a9f73a5059a6d5274a6f0633f5
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
* Returns information about the platform this function is being run on.
* @internal
*/
export function getRuntimeInfo() {
return `BROWSER-VERSION; Browser ${getReleaseInfo()}`;
}
function getReleaseInfo() {
if (typeof self === "undefined") {
return "";
}
const navigator = self.navigator;
return navigator.appVersion;
}
//# sourceMappingURL=runtimeInfo.browser.js.map
|
JavaScript
|
CL
|
5151c44a78656667f49314e816c77d94478f58dcdc8acaa7bcefeac0ce790fb0
|
import { app, BrowserWindow, ipcMain, dialog } from 'electron'; // eslint-disable-line
import { join } from 'path';
import { homedir } from 'os';
import { cancel, download } from './download';
/**
* Set `__static` path to static files in production
* https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
*/
if (process.env.NODE_ENV !== 'development') {
global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\') // eslint-disable-line
}
let mainWindow;
const winURL = process.env.NODE_ENV === 'development'
? 'http://localhost:9080'
: `file://${__dirname}/index.html`;
function createWindow() {
/**
* Initial window options
*/
mainWindow = new BrowserWindow({
height: 350,
useContentSize: true,
width: 450,
autoHideMenuBar: true,
});
mainWindow.loadURL(winURL);
mainWindow.on('closed', () => {
mainWindow = null;
});
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
});
/**
* Auto Updater
*
* Uncomment the following code below and install `electron-updater` to
* support auto updating. Code Signing with a valid certificate is required.
* https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
*/
/*
import { autoUpdater } from 'electron-updater'
autoUpdater.on('update-downloaded', () => {
autoUpdater.quitAndInstall()
})
app.on('ready', () => {
if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
*/
export default function notice(eventName, ...args) {
mainWindow.webContents.send(eventName, args);
}
ipcMain.on('start-download', (event, url, doArchive) => {
let saveDir;
try {
[saveDir] = dialog.showOpenDialog(mainWindow, {
title: '保存場所を選択する',
defaultPath: join(homedir(), 'Downloads'),
properties: ['openDirectory', 'treatPackageAsDirectory'],
});
} catch (e) {
notice('canceled');
return;
}
notice('selected-directory');
download(url, saveDir, doArchive).then(() => notice('complete'), () => notice('error'));
});
ipcMain.on('cancel', () => {
cancel().then(() => notice('canceled'));
});
|
JavaScript
|
CL
|
cd8c2657aed6b40ed47cb014cab65c58b365e6b227237a01b18d6749830727b5
|
const express = require('express');
const path = require('path');
const http = require('http');
const request = require('request-promise');
const bodyParser = require('body-parser');
const app = express();
const GoogleOAuth2Strategy = require('passport-google-oauth').OAuth2Strategy;
const passport = require('passport');
const port = process.env.PORT || 3000;
const config = require('./config/config.js');
const cors = require('cors');
// Parse application/json request data.
app.use(bodyParser.json());
app.use(cors());
//----------------------------------------------PASSPORT--------------------------------------------
passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((user, done) => done(null, user));
passport.use(new GoogleOAuth2Strategy(
{
clientID: config.oAuthClientID,
clientSecret: config.oAuthclientSecret,
callbackURL: config.oAuthCallbackUrl,
},
(token, refreshToken, profile, done) => {
done(null, { profile, token })
}));
app.use(passport.initialize());
app.use(passport.session());
//----------------------------------------------ROUTES--------------------------------------------
///build path of the project
app.use(express.static(path.join(__dirname, 'dist')));
//redirect to index page
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
// Star the OAuth login process for Google.
app.get('/auth/google', passport.authenticate('google', {
scope: [
'https://www.googleapis.com/auth/photoslibrary.readonly',
'profile',
],
failureFlash: true,
session: true,
}));
var token;
// Callback receiver for the OAuth process after log in.
app.get('/authenticate', passport.authenticate('google', { failureRedirect: '/', failureFlash: true, session: true }),
(req, res) => {
// User has logged in.
console.log('User has logged in.');
token = req.user.token;
res.redirect('/#/albums');
});
// Returns all albums owned by the user.
app.get('/getAlbums', async (req, res) => {
const data = await libraryApiGetAlbums(token);
if (data.error) {
returnError(res, data);
} else {
res.status(200).send(data);
}
});
// Returns a list of all albums owner by the logged in user from the Library
// API.
async function libraryApiGetAlbums(authToken) {
let albums = [];
// let nextPageToken = null;
let error = null;
let parameters = { pageSize: 50 };
try {
do {
const result = await request.get('https://photoslibrary.googleapis.com/v1/albums', {
headers: { 'Content-Type': 'application/json' },
qs: parameters,
json: true,
auth: { 'bearer': authToken },
});
if (result && result.albums) {
const items = result.albums.filter(x => !!x);
albums = albums.concat(items);
}
parameters.pageToken = result.nextPageToken;
// Loop until all albums have been listed and no new nextPageToken is
// returned.
} while (parameters.pageToken != null);
} catch (err) {
error = err.error.error ||
{ name: err.name, code: err.statusCode, message: err.message };
console.log(error);
}
return { albums };
}
//----------------------------------------------INITIATING SERVER--------------------------------------------
const server = http.createServer(app);
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});
|
JavaScript
|
CL
|
c3e8b287ef895450197aa44d136db17579770a33f43d3b592b86208dc630ab7f
|
YUI.add("yuidoc-meta", function(Y) {
Y.YUIDoc = { meta: {
"classes": [
"Adapter",
"Adapter.OData",
"Adapter.Offline",
"ApplicationInitializer",
"ApplicationInstance",
"ApplicationInstanceInitializer",
"ArrayContainsHelper",
"ArrayHelper",
"Audit",
"BaseControlComponent",
"BaseLayer",
"BaseLayerComponent",
"BaseLegendComponent",
"BaseMapCommand",
"BaseMapCommandComponent",
"BaseMapTool",
"BaseMapToolComponent",
"BaseNonclickableMapTool",
"ColsConfigMenuService",
"ColsconfigDialogContentComponent",
"DecimalTransform",
"DetailEditFormController",
"DetailInterationService",
"DeviceService",
"DivControlComponent",
"DomActionsMixin",
"DragMapTool",
"DragMapToolComponent",
"DrawCircleMapTool",
"DrawClearMapTool",
"DrawMapTool",
"DrawMapToolComponent",
"DrawMarkerMapTool",
"DrawPolygonMapTool",
"DrawPolylineMapTool",
"DrawRectangleMapTool",
"DynamicActionObject",
"DynamicActionsMixin",
"DynamicPropertiesMixin",
"EarthCrs",
"EditFormController",
"EditFormNewRoute",
"EditFormRoute",
"EditMapController",
"EditMapNewRoute",
"EnumCaptionHelper",
"Epsg3395Crs",
"Epsg3857Crs",
"Epsg4326Crs",
"ErrorableControllerMixin",
"ExportDownloadMapCommand",
"ExportMapCommand",
"ExportMapCommandComponent",
"ExportPrintMapCommand",
"FeatureResultItemComponent",
"FileTransform",
"FlexberryAddLayerDialogComponent",
"FlexberryBaseComponent",
"FlexberryButtonComponent",
"FlexberryCheckboxComponent",
"FlexberryColorpickerComponent",
"FlexberryCswComponent",
"FlexberryDatePicker",
"FlexberryDdauCheckboxActionsHandlerMixin",
"FlexberryDdauCheckboxComponent",
"FlexberryDdauSliderActionsHandlerMixin",
"FlexberryDdauSliderComponent",
"FlexberryDialogComponent",
"FlexberryDropDown",
"FlexberryEditLayerDialogComponent",
"FlexberryEnumTransform",
"FlexberryExportMapCommandDialogComponent",
"FlexberryField",
"FlexberryFileCompatibleComponentMixin",
"FlexberryFileComponent",
"FlexberryFileControllerMixin",
"FlexberryFileViewDialogController",
"FlexberryGoToMapCommandDialogComponent",
"FlexberryGroupeditComponent",
"FlexberryGroupeditRouteMixin",
"FlexberryIconComponent",
"FlexberryIdentifyPanelComponent",
"FlexberryJsonareaComponent",
"FlexberryLayersComponent",
"FlexberryLayersDropdownComponent",
"FlexberryLayerslegendsComponent",
"FlexberryLookup",
"FlexberryLookupCompatibleComponent",
"FlexberryLookupMixin",
"FlexberryMapActionsHandlerMixin",
"FlexberryMapComponent",
"FlexberryMaplayerActionsHandlerMixin",
"FlexberryMaplayerComponent",
"FlexberryMaplayersComponent",
"FlexberryMaptoolbarComponent",
"FlexberryMaptoolbarComponet",
"FlexberryMenu",
"FlexberryMenuitem",
"FlexberryObjectlistview",
"FlexberryObjectlistviewHierarchicalControllerMixin",
"FlexberryObjectlistviewHierarchicalRouteMixin",
"FlexberryObjectlistviewOnEditFormControllerMixin",
"FlexberryObjectlistviewRouteMixin",
"FlexberryRemoveLayerDialogComponent",
"FlexberrySearchComponent",
"FlexberrySearchMapCommandDialogComponent",
"FlexberrySimpledatetime",
"FlexberryTabBarComponent",
"FlexberryTextarea",
"FlexberryTextbox",
"FlexberryToggler",
"FlexberryTreeComponent",
"FlexberryTreenodeActionsHandlerMixin",
"FlexberryTreenodeComponent",
"FlexberryValidationmessage",
"FlexberryValidationsummary",
"FormLoadTimeTrackerComponent",
"FormLoadTimeTrackerService",
"FullExtentMapCommand",
"FullExtentMapCommandComponent",
"GeocoderBaseLayerComponent",
"GeocoderOsmOverpassLayerComponent",
"GeocoderOsmOverpassLayerSettingsComponent",
"GeocoderOsmRuLayer",
"GeocoderOsmRuLayerComponent",
"GeocoderOsmRuLayerSettingsComponent",
"GeocoderOsmRuSearchSettingsComponent",
"GetWithDynamicActionsHelper",
"GoToMapCommand",
"GoToMapCommandComponent",
"GroupEditToolbarComponent",
"GroupLayer",
"GroupLayerComponent",
"GroupLayerSettingsComponent",
"GuidTransform",
"HistoryControlComponent",
"IISCaseberryLoggingObjectsApplicationLogEController",
"IISCaseberryLoggingObjectsApplicationLogERoute",
"IISCaseberryLoggingObjectsApplicationLogLController",
"IISCaseberryLoggingObjectsApplicationLogLRoute",
"IISCaseberryLoggingObjectsApplicationLogModel",
"IISCaseberryLoggingObjectsApplicationLogSerializer",
"IdentifyAllMixin",
"IdentifyAllPolygonMapTool",
"IdentifyAllRectangleMapTool",
"IdentifyAllVisiblePolygonMapTool",
"IdentifyAllVisibleRectangleMapTool",
"IdentifyMapTool",
"IdentifyMapToolComponent",
"IdentifyTopMixin",
"IdentifyTopVisiblePolygonMapTool",
"IdentifyTopVisibleRectangleMapTool",
"IdentifyVisibleMixin",
"LayerResultListComponent",
"LeafletCrsMixin",
"LeafletEventsMixin",
"LeafletOptionsMixin",
"LeafletPropertiesMixin",
"LegendControlComponent",
"LimitedController",
"LimitedRouteMixin",
"ListFormController",
"ListFormRoute",
"ListMapController",
"ListMapRoute",
"LockRouteMixin",
"LogService",
"LookupDialogController",
"LookupEvents",
"MapRoute",
"MapRouteCswLoaderMixin",
"MeasureAreaMapTool",
"MeasureClearMapTool",
"MeasureCoordinatesMapTool",
"MeasureDistanceMapTool",
"MeasureMapTool",
"MeasureMapToolComponent",
"MeasureRadiusMapTool",
"MiniMapComponent",
"Mobile.FlexberryFileComponent",
"Mobile.FlexberryGroupeditComponent",
"Mobile.FlexberryObjectlistview",
"Mobile.ObjectListViewComponent",
"Mobile.ObjectListViewRowComponent",
"ModalApplicationRoute",
"ModalDialog",
"NewPlatformFlexberryFlexberryUserSettingModel",
"NewPlatformFlexberryFlexberryUserSettingSerializer",
"NewPlatformFlexberryGISCswConnectionModel",
"NewPlatformFlexberryGISCswConnectionSerializer",
"NewPlatformFlexberryGISLayerMetadata",
"NewPlatformFlexberryGISMap",
"NewPlatformFlexberryGISMapLayer",
"NewPlatformFlexberryServicesLockAdapter",
"NewPlatformFlexberryServicesLockListController",
"NewPlatformFlexberryServicesLockListRoute",
"NewPlatformFlexberryServicesLockModel",
"NewPlatformFlexberryServicesLockSerializer",
"NewPlatformFlexberyGISCswConnectionModelMixin",
"NewPlatformFlexberyGISCswConnectionSerializerMixin",
"NewPlatformFlexberyGISLayerMetadataModelMixin",
"NewPlatformFlexberyGISLayerMetadataSerializerMixin",
"NewPlatformFlexberyGISMapLayerModelMixin",
"NewPlatformFlexberyGISMapLayerSerializerMixin",
"NewPlatformFlexberyGISMapModelMixin",
"NewPlatformFlexberyGISMapSerializerMixin",
"ObjectListViewCell",
"ObjectListViewComponent",
"ObjectListViewRowComponent",
"ObjectListViewSingleColumnCellComponent",
"ObjectlistviewEvents",
"Offline",
"Offline.DexieService",
"Offline.GlobalsService",
"Offline.LocalStore",
"Offline.Model",
"Offline.ModelMixin",
"Offline.Store",
"Offline.Syncer",
"OlvToolbar",
"PaginatedController",
"PolygonIdentifyMapTool",
"Proj4Crs",
"ProjectedModelForm",
"Projection",
"Projection.AdapterMixin",
"Projection.Model",
"Projection.StoreMixin",
"Query",
"Query.BaseAdapter",
"Query.BaseBuilder",
"Query.BasePredicate",
"Query.Builder",
"Query.ComplexPredicate",
"Query.Condition",
"Query.DetailPredicate",
"Query.FilterOperator",
"Query.IndexedDBAdapter",
"Query.JsAdapter",
"Query.ODataAdapter",
"Query.OrderByClause",
"Query.QueryObject",
"Query.SimplePredicate",
"Query.StringPredicate",
"ReadonlyCellHelper",
"RectangleIdentifyMapTool",
"RectangleMapTool",
"RegexTestHelper",
"ReloadListMixin",
"RequiredActionsMixin",
"Resolver",
"ScaleControlComponent",
"SearchAttributesMapCommand",
"SearchClearMapCommand",
"SearchMapCommand",
"SearchMapCommandComponent",
"SearchShowMapCommand",
"Security",
"Serializer",
"Serializer.Base",
"Serializer.OData",
"Serializer.Offline",
"SimpleCrs",
"SortableColumn",
"SortableControllerMixin",
"SortableRoute",
"SpaceBookmarkCommandComponent",
"SwitchScaleControlComponent",
"TileLayer",
"TileLayerComponent",
"TileLayerSettingsComponent",
"TreeNodeObject",
"UIMessage",
"UserSettingsService",
"Utils",
"Utils.Information",
"Utils.Layers",
"ValidationDataObject",
"WFSSearchSettingsComponent",
"WMSLayerComponent",
"WMSSingleTileLayerComponent",
"WfsLayer",
"WfsLayerComponent",
"WfsLayerSettingsComponent",
"WfsLegendComponent",
"WmsLayer",
"WmsLayerSettingsComponent",
"WmsLegendComponent",
"WmsSingleTileLayer",
"WmsSingleTileLayerSettingsComponent",
"WmsWfsLayer",
"WmsWfsLayerComponent",
"WmsWfsLegendComponent",
"ZoomInMapTool",
"ZoomInMapToolComponent",
"ZoomOutMapToolComponent",
"ZoomOutMaptool",
"ZoomsliderControlComponent"
],
"modules": [
"ember-flexberry",
"ember-flexberry-data",
"ember-flexberry-gis"
],
"allModules": [
{
"displayName": "ember-flexberry",
"name": "ember-flexberry"
},
{
"displayName": "ember-flexberry-data",
"name": "ember-flexberry-data",
"description": "Ember Addon that adds support of projections in models."
},
{
"displayName": "ember-flexberry-gis",
"name": "ember-flexberry-gis"
}
],
"elements": []
} };
});
|
JavaScript
|
CL
|
a169a6abb3da0ea11f1bc9c221c900501136df289ceed1cbcf8af70571d59d59
|
import Vue from 'vue';
import Router from 'vue-router';
const _import = require('./_import_' + process.env.NODE_ENV);
// import Full from '@/containers/Full'
// import Full2 from '@/containers/Full2'
// import VisitorFull from '@/containers/VisitorFull';
//
// import Buttons from '@/views/components/Buttons';
// import {visitorRouterMap} from './visitorRouterMap';
import {globalRouterMap} from './globalRouterMap';
// import {articleMgrRouterMap} from './articleMgrRouterMap';
// import {settingCenterRouterMap} from './settingCenterRouterMap';
// import {subscribeCenterRouterMap} from './subscribeCenterRouterMap';
// import {logRouterMap} from './logRouterMap';
// import {systemMgrRouterMap} from './systemMgrRouterMap';
/* login */
const Login = _import('login/index');
Vue.use(Router);
export const constantRouterMap = [
{
path: '/admin/login',
component: Login,
hidden: true
}
]
.concat(globalRouterMap)
// .concat(visitorRouterMap)
// .concat(articleMgrRouterMap)
// .concat(settingCenterRouterMap)
// .concat(logRouterMap)
// .concat(systemMgrRouterMap)
// .concat(subscribeCenterRouterMap);
const scrollBehavior = (to, from, savedPosition) => {
if (savedPosition) {
// savedPosition is only available for popstate navigations.
return savedPosition
} else {
const position = {}
// new navigation.
// scroll to anchor by returning the selector
if (to.hash) {
position.selector = to.hash
}
// check if any matched route config has meta that requires scrolling to top
if (to.matched.some(m => m.meta.scrollToTop)) {
// cords will be used if no selector is provided,
// or if the selector didn't match any element.
position.x = 0
position.y = 0
}
// if the returned position is falsy or an empty object,
// will retain current scroll position.
return position
}
}
//使用浏览器历史访问模式,可使用浏览器前进后退功能
export default new Router({
mode: 'history',
// mode: 'hash',
linkActiveClass: 'linkActiveClass',
scrollBehavior: scrollBehavior,
routes: constantRouterMap
});
|
JavaScript
|
CL
|
adb058f83ff29f4126d98d421761d4401b23292643bf0d9ba3c5455947e3eee4
|
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {expectCodeIsEqual, FakeWritable} from '../src/TestHelpers';
import {
emitNotificationDef,
emitRequestDef,
emitResponseDef,
emitTypeDef,
} from '../src/ImplementationWriter';
import { Event } from '../src/Event';
import { Command } from '../src/Command';
import { Type } from '../src/Type';
let stream = null;
beforeEach(() => {
stream = new FakeWritable();
});
test('emits type def', () => {
let obj = {
'id': 'Location',
'type': 'object',
'properties': [
{ 'name': 'scriptId', '$ref': 'Runtime.ScriptId', 'description': 'Script identifier as reported in the <code>Debugger.scriptParsed</code>.' },
{ 'name': 'lineNumber', 'type': 'integer', 'description': 'Line number in the script (0-based).' },
{ 'name': 'columnNumber', 'type': 'integer', 'optional': true, 'description': 'Column number in the script (0-based).' },
],
'description': 'Location in the source code.',
};
let type = Type.create('Debugger', obj);
emitTypeDef(stream, type);
expectCodeIsEqual(stream.get(), `
debugger::Location::Location(const dynamic &obj) {
assign(scriptId, obj, "scriptId");
assign(lineNumber, obj, "lineNumber");
assign(columnNumber, obj, "columnNumber");
}
dynamic debugger::Location::toDynamic() const {
dynamic obj = dynamic::object;
put(obj, "scriptId", scriptId);
put(obj, "lineNumber", lineNumber);
put(obj, "columnNumber", columnNumber);
return obj;
}
`);
});
test('emits request def', () => {
let obj = {
'name': 'getScriptSource',
'parameters': [
{ 'name': 'scriptId', '$ref': 'Runtime.ScriptId', 'description': 'Id of the script to get source for.' },
],
'returns': [
{ 'name': 'scriptSource', 'type': 'string', 'description': 'Script source.' },
],
'description': 'Returns source for the script with given id.',
};
let command = Command.create('Debugger', obj);
emitRequestDef(stream, command);
expectCodeIsEqual(stream.get(), `
debugger::GetScriptSourceRequest::GetScriptSourceRequest()
: Request("Debugger.getScriptSource") {}
debugger::GetScriptSourceRequest::GetScriptSourceRequest(const dynamic &obj)
: Request("Debugger.getScriptSource") {
assign(id, obj, "id");
assign(method, obj, "method");
dynamic params = obj.at("params");
assign(scriptId, params, "scriptId");
}
dynamic debugger::GetScriptSourceRequest::toDynamic() const {
dynamic params = dynamic::object;
put(params, "scriptId", scriptId);
dynamic obj = dynamic::object;
put(obj, "id", id);
put(obj, "method", method);
put(obj, "params", std::move(params));
return obj;
}
void debugger::GetScriptSourceRequest::accept(RequestHandler &handler) const {
handler.handle(*this);
}
`);
});
test('emits response def', () => {
let obj = {
'name': 'getScriptSource',
'parameters': [
{ 'name': 'scriptId', '$ref': 'Runtime.ScriptId', 'description': 'Id of the script to get source for.' },
],
'returns': [
{ 'name': 'scriptSource', 'type': 'string', 'description': 'Script source.' },
],
'description': 'Returns source for the script with given id.',
};
let command = Command.create('Debugger', obj);
emitResponseDef(stream, command);
expectCodeIsEqual(stream.get(), `
debugger::GetScriptSourceResponse::GetScriptSourceResponse(const dynamic &obj) {
assign(id, obj, "id");
dynamic res = obj.at("result");
assign(scriptSource, res, "scriptSource");
}
dynamic debugger::GetScriptSourceResponse::toDynamic() const {
dynamic res = dynamic::object;
put(res, "scriptSource", scriptSource);
dynamic obj = dynamic::object;
put(obj, "id", id);
put(obj, "result", std::move(res));
return obj;
}
`);
});
test('emits notification def', () => {
let obj = {
'name': 'messageAdded',
'parameters': [
{ 'name': 'message', '$ref': 'ConsoleMessage', 'description': 'Console message that has been added.' },
],
'description': 'Issued when new console message is added.',
};
let event = Event.create('Console', obj);
emitNotificationDef(stream, event);
expectCodeIsEqual(stream.get(), `
console::MessageAddedNotification::MessageAddedNotification()
: Notification("Console.messageAdded") {}
console::MessageAddedNotification::MessageAddedNotification(const dynamic &obj)
: Notification("Console.messageAdded") {
assign(method, obj, "method");
dynamic params = obj.at("params");
assign(message, params, "message");
}
dynamic console::MessageAddedNotification::toDynamic() const {
dynamic params = dynamic::object;
put(params, "message", message);
dynamic obj = dynamic::object;
put(obj, "method", method);
put(obj, "params", std::move(params));
return obj;
}
`);
});
|
JavaScript
|
CL
|
a05b8293252f4df90dbf6150be9f10895acdd3e7119f8e7469b0eaeebd4329a5
|
/**
* This class implements data and functionality required for AVSDF layout per
* circle.
*
*
* Copyright: i-Vis Research Group, Bilkent University, 2007 - present
*/
let LGraph = require('layout-base').LGraph;
// -----------------------------------------------------------------------------
// Section: Initializations
// -----------------------------------------------------------------------------
function AVSDFCircle(parent, graphMgr, vObject)
{
LGraph.call(this, parent, graphMgr, vObject);
this.inOrder = undefined;
this.currentIndex = 0;
this.nodeSeparation = undefined;
this.stack = [];
this.perimeter = 0;
this.centerX = 0;
this.centerY = 0;
this.radius = 0;
}
AVSDFCircle.prototype = Object.create(LGraph.prototype);
for(let property in LGraph)
{
AVSDFCircle[property] = LGraph[property];
}
AVSDFCircle.prototype.initOrdering = function()
{
this.inOrder = [];
};
// -----------------------------------------------------------------------------
// Section: Accessor Functions
// -----------------------------------------------------------------------------
// This function returns the array in which the nodes of this circle are kept in order.
AVSDFCircle.prototype.getOrder = function()
{
return this.inOrder;
};
// This function returns the x-coordinate of the center of this circle.
AVSDFCircle.prototype.getCenterX = function()
{
return this.centerX;
};
// This function returns the y-coordinate of the center of this circle.
AVSDFCircle.prototype.getCenterY = function()
{
return this.centerY;
};
// This function returns the radius of this circle.
AVSDFCircle.prototype.getRadius = function()
{
return this.radius;
};
// This function returns the total number of vertices of this circle.
AVSDFCircle.prototype.getSize = function()
{
return this.getNodes().length;
};
// This function calculates and returns the total number of crossings in this
// circle by adding up the crossing number of individual nodes on it.
AVSDFCircle.prototype.getTotalCrossingOfCircle = function()
{
let self = this;
let crossingNumber = 0;
for(let node in self.inOrder)
{
let nodeCrossing = node.getTotalCrossingOfEdges();
if(nodeCrossing === -1)
{
return -1;
}
crossingNumber += nodeCrossing;
}
return crossingNumber / 4;
};
// This function checks whether or not all of the vertices of this circle are
// assigned an index on the circle.
AVSDFCircle.prototype.hasFinishedOrdering = function()
{
return this.currentIndex === this.getNodes().length;
};
// This function returns the node separation of this circle.
AVSDFCircle.prototype.getNodeSeparation = function()
{
return this.nodeSeparation;
};
// This function sets the node separation of this circle.
AVSDFCircle.prototype.setNodeSeparation = function(nodeSeparation)
{
this.nodeSeparation = nodeSeparation;
};
// -----------------------------------------------------------------------------
// Section: Remaining Functions
// -----------------------------------------------------------------------------
// This function traverses the vertices of this circle and corrects the angle
// of the vertices with respect to their circle indices.
AVSDFCircle.prototype.correctAngles = function()
{
let self = this;
self.currentIndex = 0;
self.inOrder.forEach(
(node) => self.putInOrder(node)
);
};
// This function puts the given node on the circle in the current order and
// sets its angle appropriately.
AVSDFCircle.prototype.putInOrder = function(node)
{
let self = this;
let nodes = self.getNodes();
// Note that id attribute of a node is added before
// AVSDFLayout is called
let found = false;
for(let i = 0; i < nodes.length; i++) {
if (nodes[i].id == node.id) {
found = true;
break;
}
}
if(!found)
{
throw "The node must be a member of LGraph";
}
self.inOrder[self.currentIndex] = node;
node.setIndex(self.currentIndex);
if(self.currentIndex === 0)
{
node.setAngle(0.0);
}
else
{
node.setAngle(self.inOrder[self.currentIndex - 1].getAngle() + 2 * Math.PI *
(node.getDiagonal() / 2 + self.nodeSeparation +
self.inOrder[self.currentIndex - 1].getDiagonal() / 2)
/ self.perimeter);
}
self.currentIndex++;
};
// This function returns the next node to be placed on this circle with
// respect to the AVSDF algorithm.
AVSDFCircle.prototype.findNodeToPlace = function()
{
let self = this;
let sDegreeNode = undefined;
// Find the smallest degree vertex if the stack is empty
if(self.stack.length === 0)
{
sDegreeNode = self.findUnorderedSmallestDegreeNode();
}
// Find the first vertex in the stack not yet placed
else
{
let foundUnorderNode = false;
while (!foundUnorderNode && !(self.stack.length === 0))
{
sDegreeNode = self.stack.pop();
foundUnorderNode = !sDegreeNode.isOrdered();
}
if (!foundUnorderNode)
{
sDegreeNode = undefined;
}
}
// If no unordered vertex is found in the stack, find one
// from the remaining ones
if(sDegreeNode === undefined)
{
sDegreeNode = self.findUnorderedSmallestDegreeNode();
}
// Add the unordered neighbors of this node to the stack
if( sDegreeNode !== undefined)
{
let neighbors = sDegreeNode.getNeighborsSortedByDegree();
for(let i = neighbors.length - 1; i >= 0 ; i--)
{
let neighbor = neighbors[i];
if(!neighbor.isOrdered()) // Check here for possible error
{
self.stack.push(neighbor);
}
}
}
return sDegreeNode;
};
// This function calculates the radius of this circle with respect to the sizes
// of the vertices and the node separation parameter.
AVSDFCircle.prototype.calculateRadius = function()
{
let self = this;
let totalDiagonal = 0;
self.getNodes().forEach(
(node) => totalDiagonal += Math.sqrt(node.getWidth() * node.getWidth() + node.getHeight() * node.getHeight())
);
self.perimeter = totalDiagonal + self.getNodes().length * self.nodeSeparation;
let radius = self.perimeter / ( 2 * Math.PI);
// Check here for possible error
self.getParent().setWidth( 2 * radius );
self.getParent().setHeight( 2 * radius );
self.getParent().setCenter( self.getParent().getWidth(), self.getParent().getHeight() );
self.centerX = self.getParent().getCenterX();
self.centerY = self.getParent().getCenterY();
self.radius = self.getParent().getHeight() / 2;
};
// This function calculates the total number of crossings of all vertices of
// this circle.
AVSDFCircle.prototype.calculateEdgeCrossingsOfNodes = function()
{
this.getNodes().forEach( (node) => node.calculateTotalCrossing());
};
// This function sets the index of each vertex to its position in inOrder
// array. Note that index of a node can be different from its place in the
// array due to crossing reduction phase of the AVSDF algorithm. It loads
// old index values to vertices due to an increase in the number of
// crossings with the new indices.
AVSDFCircle.prototype.loadOldIndicesOfNodes = function()
{
//this.inOrder.forEach( (node,index) => node.setIndex(index));
var self = this;
for (let i = 0; i < this.inOrder.length; i++){
self.inOrder[i].setIndex(i);
}
};
// This function sets the position of each node in inOrder array to its index.
// Note that index of a node can be different from its place in the inOrder
// array due to crossing reduction phase of the AVSDF algorithm. This function
// puts the nodes to their new index values in inOrder array due to a
// decrease in the number of crossings with the new indices.
AVSDFCircle.prototype.reOrderVertices = function()
{
var self = this;
this.getNodes().forEach( (node) => self.inOrder[node.getIndex()] = node );
};
// This function finds and returns the unordered smallest degree vertex on
// this circle.
AVSDFCircle.prototype.findUnorderedSmallestDegreeNode = function()
{
let minDegree = Number.MAX_SAFE_INTEGER;
let sDegreeNode;
this.getNodes().forEach(
function(node){
if(node.getDegree() < minDegree && !node.isOrdered())
{
minDegree = node.getDegree();
sDegreeNode = node;
}
}
);
return sDegreeNode;
};
module.exports = AVSDFCircle;
|
JavaScript
|
CL
|
0f417e6ec42078c62377f83290732e0acfd6e807105ae5ffd3083bae6756496d
|
/*
********************************************
Copyright © 2021 Agora Lab, Inc., all rights reserved.
AppBuilder and all associated components, source code, APIs, services, and documentation
(the “Materials”) are owned by Agora Lab, Inc. and its licensors. The Materials may not be
accessed, used, modified, or distributed for any purpose without a license from Agora Lab, Inc.
Use without a license or in violation of any license terms and conditions (including use for
any purpose competitive to Agora Lab, Inc.’s business) is strictly prohibited. For more
information visit https://appbuilder.agora.io.
*********************************************
*/
/**
* @format
*/
import {AppRegistry} from 'react-native';
import * as Sentry from '@sentry/react-native';
import App from './src/App';
import {name as appName} from './app.json';
Sentry.init({
dsn: 'https://b5df0450fe284baa8376e62ace331580@o615358.ingest.sentry.io/5749898',
});
AppRegistry.registerComponent(appName, () => App);
|
JavaScript
|
CL
|
f5c2b572e6c1467c37a071120c77561cf98390aec3cc1962b5f7fa8d37e53c98
|
import React,{Component} from 'react';
import {render} from 'react-dom';
import {Section , Container , Header, Title, InputContainer, Input, ListaContainer} from './styles/styles.js';
import io from 'socket.io-client';
class App extends Component{
constructor(){
super();
this.state = {
messages: []
}
}
//iniciamos el socket en un componentDidMount -> porque esta es la manera en la cual mi aplicacion se va a cargar primero y una vez se carge voy a iniciar el componente de socket
componentDidMount(){
this.socket = io('/');
//agg otro evento para escuchar lo que viene del servidor
this.socket.on('message',message => {
//y lo agregamos a nuestro estado junto a lo que ya teniamos alli
this.setState({
messages: [message, ...this.state.messages]
})
});
}
handleSubmit(e){
//traemos la entrada de datos por medio de un evento del input y lo asignamos a una variable
const body = e.target.value;
// trabajamos con el numero 13 que es el caracter del Enter de nuestro teclado y comprobamos que el valor del input no sea nulo
if(e.keyCode === 13 && body){
//creamos un objeto y le pasamos el valor del input al socket y quien lo envia
const message= {
body,
from:'me'
};
//antes de enviarlo al socket , establecemos el mensaje con el mensaje que ya estableci mas los que tengo en el estado, para que tambien me salgan a mi por pantalla
this.setState({messages: [message, ...this.state.messages]})
//le enviamos los datos al socket
this.socket.emit('message', body);
// y limpaimos el valor del input
e.target.value = '';
}
}
render(){
//para mostrarlo en pantalla iteramos los mensajes que estan en nuestro estado a traves de map
const messages = this.state.messages.map((message,index) => {
return(
<li key={index}>
<b>{message.from} : {message.body}</b>
</li>
)
});
return(
<Section>
<Container>
<Header>
<Title>Haki Chat</Title>
</Header>
<ListaContainer>
<ul>
{messages}
</ul>
</ListaContainer>
<InputContainer>
<Input
type="text"
placeholder="Insert a message"
//usamos onKeyUp para tomar los datos que el usuario ingresa por teclado
onKeyUp={this.handleSubmit.bind(this)}
/>
</InputContainer>
</Container>
</Section>
)
}
}
render(
<App/>,document.getElementById('app')
)
|
JavaScript
|
CL
|
2cf75d4b20e2b1a21e9a913aa94109f56cf76c0b7c8f71b0e06a9ced92f1c7f0
|
module["exports"] = [
"11. Октомври",
"12. Македонска Народноослободителна Ударна Бригада",
"13. Август",
"13. Ноември",
"14. Декември",
"15. Македонски Корпус",
"20. Октомври",
"23. Октомври",
"50. Македонска Дивизија",
"8. Март",
"8. Септември",
"9. Мај",
"Аврам Пишевски",
"Австралиска",
"Александар Бујанов",
"Александар Македонски",
"Александар Македонски",
"Александар Мартулков",
"Александар Пушкин",
"Александар Турунџев",
"Александар Урдаревски - Санде",
"Алексо Демниевски - Бауман",
"Алжирска",
"Аминта III",
"Анастас Митрев",
"Ангел Винички",
"Ангел Димовски",
"Ангел Динев",
"Андон Дуков",
"Андон Кецкаров",
"Андон Папрадишки",
"Андон Тошев",
"Андреа Зограф",
"Анкарска",
"Анте Хаџи Митков",
"Антифашистички Фронт на Жените",
"Антифашистичко Собрание на Народното Ослободување на Македонија",
"Антон Панов",
"Антон Попов",
"Антон Чехов",
"Апостол Гусларот",
"Апостол Петков",
"Арсениј Јовков",
"Арсо Мицков",
"Архиепископ Ангелариј",
"Архиепископ Доситеj",
"Архимедова",
"Архитект Сотир Томовски",
"Атанас Димитров - Бабата",
"Атанас Иљовски",
"Атанас Раздолов",
"Атинска",
"Ацо Караманов",
"Ацо Шопов",
"Бабуна",
"Багдадска",
"Балканска",
"Банатска",
"Баница",
"Банско",
"Бардовечки Пат",
"Беласица",
"Белградска",
"Бел Камен",
"Белчишка",
"Беровска",
"Бертранд Расел",
"Бистра",
"Бетовенова",
"Битолска",
"Битпазарска",
"Благоја Вујов",
"Благоја Гојан",
"Благоја Стефковски",
"Благој Давков - Блацки",
"Благој Деспотовски - Шовељ",
"Благој Јанков - Мучето",
"Благој Страчков",
"Блаже Крстев - Биринчето",
"Блажо Нешков",
"Бледски Договор",
"Богомилски Поход",
"Божидар Аџија",
"Божин Николов - Силни",
"Божин Стизов",
"Божин Стојков",
"Бојаџиска",
"Боривој Милошевски",
"Борис Бојаџиски",
"Борис Кидрич",
"Борис Сарафов",
"Борис Траjковски",
"Борка Талески",
"Боро Боцевски - Боте",
"Боро Камчевски",
"Боро Кралевски",
"Боро Менков",
"Боро Петрушевски",
"Боца Ивановска",
"Браќа Галеви",
"Браќа Кошулчеви",
"Бранко Заревски",
"Брегалница",
"Бриселска",
"Будимпештанска",
"Букурешка",
"Бутелска",
"Бутелски Венец",
"Валандовска",
"Вангел Тодоровски - Мајорот",
"Ванчо Мицков",
"Вардар",
"Вардарска",
"Варшавска",
"Васил Аџиларски",
"Васил Главинов",
"Васил Ѓоргов",
"Васил Стефановски",
"Васил Чакаларов",
"Васко Карајанов",
"Васко Карангелески",
"Ваташа",
"Веле Марков",
"Велешка",
"Венијамин Мачуковски",
"Вера Циривири - Трена",
"Видое Смилевски - Бато",
"Виенска",
"Виетнамска",
"Виктор Иго",
"Вилијам Шекспир",
"Виничка",
"Винсент Ван Гог",
"Владимир Каваев",
"Владимир Мајаковски",
"Владимир Полежиноски - Полежина",
"Влае",
"Внатрешна Македонска Револуционерна Организација",
"Воденска",
"Водоча",
"Војвода Ивец",
"Војдан Чернодрински",
"Волковска",
"Волфганг Амадеус Моцарт",
"Востаничка",
"Гаврил Лесновски",
"Гаврило Радомир",
"Галичица",
"Галичник",
"Гемиџиска",
"Георги Димитров",
"Георгиј Кастриот - Скендер Бег",
"Георги Казепов",
"Георги Пешков",
"Георги Поп Христов",
"Георги Стрижевски",
"Герман",
"Герника",
"Гиго Михајловски",
"Ѓорѓе Андреевиќ - Кун",
"Ѓорѓи Абаџиев",
"Ѓорѓи Динков - Динката",
"Ѓорѓија Пулески",
"Ѓорѓи Капчев",
"Ѓорѓи Костовски",
"Ѓорѓи Сугарев",
"Ѓоре Ѓорески",
"Горноврановска",
"Горно Лисиче",
"Ѓорче Петров",
"Гостиварска",
"Гоце Делчев",
"Григор Прличев",
"Груица Војвода",
"Ѓузепе Гарибалди",
"Ѓуро Малешевец",
"Ѓуро Салај",
"Ѓуро Стругар",
"Ѓурчин Кокале",
"Дабничка",
"Дамаска",
"Даме Груев",
"Дамјан Крапчев - Стари",
"Даскал Камче",
"Даутица",
"Дебарска",
"Дебарца",
"Дејан Војвода",
"Демир Трајко",
"Депа Кавајова",
"Дижонска",
"Диме Анцин",
"Диме Мечето",
"Димитар Благоев",
"Димитар Василев - Македонски",
"Димитар Влахов",
"Димитар Гуштанов",
"Димитар Мирачиев",
"Димитар Николовски - Таки Даскалот",
"Димитар Пандилов",
"Димитар Поп-Георгиев Беровски",
"Димитар Туриманџоски",
"Димитрија Чуповски",
"Димо Хаџи Димов",
"Димче Мирчев",
"Дичо Петров",
"Добри Даскалов",
"Драган Ѓаконовски - Шпато",
"Драга Стојановска",
"Драмска",
"Дрезденска",
"Дренак",
"Дреновска Клисура",
"Дринска",
"Дубровничка",
"Дурмиторска",
"Душко Бојковски",
"Евлија Челебија",
"Езерци",
"Елисие Поповски - Марко",
"Емил Зола",
"Ениџе Вардар",
"Ернесто Че Гевара",
"Ефтим Спространов",
"Жданец",
"Жеденска",
"Женевска",
"Живко Чинго",
"Жил Верн",
"Жорж Бизе",
"Загребска",
"Зејнел Ајдини",
"Зеленгора",
"Зеничка",
"Зеф Љуш Марку",
"Злате Михајловски",
"Златко Шнајдер",
"Ибе Паликуќа",
"Иван Аговски",
"Иван Козаров",
"Иван Мажураниќ",
"Иван Наумов - Алабакот",
"Иван Тургењев",
"Иван Хаџи Николов",
"Иван Цанкар",
"Извор",
"Илија Димовски - Гоце",
"Илија Марков",
"Илија Плавев",
"Илија Ристовски",
"Илинден",
"Иљо Војвода",
"Индира Ганди",
"Индустриска",
"Исаија Мажовски",
"Истарска",
"Јабланица",
"Јадранска",
"Јајце",
"Јакупица",
"Јане Сандански",
"Јани Лукровски",
"Јоаким Крчовски",
"Јован Кукузел",
"Јорганџиска",
"Јордан Николов - Орце",
"Јордан Пиперков - Пиперката",
"Јордан Поп Јорданов - Орцето",
"Јордан Филиповски",
"Јордан Хаџи Константинов - Џинот",
"Јордан Чопела - Орде",
"Јосип Јуриј Штросмаер",
"Јосиф Даскалов",
"Јосиф Јосифовски - Свештарот",
"Јосиф Михајловиќ",
"Јохан Гутенберг",
"Јуриј Гагарин",
"Јуриј Розентал",
"Јустинијан I",
"Кавадаречка",
"Кавалска",
"Кадињача",
"Казанџиска",
"Каирска",
"Кајларска",
"Камник",
"Капиштец",
"Караорман",
"Кара Трифун",
"Караџица",
"Карбуница",
"Карпошово Востание",
"Катлановска",
"Кемал Сејфула",
"Керамидница",
"Кипарска",
"Кирe Гаврилоски - Јане",
"Кирил и Методиј",
"Кирил Манчев",
"Кирил Пејчиновиќ - Тетоец",
"Киро Глигоров",
"Киро Димишков",
"Киро Крстески - Платник",
"Киро Нацев - Фетак",
"Китка",
"Кичевска",
"Клепа",
"Климент Охридски",
"Клисурска",
"Ковачка",
"Кожув",
"Козјак",
"Козле",
"Коле Канински",
"Коле Неделковски",
"Копачка",
"Кораб",
"Корџевска",
"Коста Абраш",
"Коста Веселинов",
"Коста Кирков",
"Коста Ристовски",
"Коста Солев",
"Коста Шахов",
"Костурска",
"Костурски Херои",
"Коце Металец",
"Кочанска",
"Кочо Рацин",
"Краишка",
"Крали Марко",
"Кратовска",
"Кримска",
"Крсте Асенов",
"Крсте Гермов - Шаќир",
"Крсте Мисирков",
"Крсто Раковски",
"Крушевска Република",
"Крчин",
"Кузман Јосифоски - Питу",
"Кузман Шапкарев",
"Кујунџиска",
"Кукушка",
"Кумановска",
"Кумбара",
"Кумровец",
"Лав Толстој",
"Лавчанска Корија",
"Лазар Дамовски - Ошенски",
"Лазар Димитров",
"Лазар Личеноски",
"Лазар Поп Трајков",
"Лазар Танев",
"Лазар Трповски",
"Лазо Дренков",
"Лазо Москов",
"Лајош Кошут",
"Леринска",
"Лесновска",
"Лисец",
"Лихнида",
"Локов",
"Лондонска",
"Луj Пастер",
"Лудвиг Ван Бетовен",
"Љубин",
"Љубљанска",
"Љубо Здравковски - Орлов",
"Људевит Гај",
"Мавровска",
"Мајка Тереза",
"Мајски Манифест",
"Македонија",
"Македонска Војска",
"Македонска Преродба",
"Македонски Кралеви",
"Македонско-косовска ударна бригада",
"Максим Горки",
"Малешевска",
"Малина Попиванова",
"МАНАПО",
"Манчу Матак",
"Мара Междуречка",
"Марија Кири Склодовска",
"Мариовска",
"Марјан Лазевски",
"Маркова Река",
"Марко Цепенков",
"Марк Твен",
"Маршал Тито",
"Махатма Ганди",
"Маџари",
"Маџир Маало",
"Мегленска",
"Места",
"Методија Андонов - Ченто",
"Методија Патчев",
"Методија Шаторов - Шарло",
"Метохиска",
"Мечкин Камен",
"Мијачка",
"Милан Комненоски",
"Миле Поп Јорданов",
"Мирка Гинова",
"Мирче Ацев",
"Мирче Мацанов",
"Мис Елен Стон",
"Мите Богоевски",
"Мито Хаџивасилев - Јасмин",
"Митре Влаот",
"Михаил Глинка",
"Михаил и Ефтихиј",
"Михаил Цоков",
"Михаил Чаков",
"Мице Козароски - Јандре",
"Мишевска",
"Мишко Михајловски",
"Модест Мусогорски",
"Мокра",
"Момин Поток",
"Морава",
"Московска",
"Мостарска",
"Мраморец",
"Мрежичка",
"Мукос",
"Мустафа Кемал Ататурк",
"Мутавџиска",
"Надбискуп Чекада",
"Надежда Крупскаја",
"Народен Фронт",
"Натанаил Кучевишки",
"Наум Наумоски - Борче",
"Наум Охридски",
"Наум Чакаров",
"Невена Георгиева - Дуња",
"Неврокопска",
"Негоричанска",
"Неготинска",
"Никола Вапцаров",
"Никола Грчето",
"Николај Островски",
"Никола Карев",
"Никола Киров - Мајски",
"Никола Кљусев",
"Никола Коперник",
"Никола Малешевски",
"Никола Мартиноски",
"Никола Парапунов",
"Никола Петров",
"Никола Петров - Русински",
"Никола Пушкаров",
"Никола Тесла",
"Никола Тримпаре",
"Ниџе Планина",
"Нов Живот",
"Новопроектирана",
"Њуделхиска",
"Овчеполска",
"Огражден",
"Опинчарска",
"Оровска",
"Осло",
"Островска",
"Отокар Кершовани",
"Отон Жупанчич",
"Охридска",
"Павел Шатев",
"Павле Илиќ",
"Пајак Планина",
"Палмиро Тољати",
"Панајот Гиновски",
"Пандил Шишков",
"Пандо Кљашев",
"Панко Брашнаров",
"Панче Арсовски",
"Панче Неделковски",
"Папуџиска",
"Париска",
"Париска Комуна",
"Партение Зографски",
"Партизански Одреди",
"Патрис Лумумба",
"Пејо Јаворов",
"Пелинце",
"Пелистерска",
"Пере Тошев",
"Перо Наков",
"Петар Ацев",
"Петар Драпшин",
"Петар Ичко",
"Петар Манџуков",
"Петар Поп Арсов",
"Петар Чајковски",
"Петар Чангов",
"Петар Чаулев",
"Петко Јанчевски",
"Петре Георгиев",
"Петре Пирузе",
"Петре Филиповски - Гарката",
"Петричка",
"Пехчевска",
"Пијанец",
"Пиринска",
"Питу Гули",
"Плачковица",
"Покриена Чаршија",
"Полог",
"Поп Богомил",
"Прашка",
"Презвитер Константин",
"Пресека",
"Преспанска",
"Пржино",
"Призренска",
"Прилепска",
"Пробиштипска",
"Пролет",
"Просек",
"Прохор Пчињски",
"Раде Јовчевски - Корчагин",
"Радика",
"Радишанска",
"Радњанска",
"Радобил",
"Радослав Петковски",
"Радушка",
"Разловечко Востание",
"Разлошка",
"Рајко Жинзифов",
"Рампо Левков - Левката",
"Рафаел Батино",
"Рељо Шесто Крило",
"Ресенска",
"Речиште",
"Ризо Ризов",
"Римска",
"Ристо Равановски",
"Ристо Шишков",
"Роcа Плавева",
"Роза Луксембург",
"Рокомија",
"Романија",
"Ромен Ролан",
"Роналд Реган",
"Рударска",
"Рудо",
"Румена Хаџи Панзова",
"Сава Михајлов",
"Салих Асим",
"Самарџиска",
"Самоилова",
"Сараевска",
"Сарачка",
"Саса",
"Свеќарска",
"Светиниколска",
"Светозар Марковиќ",
"Серава",
"Сердарот",
"Серска",
"Симеон Кавракиров",
"Симче Настевски",
"Сирма Војвода",
"Славе Георгиевски - Шнајдер",
"Славе Деловски",
"Славејко Арсов",
"Славеј Планина",
"Славка Димкова",
"Славчо Стојменски",
"Сливовска",
"Смилевска",
"Солунска",
"Солунска Глава",
"Софиска",
"Софре Марковски",
"Спиро Големџиојски - Црне",
"Спиро Гулапчев",
"Стале Попов",
"Стари Новак",
"Стефан Верковиќ",
"Стефан Јакимов - Дедов",
"Стефан Наумов - Стив",
"Стјепан Филиповиќ - Стево",
"Стоби",
"Стогово",
"Стојко Јовановски",
"Стојна Стевкова",
"Стокхолмска",
"Страхил Пинџуров",
"Страшо Пинџур",
"Стрезово",
"Стрмашево",
"Струма",
"Струмичка",
"Струмјани",
"Струшка",
"Тајмишка",
"Тале Христов",
"Тасино Чешмиче",
"Ташкентска",
"Ташко Караџа",
"Темко Попов",
"Теодосиј Гологанов",
"Теодосиј Синаитски",
"Тиранска",
"Товарник",
"Тодор Александров",
"Тодор Циповски - Мерџан",
"Тодор Чангов",
"Тодор Чапов",
"Томас Минцер",
"Томе Арсовски",
"Томе Пуре",
"Томе Стефановски",
"Томе Томшиќ",
"Топаанска",
"Тоше Проески",
"Трајко Иванов",
"Трајко Китанчев",
"Три Круши",
"Трифун Бузев",
"Трифун Пановски",
"Трифун Хаџи Јанев",
"Трнодол",
"Трпе Петревски",
"Тушинска",
"Ужичка Република",
"Февруарски Поход",
"Федерико Гарсија Лорка",
"Ферид Бајрам",
"Ферид Заири",
"Филип II Македонски",
"Финска",
"Фјодор Достоевски",
"Франклин Рузвелт",
"Франсоа Волтер",
"Франце Прешерн",
"Франц Лист",
"Фрањо Клуз",
"Фредерик Шопен",
"Фуштанска",
"Хаванска",
"Хаџи Јован Шишков",
"Хаџи Трајко",
"Хашка",
"Хелсинки",
"Хераклеа Линкестис",
"Хо Ши Мин",
"Христијан Тодоровски - Карпош",
"Христо Батанџиев",
"Христо Смирненски",
"Христо Татарчев",
"Христо Узунов",
"Христо Чернопеев",
"Хусеин Бајрам",
"Цветан Димов - Чаирчанец",
"Цветан Цветковски",
"Церска",
"Цетињска",
"Црвена Вода",
"Црвени Брегови",
"Црниче",
"Црногорска",
"Црноок",
"Црноризец Храбар",
"Чаирска",
"Чудомир Кантарџиев",
"Чупино Брдо",
"Џумајска",
"Шандор Петефи",
"Шар Планина",
"Шарски Одред",
"Шина Стојанова",
"Штипска",
"Шундаревска"
];
|
JavaScript
|
CL
|
b6d776dd47c2bd96700f898130dbed9a14ed5f997c9cb3f4d027e2c2265f8cbf
|
/** @jsx jsx */
import { jsx } from "@emotion/core";
import theme from "../../config/theme";
import SectionHeader from "../SectionHeading";
import JumpOffset from "../JumpOffset";
import Markdown from "../controls/Markdown";
const AboutUs = ({
sectionTitle = "O nás",
imageUri = "https://i.imgur.com/NXerfN2.jpg",
headerImageUri = "https://i.imgur.com/aryuWJR.jpg",
headerImageHeight = 600,
textMd = `
Náš restaurant SEKERY je zatím poslední realizací našeho
rodinnéhořeznictví Kratochvíl. Tradice řeznictví Kratochvíl započala v
našírodině již roku 1875, kdy můj pra pra pra dědeček František
Kratochvíl otevřel na Smíchově své řeznictví. V roce 1904 převzal
úspěšně řeznictví můj pra pra děda František Kratochvíl a vedl ho až
do roku 1948. V tomto roce ho "zabavil" komunistický režim a pra pra
děda byl přinucen vyměnit řezničinu za práci v huti na Kladně.
Řeznickému řemeslu však zůstal věrný a ve volném čase se věnoval
"rodinným" zabijačkám. Po pádu režimu se k řeznickému řemeslu v roce
1992 přidal i můj otec František Kratochvíl a "vrátil" naše tradiční
řeznictví na výslunní. Jako vášnivý myslivec navíc přidal do nabídky
zvěřinu a značně rozšířil výrobnu. V roce 2017 jsem převzal řeznictví
já a navazuji s hrdostí na naši dlouholetou tradici. Každý Kratochvíl
naše řeznictví posílil a posunul dál. Ani já tak nezůstávám pozadu a
věřím, že naše nová restaurace / řeznická jídelna SEKERY si brzy získá
své spokpojené hostya štamgasty. Přijďte i vy ochutnat kus české
tradice k nám na Anděl.
Těším se na vás.
Michal František Kratochvíl
`
}) => {
return (
<section
css={{
marginBottom: theme.spacing * 2
}}
>
<JumpOffset id="o-nas" />
<SectionHeader
backgroundUrl={headerImageUri}
css={{
backgroundAttachment: "scroll",
backgroundPosition: "center center",
backgroundSize: "auto auto",
height: headerImageHeight - theme.spacing * 2,
minHeight: 0
}}
>
{sectionTitle}
</SectionHeader>
<div
css={{
padding: theme.spacing,
[`@media (min-width: ${theme.breakpoint.large}px)`]: {
display: "grid",
gridTemplateColumns: "1fr 2fr",
gridGap: theme.spacing
}
}}
>
<div>
<Markdown source={textMd} />
</div>
<div>
<img css={{ width: "100%" }} src={imageUri} />
</div>
</div>
</section>
);
};
export default AboutUs;
|
JavaScript
|
CL
|
65cfbcd6931698a30d746579e0f3423231fe299b2cffe3f1e27b27bfd5942c1d
|
'use strict'
const Empresa = use('App/Models/Empresa')
const Database = use('Database')
/** @typedef {import('@adonisjs/framework/src/Request')} Request */
/** @typedef {import('@adonisjs/framework/src/Response')} Response */
/** @typedef {import('@adonisjs/framework/src/View')} View */
/**
* Resourceful controller for interacting with empresas
*/
class EmpresaController {
/**
* Show a list of all empresas.
* GET empresas
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {View} ctx.view
*/
async index () {
const empresas = Empresa.query().with('avaliacao').fetch()
// await empresas.load('avaliacao')
return empresas
}
/**
* Create/save a new empresa.
* POST empresas
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async store ({ request, response }) {
const data = request.only([
'nome_empresa',
'cod_empresa',
'bairro_empresa',
'situação_empresa'
])
const empresa = await Empresa.create(data)
return empresa
}
/**
* Display a single empresa.
* GET empresas/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {View} ctx.view
*/
async show ({ params, request, response, view }) {
const empresa = await Empresa.query().where('id',params.id).with('avaliacao').fetch()
// console.log(Empresa.query().with('avaliacao').fetch())
// empresa = await empresa.query().with('avaliacao').fetch()
// .findOrFail(params.empresa_id)
return empresa
}
/**
* Update empresa details.
* PUT or PATCH empresas/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async update ({ params, request, response }) {
const empresa = await Empresa.findOrFail(params.id)
const data = request.only([
'nome_empresa',
'cod_empresa',
'bairro_empresa',
'situação_empresa'
])
empresa.merge(data)
await empresa.save()
return empresa
}
/**
* Delete a empresa with id.
* DELETE empresas/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async destroy ({ params, request, response }) {
const empresa = await Empresa.findOrFail(params.id)
await empresa.delete()
}
}
module.exports = EmpresaController
|
JavaScript
|
CL
|
f7fa7ac49ecc85e7aecb579178f7a9c948d751ca24ba500a7de2cdffa319be96
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
define("mojo/services/location/interfaces/location.mojom", [
"mojo/public/js/bindings",
"mojo/public/js/codec",
"mojo/public/js/connection",
"mojo/public/js/core",
"mojo/public/js/validator",
], function(bindings, codec, connection, core, validator) {
function Location(values) {
this.initDefaults_();
this.initFields_(values);
}
Location.prototype.initDefaults_ = function() {
this.time = 0;
this.has_elapsed_real_time_nanos = false;
this.has_altitude = false;
this.has_speed = false;
this.has_bearing = false;
this.has_accuracy = false;
this.speed = 0;
this.elapsed_real_time_nanos = 0;
this.latitude = 0;
this.longitude = 0;
this.altitude = 0;
this.bearing = 0;
this.accuracy = 0;
};
Location.prototype.initFields_ = function(fields) {
for(var field in fields) {
if (this.hasOwnProperty(field))
this[field] = fields[field];
}
};
Location.validate = function(messageValidator, offset) {
var err;
err = messageValidator.validateStructHeader(offset, Location.encodedSize, 0);
if (err !== validator.validationError.NONE)
return err;
return validator.validationError.NONE;
};
Location.encodedSize = codec.kStructHeaderSize + 56;
Location.decode = function(decoder) {
var packed;
var val = new Location();
var numberOfBytes = decoder.readUint32();
var version = decoder.readUint32();
val.time = decoder.decodeStruct(codec.Uint64);
packed = decoder.readUint8();
val.has_elapsed_real_time_nanos = (packed >> 0) & 1 ? true : false;
val.has_altitude = (packed >> 1) & 1 ? true : false;
val.has_speed = (packed >> 2) & 1 ? true : false;
val.has_bearing = (packed >> 3) & 1 ? true : false;
val.has_accuracy = (packed >> 4) & 1 ? true : false;
decoder.skip(1);
decoder.skip(1);
decoder.skip(1);
val.speed = decoder.decodeStruct(codec.Float);
val.elapsed_real_time_nanos = decoder.decodeStruct(codec.Uint64);
val.latitude = decoder.decodeStruct(codec.Double);
val.longitude = decoder.decodeStruct(codec.Double);
val.altitude = decoder.decodeStruct(codec.Double);
val.bearing = decoder.decodeStruct(codec.Float);
val.accuracy = decoder.decodeStruct(codec.Float);
return val;
};
Location.encode = function(encoder, val) {
var packed;
encoder.writeUint32(Location.encodedSize);
encoder.writeUint32(0);
encoder.encodeStruct(codec.Uint64, val.time);
packed = 0;
packed |= (val.has_elapsed_real_time_nanos & 1) << 0
packed |= (val.has_altitude & 1) << 1
packed |= (val.has_speed & 1) << 2
packed |= (val.has_bearing & 1) << 3
packed |= (val.has_accuracy & 1) << 4
encoder.writeUint8(packed);
encoder.skip(1);
encoder.skip(1);
encoder.skip(1);
encoder.encodeStruct(codec.Float, val.speed);
encoder.encodeStruct(codec.Uint64, val.elapsed_real_time_nanos);
encoder.encodeStruct(codec.Double, val.latitude);
encoder.encodeStruct(codec.Double, val.longitude);
encoder.encodeStruct(codec.Double, val.altitude);
encoder.encodeStruct(codec.Float, val.bearing);
encoder.encodeStruct(codec.Float, val.accuracy);
};
var exports = {};
exports.Location = Location;
return exports;
});
|
JavaScript
|
CL
|
ee29189313ff6e240e1049a6262671f80e3afc66559aaf37c189038cda4828fc
|
import*as Common from"../common/common.js";import*as Components from"../components/components.js";import*as Host from"../host/host.js";import*as PerfUI from"../perf_ui/perf_ui.js";import*as SDK from"../sdk/sdk.js";import*as UI from"../ui/ui.js";import{ProfileFlameChartDataProvider}from"./CPUProfileFlameChart.js";import{Formatter,ProfileDataGridNode}from"./ProfileDataGrid.js";import{ProfileEvents,ProfileHeader,ProfileType}from"./ProfileHeader.js";import{ProfileView,WritableProfileHeader}from"./ProfileView.js";export class CPUProfileView extends ProfileView{constructor(e){super(),this._profileHeader=e,this.initialize(new NodeFormatter(this));const r=e.profileModel();this.adjustedTotal=r.profileHead.total,this.adjustedTotal-=r.idleNode?r.idleNode.total:0,this.setProfile(r)}wasShown(){super.wasShown();const e=self.runtime.sharedInstance(PerfUI.LineLevelProfile.Performance);e.reset(),e.appendCPUProfile(this._profileHeader.profileModel())}columnHeader(e){switch(e){case"self":return Common.UIString.UIString("Self Time");case"total":return Common.UIString.UIString("Total Time")}return""}createFlameChartDataProvider(){return new CPUFlameChartDataProvider(this._profileHeader.profileModel(),this._profileHeader._cpuProfilerModel)}}export class CPUProfileType extends ProfileType{constructor(){super(CPUProfileType.TypeId,Common.UIString.UIString("Record JavaScript CPU Profile")),this._recording=!1,CPUProfileType.instance=this,SDK.SDKModel.TargetManager.instance().addModelListener(SDK.CPUProfilerModel.CPUProfilerModel,SDK.CPUProfilerModel.Events.ConsoleProfileFinished,this._consoleProfileFinished,this)}profileBeingRecorded(){return super.profileBeingRecorded()}typeName(){return"CPU"}fileExtension(){return".cpuprofile"}get buttonTooltip(){return this._recording?Common.UIString.UIString("Stop CPU profiling"):Common.UIString.UIString("Start CPU profiling")}buttonClicked(){return this._recording?(this._stopRecordingProfile(),!1):(this._startRecordingProfile(),!0)}get treeItemTitle(){return Common.UIString.UIString("CPU PROFILES")}get description(){return Common.UIString.UIString("CPU profiles show where the execution time is spent in your page's JavaScript functions.")}_consoleProfileFinished(e){const r=e.data,t=r.cpuProfile,o=new CPUProfileHeader(r.cpuProfilerModel,this,r.title);o.setProtocolProfile(t),this.addProfile(o)}_startRecordingProfile(){const e=self.UI.context.flavor(SDK.CPUProfilerModel.CPUProfilerModel);if(this.profileBeingRecorded()||!e)return;const r=new CPUProfileHeader(e,this);this.setProfileBeingRecorded(r),SDK.SDKModel.TargetManager.instance().suspendAllTargets(),this.addProfile(r),r.updateStatus(Common.UIString.UIString("Recording…")),this._recording=!0,e.startRecording(),Host.userMetrics.actionTaken(Host.UserMetrics.Action.ProfilesCPUProfileTaken)}async _stopRecordingProfile(){if(this._recording=!1,!this.profileBeingRecorded()||!this.profileBeingRecorded()._cpuProfilerModel)return;const e=await this.profileBeingRecorded()._cpuProfilerModel.stopRecording(),r=this.profileBeingRecorded();r&&(console.assert(e),r.setProtocolProfile(e),r.updateStatus(""),this.setProfileBeingRecorded(null)),await SDK.SDKModel.TargetManager.instance().resumeAllTargets(),this.dispatchEventToListeners(ProfileEvents.ProfileComplete,r)}createProfileLoadedFromFile(e){return new CPUProfileHeader(null,this,e)}profileBeingRecordedRemoved(){this._stopRecordingProfile()}}CPUProfileType.TypeId="CPU";export class CPUProfileHeader extends WritableProfileHeader{constructor(e,r,t){super(e&&e.debuggerModel(),r,t),this._cpuProfilerModel=e}createView(){return new CPUProfileView(this)}protocolProfile(){return this._protocolProfile}profileModel(){return this._profileModel}setProfile(e){const r=this._cpuProfilerModel&&this._cpuProfilerModel.target()||null;this._profileModel=new SDK.CPUProfileDataModel.CPUProfileDataModel(e,r)}}export class NodeFormatter{constructor(e){this._profileView=e}formatValue(e){return Common.UIString.UIString("%.1f ms",e)}formatValueAccessibleText(e){return this.formatValue(e)}formatPercent(e,r){return r.profileNode===this._profileView.profile().idleNode?"":Common.UIString.UIString("%.2f %%",e)}linkifyNode(e){const r=this._profileView._profileHeader._cpuProfilerModel,t=r?r.target():null;return this._profileView.linkifier().maybeLinkifyConsoleCallFrame(t,e.profileNode.callFrame,{className:"profile-node-file"})}}export class CPUFlameChartDataProvider extends ProfileFlameChartDataProvider{constructor(e,r){super(),this._cpuProfile=e,this._cpuProfilerModel=r}_calculateTimelineData(){const e=[],r=[];let t=5;this._cpuProfile.forEachFrame((function(){r.push(e.length),e.push(null)}),(function(o,i,l,n,s){const a=r.pop();e[a]=new CPUFlameChartDataProvider.ChartEntry(o,n,l,s,i),t=Math.max(t,o)}));const o=new Array(e.length),i=new Uint16Array(e.length),l=new Float32Array(e.length),n=new Float32Array(e.length),s=new Float64Array(e.length);for(let r=0;r<e.length;++r){const t=e[r];o[r]=t.node,i[r]=t.depth,l[r]=t.duration,s[r]=t.startTime,n[r]=t.selfTime}return this._maxStackDepth=t+1,this._timelineData=new PerfUI.FlameChart.TimelineData(i,l,s,null),this._entryNodes=o,this._entrySelfTimes=n,this._timelineData}prepareHighlightedEntryInfo(e){const r=this._timelineData,t=this._entryNodes[e];if(!t)return null;const o=[];function i(e,r){o.push({title:e,value:r})}function l(e){return 0===e?"0":e<1e3?Common.UIString.UIString("%.1f ms",e):Number.secondsToString(e/1e3,!0)}const n=UI.UIUtils.beautifyFunctionName(t.functionName);i(ls`Name`,n);const s=l(this._entrySelfTimes[e]),a=l(r.entryTotalTimes[e]);i(ls`Self time`,s),i(ls`Total time`,a);const f=new Components.Linkifier.Linkifier,d=f.maybeLinkifyConsoleCallFrame(this._cpuProfilerModel&&this._cpuProfilerModel.target(),t.callFrame);return d&&i(ls`URL`,d.textContent),f.dispose(),i(ls`Aggregated self time`,Number.secondsToString(t.self/1e3,!0)),i(ls`Aggregated total time`,Number.secondsToString(t.total/1e3,!0)),t.deoptReason&&i(ls`Not optimized`,t.deoptReason),ProfileView.buildPopoverTable(o)}}CPUFlameChartDataProvider.ChartEntry=class{constructor(e,r,t,o,i){this.depth=e,this.duration=r,this.startTime=t,this.selfTime=o,this.node=i}};
|
JavaScript
|
CL
|
cbdf7437d48c5a56407704d4dc06dfc0bd256ff6d262fe8fbea0b0f758c8c8e7
|
require('dotenv').config();
const express = require('express'),
app = express(),
extend = require('util')._extend,
request = require('request'),
i18n = require('i18next'),
slack = require('./routes/slack');
app.use(require('body-parser').json());
app.use('/slack', slack);
//i18n settings
require('./config/i18n')(app);
// Bootstrap application settings
require('./config/express')(app);
app.get('/', function (req, res) {
res.render('index', {
ct: req._csrfToken
});
});
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p, 'reason:', reason);
// application specific logging, throwing an error, or other logic here
});
// error-handler settings
require('./config/error-handler')(app);
var port = process.env.PORT || process.env.VCAP_APP_PORT || 3000;
app.listen(port);
console.log('listening at:', port);
|
JavaScript
|
CL
|
38dd2c453252421554bf6e3c0f92e5a3f38b1c969e0cdde33e6eaa17b71c1060
|
import React, { useEffect } from "react"
import axios from "axios"
// import { Link } from "react-router-dom"
import { connect } from "react-redux"
import { updateUser, updateRegisteredClans } from "../../ducks/reducer"
import AccountImage from "./AccountImage/AccountImage"
import Notification from "./Notification/Notification"
//MaterialUI
import PropTypes from "prop-types"
import { withStyles } from "@material-ui/core/styles"
import AppBar from "@material-ui/core/AppBar"
import Toolbar from "@material-ui/core/Toolbar"
import Typography from "@material-ui/core/Typography"
import Button from "@material-ui/core/Button"
import Menu from "./Menu/Menu"
import logo from "./gamehub.png"
const styles = {
root: {
// flexGrow: 1,
overflow: "hidden",
position: "relative",
zIndex: 1
},
grow: {
flexGrow: 1
},
navbar: {
backgroundColor: "#414744",
color: "#FF473A",
transparency: 0.6,
position: "relative",
top: 0
},
card: {
maxWidth: 345
}
}
function Nav(props) {
useEffect(() => {
handleCurrent()
})
function handleLogout() {
try {
props.auth.logout()
axios.post("/auth/logout")
} catch (err) {
console.log(err)
}
}
async function handleCurrent() {
try {
const { updateUser, updateRegisteredClans, history, location } = props
const user = await axios.get("/auth/account")
updateUser(user.data)
const getRegisteredClans = await axios.get("/api/registeredclans")
updateRegisteredClans(getRegisteredClans.data)
if (user && location.pathname === "/") {
history.push("/dashboard")
}
} catch (err) {
if (location.pathname !== "/") {
props.history.push("/")
}
}
}
const { classes, location } = props
return (
<div className={classes.root}>
<AppBar className={classes.navbar}>
<Toolbar>
{location.pathname !== "/" && <Menu history={props.history} />}
<Typography variant="h6" color="inherit" className={classes.grow}>
<img
style={{
width: "300px",
height: "75px"
}}
src={logo}
alt="logo"
/>
</Typography>
{location.pathname === "/" ? (
<Button onClick={props.auth.login} color="inherit">
Login
</Button>
) : (
<>
<Notification />
<AccountImage handleLogout={handleLogout} />
</>
)}
</Toolbar>
</AppBar>
</div>
)
}
Nav.propTypes = {
classes: PropTypes.object.isRequired
}
const mapDispatchToProps = {
updateUser,
updateRegisteredClans
}
export default connect(
null,
mapDispatchToProps
)(withStyles(styles)(Nav))
|
JavaScript
|
CL
|
15203beb0cb88d723113b69f17e20929a3ce149f321ad1235e7024db7082ec4f
|
import React from 'react'
import { graphql } from 'gatsby'
// import { mapEdgesToNodes, filterOutDocsWithoutSlugs } from '../lib/helpers'
// import BlogPostPreviewGrid from '../components/blog-post-preview-grid'
import Container from '../components/container'
import GraphQLErrorList from '../components/graphql-error-list'
import SEO from '../components/seo'
import Landing from '../containers/landing'
import Layout from '../containers/layout'
export const query = graphql`
query IndexPageQuery {
posts: allSanityPost(
limit: 6
sort: { fields: [publishedAt], order: DESC }
) {
edges {
node {
id
publishedAt
mainImage {
crop {
_key
_type
top
bottom
left
right
}
hotspot {
_key
_type
x
y
height
width
}
asset {
_id
}
alt
}
title
_rawExcerpt
slug {
current
}
}
}
}
}
`
const IndexPage = props => {
// const { data, errors } = props
const { errors } = props
if (errors) {
return (
<Layout>
<GraphQLErrorList errors={errors} />
</Layout>
)
}
// const postNodes = (data || {}).posts
// ? mapEdgesToNodes(data.posts).filter(filterOutDocsWithoutSlugs)
// : []
return (
<Layout>
<SEO />
<Container>
<Landing />
{/* {postNodes.length !== 0 && (
<BlogPostPreviewGrid
title="Latest blog posts"
nodes={postNodes}
browseMoreHref="/blog/"
/>
)} */}
</Container>
</Layout>
)
}
export default IndexPage
|
JavaScript
|
CL
|
71f8b6becd4eba2badd8fdc0c47ee66d4fcb6dcf67fed6a37289059a56f03d41
|
/**
* @author troffmo5 / http://github.com/troffmo5
*
* Google Street View viewer for the Oculus Rift
*
* Modified by jpleitao / http://github.com/jpleitao
*/
// Parameters
// ----------------------------------------------
var QUALITY;
var DEFAULT_LOCATION;
var SHOW_SETTINGS;
var NAV_DELTA;
var FAR;
var USE_DEPTH;
var scene;
var camera;
var controls;
var projSphere;
var progBarContainer;
var progBar;
var renderer;
var effect;
var vrmgr;
var panoLoader;
var panoDepthLoader;
var rotation_angle_cons;
var rotation;
// Globals
// ----------------------------------------------
var WIDTH, HEIGHT;
var currHeading = 0;
var centerHeading = 0;
var headingVector;
// Utility function
// ----------------------------------------------
function angleRangeDeg( angle ) {
angle %= 360;
if ( angle < 0 ) {
angle += 360;
}
return angle;
}
function deltaAngleDeg( a, b ) {
return Math.min( 360 - ( Math.abs( a - b ) % 360 ), Math.abs( a - b ) % 360 );
}
// ----------------------------------------------
function initWebGL() {
// create scene
scene = new THREE.Scene();
// Create camera
camera = new THREE.PerspectiveCamera( 60, WIDTH/HEIGHT, 0.1, FAR );
camera.lookAt(new THREE.Vector3( 1, 0, 0 ));
camera.rotation.order = 'YXZ'; // Rotate first around the Y-Axis, then X, then Z
// Add VR Controls
controls = new THREE.VRControls( camera );
// Add camera to the scene
scene.add( camera );
// Add projection sphere
projSphere = new THREE.Mesh( new THREE.SphereGeometry( 500, 512, 256, 0, Math.PI * 2, 0, Math.PI ),
new THREE.MeshBasicMaterial( {
map: THREE.ImageUtils.loadTexture( 'images/placeholder.png' ),
side: THREE.DoubleSide
} ) );
projSphere.geometry.dynamic = true;
scene.add( projSphere );
// Add Progress Bar
progBarContainer = new THREE.Mesh( new THREE.BoxGeometry( 1.2, 0.2, 0.1),
new THREE.MeshBasicMaterial( {color: 0xaaaaaa} ) );
progBarContainer.translateZ( -3 );
camera.add( progBarContainer );
progBar = new THREE.Mesh( new THREE.BoxGeometry( 1.0, 0.1, 0.1 ),
new THREE.MeshBasicMaterial( {color: 0x0000ff} ) );
progBar.translateZ( 0.2 );
progBarContainer.add( progBar );
// Create render
try {
renderer = new THREE.WebGLRenderer();
} catch( e ){
alert( 'This application needs WebGL enabled!' );
return false;
}
renderer.autoClearColor = false;
renderer.setSize( WIDTH, HEIGHT );
effect = new THREE.VREffect( renderer );
effect.setSize( WIDTH, HEIGHT );
vrmgr = new WebVRManager( effect );
var viewer = $( '#viewer' );
viewer.append( renderer.domElement );
return true;
}
function initControls() {
// Keyboard
// ---------------------------------------
$( document ).keydown( function( event ) {
switch( event.keyCode ) {
case 13: // Enter - Move forward
moveToNextPlace();
break;
case 18: // Alt
USE_DEPTH = !USE_DEPTH;
setSphereGeometry();
break;
case 37: // Left Arrow - Look left
updateRotation( false, true );
break;
case 38: // Up Arrow - Look up
updateRotation( true, true );
break;
case 39: // Right Arrow - Look right
updateRotation( false, false );
break;
case 40: // Down Arrow -- Look down
updateRotation( true, false );
break;
}
});
}
function initGui() {
window.addEventListener( 'resize', resize, false );
}
function initPano() {
panoLoader = new GSVPANO.PanoLoader();
panoDepthLoader = new GSVPANO.PanoDepthLoader();
panoLoader.setZoom( QUALITY );
panoLoader.onProgress = function( progress ) {
if (progress > 0) {
progBar.visible = true;
progBar.scale = new THREE.Vector3( progress / 100.0, 1,1 );
}
};
panoLoader.onPanoramaData = function( result ) {
progBarContainer.visible = true;
progBar.visible = false;
};
panoLoader.onNoPanoramaData = function( status ) {
//alert('no data!');
};
panoLoader.onPanoramaLoad = function() {
var a = THREE.Math.degToRad( 90 - panoLoader.heading );
projSphere.quaternion.setFromEuler( new THREE.Euler( 0, a, 0, 'YZX' ) );
projSphere.material.wireframe = false;
projSphere.material.map.needsUpdate = true;
projSphere.material.map = new THREE.Texture( this.canvas );
projSphere.material.map.needsUpdate = true;
centerHeading = panoLoader.heading;
progBarContainer.visible = false;
progBar.visible = false;
panoDepthLoader.load( this.location.pano );
};
panoDepthLoader.onDepthLoad = function() {
setSphereGeometry();
};
}
function setSphereGeometry() {
var geom = projSphere.geometry;
var geomParam = geom.parameters;
var depthMap = panoDepthLoader.depthMap.depthMap;
var y, x, u, v, radius, i=0;
for ( y = 0; y <= geomParam.heightSegments; y ++ ) {
for ( x = 0; x <= geomParam.widthSegments; x ++ ) {
u = x / geomParam.widthSegments;
v = y / geomParam.heightSegments;
radius = USE_DEPTH ? Math.min(depthMap[y*512 + x], FAR) : 500;
var vertex = geom.vertices[i];
vertex.x = - radius * Math.cos( geomParam.phiStart + u * geomParam.phiLength ) *
Math.sin( geomParam.thetaStart + v * geomParam.thetaLength );
vertex.y = radius * Math.cos( geomParam.thetaStart + v * geomParam.thetaLength );
vertex.z = radius * Math.sin( geomParam.phiStart + u * geomParam.phiLength ) *
Math.sin( geomParam.thetaStart + v * geomParam.thetaLength );
i++;
}
}
geom.verticesNeedUpdate = true;
}
function checkWebVR() {
if( !vrmgr.isWebVRCompatible() ) {
$( "#webvrinfo" ).dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});
}
else {
$( "#webvrinfo" ).hide();
}
}
function moveToNextPlace() {
var nextPoint = null;
var minDelta = 360;
var navList = panoLoader.links;
for ( var i = 0; i < navList.length; i++ ) {
var delta = deltaAngleDeg( currHeading, navList[i].heading );
if ( delta < minDelta && delta < NAV_DELTA ) {
minDelta = delta;
nextPoint = navList[i].pano;
}
}
if ( nextPoint ) {
console.log("Have next point");
panoLoader.load( nextPoint );
} else {
console.log("Do not have next point");
}
}
/**
* Process current rotation input, updating the rotation variable
* @param updateX Update the x field of the rotation variable
* @param increase Increase the rotation value of the given field
*/
function updateRotation( updateX, increase) {
if ( updateX ) {
if ( increase ) {
rotation.x = ( rotation.x + rotation_angle_cons * Math.PI / 180 ) % (2 * Math.PI);
} else {
rotation.x = ( rotation.x - rotation_angle_cons * Math.PI / 180 ) % (2 * Math.PI);
}
} else if ( increase ){
rotation.y = ( rotation.y + rotation_angle_cons * Math.PI / 180 ) % (2 * Math.PI);
} else {
rotation.y = ( rotation.y - rotation_angle_cons * Math.PI / 180 ) % (2 * Math.PI);
}
}
/**
* Update the rotation of the scene's camera
*/
function updateCameraRotation() {
camera.rotation.x = rotation.x;
camera.rotation.y = rotation.y;
camera.rotation.z = rotation.z;
}
/**
* Renders the scene, selecting the appropriate renderer taken into account the display mode (normal mode or VR mode)
*/
function render() {
if ( vrmgr.isVRMode() ) {
effect.render( scene, camera );
}
else {
updateCameraRotation();
renderer.render( scene, camera );
}
}
function resize( event ) {
WIDTH = window.innerWidth;
HEIGHT = window.innerHeight;
renderer.setSize( WIDTH, HEIGHT );
camera.projectionMatrix.makePerspective( 60, WIDTH /HEIGHT, 1, 1100 );
}
function loop() {
requestAnimationFrame( loop );
// Compute heading
headingVector.setFromQuaternion( camera.quaternion, 'YZX' );
currHeading = angleRangeDeg( THREE.Math.radToDeg( -headingVector.y ) );
controls.update();
// render
render();
}
function getParams() {
var params = {};
var items = window.location.search.substring( 1 ).split( "&" );
for ( var i=0; i < items.length; i++ ) {
var kvpair = items[i].split( "=" );
params[kvpair[0]] = decodeURI( kvpair[1] );
}
return params;
}
$(document).ready(function() {
var params;
// Initialize some default values
QUALITY = 3;
DEFAULT_LOCATION = { lat : 40.201877, lng : -8.414434 };
SHOW_SETTINGS = true;
NAV_DELTA = 45;
FAR = 1000;
headingVector = new THREE.Euler();
// Read parameters
params = getParams();
if ( params.lat !== undefined ) {
DEFAULT_LOCATION.lat = params.lat;
}
if ( params.lng !== undefined ) {
DEFAULT_LOCATION.lng = params.lng;
}
if ( params.q !== undefined ) {
QUALITY = params.q;
}
if ( params.s !== undefined ) {
SHOW_SETTINGS = params.s !== "false";
}
if ( params.depth !== undefined ) {
USE_DEPTH = params.depth !== "false";
}
// Get window width and height
WIDTH = window.innerWidth;
HEIGHT = window.innerHeight;
// Initialize user rotation values
rotation_angle_cons = 10;
rotation = { x: 0, y : 0, z : 0 };
if ( !initWebGL() ) {
return ;
}
initControls();
initGui();
initPano();
// Load default location
panoLoader.load( new google.maps.LatLng( DEFAULT_LOCATION.lat, DEFAULT_LOCATION.lng ) );
checkWebVR();
loop();
});
|
JavaScript
|
CL
|
4110e2b31a218d6276755ffc467ff3159d6390208becd1453bc4747c149a6c41
|
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import PageTitle from 'REUSE/components/pageTitle/pageTitle';
import Locale from 'REUSE/locales/locale';
// TEMPORARY IMPORTS FROM CLIENT-REACT
import HtmlUtils from 'APP/utils/htmlUtils';
import WindowLocationUtils from 'APP/utils/windowLocationUtils';
import {DEFAULT_PAGE_TITLE} from 'APP/constants/urlConstants';
// TEMPORARY IMPORTS FROM CLIENT-REACT
let component;
let testRealm = 'NinjaTurtles';
describe('PageTitle', () => {
beforeEach(() => {
spyOn(HtmlUtils, 'updatePageTitle');
spyOn(WindowLocationUtils, 'getHostname').and.returnValue(testRealm);
});
function generateTestTitle(titles) {
let titleArray = titles;
if (!Array.isArray(titles)) {
titleArray = [titles];
}
titleArray.push(DEFAULT_PAGE_TITLE);
return titleArray.join(Locale.getMessage('pageTitles.pageTitleSeparator'));
}
let testTitle = 'Raphael';
let testCases = [
{
description: 'updates the page title to the provided title string',
title: testTitle,
expectedTitles: testTitle
},
{
description: 'displays the realm name in the page title if no title provided',
expectedTitles: testRealm
}
];
testCases.forEach(testCase => {
it(testCase.description, () => {
component = TestUtils.renderIntoDocument(<PageTitle title={testCase.title} />);
expect(HtmlUtils.updatePageTitle).toHaveBeenCalledWith(generateTestTitle(testCase.expectedTitles));
});
});
});
|
JavaScript
|
CL
|
91b258504b8ee3e6fad15ead0cefbd1a1104fc1badd69cce7aba22e7ee83128f
|
/**
* @fileOverview Pivot Grid rows viewmodel
* @author Najmeddine Nouri <najmno@gmail.com>
*/
'use strict';
/* global module, require */
/*jshint eqnull: true*/
var axe = require('./orb.axe');
var axeUi = require('./orb.ui.axe');
var uiheaders = require('./orb.ui.header');
/**
* Creates a new instance of rows ui properties.
* @class
* @memberOf orb.ui
* @param {orb.axe} rowsAxe - axe containing all rows dimensions.
*/
module.exports = function(rowsAxe) {
var self = this;
axeUi.call(self, rowsAxe);
this.build = function() {
var headers = [];
var grandtotalHeader;
if (self.axe != null) {
if(self.axe.root.values.length > 0 || self.axe.pgrid.config.grandTotal.rowsvisible) {
headers.push([]);
// Fill Rows layout infos
getUiInfo(headers, self.axe.root);
if (self.axe.pgrid.config.grandTotal.rowsvisible) {
var lastrow = headers[headers.length - 1];
grandtotalHeader = new uiheaders.header(axe.Type.ROWS, uiheaders.HeaderType.GRAND_TOTAL, self.axe.root, null, self.dataFieldsCount());
if (lastrow.length === 0) {
lastrow.push(grandtotalHeader);
} else {
headers.push([grandtotalHeader]);
}
}
}
if (headers.length === 0) {
headers.push([grandtotalHeader = new uiheaders.header(axe.Type.ROWS, uiheaders.HeaderType.INNER, self.axe.root, null, self.dataFieldsCount())]);
}
if(grandtotalHeader) {
// add grand-total data headers if more than 1 data field and they will be the leaf headers
addDataHeaders(headers, grandtotalHeader);
}
}
self.headers = headers;
};
this.build();
function addDataHeaders(infos, parent) {
if (self.isMultiDataFields()) {
var lastInfosArray = infos[infos.length - 1];
for (var datafieldindex = 0; datafieldindex < self.dataFieldsCount(); datafieldindex++) {
lastInfosArray.push(new uiheaders.dataHeader(self.axe.pgrid.config.dataFields[datafieldindex], parent));
if (datafieldindex < self.dataFieldsCount() - 1) {
infos.push((lastInfosArray = []));
}
}
}
}
/**
* Fills the infos array given in argument with the dimension layout infos as row.
* @param {orb.dimension} dimension - the dimension to get ui info for
* @param {object} infos - array to fill with ui dimension info
*/
function getUiInfo(infos, dimension) {
if (dimension.values.length > 0) {
var infosMaxIndex = infos.length - 1;
var lastInfosArray = infos[infosMaxIndex];
var parent = lastInfosArray.length > 0 ? lastInfosArray[lastInfosArray.length - 1] : null;
for (var valIndex = 0; valIndex < dimension.values.length; valIndex++) {
var subvalue = dimension.values[valIndex];
var subdim = dimension.subdimvals[subvalue];
var subTotalHeader;
if (!subdim.isLeaf && subdim.field.subTotal.visible) {
subTotalHeader = new uiheaders.header(axe.Type.ROWS, uiheaders.HeaderType.SUB_TOTAL, subdim, parent, self.dataFieldsCount());
} else {
subTotalHeader = null;
}
var newHeader = new uiheaders.header(axe.Type.ROWS, null, subdim, parent, self.dataFieldsCount(), subTotalHeader);
if (valIndex > 0) {
infos.push((lastInfosArray = []));
}
lastInfosArray.push(newHeader);
if (!subdim.isLeaf) {
getUiInfo(infos, subdim);
if (subdim.field.subTotal.visible) {
infos.push([subTotalHeader]);
// add sub-total data headers if more than 1 data field and they will be the leaf headers
addDataHeaders(infos, subTotalHeader);
}
} else {
// add data headers if more than 1 data field and they will be the leaf headers
addDataHeaders(infos, newHeader);
}
}
}
}
};
|
JavaScript
|
CL
|
af300536645fcbc74e76c5e3ed8fcab60f4659e52f7787e495886711589508a8
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _times = _interopRequireDefault(require("lodash/times"));
var _helpers = require("./helpers");
var _helpers2 = require("../../../common/helpers");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var YearView = /*#__PURE__*/function (_React$Component) {
_inherits(YearView, _React$Component);
function YearView() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, YearView);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(YearView)).call.apply(_getPrototypeOf2, [this].concat(args)));
_defineProperty(_assertThisInitialized(_this), "state", {
date: new Date(_this.props.date),
selectedDate: new Date(_this.props.date)
});
_defineProperty(_assertThisInitialized(_this), "getMonthArray", function () {
var date = new Date('1/1/1');
return (0, _times["default"])(12, function (i) {
return Intl.DateTimeFormat(_this.props.locale, {
month: 'short'
}).format((0, _helpers.addMonths)(date, i));
});
});
_defineProperty(_assertThisInitialized(_this), "getPrevYear", function () {
var date = _this.state.date;
_this.setState({
date: (0, _helpers.addYears)(date, -1)
});
});
_defineProperty(_assertThisInitialized(_this), "getNextYear", function () {
var date = _this.state.date;
_this.setState({
date: (0, _helpers.addYears)(date, 1)
});
});
_defineProperty(_assertThisInitialized(_this), "setSelectedMonth", function (month) {
var date = _this.state.date;
date.setMonth(month);
_this.props.setSelected(date);
_this.props.toggleDateView('M');
});
return _this;
}
_createClass(YearView, [{
key: "render",
value: function render() {
var _this2 = this;
var _this$state = this.state,
date = _this$state.date,
selectedDate = _this$state.selectedDate;
var _ref = [date.getMonth(), date.getFullYear()],
currMonth = _ref[0],
currYear = _ref[1];
var selectedYear = selectedDate.getFullYear();
var monthArray = this.getMonthArray();
return _react["default"].createElement("div", {
className: "datepicker-months"
}, _react["default"].createElement("table", {
className: "table-condensed"
}, _react["default"].createElement("thead", null, _react["default"].createElement("tr", null, _react["default"].createElement("th", {
className: "prev",
onClick: this.getPrevYear
}, _react["default"].createElement("span", {
className: "glyphicon glyphicon-chevron-left"
})), _react["default"].createElement("th", {
className: "picker-switch",
onClick: function onClick() {
return _this2.props.toggleDateView('D');
},
colSpan: "5"
}, currYear), _react["default"].createElement("th", {
className: "next",
onClick: this.getNextYear
}, _react["default"].createElement("span", {
className: "glyphicon glyphicon-chevron-right"
})))), _react["default"].createElement("tbody", null, _react["default"].createElement("tr", null, _react["default"].createElement("td", {
colSpan: "7"
}, monthArray.map(function (month, idx) {
return _react["default"].createElement("span", {
onClick: function onClick() {
return _this2.setSelectedMonth(idx);
},
className: "month ".concat(idx === currMonth && selectedYear === currYear ? 'active' : ''),
key: idx
}, month);
}))))));
}
}]);
return YearView;
}(_react["default"].Component);
YearView.propTypes = {
date: _propTypes["default"].oneOfType([_propTypes["default"].instanceOf(Date), _propTypes["default"].string]),
setSelected: _propTypes["default"].func,
toggleDateView: _propTypes["default"].func,
locale: _propTypes["default"].string
};
YearView.defaultProps = {
setSelected: _helpers2.noop,
toggleDateView: _helpers2.noop,
date: new Date(),
locale: 'en-US'
};
var _default = YearView;
exports["default"] = _default;
|
JavaScript
|
CL
|
4496bdb22d33a9b274a890cd713db040019bf8b3e2ad658c9a12acdd803fc2e9
|
"use strict";
(function () {
class QuillLoader extends THREE.Loader {
load(url, onLoad, onProgress, onError) {
const scope = this;
const loader = new THREE.FileLoader(this.manager);
loader.setPath(this.path);
loader.setResponseType("arraybuffer");
loader.setWithCredentials(this.withCredentials);
loader.load(url, function (buffer) {
try {
onLoad(scope.parse(buffer));
} catch (e) {
if (onError) {
onError(e);
} else {
console.error(e);
}
scope.manager.itemError(url);
}
}, onProgress, onError);
}
parse(buffer) {
const zip = fflate.unzipSync(new Uint8Array(buffer));//.slice(16)));
const metadata = JSON.parse(fflate.strFromU8(zip["Quill.json"]));
const data = new DataView(zip["Quill.qbin"].buffer);
const material = new THREE.LineBasicMaterial({
vertexColors: true,
});
const scale = 10;
const children = metadata["Sequence"]["RootLayer"]["Implementation"]["Children"];
for (let i=0; i < children.length; i++) {
const childNode = children[i];
// skip the child node if it contains no drawings
let drawingCount = 0;
try {
drawingCount = childNode["Implementation"]["Drawings"].length;
} catch (e) {
continue;
}
for (let j=0; j < drawingCount; j++) {
const drawingNode = childNode["Implementation"]["Drawings"][j];
const dataFileOffsetString = drawingNode["DataFileOffset"];
const dataFileOffset = parseInt("0x" + dataFileOffsetString);
const numNodeStrokes = data.getInt32(dataFileOffset, true);
let offset = dataFileOffset + 4;
for (let k = 0; k < numNodeStrokes; k++) {
offset += 36;
const numVertices = data.getInt32(offset, true);
const positions = new Float32Array(numVertices * 3);
const colors = new Float32Array(numVertices * 4);
const widths = new Float32Array(numVertices);
offset += 4;
for (let l = 0, m = 0, n = 0; n < numVertices; l += 3, m += 4, n++) {
positions[l+0] = data.getFloat32(offset + 0, true) * scale; // x
positions[l+1] = data.getFloat32(offset + 4, true) * scale; // y
positions[l+2] = data.getFloat32(offset + 8, true) * scale; // z
offset += 36;
colors[m+0] = data.getFloat32(offset + 0, true); // r
colors[m+1] = data.getFloat32(offset + 4, true); // g
colors[m+2] = data.getFloat32(offset + 8, true); // b
colors[m+3] = data.getFloat32(offset + 12, true); // a
offset += 16;
widths[n] = data.getFloat32(offset + 0, true);
offset += 4;
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.BufferAttribute(new Float32Array(positions), 3));
geometry.setAttribute("color", new THREE.BufferAttribute(new Float32Array(colors), 4));
const line = new THREE.Line(geometry, material);
scene.add(line);
}
}
}
}
}
THREE.QuillLoader = QuillLoader;
})();
|
JavaScript
|
CL
|
9c3766c2edbc82057c57ed0bcd71b54768ed45c6fa6501207c8e6cebbc7f4151
|
/*
Crie um array com 5 items (tipos variados).
*/
let arr = [1, "snazzy", /wild-regex/, undefined, true];
/*
Crie uma função chamada `addItem`, que irá adicionar itens no array criado.
A função deverá retornar o array atualizado.
*/
const addItem = (arr, item) => arr.concat(item);
/*
Adicione um novo array ao array criado no início do desafio, com ao menos 3
itens de tipos diferentes, mostrando o resultado no console.
*/
let blag = [24, /another-regex/, false];
console.log(addItem(arr, blag));
/*
Mostre no console o segundo elemento desse último array, criado acima, com a
frase:
"O segundo elemento do segundo array é [ELEMENTO]."
*/
console.log(`O segundo elemento do segundo array é ${blag[1]}`);
/*
Mostre no console quantos itens tem o primeiro array criado, com a frase:
"O primeiro array tem [QUANTIDADE DE ITENS] itens."
*/
console.log(`O primeiro array tem ${arr.length} itens.`);
/*
Agora mostre no console quantos itens tem o segundo array criado, com a frase:
"O segundo array tem [QUANTIDADE DE ITENS] itens."
*/
console.log(`O segundo array tem ${blag.length} itens.`);
/*
Utilizando a estrutura de repetição `while`, mostre no console todos os números
pares entre 10 e 20, inclusive esses 2.
*/
console.log( 'Números pares entre 10 e 20:' );
/*
Na mesma ideia do exercício acima: mostre agora os números ímpares.
*/
console.log( 'Números ímpares entre 10 e 20:' );
/*
Repita os mesmos exercícios feitos acima, mas agora usando o loop "for".
Só vamos mudar o range:
- No primeiro "for", mostre os números pares entre 100 e 120, inclusive eles;
- No segundo "for", mostre os números ímpares entre 111 e 125, inclusive eles.
*/
// Não quero repetir código
const logRange = (start, stop, condition) => {
let buf = start;
while (buf <= stop) {
if (condition(buf)) {
console.log(buf);
}
buf++;
}
};
console.log( 'Números pares entre 100 e 120:' );
logRange(100, 120, n => n % 2 == 0);
console.log( 'Números ímpares entre 111 e 125:' );
logRange(111, 125, n => n % 2 != 0);
module.exports = {
arr, blag,
addItem
};
|
JavaScript
|
CL
|
38c8c9a393bbdc9e5b9ca3adca89720892f1db52dd6c64f0407c35052dc180fd
|
const express = require('express');
const chalk = require('chalk');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const compression = require('compression');
const helmet = require('helmet');
const defaultOptions = {
bodyParser: true,
compression: true,
helmet: true,
};
module.exports = function (options = {}) {
const app = express(options);
const isProd = process.env.NODE_ENV === 'production';
const mergedOptions = Object.assign({}, defaultOptions, options);
if (options.httpLogCb) {
app.use(morgan((tokens, req, res) => {
options.httpLogCb({
method: tokens.method(req, res),
url: tokens.url(req, res),
status: tokens.status(req, res),
'content-length': tokens.res(req, res, 'content-length'),
'response-time': tokens['response-time'](req, res),
'user-agent': tokens['user-agent'](req, res),
});
}));
} else {
app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));
}
// General
if (mergedOptions.bodyParser) {
app.use(bodyParser.urlencoded({
extended: true,
}));
app.use(bodyParser.json());
}
if (mergedOptions.compression) app.use(compression(mergedOptions.compression.options));
if (mergedOptions.helmet) app.use(helmet(mergedOptions.helmet.options));
app.nativeListen = app.listen;
app.listen = (port, cb) => {
console.log(chalk.blue(`Super express will listen on port ${port}`));
console.log(chalk.blue(`Production mode: ${isProd}`));
app.nativeListen(port, cb);
};
return app;
};
|
JavaScript
|
CL
|
ad608aad4665440d09bf3b7af87c2b6bc5df2d78ee8c37ab59b7083bf0aa0d20
|
import { message } from 'antd';
import moment from 'moment';
import { call, all, modify } from '@ixinwu-ngp/web-core';
import { qsParse } from '@ixinwu-ngp/web-framework';
import {
fetchGetDataSetData,
fetchGetGroupTypeData,
fetchEditDataSetData,
} from '../../services/common';
// 获取页面列表数据
export function* getData(props) {
const {
dataSetKey,
fields,
location: { search },
} = props;
try {
const { aaaId } = qsParse(search) || {};
const data = yield call(fetchGetDataSetData, dataSetKey, aaaId, fields);
return {
originalData: { ...data },
data,
};
} catch (e) {
console.log(e);
message.error(e.message || 'AAA数据获取失败!');
}
}
// 初始化页面数据
export function* initPage(props) {
const { fields } = props;
try {
const callMap = { result: call(getData, props) };
// 获取field的group定义
fields.forEach(field => {
// TODO 根据实际业务进行修改
if (field.groupKey && field.groupKey !== 'typeGroup') {
callMap[field.groupKey] = call(fetchGetGroupTypeData, field.groupKey);
}
});
const { result, ...groups } = yield all(callMap);
return {
...result,
...groups,
};
} catch (e) {
message.error(e.message || '页面初始化失败!');
}
}
const setData = (setters, identity, value) => setters[identity].data(value);
export function* submit(props, values) {
const {
identity,
dataSetKey,
fields,
originalData,
location: { search },
} = props;
try {
yield modify(setData, identity, values);
const { aaaId } = qsParse(search) || {};
const changedFields = fields
.filter(field => field.visible)
.filter(field => {
const value = values[field.key];
if (moment.isMoment(value)) {
return !value.isSame(originalData[field.key]);
}
return originalData[field.key] !== values[field.key];
});
if (changedFields.length < 1) {
message.warning('没有修改数据');
return;
}
const params = {
dataSetKey,
primaryKey: aaaId,
fields: changedFields.map(field => {
let value = values[field.key];
if (moment.isMoment(value)) {
value = value.format('YYYY-MM-DDTmm:hh:ss');
}
return {
fieldKey: field.key,
value,
originalValue: originalData[field.key],
};
}),
};
yield call(fetchEditDataSetData, params);
message.success('操作成功!');
} catch (e) {
message.error(e.message || '操作失败!');
}
}
|
JavaScript
|
CL
|
d0d2e0c7f3e4673923ef4f9938b86c2077325385282b89ee41671a0aa39acdd5
|
var util = require('util'),
cache = {};
/**
* @param {Function} BaseAgent Agent constructor (http.Agent, https.Agent or something had similiar public API)
* @returns {Function} AdvancedAgent constructor
*/
function advancedAgentFactory(BaseAgent) {
/**
* http.Agent successor which fire 'socketRemoved' event in the end of Agent#removeSocket
*
* @constructor
* @extends http.Agent
* @param {Object} options default http.Agent options object, extended with following props:
* @param {String} options.name Agent name to identify it
* @param {Boolean} [options.persistent] Non-persistent agents removed when queue empty
*/
function AdvancedAgent(options) {
BaseAgent.apply(this, Array.prototype.slice.call(arguments));
// keep track for all AdvancedAgent instances
AdvancedAgent.pool[options.name] = this;
// Setup `removeSocket` event listener for non-persistnt agents.
// Destroy agent then requests queue and sockets pool became empty.
if ( ! options.persistent) {
this.on(AdvancedAgent.EVENTS.SOCKET_REMOVED, function() {
if (Object.keys(this.requests).length === 0 &&
Object.keys(this.sockets).length === 0) {
delete AdvancedAgent.pool[options.name];
}
});
}
}
util.inherits(AdvancedAgent, BaseAgent);
/**
* Pool of AdvancedAgent instances
* @type {Object}
*/
AdvancedAgent.pool = {};
/**
* returns AdvancedAgent instance from the pool or
* `undefined` if agent with desired name is not exists
* @param {String} name
* @returns {AdvancedAgent|undefined}
*/
AdvancedAgent.get = function(name) {
return this.pool[name];
};
/**
* new events names
*/
AdvancedAgent.EVENTS = {
SOCKET_REMOVED : 'socketRemoved'
};
/**
* keep inherited removeSocket
*/
AdvancedAgent.prototype._removeSocket = AdvancedAgent.prototype.removeSocket;
/**
* extends inherited removeSocket method
* with emitting `socketRemoved` event
*/
AdvancedAgent.prototype.removeSocket = function() {
var result = this._removeSocket.apply(this, arguments);
this.emit(AdvancedAgent.EVENTS.SOCKET_REMOVED);
return result;
};
return AdvancedAgent;
}
/**
* Memoization for createAdvancedAgent by module name
* @param {String} moduleName 'http', 'https' or something had similiar Agent implementation
* @returns {Function} AdvancedAgent constructor
*/
module.exports = function (moduleName) {
if (typeof moduleName === 'undefined') {
moduleName = 'http';
}
if ( ! Object.prototype.hasOwnProperty.call(cache, moduleName)) {
cache[moduleName] = advancedAgentFactory(require(moduleName).Agent);
}
return cache[moduleName];
};
|
JavaScript
|
CL
|
201e711781f1a16540471725061ae1189dbea426efd2c84c9ca34d4dabe9943d
|
function nameGen(type){var nm1=["Abhijit","Abhiru","Acalavarman","Acyut","Adratipin","Agnitejas","Agnivay","Ahina","Ahinas","Ahovirya","Ajatashatru","Ajitashatru","Akopa","Alikayu","Amitaujas","Anadhristi","Anangi","Angarasetu","Anuharant","Anuvaktar","Apratimaujas","Aradhin","Arijit","Aristakarman","Asadha","Asadhi","Ashmaratha","Atibhanu","Aupajihvi","Aviksit","Bahu","Bahvashin","Balin","Balina","Barhin","Bhadrabahu","Bhadracaru","Bhagavaddosa","Bhajya","Bhanumant","Bhaskara","Bhavasvamin","Bhayankara","Bhoja","Bhrigu","Bhrigubhumi","Bhuritejas","Bhutasharman","Brahmabali","Brahmavriddhi","Brihadbhanu","Brihanmanas","Brihaspati","Brihatkarman","Camasin","Candabhargava","Candraketu","Caru","Carugupta","Chandogi","Cirakari","Cirakarin","Dabhiti","Dambhodbhava","Dandapani","Dandasharman","Darbhi","Darbhin","Devabhuti","Devadarsha","Devaki","Devamidhusa","Devapi","Devashravas","Devasvamin","Devavant","Devavisnu","Dharmaketu","Dharmasarathi","Dharmeyu","Dhimant","Dhrisnu","Dhriti","Dhritimant","Dhritimitra","Dhruvasharman","Dhuni","Dhvasan","Dhvasanti","Dirghalocana","Divakarasvamin","Dridhacyut","Dridharuci","Duli","Durgama","Durmukha","Duryodhana","Dustaritu","Dyutimant","Ekadyu","Ekayavan","Ganapati","Garavant","Gauragriva","Gauramukha","Ghosavasu","Ghujyu","Gopali","Gopati","Govindagupta","Govindasvamin","Harimedhas","Harishcandra","Harishmashru","Havirdhaman","Havismant","Hiranyaroman","Hotrapaci","Hrasvaroman","Hridya","Hritsvashaya","Ilin","Indrahu","Indrapramati","Indrota","Itant","Jaimini","Jamadagni","Janghabandhu","Janu","Jayaka","Jihvavan","Jisnu","Jyayan","Kalmasanghri","Kapatu","Karnashravas","Katujit","Ketu","Khandapani","Kohada","Kratumant","Kratuvid","Krisnadhriti","Kritagni","Ksanabhojin","Ksanti","Ksemadarshin","Ksemadhurti","Ksemari","Ksemavriddhi","Kumarashanti","Kurubasha","Laugaksi","Lohitaksa","Lomaharsana","Madhu","Madhushcut","Mahabhauma","Mahakarni","Mahamati","Mahanandin","Mahant","Mahanta","Mahasvant","Manas","Mandhatri","Matarishvan","Mayuraksaka","Meghayati","Mitrabhanu","Mitravarcas","Mitrayu","Mridu","Nabhi","Nagadatta","Naikadrish","Naimishri","Nami","Nandin","Naradin","Natha","Niramaya","Nirvrita","Nivaku","Nrisad","Palin","Parahan","Parakrathin","Paramesthin","Paravrit","Parthin","Pashupati","Pathin","Pattanadhipati","Pavitrapani","Prabahu","Prabhanu","Pracinabarhis","Pradyumna","Prakaramardin","Prakshringavant","Pramshu","Prasanneya","Pratibahu","Pratiksatra","Pravasu","Prenin","Prithukarman","Pulasti","Purujanu","Purusaprabhu","Putakratu","Rajastambha","Ranavanya","Raudrakarman","Ravikirtti","Riju","Ripu","Ritavac","Ritayus","Ruciparvan","Rudrabhuti","Rudradaman","Sabhapati","Sadahsuvak","Sahasrapad","Sahisnu","Sakrajit","Samkriti","Samnateyu","Samraj","Saptapala","Sarpamalin","Sasthidatta","Satrajit","Satyadharman","Satyajit","Satyaketu","Satyashri","Satyavan","Satyavant","Senajit","Shakandhi","Shambhu","Shamtanu","Shankhapada","Shanti","Sharvavarman","Shashaloman","Shatapati","Shatrughatin","Shatrujit","Shatursaha","Shayu","Shiras","Shirsin","Shivagupta","Shivashri","Shribhanu","Shrimant","Shrusti","Shrutavid","Shucanti","Shvetakarna","Sikhavant","Sindhuksit","Somakirti","Somashravas","Sthandileyu","Sthaulasthivi","Subhanu","Subhraj","Sucetas","Sudaman","Sudarsha","Sudhaman","Sudhriti","Suditi","Suhavis","Sukriti","Sulabhin","Sumanas","Sumnayu","Sunvant","Suparshva","Suprabha","Surakrit","Surari","Surupa","Susamchi","Sushanti","Sutvan","Suvarnashiras","Suyastavya","Svarjit","Svarupa","Svaryati","Svati","Tamas","Tandi","Tandin","Tanu","Tapasvin","Tapodhriti","Tapomurti","Tarasvin","Trasadayu","Trisoka","Tuji","Tustimant","Uccairmanyu","Udhajit","Ugrayayin","Upamashravas","Upaveshi","Upavi","Urjayoni","Usangu","Ushant","Utathya","Utatya","Uttanabarhis","Vadanya","Vajabandhu","Valgujangha","Vama","Vamadeva","Varayu","Varcas","Varcin","Varpeyu","Vasati","Vasu","Vasudharman","Vataki","Vatavant","Vatsahanu","Vayuretas","Vibhavasu","Vibhuti","Vicarin","Vidabhrit","Vidanvant","Vidyutprabhu","Vikriti","Vikuksi","Vinatatman","Vipulasvant","Virabahu","Virupa","Viryacandra","Vishrutavant","Visnudeva","Visnusimha","Visnuyashas","Visri","Vitarka","Vrateyu","Vrijinavant","Vrijinivant","Vrisaparvan","Vyudhoru","Yajnabahu","Yajnapati","Yajnyapati","Yajnyubahu","Yamaduta","Yudhamanyu","Yuyudhana"];var nm2=["Abandhaka","Abja","Adrishyanti","Ahalya","Aksamala","Alambusa","Amalaja","Amba","Ambika","Amrita","Ananta","Anibha","Apala","Arcismati","Arundhati","Arusi","Asmaki","Asti","Asvapali","Atiki","Badhiraka","Bahula","Bala","Balada","Balandhara","Bandhaki","Bhadra","Bhagala","Bhanugupta","Bhanumati","Bindumati","Brihatsena","Canda","Caruhasini","Carumati","Citra","Citralekha","Citrangada","Cuda","Cudala","Damayanti","Dasi","Datta","Dattadevi","Devaki","Devayani","Devika","Dharmavati","Dharmini","Dhenuka","Dhritadeva","Dhruvadevi","Dhumini","Dhusala","Drsadvati","Druvaka","Durga","Durmitra","Dvarapali","Eraka","Ganda","Gandhapingala","Gauri","Ghosa","Ghritaci","Ghurnika","Giribhadra","Girika","Gocapala","Gopajala","Gopika","Gupta","Haimii","Hamsi","Harsigupta","Havismati","Ilini","Indrasena","Jangha","Jatila","Jayasvamini","Jitavati","Kadamba","Kakudmati","Kalavati","Kalindi","Kalyani","Kama","Kamadyu","Kamsa","Kamsavati","Kanistha","Kapila","Kapilika","Karambha","Karenumati","Karmavati","Karmi","Kaveri","Keshiki","Keshini","Khadonmatta","Khala","Khalya","Khalyaka","Kisorika","Krata","Krimi","Kripi","Kritvi","Kuksi","Kulata","Kumaradevi","Kumari","Kumarika","Kumudvati","Kundala","Kundini","Kusherika","Kutharika","Kuverika","Laksmana","Laksmivati","Lapita","Lilavati","Madalasa","Madayanti","Madira","Madra","Mahi","Maitreyi","Malini","Malti","Mamata","Manasvini","Manini","Manipali","Manthara","Marisa","Maryada","Mayadevi","Mena","Menaka","Mitravinda","Mudavati","Mura","Musika","Nalini","Nanda","Nandini","Narmada","Nava","Nili","Nilini","Nriga","Oghavati","Padmini","Pila","Pindi","Pingala","Pivari","Prabhavati","Pradvesi","Prajavati","Pramadvara","Pramatha","Prapti","Praticya","Pritha","Priti","Pskaradharini","Puramdhi","Purohitika","Putakrata","Radha","Rajadhidevi","Rajivalocana","Rajni","Rajnyi","Raksa","Ramadevi","Rangavato","Rastrapali","Rathamtari","Renuka","Revati","Riksa","Rocana","Rohini","Ruci","Rudra","Rudramati","Rukmini","Sahadeva","Sampriya","Sarasvati","Sarparajni","Satya","Satyabhama","Satyaratha","Satyavati","Savarna","Savitri","Shabari","Shalaka","Shalakabhru","Shalavati","Shanta","Sharmistha","Shikha","Shiksita","Shiva","Shrideva","Shrutadeva","Shrutavati","Shubha","Shudra","Shushsrava","Shuvhangi","Sita","Subhadra","Subhaga","Subhima","Sudarashana","Sudesna","Sudeva","Sudevala","Sudharma","Sugandhi","Sujata","Sukanya","Sukeshi","Sukumari","Sulabha","Sumana","Sumitra","Sunamni","Sunanda","Sundari","Sunitha","Suniti","Suprabha","Surasa","Surici","Surohika","Surohitika","Sushila","Sushobhana","Sutanu","Sutara","Suvarna","Suyajna","Suyashas","Svayamprabha","Tala","Tamprapaksa","Tamrarasa","Ugraseni","Upadeva","Upadevi","Upagupta","Upama","Urjasvati","Urmila","Urvasi","Usa","Utpalavati","Uttara","Vadava","Vadhrimati","Vahini","Vahyaka","Vajrajivala","Vajrajvala","Vanaraji","Vapusmati","Vapustama","Vara","Varangi","Varkadeva","Varkala","Vasavadatta","Vedavati","Vidula","Vijaya","Vimala","Vipatha","Vira","Vishala","Vriddhakanya","Vrkadeva","Vrkala","Yashoda","Yashodevi","Yasodhara","Yaudheyi"];var br="";$('#placeholder').css('textTransform','capitalize');var tp=type;var element=document.createElement("div");element.setAttribute("id","result");for(i=0;i<10;i++){if(tp===1){rnd=Math.random()*nm2.length|0;names=nm2[rnd];nm2.splice(rnd,1);}else{rnd=Math.random()*nm1.length|0;names=nm1[rnd];nm1.splice(rnd,1);}
br=document.createElement('br');element.appendChild(document.createTextNode(names));element.appendChild(br);}
if(document.getElementById("result")){document.getElementById("placeholder").removeChild(document.getElementById("result"));}
document.getElementById("placeholder").appendChild(element);}
|
JavaScript
|
CL
|
f5159b7cc0d541b44d5489bf1edc91ac28b77f4009a9f60fa8cd332a2507843c
|
require('../spec_helper')
const { makeDataContext, setCtx, getCtx } = require('../../lib/makeDataContext')
setCtx(makeDataContext({}))
const cp = require('child_process')
const fse = require('fs-extra')
const os = require('os')
const path = require('path')
const _ = require('lodash')
const { expect } = require('chai')
const debug = require('debug')('test:proxy-performance')
const DebuggingProxy = require('@cypress/debugging-proxy')
const HarCapturer = require('chrome-har-capturer')
const performance = require('@tooling/system-tests/lib/performance')
const Promise = require('bluebird')
const sanitizeFilename = require('sanitize-filename')
const { createRoutes } = require(`../../lib/routes`)
process.env.CYPRESS_INTERNAL_ENV = 'development'
const CA = require('@packages/https-proxy').CA
const { setupFullConfigWithDefaults } = require('@packages/config')
const { ServerBase } = require('../../lib/server-base')
const { SocketE2E } = require('../../lib/socket-e2e')
const { _getArgs } = require('../../lib/browsers/chrome')
const CHROME_PATH = 'google-chrome'
const URLS_UNDER_TEST = [
'https://test-page-speed.cypress.io/index1000.html',
'http://test-page-speed.cypress.io/index1000.html',
]
const start = (new Date()) / 1000
const PROXY_PORT = process.env.PROXY_PORT || 45678
const HTTPS_PROXY_PORT = process.env.HTTPS_PROXY_PORT || 45681
const CDP_PORT = 45679 /** port range starts here, not the actual port */
const CY_PROXY_PORT = 45680
const TEST_CASES = [
// these first 4 cases don't involve Cypress, don't need to run every time
// {
// name: 'Chrome w/o HTTP/2',
// disableHttp2: true,
// },
// {
// name: 'Chrome',
// },
// {
// name: 'With proxy',
// upstreamProxy: true,
// },
// {
// name: 'With HTTPS proxy',
// httpsUpstreamProxy: true,
// },
// baseline test that all other tests are compared to
{
name: 'Chrome w/ proxy w/o HTTP/2 (baseline)',
disableHttp2: true,
upstreamProxy: true,
},
{
name: 'With Cypress proxy, Intercepted',
cyProxy: true,
cyIntercept: true,
},
{
name: 'With Cypress proxy, Not Intercepted',
cyProxy: true,
},
{
name: 'With Cypress proxy w/o HTTP/2, Not Intercepted',
cyProxy: true,
disableHttp2: true,
},
{
name: 'With Cypress proxy and upstream, Intercepted',
cyProxy: true,
upstreamProxy: true,
cyIntercept: true,
},
{
name: 'With Cypress proxy and HTTPS upstream, Intercepted',
cyProxy: true,
httpsUpstreamProxy: true,
cyIntercept: true,
},
{
name: 'With Cypress proxy and upstream, Not Intercepted',
cyProxy: true,
upstreamProxy: true,
},
{
name: 'With Cypress proxy and HTTPS upstream, Not Intercepted',
cyProxy: true,
httpsUpstreamProxy: true,
},
].map((v) => {
// fill in all the fields so the keys are in the correct order for readability
return _.defaults(v, {
disableHttp2: false,
upstreamProxy: false,
httpsUpstreamProxy: false,
cyProxy: false,
cyIntercept: false,
})
})
const average = (arr) => {
return _.sum(arr) / arr.length
}
const percentile = (sortedArr, p) => {
const i = Math.floor(p / 100 * (sortedArr.length - 1))
return Math.round(sortedArr[i])
}
const getResultsFromHar = (har) => {
// HAR 1.2 Spec: http://www.softwareishard.com/blog/har-12-spec/
const { entries } = har.log
const results = {}
const first = entries[0]
const last = entries[entries.length - 1]
const elapsed = Number(new Date(last.startedDateTime)) + last.time - Number(new Date(first.startedDateTime))
results['Total'] = Math.round(elapsed)
let mins = {}
let maxes = {}
const timings = {
'receive': [],
'wait': [],
'send': [],
'total': [],
}
entries.forEach((entry) => {
const blockedTime = _.get(entry.timings, 'blocked', -1) === -1 ? 0 : entry.timings.blocked
const totalTime = entry.time - blockedTime
timings.total.push(totalTime)
Object.keys(entry.timings).forEach((timingKey) => {
if (entry.timings[timingKey] === -1 || !entry.timings[timingKey]) return
const ms = Math.round(entry.timings[timingKey])
if (timings[timingKey]) timings[timingKey].push(ms)
})
})
for (const key in timings) {
const arr = timings[key]
arr.sort((a, b) => {
return a - b
})
mins[key] = Math.round(arr[0])
maxes[key] = Math.round(arr[arr.length - 1])
_.merge(results, {
[`Avg ${_.upperFirst(key)}`]: Math.round(average(arr)),
})
}
results['Min'] = mins.total
expect(timings.total.length).to.be.at.least(1000)
;[1, 5, 25, 50, 75, 95, 99, 99.7].forEach((p) => {
results[`${p}% <=`] = percentile(timings.total, p)
})
results['Max'] = maxes.total
return results
}
const runBrowserTest = (urlUnderTest, testCase) => {
const cdpPort = CDP_PORT + Math.round(Math.random() * 10000)
const browser = {
isHeadless: true,
}
const options = {}
const args = _getArgs(browser, options, cdpPort).concat([
// additionally...
'--disable-background-networking',
'--no-sandbox', // allows us to run as root, for CI
`--user-data-dir=${fse.mkdtempSync(path.join(os.tmpdir(), 'cy-perf-'))}`,
])
if (testCase.disableHttp2) {
args.push('--disable-http2')
}
if (testCase.cyProxy) {
args.push(`--proxy-server=http://localhost:${CY_PROXY_PORT}`)
}
if (testCase.upstreamProxy && !testCase.cyProxy) {
args.push(`--proxy-server=http://localhost:${PROXY_PORT}`)
} else if (testCase.httpsUpstreamProxy && !testCase.cyProxy) {
args.push(`--proxy-server=https://localhost:${HTTPS_PROXY_PORT}`)
}
if (testCase.upstreamProxy && testCase.cyProxy) {
process.env.HTTP_PROXY = process.env.HTTPS_PROXY = `http://localhost:${PROXY_PORT}`
} else if (testCase.httpsUpstreamProxy && testCase.cyProxy) {
process.env.HTTP_PROXY = process.env.HTTPS_PROXY = `https://localhost:${HTTPS_PROXY_PORT}`
} else {
delete process.env.HTTPS_PROXY
delete process.env.HTTP_PROXY
}
if (testCase.cyIntercept) {
cyServer.remoteStates.set(urlUnderTest)
} else {
cyServer.remoteStates.set('<root>')
}
let cmd = CHROME_PATH
debug('Launching Chrome: ', cmd, args.join(' '))
const proc = cp.spawn(cmd, args, {
stdio: 'ignore',
})
const storeHar = Promise.method((name, har) => {
const artifacts = process.env.CIRCLE_ARTIFACTS
if (artifacts) {
return fse.ensureDir(artifacts)
.then(() => {
const pathToFile = path.join(artifacts, sanitizeFilename(`${name}.har`))
debug('saving har to path:', pathToFile)
return fse.writeJson(pathToFile, har)
})
}
})
const runHar = () => {
// wait for Chrome to open, then start capturing
return Promise.delay(500).then(() => {
debug('Trying to connect to Chrome...')
const harCapturer = HarCapturer.run([
urlUnderTest,
], {
port: cdpPort,
// disable SSL verification on older Chrome versions, copied from the HAR CLI
// https://github.com/cyrus-and/chrome-har-capturer/blob/587550508bddc23b7f4b4328c158322be4749298/bin/cli.js#L60
preHook: (_, cdp) => {
const { Security } = cdp
return Security.enable().then(() => {
return Security.setOverrideCertificateErrors({ override: true })
})
.then(() => {
return Security.certificateError(({ eventId }) => {
debug('EVENT ID', eventId)
return Security.handleCertificateError({ eventId, action: 'continue' })
})
})
},
// wait til all data is done before finishing
// https://github.com/cyrus-and/chrome-har-capturer/issues/59
postHook: (_, cdp) => {
let timeout
return new Promise((resolve) => {
cdp.on('event', (message) => {
if (message.method === 'Network.dataReceived') {
// reset timer
clearTimeout(timeout)
timeout = setTimeout(resolve, 1000)
}
})
})
},
})
return new Promise((resolve, reject) => {
harCapturer.on('fail', (_, err) => {
return reject(err)
})
harCapturer.on('har', resolve)
})
.then((har) => {
proc.kill(9)
debug('Received HAR from Chrome')
const results = getResultsFromHar(har)
_.merge(testCase, results)
return storeHar(testCase.name, har)
.return(results)
})
.catch({ code: 'ECONNREFUSED' }, (err) => {
// sometimes chrome takes surprisingly long, just reconn
debug('Chrome connection failed: ', err)
return runHar()
})
})
}
return runHar()
}
let cyServer
describe('Proxy Performance', function () {
this.timeout(60 * 1000)
this.retries(3)
beforeEach(function () {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
nock.enableNetConnect()
})
before(function () {
setCtx(makeDataContext({}))
const getFilesByGlob = getCtx().file.getFilesByGlob
return CA.create()
.then((ca) => {
return ca.generateServerCertificateKeys('localhost')
})
.spread((cert, key) => {
return Promise.join(
new DebuggingProxy().start(PROXY_PORT),
new DebuggingProxy({
https: { cert, key },
}).start(HTTPS_PROXY_PORT),
setupFullConfigWithDefaults({
projectRoot: '/tmp/a',
config: {
supportFile: false,
},
}, getFilesByGlob).then((config) => {
config.port = CY_PROXY_PORT
// turn off morgan
config.morgan = false
cyServer = new ServerBase()
return cyServer.open(config, {
SocketCtor: SocketE2E,
createRoutes,
testingType: 'e2e',
getCurrentBrowser: () => null,
})
}),
)
})
})
URLS_UNDER_TEST.map((urlUnderTest) => {
// TODO: fix flaky tests https://github.com/cypress-io/cypress/issues/23214
describe(urlUnderTest, { retries: 15 }, function () {
let baseline
const testCases = _.cloneDeep(TEST_CASES)
before(function () {
// run baseline test
return runBrowserTest(urlUnderTest, testCases[0])
.then((runtime) => {
debug('baseline runtime is: ', runtime)
baseline = runtime
})
})
// slice(1) since first test is used as baseline above
testCases.slice(1).map((testCase) => {
let multiplier = 3
if (testCase.httpsUpstreamProxy) {
// there is extra slowdown when the HTTPS upstream is used, so slightly increase the multiplier
// maybe from higher CPU utilization with debugging-proxy and HTTPS
multiplier *= 1.5
}
it(`${testCase.name} loads 1000 images less than ${multiplier}x as slowly as Chrome`, function () {
debug('Current test: ', testCase.name)
return runBrowserTest(urlUnderTest, testCase)
.then((results) => {
expect(results['Total']).to.be.lessThan(multiplier * baseline['Total'])
})
})
})
after(() => {
debug(`Done in ${Math.round((new Date() / 1000) - start)}s`)
process.stdout.write('Note: All times are in milliseconds.\n')
// eslint-disable-next-line no-console
console.table(testCases)
return Promise.map(testCases, (testCase) => {
testCase['URL'] = urlUnderTest
return performance.track('Proxy Performance', testCase)
})
})
})
})
})
|
JavaScript
|
CL
|
6e9a56d3d0f083ff382a7d891e1bc00b0f95b22ca8f46f82134f911fa3b776e2
|
import merge from "./merge"
/**
* Blends two values together based on their type.
* If both are objects this would result in a new object with the second value's props merged onto the first's.
* If the first value is an array, this would result in a new array with the second value concatenated onto the first value.
* If both values are strings or numbers, a new string will be returned with the second value added onto the first.
*
* @function
* @name append
* @param {string | number | Object<string, any> | Array<*>} firstVal A value that will have another appended onto
* @param {string | number | Object<string, any> | Array<*>} secondVal A value to append to the first value
* @returns {Array<*> | object | string} A new Array, Object, or String that has the characters/values from the second provided value merged _after_ those from the first provided value
*/
function append(firstVal, secondVal) {
if ([firstVal, secondVal].every(val => typeof val === "string" || typeof val === "number")) {
return `${firstVal}${secondVal}`
}
if (Array.isArray(firstVal) && Array.isArray(secondVal)) {
return [...firstVal, ...secondVal]
}
return merge(firstVal, secondVal)
}
export default append
|
JavaScript
|
CL
|
80cf15f4555ffd39cdc1ad5e881f1c738931ab38504503adbeb7aac6073f144b
|
/*
DUCK MODULE register.js 🦆
MUST export default a function called reducer()
MUST export its action creators as functions
MUST have action types in the form npm-module-or-app/reducer/ACTION_TYPE
MAY export its action types as UPPER_SNAKE_CASE, if an external reducer needs to listen for them, or if it is a published reusable library
*/
import axios from 'axios'
import { makeUrl } from '../../services'
// Action Types
const REGISTER_BEGIN = 'register/REGISTER_BEGIN'
const REGISTER_SUCCEDED = 'register/REGISTER_SUCCEDED'
const REGISTER_FAILED = 'register/REGISTER_FAILED'
// InitialState
const initialState = {
loading: false,
error: null
}
// Reducer
export default function reducer (state = initialState, action) {
switch (action.type) {
case REGISTER_BEGIN:
return {
...state,
error: null,
loading: true
}
case REGISTER_SUCCEDED:
return {
...state,
loading: false
}
case REGISTER_FAILED:
return {
...state,
loading: false,
error: action.error
}
default:
return state
}
}
// Action Creators
export const registerBegin = () => ({
type: REGISTER_BEGIN
})
export const registerSucceded = () => ({
type: REGISTER_SUCCEDED
})
export const registerFailed = (error) => ({
type: REGISTER_FAILED,
error
})
// Thunks
export const register = (user) => async (dispatch, getState) => {
try {
dispatch(registerBegin())
await axios.post(makeUrl('users'), user)
dispatch(registerSucceded())
return true
} catch (error) {
dispatch(registerFailed(error))
return false
}
}
|
JavaScript
|
CL
|
99b2afbac91dc05c197cc3a874cea53cf20fc3adb71fb69eb90b2b1059fb4971
|
// for phoenix_html support, including form and button helpers
// copy the following scripts into your javascript bundle:
// * https://raw.githubusercontent.com/phoenixframework/phoenix_html/v2.3.0/priv/static/phoenix_html.js
|
JavaScript
|
CL
|
76469568e95460413c75d97feedade6eb527541feb7bd73e32d1ff6b649618d2
|
/*
* This file is to be included by beaver contest tasks, it defines a basic
* implementation of the main functions of the task object, as well as a grader.
*
* Task can overwrite these definitions.
*
*/
/************************************************************************
* Untouched parts from beaver-task-1.0.
************************************************************************/
var task = {};
task.showViews = function(views, callback) {
if (views.forum || views.hint || views.editor) {
//console.error("this task does not have forum, hint nor editor specific view, showing task view instead.");
views.task = true;
}
$.each(['task', 'solution'], function(i, view) {
if (views[view]) {
$('#'+view).show();
} else {
$('#'+view).hide();
}
});
if (typeof task.hackShowViews === 'function') {task.hackShowViews(views);}
callback();
};
task.getViews = function(callback) {
// all beaver tasks have the same views
var views = {
task: {},
hints: {requires: "task"},
forum: {requires: "task"},
editor: {requires: "task"},
submission: {requires: "task"}
};
// Only declare the solution view if there's actually one
var solution = $('#solution').html();
if(solution && $.trim('' + solution)) {
views.solution = {};
}
callback(views);
};
task.updateToken = function(token, callback) {
callback();
};
task.getHeight = function(callback) {
callback(parseInt($("html").outerHeight(true)));
};
task.getMetaData = function(callback) {
if (typeof json !== 'undefined') {
callback(json);
} else {
callback({nbHints:0});
}
};
/************************************************************************
* Updated parts in beaver-task-2.0.
************************************************************************/
// TODO We update the grader below, if the task has levels. Is this line necessary?
var grader = grader ? grader : {};
function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
window.forcedLevel = getUrlParameter("level");
window.initialLevel = getUrlParameter("initialLevel");
function initWrapper(initSubTask, levels, defaultLevel, reloadWithCallbacks) {
// Create a subTask instance, possibly operating on an existing object.
function createTask(displayFlag) {
var subTask = {};
subTask.delayFactory = new DelayFactory();
subTask.raphaelFactory = new RaphaelFactory();
// Simulation factory needs a specific corresponding delay factory.
// TODO should it expect something else? subTask? A list of factories?
subTask.simulationFactory = new SimulationFactory(subTask.delayFactory);
subTask.display = displayFlag;
initSubTask(subTask);
return subTask;
}
// Destroy a subTask instance.
function destroyTask(subTask, callback) {
var doUnload = function() {
// Order is important.
subTask.raphaelFactory.destroyAll();
subTask.simulationFactory.destroyAll();
subTask.delayFactory.destroyAll();
if(callback && typeof callback === "function") {
callback();
}
};
if(levels || subTask.assumeLevels) {
subTask.unloadLevel(doUnload);
}
else {
// TODO Can we assume non-level tasks will imeplement 'unload'?
subTask.unload(doUnload);
}
}
// Invoke a function for each level, and wait for callback.
// When done, invoke finalCallback (optional).
function callbackLoop(array, itemCallback, finalCallback) {
var index = 0;
function innerLoop() {
if(index >= array.length) {
if(finalCallback) {
finalCallback();
}
return;
}
itemCallback(array[index], function() {
index++;
innerLoop();
});
}
innerLoop();
}
// Main subTask instance, for user display.
var mainTask;
var mainTaskParams;
// The state of the task, including current level and levelState for each level.
var state = null;
// Instances of subTask intended for grading.
var gradingTasks = {};
// Store whether this task has loaded but reloadAnswer was not yet called.
// Used for automatically changing to the first level that can gain points.
var hasJustLoaded = false;
task.load = function(views, callback) {
hasJustLoaded = true;
platform.getTaskParams(null, null, function(taskParams) {
if(taskParams.options && taskParams.options.level) {
window.forcedLevel = taskParams.options.level;
}
if(taskParams.options && taskParams.options.initialLevel) {
window.initialLevel = taskParams.options.initialLevel;
}
if(window.forcedLevel) {
window.initialLevel = window.forcedLevel;
levels = [window.forcedLevel];
}
if(window.initialLevel) {
defaultLevel = window.initialLevel;
} else if(defaultLevel) {
window.initialLevel = defaultLevel;
}
if(levels) {
var found = {};
for(var i = 0; i < levels.length ; i++) {
found[levels[i]] = true;
}
if(!found[window.initialLevel]) {
window.initialLevel = found['easy'] ? 'easy' : levels[0];
}
}
mainTask = createTask(true);
mainTask.taskParams = taskParams;
mainTaskParams = taskParams;
task.displayedSubTask = mainTask;
if(levels || mainTask.assumeLevels) {
// mainTask.assumeLevels is used for some quickAlgo tasks which
// don't declare any levels at all
if (window.forcedLevel) {
$("." + window.forcedLevel).show(); // TODO: why is it needed here?
}
if(!window.initialLevel) {
// Should happen only if mainTask.assumeLevels
window.initialLevel = "easy";
}
if(defaultLevel === null || defaultLevel === undefined) {
defaultLevel = window.initialLevel;
}
// The objects levelAnswers and levelStates are indexed by level names.
state = {
levelAnswers: {},
levelStates: {},
level: defaultLevel
};
if(window.displayHelper) {
displayHelper.displayLevel(state.level);
}
mainTask.loadLevel(state.level, null, views);
if(levels) {
displayHelper.setupLevels(defaultLevel, reloadWithCallbacks, levels);
}
callback();
}
else {
// TODO what's the desired behavior when no levels?
mainTask.load(views, callback);
}
});
};
task.getState = function(callback) {
if(levels || mainTask.assumeLevels) {
// Update state to reflect latest user interaction.
state.levelStates[state.level] = mainTask.getStateObject();
state.levelAnswers[state.level] = mainTask.getAnswerObject();
callback(JSON.stringify(state));
}
else {
// TODO is this the desired behavior? It is from beaver-task-1.0.
var currentState = {};
var displayedAnswer = mainTask.getAnswerObject();
currentState.displayedAnswer = displayedAnswer;
callback(JSON.stringify(currentState));
}
};
task.getStateObject = function() {
state.levelStates[state.level] = mainTask.getStateObject();
state.levelAnswers[state.level] = mainTask.getAnswerObject();
return state;
};
task.reloadAnswer = function(strAnswer, callback) {
if(hasJustLoaded && levels) {
// If this is the first time we reload an answer, jump to the first
// level that can gain points, if there are levels.
hasJustLoaded = false;
task.gradeAnswer(strAnswer, null, function(score, message) {
var maxScores = displayHelper.getLevelsMaxScores();
var level = window.initialLevel;
for(var i=1; i < levels.length; i++) {
if(score >= maxScores[levels[i-1]]) {
level = levels[i];
}
}
if (window.forcedLevel != null) {
level = window.forcedLevel;
}
var newAnswer = null;
if(strAnswer && strAnswer !== '') {
newAnswer = JSON.parse(strAnswer);
}
task.reloadAnswerObject(newAnswer, function() {
displayHelper.setLevel(level);
callback();
});
});
return;
}
var newAnswer;
if(strAnswer && strAnswer !== '') {
newAnswer = JSON.parse(strAnswer);
}
else {
newAnswer = null;
}
task.reloadAnswerObject(newAnswer, callback);
};
task.reloadAnswerObject = function(newAnswers, callback) {
if(levels || mainTask.assumeLevels) {
if (!newAnswers) {
state.levelAnswers = {};
}
else {
state.levelAnswers = newAnswers;
}
// Recreate the main task and load the relevant answer.
var level = state.level;
var levelAnswer = state.levelAnswers[level];
if(levelAnswer === undefined || levelAnswer === null) {
levelAnswer = mainTask.getDefaultAnswerObject();
state.levelAnswers[level] = levelAnswer;
}
state.levelStates[state.level] = mainTask.getStateObject();
var levelState = state.levelStates[level];
if(mainTask.getDefaultStateObject && (levelState === undefined || levelState === null)) {
levelState = mainTask.getDefaultStateObject();
state.levelStates[level] = levelState;
}
destroyTask(mainTask, function() {
mainTask = createTask(true);
mainTask.taskParams = mainTaskParams;
task.displayedSubTask = mainTask;
if(window.displayHelper) {
displayHelper.displayLevel(level);
}
mainTask.loadLevel(level, levelState);
mainTask.reloadAnswerObject(levelAnswer);
if(mainTask.resetDisplay) {
mainTask.resetDisplay();
}
if(callback && typeof callback === "function") {
callback();
}
});
}
else {
// TODO is this the desired behavior? Taken from beaver-task-1.0.
if (!newAnswers) {
mainTask.reloadAnswerObject(mainTask.getDefaultAnswerObject());
} else {
mainTask.reloadAnswerObject(newAnswers);
}
if(callback && typeof callback === "function") {
callback();
}
}
};
task.reloadState = function(newStateStr, callback) {
if (newStateStr) {
task.reloadStateObject(JSON.parse(newStateStr), callback);
} else {
task.reloadStateObject(task.getDefaultStateObject(), callback);
}
};
task.reloadStateObject = function(newState, callback) {
if(levels || mainTask.assumeLevels) {
// Recreate the task to reflect the new state.
state = newState;
if(!state.levelStates) { state.levelStates = {}; }
if(!state.levelAnswers) { state.levelAnswers = {}; }
if(!state.level) {
state.level = window.forcedLevel || window.initialLevel;
}
var level = state.level;
var levelState = state.levelStates[level];
destroyTask(mainTask, function() {
mainTask = createTask(false);
mainTask.taskParams = mainTaskParams;
task.displayedSubTask = mainTask;
if(window.displayHelper) {
displayHelper.displayLevel(level);
}
mainTask.loadLevel(level, levelState);
mainTask.reloadAnswerObject(state.levelAnswers[level]);
if(callback && typeof callback === "function") {
callback();
}
});
}
else {
// TODO is this the desired behavior? Taken from beaver-task-1.0.
if (typeof newState.displayedAnswer !== 'undefined') {
mainTask.reloadAnswer(newState.displayedAnswer, callback);
}
else {
if(callback && typeof callback === "function") {
callback();
}
}
}
};
task.getDefaultStateObject = function() {
return {
level: defaultLevel,
levelStates: {},
levelAnswers: {}
};
};
task.getDefaultAnswerObject = function() {
return {};
};
task.getAnswer = function(callback) {
if(levels || mainTask.assumeLevels) {
// Update answer to reflect latest user interaction.
state.levelAnswers[state.level] = mainTask.getAnswerObject();
callback(JSON.stringify(state.levelAnswers));
}
else {
// TODO is this desired behavior? Taken from beaver-task-1.
var answerObj = mainTask.getAnswerObject();
callback(JSON.stringify(answerObj));
}
};
task.getAnswerObject = function() {
if(levels || mainTask.assumeLevels) {
state.levelAnswers[state.level] = mainTask.getAnswerObject();
return state.levelAnswers;
}
else {
return mainTask.getAnswerObject();
}
};
task.unload = function(callback) {
var instances = [];
var iSeed;
if (typeof Blockly !== 'undefined') { // TEMPORARY, to replace with a global unload function provided by the task
removeBlockly();
}
if (levels) {
for(var iLevel in gradingTasks) {
for(iSeed in gradingTasks[iLevel]) {
instances.push(gradingTasks[iLevel][iSeed]);
}
}
} else {
for(iSeed in gradingTasks) {
instances.push(gradingTasks[iSeed]);
}
}
instances.push(mainTask);
callbackLoop(instances, function(subTask, loopCallback) {
destroyTask(subTask, loopCallback);
}, function() {
task.displayedSubTask = null;
callback();
});
};
function gradeAnswerInner(gradingTask, answer, minScore, maxScore, callback) {
gradingTask.isGrading = true;
if(answer === undefined || answer === null) {
answer = gradingTask.getDefaultAnswerObject();
}
if (window.forcedLevel != null && answer[window.forcedLevel]) {
answer = answer[window.forcedLevel];
} else if(!levels && mainTask.assumeLevels && answer.easy) {
answer = answer.easy;
}
gradingTask.reloadAnswerObject(answer);
gradingTask.getGrade(function(result) {
gradingTask.isGrading = false;
var score = 0;
if(result.successRate > 0) {
score = Math.round(result.successRate * (maxScore - minScore) + minScore);
}
callback({
score: score,
message: result.message
});
});
}
function gradeAnswerByLevel(taskParams, level, seed, levelAnswer, minScore, maxScore, callback) {
var gradingTask;
if(!gradingTasks[level]) {
gradingTasks[level] = {};
}
// Create new instance to be kept in gradingTasks array, and use it for this grading.
if(!gradingTasks[level][seed]) {
gradingTask = createTask(false);
gradingTask.taskParams = taskParams;
gradingTask.isGrading = false;
gradingTask.loadLevel(level);
gradingTasks[level][seed] = gradingTask;
gradeAnswerInner(gradingTask, levelAnswer, minScore, maxScore, callback);
}
// Current gradingTasks[level][seed] instance is busy, so create a temporary instance,
// to be destroyed immediately after grading.
else if(gradingTasks[level][seed].isGrading) {
gradingTask = createTask(false);
gradingTask.taskParams = taskParams;
gradingTask.isGrading = false;
gradingTask.loadLevel(level);
gradeAnswerInner(gradingTask, levelAnswer, minScore, maxScore, function(result) {
destroyTask(gradingTask, function() {
callback(result);
});
});
}
// Current gradingTasks[level][seed] instance is not busy, use it.
else {
gradingTasks[level][seed].taskParams = taskParams;
gradeAnswerInner(gradingTasks[level][seed], levelAnswer, minScore, maxScore, callback);
}
}
function gradeAnswerNoLevels(taskParams, seed, answer, minScore, maxScore, callback) {
var gradingTask;
// Grade a task instance.
var doGrading = function() {
gradeAnswerInner(gradingTask, answer, minScore, maxScore, callback);
};
// Grade a task instance and destroy it. Invoke callback after destruction.
var doGradingAndDestroy = function() {
gradeAnswerInner(gradingTask, answer, minScore, maxScore, function(result) {
destroyTask(gradingTask, function() {
callback(result);
});
});
};
// Create new instance to be kept in gradingTasks array, and use it for this grading.
if(!gradingTasks[seed]) {
gradingTask = createTask(false);
gradingTask.taskParams = taskParams;
gradingTasks[seed] = gradingTask;
gradingTask.load(null, doGrading);
}
// Current gradingTasks[seed] instance is busy, so create a temporary instance,
// to be destroyed immediately after grading.
else if(gradingTasks[seed].isGrading) {
gradingTask = createTask(false);
gradingTask.taskParams = taskParams;
gradingTask.load(null, doGradingAndDestroy);
}
// Current gradingTasks[seed] instance is not busy, use it.
else {
gradingTask = gradingTasks[seed];
gradingTask.taskParams = taskParams;
doGrading();
}
}
task.gradeAnswer = function(strAnswer, answerToken, callback) {
task.getLevelGrade(strAnswer, answerToken, callback, null);
};
// TODO: case where gradeAnswer is called again before it calls its callback
task.getLevelGrade = function(strAnswer, answerToken, callback, gradedLevel) {
// TODO Can we fetch task params just once instead of every time?
// If we can, then why do we need to index by seed in graders[level][seed]?
platform.getTaskParams(null, null, function(taskParams) {
if (strAnswer === '') {
callback(taskParams.minScore, '');
return;
}
var seed = taskParams.randomSeed;
var parsedAnswer = $.parseJSON(strAnswer);
if(levels) {
var maxScores = displayHelper.getLevelsMaxScores();
var minScores = {};
for(var i=0; i < levels.length; i++) {
minScores[levels[i]] = i > 0 ? maxScores[levels[i-1]] : 0;
}
var levelAnswers = parsedAnswer;
var scores = {};
var messages = {};
callbackLoop(levels, function(level, loopCallback) {
if(gradedLevel !== null && gradedLevel !== undefined && level !== gradedLevel) {
loopCallback();
return;
}
gradeAnswerByLevel(taskParams, level, seed, levelAnswers[level], minScores[level], maxScores[level], function(result) {
scores[level] = result.score;
messages[level] = result.message;
loopCallback();
});
},
function() {
// TODO is this correct? Taken from Arthur's level wrapper.
if(gradedLevel === null || gradedLevel === undefined) {
displayHelper.sendBestScore(callback, scores, messages);
} else {
callback(scores[gradedLevel], messages[gradedLevel]);
}
});
}
else {
gradeAnswerNoLevels(taskParams, seed, parsedAnswer, taskParams.minScore, taskParams.maxScore, function(result) {
callback(result.score, result.message);
});
}
});
};
// TODO is this the correct behavior?
grader.gradeTask = task.gradeAnswer;
task.gradeTask = grader.gradeTask;
}
/************************************************************************
* Utilities
************************************************************************/
function extractLevelSpecific(item, level) {
if ((typeof item != "object")) {
return item;
}
if($.isArray(item)) {
return $.map(item, function(val) {
return extractLevelSpecific(val, level);
});
}
if (item.shared === undefined) {
if (item[level] === undefined) {
var newItem = {};
for (var prop in item) {
newItem[prop] = extractLevelSpecific(item[prop], level);
}
return newItem;
}
return extractLevelSpecific(item[level], level);
}
if ($.isArray(item.shared)) {
var newItem = [];
for (var iElem = 0; iElem < item.shared.length; iElem++) {
newItem.push(extractLevelSpecific(item.shared[iElem], level));
}
if (item[level] != undefined) {
if (!$.isArray(item[level])) {
console.error("Incompatible types when merging shared and " + level);
}
for (var iElem = 0; iElem < item[level].length; iElem++) {
newItem.push(extractLevelSpecific(item[level][iElem], level));
}
}
return newItem;
}
if (typeof item.shared == "object") {
var newItem = {};
for (var prop in item.shared) {
newItem[prop] = extractLevelSpecific(item.shared[prop], level);
}
if (item[level] != undefined) {
if (typeof item[level] != "object") {
console.error("Incompatible types when merging shared and " + level);
}
for (var prop in item[level]) {
newItem[prop] = extractLevelSpecific(item[level][prop], level);
}
}
return newItem;
}
console.error("Invalid type for shared property");
}
function sendErrorLog() {
// Send errors to the platform
var args = Array.prototype.slice.call(arguments);
var key = args.join(':');
if(key == window.lastErrorLogSentKey) { return; }
try {
window.platform.log(["error", args]);
} catch(e) {}
}
window.onerror = sendErrorLog;
$('document').ready(function() {
platform.initWithTask(window.task);
});
|
JavaScript
|
CL
|
b4bc7e9267ab2e2b7fdb0d27eb458b30fe335a63e94dd37a2e9f7fef15c2b836
|
"use strict";
const _ = require('lodash');
/**
* Serializer Class used to serialize Sequelize
* Model attributes.
*
* @class Serializer
* @extends RestSequelize.Object
* @namespace RestSequelize
*/
class Serializer {
/**
* Serializes the payload obtained from the database to
* be flushed to the client.
*
* By default this function returns a `toJSON` representation
* of the Sequelize Model.
*
* @method serialize
* @param {RestAdapter} adapter
* @param {Model} model
* @param {Instance|Array} payload
* @param {Object meta
* @param {Numbser} status
* @return {Object}
*/
serialize(adapter, model, payload, meta, status) {
let serialized;
if (_.isArray(payload)) {
serialized = _.map(payload, (record) => this.serializeRecord(record) );
} else {
serialized = this.serializeRecord(payload);
}
meta = meta || {};
status = status || 200;
return {
result: serialized,
meta, status
};
}
/**
* Serializes a single record.
*
* @param {Instance} record
* @return {Object}
*/
serializeRecord(record) {
if (_.isFunction(record.toJSON)) {
return record.toJSON();
}
return record;
}
}
module.exports = Serializer;
|
JavaScript
|
CL
|
a2a6f86f1735a99bf8b9d17d047518d4a5a73e31ca67214b6c72e88ce3e73088
|
import debug from 'debug';
import { Permissions } from 'discord.js';
import { guildEmbed } from '../../lib/helpers/embeds';
const log = debug('Notification');
export const info = {
name: 'notification',
hidden: true,
description: 'Alerts the bot owner to events or problems with the bot.',
permissions: [Permissions.FLAGS.EMBED_LINKS],
};
/** @type {import('../../typedefs').Command} */
export default async ({ aquarius, analytics }) => {
aquarius.on('guildCreate', async guild => {
log(`Joined Server ${guild.name} (${guild.memberCount} members)`);
const channel = aquarius.channels.get(aquarius.config.home.channel);
const check = aquarius.permissions.check(
channel.guild,
...info.permissions
);
if (!check.valid) {
log('Invalid permissions');
return;
}
const embed = await guildEmbed(guild);
embed.setColor('2ECC40');
channel.send('**Joined Server**', embed);
analytics.trackUsage('guild join', null, {
guildId: guild.id,
guildName: guild.name,
});
});
aquarius.on('guildDelete', async guild => {
log(`Left Server ${guild.name} (${guild.memberCount} members)`);
const channel = aquarius.channels.get(aquarius.config.home.channel);
const check = aquarius.permissions.check(
channel.guild,
...info.permissions
);
if (!check.valid) {
log('Invalid permissions');
return;
}
const embed = await guildEmbed(guild);
embed.setColor('FF4136');
channel.send('**Left Server**', embed);
analytics.trackUsage('guild leave', null, {
guildId: guild.id,
guildName: guild.name,
});
});
};
|
JavaScript
|
CL
|
ff7b5e9fc1e2a69c8a30977d4b4396c4e3b34f9ecd219f1224ee2d7c43e0d46d
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.