text
stringlengths 7
3.69M
|
|---|
import GoodData from '../../src/lib/GoodData';
const _ = require('lodash');
const expect = require('unexpected');
const gd = new GoodData({
login: process.env.GD_ADMIN_LOGIN,
password: process.env.GD_ADMIN_PASS,
domain: process.env.GD_DOMAIN,
ssoProvider: process.env.GD_SSO_PROVIDER,
});
describe('GoodData', () => {
it('createProject, deleteProject', async () => {
const pid = await gd.createProject('test', process.env.TEST_GD_AUTH_TOKEN);
expect(pid, 'not to be empty');
let res = await expect(GoodData.call('get', `/gdc/projects/${pid}`), 'to be fulfilled');
expect(_.get(res, 'project.content.state'), 'to be', 'PREPARING');
// Wait for the project to be created (we cannot delete it until then)
await expect(gd.waitForProject(pid), 'to be fulfilled');
res = await expect(GoodData.call('get', `/gdc/projects/${pid}`), 'to be fulfilled');
expect(_.get(res, 'project.content.state'), 'to be', 'ENABLED');
await gd.deleteProject(pid);
res = await expect(GoodData.call('get', `/gdc/projects/${pid}`), 'to be fulfilled');
expect(_.get(res, 'project.content.state'), 'to be', 'DELETED');
});
const login = `e1${_.random(1000, 1000000)}@t.${process.env.KBC_ACCESS_DOMAIN}`;
const email = `${_.random(1000, 2000)}@t.${process.env.KBC_ACCESS_DOMAIN}`;
it('createUser, deleteUser, getUserUid', async () => {
const uid = await gd.createUser(login, `abcd${_.random(3000, 8000)}`, 'Provisioning', 'Test', email);
expect(uid, 'not to be empty');
let res = await GoodData.call('get', `/gdc/account/profile/${uid}`);
expect(_.get(res, 'accountSetting.email'), 'to be', email);
expect(_.get(res, 'accountSetting.login'), 'to be', login);
expect(_.get(res, 'accountSetting.ssoProvider'), 'to be', process.env.GD_SSO_PROVIDER);
expect(_.get(res, 'accountSetting.links.domain'), 'to be', `/gdc/domains/${process.env.GD_DOMAIN}`);
res = await gd.getUserUid(login);
expect(res, 'to be', uid);
await gd.deleteUser(uid);
res = await expect(GoodData.call('get', `/gdc/account/profile/${uid}`), 'to be fulfilled');
expect(_.get(res, 'accountSetting.email'), 'to be', 'deleted@gooddata.com');
});
const login2 = `e2${_.random(1000, 1000000)}@t.${process.env.KBC_ACCESS_DOMAIN}`;
it('addUserToProject, removeUserFromProject', async () => {
const uid = await gd.createUser(login2, `abcd${_.random(3000, 8000)}`, 'Provisioning', 'Test');
expect(uid, 'not to be empty');
const pid = await gd.createProject('test', process.env.TEST_GD_AUTH_TOKEN);
expect(pid, 'not to be empty');
await gd.waitForProject(pid);
await expect(() => GoodData.call('get', `/gdc/projects/${pid}/users/${uid}`), 'to be rejected');
await expect(() => gd.addUserToProject(pid, uid, 'editor'), 'to be fulfilled');
await expect(() => GoodData.call('get', `/gdc/projects/${pid}/users/${uid}`), 'to be fulfilled');
await expect(() => gd.removeUserFromProject(pid, uid), 'to be fulfilled');
await expect(() => GoodData.call('get', `/gdc/projects/${pid}/users/${uid}`), 'to be rejected');
await gd.deleteUser(uid);
await gd.deleteProject(pid);
});
});
|
$('.burger-button').on('click', function(){ //добавляем событие при клике по burger-button и тогда NAV добавляем класс active
$('.header-nav').toggleClass('active')
//также обычно добавляют класс active и самому нажатию (this)
$(this).toggleClass('active')
});
//РАскрывающийся вложенный список
$('.contain').on('click', function(){
$('.header-nav-list-invest').toggleClass('active')
});
$('.contain').on('click', function(event){ /*остановили событие - а ниже записано, что при клике на любую область body у нас удаляется класс active (то есть display: block пропадает) */
event.stopPropagation()
});
$('body').on('click', function(event){
$('.header-nav-list-invest').removeClass('active')
});
/*ДЛя карусели - подключаем 3 файла с библиотеки и пишем код */
// $('.second-carousel').on('afterChange', function(event, slick, currentSlide){
// $('h3').text('Current slide is ' + currentSlide)
// })
//НАйстройки:
$('.carusel').slick({
// autoplay: true, // автоматически через время меняются тексты Div ов
// autoplaySpeed: 1000 //указывается в ms, как быстро переключается
// centerMode: true,
arrows: true,
dots: true, // отображение точек по слайдам
prevArrow: '.prev-button',
nextArrow: '.next-button',
slidesToShow: 2,
slidesToScroll: 1,
responsive: [
{
breakpoint: 720,
settings:{
slidesToShow: 1,
slidesToScroll: 1,
arrows: false
}
},
{
breakpoint: 475,
settings:{
slidesToShow:1,
slidesToScroll:1,
arrows: false
}
}
]
});
/*Кнопка наверх */
//МОжно сделать через функцию
function setUpVisibility(){
var scrollTop = $(window).scrollTop() //console.log(scrollTop)
console.log(scrollTop) /*показать в консоле , на сколько сдвинут экран в px */
if(scrollTop > 900){ // сдвигаем на 200px и появляется кнопка
$('#up').addClass('visible')
}
else{
$('#up').removeClass('visible')
}
}
setUpVisibility();
$(window).on('scroll',setUpVisibility);
//Более оптимизированная кнопка
/*
// function setUpVisibility(){
// var scrollTop = $(window).scrollTop() //console.log(scrollTop)
// if(scrollTop > 600 && !$('#up').hasClass('visible')){ // сдвигаем на 200px и если id = 'up' не имеет класса visible - появляется кнопка
// $('#up').addClass('visible')
// }
// else if (scrollTop <= 600 && $('#up').hasClass('visible')){
// $('#up').removeClass('visible')
// }
// }
// setUpVisibility();
// $(window).on('scroll',setUpVisibility);
*/
/*Теперь скрол наверх */
$('#up').on('click', function(){ // на кнопку up вешаем слушатель событий анимацию вверх (0)
$('html').stop().animate({
scrollTop: 0
})
});
|
angular.module('myApp.view1', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl',
controllerAs: 'view1',
});
}])
.controller('View1Ctrl', ['$scope', '$http', function($scope, $http) {
var vm = this;
$http.get("https://interview-api-staging.bytemark.co/books").then(function(response){
vm.booklist = response.data;
});
vm.viewmorefun = function(booklist,index){
vm['viewmore' + index] = !(vm['viewmore' + index]);
if(booklist.showedit && booklist.edit){
booklist['showedit']=false;
booklist['edit']=false;
}else{
booklist['showedit']=true;
booklist['edit']=true;
}
}
vm.editabookfun = function(booklist,index){
booklist['edit']=false;
vm['editabook' + index] = false;
console.log(booklist);
}
vm.addbook = function(addnewbookobj){
console.log(addnewbookobj);
var data={
"author": addnewbookobj.author,
"categories": addnewbookobj.categories,
"publisher": addnewbookobj.publisher,
"title": addnewbookobj.title
};
$http.post("https://interview-api-staging.bytemark.co/books",data).then(function(response){
alert(response);
});
/*$http({
method: 'POST',
dataType: 'json',
url: "https://interview-api-staging.bytemark.co/books",
data: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).success(function (data, status, headers, config) {
console.log(data);
}).error(function (data, status, headers, config) {
console.log(data);
});*/
}
vm.saveabook = function(book) {
book.edit=true;
console.log(book);
//var id=book.url.substring(book.url.length, book.url.indexOf("/")+1);
var id=book.url.split("/").slice(2);
console.log(id[0]);
var data={
"author": book.author,
"categories": book.categories,
"publisher": book.publisher,
"title": book.title
};
$http.put("https://interview-api-staging.bytemark.co/books/"+id[0],data).then(function(response){
alert(response);
});
}
vm.deleteabookfun = function(book) {
var id=book.url.split("/").slice(2);
console.log(id[0]);
$http.delete("https://interview-api-staging.bytemark.co/books/"+id[0]).then(function(response){
alert(response);
});
}
vm.deletebooks = function() {
$http.delete("https://interview-api-staging.bytemark.co/clean").then(function(response){
console.log(response);
})
}
}]);
|
/**
* ownCloud
*
* @author Vincent Petry
* @copyright Copyright (c) 2017 Vincent Petry <pvince81@owncloud.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
describe('OC.Share.ShareDialogLinkExpirationView', function() {
var itemModel;
var fileInfoModel;
var configModel;
var tooltipStub;
var model;
var view;
beforeEach(function() {
configModel = new OC.Share.ShareConfigModel();
fileInfoModel = new OCA.Files.FileInfoModel({
id: 123,
name: 'shared_folder',
path: '/subdir',
size: 100,
mimetype: 'httpd/unix-directory',
permissions: 31,
sharePermissions: 31
});
itemModel = new OC.Share.ShareItemModel({
itemType: 'folder',
itemSource: 123,
permissions: 31
}, {
configModel: configModel,
fileInfoModel: fileInfoModel
});
tooltipStub = sinon.stub($.fn, 'tooltip');
/* jshint camelcase: false */
model = new OC.Share.ShareModel({
id: 1,
name: 'first link',
token: 'tehtokenz',
shareType: OC.Share.SHARE_TYPE_LINK,
itemType: 'folder',
stime: 1489657516,
permissions: OC.PERMISSION_READ,
share_with: null,
expireDate: null,
});
view = new OC.Share.ShareDialogLinkExpirationView({
model: model,
itemModel: itemModel
});
view.render();
});
afterEach(function() {
tooltipStub.restore();
view.remove();
});
describe('rendering', function() {
it('renders fields populated with model values', function() {
view.render();
expect(view.$('.expirationDate').val()).toEqual('');
model.set({
expireDate: '2017-10-12',
});
view.render();
expect(view.$('.expirationDate').val()).toEqual('12-10-2017');
});
describe('enforced expiration', function() {
it('renders enforced message when enforced', function() {
configModel.set('isDefaultExpireDateEnforced', true);
view.render();
expect(view.$('.defaultExpireMessage').length).toEqual(1);
expect(view.$('.required-indicator').length).toEqual(1);
});
it('does not render enforced message when not enforced', function() {
configModel.set('isDefaultExpireDateEnforced', false);
view.render();
expect(view.$('.defaultExpireMessage').length).toEqual(0);
expect(view.$('.required-indicator').length).toEqual(0);
});
it('shows error message on validate if expiration date is empty', function() {
configModel.set('isDefaultExpireDateEnforced', true);
view.render();
view.$('.expirationDate').val('');
expect(view.validate()).toEqual(false);
expect(view.$('.error-message').hasClass('hidden')).toEqual(false);
expect(view.$('.error-message').text()).toContain('required');
});
it('does not show error message on validate when not enforced', function() {
configModel.set('isDefaultExpireDateEnforced', false);
view.render();
view.$('.expirationDate').val('');
expect(view.validate()).toEqual(true);
expect(view.$('.error-message').hasClass('hidden')).toEqual(true);
});
});
describe('date picker defaults', function() {
var clock;
var expectedMinDate;
var setDefaultsStub;
var datepickerStub;
beforeEach(function() {
// pick a fake date
clock = sinon.useFakeTimers(new Date(2014, 0, 20, 14, 0, 0).getTime());
expectedMinDate = new Date(2014, 0, 20, 14, 0, 0);
datepickerStub = sinon.stub($.fn, 'datepicker');
setDefaultsStub = sinon.stub($.datepicker, 'setDefaults');
configModel.set({
isDefaultExpireDateEnabled: false,
isDefaultExpireDateEnforced: false,
defaultExpireDate: 7
});
model.set('expireDate', null);
});
afterEach(function() {
clock.restore();
datepickerStub.restore();
setDefaultsStub.restore();
});
it('sets date picker format', function() {
view.render();
expect(datepickerStub.calledOnce).toEqual(true);
expect(datepickerStub.getCall(0).args[0]).toEqual({dateFormat: 'dd-mm-yy'});
});
it('does not check expiration date checkbox when no date was set', function() {
view.render();
expect(view.$el.find('.datepicker').val()).toEqual('');
});
it('does not check expiration date checkbox for new share', function() {
view.render();
expect(view.$el.find('.datepicker').val()).toEqual('');
});
it('checks expiration date checkbox and populates field when expiration date was set', function() {
model.set('expireDate', '2014-02-01 00:00:00');
view.render();
expect(view.$el.find('.datepicker').val()).toEqual('01-02-2014');
});
it('sets default date when default date setting is enabled', function() {
configModel.set('isDefaultExpireDateEnabled', true);
view.render();
// here fetch would be called and the server returns the expiration date
model.set('expireDate', '2014-1-27 00:00:00');
view.render();
// enabled by default
expect(view.$el.find('.datepicker').val()).toEqual('27-01-2014');
});
it('enforces default date when enforced date setting is enabled', function() {
configModel.set({
isDefaultExpireDateEnabled: true,
isDefaultExpireDateEnforced: true
});
view.render();
// here fetch would be called and the server returns the expiration date
model.set('expireDate', '2014-1-27 00:00:00');
view.render();
expect(view.$el.find('.datepicker').val()).toEqual('27-01-2014');
});
it('sets picker minDate to today and no maxDate by default', function() {
view.render();
expect(setDefaultsStub.getCall(0).args[0].minDate).toEqual(expectedMinDate);
expect(setDefaultsStub.getCall(0).args[0].maxDate).toEqual(null);
});
it('limits the date range to X days after share time when enforced', function() {
configModel.set({
isDefaultExpireDateEnabled: true,
isDefaultExpireDateEnforced: true
});
model.set('stime', new Date(2014, 0, 20, 11, 0, 25).getTime() / 1000);
view.render();
expect(setDefaultsStub.lastCall.args[0].minDate).toEqual(expectedMinDate);
expect(setDefaultsStub.lastCall.args[0].maxDate).toEqual(new Date(2014, 0, 27, 0, 0, 0, 0));
});
it('limits the date range to X days after share time when enforced, even when redisplayed the next days', function() {
// item exists, was created two days ago
model.set({
expireDate: '2014-1-27',
// share time has time component but must be stripped later
stime: new Date(2014, 0, 20, 11, 0, 25).getTime() / 1000
});
configModel.set({
isDefaultExpireDateEnabled: true,
isDefaultExpireDateEnforced: true
});
view.render();
expect(setDefaultsStub.getCall(0).args[0].minDate).toEqual(expectedMinDate);
expect(setDefaultsStub.getCall(0).args[0].maxDate).toEqual(new Date(2014, 0, 27, 0, 0, 0, 0));
});
});
});
it('returns field value', function() {
view.$('.expirationDate').val('03-04-2017');
expect(view.getValue()).toEqual('03-04-2017');
});
});
|
const React = require('react')
const axios = require('axios')
const INVITE_BUTTON = 'INVITE_BUTTON'
const INVITE_ERROR = 'INVITE_ERROR'
const INVITE_SUCCESS = 'INVITE_SUCCESS'
const InviteButton = React.createClass({
propTypes: {
emailAddress: React.PropTypes.string.isRequired,
sendState: React.PropTypes.func.isRequired
},
postInvite() {
axios.post('./invite', {
email: this.props.emailAddress
}).then(() => {
this.props.sendState({APP_STATE: INVITE_SUCCESS, error: null})
}).catch((response) => {
this.props.sendState({APP_STATE: INVITE_ERROR, error: response.data.msg})
})
},
render() {
return (
<div>
<div className="logos"><div className="logo org"></div><div className="logo slack"></div></div>
<p>
Slack is a messaging app for teams. IT Services is using Slack to communicate more effectively between ITS units, within project teams, and directly between colleagues.
Create a public slack team for your new project, chat privately between your small team, or 1-to-1. Even the CIO uses Slack!
</p>
<p>
Click the button below to join SFU ITS on Slack.
</p>
<button
onClick={this.postInvite}
style={{
marginBottom: '50px',
marginTop: '25px'
}}
>
Join SFU ITS on Slack
</button>
</div>
)
}
})
const InviteSuccess = ({emailAddress}) => {
return (
<div>
<h2>Invitation Sent</h2>
<p>
An invitaiton to join the SFUITS team on Slack has been sent to {emailAddress}.
Please check your email and follow the instructions in the invitation.
</p>
<p>
Chat with you soon! 🎉
</p>
</div>
)
}
InviteSuccess.propTypes = {
emailAddress: React.PropTypes.string.isRequired
}
const InviteError = React.createClass({
propTypes: {
msg: React.PropTypes.string.isRequired,
sendState: React.PropTypes.func.isRequired
},
tryAgain() {
this.props.sendState({APP_STATE: INVITE_BUTTON, error: null})
},
render() {
const style = {
borderLeft: '3px solid #ccc',
paddingLeft: '15px'
}
return (
<div>
<h2>Uh-Oh…</h2>
<p>
This is embarrasing, but there was a problem sending you an invitation to Slack. 😢
Here's what they told us:
</p>
<p style={style}><i>{this.props.msg}</i></p>
<button
onClick={this.tryAgain}
style={{
marginBottom: '50px',
marginTop: '25px'
}}
>
Try Again?
</button>
</div>
)
}
})
const App = React.createClass({
getInitialState() {
return Object.assign({
APP_STATE: INVITE_BUTTON,
error: null
}, window.__STATE__)
},
_receiveState(state) {
const {APP_STATE, error} = state
this.setState({
APP_STATE,
error
})
},
_renderer() {
let output
switch (this.state.APP_STATE) {
case INVITE_BUTTON:
output = (
<InviteButton
emailAddress={this.state.email}
sendState={this._receiveState}
/>
)
break
case INVITE_SUCCESS:
output = (
<InviteSuccess emailAddress={this.state.email} />
)
break
case INVITE_ERROR:
output = (
<InviteError
msg={this.state.error}
sendState={this._receiveState}
/>
)
break
}
return output
},
render() {
return (
<div>
{this._renderer()}
</div>
)
}
})
module.exports = App
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import GoogleLogin from 'react-google-login';
import { FormattedMessage } from 'react-intl';
import { loginWithGoogle } from '../../actions/userActions';
import keys from '../../constants/keys';
class Google extends Component {
handleSuccess= (response) =>{
this.props.loginWithGoogle(response.accessToken)
}
handleFailure = () => {
}
render() {
return (
<GoogleLogin
clientId={keys.googleClientID}
buttonText={<FormattedMessage id="login_with_google" />}
onSuccess={this.handleSuccess}
onFailure={this.handleFailure}
cookiePolicy={'single_host_origin'}
/>
)
}
}
const mapStateToProps = ({ auth }) => auth;
const mapDispatchToProps = {
loginWithGoogle,
}
export default connect(mapStateToProps, mapDispatchToProps)(Google);
|
import { dcs_mapping } from '../../../../config/json_visualization_dcs_bit_mapping';
const getWhichSubsystemDCSBelongsTo = (dcs_var) => {
for (const [subsystem, dcs_vars] of Object.entries(dcs_mapping)) {
if (dcs_vars.includes(dcs_var)) {
return subsystem;
}
}
return 'unknown';
};
const generateData = (rules_flagged_false_combination_luminosity) => {
// ONLY DCS:
let dcs_lumi_losses = {};
let dcs_lumi_losses_runs = {};
let dcs_lumi_loss_total = 0;
// DCS grouped per subsystem:
let subsystem_dcs_losses = {};
let subsystem_dcs_losses_runs = {};
let subsystem_lumi_loss_total = 0;
// RR Quality:
let rr_lumi_losses = {};
let rr_lumi_losses_runs = {};
let rr_lumi_loss_total = 0;
// RR Quality per subsystem:
let subsystem_rr_losses = {};
let subsystem_rr_losses_runs = {};
let subsystem_rr_loss = 0;
// Both:
let inclusive_losses = {};
let inclusive_losses_runs = {};
let inclusive_loss = 0;
// Exclusive losses
let exclusive_losses = {
mixed: 0,
};
let exclusive_losses_runs = {
mixed: {},
};
let exclusive_loss = 0;
for (const [key, val] of Object.entries(
rules_flagged_false_combination_luminosity
)) {
const vars = getVars(key);
const rr_only = vars
.filter((name) => name.includes('.rr.'))
.map((name) => name.split('.rr.')[1]);
const dcs_only = vars
.filter((name) => name.includes('.oms.'))
.map((name) => name.split('.oms.')[1]);
dcs_only.forEach((dcs_name) => {
dcs_lumi_loss_total += val;
if (typeof dcs_lumi_losses[dcs_name] === 'undefined') {
dcs_lumi_losses[dcs_name] = val;
dcs_lumi_losses_runs[dcs_name] =
runs_lumisections_responsible_for_rule[key];
} else {
dcs_lumi_losses[dcs_name] = dcs_lumi_losses[dcs_name] + val;
dcs_lumi_losses_runs[dcs_name] = add_jsons_fast(
dcs_lumi_losses_runs[dcs_name],
runs_lumisections_responsible_for_rule[key]
);
}
});
let subsystem_already_added = {};
dcs_only.forEach((dcs_name) => {
// We need to find to which subsystem does this dcs rule belong to:
const subsystem = getWhichSubsystemDCSBelongsTo(dcs_name);
if (typeof subsystem_already_added[subsystem] === 'undefined') {
subsystem_lumi_loss_total += val;
if (typeof subsystem_dcs_losses[subsystem] === 'undefined') {
subsystem_dcs_losses[subsystem] = val;
subsystem_dcs_losses_runs[subsystem] =
runs_lumisections_responsible_for_rule[key];
} else {
subsystem_dcs_losses[subsystem] =
subsystem_dcs_losses[subsystem] + val;
subsystem_dcs_losses_runs[subsystem] = add_jsons_fast(
subsystem_dcs_losses_runs[subsystem],
runs_lumisections_responsible_for_rule[key]
);
}
subsystem_already_added[subsystem] = true;
}
});
rr_only.forEach((rr_name) => {
rr_lumi_loss_total += val;
if (typeof rr_lumi_losses[rr_name] === 'undefined') {
rr_lumi_losses[rr_name] = val;
rr_lumi_losses_runs[rr_name] =
runs_lumisections_responsible_for_rule[key];
} else {
rr_lumi_losses[rr_name] = rr_lumi_losses[rr_name] + val;
rr_lumi_losses_runs[rr_name] = add_jsons_fast(
rr_lumi_losses_runs[rr_name],
runs_lumisections_responsible_for_rule[key]
);
}
});
subsystem_already_added = {};
rr_only.forEach((rr_name) => {
const subsystem = rr_name.split('-')[0];
if (typeof subsystem_already_added[subsystem] === 'undefined') {
subsystem_rr_loss += val;
if (typeof subsystem_rr_losses[subsystem] === 'undefined') {
subsystem_rr_losses[subsystem] = val;
subsystem_rr_losses_runs[subsystem] =
runs_lumisections_responsible_for_rule[key];
} else {
subsystem_rr_losses[subsystem] = subsystem_rr_losses[subsystem] + val;
subsystem_rr_losses_runs[subsystem] = add_jsons_fast(
subsystem_rr_losses_runs[subsystem],
runs_lumisections_responsible_for_rule[key]
);
}
subsystem_already_added[subsystem] = true;
}
});
const subsystem_already_added = {};
rr_only.forEach((rr_name) => {
const subsystem = rr_name.split('-')[0];
if (typeof subsystem_already_added[subsystem] === 'undefined') {
inclusive_loss += val;
if (typeof inclusive_losses[subsystem] === 'undefined') {
inclusive_losses[subsystem] = val;
inclusive_losses_runs[subsystem] =
runs_lumisections_responsible_for_rule[key];
} else {
inclusive_losses[subsystem] = inclusive_losses[subsystem] + val;
inclusive_losses_runs[subsystem] = add_jsons_fast(
inclusive_losses_runs[subsystem],
runs_lumisections_responsible_for_rule[key]
);
}
subsystem_already_added[subsystem] = true;
}
});
dcs_only.forEach((dcs_name) => {
// We need to find to which subsystem does this dcs rule belong to:
const subsystem = getWhichSubsystemDCSBelongsTo(dcs_name);
if (typeof subsystem_already_added[subsystem] === 'undefined') {
inclusive_loss += val;
if (typeof inclusive_losses[subsystem] === 'undefined') {
inclusive_losses[subsystem] = val;
inclusive_losses_runs[subsystem] =
runs_lumisections_responsible_for_rule[key];
} else {
inclusive_losses[subsystem] = inclusive_losses[subsystem] + val;
inclusive_losses_runs[subsystem] = add_jsons_fast(
inclusive_losses_runs[subsystem],
runs_lumisections_responsible_for_rule[key]
);
}
subsystem_already_added[subsystem] = true;
}
});
const loss_added = false;
for (const [subsystem, dcs_bits] of Object.entries(dcs_mapping)) {
const only_dcs_bits_from_this_subystem = dcs_only.every((dcs_bit) =>
dcs_bits.includes(dcs_bit)
);
const only_rr_from_this_subystem = rr_only.every(
(rr_rule) => rr_rule.split('-')[0] === subsystem
);
if (only_dcs_bits_from_this_subystem && only_rr_from_this_subystem) {
exclusive_loss += val;
loss_added = true;
if (typeof exclusive_losses[subsystem] === 'undefined') {
exclusive_losses[subsystem] = val;
exclusive_losses_runs[subsystem] =
runs_lumisections_responsible_for_rule[key];
} else {
exclusive_losses[subsystem] = exclusive_losses[subsystem] + val;
exclusive_losses_runs[subsystem] = add_jsons_fast(
exclusive_losses_runs[subsystem],
runs_lumisections_responsible_for_rule[key]
);
}
}
}
if (!loss_added) {
exclusive_losses['mixed'] = exclusive_losses['mixed'] + val;
exclusive_losses_runs['mixed'] = add_jsons_fast(
exclusive_losses_runs['mixed'],
runs_lumisections_responsible_for_rule[key]
);
}
}
};
|
import React, { Component, Suspense } from 'react';
import AppMain from './components/AppMain';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';
import * as userActions from './actions/userActions';
import * as settingsActions from './actions/settingsActions';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import PropTypes from 'prop-types';
import { Spin } from 'antd'
import { Auth } from 'aws-amplify';
import { ThemeProvider } from 'styled-components';
import { themes } from './themes.js'
import NotFound from './components/NotFound';
import ComingSoon from './components/ComingSoon';
import './App.scss';
const UserAuth = React.lazy(() => import('./components/UserAuth'));
class App extends Component {
state = {
isAuthenticating: true
};
async componentDidMount() {
try {
await Auth.currentSession();
const userDetails = await Auth.currentAuthenticatedUser();
this.props.userActions.updateUser({ ...this.props.user, user: userDetails, isAuthenticated: true });
this.props.settingsActions.fetchSettings();
} catch (e) {
console.error(e);
}
this.setState({ isAuthenticating: false });
}
render() {
return (
!this.state.isAuthenticating && (
<ThemeProvider theme={themes[this.props.settings.theme]}>
<BrowserRouter>
<Switch>
<Route
exact
path="/user"
component={() => (
<Suspense fallback={<Spin style={{top: '35vh', left: '50vw', position: 'absolute'}}/>}>
<UserAuth />
</Suspense>
)}
/>
<ProtectedRoute path="/app" authed={this.props.user.isAuthenticated} component={AppMain} title="Home" />
<Route exact path="/" component={ComingSoon} title="Stay in the flow" />
<Route component={NotFound} title="404 Not Found"/>
</Switch>
</BrowserRouter>
</ThemeProvider>
)
);
}
}
function ProtectedRoute({ component: Component, authed, ...rest }) {
return (
<Route
{...rest}
render={(props) =>
authed === true ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: '/user', state: { from: props.location } }} />
)}
/>
);
}
App.propTypes = {
userActions: PropTypes.object,
user: PropTypes.object,
settings: PropTypes.object
};
function mapStateToProps(state) {
return {
user: state.user,
settings: state.settings
};
}
function mapDispatchToProps(dispatch) {
return {
userActions: bindActionCreators(userActions, dispatch),
settingsActions: bindActionCreators(settingsActions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
|
const http=require('http');
const unifiedServer=require('./serverConfig');
//Instantiate the http server
const httpServer=http.createServer((req,res)=>{
unifiedServer(req,res)
})
//Start the server
httpServer.listen(3000,(err)=>{
if(err)
{
throw err;
}
console.log("Server listening at port",3000)
})
|
import React from 'react'
import { StyleSheet, Text, View, Image, TouchableWithoutFeedback } from 'react-native'
import {map} from 'lodash'
import { API_URL } from '../../utils/constants'
import {useNavigation} from '@react-navigation/native'
export default function ListProducts(props) {
const {products} = props
const navigation = useNavigation()
const goToProduct = (id) => {
navigation.push("product", {idProducto: id})
}
return (
<View style= {styles.container}>
{
map(products, (product) => (
<TouchableWithoutFeedback
key={product._id}
onPress={() => goToProduct(product._id)}
>
<View style={styles.containerProduct}>
<View style={styles.product}>
<Text style= { styles.marca} numberOfLines={1} ellipsizeMode="tail">{product.marca}</Text>
<Image
style={styles.image}
source= {{
uri: `${API_URL}${product.main_image.url}`
}}
/>
<Text style= { styles.modelo} numberOfLines={1} ellipsizeMode="tail">{product.title}</Text>
</View>
</View>
</TouchableWithoutFeedback>
))
}
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "row",
flexWrap:"wrap",
alignItems: "flex-start",
margin: -2
},
containerProduct:{
width: "50%",
padding: 2
},
product: {
backgroundColor: "#f5f5f5",
padding: 10
},
image:{
height: 150,
resizeMode:"contain"
},
modelo: {
padding: 5,
fontSize:12,
alignSelf: "center"
},
marca: {
padding: 5,
fontSize:18,
alignSelf: "center",
fontWeight: "bold"
}
})
|
import React, {Component} from 'react';
import {Card, Select, Divider} from 'antd';
import {Link} from 'react-router-dom';
import IngresoInfo from "./InfoIngreso";
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import moment from 'moment';
import * as ingresoActions from '../../redux/actions/administracion/ingresosActions';
import * as linesActions from '../../redux/actions/blines/blinesActions';
import * as cuentasActions from '../../redux/actions/cuentas/cuentasActions';
import * as clientesActions from '../../redux/actions/administracion/clientesActions';
import MainLoader from "../common/Main Loader";
const Option = Select.Option;
const opciones = [{
name :'Cerdos',
id: 1
},
{
name:'Ganado',
id:2
},
{
name:'Granos',
id:3
},
{
name:'Planta de alimentos',
id:4
},
{
name:'Campo',
id:5
},
];
class DetailIngresoPage extends Component{
state={
editMode:false,
linea:'',
cuenta:'',
cliente:'',
clientChange:false,
idCuent:null,
idBl:null,
idClient:null,
};
handleEditMode=()=>{
this.setState({editMode:!this.state.editMode})
};
handleSearchLine=(a)=>{
console.log(a)
let basePath = 'https://rancho.davidzavala.me/api/ingresos/blines/?q=';
//let basePath = 'http://127.0.0.1:8000/api/ingresos/blines/?q=';
let url = basePath+a;
console.log(url)
this.props.linesActions.getLiSearch(url);
};
handleChangeS=(value, obj)=> {
console.log(`selected ${value}`);
this.setState({linea:value});
//let basePath = 'http://127.0.0.1:8000/api/ingresos/blines/';
//this.props.linesActions.getLiSearch(basePath);
};
//Cuentas
handleCuenta=(a)=>{
console.log(a)
let basePath = 'https://rancho.davidzavala.me/api/ingresos/cuentas/?q=';
//let basePath = 'http://127.0.0.1:8000/api/ingresos/cuentas/?q=';
let url = basePath+a;
console.log(url)
this.props.cuentasActions.getCuSearch(url);
};
changeCuentaS=(value, obj)=> {
console.log(`selected ${value}`);
this.setState({cuenta:value});
};
//Clientes
handleClient=(a)=>{
console.log(a)
//let basePath = 'http://127.0.0.1:8000/api/ingresos/clientes/?q=';
let basePath = 'https://rancho.davidzavala.me/api/ingresos/clientes/?q=';
let url = basePath+a;
console.log(url)
this.props.clientesActions.getClSearch(url);
};
changeClientS=(value, obj)=> {
console.log(`selected ${value}`);
this.setState({cliente:value, handleClient:true});
};
//saveIDs
saveClient=(id)=>{
console.log("DD", id)
this.setState({idClient:id})
};
saveBl=(id)=>{
this.setState({idBl:id})
};
saveCuent=(id)=>{
this.setState({idCuent:id})
};
saveCompany=(id)=>{
this.setState({idCompany:id})
};
render(){
let {ingreso, fetched, clientes, blines, cuentas,companies} = this.props;
let {editMode, linea} = this.state;
if(!fetched)return(<MainLoader/>);
let options = opciones.map(o => <Option title={o.name} value={o.name} key={o.id}>{o.name}</Option>);
return(
<div>
<div style={{marginBottom:10, color:'rgba(0, 0, 0, 0.65)' }}>
Administración
<Divider type="vertical" />
<Link to={`/admin/ingresos/`} style={{color:'black'}} >Ingresos</Link>
<Divider type="vertical" />
{ingreso.id}
</div>
<div style={{width:'50%', margin: '0 auto'}} >
<Card title={"Detalle"}>
<span style={{textAlign:'center', display:'inherit', marginBottom:10}}><strong>Fecha de Registro: </strong>{moment(ingreso.created).format('LL')}</span>
<IngresoInfo
{...ingreso}
editIngreso={this.props.ingresoActions.editIngreso}
handleEditMode={this.handleEditMode}
editMode={editMode}
options={blines}
clientes={clientes}
searchClient={this.handleClient}
clientHandle={this.changeClientS}
handleClient={this.state.handleClient}
companies={companies}
searchLine={this.handleSearchLine}
lineHandle={this.handleChangeS}
linea={linea}
cuentaHandle={this.changeCuentaS}
searchCuenta={this.handleCuenta}
cuentas={cuentas}
receivableEdit={this.state.cuenta}
saveClient={this.saveClient}
stateClient={this.state.idClient}
saveBline={this.saveBl}
stateBline={this.state.idBl}
saveCuentas={this.saveCuent}
stateCuentas={this.state.idCuent}
saveCompany={this.saveCompany}
stateCompany={this.state.idCompany}
/>
</Card>
</div>
</div>
)
}
}
function mapStateToProps(state, ownProps) {
let id = ownProps.match.params.in;
let ingreso = state.ingresos.list.filter(a=>{
return id == a.id;
});
ingreso = ingreso[0];
return {
ingreso,
companies:state.empresas.list,
blines:state.blines.lineSearch,
fetched: ingreso!==undefined && state.ingresos.list!==undefined && state.blines.lineSearch !== undefined && state.clientes.clienteSearch !== undefined && state.empresas.list!==undefined,
clientes: state.clientes.clienteSearch,
cuentas:state.cuentas.cuentaSearch
}
}
function mapDispatchToProps(dispatch) {
return{
ingresoActions: bindActionCreators(ingresoActions, dispatch),
linesActions: bindActionCreators(linesActions, dispatch),
cuentasActions: bindActionCreators(cuentasActions, dispatch),
clientesActions: bindActionCreators(clientesActions, dispatch),
}
}
DetailIngresoPage = connect(mapStateToProps, mapDispatchToProps)(DetailIngresoPage);
export default DetailIngresoPage;
|
import React from 'react';
import makeStyles from '@material-ui/styles/makeStyles';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import Grid from '@material-ui/core/Grid';
import Card from 'react-bootstrap/Card';
const useStyles = makeStyles({
container: {
paddingLeft: '20px',
align:'center'
},
button: {
color: 'white',
textTransform: 'None',
alignContent: 'center'
}
});
function Landing() {
const classes = useStyles();
return (
<div className="this" style={{width:"60%"}}>
<h6> bug </h6>
<h6> bug </h6>
<h6> bug </h6>
<Grid container spacing={2} className={classes.container} align="center">
<Grid item xs={200}>
<Typography varaint="h1" style={{color: "pink", fontSize: "110px", fontFamily: "Righteous", marginTop: "50px"}}>IntAI.</Typography>
<Typography varaint="h1" style={{color: "pink", fontSize: "30px", fontFamily: "Righteous", marginTop: "-30px"}}> Your home for interview preparation!</Typography>
<Typography varaint="h2" style={{color: "pink", fontSize: "20px", marginTop: "20px"}}><strong>Welcome to an AI tool to detect and pick up potential shortcomings and help you prepare to be a better interview taker!</strong></Typography>
<Typography varaint="h3" style={{color: "pink", fontSize: "17px"}}>IntAI will work with you to improve enunciation, pace, volume and much more. Input your speech now, and let's get talking!</Typography>
<br />
<Button href="/Interview" variant="outlined" color="primary" >
<Typography variant="h4" display="inline"><b>Get Started</b></Typography>
</Button>
</Grid>
<Grid item xs={2}>
</Grid>
</Grid>
</div>
);
}
export default Landing;
|
import React, { Component } from 'react';
import { Row, FormControl, Button, Alert } from 'react-bootstrap';
export default class Spoiler extends Component {
constructor(props) {
super(props);
this.state = {
serials: [],
activeSerialId: '',
spoilerText: '',
};
}
setNewSerial(id) {
this.setState({
activeSerialId: id,
});
}
updateSpoilerText(spoilerText){
this.setState({
spoilerText,
});
}
addSpoiler() {
fetch(`/api/serials/${this.state.activeSerialId}/spoilers`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
text: this.state.spoilerText,
serial_id: Number(this.state.activeSerialId),
})
})
.then(res => {
if(res.status === 201 || res.status === 200) this.setState({
message: 'Спойлер добавлен',
}); else {
throw new Error('Ошибка сервера');
}
})
.catch(err => {
this.setState({
error: err.message,
});
});
}
componentDidMount() {
fetch('/api/serials')
.then(res => res.json())
.then(serials => {
this.setState({
serials: serials,
});
this.setNewSerial(this.serial.props.defaultValue);
});
}
render() {
return (
<div>
<h2>Добавьте спойлер к сериалу</h2>
<Row>
<FormControl
ref={(sel) => {this.serial = sel;}}
defaultValue={this.state.serials[0] ? this.state.serials[0].id : ''}
onChange={(e) => {this.setNewSerial(e.target.value);}}
componentClass="select"
>
{this.state.serials.map(serial =>
<option
key={serial.id}
value={serial.id}
>{serial.name}</option>)
}
</FormControl>
</Row>
<Row>
<FormControl
componentClass="textarea"
placeholder="Введите спойлер"
onChange={(e) => { this.updateSpoilerText(e.target.value); }}
/>
</Row>
<Row>
<Button onClick={() => { this.addSpoiler(); }}>Добавить</Button>
</Row>
<Alert className={this.state.message && !this.state.error ? '' : 'hidden'}>{this.state.message}</Alert>
<Alert bsStyle='danger' className={this.state.error ? '' : 'hidden'}>{this.state.error}</Alert>
</div>
);
}
}
|
/**
* Created by admin on 2016/12/28.
*/
var mongoose = require('mongoose');
var co = require('co');
mongoose.connect('mongodb://52.78.225.48/Dev');
// 模型
var models = require('./../../model/models');
var Vegetable = mongoose.model('Vegetable', models.vegetableSchema);
var User = mongoose.model('User', models.userSchema);
var Order = mongoose.model('Order', models.OrderSchema);
exports.getVegetable = function (req, res) {
if(!req.session.userId){
console.log('wei deng lu')
}else {
console.log('yi deng lu')
}
var query = new Parse.Query('Vegetable');
query.find().then(function (result) {
console.log(result)
}, function (error) {
console.log(error.message)
});
Vegetable.find({}).then(function (data) {
res.jsonp({code:200, message:'success', result:data});
}, function (err) {
console.log(err.message)
});
};
exports.createOrder = function (req, res) {
var userId = req.session.userId;
userId = '58632b2365f182129ce6a392';
var products = req.body.products;
var totalPrice = 0;
var totalWeight = 0;
products.forEach(function (item) {
totalWeight += item.count;
totalPrice += item.count * item.price
});
co(function* () {
var user = yield new Promise(function (resolve, reject) {
User.findOne({_id: Object(userId)}).then(function (result) {
resolve(result)
}, function (error) {
reject(error)
});
});
var order = new Order({user: user, products: products, totalPrice: totalPrice, totalWeight: totalWeight});
order.save().then(function (results) {
res.jsonp({code: 200, message: 'success', result: results})
}, function (error) {
res.jsonp({code: 102, message: 'fail'})
});
});
};
exports.getOrders = function (req, res) {
var userId = req.session.userId;
userId = '58632b2365f182129ce6a392';
co(function* () {
var orders = yield new Promise(function (resolve, reject) {
Order.find({'user._id': Object(userId)}).then(function (results) {
resolve(results)
}, function (error) {
reject(error)
})
});
res.jsonp({code: 200, message: 'success', result: orders});
});
};
exports.test = function (req, res) {
console.log(req.headers)
res.jsonp({message: 'success'})
};
|
/**
* @description: 文本组件请求接口的携带数据key
* @param {type}
* @return:
*/
import store from '@/store'
import pagesUpdate from '@/views/lego/funComponents/pages/historyDataUpdate'
import checkboxUpdate from '@/views/lego/funComponents/form/Checkbox/historyDataUpdate'
const neetUpdateComponents = {
PagesForm: pagesUpdate,
PagesDetail: pagesUpdate,
PagesList: pagesUpdate,
Checkbox: checkboxUpdate,
Select: checkboxUpdate,
Radio: checkboxUpdate,
DetailCheckbox: checkboxUpdate,
DetailSelect: checkboxUpdate,
DetailRadio: checkboxUpdate
}
export default function (modules) {
Object.keys(modules).forEach((item) => {
const data = modules[item]
const updateFunction = neetUpdateComponents[data.type]
if (updateFunction) updateFunction(data)
// 全局字段处理
if (!data.styles) {
data.styles = {}
}
// 生命周期函数更名
if (data.componentEvent) {
if (data.componentEvent.componentBeforeAjax) {
data.componentEvent.componentBeforeSend = data.componentEvent.componentBeforeAjax
delete data.componentEvent.componentBeforeAjax
}
if (data.componentEvent.componentAfterAjax) {
data.componentEvent.componentAfterSend = data.componentEvent.componentAfterAjax
delete data.componentEvent.componentAfterAjax
}
}
// TODO: 执行时序问题,单体组件对象需要获取全局组件配置
if (data.relational && Array.isArray(data.relational)) {
let renderRule = ''
const ruleEnums = {
and: '&&',
or: '||'
}
data.relational.forEach((item, index) => {
// 可能在这可能在那
const relItem = modules[item.id] || store.getters['manage/idModule'][item.id]
if (relItem) {
const { key } = relItem
let rule
if (relItem.type === 'Tabs') {
rule = `this.idModule['${item.id}'].value==${item.value}`
} else {
rule = `this.pageData.${key}==${item.value}`
}
renderRule += `${index > 0 ? ruleEnums[item.rule || 'and'] : ''}${rule}`
}
})
if (renderRule) {
data.renderRule = renderRule
}
}
})
}
|
var app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
list: '',
word: '',
message:''
},
houduanButton1: function () {
tt.login({
success (res) {
console.log('code',res);
var code = res.code;
tt.request({
//请求地址
url:"https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal",
header:{
'Content-Type': 'application/json'
},
data:{
"app_id":"cli_9e4d1ead35f6100d",
"app_secret":"0ayKYOVHc3EMOmTZGAxgMcvXuybJ5wbG"
},
method:"POST",
success:function(res){
console.log('fei',res.data.app_access_token)
let token = res.data.app_access_token;
tt.request({
//请求地址
url:"https://open.feishu.cn/open-apis/mina/v2/tokenLoginValidate",
header:{
'Content-Type': 'application/json',
'Authorization':'Bearer <app_access_token>'
},
data:{
"token":token,
"code":code
},
method:"POST",
success:function(res){
console.log('c2s',res)
}
})
}
})
}
})
},
//获取输入框的内容
houduanTab_input: function (e) {
this.setData({
word: e.detail.value
})
},
// houduanButton2的网络请求
houduanButton2: function () {
var that = this;
tt.request({
url: 'http://localhost:8080/getWord',
data:{
word: that.data.word
},
method: 'GET',
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
console.log(res.data.message)//打印到控制台
var message = res.data.message;
if (message == null) {
var toastText = '数据获取失败';
tt.showToast({
title: toastText,
icon: '',
duration: 2000
});
} else {
that.setData({
message: message
})
}
tt.showModal({
title: '详细内容',
content: message,
confirmText:'确定',
showCancel:false,
})
},
fail:function(res){
console.log("get message",res.errMsg);
tt.showModal({
title: '查询失败',
showCancel:false,
content: '',
confirmText:'确定',
})
}
})
}
})
|
import React from 'react'
class SearchField extends React.Component {
state = {
searchValue: ''
}
changeValue = (e) => {
this.setState({ searchValue: e.target.value })
}
onFormSubmit = async(e) => {
e.preventDefault()
if(this.state.searchValue===''){
alert('Invalid Input')
}
else{
this.props.onSubmit(this.state.searchValue)
}
}
render() {
return (
<div className = 'form'>
<label> Search Your Recipe </label>
<form onSubmit={this.onFormSubmit} autoComplete='off'>
<input type = 'text' id = 'a'
onChange = { this.changeValue }
value = { this.state.searchValue }
placeholder="Enter name of food..."
/>
< button> Search </button>
</form>
</div>
)
};
}
export default SearchField
|
const Util = require('./util.js');
const Bullet = require('./bullet.js');
function Ship(params) {
const RADIUS = 8; // default values for ship
const COLOR = 'red';
params.radius = params.radius || RADIUS;
params.color = params.color || COLOR;
params.vel = [0,0];
MovingObject.call(this,params);
}
Util.inherits(Ship,MovingObject);
Ship.prototype.relocate = function () {
this.pos = this.game.randomPosition();
this.vel = [0,0];
};
Ship.prototype.power = function (del_v) {
this.vel[0] += del_v[0];
this.vel[1] += del_v[1];
console.log('vel = ' + this.vel)
};
Ship.prototype.fireBullet = function () {
let v = [this.vel[0]*2,this.vel[1]*2];
let bullet = new Bullet({pos: this.pos, vel: v});
this.game.addBullet(bullet);
};
module.exports = Ship;
|
export * from './authActions';
export * from './productActions';
export * from './attrActions';
export * from './cateActions';
export * from './orderActions';
export * from './customerActions';
export * from './orderListActions';
|
import SecondarySidebar from './SecondarySidebar';
export default SecondarySidebar;
|
const {ipcRenderer} = require('electron')
let arg;
// handle request
ipcRenderer.on('daemons-permission-request', (event, arg) => {
/*
arg.source - Requesting app
arg.endpoint - App being affected
arg.message - Request message
arg.help - Help message
arg.return - Return IPC channel
*/
escape(arg);
$("#loading").fadeOut();
$("#content").fadeIn();
$("#header").html("The app <b>"+arg.source+"</b> wants to "+arg.message+".");
$("#specific").html(arg.help+"<br />Allow or deny this request below.");
})
exports.denyElevate = function() {
$("#specific").html("This request has been <b>denied</b>.<br />You will be returned back to your original app shortly.");
$("div.right").fadeOut();
ipcRenderer.send(arg.return, {"source": arg.source, "endpoint": arg.endpoint, "message": arg.message, "help": arg.help, "state": false, "passthrough": arg.passthrough});
}
exports.allowElevate = function() {
$("#specific").html("This request has been <b>allowed</b>.<br />You will be returned back to your original app shortly.");
$("div.right").fadeOut();
ipcRenderer.send(arg.return, {"source": arg.source, "endpoint": arg.endpoint, "message": arg.message, "help": arg.help, "state": true, "passthrough": arg.passthrough});
}
function escape(larg){
arg = larg;
}
|
dyn.register({
name: 'e',
onLoad(err, loadDeps, onBackgroundLoad) {
console.log(`e load with deps: ${Object.keys(loadDeps)}`);
return {};
}
});
|
import React from "react";
import CheckBox from "./Ckeckbox";
function App() {
const allGroups = {
display: "flex",
justifyContent: "space-around"
};
const column = {
display: "flex",
flexDirection: "column"
};
const line = {
display: "flex"
};
return (
<section className="App" style={allGroups}>
<div className="checkboxes">
<CheckBox indexId={1} />
</div>
<div style={column}>
<CheckBox indexId={2} disabled checked />
<CheckBox indexId={3} />
<CheckBox indexId={4} disabled />
</div>
<div className="checkboxes--line" style={line}>
<CheckBox indexId={5} checked />
<CheckBox indexId={6} disabled />
<CheckBox indexId={7} />
</div>
</section>
);
}
export default App;
|
import React from 'react';
import './RegisterForm.scss';
import { MdArrowForward } from 'react-icons/md';
import { IconContext } from 'react-icons';
import { createBrowserHistory } from 'history';
import { bake_cookie } from 'sfcookies';
const RegisterForm = ({ user }) => {
console.log(user);
const registerSubmit = e => {
e.preventDefault();
const formData = new FormData(document.getElementById('form_register'));
console.log(document.getElementById('form_register'));
console.log(formData.get('email'));
fetch('http://localhost:9090/api/auth/register', {
method: 'post',
body: formData
}).then(res => {
console.log(res);
res.json().then(data => {
localStorage.setItem('webber_user', JSON.stringify(data.userVo));
bake_cookie('access_token', data.token);
window.location.replace('/');
});
});
};
return (
<div className="RegisterForm">
<form
id="form_register"
action="http://localhost:9090/api/auth/register"
method="POST"
onSubmit={registerSubmit}
>
<div className="RegisterForm_header">
<div className="RegisterForm_header_title">
webber
<span> / 회원가입</span>
</div>
<div className="RegisterForm_header_info">
기본 회원정보 등록
</div>
</div>
<div className="RegisterForm_body">
<div className="RegisterForm_body_email register_input_form">
<div>
이메일
<span>*</span>
</div>
<input
type="text"
name="email"
value={user && user.email}
readOnly
/>
</div>
<div className="RegisterForm_body_nickname register_input_form">
<div>
아이디
<span>*</span>
</div>
<input
name="nickname"
type="text"
placeholder="아이디를 입력하세요."
/>
</div>
<div className="RegisterForm_body_introduce register_input_form">
<div>한 줄 소개</div>
<input
name="intro"
type="text"
placeholder="당신을 표현해 보세요."
/>
</div>
<input type="hidden" name="type" value={user && user.type} />
<input type="hidden" name="id" value={user && user.id} />
<input
type="hidden"
name="accessToken"
value={user && user.accessToken}
/>
<input
type="hidden"
name="thumbnail"
value={user && user.thumbnail}
/>
</div>
<div className="RegisterForm_footer">
<label htmlFor="register_submit">
<div className="RegisterForm_footer_btn_submit">
다음
<IconContext.Provider
value={{
size: '20',
color: 'white'
}}
>
<div
style={{
marginLeft: '0.3rem',
paddingTop: '0.2rem'
}}
>
<MdArrowForward />
</div>
</IconContext.Provider>
</div>
</label>
<input id="register_submit" type="submit" value="다음" />
</div>
</form>
</div>
);
};
export default RegisterForm;
|
/**
* 自定义菜单
*/
const { Menu } = require('electron');
const template = [{
label: '文件',
submenu: [
{
label: '新建文件',
accelerator: 'CmdOrCtrl+N',
click: () => {
console.log('新建文件')
}
},
{
label: '新建窗口'
}
]
},
{
label: '编辑',
submenu: [
{
label: 'reload',
accelerator: 'CmdOrCtrl+R',
role: 'reload'
},
{
label: '复制',
accelerator: 'CmdOrCtrl+C',
role: 'copy'
},
{
label: '粘贴',
accelerator: 'CmdOrCtrl+V',
role: 'paste'
}
]
}
]
const m = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(m)
|
import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import pollsAPI from '../../api';
import { setError, fetchQuestions } from '../../redux/actions';
import { Alert } from 'antd';
import GoBack from '../../components/molecules/GoBack';
import Choices from '../../components/molecules/Choices';
import './style.scss';
const QuestionDetails = ({
match,
questions,
currentQuestion,
fetchQuestions
}) => {
const [choices, setChoices] = useState(currentQuestion.choices);
useEffect(() => {
fetchQuestions();
}, [fetchQuestions]);
const questionID = match.params.id;
const question = questions.find(question => question.url === `/questions/${questionID}`);
const handleVote = async choiceURL => {
try {
await pollsAPI.post(choiceURL);
const updatedChoices = [...choices]
const index = updatedChoices.findIndex(choice => choice.url === choiceURL);
updatedChoices[index].votes++
setChoices(updatedChoices);
} catch (error) {
setError(error);
}
}
return (
<div className="container">
<h1>Q: {currentQuestion.question || question['question']}</h1>
<GoBack />
{
!question
?
<Alert message="Invalid ID" type="error" />
:
<Choices choices={choices || question.choices} onClickButton={handleVote} />
}
</div>
);
}
const mapStateToProps = state => ({
questions: state.questions,
currentQuestion: state.question,
error: state.error
});
const mapDispatchToProps = dispatch => ({
fetchQuestions: () => dispatch(fetchQuestions()),
setError: error => dispatch(setError(error))
});
export default connect(mapStateToProps, mapDispatchToProps)(QuestionDetails);
|
/* eslint-env jest */
const { setupServer, setupModels, stopServer } = require('../test/integration-setup.js')()
describe('Test create', () => {
const STATUS_OK = 200
const STATUS_NOT_FOUND = 404
const STATUS_BAD_REQUEST = 400
let server
let sequelize
beforeEach(async () => {
const { server: _server, sequelize: _sequelize } = await setupServer()
server = _server
sequelize = _sequelize
await setupModels(sequelize)
})
afterEach(() => stopServer(server))
test('where /player {name: "Chard"}', async () => {
const { models: { Player } } = sequelize
const url = '/player'
const method = 'POST'
const payload = { name: 'Chard' }
const notPresentPlayer = await Player.findOne({ where: payload })
expect(notPresentPlayer).toBeNull()
const { result, statusCode } = await server.inject({ url, method, payload })
expect(statusCode).toBe(STATUS_OK)
expect(result.id).toBeTruthy()
expect(result.name).toBe(payload.name)
})
test('not found /notamodel {name: "Chard"}', async () => {
const url = '/notamodel'
const method = 'POST'
const payload = { name: 'Chard' }
const { statusCode } = await server.inject({ url, method, payload })
expect(statusCode).toBe(STATUS_NOT_FOUND)
})
test('no payload /player/1', async () => {
const url = '/player'
const method = 'POST'
const response = await server.inject({ url, method })
const { statusCode } = response
expect(statusCode).toBe(STATUS_BAD_REQUEST)
})
})
|
import React, { useEffect, useState, useContext } from 'react';
import { init } from './Socket';
import { GameContext } from '../../contexts/GameContext';
import ACTIONS from '../../types/gameTypes';
import WaitRoomScreen from './components/WaitRoomScreen';
import CreateScreen from './components/CreateScreen';
import GameScreen from './components/GameScreen';
import { userData } from '../../store/store';
import { useAtom } from 'jotai';
export const Play = () => {
const [socketHandler, setSocketHandler] = useState(null);
const { gameState, dispatch } = useContext(GameContext);
const [user, setUser] = useAtom(userData);
useEffect(() => {
const socketClient = init();
setSocketHandler(socketClient);
return () => {
socketClient.emit('LEFT_ROOM');
socketClient.disconnect();
};
}, []);
useEffect(() => {
if (socketHandler !== null) {
socketHandler.on('connection', () => {
// console.log('sent connection request');
});
/**
* Game Listeners
*/
socketHandler.on('GAME_DATA', (data) => {
dispatch({ type: ACTIONS.SET_GAME_DATA, payload: data });
});
socketHandler.on('TURN', (data) => {
dispatch({ type: ACTIONS.SET_TURN, payload: data });
});
socketHandler.on('INIT', (data) => {
dispatch({ type: ACTIONS.SET_PLAYER_NUMBER, payload: data });
});
socketHandler.on('GAME_CODE', (data) => {
dispatch({ type: ACTIONS.SET_ROOM, payload: data });
});
socketHandler.on('IS_WINNER', (data) => {
console.log('winner check = ', data);
dispatch({ type: ACTIONS.SET_WINNER, payload: data });
});
/**
* Error Listeners
*/
socketHandler.on('ROOM_FULL', (data) => {
console.log('errors', data);
dispatch({ type: ACTIONS.SET_ERRORS, payload: data.errorMsg });
});
socketHandler.on('UNKNOWN_CODE', (data) => {
dispatch({ type: ACTIONS.SET_ERRORS, payload: data.errorMsg });
});
socketHandler.on('UNKNOWN_ERROR', (data) => {
dispatch({ type: ACTIONS.SET_ERRORS, payload: data.errorMsg });
});
socketHandler.on('connect_error', (data) => {
console.log('data from not authorized', data.data);
if (data.data.content) {
dispatch({ type: ACTIONS.SET_ERRORS, payload: data.data.content });
}
});
}
}, [socketHandler]);
useEffect(() => {
setTimeout(() => {
dispatch({ type: ACTIONS.CLEAR_ERRORS });
}, 5000);
}, [gameState]);
if (!user) {
return <></>;
}
return (
<div className="text-gray-700 mt-8 mx-auto max-w-sm flex flex-col">
<span className="font-bold text-4xl text-center ">Play</span>
{gameState.errors.map((item, index) => {
return (
<div
key={index}
className="mt-4 max-w-xs mx-auto bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative"
role="alert"
>
<span className="block sm:inline">{item}</span>
</div>
);
})}
{gameState.playerNumber === 0 && (
<CreateScreen socketHandler={socketHandler} />
)}
{gameState.playerNumber === 1 && gameState.gameData.length === 0 && (
<WaitRoomScreen />
)}
{gameState.winner !== 0 && (
<div className="mt-4 flex flex-col content-center justify-center text-center"></div>
)}
{gameState.gameData.length !== 0 && (
<GameScreen socketHandler={socketHandler} />
)}
</div>
);
};
|
export const DB_CONFIG = {
apiKey: "AIzaSyCzVjOTQbLq920IbI4RRCurWvzHXKFMeos",
authDomain: "todolist-1dbbf.firebaseapp.com",
databaseURL: "https://todolist-1dbbf.firebaseio.com",
projectId: "todolist-1dbbf",
storageBucket: "todolist-1dbbf.appspot.com",
messagingSenderId: "57666522301"
};
|
export { default } from './Drum';
|
angular.module('AdAcc').controller('EditAccBlncController', function($scope, $routeParams, $location, AccBlncResource ) {
var self = this;
$scope.disabled = false;
$scope.$location = $location;
$scope.get = function() {
var successCallback = function(data){
self.original = data;
$scope.accBlnc = new AccBlncResource(self.original);
};
var errorCallback = function() {
$location.path("/AccBlncs");
};
AccBlncResource.get({AccBlncId:$routeParams.AccBlncId}, successCallback, errorCallback);
};
$scope.isClean = function() {
return angular.equals(self.original, $scope.accBlnc);
};
$scope.save = function() {
var successCallback = function(){
$scope.get();
$scope.displayError = false;
};
var errorCallback = function() {
$scope.displayError=true;
};
$scope.accBlnc.$update(successCallback, errorCallback);
};
$scope.cancel = function() {
$location.path("/AccBlncs");
};
$scope.remove = function() {
var successCallback = function() {
$location.path("/AccBlncs");
$scope.displayError = false;
};
var errorCallback = function() {
$scope.displayError=true;
};
$scope.accBlnc.$remove(successCallback, errorCallback);
};
$scope.pstgDirList = [
"DEBIT",
"CREDIT"
];
$scope.get();
});
|
var n = 100;
var song = '';
while ( n >= 0 ) {
if ( n !== 0 ) {
song = song + '' + n + "bottles of beer on the wall! chug, chug, chug";
} else {
song += "no bottles of beer! stumble, btumble, stumble...";
}
n--;
}
document.querySelector('#lyrics-one').textContent = song;
|
import React from "react";
import "../CSS/input.css";
const Input = (props) => {
return (
<div className = "inputBox">
<input className = "input" placeholder="Search...
" onChange={props.handleChange} onKeyDown={props.handleKeyPress} value={props.userInput}></input>
</div>
);
};
export default Input;
|
Vue.component("my-page", {
watch: {
pageIndex: function () {
return this.$emit("change", this.pageIndex);
}
},
model: {
prop: "pageIndex",
event: "change"
},
computed: {
count: function () {
return this.total % this.size == 0 ? parseInt(this.total / this.size) : parseInt((this.total / this.size) + 1);
},//总页数
ToggleCount: function () {
return this.count % this.displayElementCountOfA == 0 ? parseInt(this.count / this.displayElementCountOfA) : parseInt((this.count / this.displayElementCountOfA) + 1);
},//如果当前页为最后一个标签,就进行切换一次,对分页的数据进行更新一次
currentFirstNumber: function () {
return this.currentToggleCount * this.displayElementCountOfA;
},//当前第一个分页标签中第一个字母
currentLastNumber: function () {
return this.currentToggleCount < this.ToggleCount - 1 ? (this.currentToggleCount + 1) * this.displayElementCountOfA : this.count;
}//当前分页标签中最后一个字母
},
props: {
"size": { type: Number, default: 0 },//大小
"total": { type: Number, default: 0 },//总条数
"resource": { type: Array, default: [] },//数据
"ishaveopration": { type: Boolean, default: false },//是否出现操作符
"ishaveadd": { type: Boolean, default: false },//是否出现添加按钮
"ishavedelete": { type: Boolean, default: false },//是否出现删除按钮
"ishaveupdate": { type: Boolean, default: false },//是否出现修改按钮
"ishavefindone": { type: Boolean, default: false },//是否出现单值查询按钮
"addurl": { type: String, default: "#" },//添加的路径
"deleteurl": { type: String, default: "#" },//删除的路径
"updateurl": { type: String, default: "#" },//修改的路劲
"findurl": { type: String, default: "#" },//单值查询的路劲
"paremeter": { type: String, default: "#" }//增删改查的参数(id)
//"currentpagename": { type: String,default:"#" } //当前页面的相对路劲(Action或页面的地址)
},
data: function () {
return {
pageIndex: 1,
displayElementCountOfA: 5,//显示分页中超链接标签的数量
currentToggleCount: 0,//当前切换的次数
isDisplayData: true, //是否显示数据
isExecuteNextCode: true //是否执行下一行代码
}
},
mounted: function () {
if (this.resource.isHaveData) {
if (this.ishaveopration && (this.ishavedelete || this.ishavefindone || this.ishaveupdate)) {
if (this.paremeter == "#" || this.paremeter == "" || this.paremeter == null) {
this.isDisplayData = false;
throw "如需通过该组件生成表格,并且需要进行操作,请为当前组件添加该表的主键列名或其他列名";
}
}
}
},
methods: {
goPage: function (x, num) {//通过传入的数字来判断点击的下拉框还是分页中的标签
this.pageIndex = x;
if (num != 0) {
this.currentToggleCount = this.pageIndex % this.displayElementCountOfA == 0 ? parseInt(this.pageIndex / this.displayElementCountOfA) : parseInt((this.pageIndex / this.displayElementCountOfA) + 1);
this.currentToggleCount--;//因为默认为0,如果为1则可省略此步
}
},
toggleIndex: function (num) { //切换下标 0则为上一页 1则为下一页
if (num == 0) {
if (this.pageIndex == (this.currentFirstNumber + 1) && this.currentToggleCount > 0) {//如果当前的页面等于第一个数字,点击上一页就说明需要切换了,同时切换的次数要大于0
this.currentToggleCount--;
this.currentLastNumber = (this.currentToggleCount - 1) * this.displayElementCountOfA; //更新数据,更新分页中标签中末尾的数字
}
this.pageIndex = this.pageIndex > 1 ? this.pageIndex - 1 : 1;
}
else if (num == 1) {
if (this.pageIndex != this.count) { //因为切换次数默认为0,如果没有此步骤,最后没有数据的时候将会多切换一次
if (this.pageIndex == this.currentLastNumber && this.currentToggleCount < this.ToggleCount) {//如果当前的页面等于最后的数字,点击下一页就说明需要切换了,同时当前切换的次数小于总共能切换的次数
this.currentToggleCount++;
this.currentLastNumber = (this.currentToggleCount + 1) * this.displayElementCountOfA; //更新数据,更新分页中标签中末尾的数字
}
this.pageIndex = this.pageIndex < this.count ? this.pageIndex + 1 : this.count;
}
}
},
ModifyData: function (id, url, callback) {
if (id < 0 || id == "" || id == null) {
throw "无法得到id参数值";
this.isExecuteNextCode = false;
}
if (url == "#" || url == null || url == "") {
throw "url缺少参数,请进行赋相应的值";
this.isExecuteNextCode = false;
}
if (this.isExecuteNextCode) {
this.$http.delete(url + id).then(d => { callback != null ? callback(d.data) : null; });
}
},
del: function (id, index) {
var obj = this;
this.ModifyData(id, this.deleteurl, function (d) {
if (d > 0) {
obj.resource.ls.splice(index, 1);
}
})
},
edit: function (id) {
location.href = this.updateurl + id;
},
find: function (id) {
location.href = this.findurl + id;
}
},
template: '<ul class="pagination">\
<li v-if="resource!=null && isDisplayData">\
<table border="1" class="table table-bordered table-striped">\
<thead >\
<tr>\
<td v-for= "(objhead,indexhead) in resource.head" > {{ objhead.title }}</td > <td v-if="ishaveopration">Operation</td>\
</tr >\
</thead >\
<tbody>\
<tr v-for="(objdata,indexdata) in resource.ls">\
<td v-if="objhead2.formatter==null" v-for= "(objhead2,indexhead2) in resource.head" > {{objdata[objhead2.key]}}</td >\
<td v-else>{{objhead2.formatter(objdata[objhead2.key])}}</td> \
<td v-if= "ishaveopration" >\
<a :href="addurl" v-if="ishaveadd" class="btn btn-default btn-xs" >Add</a >\
<a href="#" @click="del(objdata[paremeter],indexdata)" v-if="ishavedelete" class="btn btn-danger btn-xs" >Delete</a >\
<a href="#" @click="edit(objdata[paremeter])" v-if="ishaveupdate" class="btn btn-primary btn-xs" >Modify</a >\
<a href="#" @click="find(objdata[paremeter])"v-if="ishavefindone" class="btn btn-success btn-xs" >Find</a >\
</td >\
</tr >\
</tbody >\
</table>\
</li ><br v-if="resource==null"/>\
<li v-if="isDisplayData">\
<a href = "#" aria-label="Previous" @click="toggleIndex(0)">\
<span aria-hidden="true">«</span>\
</a>\
</li >\
<li v-for="(x,index) in currentLastNumber" :class="{active:x==pageIndex}" v-if="isDisplayData"><a href="#" @click="goPage(x,0)" v-if="x>currentFirstNumber && x<=currentLastNumber">{{x}}</a></li>\
<li v-if="isDisplayData">\
<a href="#" @click="toggleIndex(1)" aria-label="Next">\
<span aria-hidden="true">»</span>\
</a>\
<a href="#" aria-label="Next">\
<span aria-hidden="true">第{{pageIndex}}页/共{{count}}页 | 共{{total}}条</span>\
</a>\
</li>\
<li v-if="isDisplayData">\
<select @change="goPage($event.target.value,1)" v-model="pageIndex">\
<option v-for="x in count" :value="x">{{x}}</option>\
</select>\
</li>\
</ul >'
})
|
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
const cors = require('cors')({origin: true});
admin.initializeApp();
/**
* Here we're using Gmail to send
*/
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'alesalgueroq1223@gmail.com',
pass: 'MariAle1223'
}
});
exports.sendMail = functions.https.onRequest((req, res) => {
cors(req, res, () => {
// getting dest email by query string
const email = req.query.email;
const name = req.query.name;
const phone = req.query.phone;
const message = req.query.message;
res.set('Access-Control-Allow-Origin', '*');
const mailOptions = {
from: 'MaquiPrintWeb', // Something like: Jane Doe <janedoe@gmail.com>
to: 'alejandrosalgueroq@hotmail.com',
subject: 'Te está intentando contactar un cliente', // email subject
html: `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<!--[if gte mso 9]><xml><o:OfficeDocumentSettings><o:AllowPNG/><o:PixelsPerInch>96</o:PixelsPerInch></o:OfficeDocumentSettings></xml><![endif]-->
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<meta content="width=device-width" name="viewport"/>
<!--[if !mso]><!-->
<meta content="IE=edge" http-equiv="X-UA-Compatible"/>
<!--<![endif]-->
<title></title>
<!--[if !mso]><!-->
<!--<![endif]-->
<style type="text/css">
body {
margin: 0;
padding: 0;
}
table,
td,
tr {
vertical-align: top;
border-collapse: collapse;
}
* {
line-height: inherit;
}
a[x-apple-data-detectors=true] {
color: inherit !important;
text-decoration: none !important;
}
</style>
<style id="media-query" type="text/css">
@media (max-width: 520px) {
.block-grid,
.col {
min-width: 320px !important;
max-width: 100% !important;
display: block !important;
}
.block-grid {
width: 100% !important;
}
.col {
width: 100% !important;
}
.col>div {
margin: 0 auto;
}
img.fullwidth,
img.fullwidthOnMobile {
max-width: 100% !important;
}
.no-stack .col {
min-width: 0 !important;
display: table-cell !important;
}
.no-stack.two-up .col {
width: 50% !important;
}
.no-stack .col.num4 {
width: 33% !important;
}
.no-stack .col.num8 {
width: 66% !important;
}
.no-stack .col.num4 {
width: 33% !important;
}
.no-stack .col.num3 {
width: 25% !important;
}
.no-stack .col.num6 {
width: 50% !important;
}
.no-stack .col.num9 {
width: 75% !important;
}
.video-block {
max-width: none !important;
}
.mobile_hide {
min-height: 0px;
max-height: 0px;
max-width: 0px;
display: none;
overflow: hidden;
font-size: 0px;
}
.desktop_hide {
display: block !important;
max-height: none !important;
}
}
</style>
</head>
<body class="clean-body" style="margin: 0; padding: 0; -webkit-text-size-adjust: 100%; background-color: #FFFFFF;">
<!--[if IE]><div class="ie-browser"><![endif]-->
<table bgcolor="#FFFFFF" cellpadding="0" cellspacing="0" class="nl-container" role="presentation" style="table-layout: fixed; vertical-align: top; min-width: 320px; Margin: 0 auto; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; background-color: #FFFFFF; width: 100%;" valign="top" width="100%">
<tbody>
<tr style="vertical-align: top;" valign="top">
<td style="word-break: break-word; vertical-align: top;" valign="top">
<!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td align="center" style="background-color:#FFFFFF"><![endif]-->
<div style="background-color:transparent;">
<div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 500px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;">
<div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;">
<!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:500px"><tr class="layout-full-width" style="background-color:transparent"><![endif]-->
<!--[if (mso)|(IE)]><td align="center" width="500" style="background-color:transparent;width:500px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:5px;"><![endif]-->
<div class="col num12" style="min-width: 320px; max-width: 500px; display: table-cell; vertical-align: top; width: 500px;">
<div style="width:100% !important;">
<!--[if (!mso)&(!IE)]><!-->
<div style="border-top:0px solid transparent; border-left:0px solid transparent; border-bottom:0px solid transparent; border-right:0px solid transparent; padding-top:5px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;">
<!--<![endif]-->
<div></div>
<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; font-family: Arial, sans-serif"><![endif]-->
<div style="color:#555555;font-family:Arial, 'Helvetica Neue', Helvetica, sans-serif;line-height:120%;padding-top:10px;padding-right:10px;padding-bottom:10px;padding-left:10px;">
<p style="font-size: 12px; line-height: 15px; color: #555555; font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; margin: 0;"><span style="font-size: 13px; mso-ansi-font-size: 14px;"><strong>Información de posible cliente.</strong></span></p>
</div>
<!--[if mso]></td></tr></table><![endif]-->
<!--[if (!mso)&(!IE)]><!-->
</div>
<!--<![endif]-->
</div>
</div>
<!--[if (mso)|(IE)]></td></tr></table><![endif]-->
<!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]-->
</div>
</div>
</div>
<div style="background-color:transparent;">
<div class="block-grid mixed-two-up" style="Margin: 0 auto; min-width: 320px; max-width: 500px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;">
<div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;">
<!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:500px"><tr class="layout-full-width" style="background-color:transparent"><![endif]-->
<!--[if (mso)|(IE)]><td align="center" width="125" style="background-color:transparent;width:125px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:5px;"><![endif]-->
<div class="col num3" style="display: table-cell; vertical-align: top; max-width: 320px; min-width: 123px; width: 125px;">
<div style="width:100% !important;">
<!--[if (!mso)&(!IE)]><!-->
<div style="border-top:0px solid transparent; border-left:0px solid transparent; border-bottom:0px solid transparent; border-right:0px solid transparent; padding-top:5px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;">
<!--<![endif]-->
<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; font-family: Arial, sans-serif"><![endif]-->
<div style="color:#555555;font-family:Arial, 'Helvetica Neue', Helvetica, sans-serif;line-height:120%;padding-top:10px;padding-right:10px;padding-bottom:10px;padding-left:10px;">
<div style="font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; font-size: 12px; line-height: 14px; color: #555555;">
<p style="font-size: 14px; line-height: 16px; margin: 0;">Nombre:</p>
</div>
</div>
<!--[if mso]></td></tr></table><![endif]-->
<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; font-family: Arial, sans-serif"><![endif]-->
<div style="color:#555555;font-family:Arial, 'Helvetica Neue', Helvetica, sans-serif;line-height:120%;padding-top:10px;padding-right:10px;padding-bottom:10px;padding-left:10px;">
<div style="font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; font-size: 12px; line-height: 14px; color: #555555;">
<p style="font-size: 14px; line-height: 16px; margin: 0;">Correo:</p>
</div>
</div>
<!--[if mso]></td></tr></table><![endif]-->
<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; font-family: Arial, sans-serif"><![endif]-->
<div style="color:#555555;font-family:Arial, 'Helvetica Neue', Helvetica, sans-serif;line-height:120%;padding-top:10px;padding-right:10px;padding-bottom:10px;padding-left:10px;">
<div style="font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; font-size: 12px; line-height: 14px; color: #555555;">
<p style="font-size: 14px; line-height: 16px; margin: 0;">Teléfono:</p>
</div>
</div>
<!--[if mso]></td></tr></table><![endif]-->
<!--[if (!mso)&(!IE)]><!-->
</div>
<!--<![endif]-->
</div>
</div>
<!--[if (mso)|(IE)]></td></tr></table><![endif]-->
<!--[if (mso)|(IE)]></td><td align="center" width="375" style="background-color:transparent;width:375px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:5px;"><![endif]-->
<div class="col num9" style="display: table-cell; vertical-align: top; min-width: 320px; max-width: 369px; width: 375px;">
<div style="width:100% !important;">
<!--[if (!mso)&(!IE)]><!-->
<div style="border-top:0px solid transparent; border-left:0px solid transparent; border-bottom:0px solid transparent; border-right:0px solid transparent; padding-top:5px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;">
<!--<![endif]-->
<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; font-family: Arial, sans-serif"><![endif]-->
<div style="color:#555555;font-family:Arial, 'Helvetica Neue', Helvetica, sans-serif;line-height:120%;padding-top:10px;padding-right:10px;padding-bottom:10px;padding-left:10px;">
<div style="font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; font-size: 12px; line-height: 14px; color: #555555;">
<p style="font-size: 14px; line-height: 16px; margin: 0;">${name}</p>
</div>
</div>
<!--[if mso]></td></tr></table><![endif]-->
<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; font-family: Arial, sans-serif"><![endif]-->
<div style="color:#555555;font-family:Arial, 'Helvetica Neue', Helvetica, sans-serif;line-height:120%;padding-top:10px;padding-right:10px;padding-bottom:10px;padding-left:10px;">
<div style="font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; font-size: 12px; line-height: 14px; color: #555555;">
<p style="font-size: 14px; line-height: 16px; margin: 0;">${email}</p>
</div>
</div>
<!--[if mso]></td></tr></table><![endif]-->
<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; font-family: Arial, sans-serif"><![endif]-->
<div style="color:#555555;font-family:Arial, 'Helvetica Neue', Helvetica, sans-serif;line-height:120%;padding-top:10px;padding-right:10px;padding-bottom:10px;padding-left:10px;">
<div style="font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; font-size: 12px; line-height: 14px; color: #555555;">
<p style="font-size: 14px; line-height: 16px; margin: 0;">${phone}</p>
</div>
</div>
<!--[if mso]></td></tr></table><![endif]-->
<!--[if (!mso)&(!IE)]><!-->
</div>
<!--<![endif]-->
</div>
</div>
<!--[if (mso)|(IE)]></td></tr></table><![endif]-->
<!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]-->
</div>
</div>
</div>
<div style="background-color:transparent;">
<div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 500px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;">
<div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;">
<!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:500px"><tr class="layout-full-width" style="background-color:transparent"><![endif]-->
<!--[if (mso)|(IE)]><td align="center" width="500" style="background-color:transparent;width:500px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:5px;"><![endif]-->
<div class="col num12" style="min-width: 320px; max-width: 500px; display: table-cell; vertical-align: top; width: 500px;">
<div style="width:100% !important;">
<!--[if (!mso)&(!IE)]><!-->
<div style="border-top:0px solid transparent; border-left:0px solid transparent; border-bottom:0px solid transparent; border-right:0px solid transparent; padding-top:5px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;">
<!--<![endif]-->
<table border="0" cellpadding="0" cellspacing="0" class="divider" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top" width="100%">
<tbody>
<tr style="vertical-align: top;" valign="top">
<td class="divider_inner" style="word-break: break-word; vertical-align: top; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" class="divider_content" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; border-top: 1px solid #BBBBBB; width: 100%;" valign="top" width="100%">
<tbody>
<tr style="vertical-align: top;" valign="top">
<td style="word-break: break-word; vertical-align: top; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top"><span></span></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; font-family: Arial, sans-serif"><![endif]-->
<div style="color:#555555;font-family:Arial, 'Helvetica Neue', Helvetica, sans-serif;line-height:120%;padding-top:10px;padding-right:10px;padding-bottom:10px;padding-left:10px;">
<div style="font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; font-size: 12px; line-height: 14px; color: #555555;">
<p style="font-size: 14px; line-height: 16px; margin: 0;">Comentarios:</p>
</div>
</div>
<!--[if mso]></td></tr></table><![endif]-->
<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; font-family: Arial, sans-serif"><![endif]-->
<div style="color:#555555;font-family:Arial, 'Helvetica Neue', Helvetica, sans-serif;line-height:120%;padding-top:10px;padding-right:10px;padding-bottom:10px;padding-left:10px;">
<div style="font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; font-size: 12px; line-height: 14px; color: #555555;">
<p style="font-size: 14px; line-height: 16px; text-align: justify; margin: 0;"><em>${message}</em></p>
</div>
</div>
<!--[if mso]></td></tr></table><![endif]-->
<!--[if (!mso)&(!IE)]><!-->
</div>
<!--<![endif]-->
</div>
</div>
<!--[if (mso)|(IE)]></td></tr></table><![endif]-->
<!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]-->
</div>
</div>
</div>
<!--[if (mso)|(IE)]></td></tr></table><![endif]-->
</td>
</tr>
</tbody>
</table>
<!--[if (IE)]></div><![endif]-->
</body>
</html>` // email content in HTML
};
// returning result
return transporter.sendMail(mailOptions, (erro, info) => {
if(erro){
return res.send(erro.toString());
}
return res.send('Sended');
});
});
});
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
|
/**
* Created by f.putra on 2019-04-09.
*/
import React from 'react';
import {Dimensions, Text, TouchableOpacity, View} from 'react-native';
import {Body, Container, Content, Header, Icon, Left, Right, Tab, Tabs} from 'native-base'
import MultiSwitch from './../../components/MultiSwitch';
import styles from '../../utils/Style'
const {width, height} = Dimensions.get('window')
class Home extends React.Component {
static navigationOptions = {
tabBarIcon: ({tintColor}) => (
<Icon name={'logo-usd'}/>
),
};
constructor(props) {
super(props)
this.state = {
active: false,
selected: undefined,
data: [
{
title: "ABC",
price: 12000
}
],
index: 0,
routes: 'Lead In',
};
}
async onSave() {
}
onValueChange(value) {
this.setState({
selected: value
});
}
render() {
const {routes} = this.state
return (
<Container style={styles.container}>
<Header style={styles.subHeader}>
<Left>
<TouchableOpacity onPress={() => this.props.navigation.goBack()} style={{left: 10}}>
<Icon name="arrow-back" style={[styles.xxlarge, {color: '#212121'}]}/>
</TouchableOpacity>
</Left>
<Body>
</Body>
<Right>
<TouchableOpacity onPress={this.onSave} style={{right: 10}}>
<Icon name="create" style={[styles.xxlarge, {color: '#212121'}]}/>
</TouchableOpacity>
</Right>
</Header>
<Content>
<View style={{flex: 1, backgroundColor: '#f5f5f5'}}>
<View style={{padding: 15}}>
<Text>Name Deal</Text>
</View>
<View style={{flex: 1, flexDirection: 'row', left: 50}}>
<Icon name="arrow-back" style={[styles.xxlarge, {color: '#212121'}]}/>
<Text style={{left: 15}}>Name Organisation</Text>
</View>
<MultiSwitch
disableSwitch={false}
currentStatus={'third'}
disableScroll={value => {
console.log('scrollEnabled', value);
// this.scrollView.setNativeProps({
// scrollEnabled: value
// });
}}
isParentScrollEnabled={false}
onStatusChanged={text => {
console.log('Change Status ', text);
}}/>
<View style={{flex: 0.1, padding: 15, flexDirection: 'row', justifyContent: 'space-between'}}>
<View>
<Text style={[styles.large]}>$0</Text>
</View>
<View style={{flex: 0.3, flexDirection: 'row', right: 50}}>
<TouchableOpacity style={{
alignContent: 'center',
justifyContent: 'center',
backgroundColor: '#43a047',
width: 60,
marginRight: 5
}}>
<Text style={{alignSelf: 'center', color: '#f5f5f5'}}>WON</Text>
</TouchableOpacity>
<TouchableOpacity style={{
alignContent: 'center',
justifyContent: 'center',
backgroundColor: '#f44336',
width: 60,
marginLeft: 5
}}>
<Text style={{alignSelf: 'center', color: '#f5f5f5'}}>LOST</Text>
</TouchableOpacity>
</View>
</View>
<Tabs onScroll={(index) => this.setState({index})}>
<Tab heading={'TIMELINE'}
tabStyle={{backgroundColor: "#bdbdbd"}}
activeTabStyle={{backgroundColor: "#bdbdbd"}}
textStyle={{color: '#212121'}}>
<TouchableOpacity onPress={this.onSave.bind(this)}>
<View style={{
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
backgroundColor: "#fafafa",
padding: 15,
borderRadius: 4,
borderWidth: 0.5,
borderColor: '#d6d7da'
}}>
<View>
<Text>PT ABC deal</Text>
<Text>12.000 - PT ABC</Text>
</View>
<View>
<Icon name={'warning'} style={{color: '#ffee58', fontSize: 20}}/>
</View>
</View>
</TouchableOpacity>
</Tab>
<Tab heading={'DETAILS'}
tabStyle={{backgroundColor: "#bdbdbd"}}
activeTabStyle={{backgroundColor: "#bdbdbd"}}
textStyle={{color: '#212121'}}>
</Tab>
</Tabs>
</View>
</Content>
</Container>
);
}
}
export default Home;
|
const stateDefault = {
dsPhim: [],
slides: [
{ picture: "img/carousel/Doraemon.jpg" },
{ picture: "img/carousel/AQUA.jpg" },
{ picture: "img/carousel/FL.jpg" },
{ picture: "img/carousel/GOT.jpg" },
{ picture: "img/carousel/MIB.jpg" },
{ picture: "img/carousel/TW3.jpg" },
// { picture: "img/carousel/VAMPIRE.jpg" },
],
listRap: [],
danhSachCumRapHeThong: [],
listPhimCumRap: [],
thongTinLichChieuTheoCum: [],
chiTietPhim: {},
thongTinPhongVe: {},
danhSachGheDangDat: [],
};
export const QuanLyPhimReducer = (state = stateDefault, action) => {
switch (action.type) {
case "LAY_DANH_SACH_PHIM_ACTION": {
state.dsPhim = action.dsPhim;
return { ...state };
}
case "LAY_LIST_TT_RAP": {
state.listRap = action.listRap;
return { ...state };
}
case "LAY_LIST_CUM_RAP_HT": {
state.danhSachCumRapHeThong = action.danhSachCumRapHeThong;
return { ...state };
}
case "LAY_LIST_DANH_SACH_PHIM": {
state.listPhimCumRap = action.listPhimCumRap;
}
case "LAY_TT_LICH_CHIEU": {
state.thongTinLichChieuTheoCum = action.thongTinLichChieuTheoCum;
}
case "LAY_CHI_TIET_PHIM": {
state.chiTietPhim = action.chiTietPhim;
return { ...state };
}
case "THONG_TIN_PHONG_VE": {
state.thongTinPhongVe = action.thongTinPhongVe;
return { ...state };
}
case "DAT_GHE": {
let mangGheDangDat = [...state.danhSachGheDangDat];
let index = mangGheDangDat.findIndex(
(gheDangDat) => gheDangDat.maGhe === action.gheDangDat.maGhe
);
if (index !== -1) {
mangGheDangDat.splice(index, 1);
} else {
mangGheDangDat.push(action.gheDangDat);
}
return { ...state, danhSachGheDangDat: mangGheDangDat };
}
case "DAT_VE_THANH_CONG": {
return { ...state, danhSachGheDangDat: [] };
}
default:
return { ...state };
}
};
|
const express = require('express');
const router = express.Router();
const gameController = require("../controllers/gameController");
const routeHelper = require("../helper/routeHelper");
const { query, body, validationResult } = require('express-validator');
router.get('/games', routeHelper.mustBeloggedin, function (req, res, next) {
return gameController.GetByUserId(req.session.userId)
.then((games) => {
for (var i = 0; i < games.length; i++) {
games[i].id = gameController.CleanId(games[i].id);
}
routeHelper.renderView(req, res, "games", { games: games, errors: [] });
});
});
router.post('/game/create', routeHelper.mustBeloggedin, [body('name').exists().not().isEmpty()], function (req, res) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return gameController.GetAll()
.then((games) => {
for (var i = 0; i < games.length; i++) {
games[i].id = gameController.CleanId(games[i].id);
}
routeHelper.renderView(req, res, "games", { games: games, errors: [] });
});
}
req.body.name = routeHelper.removeXSS(req.body.name);
return gameController.create(req.body.name, req.session.userId)
.then((gameId) => {
routeHelper.Redirect(res, '/game/edit/' + gameId);
});
});
router.post('/game/save', routeHelper.mustBeloggedin, [body('gameId').exists().not().isEmpty(), body('items').exists().not().isEmpty(), body('name').exists().not().isEmpty(), body('isPublic').exists().not().isEmpty()], function (req, res) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array().map(e => e.msg + ": " + e.param) });
}
gameController.GetById(req.body.gameId)
.then((game) => {
if (game.userId == req.session.userId) {
gameController.update(req.body.gameId, JSON.parse(req.body.items), req.body.isPublic, req.body.name)
.then(() => {
res.json({ message: "Game successfully saved" });
});
}
else {
routeHelper.Redirect(res, '/back');
}
});
});
router.get('/game/edit/:id', routeHelper.mustBeloggedinAndHasGame, function (req, res, next) {
gameController.GetById("games/" + req.params.id)
.then((game) => {
if (game == undefined || game == null) {
return routeHelper.Redirect(res, '/');
}
else {
routeHelper.renderView(req, res, "game-editor", { game: game, baseUrl: "http://" + process.env.URL + ":" + process.env.HTTP_PORT });
}
});
});
router.get('/game/delete/:id', routeHelper.mustBeloggedinAndHasGame, function (req, res, next) {
gameController.delete("games/" + req.params.id)
.then(() => {
routeHelper.Redirect(res, '/games');
});
});
module.exports = router;
|
$(function() {
$('<img src="http://lorempixel.com/1600/1200/nature/5" />').on( 'load', function( ) {
$('.container').addClass('loaded');
var height = 0;
$( '.page' ).each(function( i ) {
$( this ).css({
zIndex:'-'+i
});
$( this ).data('start', height);
height += $( this ).height();
$( this ).data('end', height);
} );
$( '.container' ).css({ height : height });
} )
})
$( window ).on( 'scroll touchmove', function( ) {
var activePage = $( '.page.active' );
if ( activePage ) translate( activePage );
} )
function translate( activePage ) {
var scrollTop = $(window).scrollTop();
var start = activePage.data( 'start' );
var end = activePage.data( 'end' );
if ( (scrollTop) >= start && scrollTop <= end ) {
var dist = activePage.data( 'start' ) - $(window).scrollTop()
activePage.css({
webkitTransform:'translate(0,'+dist+'px)',
mozTransform:'translate(0,'+dist+'px)',
msTransform:'translate(0,'+dist+'px)',
oTransform:'translate(0,'+dist+'px)',
transform:'translate(0,'+dist+'px)'
})
} else if ( scrollTop >= start ) {
activePage.css({
webkitTransform:'translate(0,'+end+'px)',
mozTransform:'translate(0,'+end+'px)',
msTransform:'translate(0,'+end+'px)',
oTransform:'translate(0,'+end+'px)',
transform:'translate(0,'+end+'px)'
}).removeClass('active').next('.page').addClass('active');
} else if ( scrollTop <= end ) {
activePage.css({
webkitTransform:'',
mozTransform:'',
msTransform:'',
oTransform:'',
transform:'',
}).removeClass('active').prev('.page').addClass('active');
}
};
|
import React, { Component } from 'react'
import Reviews from '../component/Reviews'
import 'semantic-ui-css/semantic.min.css'
import Navigation from './Navigation'
import Image from '../component/Img'
const imageBuilder = (images) => {
return images.map((image) => (
<Image
img= {image}
/>
))
}
export default class BusinessProfile extends Component {
render() {
return (
<div >
<Navigation/>
<div className="ui centered grid">
<h1 className="Bussiness-Name">{this.props.business.name}</h1>
<h3 className="Bussiness-Type">{this.props.business.cuisine_type} </h3>
<h4 className="Bussiness-Hours">
{this.props.business.operating_hours}
</h4>
<button className="ui form">Write a Review</button>
<p className="Phone-Number">{this.props.business.phone}</p>
<p className="Address">{this.props.business.address}</p>
<div className="ui row">
<div id="images" >
{ this.props.business.imgsrc === undefined ? null : imageBuilder(this.props.business.imgsrc)}
</div>
</div>
<a className="businessFire">
<i className='sun icon'></i>
{this.props.business.text}
<div></div>
<button className="ui button" onClick={() => this.props.addLike(this.props.business.info)}>Add to Fire {<i className="fire icon" ></i>}</button>
</a>
</div>
<Reviews/>
<h1 className="my-reviews">Reviews</h1>
</div>
)
}
}
|
import React from 'react';
export default props => {
const styles = {
container: {
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
padding: 10,
height: 70,
backgroundColor: 'purple',
color: 'white'
},
navItem: {
margin: 10
}
}
return (
<div style={styles.container}>
<div style={styles.navItem} onClick={() => props.onNavClick('products')}>
products
</div>
<div style={styles.navItem} onClick={() => props.onNavClick('cart')}>
cart
</div>
</div>
)
}
|
import React, { Component } from "react";
import Title from "../components/Title";
import { Row, Container } from "../components/Grid"
import API from "../utils/API";
import {BooksList, BooksListItem} from "../components/BookList";
import { Link } from "react-router-dom";
import Button from "../components/Button"
class Saved extends Component {
state = {
books: [],
};
componentDidMount() {
this.loadBooks();
};
loadBooks = () => {
API.getBooks()
.then(res => this.setState({ books: res.data }))
.catch(err => console.log(err));
};
deleteBook = id => {
API.deleteBook(id)
.then(res => this.loadBooks())
.catch(err => console.log(err));
};
render() {
return (
<div>
<Title
title="Your Saved Book List"
subtitle="View or Delete Your Books"/>
<div className="my-3" />
<Row>
<Container>
<div className="border bg-light text-center">
<h5 className="m-3">List of Your Books</h5>
<Link to={"/"}>
<Button
color="primary"
text="Search Books">
</Button>
</Link>
<BooksList>
{this.state.books.map( (book, index) => (
<BooksListItem
key={index}
title={book.title}
subtitle={book.subtitle}
infoLink={book.link}
authors={book.author}
image={book.image}
description={book.description}
allowDelete={true}
onDelete={() => this.deleteBook(book._id)}
/>
)
)}
</BooksList>
</div>
</Container>
</Row>
</div>
)
}
}
export default Saved;
|
///////////////反馈管理/////////////
//刷新数据
function reload(){
$('#dg').datagrid('reload');
}
$(function() {
//加载数据
$('#dg').datagrid({
onLoadSuccess : function(data) {
if (data.total == 0 && data.ERROR == 'No Login!') {
var user_id = localStorage.getItem('user_id');
var user_pwd = localStorage.getItem('user_pwd');
if(user_id==''||!user_id||user_pwd==''||!user_pwd){
$.messager.alert('信息提示', '登录超时,请重新登录!', 'error');
//relogin();
setTimeout(function(){
location.replace('index.html');
}, 3000);
}
else{
$.post('loginAction!login1.zk',{user_id:user_id,user_pwd:user_pwd},function(data){
if(data.STATUS){
$('#dg').datagrid('reload');
}
},'json').complete(function(){
$('#dg').datagrid('reload');
});
}
/*
$.messager.alert('信息提示', '登录超时,请重新登录!', 'error');
setTimeout(function(){
location.replace('index.html');
}, 3000);*/
}
$('#dg').datagrid('doCellTip', {
onlyShowInterrupt: true,
position: 'bottom',
cls: { 'background-color': '#FFF' },
delay: 100
});
},
onLoadError : function() {
alert('网络连接超时!');
}
});
});
//显示消息提示
function showTip(msg) {
$.messager.show({
title : "消息",
timeout:2000,
msg : msg
});
}
//回复
function reply() {
var row = $('#dg').datagrid('getSelected');
if (row){
if(row.is_reply == 'n'){
//alert('可以回复');
$("#p_suggetion_contion").text(row.content);
$("#user_id").val(row.user_id);
$("#suggestion_id").val(row.id);
$('#dlg').dialog('open').dialog('setTitle','填写回复信息');
}else {
$.messager.alert('错误','已经回复啦!','error');
}
}else{
$.messager.alert('错误','请先选择反馈内容!','error');
}
}
//提交答复
function save(){
var suggestion_id = $("#suggestion_id").val();
var answer = $("#answer").val();
if(answer!=''){
var postData = {suggestion_id:suggestion_id,reply_content:answer};
$.post("feedbackAction!answer.zk",postData,function(data){
if(data.STATUS){
if(data.ERROR&&data.ERROR=='No Login!'){
alert('登陆超时,请重新登录!');
location.replace('index.html');
}else{
$("#dlg").dialog('close');
reload();//刷新表格
showTip("回复成功!");
$("#p_suggetion_contion").text('');
$("#user_id").val('');
$("#suggestion_id").val('');
$("#answer").val('');
}
}else{
alert("回复失败!");
}
},'json');
}else{
alert('回复内容不能为空!');
}
}
//删除全部反馈
function deleteAll(){
var ids = new Array();
var rows = $('#dg').datagrid('getSelections');//获取选中的多行
var size = rows.length;
for(var i=0; i<rows.length; i++){
ids.push(rows[i].id);
}
if(ids.length<1){
alert("请选择要删除的反馈!");
return ;
}
if (confirm('确定要删除所选反馈吗?')) {
$.post("feedbackAction!batchDelete.zk", {
id : ids.join(",")
}, function(data) {
if (data.STATUS) {
if(data.ERROR&&data.ERROR=='No Login!'){
alert('登陆超时,请重新登录!');
location.replace('index.html');
}else{
reload();//刷新表格
showTip("成功删除"+size+"条反馈!");
}
} else {
alert("删除反馈失败");
}
}, 'json');
}
}
//格式化时间
function formatDate(value){
var d = new Date(value);
return d.format("yyyy-MM-dd hh:mm:ss");
}
//重新加载表格数据
function reloadData(word , status){
$("#isReplyHd").val(status);
$("#dg").datagrid('load',{keyword:word,isReply:status});
}
//搜索框点击和回车事件
function search(value,name){
reloadData(value, name);
}
//下拉选框改变事件
function menuHandler(item){
var word = $("#txt_word").val();
reloadData(word, item.name);
linkBtnHandler(item.name);
}
//更新回复buton状态
function linkBtnHandler(s){
if(s == 'n' || s == 'a'){
$('#replyLnk').linkbutton('enable');
}else {
$('#replyLnk').linkbutton('disable');
}
}
|
class Selector {
constructor() {
this.data;
}
getData(table) {
let url = `http://localhost:5000/selectTable/${table}`;
return fetch(url)
.then((response) => response.json())
.then((json) => {
this.data = Array.from(json);
});
}
writeData() {
let box = document.querySelector('.box')
box.innerHTML = "";
let table = document.createElement("table");
let headers = Object.keys(this.data[0]);
let colNames = document.createElement("tr");
for (let el of headers) {
let th = document.createElement("th");
th.innerText = el;
colNames.append(th);
}
table.append(colNames);
for (let i in this.data) {
let row = document.createElement("tr");
for (let el of headers) {
let cell = document.createElement("td");
cell.innerText = this.data[i][el];
row.append(cell);
}
table.append(row);
}
box.append(table);
}
}
const manager = new Selector();
for (let link of document.querySelectorAll(".rect")) {
link.addEventListener("click", function () {
let rows = manager.getData(this.innerText);
rows.then((res) => manager.writeData());
});
}
|
/* eslint-disable react/prop-types */
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import Chip from '@material-ui/core/Chip';
import { selectNoteById, selectTodos } from './selector';
export default function DependencyChips(props) {
// eslint-disable-next-line react/prop-types
const { noteId } = props;
const note = useSelector(selectNoteById(noteId));
const todos = useSelector(selectTodos);
if (!note) return null;
const dep = note.todoDependency || [];
// get the todo names
const dependencies = dep.map((d) => {
return todos.map((t) => {
return d === t.id ? t.description : null;
});
});
const chips = [];
dependencies.forEach((d, index) => {
const domKey = `chip-${index}`;
chips.push(<Chip label={d} key={domKey} />);
});
return <div> {chips}</div>;
}
|
angular.module('app')
.controller('ResetPasswordController', function ($scope, User, $state, $rootScope, LoopBackAuth, $stateParams, $http, cfpLoadingBar) {
$http.defaults.headers.common['access_token'] = $stateParams.token;
$scope.user = {};
$rootScope.isAdmin = true;
$scope.save = function () {
cfpLoadingBar.start();
User.resetPassword({ email: $stateParams.email, password: $scope.user.password, password_confirmation: $scope.user.confirm_password, id: $stateParams.id }, function (response, headers) {
alert("Password successfully changed, please login with the new password");
$state.go("login");
cfpLoadingBar.complete();
}, function (response) {
cfpLoadingBar.complete();
alert(JSON.stringify(response.data.error.message));
});
}
})
|
$(document).ready(function() {
$(document).mousedown(function(event){
switch (event.which) {
case 1:
!function(e, t) {
"use strict";
function n(e, t) {
var n = .5
, o = .3
, a = n / (o + n)
, i = {};
return i.x0 = m = a * e + (1 - a) * m,
i.y0 = g = a * t + (1 - a) * g,
i
}
function o(e) {
var t = 19.8
, n = 3.14
, o = 9.8;
e += o,
e > t ? e = t : 0 > e && (e = 0);
return i(e) * n
}
function a(e, t) {
return 0 > t ? e : -e
}
function i(e) {
for (var t, n, o = [19.6, 18.8, 16.6, 13.6, 9.8, 6, 3, .8, 0], a = [0, .125, .25, .375, .5, .625, .75, .875, 1], i = 0, s = 1, r = 1; r < o.length && (i = r - 1,
s = r,
t = o[i],
n = o[s],
!(e >= n)); r++)
;
var l = a[i]
, p = a[s]
, d = (t - e) / (t - n)
, u = (p - l) * d + l;
return u
}
function s(e, t) {
var i = n(e, t)
, s = a(o(i.x0), i.y0);
null == h && (h = s);
var r = s - 1.57;
r >= -4.71 && -3.14 >= r && (r = 1.57 + Math.abs(-4.71 - r)),
h = (r - h) / 8 + h;
var l = h;
return l
}
var r;
!function(t) {
var n = function() {
function t() {
this.date = e.performance ? e.performance.now() : (new Date).getDate,
this.now = 0,
this.time = 0,
this.dt = 0,
this.getDeltaTimeInSeconds = function() {
return this.now = e.performance ? e.performance.now() : (new Date).getTime(),
this.dt = this.now - (this.time || this.now),
this.time = this.now,
this.dt / 1e3
}
}
return t
}();
t.DeltaTimeComputer = n
}(r || (r = {}));
for (var l = e.location.href.split("/"), p = "ge", d = 0, u = l.length; u > d; d++)
"en" == l[d] && (p = "en");
var c = function() {
var n, o = t.getElementById("mug-canvas"), a = o.getContext("2d"), i = e.location.hostname, l = new WebSocket("ws://" + i + ":8088"), d = 0, u = 0, c = [], m = t.getElementById("beer-mug"), g = t.getElementById("beer-tap-top"), h = t.getElementById("beer-pouring-from-tap"), y = t.getElementById("beer-pouring-from-mug"), f = t.getElementById("beer-audio-back"), v = new Audio("sounds/beer-sound-back.mp3"), I = t.getElementById("beer-audio-begin"), E = -1, w = 0, B = 0, b = 0, C = !1, T = !1, k = e.navigator.userAgent, M = new r.DeltaTimeComputer;
M.getDeltaTimeInSeconds();
var x = M.getDeltaTimeInSeconds()
, A = function() {
e.fbAsyncInit = function() {
FB.init({
appId: "1440544539599395",
xfbml: !0,
version: "v2.3"
})
}
,
function(e, t, n) {
var o, a = e.getElementsByTagName(t)[0];
e.getElementById(n) || (o = e.createElement(t),
o.id = n,
o.src = "https://connect.facebook.net/en_US/sdk.js",
a.parentNode.insertBefore(o, a))
}(t, "script", "facebook-jssdk")
};
A();
var D = function() {
function e(e) {
var t = randomInRange(25, 50) / 10
, n = randomInRange(20, 50) / 10;
e.style.webkitAnimationDelay = t + "s",
e.style.msAnimationDelay = t + "s",
e.style.mozAnimationDelay = t + "s",
e.style.oAnimationDelay = t + "s",
e.style.animationDelay = t + "s",
e.style.webkitAnimationDuration = n + "s",
e.style.msAnimationDuration = n + "s",
e.style.mozAnimationDuration = n + "s",
e.style.oAnimationDuration = n + "s",
e.style.animationDuration = n + "s"
}
if (-1 != k.indexOf("Firefox"))
for (var n = t.getElementsByClassName("window-day-seagull-wing"), o = 0, a = n.length; a > o; o++)
n[o].style.animation = "none",
n[o].style.webkitAnimation = "none",
n[o].style.mozAnimation = "none";
var i = new Date;
if (i.getHours() > 19 || i.getHours() < 7) {
t.getElementById("window-day").style.display = "none";
for (var s = t.getElementById("window-night").childNodes, o = 0, a = s.length; a > o; o++)
s[o].nodeName && "circle" == s[o].nodeName.toLowerCase() && e(s[o])
} else
t.getElementById("window-night").style.display = "none"
};
D();
var S = function() {
for (var e = randomInRange(16, 26), t = 0; e > t; t++) {
var n = randomInRange(2, 93)
, a = randomInRange(10, 50)
, i = randomInRange(3, 9) / 3
, s = randomInRange(25, 35) / 10;
c[t] = {
y: o.height + a,
x: n,
speed: i,
size: s,
delay: a
}
}
};
S();
var L = function(e) {
u += w > 40 && 50 > w ? e : w > 16 && 60 > w ? 2 * e : 5 * e
}
, P = function() {
var e = o.width
, t = o.height
, n = e * d;
if (a.globalAlpha = .6,
a.fillStyle = "#FFCD44",
n > 0 && w > 0) {
var i = Math.sin(w * (Math.PI / 180))
, s = Math.sin((90 - w) * (Math.PI / 180));
if (B = Math.sqrt(2 * n * s / i),
e > B) {
var r = 2 * n / B;
b = r,
a.beginPath(),
a.moveTo(0, t - r),
a.lineTo(0, t),
a.lineTo(B, t),
a.fill(),
a.fillStyle = "#f4efe5",
a.globalAlpha = 1,
a.beginPath(),
a.moveTo(0, t - r),
a.lineTo(B, t),
a.lineTo(B - u / i, t),
a.lineTo(0, t - r + u / s),
a.fill()
} else {
var l = n / e + e * i / (2 * s)
, p = 2 * n / e - l;
b = l,
a.beginPath(),
a.moveTo(0, t - l),
a.lineTo(0, t),
a.lineTo(e, t),
a.lineTo(e, t - p),
a.fill(),
a.fillStyle = "#f4efe5",
a.globalAlpha = 1,
a.beginPath(),
a.moveTo(0, t - l),
a.lineTo(e, t - p),
a.lineTo(e, t - p + u / s),
a.lineTo(0, t - l + u / s),
a.fill()
}
var c, m = 17;
c = 52 > w ? 27 : 22,
h.style.height = m * s / i + c + "px"
} else
B = e,
b = d,
a.fillRect(0, t - d, e, d),
a.fillStyle = "#f4efe5",
a.globalAlpha = 1,
a.fillRect(0, t - d, e, u),
h.style.height = "229px";
Math.round(b) > t ? (C = !0,
d -= 1.8,
u > 10 && (u -= 1)) : C = !1
}
, N = function(e, t) {
var n = getComputedStyle(e).getPropertyValue("background-position").split(" ")
, o = parseFloat(n[1]);
o > 0 ? (e.style.backgroundPosition = "50% " + (o - t + "%"),
e.style.msBackgroundPositionY = o - t + "%") : (e.style.backgroundPosition = "50% 100%",
e.style.msBackgroundPositionY = "100%")
}
, R = function() {
a.clearRect(0, 0, o.width, o.height),
x = parseInt(1e3 * M.getDeltaTimeInSeconds()) / 1e3;
for (var e = 0, i = c.length; i > e; e++) {
var s = o.width * d;
if (c[e].x < B - 7 && s > 0) {
var r = Math.sin(w * (Math.PI / 180))
, p = Math.sin((90 - w) * (Math.PI / 180))
, I = b - u / p - c[e].x * r / p;
a.globalAlpha = .5,
a.strokeStyle = "#ffe3b4",
a.beginPath(),
a.lineWidth = 2,
c[e].y > o.height - I + 10 ? c[e].y -= c[e].speed : c[e].y = o.height + c[e].delay,
a.arc(c[e].x, c[e].y, c[e].size, 0, 2 * Math.PI),
a.stroke()
}
}
if (T)
if (h.style.maxHeight = 232 - d + "px",
h.style.opacity = "1",
h.style.filter = "alpha(opacity=100)",
N(h, .4),
d < o.height - 1)
g.setAttribute("class", "clicked"),
t.getElementById("beer-tap-top-shadow").setAttribute("class", "clicked"),
C || (d += 16 * x,
L(2 * x));
else {
d = o.height;
var E = {
mugFull: "true",
id: n
};
l.send(JSON.stringify(E)),
C = !1,
T = !1,
f.pause(),
v.pause(),
changeStyle(m, {
webkitTransform: "rotate(0)",
MozTransform: "rotate(0)",
msTransform: "rotate(0)",
transform: "rotate(0)"
}),
w = 0,
g.setAttribute("class", ""),
t.getElementById("beer-tap-top-shadow").setAttribute("class", ""),
R(),
l.onopen = function() {
l.send(JSON.stringify({
registerMe: "desktop",
lang: p
}))
}
,
l.onmessage = function(e) {
var o = JSON.parse(e.data);
if (o.coords) {
var a = o.coords.message
, i = s(a.ax, a.ay)
, r = -Math.round(i * (180 / 3.14) * 100) / 100;
o.coords.clicked ? (T = !0,
void 0 == n && (n = o.coords.id),
I.currentTime < I.duration - 1 ? I.play() : f.currentTime < f.duration - 1 ? f.play() : v.currentTime < v.duration - 2 ? v.play() : (f.currentTime = 0,
setTimeout(function() {
v.pause(),
v.currentTime = 0
}, 300))) : (T = !1,
f.pause(),
v.pause(),
I.pause(),
g.setAttribute("class", ""),
t.getElementById("beer-tap-top-shadow").setAttribute("class", "")),
-r > 1 && 63 >= -r ? w = -r : 1 >= -r ? w = 0 : -r > 63 && (w = 63);
var l = "rotate(" + -1 * w + "deg)";
changeStyle(m, {
webkitTransform: l,
MozTransform: l,
msTransform: l,
transform: l
});
var p = "rotate(" + w + "deg)";
changeStyle(y, {
webkitTransform: p,
MozTransform: p,
msTransform: p,
transform: p,
height: 260 + .23 * w + "px"
})
}
};
var m = 0
, g = 0;
!function() {
function e(e, t, n) {
return "undefined" == typeof n || 0 === +n ? Math[e](t) : (t = +t,
n = +n,
isNaN(t) || "number" != typeof n || n % 1 !== 0 ? 0 / 0 : (t = t.toString().split("e"),
t = Math[e](+(t[0] + "e" + (t[1] ? +t[1] - n : -n))),
t = t.toString().split("e"),
+(t[0] + "e" + (t[1] ? +t[1] + n : n))))
}
Math.round10 || (Math.round10 = function(t, n) {
return e("round", t, n)
}
),
Math.floor10 || (Math.floor10 = function(t, n) {
return e("floor", t, n)
}
),
Math.ceil10 || (Math.ceil10 = function(t, n) {
return e("ceil", t, n)
}
)
}();
var h = 0
}(window, document);
}
}
}
}
})
});
|
function or35(n){
if (n % 5 === 0) {
return true;
}
if (n % 3 === 0) {
return true;
}
else return false;
}
|
import React from "react";
const FormsContact = () => (
<div className="col-12 col-sm-12 hasBgWhite">
<div className="card hasbg-ovelay ">
<h2 className="se_contact_title">Laisser un message</h2>
<form
className="contact-form"
name="contact-form"
method="post"
data-netlify="true"
data-netlify-honeypot="bot-field"
>
<div className="contact-name">
<label>
<span className="hide-text">Nom Complet</span>
<input name="name" type="text" placeholder="Nom Complet" />
</label>
</div>
<div className="contact-email">
<label>
<span className="hide-text">Email</span>
<input name="email" type="email" placeholder="Email" />
</label>
</div>
<div className="contact-sujet">
<label>
<span className="hide-text">Choisir département</span>
<select className="custom-select" name="departement">
<option>Choisir département</option>
<option value="Département Marketing">
Département Marketing
</option>
<option value="Département Juridique">
Département Juridique
</option>
<option value="Département Finance">Département Finance</option>
<option value="Département Commercial">
Département Commercial
</option>
</select>
</label>
</div>
<div>
<label className="hide-text" htmlFor="message">
Message
</label>
<div className="contact-message">
<textarea
name="message"
rows="4"
id="message"
required="required"
placeholder="Message"
></textarea>
</div>
</div>
<div className="text-right">
<button className="send">Envoyer</button>
</div>
</form>
</div>
</div>
);
export default FormsContact;
|
import axios from 'axios'
import util from '@/util/util.js'
// ----------------------------------------------------------------
// 开始动画
export default function ajax(url = '', params = {}, type = 'GET', delay = 0) {
let promise
return new Promise((resolve, reject) => {
// 设置headers
var headers = {
// 'k': 'bb04d055-9b7b-4da6-9895-66965efb4d13',
// 'u': 'bd8063c7-4323-4a9a-9a20-b7dd48772983',
'u': util.getCookie('u'),
'k': util.getCookie('k'),
}
if (type === 'GET') {
let paramsStr = ''
// 拼接请求字符串
Object.keys(params).forEach(key => {
paramsStr += key + '=' + encodeURIComponent(params[key]) + '&'
})
// 处理最后一个&
if (paramsStr !== '') {
paramsStr = paramsStr.substr(0, paramsStr.lastIndexOf('&'))
}
// 完整路径
url += '?' + paramsStr
promise = axios.get(url, {
headers
})
} else if (type === 'POST') {
promise = axios.post(url, params, {
headers
})
}
// 返回请求数据
promise.then(reqponse => {
resolve(reqponse.data)
}).catch(error => {
reject(error)
// Message({
// message: '数据库连接失败',
// type: 'error'
// })
})
})
}
// let loading = null
// function startLoading () {
// loading = Loading.service({
// lock: true,
// // text: '拼命加载中',
// // background: 'rgba(0,0,0,0.7)'
// text: '',
// background: 'transparent'
// })
// }
// // 结束加载动画
// function endLoading () {
// loading.close()
// }
// 请求过期时间
// axios.defaults.timeout = 5000
// axios.defaults.withCredentials=true
// // 请求拦截
// axios.interceptors.request.use(config => {
// startLoading()
// return config
// }, error => {
// return Promise.reject(error)
// })
// // 响应拦截
// axios.interceptors.response.use(response => {
// endLoading()
// return response
// }, error => {
// endLoading()
// // Message.error(error.response.data)
// return Promise.reject(error)
// })
|
define(function(require) {
'use strict';
var descriptors = require('tools/descriptors');
var isChrome = !!window.webkitRequestFileSystem;
var fs = isChrome ? require('./fs-wrapper') : require('localforage');
var filekey = 'filedata|';
function File(data) {
this.id = data.id;
this.type = data.type;
this.path = data.path;
this.size = data.size;
}
Object.defineProperties(File.prototype, descriptors({
getUrl: function() {
return fs.getItem(filekey + this.id).then(function(blob) {
return URL.createObjectURL(blob);
});
},
getContent: function() {
return fs.getItem(filekey + this.id).then(function(blob) {
return new Promise(function(resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function() { resolve(reader.result) };
reader.readAsDataURL(blob);
});
});
},
setContent: function(blob) {
return fs.setItem(filekey + this.id, blob).then(function() {
this.size = blob.size;
return this;
}.bind(this));
},
remove: function() {
return fs.removeItem(filekey + this.id);
},
}));
return File;
});
|
// Change the background color of the box to blue
document.getElementById('box').style.background='blue';
|
const express = require('express')
const bcrypt = require('bcryptjs')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const session = require('express-session')
const pgp = require('pg-promise')
const expressValidator = require('express-validator')
const flash = require('connect-flash')
const {
insertUser,
checkUserPassword,
checkUserEmail
} = require('./database/queries')
const app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(expressValidator())
app.use(cookieParser())
app.set('view engine', 'ejs')
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUnititalized: true,
cookie: {
maxAge: 30 * 60 * 1000
}
}))
app.use(require('connect-flash')())
app.use((req, res, next) => {
res.locals.messages = require('express-messages')(req, res)
next()
})
app.use(expressValidator({
errorFormatter: (param, msg, value) => {
let namespace = param.split('.')
, root = namespace.shift()
, formParam = root
while(namespace.length) {
formparam += '[' + namespace.shift() + ']'
}
return {
param: formParam,
msg : msg,
value: value
}
}
}))
app.get('/', (req, res) => {
res.render('home.ejs')
})
app.route('/signup')
.get((req, res) => {
res.render('signup.ejs')
})
.post((req, res) => {
if (
req.body.email === '' &&
req.body.password === '' &&
req.body.passwordConfirmation === ''
) {
req.flash('no values', 'please provide an email and a password to sign up')
res.redirect('/signup')
} else if (
req.body.password !== req.body.passwordConfirmation
) {
req.flash('password not matching', 'password do not match')
res.redirect('/signup')
} else {
const hash = bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(10))
const email = req.body.email
insertUser(email, hash)
.then((data) => {
req.session.email = data.email
res.render('loggedIn.ejs', { data: req.session.email })
})
.catch((error) => {
console.log(error)
res.redirect('signup')
})
}
})
app.route('/login')
.get((req, res) => {
res.render('login.ejs')
})
.post((req, res) => {
if (
req.body.email === '' &&
req.body.password === ''
) {
req.flash('no values', 'please provide an email and a password to login')
res.redirect('/login')
}
const email = req.body.email
checkUserPassword(email)
.then((data) => {
if (bcrypt.compareSync(req.body.password, data.password)) {
req.session.email = data.email
res.render('loggedIn.ejs', { data: email })
} else {
req.flash('incorrect values', 'incorrect email or password')
res.redirect('/login')
}
})
.catch((error) => {
req.flash('incorrect values', 'incorrect email or password')
res.redirect('/login')
})
})
app.get('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) throw err
res.redirect('/')
})
})
const port = 3000
app.listen(port, () => {
console.log('Express server running on port:', port)
})
|
var alias_2config_8c =
[
[ "config_init_alias", "alias_2config_8c.html#abeecb3c988acb9aa91ec8a680d328e6e", null ],
[ "SortAliasMethods", "alias_2config_8c.html#a6accc5f32e32ca3daa7c85ceeb133106", null ],
[ "AliasVars", "alias_2config_8c.html#afdb0e9d9303634ffd195c833daa8ab66", null ]
];
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import styled from 'styled-components';
import { initialize } from 'redux-form';
import moment from 'moment';
import { toastr } from 'react-redux-toastr';
import { Row, Col } from 'react-flexbox-grid';
import { Link } from 'react-router-dom';
import { db } from '../../firebaseConfig';
import { setUserEvents } from './actions';
import CreateEventForm from './Form';
import Button from '@material-ui/core/Button';
export const PageHeader = styled(Col)`
max-width: 100vw;
height: 50px;
background: #F5A800;
padding: 0 12px;
top: 0;
left: 0;
right: 0;
position: fixed;
`;
export const Column = styled(Col)`
width: 100%;
padding: 12px;
`;
export const Wrapper = styled.div`
margin: 0;
padding: 12px;
`;
export const LogList = styled.div`
padding: 0;
margin: 0;
list-style: none;
`;
export const ContentRow = styled(Row)`
padding: 0 12px;
`;
export const ContentWrapper = styled.div`
width: 100%;
margin-top: 10vh;
`;
export const ListItem = styled(Link)`
color: #000;
text-decoration: none;
`;
export const ListItemWrapper = styled.div`
padding: 18px;
margin: 16px 0;
box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.19);
`;
export const ListItemTitle = styled.h4`
margin: 0;
padding: 0;
text-align: left;
`;
export const FeedWrapper = styled.div`
display: flex;
align-items: center;
justify-content: center;
margin-top: 10vh;
`;
export const PageWrapper = styled.div`
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
margin-top: 10vh;
`;
export function handleSubmit(values, user, history) {
// step 1: create the reference
const timeStamp = new Date().getTime();
const eventReference = db.collection('posts').doc(`${user}${timeStamp}`);
// step 2: update the reference with the countries
eventReference.set({
id: eventReference.id,
uid: user,
post: values.post,
timestamp: timeStamp,
}).then(() => {
toastr.success('Event Created', 'You have successfully created an event');
history.push('/news');
}).catch((error) => {
toastr.error('Something went wrong', 'Your event was not registered.');
console.log('error: ', error);
});
}
function renderLogs(userEvents, initializeForm, user, history) {
if (!userEvents.length) return <FeedWrapper><h1>No feed yet</h1></FeedWrapper>;
return (
<ContentWrapper>
<ContentRow start='xs' center='md'>
<Column xs={12} md={2}>
<LogList>
{userEvents.map((event) => {
const {
id, post, timestamp,
} = event;
const dateTime = new Date(timestamp);
const formatDate = moment(dateTime).format('DD MMMM YYYY');
return (
<ListItem to='/post' key={id} onClick={() => initializeForm(event)}>
<ListItemWrapper>
<ListItemTitle>
<p>
{formatDate}
</p>
{post}
</ListItemTitle>
</ListItemWrapper>
</ListItem>
);
})}
</LogList>
</Column>
</ContentRow>
</ContentWrapper>
);
}
class Logbook extends Component {
constructor(props) {
super(props);
this.getEvents = this.getEvents.bind(this);
}
componentDidMount() {
const {
user, setUserEventsToState,
} = this.props;
this.getEvents(setUserEventsToState, user);
}
getEvents(setUserEventsToState, user) {
const docRef = db.collection('posts').where('uid', '==', user).orderBy('timestamp', 'desc');
docRef.onSnapshot({ includeMetadataChanges: true }, (querySnapshot) => {
const data = [];
querySnapshot.forEach((doc) => {
data.push(doc.data());
});
setUserEventsToState(data);
});
}
render() {
const { user, userEvents, initializeForm, history } = this.props;
return (
<PageWrapper>
<CreateEventForm user={user} submitFunction={handleSubmit} history={history} />
{renderLogs(userEvents, initializeForm, user, history)}
</PageWrapper>
);
}
}
export function mapStateToProps(state) {
return {
userEvents: state.logbook.userEvents,
};
}
export function mapDispatchToProps(dispatch) {
return {
setUserEventsToState: data => dispatch(setUserEvents(data)),
initializeForm: (data) => {
dispatch(initialize('UpdateLogForm', data));
},
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Logbook);
|
function signup(firstName, lastName, email, password, successFunction, errorFunction) {
$.ajax({
url: '/signup/perform',
type: 'POST',
processData: true,
dataType: "json",
data: {'firstName': firstName,
'lastName': lastName,
'email': email,
'password': password},
success: function(result, status, xhr) {
successFunction(result, status);
},
error: function(xhr, status, error) {
errorFunction(error, status, xhr.responseText);
}});
}
function signin(email, password, redirect_uri, successFunction, errorFunction) {
$.ajax({
url: '/signin/perform?redirect=' + redirect_uri,
type: 'POST',
processData: true,
dataType: "json",
data: {'email':email,
'password':password},
success: function(result, status, xhr) {
successFunction(result, status);
},
error: function(xhr, status, error) {
errorFunction(error, status, xhr.responseText);
}});
}
function create_client_id(successFunction, errorFunction) {
$.ajax({
url: '/oauth2/apps/create',
type: 'GET',
processData: true,
dataType: "json",
success: function(result, status, xhr) {
successFunction(result, status);
},
error: function(xhr, status, error) {
errorFunction(error, status, xhr.responseText);
}});
}
|
var caching = null,
cachingSettings = {},
logger = null;
module.exports = function(cachingSettings) {
logger = cachingSettings.logger;
if (!cachingSettings) {
logger.Info('Caching status: OFF');
}
logger.Info("Caching service initialized.");
this.cachingSettings = cachingSettings;
if (cachingSettings) {
if (cachingSettings.ram){
caching = require('./ram')(cachingSettings.tools.DefaultSettingHandler(cachingSettings.ram));
logger.Info('Chaching type set to ram type.');
} else {
logger.Fatal('Error: Caching settings are not set!');
return false;
}
}
module.exports.get = function(options, fun){
var result;
// if force skip cache or cached object not found
if (options.skipCache === true || typeof (result = caching.get(options.key)) === "undefined") {
var args = Array.prototype.slice.call(arguments, 2);
result = fun.apply(null, args);
caching.set(options.key, result);
}
return result;
};
return module.exports;
};
|
//配置网络请求
let baseUrl="https://reactapi.iynn.cn";
//地址的定义
export const NORMAL_LOGIN=baseUrl+"/api/common/auth/login";
export const MOBILE_LOGIN=baseUrl+"/api/common/auth/mobile";
export const VERIFY_CAPTCHA=baseUrl+"/api/common/captcha/verify";
export const GET_SMS_CODE=baseUrl+"/api/common/sms/send";
export const JWT_PRE_CHECK=baseUrl+"/api/common/auth/jwtPreCheck";
export const ADMIN_INFO=baseUrl+"/api/common/auth/adminInfo";
export const GET_USERS_LIST=baseUrl+"/api/users";
export const GET_STATISTICS=baseUrl+"/api/users/statistics/getData";
export const ADD_USERS=baseUrl+"/api/users/add";
export const DELETE_USERS=baseUrl+"/api/users";
export const DETAILED_USERS=baseUrl+"/api/users";
export const UPDATA_USERS=baseUrl+"/api/users";
|
import React from 'react';
import { Link } from 'react-router-dom';
const Greeting = ({currentUser, logout}) => {
const sessionRoutes = () => (
<nav className="login_signup">
<Link class='login_button'to="/login">Login</Link>
<Link class='signup_button'to="/signup">Get Started</Link>
</nav>
);
const LoggedIn = () => (
<div>
<div className='portfolio_link' >
<Link className='portfolio_button' to={`/portfolio`}>Portfolio</Link>
</div>
<div>
<Link className='trade_link' to={`/trade`}>Trade</Link>
</div>
<div className="header">
<h2 className='header-email'>{currentUser.email}</h2>
<button className='logout_button' onClick={logout}>Logout</button>
</div>
</div>
);
return currentUser ? LoggedIn() : sessionRoutes();
};
export default Greeting;
|
let url='www.baidu.com?wd=wh&age=28';
/***
* 第一种方法
* 原理: 首先看是否存在?,不存在,则后面没有跟参数,
* 存在,则用?分割url,取后面部分,再根据&分割,再进一步根据=分割
* 用到str.indexOf
* str.split()方法
* 最后把分割的项存到一个对象里面
* **/
String.prototype.myUrlQuery=function () {
let obj={};
if(this.indexOf("?")!==-1){
return obj;
}else{
let url=this.split('?');
let item=url[1].split("&");//[wd=wh,age=28]
for(let i=0; i<item.length; i++){
let cur=item[i].split('=');
obj[cur[0]]=cur[1];
}
}
return obj;
};
let url1=url.myUrlQuery();
console.log(url1);
/***
* 第二种方法
* 利用正则;靠等号链接,并且前后不能是=?&
* /([^&=?]+)=(([^&=?]+)/g
* str.replace(reg,function(){});
* function中参数,第一个为符合要求的整体匹配,剩下的为小括号组成的小组
* **/
String.prototype.myQueryReg=function(){
let reg=/([^&?=]+)=([^&=?]+)/g;
let obj={};
this.replace(reg,function (...arg) {
obj[arg[1]]=arg[2];
});
return obj;
};
let url2=url.myQueryReg();
console.log(url2);
|
'use strict';
function makeStudentsReport(data) {
const studentReports = [];
for (let i = 0; i < data.length; i++) {
studentReports.push(data[i]['name'] + ': ' + data[i]['grade']);
}
return studentReports;
}
|
const querystring = require('querystring')
function isLoggedIn (req, res, next) {
if (req.isAuthenticated()) return next()
res.redirect('/user/login')
}
function reportAccess (dontDirectToAccess) {
return function (req, res, next) {
if (!req.isAuthenticated()) {
res.redirect(`/user/login`)
} else if (!dontDirectToAccess && !req.session.reportUserId) {
const queryString = querystring.stringify({ continueUrl: req.originalUrl })
res.redirect('/report/access?' + queryString)
} else {
next()
}
}
}
function payrollAccessOther (dontDirectToAccess) {
return function (req, res, next) {
const grantedUserIDs = [process.env.SUPERUSER1, process.env.SUPERUSER2, process.env.SUPERUSER3]
if (!req.isAuthenticated()) {
res.redirect(`/user/login`)
} else if (!grantedUserIDs.includes(req.user._id.toString())) {
res.redirect('back')
} else if (!dontDirectToAccess && !grantedUserIDs.includes(req.session.otherPayrollUserId || '')) {
const queryString = querystring.stringify({ continueUrl: req.originalUrl })
res.render('./partials/accessView', {
title: 'Other Payroll',
postUrl: '/payroll/access-other?' + queryString
})
} else {
next()
}
}
}
function payrollAccessMonthly (dontDirectToAccess) {
return function (req, res, next) {
const grantedUserIDs = [process.env.SUPERUSER1, process.env.SUPERUSER2, process.env.SUPERUSER3]
if (!req.isAuthenticated()) {
res.redirect(`/user/login`)
} else if (!grantedUserIDs.includes(req.user._id.toString())) {
res.redirect('back')
} else if (!dontDirectToAccess && !grantedUserIDs.includes(req.session.monthlyPayrollUserId || '')) {
const queryString = querystring.stringify({ continueUrl: req.originalUrl })
res.render('./partials/accessView', {
title: 'Monthly Payroll',
postUrl: '/payroll/access-monthly?' + queryString
})
} else {
next()
}
}
}
function blocked (blocked) {
return (req, res, next) => {
if (blocked) return res.redirect('back')
else next()
}
}
module.exports = {
isLoggedIn,
reportAccess,
payrollAccessOther,
payrollAccessMonthly,
blocked
}
|
import React, { useEffect, useState } from "react";
import "./History.css";
import { ResponsiveLine } from "@nivo/line";
const History = () => {
const [emotions, setEmotions] = useState({});
const [loading, setLoading] = useState(true);
const responseData = {
"2020-06-30": {
sadness: 0.161487,
joy: 0.607734,
fear: 0.139994,
disgust: 0.111099,
anger: 0.051704
},
"2020-06-29": {
sadness: 0.161487,
joy: 0.607734,
fear: 0.139994,
disgust: 0.111099,
anger: 0.051704
},
"2020-06-28": {
sadness: 0.161487,
joy: 0.607734,
fear: 0.139994,
disgust: 0.111099,
anger: 0.051704
},
"2020-06-27": {
sadness: 0.161487,
joy: 0.607734,
fear: 0.139994,
disgust: 0.111099,
anger: 0.051704
},
"2020-06-26": {
sadness: 0.161487,
joy: 0.607734,
fear: 0.139994,
disgust: 0.111099,
anger: 0.051704
},
"2020-06-25": {
sadness: 0.161487,
joy: 0.607734,
fear: 0.139994,
disgust: 0.111099,
anger: 0.051704
},
"2020-06-24": {
sadness: 0.161487,
joy: 0.607734,
fear: 0.139994,
disgust: 0.111099,
anger: 0.051704
},
"2020-06-23": {
sadness: 0.161487,
joy: 0.607734,
fear: 0.139994,
disgust: 0.111099,
anger: 0.051704
},
"2020-06-22": {
sadness: 0.161487,
joy: 0.607734,
fear: 0.139994,
disgust: 0.111099,
anger: 0.051704
},
"2020-06-21": {
sadness: 0.161487,
joy: 0.607734,
fear: 0.139994,
disgust: 0.111099,
anger: 0.051704
},
"2020-06-20": {
sadness: 0.161487,
joy: 0.607734,
fear: 0.139994,
disgust: 0.111099,
anger: 0.051704
},
"2020-06-19": {
sadness: 0.225129,
joy: 0.435498,
fear: 0.030406,
disgust: 0.294654,
anger: 0.104626
},
"2020-06-18": {
sadness: 0.225129,
joy: 0.435498,
fear: 0.030406,
disgust: 0.294654,
anger: 0.104626
},
"2020-06-17": {
sadness: 0.225129,
joy: 0.435498,
fear: 0.030406,
disgust: 0.294654,
anger: 0.104626
},
"2020-06-16": {
sadness: 0.225129,
joy: 0.435498,
fear: 0.030406,
disgust: 0.294654,
anger: 0.104626
},
"2020-06-15": {
sadness: 0.225129,
joy: 0.435498,
fear: 0.030406,
disgust: 0.294654,
anger: 0.104626
},
"2020-06-14": {
sadness: 0.225129,
joy: 0.435498,
fear: 0.030406,
disgust: 0.294654,
anger: 0.104626
},
"2020-06-13": {
sadness: 0.225129,
joy: 0.435498,
fear: 0.030406,
disgust: 0.294654,
anger: 0.104626
},
"2020-06-12": {
sadness: 0.225129,
joy: 0.435498,
fear: 0.030406,
disgust: 0.294654,
anger: 0.104626
},
"2020-06-11": {
sadness: 0.225129,
joy: 0.435498,
fear: 0.030406,
disgust: 0.294654,
anger: 0.104626
},
"2020-06-10": {
sadness: 0.225129,
joy: 0.435498,
fear: 0.030406,
disgust: 0.294654,
anger: 0.104626
},
"2020-06-09": {
sadness: 0.225129,
joy: 0.435498,
fear: 0.030406,
disgust: 0.294654,
anger: 0.104626
},
"2020-06-08": {
sadness: 0.225129,
joy: 0.435498,
fear: 0.030406,
disgust: 0.294654,
anger: 0.104626
},
"2020-06-07": {
sadness: 0.225129,
joy: 0.435498,
fear: 0.030406,
disgust: 0.294654,
anger: 0.104626
},
"2020-06-06": {
sadness: 0.225129,
joy: 0.435498,
fear: 0.030406,
disgust: 0.294654,
anger: 0.104626
},
"2020-06-05": {
sadness: 0.225129,
joy: 0.435498,
fear: 0.030406,
disgust: 0.294654,
anger: 0.104626
},
"2020-07-08": {
sadness: 0.2821285,
joy: 0.07091700000000001,
fear: 0.1489865,
disgust: 0.2465125,
anger: 0.10238249999999999
}
};
const setData = () => {
let anger = [
{
id: "emotion",
color: "hsl(129, 70%, 50%)",
data: []
}
];
let fear = [
{
id: "emotion",
color: "hsl(192, 70%, 50%)",
data: []
}
];
let joy = [
{
id: "emotion",
color: "hsl(311, 70%, 50%)",
data: []
}
];
let sad = [
{
id: "emotion",
color: "hsl(252, 70%, 50%)",
data: []
}
];
let disgust = [
{
id: "emotion",
color: "hsl(131, 70%, 50%)",
data: []
}
];
Object.keys(responseData).map(key => {
var date = key;
anger[0].data.push({
x: date.split("-")[2],
// y: responseData[date]["anger"]
y: Math.random(1)
});
fear[0].data.push({
x: date.split("-")[2],
// y: responseData[date]["fear"]
y: Math.random(1)
});
sad[0].data.push({
x: date.split("-")[2],
// y: responseData[date]["sad"]
y: Math.random(1)
});
joy[0].data.push({
x: date.split("-")[2],
// y: responseData[date]["joy"]
y: Math.random(1)
});
disgust[0].data.push({
x: date.split("-")[2],
// y: responseData[date]["disgust"]
y: Math.random(1)
});
});
// for (let i = 0; i < Object.keys(responseData).length; i = i + 2) {
// let date = Object.keys(responseData)[i];
// }
let emotions = {
anger,
fear,
sad,
joy,
disgust
};
setEmotions(emotions);
setLoading(false);
};
useEffect(() => {
setData();
}, []);
if (loading) {
return (
<div>
<p>Loading</p>
</div>
);
} else {
return (
<div style={{ marginTop: -18, marginLeft: 20 }}>
<div className="title-header" style={{ marginLeft: -4 }}>
<p>History of sentiments throughout the month</p>
</div>
<div className="grid-container">
<div className="grid-item" style={{ marginBottom: 20 }}>
<div className="card">
<div className="card-header">
<p>Anger</p>
</div>
<div className="card-content" style={{ height: 250 }}>
<ResponsiveLine
data={emotions.anger}
margin={{ top: 10, right: 50, bottom: 50, left: 50 }}
xScale={{ type: "point" }}
yScale={{
type: "linear",
min: "0",
max: "1",
stacked: true,
reverse: false
}}
axisTop={null}
axisRight={null}
axisBottom={{
orient: "bottom",
tickSize: 5,
tickPadding: 5,
tickRotation: 90,
legend: "Date of month",
legendOffset: 36,
legendPosition: "middle"
}}
axisLeft={{
orient: "left",
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: "sentiment level",
legendOffset: -40,
legendPosition: "middle"
}}
colors={{ scheme: "dark2" }}
pointSize={10}
pointColor={{ theme: "background" }}
pointBorderWidth={2}
pointBorderColor={{ from: "serieColor" }}
pointLabel="week"
pointLabelYOffset={-12}
useMesh={true}
/>
</div>
</div>
</div>
<div className="grid-item">
<div className="card">
<div className="card-header">
<p>Joy</p>
</div>
<div className="card-content" style={{ height: 250 }}>
<ResponsiveLine
data={emotions.joy}
margin={{ top: 10, right: 50, bottom: 50, left: 50 }}
xScale={{ type: "point" }}
yScale={{
type: "linear",
min: "0",
max: "1",
stacked: true,
reverse: false
}}
axisTop={null}
axisRight={null}
axisBottom={{
orient: "bottom",
tickSize: 5,
tickPadding: 5,
tickRotation: 90,
legend: "Date of month",
legendOffset: 36,
legendPosition: "middle"
}}
axisLeft={{
orient: "left",
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: "sentiment level",
legendOffset: -40,
legendPosition: "middle"
}}
colors={{ scheme: "dark2" }}
pointSize={10}
pointColor={{ theme: "background" }}
pointBorderWidth={2}
pointBorderColor={{ from: "serieColor" }}
pointLabel="week"
pointLabelYOffset={-12}
useMesh={true}
/>
</div>
</div>
</div>
</div>
<div className="grid-container">
<div className="grid-item" style={{ marginBottom: 20 }}>
<div className="card">
<div className="card-header">
<p>Disgust</p>
</div>
<div className="card-content" style={{ height: 250 }}>
<ResponsiveLine
data={emotions.disgust}
margin={{ top: 10, right: 50, bottom: 50, left: 50 }}
xScale={{ type: "point" }}
yScale={{
type: "linear",
min: "0",
max: "1",
stacked: true,
reverse: false
}}
axisTop={null}
axisRight={null}
axisBottom={{
orient: "bottom",
tickSize: 5,
tickPadding: 5,
tickRotation: 90,
legend: "Date of month",
legendOffset: 36,
legendPosition: "middle"
}}
axisLeft={{
orient: "left",
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: "sentiment level",
legendOffset: -40,
legendPosition: "middle"
}}
colors={{ scheme: "dark2" }}
pointSize={10}
pointColor={{ theme: "background" }}
pointBorderWidth={2}
pointBorderColor={{ from: "serieColor" }}
pointLabel="week"
pointLabelYOffset={-12}
useMesh={true}
/>
</div>
</div>
</div>
<div className="grid-item">
<div className="card">
<div className="card-header">
<p>Sad</p>
</div>
<div className="card-content" style={{ height: 250 }}>
<ResponsiveLine
data={emotions.sad}
margin={{ top: 10, right: 50, bottom: 50, left: 50 }}
xScale={{ type: "point" }}
yScale={{
type: "linear",
min: "0",
max: "1",
stacked: true,
reverse: false
}}
axisTop={null}
axisRight={null}
axisBottom={{
orient: "bottom",
tickSize: 5,
tickPadding: 5,
tickRotation: 90,
legend: "Date of month",
legendOffset: 36,
legendPosition: "middle"
}}
axisLeft={{
orient: "left",
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: "sentiment level",
legendOffset: -40,
legendPosition: "middle"
}}
colors={{ scheme: "dark2" }}
pointSize={10}
pointColor={{ theme: "background" }}
pointBorderWidth={2}
pointBorderColor={{ from: "serieColor" }}
pointLabel="week"
pointLabelYOffset={-12}
useMesh={true}
/>
</div>
</div>
</div>
</div>
<div className="grid-container">
<div className="grid-item" style={{ marginBottom: 20 }}>
<div className="card">
<div className="card-header">
<p>Fear</p>
</div>
<div className="card-content" style={{ height: 250 }}>
<ResponsiveLine
data={emotions.fear}
margin={{ top: 10, right: 50, bottom: 50, left: 50 }}
xScale={{ type: "point" }}
yScale={{
type: "linear",
min: "0",
max: "1",
stacked: true,
reverse: false
}}
axisTop={null}
axisRight={null}
axisBottom={{
orient: "bottom",
tickSize: 5,
tickPadding: 5,
tickRotation: 90,
legend: "Date of month",
legendOffset: 36,
legendPosition: "middle"
}}
axisLeft={{
orient: "left",
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: "sentiment level",
legendOffset: -40,
legendPosition: "middle"
}}
colors={{ scheme: "dark2" }}
pointSize={10}
pointColor={{ theme: "background" }}
pointBorderWidth={2}
pointBorderColor={{ from: "serieColor" }}
pointLabel="week"
pointLabelYOffset={-12}
useMesh={true}
/>
</div>
</div>
</div>
</div>
</div>
);
}
};
export default History;
const data = [
{
id: "emotion",
color: "hsl(0, 100%, 50%)",
data: [
{
x: "03",
y: 60
},
{
x: "06",
y: 20
},
{
x: "09",
y: 29
},
{
x: "12",
y: 67
},
{
x: "15",
y: 28
},
{
x: "18",
y: 12
},
{
x: "21",
y: 25
},
{
x: "24",
y: 29
},
{
x: "27",
y: 24
},
{
x: "30",
y: 10
}
]
}
];
|
const { ForumQuestionInput } = require('./forumQuestion');
exports.allForumQuestionInputs = `
${ ForumQuestionInput }
`;
|
import { CHANGE_REFINE_FIELD } from "../actions/types";
const INITIAL_STATE = {
refineField: ""
};
export default (state = INITIAL_STATE, action = {}) => {
switch (action.type) {
case CHANGE_REFINE_FIELD:
return { ...state, refineField: action.payload };
default:
return state;
}
};
|
/*
* @Author: echo
* @Date: 2021-02-20 15:22:43
* @LastEditTime: 2021-03-18 17:26:43
* @LastEditors: Please set LastEditors
* @Description: axios的请求封装
* @FilePath: \jiake-share-h5\src\api\api.ts
*/
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import store from '@/store';
import * as Types from '@/store/action-types';
import { Notify } from 'vant';
class JKRequest {
#baseURL;
#timeout;
constructor() {
this.#baseURL = process.env.DEV_BASE_URL;
this.#timeout = 30 * 1000;
}
request(options) {
// 针对每次请求创建新的实例,每个实例的拦截器和其他请求无关,这样方便给每次请求单独配置拦截器
const instance = axios.create();
this.setInterceptors(instance);
const opts = this.#mergeOptions(options);
return instance(opts);
}
// 添加拦截
setInterceptors(instance) {
instance.interceptors.request.use((config) => {
// 显示加载状态
store.commit(Types.SET_LOADING, true);
if (config.data && String(config.method).toLocaleUpperCase() === "GET") {
config.params = config.data;
}
return config;
});
instance.interceptors.response.use((res) => {
// 关闭加载状态
store.commit(Types.SET_LOADING, false);
// java解析状态值
const code = res.data.code;
if(res.status === 200 && !code) return Promise.resolve(res.data);
return this.#analysisStatus(code, res.data);
}, err => {
return this.#analysisStatus(err.response.status, err.response.data);
});
}
// 解析接口返回状态值
#analysisStatus(status, data){
switch(status) {
case 200:
return Promise.resolve(data);
case 400:
Notify({ type: "danger", message: data.msg || data });
break;
case 404:
Notify({ type: "danger", message: "网络请求不存在" });
break;
default:
Notify({ type: "danger", message: data.msg || data });
break;
}
return Promise.reject(data);
}
// 合并options
#mergeOptions(options = {}) {
return {
baseURL: this.#baseURL,
timeout: this.#timeout,
...options
};
}
get(url, params = {}, headers = {}) {
return this.request({
method: 'get',
url,
params,
headers,
});
}
post(url, data = {}, headers = {}) {
return this.request({
method: 'post',
url,
data,
headers
});
}
}
export default JKRequest;
|
import React from "react";
import {withRouter} from 'react-router';
import './History.css';
import APIClient from '../../Actions/apiClient';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import ListGroup from 'react-bootstrap/ListGroup';
import Tab from 'react-bootstrap/Tab';
import Table from 'react-bootstrap/Table';
import Form from 'react-bootstrap/Form';
import i18n from "i18next";
import Plot from 'react-plotly.js';
import { withTranslation } from 'react-i18next';
class History extends React.Component {
constructor(props) {
super(props);
this.state = {
isFetchingData: true,
profile: {},
predictionIsFinished: false,
history: {},
searchField: ''
}
this.getFilteredList = this.getFilteredList.bind(this);
}
// Check the users auth token,
// If there is none / it is blacklisted,
// Push user to login, set message banner to appropriate message,
// Store current location to redirect user back here after successful login
async componentDidMount() {
this.apiClient = new APIClient();
this.apiClient.getAuth().then((data) => {
this.apiClient.getUserDetails(data.logged_in_as.email).then((data) => { console.log(data)
this.setState({
isFetchingData: false,
profile: data,
history: data.submittedJobs
})
})
}).catch((err) => {
if (err.response.status) {
if (err.response.status === 401) {
const location = {
pathname: '/login',
state: {
from: 'History',
message: i18n.t('messages.notauthorized')
}
}
this.props.history.push(location)
}
}
})
}
// Filter object array
// Return item if value at specified key includes letter(s)
// Used for searching through list of history items
getFilteredList(array, key, value) {
return array.filter(function(e) {
return e[key].includes(value);
});
}
handleInputChange = (event) => {
const { value, name } = event.target;
this.setState({
[name]: value
});
var filteredList = this.getFilteredList(this.state.profile.submittedJobs, "predictionTitle", value);
this.setState({
history: filteredList.reverse()
});
}
// CreateTabs and CreateCols map arrays of data to return functions that generate DOM elements
createTabs(item) {
return (
<ListGroup.Item action eventKey={item._id.$oid} key={item._id.$oid}>
{item.predictionTitle}
</ListGroup.Item>
)
}
createCols(item) {
let startTime = new Date(item.timeStarted.$date);
var endTime = i18n.t('history.predictionrunning');
if (item.timeEnded) {
let timeEnded = new Date(item.timeEnded.$date);
endTime = timeEnded.toLocaleTimeString() + ' ' + timeEnded.toLocaleDateString()
}
function range(start, stop, step) {
var a = [start], b = start;
while (b < stop) {
a.push((b += step || 1)/365);
}
return a;
}
function x_axis(nb_bins) {
return range(0, 3498, 3498/nb_bins);
}
function createPlotPatient(item) {
if (item.result) {
// Creating the plot for each patient
function createPatientList(item) {
return (
<ListGroup.Item action eventKey={item.patient_id} key={item.patient_id}>
{item.patient_id}
</ListGroup.Item>
)
}
var patientList = item.result.map(createPatientList);
function createPatientPlot(item) {
console.log('item plot', item)
var plot_data = [];
Object.keys(item).forEach(function(key) {
if (key != 'patient_id') {
if (key == 'NO') {
var trace1 = {
x: x_axis(item[key].length),
y: item[key],
type: 'scatter',
name: key,
mode: 'lines',
line: {
dash: 'Solid',
width: 3
}
}
plot_data.push(trace1)
} else {
var trace1 = {
x: x_axis(item[key].length),
y: item[key],
type: 'scatter',
name: key,
mode: 'lines',
opacity: 0.5,
line: {
dash: 'dot',
width: 2
}
}
plot_data.push(trace1)
}
}
})
return (
<Tab.Pane eventKey={item.patient_id} key={item.patient_id} mountOnEnter="true" unmountOnExit="false">
<Table striped bordered hover className="prediction-plot">
<tbody>
<tr> <Plot data={plot_data} layout={ {width: 500, height: 500,
title: item.patient_id,
xaxis: {title: i18n.t('history.plotXaxis')},
yaxis: {range: [0, 1], title: i18n.t('history.plotYaxis')}}}/>
</tr>
</tbody>
</Table>
</Tab.Pane>
)
}
var patientPlot = item.result.map(createPatientPlot);
return (
<div className="container">
<div className="container-fluid">
<Tab.Container id="list-plot" defaultActiveKey='patient_0'>
<Row key="f">
<Col sm={4} id='list_group_patient'>
{patientList}
</Col>
<Col sm={8}>
<Tab.Content>
{patientPlot}
</Tab.Content>
</Col>
</Row>
</Tab.Container>
</div>
</div>
)
} else {
return (
<div> </div>
)
}
}
var res = createPlotPatient(item)
return (
<Tab.Pane eventKey={item._id.$oid} key={item._id.$oid} mountOnEnter="true" unmountOnExit="false">
<Table bordered className="prediction-info" size="sm">
<tbody>
<tr>
<td className="prediction-info-left" > {i18n.t('history.predictionname')}</td>
<td> {item.predictionTitle} </td>
</tr>
<tr>
<td> {i18n.t('history.predictionstarted')}</td>
<td> {startTime.toLocaleTimeString() + ' ' + startTime.toLocaleDateString()} </td>
</tr>
<tr>
<td> {i18n.t('history.predictionfinished')}</td>
<td> {endTime} </td>
</tr>
<tr>
{res}
</tr>
</tbody>
</Table>
</Tab.Pane>
)
}
render() {
// Translation item
const { t } = this.props;
if (!this.state.isFetchingData) {
var historyEntries = this.state.history;
historyEntries = historyEntries.reverse()
var tabs = historyEntries.map(this.createTabs);
var cols = historyEntries.map(this.createCols);
}
return (
<div className="container">
<div className="container-fluid">
<Tab.Container id="list-group-tabs-example" defaultActiveKey="explanation">
<Table striped className="prediction-list">
<Row key="Explanation">
<Col sm={4}>
<ListGroup.Item action eventKey="explanation">
{t('history.explanationtab')}
</ListGroup.Item>
{tabs}
</Col>
<Col sm={8}>
<Tab.Content>
<Tab.Pane eventKey="explanation">
{t('history.explanationcontent')}
</Tab.Pane>
{cols}
</Tab.Content>
</Col>
</Row>
</Table>
</Tab.Container>
</div>
</div>
)
}
}
export default withRouter(withTranslation()(History));
|
let a = 3;
let b = 5;
let res = a + b;
console.log('Resultado: ' + res);
a = 300
b = 400
console.log(a, b)
const c = 5
|
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const morgan = require("morgan");
const port = process.env.PORT || 3000;
let Consumer = require("./consumer");
app.use(morgan('combined'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
let consumer = new Consumer();
consumer.pullMessages();
});
|
(function () {
var copy = (function () {
var ipt = document.getElementById("wenhao-copy-textarea");
if (!ipt) {
ipt = document.createElement("textarea");
ipt.id = "wenhao-copy-textarea";
ipt.style.cssText = "opacity:0;position:absolute;";
document.body.appendChild(ipt);
}
return function (text) {
ipt.value = text;
ipt.select();
document.execCommand("copy");
}
})();
var toast = (function () {
var containerDom = document.getElementById("ahao-toast-container");
if (!containerDom) {
containerDom = document.createElement("div");
containerDom.id = "ahao-toast-container";
containerDom.style.cssText =
"margin-top:30px;position: fixed;z-index: 1000;top: 20px;left: 50%;transform: translateX(-50%);";
document.body.appendChild(containerDom);
}
return function (text) {
var boxDom = document.createElement("div");
boxDom.textContent = text;
boxDom.style.cssText =
"padding:5px 15px;background-color:#299a75;color:white;border-radius:5px;margin-top:7px;transition: all 0.5s;box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.3);";
containerDom.appendChild(boxDom);
setTimeout(() => {
boxDom.style.transform = "translateY(-100%)";
boxDom.style.opacity = "0";
setTimeout(() => {
containerDom.removeChild(boxDom);
}, 500);
}, 1500);
};
})();
var debounce = function (fn, delay, immediate = true) {
let timer = null
return function (...args) {
if (timer) clearTimeout(timer)
immediate && !timer && fn.apply(this, args)
timer = setTimeout(() => {
timer = null
!immediate && fn.apply(this, args)
}, delay)
}
}
var createTemplate = function (name, url, method, remark) {
var templ = `//${remark}\n export const ${name}= Simple.Store.create({\n url:'_host:/${url}',\n method:'${method}',\n params:{\n \n},\n dataFormat(type,params,json){\n return json\n}\n})\n \n`;
return templ;
};
var urlToName = function (url) {
return url
.split("/")
.pop()
.split(".")[0]
.split("-")
.reduce((total, n) => {
return total + (n.slice(0, 1).toUpperCase() + n.slice(1));
});
};
var init = function () {
document.querySelectorAll(".opblock-summary-path").forEach((n) => {
var btn = document.createElement("div");
var btn2 = document.createElement("div");
btn.textContent = "复制url";
btn.style.cssText =
"height:40px;margin-left:10px;padding:0 10px;border-radius:4px;display:flex;justify-content: center;align-items: center;background-color:green;color:white;";
btn2.textContent = "复制Store";
btn2.style.cssText =
"height:40px;padding:0 10px;margin-left:10px;border-radius:4px;display:flex;justify-content: center;align-items: center;background-color:green;color:white;";
n.parentNode.appendChild(btn);
n.parentNode.appendChild(btn2);
btn.addEventListener("click", function (e) {
var url = n.dataset.path;
copy(url);
toast("复制成功");
e.stopPropagation();
return false;
});
btn2.addEventListener("click", function (e) {
var name = urlToName(n.dataset.path);
var url = n.dataset.path;
var method = n.previousElementSibling.textContent;
var remark = n.nextElementSibling.textContent;
copy(createTemplate(name, url, method, remark));
toast("复制成功");
e.stopPropagation();
return false;
});
});
}
init();
document.getElementById('list').addEventListener('click', debounce(function (e) {
if (e.target.className && (~e.target.className.indexOf('node'))) {
var timer = setInterval(function () {
if (document.querySelectorAll(".opblock-summary-path")) {
clearInterval(timer)
init()
}
}, 200);
}
}, 400))
})();
|
const users = require('./users');
function login(req, res) {
// Get user credentials
const { email, password } = req.body;
// Authenticate the user
if (authenticate(email, password)) {
// Mark user session as authenticated
res.cookie('loggedInUser', email);
// Get return address
const returnTo = eval('(' + req.query.returnTo + ')');
// Redirect to the return address
res.redirect(returnTo.url);
} else {
// HTTP 401 when authentication fails
res.sendStatus(401);
}
}
function authenticate(email, password) {
// Try each user
for (let i = 0; i < users.length; ++i) {
// If email and password match
if (users[i].email === email && users[i].password === password) {
// Authentication successful
return true;
}
}
// If no user matched, authentication failed
return false;
}
module.exports = login;
|
#!/usr/bin/env node
'use strict';
const meow = require('meow');
const termSize = require('term-size');
meow(`
Example
$ term-size
143
24
First line is the number of columns
Second line is the number of rows
`);
const size = termSize();
console.log(`${size.columns}\n${size.rows}`);
|
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var handleErrors = require('./helpers/handleErrors');
var runSequence = require('run-sequence');
/**
* Build tasks
*
* Runs all the build tasks in this file from one command.
*
* Usage: gulp build
*/
gulp.task('build', function(callback) {
runSequence(
['sprite', 'iconfont', 'scripts'],
['styles', 'copysvg', 'copyimages'],
callback);
});
/**
* Copy svgs into /dist
*
* Usage: gulp copysvg
*/
gulp.task('copysvg', function () {
return gulp.src('src/svg/**/*.svg')
.pipe(gulp.dest('dist/svg'));
});
/**
* Copy images into /dist
*
* Usage: gulp copyimages
*/
gulp.task('copyimages', function () {
return gulp.src('src/images/**/*.{jpg,png,gif}')
.pipe(gulp.dest('dist/images'));
});
|
importApi("ui");
importClass("android.widget.BaseAdapter");
var listXml = require('raw!./list.xml');
var listItemXml = require('raw!./list/listItem.xml');
var page = {
onLoad : function () {
var listView = ui.find("listView");
listView.setAdapter(new BaseAdapter({
getCount : function() {
return 80;
},
getView : function(position, convertView, parent){
if(convertView == null){
convertView = ui.fromXml(listItemXml, null);
}
return convertView;
},
getViewTypeCount : function () {
return 1;
}
}));
}
};
hybridView.onLoad = function(result){
page.onLoad();
};
hybridView.loadXml(listXml);
|
console.log('content injecte edildi')
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.action == "changePlayRate") {
console.log(request.value)
document.querySelector("video").playbackRate = request.value;
}
})
|
import styled from "styled-components"
export const StoreButtonWrapper = styled.img`
height: 40px;
margin-left: 20px;
`
|
export const reactRoutes = [
{
name: "Product Detail Page",
path: "/products",
children: [
":identifier",
]
},
]
|
import React, { Component } from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import Case from './containers/Case'
import Main from './containers/main/Main'
class App extends Component {
render() {
return (
<Router>
<Switch>
<Route exact path="/case/:slug" component={() => <Case />} />
<Route path="/" component={Main} />
</Switch>
</Router>
);
}
}
export default App
|
$('document').ready(function(){
$('.mobile-tab').hide();
$('.Tip1').on('click',function(){
var currentTip = $('.current');
currentTip.removeClass('current');
$('.Tip1').addClass('current');
});
$('.Tip2').on('click',function(){
var currentTip = $('.current');
currentTip.removeClass('current');
$('.Tip2').addClass('current');
});
$('.Tip3').on('click',function(){
var currentTip = $('.current');
currentTip.removeClass('current');
$('.Tip3').addClass('current');
});
$('.Tip4').on('click',function(){
var currentTip = $('.current');
currentTip.removeClass('current');
$('.Tip4').addClass('current');
});
$('.Tip5').on('click',function(){
var currentTip = $('.current');
currentTip.removeClass('current');
$('.Tip5').addClass('current');
});
$('#next').on('click',function(){
var currentTip = $('.current');
var currentTipIndex = $('.current').index();
var NextTipIndex = currentTipIndex + 1;
var NextTip = $('.sliderTip').eq(NextTipIndex);
currentTip.removeClass('current');
if((NextTipIndex) == ($('.sliderTip:last').index()+1)){
$('.sliderTip').eq(0);
$('.sliderTip').eq(0).addClass('current');
}else{
NextTip.addClass('current');
}
});
$('#previous').on('click',function(){
var currentTip = $('.current');
var currentTipIndex = $('.current').index();
var PrevTipIndex = currentTipIndex - 1;
var PrevTip = $('.sliderTip').eq(PrevTipIndex);
currentTip.removeClass('current');
if((PrevTipIndex) == ($('.sliderTip:first').index()-1)){
$('.sliderTip').eq(4);
$('.sliderTip').eq(4).addClass('current');
}else{
PrevTip.addClass('current');
}
});
$('#burg').on('click',function(){
$('#burg').slideToggle(300);
$('.mobile-tab').slideToggle(300);
});
});
|
//index.js
//获取应用实例
var app = getApp()
var oilKm = 0,oilPrice = 0,oilTotalPrice=0,oilMass=0,priceKm=0,kmOil=0;
Page({
data: {
oneKm:" ",
oneOil:" ",
onePrice:" ",
twoKm:" ",
twoTotalPrice:" ",
twoPrice:" "
},
onLoad: function () {
},
bindOneKmInput:function(e){
this.setData({
oneKm:e.detail.value
})
},
bindOneOilInput:function(e){
this.setData({
oneOil:e.detail.value
})
},
bindOnePriceInput:function(e){
this.setData({
onePrice:e.detail.value
})
},
calOneMethod:function(e){
oilKm = this.data.oneOil/this.data.oneKm
oilPrice=this.data.onePrice
oilTotalPrice = this.data.oneOil*this.data.onePrice
oilMass = this.data.oneOil
priceKm = oilTotalPrice/this.data.oneKm
kmOil = this.data.oneKm/this.data.oneOil
wx.navigateTo({
url: '../detail/detail?priceKm='+priceKm+'&oilKm='+oilKm+'&oilPrice='+oilPrice+'&oilTotalPrice='+oilTotalPrice+'&oilMass='+oilMass+'&kmOil='+kmOil+"&isSave=0"
})
},
resetOneMethod:function(e){
this.setData({
oneKm:" ",
oneOil:" ",
onePrice:" "
})
},
bindTwoKmInput:function(e){
this.setData({
twoKm:e.detail.value
})
},
bindTwoTotalPriceInput:function(e){
this.setData({
twoTotalPrice:e.detail.value
})
},
bindTwoPriceInput:function(e){
this.setData({
twoPrice:e.detail.value
})
},
calTwoMethod:function(e){
oilKm = this.data.twoTotalPrice/this.data.twoPrice/this.data.twoKm
oilPrice=this.data.twoPrice
oilTotalPrice = this.data.twoTotalPrice
oilMass = this.data.twoTotalPrice/this.data.twoPrice
priceKm = oilTotalPrice/this.data.twoKm
kmOil = this.data.twoKm/oilMass
console.log(priceKm)
wx.navigateTo({
url: '../detail/detail?priceKm='+priceKm+'&oilKm='+oilKm+'&oilPrice='+oilPrice+'&oilTotalPrice='+oilTotalPrice+'&oilMass='+oilMass+'&kmOil='+kmOil
})
},
resetTwoMethod:function(e){
this.setData({
twoKm:" ",
twoTotalPrice:" ",
twoPrice:" "
})
}
})
|
var express = require("express");
var logger = require("morgan");
var bodyParser = require("body-parser");
var session = require('express-session');
// var passport = require('passport');
// var LocalStrategy = require('passport-local').Strategy;
// var bcrypt = require('bcryptjs')
var appCtrl = require('./controllers/rewards.controller');
var Store = require('./models/store.model');
var db = require('mongoose');
var app = express();
// Configure Morgan
app.use(logger('dev'));
// Configure Database
db.connect('mongodb://localhost/rewardsprogram/');
// Configure Body-Parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Configure Express Session
app.use(express.static(__dirname + '/rewards-portal'));
app.use(express.static(__dirname + '/rewards-manager'));
app.use(express.static(__dirname + '/rewards-cashier'));
app.use(express.static(__dirname + '/rewards-customer'));
app.sessionMiddleware = session({
secret: 'secret',
resave: false,
saveUninitialized: true,
})
app.use(app.sessionMiddleware)
// app.use(passport.initialize());
// app.use(passport.session());
// Socket IO Configuration
var http = require('http').Server(app);
var io = require('socket.io')(http);
// passport.serializeUser(function(user, done) {
// done(null, user.id);
// });
// passport.deserializeUser(function(id, done) {
// Store.Cashier.findById(id, function(err, user) {
// done(err, user);
// });
// });
// // Configure B-Crypt
// passport.use(new LocalStrategy(
// function(username, password, done) {
// Store.Cashier.findOne({ username: username }, function (err, user) {
// if (err) { return done(err); }
// if (!user) {
// return done(null, false);
// }
// bcrypt.compare(password, user.password, function(error, response){
// if (response === true){
// return done(null,user)
// }
// else {
// return done(null, false)
// }
// })
// });
// }
// ));
// // Authentication
// app.isAuthenticated = function(req, res, next){
// // If the current user is logged in...
// if(req.isAuthenticated()){
// // Middleware allows the execution chain to continue.
// return next();
// }
// // If not, redirect to login
// console.log('get outta here!')
// res.redirect('/');
// }
// app.isAuthenticatedAjax = function(req, res, next){
// // If the current user is logged in...
// if(req.isAuthenticated()){
// // Middleware allows the execution chain to continue.
// return next();
// }
// // If not, redirect to login
// res.send({error:'not logged in'});
// }
// Page Routes
app.get('/', appCtrl.portalPage);
app.get('/:role', appCtrl.loginPage);
// app.get('/logout', appCtrl.logoffCashier); //cashier log off
// API Routes
// app.post('/api/session', appCtrl.loginCashier); //cashier log in
app.get('/api/customers', appCtrl.getCustomers); //get all customers
app.get('/api/customers/:phone', appCtrl.findCustomer); //get current customer info
app.post('/api/customers', appCtrl.registerCustomer); //create new customer
app.put('/api/customers/:_id', appCtrl.changeCustomer); //update customer data
app.delete('/api/customers/:_id', appCtrl.removeCustomer); //remove customer
app.get('/api/prizes', appCtrl.getPrizes); //get all prizes
app.post('/api/prizes', appCtrl.registerPrize); //create new prize
app.put('/api/prizes/:_id', appCtrl.editPrize); //edit prize
app.delete('/api/prizes/:_id', appCtrl.removePrize); //remove prize
// Socket
io.on('connection', appCtrl.reward);
var port = 1337;
http.listen(port, function() {
console.log('Server running on port ' + port);
})
|
export default {
caption: 'IISMyTestApplicationEmberComputerE',
'serialNumber-caption': 'serialNumber',
'manufactureDate-caption': 'manufactureDate',
'type-caption': 'type',
'description-caption': 'description',
'computerPart-caption': 'computerPart'
};
|
import React, { Component } from "react";
import styles from "./ComicDescription.scss";
export default class ComicDescription extends Component {
constructor(props) {
super(props);
this.state = {
comic: this.props.details
};
}
render() {
const { comic } = this.state;
return (
<div className="comic-description-container">
<h2>Description</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quae, rem, itaque ad sapiente hic delectus ipsum amet corrupti, eum laboriosam molestiae perferendis cum. Aspernatur consequuntur, ad amet labore numquam sint?</p>
<h2>{comic.comicStatus}</h2>
</div>
);
}
}
|
import { helloWorld } from './core/helloWorld'
helloWorld();
|
/**
* LINKURIOUS CONFIDENTIAL
* __________________
*
* [2012] - [2014] Linkurious SAS
* All Rights Reserved.
*
*/
'use strict';
// ext libs
const Promise = require('bluebird');
// services
const LKE = require('../../index');
const Utils = LKE.getUtils();
const Errors = LKE.getErrors();
const Access = LKE.getAccess();
const VisualizationDAO = LKE.getVisualizationDAO();
const VisualizationShareDAO = LKE.getVisualizationShareDAO();
const WidgetDAO = LKE.getWidgetDAO();
// locals
const api = require('../api');
module.exports = function(app) {
app.all('/api/:dataSource/visualizations*', api.proxy(req => {
return Access.isAuthenticated(req);
}));
app.all('/api/:dataSource/sandbox*', api.proxy(req => {
return Access.isAuthenticated(req);
}));
/**
* @api {get} /api/:dataSource/visualizations/shared Get visualizations shared with current user
* @apiName sharedVisualizations
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission apiright:visualization.list
*
* @apiDescription Get all visualizations shared with the current user
*
* @apiParam {string} dataSource key of a data-source
*
* @apiSuccess {string} title Title of the visualization
* @apiSuccess {number} visualizationId ID of the visualization
* @apiSuccess {number} ownerId ID of the user that owns the visualization
* @apiSuccess {string} sourceKey Key of the dataSource the visualization is related to
*/
app.get('/api/:dataSource/visualizations/shared', api.respond(req => {
if (!VisualizationShareDAO) { return Promise.resolve(); }
return VisualizationShareDAO.getSharedWithMe(
req.param('dataSource'),
Access.getUserCheck(req, 'visualization.list')
);
}));
/**
* @api {post} /api/:dataSource/visualizations/folder Create a visualization folder
* @apiName createVisualizationFolder
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission apiright:visualizationFolder.create
*
* @apiDescription Create a folder for visualizations
*
* @apiParam {String} title Folder title
* @apiParam {Number} parent Parent folder id
* @apiParam {string} dataSource key of a data-source
*
*/
app.post('/api/:dataSource/visualizations/folder', api.respond(req => {
return VisualizationDAO.createFolder(
req.param('title'),
req.param('parent', null),
req.param('dataSource'),
Access.getUserCheck(req, 'visualizationFolder.create')
).then(r => ({folder: r}));
}, 201));
/**
* @api {patch} /api/:dataSource/visualizations/folder/:id Update a visualization folder
* @apiName updateVisualizationFolder
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission apiright:visualizationFolder.edit
*
* @apiDescription Update a property of a folder
*
* @apiParam {string} key Property key to edit
* @apiParam {string} value Property new value of the edited property
* @apiParam {string} dataSource key of a data-source (for API homogeneity, not actually used)
*
*/
app.patch('/api/:dataSource/visualizations/folder/:id', api.respond(req => {
return VisualizationDAO.updateFolder(
req.param('id'),
req.param('key'),
req.param('value', null),
Access.getUserCheck(req, 'visualizationFolder.edit')
).then(r => ({folder: r}));
}));
/**
* @api {delete} /api/:dataSource/visualizations/folder/:id Delete a visualization folder
* @apiName deleteVisualizationFolder
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission apiright:visualizationFolder.delete
*
* @apiDescription Remove the specified folder and its children (visualizations and sub-folders)
*
* @apiParam {number} visualization ID
* @apiParam {string} dataSource key of a data-source (for API homogeneity, not actually used)
*
*/
app.delete('/api/:dataSource/visualizations/folder/:id', api.respond(req => {
return VisualizationDAO.removeFolder(
req.param('id'),
Access.getUserCheck(req, 'visualizationFolder.delete')
);
}, 204));
/**
* @api {get} /api/:dataSource/visualizations/tree Get the visualization tree
* @apiName getVisualizationTree
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission apiright:visualization.list
* @apiDescription Return visualizations ordered with folders hierarchy.
*
* @apiParam {string} dataSource key of a data-source
*
* @apiSuccess {Object} response
* @apiSuccess {Object[]} response.tree
* @apiSuccess {string} response.tree.type `"visu"` or `"folder"`
* @apiSuccess {number} response.tree.id visualization or folder ID
* @apiSuccess {string} response.tree.title visualization or folder title
* @apiSuccess {object[]} [response.tree.children] children visualizations and folders
* (mandatory when `type` is `"folder"`)
* @apiSuccess {number} [response.tree.shareCount] number of users a visualization is shared with
* (mandatory `type` is `"visu"`)
* @apiSuccess {string} [response.tree.widgetKey] key of the widget created for this visualization
* (possible if `type` is `"visu"`)
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "tree": [
* {
* "id": 1,
* "type": "folder",
* "title": "Toto",
* "children": [
* {
* "id": 2,
* "type": "folder",
* "title": "Titi",
* "children": [
* {
* "id": 3,
* "type": "visu",
* "title": "vis. three",
* "shareCount": 0,
* "widgetKey": "aef3ce"
* }
* ]
* },
* {
* "id": 1,
* "type": "vis. one",
* "title": "a",
* "shareCount": 0
* },
* {
* "id": 2,
* "type": "visu",
* "title": "vis. two",
* "shareCount": 0
* }
* ]
* },
* {
* "id": 4,
* "type": "visu",
* "title": "vis. four",
* "shareCount": 0
* }
* ]
* }
*/
app.get('/api/:dataSource/visualizations/tree', api.respond(req => {
return VisualizationDAO.getTree(
req.param('dataSource'),
Access.getUserCheck(req, 'visualization.list')
).then(r => ({tree: r}));
}));
/**
* @api {get} /api/:dataSource/visualizations/count Get visualizations count
* @apiName GetVisualizationCount
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiDescription Get the number of visualizations for this data-source.
*
* @apiParam {string} dataSource key of a data-source
*
* @apiSuccess {number} count
*/
app.get('/api/:dataSource/visualizations/count', api.respond(req => {
const wrappedUser = Access.getCurrentWrappedUser(req);
wrappedUser.canSeeDataSource(req.param('dataSource'));
return VisualizationDAO.getVisualizationCount(
req.param('dataSource')
).then(count => ({count: count}));
}));
/**
* @api {get} /api/:dataSource/visualizations/:id Get a visualization
* @apiName GetVisualization
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission apiright:visualization.read
*
* @apiDescription Return a visualization selected by ID.
*
* @apiParam {string} dataSource Key of the data-source
* @apiParam {number} id ID of the isualization
* @apiParam {boolean} [populated=false] Whether nodes and edges are populated of data, categories, version, type, source and target
* @apiParam {boolean} [with_digest=false] Whether to include the adjacency digest in the returned nodes
* @apiParam {boolean} [with_degree=false] Whether to include the degree in the returned nodes
*
* @apiSuccess {object} visualization The visualization
* @apiSuccess {number} visualization.id ID of the visualization
* @apiSuccess {string} visualization.title Title of the visualization
* @apiSuccess {number} visualization.folder Parent visualizationFolder ID (-1 for root folder)
* @apiSuccess {object[]} visualization.nodes Nodes in this visualization
* @apiSuccess {string} visualization.nodes.id ID of the node (native or alternative ID)
* @apiSuccess {number} visualization.nodes.nodelink The node position (in "nodelink" mode)
* @apiSuccess {number} visualization.nodes.nodelink.x X coordinate of the node
* @apiSuccess {number} visualization.nodes.nodelink.y Y coordinate of the node
* @apiSuccess {number} visualization.nodes.geo The node position (in "geo" mode)
* @apiSuccess {number} [visualization.nodes.geo.latitude] Latitude of the node (decimal format)
* @apiSuccess {number} [visualization.nodes.geo.longitude] Longitude of the node (decimal format)
* @apiSuccess {number} visualization.nodes.geo.latitudeDiff Latitude diff (if the node has been dragged)
* @apiSuccess {number} visualization.nodes.geo.longitudeDiff Longitude diff (if the node has been dragged)
* @apiSuccess {boolean} visualization.nodes.selected Whether the node is selected
* @apiSuccess {object} [visualization.nodes.data] Properties of the node
* @apiSuccess {string[]} [visualization.nodes.categories] Categories of the node
* @apiSuccess {object} [visualization.nodes.statistics] Statistics of the node
* @apiSuccess {type:LkDigestItem[]} [visualization.nodes.statistics.digest] Statistics of the neighborhood of the node
* @apiSuccess {number} [visualization.nodes.statistics.degree] Number of neighbors of the node readable by the current user
* @apiSuccess {number} [visualization.nodes.version] Version of the node
* @apiSuccess {object[]} visualization.edges Edges in this visualization
* @apiSuccess {string} visualization.edges.id ID of the edge (native or alternative ID)
* @apiSuccess {boolean} visualization.edges.selected Whether the edge is selected
* @apiSuccess {string} [visualization.edges.type] Type of the edge
* @apiSuccess {object} [visualization.edges.data] Properties of the edge
* @apiSuccess {string} [visualization.edges.source] Source of the edge
* @apiSuccess {string} [visualization.edges.target] Target of the edge
* @apiSuccess {number} [visualization.edges.version] Version of the edge
* @apiSuccess {object} visualization.design Design
* @apiSuccess {object} visualization.design.styles Style mappings
* @apiSuccess {object} visualization.design.palette Color and icon palette
* @apiSuccess {string="nodelink","geo"} visualization.mode The current interaction mode
* @apiSuccess {object} visualization.layout The last used layout
* @apiSuccess {string} visualization.layout.algorithm Layout algorithm name (`"force"`, `"hierarchical"`)
* @apiSuccess {string} visualization.layout.mode Layout algorithm mode (depends on the algorithm)
* @apiSuccess {string} [visualization.layout.incremental] Whether the layout is incremental (only for `"force"` algorithm)
* @apiSuccess {object} visualization.geo Geographical info
* @apiSuccess {string} [visualization.geo.latitudeProperty] Property name containing the latitude
* @apiSuccess {string} [visualization.geo.latitudeProperty] Property name containing the longitude
* @apiSuccess {string[]} visualization.geo.layers Names of enabled leaflet tile layers
* @apiSuccess {string} createdAt Creation date in ISO-8601 format
* @apiSuccess {string} updatedAt Last update date in ISO-8601 format
* @apiSuccess {object} visualization.alternativeIds Used to reference nodes or edges by a property instead of their database ID
* @apiSuccess {string} [visualization.alternativeIds.node] Node property to use as identifier instead of database ID
* @apiSuccess {string} [visualization.alternativeIds.edge] Edge property to use as identifier instead of database ID
* @apiSuccess {object[]} visualization.filters Filters
* @apiSuccess {string="node.data.categories","node.data.properties.propertyName","edge.data.type","edge.data.properties.propertyName","geo-coordinates"} visualization.filters.key Key of the filter
* @apiSuccess {string[]} [visualization.filters.values] Values of the filter (no values for `"geo-coordinates"`)
* @apiSuccess {string} visualization.sourceKey Key of the data-source
* @apiSuccess {object} visualization.user Owner of the visualization
* @apiSuccess {number} visualization.userId ID of the owner of the visualization
* @apiSuccess {string} visualization.widgetKey Key of the widget (`null` if the no widget exists)
* @apiSuccess {boolean} visualization.sandbox Whether the visualization is the sandbox
* @apiSuccess {string} visualization.right Right on the visualization of the current user
* @apiSuccess {object} visualization.nodeFields Captions and fields options
* @apiSuccess {object} visualization.nodeFields.captions Caption descriptions indexed by node category
* @apiSuccess {object} visualization.nodeFields.captions.nodeCategory `nodeCategory` is a placeholder for the actual node category
* @apiSuccess {boolean} visualization.nodeFields.captions.nodeCategory.active Whether to use this caption
* @apiSuccess {boolean} visualization.nodeFields.captions.nodeCategory.displayName Whether to include the node category in the caption
* @apiSuccess {string[]} visualization.nodeFields.captions.nodeCategory.properties List of properties to include in the caption
* @apiSuccess {object[]} visualization.nodeFields.fields Fields listed in context menu
* @apiSuccess {string} visualization.nodeFields.fields.name Name of the field
* @apiSuccess {boolean} visualization.nodeFields.fields.active Whether the field is visible in the context menu
* @apiSuccess {object} visualization.edgeFields Captions and fields options
* @apiSuccess {object} visualization.edgeFields.captions Caption descriptions indexed by edge type
* @apiSuccess {object} visualization.edgeFields.captions.edgeType `edgeType` is a placeholder for the actual edge type
* @apiSuccess {boolean} visualization.edgeFields.captions.edgeType.active Whether to use this caption
* @apiSuccess {boolean} visualization.edgeFields.captions.edgeType.displayName Whether to include the edge type in the caption
* @apiSuccess {string[]} visualization.edgeFields.captions.edgeType.properties List of properties to include in the caption
* @apiSuccess {object[]} visualization.edgeFields.fields Fields listed in context menu
* @apiSuccess {string} visualization.edgeFields.fields.name Name of the field
* @apiSuccess {boolean} visualization.edgeFields.fields.active Whether the field is visible in the context menu
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "visualization": {
* "id": 2,
* "version": 2,
* "title": "Viz name",
* "folder": -1,
* "nodes": [
* {
* "id": 1,
* "nodelink": {
* "x": 10.124,
* "y": 12.505
* },
* "geo": {
* "latitudeDiff": 0,
* "longitudeDiff": 0
* },
* "selected": true,
* "data": {
* "firstName": "David"
* },
* "categories": [
* "Person"
* ],
* "statistics": {
* "digest": [
* {
* "edgeType": "worksAt",
* "nodeCategories": [
* "Company"
* ],
* "nodes": 1,
* "edges": 1
* }
* ]
* },
* "version": 1
* },
* {
* "id": 2,
* "nodelink": {
* "x": -6.552,
* "y": -8.094
* },
* "geo": {
* "latitudeDiff": 0,
* "longitudeDiff": 0
* },
* "data": {
* "name": "Linkurious"
* },
* "categories": [
* "Company"
* ],
* "statistics": {
* "digest": [
* {
* "edgeType": "worksAt",
* "nodeCategories": [
* "Person"
* ],
* "nodes": 1,
* "edges": 1
* }
* ]
* },
* "version": 1
* }
* ],
* "edges": [
* {
* "id": 0,
* "type": "worksAt",
* "data": {},
* "source": 1,
* "target": 2,
* "version": 1
* }
* ],
* "nodeFields": {
* "fields": [
* {
* "name": "firstName",
* "active": true
* },
* {
* "name": "name",
* "active": true
* }
* ],
* "captions": {
* "Person": {
* "active": true,
* "displayName": true,
* "properties": []
* },
* "Company": {
* "active": true,
* "displayName": true,
* "properties": []
* },
* "No category": {
* "active": true,
* "displayName": true,
* "properties": []
* }
* }
* },
* "edgeFields": {
* "fields": [],
* "captions": {
* "worksAt": {
* "name": "worksAt",
* "active": true,
* "displayName": true,
* "properties": []
* }
* }
* },
* "design": {
* // ...
* },
* "filters": [
* {
* "key": "node.data.properties.firstName",
* "values": ["David"]
* }
* ],
* "sourceKey": "860555c4",
* "user": {
* "id": 1,
* "username": "Unique user",
* "email": "user@linkurio.us",
* "source": "local",
* "preferences": {
* "pinOnDrag": false,
* "locale": "en-US"
* }
* },
* "userId": 1,
* "sandbox": false,
* "createdAt": "2017-06-01T12:30:40.397Z",
* "updatedAt": "2017-06-01T12:30:55.389Z",
* "alternativeIds": {},
* "mode": "nodelink",
* "layout": {
* "incremental": false,
* "algorithm": "force",
* "mode": "fast"
* },
* "geo": {
* "layers": []
* },
* "right": "owner",
* "widgetKey": null
* }
* }
*/
app.get('/api/:dataSource/visualizations/:id', api.respond(req => {
return VisualizationDAO.getById(
req.param('id'),
Utils.parseBoolean(req.query.populated),
Access.getUserCheck(req, 'visualization.read'),
{
withDigest: Utils.parseBoolean(req.param('with_digest')),
withDegree: Utils.parseBoolean(req.param('with_degree'))
}
).then(r => ({visualization: r}));
}));
/**
* @api {post} /api/:dataSource/visualizations Create a visualization
* @apiName CreateVisualization
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiDescription Create a new visualization.
* @apiPermission authenticated
* @apiPermission apiright:visualization.create
*
* @apiParam {string} dataSource Key of the data-source containing the nodes and edges.
* @apiParam {string} title Title of the new visualization.
* @apiParam {number} [folder=-1] ID of the folder to save the visualization in. (`-1` for root)
* @apiParam {object[]} nodes Nodes in this visualization.
* @apiParam {string} nodes.id Identifier of the node (native ID or alternative ID, see `alternativeIds`).
* @apiParam {boolean} [nodes.selected] Whether the node is selected.
* @apiParam {object} nodes.nodelink The node position information (in "nodelink" mode).
* @apiParam {number} nodes.nodelink.x X coordinate of the node.
* @apiParam {number} nodes.nodelink.y Y coordinate of the node.
* @apiParam {boolean} [nodes.nodelink.fixed] Whether the node position has been locked.
* @apiParam {object} [nodes.geo] The node position information (in "geo" mode).
* @apiParam {number} [nodes.geo.latitude] Latitude of the node (decimal format).
* @apiParam {number} [nodes.geo.longitude] Longitude of the node (decimal format).
* @apiParam {number} [nodes.geo.latitudeDiff] Latitude diff (if the node has been dragged).
* @apiParam {number} [nodes.geo.longitudeDiff] Longitude diff (if the node has been dragged).
* @apiParam {object[]} edges Edges in this visualization.
* @apiParam {string} edges.id Identifier of the edge (native ID or alternative ID, see `alternativeIds`).
* @apiParam {boolean} [edges.selected] Whether the edge is selected
* @apiParam {object} [alternativeIds] If nodes and/or edges should be referenced by a property instead of their database ID.
* @apiParam {string} [alternativeIds.node] Node property to use as identifier instead of database ID.
* @apiParam {string} [alternativeIds.edge] Edge property to use as identifier instead of database ID.
* @apiParam {object} [layout] The last layout used.
* @apiParam {string="force","hierarchical"} [layout.algorithm] Layout algorithm.
* @apiParam {string} [layout.mode] Layout algorithm mode (depends on algorithm).
* @apiParam {boolean} [layout.incremental] Whether the layout is incremental (only for `"force"` algorithm).
* @apiParam {string="nodelink","geo"} [mode="nodelink"] The current interaction mode.
* @apiParam {object} [geo] Geographical info.
* @apiParam {string} [geo.latitudeProperty] Node property containing the latitude info.
* @apiParam {string} [geo.longitudeProperty] Node property containing the longitude info.
* @apiParam {string[]} [geo.layers] Names of used leaflet tile layers.
* @apiParam {object} [design] Design.
* @apiParam {object} design.styles Color, size and icon mapping.
* @apiParam {object} design.palette Color and icon palette.
* @apiParam {object[]} [filters] Filters.
* @apiParam {object} nodeFields Captions and fields options
* @apiParam {object} nodeFields.captions Caption descriptions indexed by node-category.
* @apiParam {boolean} nodeFields.captions.*.active Whether to use this caption.
* @apiParam {boolean} nodeFields.captions.*.displayName Whether to include the node-category in the caption.
* @apiParam {string[]} nodeFields.captions.*.properties List of properties to include in the caption.
* @apiParam {object[]} nodeFields.fields Fields listed in context menu.
* @apiParam {string} nodeFields.fields.name Name of the field.
* @apiParam {boolean} nodeFields.fields.active Whether the field is visible in the context menu.
* @apiParam {object} edgeFields Captions and fields options
* @apiParam {object} edgeFields.captions Caption descriptions indexed by edge-type.
* @apiParam {boolean} edgeFields.captions.*.active Whether to use this caption.
* @apiParam {boolean} edgeFields.captions.*.displayName Whether to include the edge-type in the caption.
* @apiParam {string[]} edgeFields.captions.*.properties List of properties to include in the caption.
* @apiParam {object[]} edgeFields.fields Fields listed in context menu.
* @apiParam {string} edgeFields.fields.name Name of the field.
* @apiParam {boolean} edgeFields.fields.active Whether the field is visible in the context menu.
*
* @apiSuccess {object} visualization The visualization object.
* @apiSuccess {string} visualization.title Title of the visualization
* @apiSuccess {number} visualization.folder Parent visualizationFolder ID (`null` for root folder)
* @apiSuccess {object[]} visualization.nodes Nodes in this visualization.
* @apiSuccess {string} visualization.nodes.id Identifier of the node (native ID or alternative ID, see `alternativeIds`).
* @apiSuccess {boolean} visualization.nodes.selected Whether the node is selected.
* @apiSuccess {number} visualization.nodes.nodelink The node position information (in "nodelink" mode).
* @apiSuccess {number} visualization.nodes.nodelink.x X coordinate of the node.
* @apiSuccess {number} visualization.nodes.nodelink.y Y coordinate of the node.
* @apiSuccess {boolean} visualization.nodes.nodelink.fixed Whether the node position has been locked.
* @apiSuccess {number} visualization.nodes.geo The node position information (in "geo" mode).
* @apiSuccess {number} visualization.nodes.geo.latitude Latitude of the node (decimal format).
* @apiSuccess {number} visualization.nodes.geo.longitude Longitude of the node (decimal format).
* @apiSuccess {number} visualization.nodes.geo.latitudeDiff Latitude diff (if the node has been dragged).
* @apiSuccess {number} visualization.nodes.geo.longitudeDiff Longitude diff (if the node has been dragged).
* @apiSuccess {object[]} visualization.edges Edges in this visualization.
* @apiSuccess {string} visualization.edges.id Identifier of the edge (native ID or alternative ID, see `alternativeIds`).
* @apiSuccess {boolean} visualization.edges.selected Whether the edge is selected
* @apiSuccess {object} visualization.alternativeIds Used to reference nodes or edges by a property instead of their database ID.
* @apiSuccess {string} visualization.alternativeIds.node Node property to use as identifier instead of database ID.
* @apiSuccess {string} visualization.alternativeIds.edge Edge property to use as identifier instead of database ID.
* @apiSuccess {object} visualization.layout The last used layout.
* @apiSuccess {string} visualization.layout.algorithm Layout algorithm name ("force", "hierarchical").
* @apiSuccess {string} visualization.layout.mode Layout algorithm mode (depends on algorithm).
* @apiSuccess {string} visualization.layout.incremental Whether the layout is incremental (only for `"force"` algorithm).
* @apiSuccess {object} visualization.geo Geographical info.
* @apiSuccess {string} visualization.geo.latitudeProperty Node property containing the latitude.
* @apiSuccess {string} visualization.geo.latitudeProperty Node property containing the longitude.
* @apiSuccess {string[]} visualization.geo.layers Names of enabled leaflet tile layers.
* @apiSuccess {string="nodelink","geo"} visualization.mode The current interaction mode.
* @apiSuccess {object} visualization.design Design.
* @apiSuccess {object} visualization.design.styles Style mappings.
* @apiSuccess {object} visualization.design.palette Color and icon palette.
* @apiSuccess {object[]} visualization.filters Filters.
* @apiSuccess {object} visualization.nodeFields Captions and fields options
* @apiSuccess {object} visualization.nodeFields.captions Caption descriptions indexed by node-category.
* @apiSuccess {boolean} visualization.nodeFields.captions.*.active Whether to use this caption.
* @apiSuccess {boolean} visualization.nodeFields.captions.*.displayName Whether to include the node-category in the caption.
* @apiSuccess {string[]} visualization.nodeFields.captions.*.properties List of properties to include in the caption.
* @apiSuccess {object[]} visualization.nodeFields.fields Fields listed in context menu.
* @apiSuccess {string} visualization.nodeFields.fields.name Name of the field.
* @apiSuccess {boolean} visualization.nodeFields.fields.active Whether the field is visible in the context menu.
* @apiSuccess {object} visualization.edgeFields Captions and fields options
* @apiSuccess {object} visualization.edgeFields.captions Caption descriptions indexed by edge-type.
* @apiSuccess {boolean} visualization.edgeFields.captions.*.active Whether to use this caption.
* @apiSuccess {boolean} visualization.edgeFields.captions.*.displayName Whether to include the edge-type in the caption.
* @apiSuccess {string[]} visualization.edgeFields.captions.*.properties List of properties to include in the caption.
* @apiSuccess {object[]} visualization.edgeFields.fields Fields listed in context menu.
* @apiSuccess {string} visualization.edgeFields.fields.name Name of the field.
* @apiSuccess {boolean} visualization.edgeFields.fields.active Whether the field is visible in the context menu.
*/
app.post('/api/:dataSource/visualizations', api.respond(req => {
return VisualizationDAO.createVisualization({
title: req.param('title'),
folder: req.param('folder', null),
nodes: req.param('nodes', []),
edges: req.param('edges', []),
nodeFields: req.param('nodeFields'),
edgeFields: req.param('edgeFields'),
design: req.param('design', null),
filters: req.param('filters', []),
sourceKey: req.param('dataSource'),
alternativeIds: req.param('alternativeIds', {}),
mode: req.param('mode', 'nodelink'),
layout: req.param('layout'),
geo: req.param('geo')
}, Access.getUserCheck(req, 'visualization.create')).then(
r => ({visualization: r})
);
}, 201));
/**
* @api {post} /api/:dataSource/visualizations/:id/duplicate Duplicate a visualization
* @apiName DuplicateVisualization
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission apiright:visualization.create
* @apiDescription Duplicates a visualization.
*
* @apiParam {String} dataSource key of a data-source
* @apiParam {number} id The id of the visualization to duplicate
* @apiParam {string} [title] Name of the created visualization (defaults to "Copy of [source title]").
* @apiParam {number} [folder] ID of the folder to duplicate the visualization to (defaults to the source visualization's folder).
*/
app.post('/api/:dataSource/visualizations/:id/duplicate', api.respond(req => {
return VisualizationDAO.duplicateVisualization(
{
id: Utils.tryParsePosInt(req.param('id'), 'id'),
folderId: Utils.tryParseNumber(req.param('folder'), 'folder', true),
title: req.param('title')
},
Access.getUserCheck(req, 'visualization.create')
);
}, 201));
/**
* @api {patch} /api/:dataSource/visualizations/:id Update a visualization
* @apiName UpdateVisualization
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission apiright:visualization.edit
* @apiDescription Update visualization selected by id.
*
* @apiParam {string} dataSource key of a data-source (ignored in this API)
* @apiParam {Number} id Visualization ID.
* @apiParam {object} visualization The visualization object. Only passed fields will be updated.
* @apiParam {boolean} [force_lock=false] Take the edit-lock by force
* (in case the current user doesn't own it)
* @apiParam {boolean} [do_layout=false] Do a server-side layout of the visualization graph.
*/
app.patch('/api/:dataSource/visualizations/:id', api.respond(req => {
return VisualizationDAO.updateVisualization(
Utils.tryParsePosInt(req.param('id'), 'id'),
req.param('visualization'),
{
forceLock: Utils.parseBoolean(req.param('force_lock')),
doLayout: Utils.parseBoolean(req.param('do_layout'))
},
Access.getUserCheck(req, 'visualization.edit')
).return(undefined);
}, 204));
/**
* @api {delete} /api/:dataSource/visualizations/:id Delete a visualization
* @apiName DeleteVisualization
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission apiright:visualization.delete
* @apiDescription Delete the visualization selected by id.
*
* @apiParam {string} dataSource Key of the data-source
* @apiParam {number} id ID of the visualization
*
* @apiSuccessExample {none} Success-Response:
* HTTP/1.1 204 No Content
*/
app.delete('/api/:dataSource/visualizations/:id', api.respond(req => {
return VisualizationDAO.removeById(
req.param('id'),
Access.getUserCheck(req, 'visualization.delete')
);
}, 204));
/**
* @api {put} /api/:dataSource/visualizations/:id/share/:userId Share a visualization
* @apiName setVisualizationShare
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission apiright:visualizationShare.create
* @apiDescription Set the share right of a user on a visualization
*
* @apiParam {string} dataSource key of a data-source
* @apiParam {number} userId id of a user User to grant access to
* @apiParam {string="read","write"} right Granted access level
* @apiParam {number} id a visualization id Visualization to grant access to
*
* @apiSuccess {number} visualizationId ID of the shared visualization.
* @apiSuccess {number} userId ID of the user the visualization has been shared with.
* @apiSuccess {string} right Name of the right (`"none"`, `"read"`, `"write"` or `"owner"`)
* @apiSuccess {string} createdAt Date the visualization has been shared.
* @apiSuccess {string} updatedAt Date at which the share has been updated.
*/
app.put('/api/:dataSource/visualizations/:id/share/:userId', api.respond(req => {
if (!VisualizationShareDAO) { return Promise.resolve(); }
return VisualizationShareDAO.shareWithUser(
req.param('id'),
req.param('userId'),
req.param('right'),
Access.getUserCheck(req, 'visualizationShare.create')
);
}));
/**
* @api {get} /api/:dataSource/visualizations/:id/shares Get visualization share rights
* @apiName visualizationShares
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission apiright:visualizationShare.read
* @apiDescription Get all share rights on a visualization
*
* @apiParam {string} dataSource key of a data-source
* @apiParam {number} id a visualization id
*
* @apiSuccess {Object} res result object
* @apiSuccess {Object} res.owner Owner of the shares
* @apiSuccess {number} res.owner.id Owner's user id
* @apiSuccess {boolean} res.owner.source Owner's source ('local', 'ldap', 'azure', etc.)
* @apiSuccess {string} res.owner.username Owner's username
* @apiSuccess {string} res.owner.email Owner's email
* @apiSuccess {Object[]} res.shares Description of all shares defined by owner
* @apiSuccess {number} res.shares.userId ID of the target user of this share
* @apiSuccess {string} res.shares.username Username of the target user of this share
* @apiSuccess {string} res.shares.email Email of the target user of this share
* @apiSuccess {number} res.shares.visualizationId ID of the shared visualization
* @apiSuccess {string} res.shares.right type of right granted to target user
* (`"read"`, `"write"` or `"owner"`)
*/
app.get('/api/:dataSource/visualizations/:id/shares', api.respond(req => {
if (!VisualizationShareDAO) { return Promise.resolve(); }
Access.getUserCheck(req, 'visualizationShare.read');
return VisualizationShareDAO.getShares(req.param('id'));
}));
/**
* @api {delete} /api/:dataSource/visualizations/:id/share/:userId Un-share a visualization
* @apiName deleteVisualizationShare
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission apiright:visualizationShare.delete
* @apiDescription Remove a share right of a user on a visualization
*
* @apiParam {string} dataSource key of a data-source
* @apiParam {number} userId id of a user
*/
app.delete('/api/:dataSource/visualizations/:id/share/:userId', api.respond(req => {
if (!VisualizationShareDAO) { return Promise.resolve(); }
return VisualizationShareDAO.unshare(
req.param('id'),
req.param('userId'),
Access.getUserCheck(req, 'visualizationShare.delete')
);
}, 204));
// sandbox routes
/**
* @api {get} /api/:dataSource/sandbox Get the visualization sandbox
* @apiName getSandbox
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission __guest
* @apiPermission apiright:sandbox
*
* @apiDescription Return the visualization sandbox of the current user for a given data-source
*
* @apiExample {curl} Populate examples:
* # Visualization by ID
* curl -i "http://localhost:3000/api/e4b5d8/sandbox?populate=visualizationId&item_id=123"
*
* # Node by ID
* curl -i "http://localhost:3000/api/e4b5d8/sandbox?populate=nodeId&item_id=123"
*
* # Edge by ID
* curl -i "http://localhost:3000/api/e4b5d8/sandbox?populate=edgeId&item_id=456"
*
* # Node by ID + neighbors
* curl -i "http://localhost:3000/api/e4b5d8/sandbox?populate=expandNodeId&item_id=123"
*
* # Nodes by search query
* curl -i "http://localhost:3000/api/e4b5d8/sandbox?populate=searchNodes&search_query=paris&search_fuzziness=0.8"
*
* # Edges by search query
* curl -i "http://localhost:3000/api/e4b5d8/sandbox?populate=searchEdges&search_query=has_city"
*
* # Nodes and/or edges by pattern query
* curl -i "http://localhost:3000/api/e4b5d8/sandbox?populate=pattern&pattern_dialect=cypher&pattern_query=MATCH+(n1)-%5Be%5D-(n2)+WHERE+ID(n1)%3D10+RETURN+e"
*
* @apiParam {string} dataSource key of a data-source
* @apiParam {string="visualizationId","expandNodeId","nodeId","edgeId","searchNodes","searchEdges","pattern","matchId"} [populate] Describes how the sandbox should be populated.
* @apiParam {string} [item_id] ID of the node, edge or visualization to load (when `populate` is one of `["visualizationId", "nodeId", "edgeId", "expandNodeId"]`).
* @apiParam {number} [match_id] ID of alert match to load (when `populate` is `"matchId"`).
* @apiParam {string} [search_query] Search query to search for nodes or edges (when `populate` is one of `["searchNodes", "searchEdges"]`).
* @apiParam {number{0-1}} [search_fuzziness=0.9] Search query fuzziness (when `populate` is one of `["searchNodes", "searchEdges"]`).
* @apiParam {string} [pattern_query] Pattern query to match nodes and/or edges (when `populate` is `"pattern"`).
* @apiParam {boolean} [do_layout] Whether to do a server-side layout of the graph.
* @apiParam {string="cypher","gremlin"} [pattern_dialect] Pattern dialect (when `populate` is `"pattern"`).
* @apiParam {boolean} [with_digest=false] Whether to include the adjacency digest in the returned nodes
* @apiParam {boolean} [with_degree=false] Whether to include the degree in the returned nodes
*/
app.get('/api/:dataSource/sandbox', api.respond(r => {
return VisualizationDAO.getSandBox({
sourceKey: r.param('dataSource'),
populate: r.param('populate'),
itemId: r.param('item_id'),
matchId: Utils.tryParsePosInt(r.param('match_id'), 'match_id', true),
searchQuery: r.param('search_query'),
searchFuzziness: Utils.tryParseNumber(r.param('search_fuzziness'), 'search_fuzziness', true),
patternQuery: r.param('pattern_query'),
patternDialect: r.param('pattern_dialect'),
doLayout: Utils.parseBoolean(r.param('do_layout')),
withDigest: Utils.parseBoolean(r.param('with_digest')),
withDegree: Utils.parseBoolean(r.param('with_degree'))
}, Access.getUserCheck(r, 'sandbox', true)
).then(
r => ({visualization: r})
);
}));
/**
* @api {patch} /api/:dataSource/sandbox Update the visualization sandbox
* @apiName updateSandbox
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission apiright:sandbox
*
* @apiDescription Update the sandbox of the current user for a given data-source.
*
* @apiParam {string} dataSource key of a data-source (ignored in this API)
* @apiParam {object} visualization The sandbox visualization object.
* @apiParam {object} [visualization.design]
* @apiParam {object} [visualization.nodeFields]
* @apiParam {object} [visualization.edgeFields]
*/
app.patch('/api/:dataSource/sandbox', api.respond(req => {
return VisualizationDAO.updateSandBox(
req.param('dataSource'),
req.param('visualization'),
Access.getUserCheck(req, 'sandbox')
).then(
r => ({visualization: r})
);
}, 204));
// widget routes
app.all('/api/widget*', api.proxy(() => {
if (LKE.isEnterprise()) {
return Promise.resolve();
}
// this is a 'business' API not found, it will not log internally
return Errors.business('api_not_found', null, true);
}));
/**
* @api {post} /api/widget Create a widget
* @apiName createVisualizationWidget
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission apiright:widget.create
*
* @apiDescription Create a widget for a visualization.
*
* @apiParam {number} visualization_id The visualization id
* @apiParam {object} [options] The configuration of the user interface elements.
* @apiParam {boolean} [options.search=false] Whether the search bar is shown.
* @apiParam {boolean} [options.share=false] The the share button is shown.
* @apiParam {boolean} [options.layout=false] Whether the layout button is shown.
* @apiParam {boolean} [options.fullscreen=false] Whether the full-screen button is shown.
* @apiParam {boolean} [options.zoom=false] Whether to zoom-in and zoom-out controllers are shown.
* @apiParam {boolean} [options.legend=false] Whether the graph legend is shown.
* @apiParam {boolean} [options.geo=false] Whether the geo-mode toggle button is visible. Ignored if the nodes don't have geo coordinates.
* @apiParam {string} [options.password] Optional password to protect the widget
*
* @apiSuccess {string} key The key of the created widget
*/
app.post('/api/widget', api.respond(req => {
const options = req.param('options', {});
return WidgetDAO.createWidget(
Utils.tryParsePosInt(req.param('visualization_id'), 'visualization_id'),
options,
false,
Access.getUserCheck(req, 'widget.create')
);
}));
/**
* @api {put} /api/widget Update a widget
* @apiName updateVisualizationWidget
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission apiright:widget.edit
*
* @apiDescription Update a widget for a visualization.
*
* @apiParam {number} visualization_id The visualization id
* @apiParam {object} [options] The configuration of the user interface elements.
* @apiParam {boolean} [options.search=false] Whether the search bar is shown.
* @apiParam {boolean} [options.share=false] The the share button is shown.
* @apiParam {boolean} [options.layout=false] Whether the layout button is shown.
* @apiParam {boolean} [options.fullscreen=false] Whether the full-screen button is shown.
* @apiParam {boolean} [options.zoom=false] Whether to zoom-in and zoom-out controllers are shown.
* @apiParam {boolean} [options.legend=false] Whether the graph legend is shown.
* @apiParam {boolean} [options.geo=false] Whether the geo-mode toggle button is visible. Ignored if the nodes don't have geo coordinates.
* @apiParam {string} [options.password] Optional password to protect the widget
*
* @apiSuccess {string} key The key of the updated widget
*/
app.put('/api/widget', api.respond(req => {
return WidgetDAO.createWidget(
Utils.tryParsePosInt(req.param('visualization_id'), 'visualization_id'),
req.param('options', {}),
true,
Access.getUserCheck(req, 'widget.edit')
);
}));
/**
* @api {delete} /api/widget/:key Delete a widget
* @apiName deleteVisualizationWidget
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission apiright:widget.delete
*
* @apiDescription Delete a widget for a visualization.
*
* @apiParam {string} key the key of the widget to delete
*/
app.delete('/api/widget/:key', api.respond(req => {
return WidgetDAO.deleteByKey(
req.param('key'),
Access.getUserCheck(req, 'widget.delete')
);
}, 204));
/**
* @api {get} /api/widget/:key Get a widget
* @apiName getWidgetByKey
* @apiGroup Visualizations
* @apiVersion 1.0.0
* @apiPermission authenticated
* @apiPermission apiright:widget.read
*
* @apiDescription Get a visualization widget's data by key
*
* @apiParam {string} key the key of a widget
*
* @apiSuccess {string} title the title of the visualization used to generate this widget
* @apiSuccess {string} key the key of this widget
* @apiSuccess {number} userId the owner ID of the visualization used to generate this widget
* @apiSuccess {number} visualizationId the ID of the visualization used to generate this widget
* @apiSuccess {boolean} password Whether password protection is enabled
* @apiSuccess {Object} content the content of the widget, as sent while generating this widget
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
*
* {
* "title": "Foo Bar",
* "key": "key",
* "userId": 12,
* "password": false,
* "visualizationId": 3,
* "content": {
* "key": "value"
* }
* }
*/
app.get('/api/widget/:key', api.respond(req => {
Access.getUserCheck(req, 'widget.read');
return WidgetDAO.getByKey(req.param('key'));
}));
};
|
const fs = require("fs");
module.exports = class Parser {
constructor(filepath) {
this.commands = fs.readFileSync(filepath, { encoding: "utf-8" })
.split("\n")
.map(line => line.replace(/[\/\/].*/g, "").trim().replace(/\s+/, " "))
.filter(line => !!line);
this.cmdIt = this.commands.values();
this.currentCommand = this.cmdIt.next();
}
hasMoreCommands() {
return !this.currentCommand.done;
}
advance() {
this.currentCommand = this.cmdIt.next();
}
/**
* 現VMコマンドの種類を返す
* 算術コマンドはすべてC_ARITHMETICが返される
*/
commandType() {
const cmd = this.currentCommand.value.split(" ")[0];
switch (true) {
case ["add", "sub", "neg", "eq", "gt",
"lt", "and", "or", "not"].includes(cmd):
return "C_ARITHMETIC";
case cmd === "push":
return "C_PUSH";
case cmd === "pop":
return "C_POP";
case cmd === "label":
return "C_LABEL";
case cmd === "goto":
return "C_GOTO";
case cmd === "if-goto":
return "C_IF";
case cmd === "function":
return "C_FUNCTION";
case cmd === "return":
return "C_RETURN";
case cmd === "call":
return "C_CALL";
default:
console.error(`illegal command: ${cmd}`);
throw new Error(`illegal command: ${cmd}`);
}
}
/**
* 現コマンドの最初の引数を返す
* C_ARITHMETICの場合、コマンド自体(add, subなど)が返される
* 現コマンドがC_RETURNの場合、本ルーチンは呼ばないようにする
*/
arg1() {
return this.commandType() === "C_ARITHMETIC" ?
this.currentCommand.value :
this.currentCommand.value.split(" ")[1] ;
}
/**
* 現コマンドの2番目の引数が返される
* 現コマンドがC_PUSH、C_POP、C_FUNCTION、C_CALLの場合のみ
* 本ルーチンを呼ぶようにする
*/
arg2() {
return Number(this.currentCommand.value.split(" ")[2]);
}
}
|
export default class Project {
tasks = [];
constructor(name) {
this.name = name;
}
addActivity(string) {
this.tasks.push(string);
}
}
|
// models, item.js
define([
'underscore',
'backbone'],
function(_,Backbone){
var Item = Backbone.Model.extend({
defaults: {
name: '',
manufacturer: '',
price: 0,
url: '',
img: '',
list: ''
}
});
return Item;
});
|
const pick = (obj, arr) => {
let result = {};
arr.forEach(val => {
if (val in obj) result[val] = obj[val];
});
return result;
};
const getNowYear = () => {
let year = new Date().getFullYear();
return year;
};
const formatStrigToMonth = str => {
return str.replace(/^(\d{4})(\d{2})$/, "$2");
};
module.exports = {
pick,
getNowYear,
formatStrigToMonth
};
|
import Vue from 'vue';
// Router
import VueRouter from 'vue-router';
Vue.use(VueRouter);
import routes from '@/router/routes';
export default new VueRouter({
routes, // short for `routes: routes`
linkActiveClass: 'active' // change to the Bootstrap class 'active'
});
|
/*
* @lc app=leetcode id=60 lang=javascript
*
* [60] Permutation Sequence
*
* https://leetcode.com/problems/permutation-sequence/description/
*
* algorithms
* Medium (35.26%)
* Likes: 1251
* Dislikes: 292
* Total Accepted: 169.2K
* Total Submissions: 475.2K
* Testcase Example: '3\n3'
*
* The set [1,2,3,...,n] contains a total of n! unique permutations.
*
* By listing and labeling all of the permutations in order, we get the
* following sequence for n = 3:
*
*
* "123"
* "132"
* "213"
* "231"
* "312"
* "321"
*
*
* Given n and k, return the k^th permutation sequence.
*
* Note:
*
*
* Given n will be between 1 and 9 inclusive.
* Given k will be between 1 and n! inclusive.
*
*
* Example 1:
*
*
* Input: n = 3, k = 3
* Output: "213"
*
*
* Example 2:
*
*
* Input: n = 4, k = 9
* Output: "2314"
*
*
*/
// @lc code=start
/**
* @param {number} n
* @param {number} k
* @return {string}
*/
var getPermutation = function(n, k) {
let str = '';
function multiply(n) {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
const leftNums = Object.keys(new Array(n).fill(0)).map(i => +i + 1);
k--;
while (str.length < n) {
const percount = multiply(n - str.length - 1);
const index = Math.floor(k / percount);
str += leftNums[index];
leftNums.splice(index, 1);
k = k % percount;
}
return str;
};
// @lc code=end
getPermutation(4, 6);
|
import React, { Component } from 'react';
import { connect } from 'react-redux'
class Favorites extends Component {
componentDidMount() {
this.props.dispatch({ type: 'GET_FAVORITES' });
}
render() {
return (
<div>
{this.props.fetchFavoriteGifs.map( (gif) =>
<img src={gif.url} />
)}
<pre>{JSON.stringify(this.props.fetchFavoriteGifs, null, 2)}</pre>
</div>
);
}
}
const mapReduxStateToProps = (reduxState) => {
return reduxState;
}
export default connect(mapReduxStateToProps)(Favorites);
|
import React, { Component } from "react";
import * as api from "../api";
import { Link } from "@reach/router";
import ArticleAdder from "./ArticleAdder";
import "./Article.css";
class Articles extends Component {
state = {
articles: []
};
render() {
return (
<div className="Articlegrid">
<span className="Articles">
<h2>Articles</h2>
{this.state.articles.map(article => {
return (
<Link
className="class1"
to={`/articles/${article._id}`}
key={article._id}
>
<li key={article._id} className="singleComment">
<div>{article.title}</div>
<h6>Comments: {article.commentcount}</h6>
</li>
</Link>
);
})}
</span>
<ArticleAdder user={this.props.user} />
</div>
);
}
componentDidMount() {
console.log(this.props.user, "article user");
this.fetchArticles();
}
fetchArticles = () => {
api
.getArticles(this.props.topic)
.then(articles => {
this.setState({
articles
});
})
.catch(error => {
this.props.navigate("/error", {
state: {
status: 404,
from: "./articles",
msg: "Our Ponies couldn't find any Articles"
}
});
});
};
}
export default Articles;
|
import React from 'react';
import { describe, add } from '@sparkpost/libby-react';
import { Box } from '@sparkpost/matchbox/components/Box';
describe('Box', () => {
add('styled', () => (
<Box
color="gray.1000"
fontWeight="semibold"
bg={['teal.200', 'yellow.200', 'red.200', 'purple.200', 'blue.200']}
py="200"
px="300"
m="400"
borderRadius="200"
zIndex="overlay"
border={400}
>
Just a Box
</Box>
));
add('flex', () => (
<Box display="flex" my="400" justifyContent="space-around">
<Box bg="magenta.400" padding="600"></Box>
<Box bg="purple.400" padding="600"></Box>
<Box bg="blue.400" padding="600"></Box>
</Box>
));
add('grid', () => (
<Box display="grid" m="400" gridTemplateColumns="2fr 1fr 1fr" gridGap="400">
<Box bg="purple.200" padding="400"></Box>
<Box bg="purple.300" padding="400"></Box>
<Box bg="purple.400" padding="400"></Box>
<Box bg="blue.400" padding="400" gridColumn="1 / 4"></Box>
<Box bg="magenta.300" padding="400" gridColumn="1 / 3"></Box>
<Box bg="magenta.400" padding="400" gridColumn="3 / 4"></Box>
</Box>
));
});
|
import React from 'react';
export class Bussiness extends React.Component {
state = {
bussinessName: 'Bussiness Name',
streetNumber: '1000',
streetName: 'second st',
city: 'kansas',
state: 'MO',
zipcode: '64112'
}
render() {
return (
<div>
<h1>{this.state.bussinessName}</h1>
<div>Business Address:</div>
<p>{this.state.streetNumber} {this.state.streetName} {this.state.city},
{this.state.state} {this.state.zipcode}</p>
</div>
)
}
}
|
// compare each element of array for equality
const eqArrays = function(arr1, arr2) {
let length = arr1.length;
for (let i = 0; i < length; i++) {
if (arr1[i] !== arr2[i]) return false;
}
return true;
};
// emoji variable to output with assertion
let emoji = require('node-emoji');
const assertArraysEqual = function(actual, expected) {
// check if 2 passsed arguments are equal
if (eqArrays(actual, expected)) {
console.log(emoji.get('heart'), ` Assertion Passed: ${actual} === ${expected}`);
} else {
console.log(emoji.get('warning'), ` Assertion Failed: ${actual} !== ${expected}`);
}
};
const without = function(array, word) {
let newArray = [];
// check condition for 2nd argument not to be array
if (Array.isArray(word)) {
for (let item of array) {
for (let i of word) {
// make sure pushed only item not in word array
if (item !== i && newArray.includes(item) === false && word.includes(item) === false) newArray.push(item);
}
}
} else {
for (let item of array) {
if (item !== word) newArray.push(item);
}
}
return newArray;
};
const words = ["hello", "world", "lighthouse"];
console.log(without(words, ["lighthouse"]));
console.log(words.includes("helo"));
console.log(without([1, 2, 3], [1])); // => [2, 3]
console.log(without(["1", "2", "3"], [1, 2, "3"]));// => ["1", "2"]
//test function
assertArraysEqual(words, ["hello", "world", "lighthouse"]);
|
import ViewerLayer from "../../layer/ViewerLayer";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Cluster from "ol/source/Cluster"
import GeoJSON from "ol/format/GeoJSON";
import Style from "ol/style/Style";
import Icon from "ol/style/Icon";
import Fill from "ol/style/Fill";
import Text from "ol/style/Text";
import axios from 'axios';
import Vue from 'vue'
import {SharedEventBus} from "@/shared";
class ViewerLayerKloosterLocaties extends ViewerLayer {
constructor(props) {
super(props);
}
OLLayer(url) {
let me = this;
let vectorReader = function (data) {
let format = new GeoJSON;
let features = format.readFeatures(data, {
dataProjection: 'EPSG:4326',
featureProjection: Vue.prototype.$config.crs
});
source.addFeatures(features);
};
let source = new VectorSource({
loader: function () {
return axios.get(url + '?name=' + me.name).then(function (response) {
vectorReader(response.data);
}).catch(function (error) {
console.error(error);
SharedEventBus.$emit('show-message', 'problem loading data: ' + error);
});
}
});
let clusterSource = new Cluster({
distance: 20,
source: source
});
let styleCache={};
return new VectorLayer({
source: clusterSource,
style: function (feature) {
const name = me.name;
const features = feature.get('features');
let num = features.length.toString();
let uq = name + num;
if (!styleCache[uq]) {
if (num == '1') {
styleCache[uq] =
new Style({
image: new Icon({
scale: 0.5,
src: me.legend_img,
opacity: 0.80
})
});
} else {
styleCache[uq] =
new Style({
image: new Icon({
scale: 0.5 + (0.4 * Math.log(num)),
src: me.legend_img,
opacity: 0.80
}),
text: new Text({
font: '14px Calibri,sans-serif',
fill: new Fill({color: '#fff'}),
offsetY: 0,
text: num
}),
});
}
}
return [styleCache[uq]];
},
type: me.type,
visible: this.visible,
opacity: 0.8,
zIndex: this.zindex,
legend_img: me.legend_img,
cluster_distance: 20,
});
}
}
export default ViewerLayerKloosterLocaties;
|
module.exports = function(app){
var NweetController = {
submit: function(req,res){
req.assert(req.body.texto, 'Insira o conteúdo do seu nweet').isEmpty();
var errors = req.validationErrors();
if(errors){
res.render("index", {'errors': errors});
}else{
var nweetModel = app.models.nweet;
var nweet = {
autor: req.session.usuario._id,
texto: req.body.texto
}
nweetModel.create(nweet, function(error, nweet){
res.redirect("/");
});
}
}
}
return NweetController;
};
|
import React, { useState } from "react";
import Header from "../../components/Header";
import Task from "../../screens/Tasks/Task.js";
import { StyleSheet, Text, View, TextInput, Button } from 'react-native';
import {useDispatch} from 'react-redux';
import { addNTask } from "../../redux/actions";
export default function TaskForm(){
const [newTask, setNewTask] = useState("");
const dispatch = useDispatch();
const onChangeText = (v) => {
setNewTask(v)
};
const addNewTask = () => {
if(newTask !== ""){
dispatch(addNTask(newTask));
setNewTask("");
}
};
return(
<View style={styles.container}>
<TextInput
style={styles.input}
onChangeText={onChangeText}
value={newTask}
placeholder="Nouvelle tâche"
/>
<Button
color="grey"
title="Ajouter"
onPress={addNewTask}
/>
</View>
)
}
const styles = StyleSheet.create({
container: {
flexDirection: "row",
marginTop: 20,
marginBottom: 20,
},
input: {
borderWidth: 2,
borderColor: "#000000",
padding: 2,
width: "70%",
}
});
|
Vue.component('reader', {
template: `<modal v-model="modal" class-name="vertical-center-modal"
id="reader" class="page"
:fullscreen="true" :closable="false" :footer-hide="mode == 'edit'"
style="overflow: hidden;"
>
<!-- header -->
<header-bar :title="title" slot="header" icon="md-arrow-back" @goBack="onPopState"
>
<div slot="right" v-if="$isLogin()">
<Icon v-if="$isAdmin() && $isDebug() && $isFlutter()" type="md-refresh" size="22" @click.native="onRefresh"
:style="{cursor: 'pointer', color: 'white', 'margin-right': '5px'} "
/>
<Icon type="md-heart" size="22" @click.native="onFavorite"
:style="{cursor: 'pointer', color: favorite ? '#c01921' : '#e8eaec', 'margin-right': '5px'} " />
<Icon v-if="$isFlutter()" type="md-download" size="22" @click.native="onDownload"
:style="{cursor: 'pointer', color: isDownload ? '#c01921' : '#e8eaec', 'margin-right': '0px'} "
/>
</div>
<Dropdown slot="right" @on-click="onClickMore($event)" style="margin-right: 10px"
:trigger="$isSmallScreen() ? 'click' : 'hover'"
>
<Icon type="md-more" size="28" color="white" style="cursor: pointer; margin-left: 10px;"></Icon>
<DropdownMenu slot="list" v-if="audio && audio.setting">
<DropdownItem name="自動播放">
<Icon type="md-checkmark" size="16" :style="{color: audio.setting.autoPlay == true ? '' : '#e5e5e5'}"></Icon>
自動播放
</DropdownItem>
<DropdownItem name="中文" v-if="isChinese()" divided>
<Icon type="md-checkmark" size="16" :style="{color: audio.setting.chinese == true ? '' : '#e5e5e5'}"></Icon>
中文
</DropdownItem>
<dropdown placement="right-start" v-if="! $isSmallScreen()" divided>
<dropdown-item>字體 <icon type="ios-arrow-forward"></icon></dropdown-item>
<dropdown-menu slot="list">
<dropdown-item name="字1.7" :selected="zoom == 1.7">大</dropdown-item>
<dropdown-item name="字1.5" :selected="zoom == 1.5">中</dropdown-item>
<dropdown-item name="字1.2" :selected="zoom == 1.2">正常</dropdown-item>
</dropdown-menu>
</dropdown>
<dropdown placement="right-start" :divide="$isSmallScreen()">
<dropdown-item>速率<icon type="ios-arrow-forward"></icon></dropdown-item>
<dropdown-menu slot="list">
<dropdown-item name="速0.9" :selected="audio.setting.rate == 0.9">慢</dropdown-item>
<dropdown-item name="速1" :selected="audio.setting.rate == 1">正常</dropdown-item>
<dropdown-item name="速1.2" :selected="audio.setting.rate == 1.2">快</dropdown-item>
</dropdown-menu>
</dropdown>
<dropdown placement="right-start">
<dropdown-item>重複播放<icon type="ios-arrow-forward"></icon></dropdown-item>
<dropdown-menu slot="list" v-for="(item, index) in options.repeat" :key="index">
<dropdown-item :name="'重複' + item" :selected="audio.setting.repeat == item">
{{item == 0 ? "關閉" : item + " 次"}}
</dropdown-item>
</dropdown-menu>
</dropdown>
<dropdown placement="right-start" v-if="audio.setting.repeat > 0">
<dropdown-item>重複範圍<icon type="ios-arrow-forward"></icon></dropdown-item>
<dropdown-menu slot="list" v-for="(item, index) in options.range" :key="index">
<dropdown-item :name="'範圍' + item.value" :selected="audio.setting.range == item.value">
{{item.label}}
</dropdown-item>
</dropdown-menu>
</dropdown>
<DropdownItem name="中斷" v-if="!$isSmallScreen() && audio.setting.repeat > 0">
<Icon type="md-checkmark" size="16"
:style="{color: audio.setting.repeat > 0 && audio.setting.interrupt == true ? '' : '#e5e5e5'}"></Icon>
重複中斷
</DropdownItem>
<dropdown placement="right-start" v-if="audio.setting.repeat > 0">
<dropdown-item>重複間距<icon type="ios-arrow-forward"></icon></dropdown-item>
<dropdown-menu slot="list" v-for="(item, index) in options.interval" :key="index">
<dropdown-item :name="'間距' + item" :selected="audio.setting.interval == item">
{{(item > 0 ? item : item * -1) + (item > 0 ? " 秒" : " 倍") }}
</dropdown-item>
</dropdown-menu>
</dropdown>
<DropdownItem name="段落區塊" v-if="audio.setting.repeat > 0">
段落區塊
</DropdownItem>
<DropdownItem name="生字" divided v-if="login == true && displayVocabulary == false && vocabulary.length > 0">
生字清單
</DropdownItem>
<DropdownItem name="google" divided>
google
</DropdownItem>
<DropdownItem name="yahoo">
yahoo
</DropdownItem>
<DropdownItem name="help" divided>
help
</DropdownItem>
<DropdownItem name="關於">
關於
</DropdownItem>
</DropdownMenu>
</Dropdown>
</header-bar>
<!-- body -->
<textarea v-if="mode=='edit'" ref="textarea"
style="height: 100%; width: 100%; font-size: 18px;"
>{{source.html}}</textarea>
<div id="readerFrame" v-else
style="height: 100%; overflow-y: auto; display: flex; flex-direction: row;"
@scroll.natvie="onScroll"
>
<div id="renderMarker" v-if="repeat > 0"
style="width: 20px; padding: 8px 0px; overflow-y: hidden;
overflow-x: visible; position: relative;">
<div v-for="(item, index) in bubbles" :key="index"
:style="{position: 'absolute', top: item.top + 'px', height: item.height + 'px',}"
>
<div class='speech-bubble' :id="'bubble' + index" @click="onClickBubble($event, index)">
{{index + 1}}
</div>
</div>
</div>
<div id="context" v-html="html" @contextmenu="$easycm($event,$root,1)"
:style="{flex: 1,
padding: repeat == 0 ? '8px' : '8px 4px 8px 2px'}"
>
</div>
<div id="board" v-if="repeat > 1 && state != 'stop'" style="bottom: 0px; min-width: 30px; text-align: center;">
{{repeatTimes + (audio.isLoop == true ? "" : "/" + repeat) }}
</div>
</div>
<easy-cm :list="cmList" :tag="1" @ecmcb="onMenuClick" :underline="true" :arrow="true" :itemHeight="34" :itemWidth="180"></easy-cm>
<!-- footer -->
<div v-show="duration > 0 && mode == '' " slot="footer" style="display: flex; flex-direction: row; align-items: center; ">
<div style="display: flex; flex-direction: row; align-items: center; ">
<Icon v-if="state == 'pause' || state == 'stop'" type="md-play"
size="20" color="white" class="button" @click.native="audio.play()" />
<Icon v-else type="md-pause" size="20" color="white" class="button"
@click.native="audio.pause()" />
<Icon type="md-square" size="20"
:color="state == 'stop' ? '#B8B8B8' : 'red'"
class="button" :class="{disable: state == 'stop'}"
@click.native="audio.stop()"
/>
<Icon v-if="repeat > 0 && block.length > 0" type="md-skip-backward" size="20"
:color="block[0] == 0 ? '#B8B8B8' : 'white'"
class="button" :class="{disable: block[0] == 0}"
@click.native="moveBlock(block[0] == 0 ? null : -1)" />
<Icon v-if="repeat > 0 && block.length > 0" type="md-skip-forward" size="20"
:color="block[1] == audio.LRCs.length - 1 ? 'grey' : 'white'"
class="button" :class="{disable: block[1] == audio.LRCs.length - 1}"
@click.native="moveBlock(block[1] == audio.LRCs.length - 1 ? null : 1)" />
</div>
<div v-if="repeat == 0" style="margin: 0px 10px 0px 5px; font-size: 20px;">
<div style="font-weight: 500;">{{convertTime(currentTime)}}</div>
<div style="font-weight: 500;">{{convertTime(duration)}}</div>
</div>
<Slider v-model="currentTime" :tip-format="format"
v-if="repeat == 0 && ! $isSmallScreen()"
:max=duration @on-change="onSlideChange" style="flex: 1; margin-right: 10px;"
:marks="marks" />
<div v-else style="flex: 1; text-align: center;">{{msg}}</div>
<div v-if="repeat > 0 && state != 'stop' && width > 600">
<Icon v-if="state == 'interrupt'"
type="md-repeat" size="20" class="button"
@click.native="onInterrupt()" />
<Icon type="md-rewind" size="20" class="button"
@click.native="onRewind" />
<Icon type="md-fastforward" size="20" class="button"
@click.native="onFastforward"/>
</div>
<Dropdown v-if="state != 'stop'" :trigger="$isSmallScreen() ? 'click' : 'hover'" style="min-width: 80px">
<a href="javascript:void(0)" style="padding: 10px 10px; display: inline-block;">
{{convertTime((sleep * 60) - passTime)}}
<Icon type="ios-arrow-down"></Icon>
</a>
<dropdown-menu slot="list" placement="left-start">
<dropdown-item v-for="(item, index) in options.limits" :key="index"
:selected="item == sleep"
@click.native="onClickSleep(item)"
>
{{item + " 分"}}
</dropdown-item>
</dropdown-menu>
</Dropdown>
</div>
<dlg-vocabulary :visible="displayVocabulary" :data="vocabulary"
@close="displayVocabulary = false" @update="updateVocabulary"/>
<dlg-paragraph :visible="displayParagraph"
:paragraph="audio == null ? [] : audio.LRCs"
:block="audio == null ? [] : audio.block"
@close="onParagraphOK" @on-cancel="displayParagraph = false"
/>
</modal>`,
props: {
source: Object,
total: Number
},
data() {
return {
width: 320,
modal: true,
login: false,
title: "",
audio: null,
state: "stop",
duration: 0,
currentTime: 0,
passTime: 0,
cmList: [],
html: "",
msg: "",
marks: {},
repeat: 0, // 主要是作為在 reader 判斷用
sleep: 30,
zoom: 1.2,
repeatTimes: 1,
bubbles: [],
block: [],
vocabulary: "",
favorite: false,
download: false,
displayVocabulary: false,
displayParagraph: false,
mode: "",
options: {
limits: [10, 15, 20, 30, 60], // 睡眠
repeat: [0, 1, 2, 3, 5, 10, 50],
range: [{label: "字幕", value: "lrc"}, {label: "段落", value: "paragraph"}],
interval: [3, 5, 10, 20, -0.75, -1, -1.5, -2] // 重複間距
},
isDownload: false
};
},
created(){
},
async mounted () {
this.login = FireStore.login;
let context = document.querySelector("#context");
if(context != null) context.style.visibility = "hidden";
if(typeof window.localStorage["VOA-sleep"] != "undefined")
this.sleep = window.localStorage["VOA-sleep"];
if(typeof window.localStorage["VOA-zoom"] != "undefined")
this.zoom = window.localStorage["VOA-zoom"];
this.html = this.source.html + "<div style='display: none;'>" + (new Date()) + "</div>";
this.title = this.source.title;
// console.log(this.source)
this.initial();
if(this.$isAdmin()){
this.options.limits = [1, 3, 5].concat(this.options.limits);
}
this.broadcast.$on('onResize', this.onResize);
if(this.$isFlutter()) {
this.broadcast.$on('onFlutter', this.onFlutter);
this.isDownload = typeof this.source.mp3Path == 'string' ? true : false
try{
// let url = await this.$toBase64(this.source.mp3Path);
// console.log(url)
// let checkMP3 = await this.$checkMP3(this.source.report, this.source.key);
// console.log("checkMP3: " + checkMP3 + ".............................")
// await this.$delMP3(this.source.report, this.source.key);
// console.log("$delMP3: " + ".............................")
// let url = await this.$MP3(this.source.report, this.source.key);
// console.log("$MP3: " + url + ".............................")
} catch (e){
console.log(e)
}
}
this.onResize();
},
destroyed() {
this.audio.src = "";
this.audio.canPlay = false;
this.audio.stop();
this.audio = null;
clearInterval(this.finalCountID);
this.$Notice.destroy();
window.removeEventListener('keydown', this.onKeydown, false);
window.removeEventListener("popstate", this.onPopState);
this.broadcast.$off('onResize', this.onResize);
if(this.$isFlutter()) {
let obj = {state: "close"};
Flutter.postMessage(JSON.stringify(obj));
console.log("Flutter.postMessage: " + JSON.stringify(obj))
this.broadcast.$off('onFlutter', this.onFlutter);
}
this.$Modal.remove();
},
methods: {
onInterrupt(){
if(this.state == "interrupt" || this.audio.state == "pendding")
this.audio.continue();
},
onRewind(){
this.audio.gotoLRC(-1)
},
onFastforward(){
this.audio.gotoLRC(1)
},
onRefresh(){
location.reload();
},
async onDownload(){
try{
let url = undefined
if(this.isDownload == true)
await this.$delMP3(this.source.report, this.source.key);
else {
url = await FireStore.downloadFileURL("VOA/" + this.source.report +
"/" + this.source.key + ".mp3");
await this.$downloadMP3(this.source.report, this.source.key, url);
}
this.isDownload = !this.isDownload;
this.$emit("onUpdate", "mp3Path", url);
} catch(e){
}
},
onFavorite(){
this.favorite = !this.favorite;
this.setHistory({favorite: this.favorite})
},
showContext(){ //f2, 為了可以 copy 到 google document
let win = this.$open("", "課文");
let s1 = this.title + "<br />";
let arr = document.querySelectorAll(".english");
arr.forEach(item=>{
let s2 = item.innerHTML.replace(/class="highlight"/g, "style='color: #c01921;'")
s1 += "<br /><div>" + s2 + "</div>";
console.log(s2)
})
win.document.body.innerHTML = s1;
},
toChinese(){ // f10, 還沒寫,翻譯網站,不滿意
let self = this;
this.$Modal.remove();
this.$Modal.confirm({
title: "中文寫入",
width: document.body.clientWidth - 100,
// loading: true,
render: (h) => {
return h('textarea', {
attrs: {
id: "clipboard",
style: "height: " + (document.body.clientHeight - 300) + "px; width: 100%;",
// readonly: true
},
props: {
// read
},
on: {
blur: (event) => {
},
paste: (event) =>{
}
}
})
},
onOk: () => {
exec();
},
onCancel: () => {
}
});
function exec() {
let div = document.createElement("DIV");
div.innerHTML = self.source.html;
let arr1 = div.querySelectorAll(".english")
let el = document.getElementById("clipboard");
if(el.value.length > 0) {
let arr2 = el.value.replaceAll("\n\n", "\n").split("\n");
arr2.forEach((item, index) =>{
if(index < arr1.length)
arr1[index].insertAdjacentHTML('afterend', "\n <div class='chinese'>" + item + "</div>");
});
}
console.log(div.innerHTML)
}
},
toTranslate(){ // f1,翻譯網站
this.$Modal.remove();
// let context = document.getElementById("context");
// let s = context.innerText.split("\n").join("\n\n");
let s = "";
let div = document.createElement("DIV");
div.innerHTML = this.source.html;
let arr = div.querySelectorAll(".english")
arr.forEach(el =>{
s += (s.length > 0 ? "\n\n" : "") + el.innerText.replaceAll("\n", "")
.replaceAll(" ", " ").replaceAll(" ", " ").replaceAll(" ", " ")
.trim();
})
this.$Modal.confirm({
title: "複製內容",
width: document.body.clientWidth - 100,
render: (h) => {
return h('textarea', {
attrs: {
id: "clipboard",
style: "height: " + (document.body.clientHeight - 300) + "px; width: 100%;",
readonly: true
},
props: {
// read
},
on: {
blur: (event) => {
this.value = event.target.value;
},
paste: (event) =>{
// console.log(event)
}
}
}, s)
},
onOk: () => {
window.open('https://www.deepl.com/translator', "",
"resizable=yes,toolbar=no,status=no,location=no,menubar=no,scrollbars=yes"
);
},
onCancel: () => {
}
});
setTimeout(() => {
let el = document.getElementById("clipboard");
if(typeof el == "object") {
el.select();
let range = document.createRange();
range.selectNode(el);
window.getSelection().addRange(range);
document.execCommand("copy");
}
}, 1000);
},
moveBlock(index){
if(index == null) return;
this.onParagraphOK([this.block[0] + index, this.block[1] + index])
},
onFlutter(arg){
// console.log("onFlutter: " + arg)
if(arg == "unplugged") { // 耳機,已拔
this.audio.pause();
} else if(arg == "action.TOGGLE") { //
if(this.state == "play")
this.audio.pause();
else
this.audio.play();
} else if(arg == "action.STOP") { //
this.audio.stop();
}
},
onParagraphOK(block){
if(Array.isArray(block)) {
this.audio.block = block;
this.assignBlock(block);
this.renderActiveBubble();
if(block.length == 2 && (this.audio.paragraph < block[0] || this.audio.paragraph > block[1])){
this.audio.assignParagraph(this.audio.block[0], true);
}
this.saveBlock();
}
this.displayParagraph = false;
},
onClickMore(item){
// console.log(item)
if(typeof item == "undefined") return;
item += "";
if(item == "自動播放")
this.audio.setting.autoPlay = !this.audio.setting.autoPlay;
else if(item == "中文") {
this.audio.setting.chinese = !this.audio.setting.chinese;
} else if(item == "生字"){
this.displayVocabulary = true;
return;
} else if(item == "google"){
this.$google("");
return;
} else if(item == "yahoo"){
this.$yahoo("");
return;
} else if(item == "help"){
this.$open("https://docs.google.com/document/d/1IQ-_LDYGWP-1y0Ogll3jRuyPyu16yzZY0d_ELV9yHD4/edit#heading=h.fwj87joqtqco");
return;
// } else if(item == "設定"){
} else if(item == "關於"){
vm.showMessage(
this.source.title,
this.source.report + ":" + this.source.key,
"異動日期:" + new Date(this.source.modifyDate).toString()
)
return;
} else if(item.indexOf("字") == 0){
this.zoom = parseFloat(item.replace("字", ""))
document.getElementById("readerFrame").style.zoom = this.zoom;
window.localStorage["VOA-zoom"] = this.zoom;
this.renderBubble();
this.buildMenu();
return;
} else if(item.indexOf("速") == 0){
let rate = parseFloat(item.replace("速", ""))
this.audio.setting = Object.assign(this.audio.setting, {rate});
} else if(item.indexOf("間距") == 0){
let interval = parseFloat(item.replace("間距", ""))
this.audio.setting = Object.assign(this.audio.setting, {interval});
} else if(item.indexOf("中斷") == 0){ //
let interrupt = ! this.audio.setting.interrupt;
this.audio.setting = Object.assign(this.audio.setting, {interrupt});
} else if(item.indexOf("段落區塊") == 0){ //
this.displayParagraph = true;
} else if(item.indexOf("重複") == 0){
let repeat = parseFloat(item.replace("重複", ""))
let update = this.audio.setting.repeat == 0 || repeat == 0 ? true : false;
this.audio.setting = Object.assign(this.audio.setting, {repeat: repeat});
if(repeat == 0) {
this.audio.setting.interrupt = false;
}
this.audio.block = this.audio.setting.repeat == 0 ? [] : this.block;
if(update == true) {
this.html = this.source.html + "<div style='display: none;'>" + (new Date()) + "</div>";
this.audio.audio.pause();
clearInterval(this.audio.timeID);
this.audio.repeat = 0;
setTimeout(() => {
this.retrieve(true);
}, 300);
}
this.repeat = this.audio.setting.repeat;
} else if(item.indexOf("範圍") == 0){
let range = item.replace("範圍", "");
// console.log(this.audio.setting.range)
let paragraph = 0, state = this.audio.state;
if(state != "stop") {
paragraph = this.audio.paragraph;
this.audio.stop();
}
this.audio.setting = Object.assign(this.audio.setting, {range});
if(state != "stop") {
setTimeout(() => {
this.audio.gotoParagraph(paragraph)
this.audio.play();
}, 600);
}
}
this.buildMenu();
// window.localStorage["VOA-Reader"] = JSON.stringify(this.audio.setting);
this.storage(this.audio.setting)
},
buildMenu(){
let arr = [], children = [];
arr.push({
text: '自動播放',
icon: "" + (this.audio.setting.autoPlay == true ? "ivu-icon-md-checkmark ivu-icon" : "")
});
if(this.isChinese() == true) {
arr.push({
text: '中文',
icon: "" + (this.audio.setting.chinese == true ? "ivu-icon-md-checkmark ivu-icon" : "")
});
this.changeChinese();
setTimeout(()=>{
this.renderBubble();
}, 300);
}
children = [{text: "大", value: 1.7}, {text: "中", value: 1.5}, {text: "正常", value: 1.2}]; //, {text: "小", value: 1}
children.forEach(item=>{
if(this.zoom == item.value)
item.icon = "ivu-icon-md-checkmark ivu-icon";
})
arr.push({text: '字體',children: children});
children = [{text: "慢", value: 0.9}, {text: "正常", value: 1}, {text: "快", value: 1.2}];
let label = "";
children.forEach(item=>{
if(this.audio.setting.rate == item.value) {
label = " - " + item.text;
item.icon = "ivu-icon-md-checkmark ivu-icon";
}
})
arr.push({text: '速率' + label, children: children});
children = [];
this.options.repeat.forEach(item =>{
children.push({
text: item == 0 ? "關閉" : item + " 次",
value: item,
icon: this.audio.setting.repeat == item ? "ivu-icon-md-checkmark ivu-icon" : ""
});
})
arr.push({text: '重複播放 - ' + (this.audio.setting.repeat > 0 ? this.audio.setting.repeat + " 次" : "關閉"), children: children});
if(this.audio.setting.repeat > 1 && this.state == "play")
this.displayVocabulary = false;
if(this.audio.setting.repeat > 0) {
// range: [{label: "字幕", value: "lrc"}, {label: "段落", value: "paragraph"}],
children = [];
this.options.range.forEach(item =>{
children.push({
text: item.label,
value: item.value,
icon: this.audio.setting.range == item.value ? "ivu-icon-md-checkmark ivu-icon" : ""
});
})
arr.push({text: '重複範圍 - ' + (this.audio.setting.range == "lrc" ? "字幕" : "段落"),
children: children
});
// --------------------------------
arr.push({text: '重複中斷', icon: this.audio.setting.interrupt == true ? "ivu-icon-md-checkmark ivu-icon" : ""});
// --------------------------------
children = [];
this.options.interval.forEach(item =>{
children.push({
text: Math.abs(item) + (item > 0 ? " 秒" : " 倍"),
value: item,
icon: this.audio.setting.interval == item ? "ivu-icon-md-checkmark ivu-icon" : ""
});
})
arr.push({text: '重複間距 - ' +
Math.abs(this.audio.setting.interval) + " " + (this.audio.setting.interval > 0 ? "秒" : "倍"),
children: children
});
// --------------------------------
}
this.cmList = this.$isSmallScreen() ? [] : arr;
},
onMenuClick(e){
// https://vuejsexamples.com/a-simple-and-easy-to-use-context-menu-with-vue/
if(this.cmList[e[0]].text == "自動播放") {
this.audio.setting.autoPlay = !this.audio.setting.autoPlay;
} else if(this.cmList[e[0]].text.indexOf("中文") > -1) {
this.audio.setting.chinese = !this.audio.setting.chinese;
} else if(this.cmList[e[0]].text == "字體") {
this.zoom = this.cmList[e[0]].children[e[1]].value;
document.getElementById("readerFrame").style.zoom = this.zoom;
window.localStorage["VOA-zoom"] = this.zoom;
this.renderBubble();
this.buildMenu();
return;
} else if(this.cmList[e[0]].text.indexOf("速率") > -1) {
this.audio.setting = Object.assign(this.audio.setting, {rate: this.cmList[e[0]].children[e[1]].value});
} else if(this.cmList[e[0]].text.indexOf("重複播放") > -1) {
let update = this.audio.setting.repeat == 0 || this.cmList[e[0]].children[e[1]].value == 0 ? true : false;
this.audio.setting = Object.assign(this.audio.setting, {repeat: this.cmList[e[0]].children[e[1]].value});
if(this.cmList[e[0]].children[e[1]].value == 0) {
this.audio.setting.interrupt = false;
}
this.audio.block = this.audio.setting.repeat == 0 ? [] : this.block;
if(update == true) {
this.html = this.source.html + "<div style='display: none;'>" + (new Date()) + "</div>";
this.audio.audio.pause();
clearInterval(this.audio.timeID);
this.audio.repeat = 0;
setTimeout(() => {
this.retrieve(true);
}, 300);
}
this.repeat = this.audio.setting.repeat;
} else if(this.cmList[e[0]].text == "重複中斷") {
this.audio.setting = Object.assign(this.audio.setting, {interrupt: ! this.audio.setting.interrupt});
} else if(this.cmList[e[0]].text.indexOf("重複間距") > -1) {
this.audio.setting = Object.assign(this.audio.setting, {interval: this.cmList[e[0]].children[e[1]].value});
} else if(this.cmList[e[0]].text.indexOf("範圍") > -1) {
if(this.audio.setting.range == this.cmList[e[0]].children[e[1]].value) return;
let range = this.cmList[e[0]].children[e[1]].value;
let paragraph = 0, state = this.audio.state;
if(state != "stop") {
paragraph = this.audio.paragraph;
this.audio.stop();
}
this.audio.setting = Object.assign(this.audio.setting, {range});
if(state != "stop") {
setTimeout(() => {
this.audio.gotoParagraph(paragraph);
this.audio.play();
}, 600);
}
}
// window.localStorage["VOA-Reader"] = JSON.stringify(this.audio.setting);
this.storage(this.audio.setting)
this.buildMenu();
},
async getHistory(){
if(!this.login) return;
try {
let snapshot1 = await FireStore.db.collection("users").doc(FireStore.uid())
.collection("history").doc(this.source.key)
.get();
return snapshot1.data();
} catch(e) {
// console.log(e)
// vm.showMessage(typeof e == "object" ? JSON.stringify(e) : e);
}
},
async setHistory(arg){
if(!this.login) return;
let ref = FireStore.db.collection("users").doc(FireStore.uid())
.collection("history").doc(this.source.key);
let obj = {
// modifyDate: (new Date()).toString("yyyymmddThhMM"),
vocabulary: this.vocabulary,
report: this.source.report,
block: this.audio.block.length == 2 ? [this.audio.block[0], this.audio.block[1]] : []
}
if(typeof arg == "object")
obj = Object.assign(obj, arg);
try {
let x = await ref.set(obj,{merge: true});
if(arg == "vocabulary") {
this.$emit("onUpdate", "vocabulary", this.vocabulary);
} else if(typeof arg == "object") {
this.$emit("onUpdate", "json", arg);
}
} catch(e) {
console.log(e)
throw e;
}
},
updateVocabulary(rows){
rows = rows.filter(word => typeof word == "string" && word.length > 0);
if(rows.length > 0)
this.vocabulary = rows.join("\n");
else
this.vocabulary = ""
this.setHistory("vocabulary");
},
onClickBubble(e, index){
let self = this;
// console.log(e)
let pk = navigator.userAgent.indexOf('Macintosh') > -1 ? e.metaKey : e.ctrlKey;
let sk = e.shiftKey, code = e.keyCode;
if(pk == false && sk == false) {
let arr = document.querySelectorAll("#renderMarker .active");
if(arr.length == 0 && e.target.classList.contains("active") == false){
clearBubble();
if(this.audio.paragraph != index)
this.audio.assignParagraph(index, true);
}
} else if(pk == true && sk == true) {
} else {
let start = -1, end = -1;
let current = parseInt(e.target.id.replace("bubble", ""), 10);
if(pk == true && sk == false) {
let active = e.target.classList.contains("active");
clearBubble();
if(active == false) {
e.target.classList.add("active");
this.audio.block = [index, index];
} else {
this.audio.block = [];
}
this.assignBlock(this.audio.block);
} else if(sk == true && pk == false) {
let arr = document.querySelectorAll("#renderMarker .active");
for (let i = 0; i < arr.length; ++i) {
let item = arr[i];
let el = parseInt(item.id.replace("bubble", ""), 10);
if(start == -1 || el < start)
start = el;
if(end == -1 || el > end)
end = el;
}
if(start == -1) return;
if(current < start)
start = current;
else if(current > end)
end = current;
else if(current > start)
start = current;
this.audio.block = [start, end];
this.assignBlock(this.audio.block);
this.renderActiveBubble();
} else {
return
}
if(this.audio.paragraph < this.audio.block[0] || this.audio.paragraph > this.audio.block[1]){
this.audio.assignParagraph(this.audio.block[0], true);
}
this.saveBlock();
}
function clearBubble() {
let arr = document.querySelectorAll("#renderMarker .active");
arr.forEach(item=>{
item.classList.remove("active");
});
self.audio.block = [];
return arr.length;
}
},
saveBlock(){
let self = this;
if(this.login == true)
this.setHistory()
else{
let s = window.localStorage["VOA-Blocks-" + self.source.report];
let arr = (typeof s == "string" && s.length > 0) ? JSON.parse(s) : [];
for(let i = 0; i < arr.length; i++){
if(arr[i].key == self.source.key) {
arr.splice(i, 1);
break;
}
}
arr.unshift({key: self.source.key, block: self.audio.block});
for(let i = arr.length - 1; i >= 0; i--){
if(arr[i].block.length == 0)
arr.splice(i, 1);
}
for(let i = arr.length - 1; i >= 10; i--){
arr.splice(i, 1);
}
if(arr.length > 0)
window.localStorage["VOA-Blocks-" + self.source.report] = JSON.stringify(arr);
else
delete window.localStorage["VOA-Blocks-" + self.source.report];
}
},
onResize(){
clearTimeout(this.resizeId);
this.resizeId = setTimeout(()=>{
this.width = document.body.clientWidth;
this.renderBubble();
}, 100);
},
storage(data){
let key = "VOA-Reader-" + this.source.report;
if(typeof data == "undefined") {
let def = {
key: this.source.key,
autoPlay: false,
rate: 0.9,
repeat: this.favorite == true ? 2 : 3,
interval: 5,
interrupt: false,
chinese: true,
range: this.favorite == true ? "paragraph" : "lrc"
}
let s = window.localStorage[key], d = null;
if(typeof s == "string" && s.length > 0) {
let arr = JSON.parse(s);
for(let i = 0; i < arr.length; i++) {
if(arr[i].key == this.source.key) {
d = arr[i]
break;
}
}
// if(d == null && arr.length > 0) {
// d = Object.assign(arr[0], {key: this.source.key});
// }
}
return Object.assign(def, d);
} else {
let setting = [data]
let s = window.localStorage[key];
if(typeof s == "string" && s.length > 0) {
let arr = JSON.parse(s);
for(let i = 0; i < arr.length; i++) {
if(arr[i].key == this.source.key) {
continue;
} else if(i > 50) {
break;
} else {
setting.push(arr[i])
}
}
}
window.localStorage[key] = JSON.stringify(setting)
}
},
assignBlock(block) {
this.block = block;
if(typeof this.audio == "object" && this.audio != null){
this.audio.checkLoop();
}
},
async initial(){
let self = this;
if(this.login == true) {
let data = await this.getHistory();
this.favorite = typeof data == "object" && data.favorite == true ? true : false;
if(data && typeof data.vocabulary == "string") {
this.vocabulary = data.vocabulary;
}
// if(this.vocabulary.length > 0 && setting.autoPlay == false && !this.$isSmallScreen())
// this.displayVocabulary = true;
if(data && Array.isArray(data.block)) {
this.assignBlock(data.block);
}
} else {
s = window.localStorage["VOA-Blocks-" + this.source.report];
let arr = (typeof s == "string" && s.length > 0) ? JSON.parse(s) : [];
this.assignBlock([]);
if(Array.isArray(arr)) {
arr.forEach(item=>{
if(item.key == this.source.key) {
this.assignBlock(item.block);
}
});
}
}
let setting = this.storage();
this.repeat = setting.repeat;
// console.log(this.block)
this.audio = new Player({block: this.repeat == 0 ? [] : this.block});
this.audio.setting = setting;
this.audio.state = "stop";
if(this.$isFlutter() && typeof this.source.mp3Path == 'string') {
this.url = await this.$toBase64(this.source.mp3Path);
} else
this.url = await FireStore.downloadFileURL("VOA/" + this.source.report + "/" + this.source.key + ".mp3");
this.audio.src = this.url;
document.getElementById("readerFrame").style.zoom = this.zoom;
window.addEventListener('keydown', this.onKeydown, false);
// window.addEventListener('resize', this.onResize, false);
window.addEventListener("popstate", this.onPopState);
self.audio.onStateChange = (e, v1, v2, v3) => {
// console.log("onStateChange.state: " + e + "; " + (new Date()))
if(this.modal == false) return;
if(e == "durationChange") {
this.duration = v1;
this.retrieve();
} else if(e == "canPlay") {
} else if(e == "timeUpdate") {
this.currentTime = v1;
// console.log(this.currentTime)
} else if(e == "sectionChange"){
this.repeatTimes = typeof v3 == "undefined" ? 1 : v3;
let arr = document.querySelectorAll(".english span.active");
arr.forEach(item=>{
item.classList.remove("active");
})
if(typeof v2 == "undefined") { // 通知要從頭開始
this.currentTime = this.audio.currentTime ;
v2 = 0;
this.$Notice.info({
title: '請稍候!!',
});
}
let el = document.querySelector("#l" + v1 + "_" + v2);
if(el != null)
el.classList.add("active");
this.scrollTo(document.querySelector("#p" + v1));
} else if(e == "play" || e == "stop" || e == "pause" || e == "interrupt") {
// console.log(e)
let state = this.state;
if(state == "interrupt") { //
this.$Notice.close("interrupt");
} else if(e == "interrupt") {
this.$Notice.info({
title: '請按空白鍵再聽一次,或按方向鍵',
duration: 0,
name: "interrupt"
});
} else if(e == "play") {
if(this.passTime == 0) {
this.finalCount(e);
}
this.audio.checkLoop();
this.setHistory({listenDate: (new Date()).getTime()});
} else if(e == "stop") {
this.finalCount(e);
this.currentTime = this.audio.currentTime;
let context = document.querySelector("#context");
if(context == null) return;
context.scrollTop = 0;
let el = document.querySelector(".english span.active");
if(el != null) {
el.classList.remove("active");
}
}
this.state = e;
if(this.$isFlutter() && (e == "play" || e == "stop" || e == "pause")) {
let obj = {state: e, title: this.source.title, report: this.source.report,
// index: this.source.index, total: this.source.total
};
Flutter.postMessage(JSON.stringify(obj));
// console.log("Flutter.postMessage: " + JSON.stringify(obj))
}
} else if(e == "repeat"){
// console.log("repeat: " + v1)
this.repeatTimes = v1 + 1;
}
}
this.buildMenu();
},
scrollTo(el) {
if(el == null) return;
let offsetTop = el.offsetTop;
let offsetBottom = offsetTop + el.clientHeight;
let viewer = document.querySelector("#readerFrame");
let scrollTop = viewer.scrollTop, clientHeight = viewer.clientHeight;
if(offsetTop >= scrollTop && offsetBottom < scrollTop + clientHeight){
} else {
viewer.scrollTop = offsetTop - 60;
}
},
onClickSleep(e) {
this.sleep = e;
window.localStorage["VOA-sleep"] = this.sleep;
// this.storage(this.audio.setting)
this.finalCount(this.state)
},
finalCount(state){
this.passTime = 0;
if(typeof this.finalCountID != "undefined") {
clearInterval(this.finalCountID);
delete this.finalCountID;
}
let start = (new Date()).getTime();
if(state != "stop") {
this.finalCountID = setInterval(() => {
let now = (new Date()).getTime() - start;
this.passTime = Math.ceil(now / (1000));
if((this.sleep * 60) - this.passTime <= 0) {
this.audio.stop(true);
}
// console.log("finalCount: " + now)
}, 500);
}
},
onKeydown(event){
if(this.audio.canPlay == false) return;
let self = this;
let o = document.activeElement;
let pk = navigator.userAgent.indexOf('Macintosh') > -1 ? event.metaKey : event.ctrlKey;
let ak = navigator.userAgent.indexOf('Macintosh') > -1 ? event.ctrlKey : event.altKey;
let sk = event.shiftKey, code = event.keyCode;
let char = (event.keyCode >=48 && event.keyCode <=122) ? String.fromCharCode(event.keyCode).toUpperCase() : ""
// console.log("key: " + code + ", cmd: " + pk + ", shift: " + sk +
// ", char: " + char + " / " + typeof(char))
// console.log(o.tagName + ": " + o.contentEditable)
if(((pk == true && sk == false) || (pk == false && sk == true)) && code >= 48 && code <= 57) {
char = parseInt(char, 10) - 1;
if(pk == true){
this.audio.restart(null, char);
} else {
this.audio.restart(char, 0, true);
}
// let p = sk == true ? char : null;
// let l = sk == true ? 0 : char;
// this.audio.restart(p, l)
} else if(pk == true && char == "S" && this.mode == "edit"){// 存檔
refresh();
} else if(pk == true && char == "P"){ // 播放
this.audio.play();
} else if(pk == true && char == "S"){ // stop
this.audio.stop();
} else if(pk == true && char == "E" && this.mode == "edit"){// 存檔
refresh();
this.mode = "";
setTimeout(() => {
document.getElementById("readerFrame").style.zoom = self.zoom;
self.retrieve(true);
}, 600);
// this.onPopState();
} else if(o.tagName == "INPUT" || o.tagName == "TEXTAREA"){
return;
} else if(pk == true && char == "M" && this.login == true){ // m, 加入筆記
let ss = window.getSelection().toString().trim();
let sel = window.getSelection();
let range = sel.getRangeAt(0);
range.deleteContents();
let div = document.createElement("span");
div.className = "highlight";
div.innerHTML = ss;
div.setAttribute("data", ss)
range.insertNode(div);
div.addEventListener('click', function (e) {
let ss = e.target.getAttribute("data");
self.$yahoo(ss)
}, false);
if(("\n" + this.vocabulary + "\n").indexOf("\n" + ss + "\n") == -1) {
this.vocabulary += (this.vocabulary.length > 0 ? "\n" : "") + ss;
this.setHistory("vocabulary");
}
} else if(pk == true && char == "B"){ //b, 開啓段落區塊對話
if(this.audio.setting.repeat > 0)
this.displayParagraph = !this.displayParagraph;
} else if(pk == true && char == "G"){ //g, google
let ss = window.getSelection().toString().trim();
if(ss.length > 0) this.$google(ss)
} else if(pk == true && char == "Y"){ //y, yahoo
let ss = window.getSelection().toString().trim();
if(ss.length > 0) this.$yahoo(ss)
} else if(code == 112 || (sk == true && char == "T")){ //t, f1 開翻譯網站
this.toTranslate();
} else if(this.$isAdmin() == true && code == 121 || (sk == true && char == "C")){ //c, f10 寫入中文
this.toChinese();
} else if(code == 113){ // f2
this.showContext();
} else if(pk == true && char == "E" && this.$isAdmin() == true){ //e, 編輯
if(this.mode == "edit") {
} else {
this.mode = "edit";
this.audio.pause();
this.displayVocabulary = false;
setTimeout(() => {
self.$refs["textarea"].focus();
}, 300);
}
} else if(code == 27){ // esc
this.displayVocabulary = false;
// } else if(this.displayVocabulary == true) {
// return;
} else if(sk && pk && char == "V" && this.login == true && this.mode != "edit"){ // Cmd + shift + V, 單字清單
this.displayVocabulary = !this.displayVocabulary;
} else if(code == 32){ //空格鍵,interrupt
this.onInterrupt();
} else if(this.block.length == 2 && ((this.block[0] == this.block[1]) || (pk == true && sk == true)) && (code == 38 || code == 40)) { // up, down; 移動 blocks
let arr = document.querySelectorAll("#renderMarker .active");
if(arr.length > 0){
let start = -1, end = -1;
for (let i = 0; i < arr.length; ++i) {
let item = arr[i];
let el = parseInt(item.id.replace("bubble", ""), 10);
if(start == -1 || el < start)
start = el;
if(end == -1 || el > end)
end = el;
}
arr = document.querySelectorAll("#renderMarker .speech-bubble");
if(start == -1 || end == -1 || (code == 38 && start == 0) || (code == 40 && end == arr.length - 1))
return;
start = start + (code == 38 ? -1 : 1);
end = end + (code == 38 ? -1 : 1);
if(start < 0)
start = 0;
else if(start > arr.length - 1)
start = arr.length - 1;
if(end > arr.length - 1) end = arr.length - 1;
if(end < start) end = start;
this.audio.block = [start, end];
this.assignBlock(this.audio.block);
this.renderActiveBubble();
if(this.audio.paragraph < this.audio.block[0] || this.audio.paragraph > this.audio.block[1]){
this.audio.assignParagraph(this.audio.block[0], true);
}
this.saveBlock();
}
} else if(code == 37 || code == 39 || code == 38 || code == 40) { // left, right, u, d
let arr = document.querySelectorAll(".english span.active");
if(code == 37 || code == 39) { // left, right
if(arr.length == 0)
this.audio.gotoLRC("first");
else if(pk == true)
this.audio.gotoLRC(code == 37 ? "first" : "end")
else
this.audio.gotoLRC(code == 37 ? -1 : 1)
} else
if(arr.length == 0)
this.audio.gotoParagraph("first");
else if(pk == true)
this.audio.gotoParagraph(code == 38 ? "first" : "end")
else
this.audio.gotoParagraph(code == 38 ? -1 : 1)
} else {
return;
}
event.preventDefault();
event.stopImmediatePropagation();
event.stopPropagation();
function refresh() {
let html = self.$refs["textarea"].value;
self.$emit("onUpdate", "html", html);
self.$set(self.source, 'html', html);
self.html = self.source.html;
}
},
isChinese() {
return this.source && this.source.html.indexOf("<div class='chinese'>") > -1;
},
onSlideChange(e){
this.audio.currentTime = e;
},
changeChinese(){
let arr = document.querySelectorAll(".chinese");
arr.forEach((item)=>{
item.style.display =
this.audio.setting.chinese == true ? "block" : "none";
});
},
format(start) {
if(start == 0 || isNaN(start))
return "00:00";
else {
let s = Math.floor(start / 60);
let m = Math.floor(start - (s * 60));
if(m == 60){
m = 0;
s++;
}
return s.leftPadding(2, '0') + ":" + m.leftPadding(2, '0').substr(0,2);
}
},
onPopState(e){
this.$emit("onClose");
if(typeof e == "undefined") {
history.back();
}
this.$destroy();
},
convertTime(start){
if(start == 0 || isNaN(start))
return "00:00";
else {
let s = Math.floor(start / 60);
let m = Math.floor(start - (s * 60));
if(m == 60){
m = 0;
s++;
}
return s.leftPadding(2, '0') + ":" + m.leftPadding(2, '0').substr(0,2);
}
},
retrieve(again){
let lrcs = []; this.marks = {};
let context = document.querySelector("#context");
if(context != null) context.style.visibility = "hidden";
let arr1 = document.querySelectorAll(".chinese");
this.changeChinese();
arr1 = document.querySelectorAll(".english");
if(this.audio.setting.repeat > 0 && arr1.length > 0) {
let i = arr1.length - 1;
while(i >= 0) {
if(arr1[i].parentNode.getAttribute("ignore") != null) {
arr1[i].parentNode.parentNode.removeChild(arr1[i].parentNode);
} else if(arr1[i].getAttribute("ignore") != null) {
arr1[i].parentNode.parentNode.removeChild(arr1[i].parentNode);
} else if(arr1[i].innerHTML.indexOf("ignore") > -1) {
let arr2 = arr1[i].querySelectorAll("span");
let j = arr2.length - 1;
while(j >= 0) {
if(arr2[j].getAttribute("ignore") != null) {
arr2[j].parentNode.removeChild(arr2[j]);
}
j--;
}
}
i--;
}
arr1 = document.querySelectorAll(".english");
}
let arr = document.querySelectorAll(".english span");
let dealine = 0.5;
for(let i = 0; i < arr.length; i++) {
let start = arr[i].getAttribute("start");
let end = arr[i].getAttribute("end");
if(start != 0 && i > 0) {
if(arr[i - 1].getAttribute("end") == null)
arr[i - 1].setAttribute("end", start - dealine);
}
if(i == 0 && start == null){
arr[i].setAttribute("start", 0);
} else if(i == arr.length - 1 && (end == null || end >= this.duration)){
arr[i].setAttribute("end", this.duration - dealine);
}
}
arr1.forEach((item1, index1)=>{
let arr2 = item1.querySelectorAll("span");
let arr3 = [];
arr2.forEach((item2, index2)=>{
let start = item2.getAttribute("start");
let end = item2.getAttribute("end");
if(isNaN(start) || start == null || isNaN(end) || end == null) {
if(item2.innerHTML.lastIndexOf("<strong") == -1){
vm.showMessage("下列位置沒有 lrc ", "block: " + index1 + ", lrc: " + index2 )
console.log(item1)
}
} else {
item2.id = "l" + lrcs.length + "_" + arr3.length;
arr3.push({start: parseFloat(start), end: parseFloat(end)})
}
});
if(arr3.length > 0) {
item1.id = "p" + lrcs.length;
lrcs.push(arr3);
let start = arr3[0].start;
let rate = Math.floor(start);
if(lrcs.length > 1 && !this.$isSmallScreen()) {
this.marks[rate] = lrcs.length + "";
}
}
});
this.audio.LRCs = lrcs;
let start = this.audio.setting.repeat > 0 && this.block.length > 0 ? this.block[0] : 0;
if(this.audio.setting.repeat > 0) {
if(lrcs.length > 0 && lrcs[start].length > 0) {
if(!isNaN(lrcs[start][0].start)) {
this.audio.currentRange = null; //lrcs[start][0];
this.audio.currentTime = lrcs[start][0].start;
}
}
} else {
this.audio.currentRange = null;
this.audio.currentTime = 0;
}
this.currentTime = this.audio.currentTime;
if(typeof again == "boolean" && this.state == "play") {
this.audio.audio.play();
this.audio.timing();
}
setTimeout(()=>{
this.renderBubble();
if(this.audio.setting.repeat > 0 && this.block.length > 0)
this.scrollTo(document.querySelector("#p" + this.block[0]));
}, 100);
setTimeout(()=>{
this.convertVocabulary();
if(context != null) context.style.visibility = "visible";
}, 200);
},
convertVocabulary(){
let self = this;
let html = context.innerHTML;
let arr = this.vocabulary.split("\n");
arr.forEach((item, index)=>{
if(item.indexOf("..") == -1) {
if(item.indexOf("(") == -1)
replaceItem(item, item);
else {
let arr2 = item.split("(")
replaceItem(arr2[1].replace(")", ""), arr2[0]);
}
}
});
context.innerHTML = html;
setTimeout(() => {
let arr = document.querySelectorAll("#context span.highlight");
for(let i = 0; i < arr.length; i++) {
arr[i].addEventListener('click', function (e) {
let ss = e.target.getAttribute("data");
self.$yahoo(ss)
}, false);
}
}, 300);
function replaceItem(item, value) {
// if(item != value) console.log(item, value)
item = item.trim();
let i = html.toUpperCase().indexOf(item.toUpperCase());
if(i > -1) {
let s1 = html.substr(0, i)
let s2 = html.substr(i, item.length)
let s3 = html.substr(i + item.length)
html = s1 + "<span class='highlight' data='" + value + "'>" + s2 + "</span>" + s3;
}
}
},
onScroll(e){
if(this.repeat == 0) return;
let readerFrame = document.getElementById("readerFrame");
let board = document.getElementById("board");
if(board != null) {
if(readerFrame.scrollTop > 100){
board.style.top = "0px";
board.style.removeProperty("bottom")
} else {
board.style.bottom = "0px";
board.style.removeProperty("top")
}
// console.log(readerFrame.scrollTop,
// "top: " + board.style.top + ", bottom: " + board.style.bottom)
}
},
renderBubble(){
if(this.repeat == 0) return;
this.bubbles = [];
let arr = document.querySelectorAll(".p");
let top = 7;
arr.forEach((item, index)=>{
this.bubbles.push({
top: top,
height: item.getBoundingClientRect().height + (index > 0 ? 14 : 0)
});
top += item.getBoundingClientRect().height + 14;
});
let context = document.querySelector("#context");
let el = document.querySelector("#renderMarker");
if(el != null) el.style.height = top + "px";
setTimeout(()=>{
this.renderActiveBubble();
}, 300);
setTimeout(()=>{
this.onScroll();
}, 1000);
},
renderActiveBubble(){
// if(this.block.length == 2) {
let arr = document.querySelectorAll("#renderMarker .speech-bubble");
arr.forEach((item, index)=>{
if(this.block.length == 2 && index >= this.block[0] && index <= this.block[1])
item.classList.add("active");
else
item.classList.remove("active");
});
// }
}
},
computed: {
position: {
get: function () {
let i = typeof this.audio == "object" ? (this.currentTime / this.duration) * 100 : 0;
// console.log(i + ": " + this.currentTime + "/" + this.duration)
return i;
},
set: function(index) {
console.log("position: " + index)
}
}
},
watch: {
source(value) {
console.log(this.source)
},
repeat(value) {
if(value > 1 && this.state == "play") {
setTimeout(() => {
this.onScroll()
}, 300);
}
},
state(value) {
if(value == "play" && this.repeat > 1) {
setTimeout(() => {
this.onScroll()
}, 300);
}
}
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.