text
stringlengths 7
3.69M
|
|---|
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setActivity("Rickrolled" , {type:"WATCHING"})
client.guilds.forEach((guild) => {
console.log(" - " + guild.name)
guild.channels.forEach((channel) => {
console.log(` - ${channel.name} ${channel.type} ${channel.id}`)
})
})
})
client.on('message' , (receivedMessage) =>{
if (receivedMessage.author ==client.user){
return
}
receivedMessage.react("🌿")
receivedMessage.react("🍪")
if (receivedMessage.content.startsWith("!")){
processCommand(receivedMessage)
}
})
function processCommand(receivedMessage){
let fullcommand = receivedMessage.content.substr(1)
let splitCommand = fullCommand.split(" ")
let primaryCommand = splitCommand[0]
let arguments = splitCommand.slice(1)
}
client.login("YOUR TOKEN");
|
// pages/foodSuccess/foodSuccess.js
//获取应用实例
const app = getApp();
Page({
/**
* 页面的初始数据
*/
data: {
orderNum: 0,
banner: ""
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
this.setData({
orderNum: options.orderNum
})
this.getBanner();
wx.setNavigationBarTitle({
title: app.globalData.cinemaList.cinemaName
});
},
look: function() {
var that = this;
var orderNum = this.data.orderNum;
wx.redirectTo({
url: '../goodsOrderDetail/goodsOrderDetail?orderNum=' + orderNum
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {
wx.setNavigationBarTitle({
title: app.globalData.cinemaList.cinemaName
});
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {
return {
title: app.globalData.cinemaList.cinemaName,
path: '/pages/index/index'
}
},
getBanner: function() { //获取轮播图
var that = this;
var nowtime = new Date().getTime();
var sign = app.createMD5('banners', nowtime);
},
bannerTap: function(e) {
var index = e.currentTarget.dataset.index;
var banner = this.data.banner;
var num = banner[index].playType;
if (num == 1 || num == 3) {
var url = banner[index].redirectUrl;
if (url != "") {
app.globalData.acivityUrl = url;
wx.navigateTo({
url: '../acivityUrl/acivityUrl',
})
}
} else if (num == 2 && banner[index].dxMovie != null) {
var id = banner[index].dxMovie.id;
var movieList = app.globalData.movieList;
for (var i = 0; i < movieList.length; i++) {
if (movieList[i].id == id) {
app.globalData.movieIndex = i;
wx.navigateTo({
url: '../movieDetail/movieDetail',
})
}
}
}
}
})
|
var _ = jst.DomX;
var ctPanel = null, contentLayout = null, mainLayout = null, crumbArea = null;
jst.complete(function() {
crumbArea = _.$("crumbArea");
ctPanel = new jst.ui.FlowPanel({
border : 0
});
ctPanel.setEl("content");
contentLayout = new jst.ui.BorderLayout({ // 内容区布局,不设定autoResize,由主布局驱动;
center : {
dest : ctPanel
}
});
mainLayout = new jst.ui.BorderLayout({ // 主布局;
bgColor : "#66FF66",
north : {
dest : "header",
size : 40,
resize : false
},
south : {
dest : "footer",
size : 20,
resize : false
},
west : {
dest : "nav",
size : 180,
resize : true
},
center : { // 中部区域使用内容区布局;
dest : contentLayout
},
autoResize : true
});
mainLayout.fill("container");
});
|
import React, { useContext } from 'react';
// Context
import { ProductContext } from '../contexts/ProductContext';
const Product = props => {
const { products, addItem } = useContext(ProductContext);
return (
<div className="product">
<img src={props.product.image} alt={`${props.product.title} book`} />
<h1 className="title">{props.product.title}</h1>
<p className="price">${props.product.price}</p>
<button onClick={() => addItem(props.product)}>
Add to cart
</button>
</div>
);
};
export default Product;
// receives product data through props and displays it
// receives addItem and sets it up as an onClick handler
// one way I could make this work with contextAPI is :
// iterate with a key that is used to access my ContextObject's array item
// and get data needed by this Product component's current iteration
|
var searchData=
[
['fixoutofboundsuvs',['fixOutOfBoundsUVs',['../class_m_b2___texture_bake_results.html#a2691265940fa5099d4d559875ba02a72',1,'MB2_TextureBakeResults']]]
];
|
#!/usr/bin/env node
// in the Script Goal
'use strict';
console.log(1);
----------------------------------------------------
[
["hashbang", "#!/usr/bin/env node"],
["comment", "// in the Script Goal"],
["string", "'use strict'"],
["punctuation", ";"],
"\r\nconsole",
["punctuation", "."],
["function", "log"],
["punctuation", "("],
["number", "1"],
["punctuation", ")"],
["punctuation", ";"]
]
|
var app;
(function () {
'use strict';
app = angular.module("ticModule", [
'ui.bootstrap']);
})();
(function () {
app.controller('ticController', function ($scope, $http, $compile, $uibModal, $timeout) {
$scope.ticArray = [null, null, null, null, null, null, null, null, null];
$scope.letter = 'X';
$scope.row1 = false;
$scope.row2 = false;
$scope.row3 = false;
$scope.column1 = false;
$scope.column2 = false;
$scope.column3 = false;
$scope.diagonal1 = false;
$scope.diagonal2 = false;
$scope.checkForWin = function () {
if ($scope.ticArray[0] != null && $scope.ticArray[1] != null && $scope.ticArray[2] != null) {
if ($scope.ticArray[0] == $scope.ticArray[1]
&& $scope.ticArray[1] == $scope.ticArray[2]) {
$scope.row1 = true;
$scope.launchModal($scope.ticArray[0]);
}
}
if ($scope.ticArray[3] != null && $scope.ticArray[4] != null && $scope.ticArray[5] != null) {
if ($scope.ticArray[3] == $scope.ticArray[4]
&& $scope.ticArray[3] == $scope.ticArray[5]) {
$scope.row2 = true;
$scope.launchModal($scope.ticArray[3]);
}
}
if ($scope.ticArray[6] != null && $scope.ticArray[7] != null && $scope.ticArray[8] != null) {
if ($scope.ticArray[6] == $scope.ticArray[7]
&& $scope.ticArray[6] == $scope.ticArray[8]) {
$scope.row3 = true;
$scope.launchModal($scope.ticArray[6]);
}
}
if ($scope.ticArray[0] != null && $scope.ticArray[3] != null && $scope.ticArray[6] != null) {
if ($scope.ticArray[0] == $scope.ticArray[3]
&& $scope.ticArray[0] == $scope.ticArray[6]) {
$scope.column1 = true;
$scope.launchModal($scope.ticArray[0]);
}
}
if ($scope.ticArray[1] != null && $scope.ticArray[4] != null && $scope.ticArray[7] != null) {
if ($scope.ticArray[1] == $scope.ticArray[4]
&& $scope.ticArray[1] == $scope.ticArray[7]) {
$scope.column2 = true;
$scope.launchModal($scope.ticArray[1]);
}
}
if ($scope.ticArray[2] != null && $scope.ticArray[5] != null && $scope.ticArray[8] != null) {
if ($scope.ticArray[2] == $scope.ticArray[5]
&& $scope.ticArray[2] == $scope.ticArray[8]) {
$scope.column3 = true;
$scope.launchModal($scope.ticArray[2]);
}
}
if ($scope.ticArray[0] != null && $scope.ticArray[4] != null && $scope.ticArray[8] != null) {
if ($scope.ticArray[0] == $scope.ticArray[4]
&& $scope.ticArray[0] == $scope.ticArray[8]) {
$scope.diagonal1 = true;
$scope.launchModal($scope.ticArray[0]);
}
}
if ($scope.ticArray[2] != null && $scope.ticArray[4] != null && $scope.ticArray[6] != null) {
if ($scope.ticArray[2] == $scope.ticArray[4]
&& $scope.ticArray[2] == $scope.ticArray[6]) {
$scope.diagonal2 = true;
$scope.launchModal($scope.ticArray[2]);
}
}
if ($scope.ticArray[0] != null && $scope.ticArray[1] != null && $scope.ticArray[2] != null
&& $scope.ticArray[3] != null && $scope.ticArray[4] != null && $scope.ticArray[5] != null
&& $scope.ticArray[6] != null && $scope.ticArray[7] != null && $scope.ticArray[8] != null
&& $scope.row1 == false && $scope.row2 == false && $scope.row3 == false
&& $scope.column1 == false && $scope.column2 == false && $scope.column3 == false
&& $scope.diagonal1 == false && $scope.diagonal2 == false) {
$scope.launchModal(null);
}
}
$scope.launchModal = function (letter) {
$scope.disable = true;
$timeout(function () {
var winner = {};
winner.letter = letter;
var modalInstance = $uibModal.open({
animation: true,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'winnerModal.html',
controller: 'winnerModalCtrl',
controllerAs: '$ctrl',
size: 'lg',
resolve: {
winner: winner
}
});
modalInstance.result.then(function () {
$scope.ticArray = [null, null, null, null, null, null, null, null, null];
$scope.letter = 'X';
$scope.row1 = false;
$scope.row2 = false;
$scope.row3 = false;
$scope.column1 = false;
$scope.column2 = false;
$scope.column3 = false;
$scope.diagonal1 = false;
$scope.diagonal2 = false;
$scope.disable = false;
});
}, 1200);
}
Array.prototype.isNull = function () {
return this.join().replace(/,/g, '').length === 0;
};
$scope.$watch(function () {
return $scope.ticArray;
}, function (newValue, oldValue) {
if (!$scope.ticArray.isNull()) {
if ($scope.letter == 'X') {
$scope.letter = 'O'
}
else
$scope.letter = 'X'
$scope.checkForWin();
}
}, true);
});
})();
app.controller('winnerModalCtrl', ['$scope', '$uibModalInstance', 'winner',
function ($scope, $uibModalInstance, winner) {
$scope.letter = winner.letter
$scope.restart = function () {
$uibModalInstance.close('ok');
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
}]);
|
import 'foundation-sites/dist/foundation.css';
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import { apiHost, routing } from './app.config';
import moviesPage from './container/movies-page';
export default angular.module('app', [uiRouter, moviesPage])
.config(routing)
.value('apiHost', apiHost)
.name;
|
//Base
import React, { Component } from 'react';
//Component
import Navigation from '../../../molecules/Navigation';
class Navi extends Component {
render() {
let navLinks = [
{
id: 0,
title: 'Home',
url: "/",
el: 'a',
style: 'nav-link',
isNavLink: true,
},
{
id: 1,
title: 'Work',
url: "/Work",
el: 'a',
style: 'nav-link',
isNavLink: true
},
{
id: 2,
title: 'Contact',
url: '/Contact',
el: 'a',
style: 'nav-link',
isNavLink: true
},
{
id: 3,
title: 'Library',
url: '/Library',
el: 'a',
style: 'nav-link',
isNavLink: true
}
]
return (
<div>
<Navigation navClass="nav-holder" links={navLinks}/>
</div>
)
}
}
export default Navi;
|
import React from 'react';
import { Grid,Paper, Avatar, TextField, Button, Typography } from '@material-ui/core'
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import axios from 'axios';
import {Link, Redirect} from 'react-router-dom'
// const config = {
// headers: { Authorization: `Bearer ${localStorage.getItem('jwt-token')}` }
// };
export default class Login extends React.Component {
constructor(props){
super(props);
this.state = {
username: '',
login: false
}
this.submit = this.submit.bind(this);
}
setUsername(u){
this.setState({username: u});
}
submit = e => {
e.preventDefault();
axios.post('http://127.0.0.1:8080/user/login/', {
username: this.state.username
})
.then(res => {
localStorage.setItem("jwt-token", res.data.token)
this.setState({login: true})
this.props.setUser(this.state.username)
})
.catch(err => console.log(err))
}
render(){
const paperStyle={padding :20,height:350, width:300, margin: "0 auto"}
const avatarStyle={backgroundColor:'#1bbd7e'}
const btnstyle={margin:'8px 0'}
if (this.state.login){
return <Redirect to={'/'}/>;
}
return(
<form onSubmit={this.submit}>
<Paper style={paperStyle}>
<Grid align='center'>
<Avatar style={avatarStyle}><LockOutlinedIcon/></Avatar>
<h2>Login</h2>
</Grid>
<TextField type="login" onChange={e=>this.setUsername(e.target.value)} label='Username' placeholder='Enter username' fullWidth required/>
<Button type="submit" color='primary' variant="contained" style={btnstyle} fullWidth>Sign In</Button>
<Typography > You don't have an account ?<br/>
<Link to={'/register'}>Register new account</Link>
</Typography>
</Paper>
</form>
)
}
}
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import queryString from 'query-string';
import PropTypes from 'prop-types';
import { setArticle, setCategory } from '../actions/blog';
import Loader from '../components/Loader';
import BlogService from '../services/BlogService';
import { setResults } from '../actions/search';
import { setSearchBarAutofocus } from '../actions/elements';
import ArticleList from '../components/ArticleList';
class SearchContainer extends Component {
async componentDidMount() {
const {
unsetAll, setResults, search, dispatchSearchBarAutoFocus,
} = this.props;
unsetAll();
if (!search) {
return dispatchSearchBarAutoFocus();
}
const results = await BlogService.search(search);
const getResults = results.items.map(async (result) => {
const [category, article] = result.path.split('/');
const info = await BlogService.getArticle({ category, article });
return {
...result,
...info,
};
});
return Promise.all(getResults).then((results) => {
setResults(results);
});
}
componentDidUpdate(newProps) {
const { location } = this.props;
const prevSearch = location.search;
const newSearch = newProps.location.search;
if (prevSearch !== newSearch) {
this.componentDidMount();
}
}
render() {
const { results, search } = this.props;
if (!search) return false;
if (!results) return <Loader />;
const message = `I found ${results.length} result${results.length > 1 ? 's' : ''} for "${search}"`;
return (
<div className="search container">
<h1 className="title">
{message}
</h1>
<ArticleList articles={results} />
</div>
);
}
}
const mapStateToProps = (state, { location }) => ({
results: state.search.results,
get search() {
const params = queryString.parse(location.search);
return params.q;
},
});
const mapDispatchToProps = dispatch => ({
unsetAll() {
dispatch(setCategory(null));
dispatch(setArticle(null));
dispatch(setResults(null));
},
setResults(results) {
dispatch(setResults(results));
},
dispatchSearchBarAutoFocus() {
dispatch(setSearchBarAutofocus(true));
},
});
SearchContainer.propTypes = {
unsetAll: PropTypes.func,
setResults: PropTypes.func,
dispatchSearchBarAutoFocus: PropTypes.func,
search: PropTypes.string,
location: PropTypes.shape({ search: PropTypes.string }),
results: PropTypes.arrayOf(PropTypes.object),
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(SearchContainer));
|
'use strict';
// Declare app level module which depends on filters, and services
angular.module('lochApp', [
'ngRoute',
'lochApp.filters',
'lochApp.services',
'lochApp.directives',
'lochApp.controllers'
])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/',
{templateUrl: 'partials/timezone-list.html',
controller: 'AllTimeZoneCtrl'});
$routeProvider.when('/:timezoneId',
{templateUrl: 'partials/timezone-detail.html',
controller: 'TimeZoneDetailCtrl'});
$routeProvider.otherwise({redirectTo: '/'});
}]);
|
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
import homeComponent from '../pages/home/'
import memberComponent from '../pages/member/'
import shopcarComponent from '../pages/shopcar/'
import searchComponent from '../pages/search/'
import newListComponent from '../pages/newList/'
import newInfoComponent from '../pages/newInfo/'
import photoShareComponent from '../pages/photoshare/'
import photoInfoComponent from '../pages/photoInfo/'
import goodsListComponent from '../pages/goodsList/'
import goodsInfoComponent from '../pages/goodsInfo/'
import goodsDescComponent from '../pages/goodsDesc/'
import goodsCommentComponent from '../pages/goodsComment/'
export default new Router({
routes: [
{
path:'/',redirect:'/home'
},
{path:'/home',component: homeComponent},
{path:'/member',component: memberComponent},
{path:'/shopcar',component: shopcarComponent},
{path:'/search',component: searchComponent},
{path:'/home/newList',component: newListComponent},
{path:'/home/newList/newInfo/:id',component: newInfoComponent},
{path:'/home/photoshare',component: photoShareComponent},
{path:'/home/photoshare/photoinfo/:id',component: photoInfoComponent},
{path:'/home/goodsList',component: goodsListComponent},
{path:'/home/goodsList/goodsInfo/:id',component: goodsInfoComponent,name:'goodsinfo'},
{path:'/home/goodsList/goodsInfo/goodsdesc/:id',component: goodsDescComponent,name:'goodsdesc'},
{path:'/home/goodsList/goodsInfo/goodscomment/:id',component: goodsCommentComponent,name:'goodscomment'}
],
linkActiveClass: 'mui-active'
})
|
import {configureStore} from '@reduxjs/toolkit';
import authSlice from './features/auth-slice';
import cartSlice from './features/cart-slice';
import productSlice from './features/product-slice';
import wishlistSlice from './features/wishlist-slice';
export const store = configureStore({
reducer:{
cart:cartSlice,
wishlist:wishlistSlice,
products:productSlice,
auth:authSlice,
}
})
|
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the organization nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
define(['jquery', '../helpers', 'readium_cfi_js', 'URIjs'], function($, Helpers, EPUBcfi, URI) {
/**
*
* @param reader
* @constructor
*/
var InternalLinksSupport = function(reader) {
var self = this;
function splitCfi(fullCfi) {
var startIx = fullCfi.indexOf("(");
var bungIx = fullCfi.indexOf("!");
var endIx = fullCfi.indexOf(")");
if(bungIx == -1) {
return undefined;
}
if(endIx == -1) {
endIx = fullCfi.length;
}
return {
spineItemCfi: fullCfi.substring(startIx + 1, bungIx),
elementCfi: fullCfi.substring(bungIx + 1, endIx)
}
}
function getAbsoluteUriRelativeToSpineItem(hrefUri, spineItem) {
var fullPath = reader.package().resolveRelativeUrl(spineItem.href);
var absUrl = hrefUri.absoluteTo(fullPath);
return absUrl;
}
function processDeepLink(hrefUri, spineItem) {
var absoluteOpfUri = getAbsoluteUriRelativeToSpineItem(hrefUri, spineItem);
if(!absoluteOpfUri) {
console.error("Unable to resolve " + hrefUri.href())
return;
}
var fullCfi = hrefUri.fragment();
var absPath = absoluteOpfUri.toString();
absPath = Helpers.RemoveFromString(absPath, "#" + fullCfi);
readOpfFile(absPath, function(opfText) {
if(!opfText) {
return;
}
var parser = new window.DOMParser;
var packageDom = parser.parseFromString(opfText, 'text/xml');
var cfi = splitCfi(fullCfi);
if(!cfi) {
console.warn("Unable to split cfi:" + fullCfi);
return;
}
var contentDocRef = EPUBcfi.Interpreter.getContentDocHref("epubcfi(" + cfi.spineItemCfi + ")", packageDom);
if(contentDocRef) {
var newSpineItem = reader.spine().getItemByHref(contentDocRef);
if(newSpineItem) {
reader.openSpineItemElementCfi(newSpineItem.idref, cfi.elementCfi, self);
}
else {
console.warn("Unable to find spineItem with href=" + contentDocRef);
}
}
else {
console.warn("Unable to find document ref from " + fullCfi +" cfi");
}
});
}
function readOpfFile(path, callback) {
//TODO: this should use readium-js resource fetcher (file / URI access abstraction layer), as right now this fails with packed EPUBs
$.ajax({
// encoding: "UTF-8",
// mimeType: "text/plain; charset=UTF-8",
// beforeSend: function( xhr ) {
// xhr.overrideMimeType("text/plain; charset=UTF-8");
// },
isLocal: path.indexOf("http") === 0 ? false : true,
url: path,
dataType: 'text',
async: true,
success: function (result) {
callback(result);
},
error: function (xhr, status, errorThrown) {
console.error('Error when AJAX fetching ' + path);
console.error(status);
console.error(errorThrown);
callback();
}
});
}
//checks if href includes path to opf file and full cfi
function isDeepLikHref(uri) {
var fileName = uri.filename();
return fileName && Helpers.EndsWith(fileName, ".opf");
}
function processLinkWithHash(hrefUri, spineItem) {
var fileName = hrefUri.filename();
var idref;
//reference to another file
if(fileName) {
var normalizedUri = new URI(hrefUri, spineItem.href);
var pathname = decodeURIComponent(normalizedUri.pathname());
var newSpineItem = reader.spine().getItemByHref(pathname);
if(!newSpineItem) {
console.error("spine item with href=" + pathname + " not found");
return;
}
idref = newSpineItem.idref;
}
else { //hush in the same file
idref = spineItem.idref;
}
var hashFrag = hrefUri.fragment();
reader.openSpineItemElementId(idref, hashFrag, self);
}
this.processLinkElements = function($iframe, spineItem) {
var epubContentDocument = $iframe[0].contentDocument;
$('a', epubContentDocument).click(function (clickEvent) {
// Check for both href and xlink:href attribute and get value
var href;
if (clickEvent.currentTarget.attributes["xlink:href"]) {
href = clickEvent.currentTarget.attributes["xlink:href"].value;
}
else {
href = clickEvent.currentTarget.attributes["href"].value;
}
var overrideClickEvent = false;
var hrefUri = new URI(href);
var hrefIsRelative = hrefUri.is('relative');
if (hrefIsRelative) {
if(isDeepLikHref(hrefUri)) {
processDeepLink(hrefUri, spineItem);
overrideClickEvent = true;
}
else {
processLinkWithHash(hrefUri, spineItem);
overrideClickEvent = true;
}
} else {
// It's an absolute URL to a remote site - open it in a separate window outside the reader
window.open(href, '_blank');
overrideClickEvent = true;
}
if (overrideClickEvent) {
clickEvent.preventDefault();
clickEvent.stopPropagation();
}
});
}
};
return InternalLinksSupport;
});
|
module.exports = {
css: {
files: '_src/sass/**/*.scss',
tasks: ['sass', 'cssmin'],
},
images: {
files: '_src/img/**/*.{png,jpg,gif,svg}',
tasks: ['newer:imagemin:dynamic'],
},
uglify: {
files: '_src/js/**/*.js',
tasks: ['concat']
}
}
|
'use strict';
(function(){
var modals = document.getElementsByClassName('modal');
var overlay = document.querySelector('#modal-overlay')
var links = document.getElementsByClassName('show-modal');
var closeModalButtons = document.getElementsByClassName('close-modal');
var showModal = function(event){
event.preventDefault();
var linkId = this.getAttribute('href');
overlay.classList.add('show');
for (var i =0; i<modals.length; i++) {
modals[i].getElementsByTagName('header')[0].innerHTML = `Modal header ${linkId.slice(1)}`;
if(linkId == '#'+modals[i].id) {
modals[i].classList.add('show');
} else {
modals[i].classList.remove('show');
}
}
};
for(var i = 0; i < links.length; i++){
links[i].addEventListener('click', showModal);
}
var hideModal = function(event){
event.preventDefault();
overlay.classList.remove('show');
};
for(var i = 0; i < closeModalButtons.length; i++){
closeModalButtons[i].addEventListener('click', hideModal);
}
overlay.addEventListener('click', hideModal);
for(var i = 0; i < modals.length; i++){
modals[i].addEventListener('click', function(event){
event.stopPropagation();
});
}
})();
|
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose');
const session = require('express-session');
const app = express();
// Middleware EJs view
app.use(expressLayouts);
app.set('view engine', 'ejs');
// Bodyparser
app.use(express.urlencoded({ extended: false }));
//Static folder
app.use(express.static('public'));
//importing routes
app.use('/', require('./routes/meroutes'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server started on ${PORT}`));
|
function solve(args){
var numJumpsAllowed = +args[0],
trackLen = +args[1],
fleas = [],
fleasLen, currentPos = [],
winner, winIn
flagLen = 0;
args.splice(0, 2);
fleas = args;
fleasLen = fleas.length;
function printHasTags(p){
for(var i = 0; i < 2; i+=1){
var hashTags = '';
for(var j = 0; j < p; j+=1){
hashTags+= '#';
}
console.log(hashTags);
}
}
for(var i = 0; i < fleasLen; i+=1){
fleas[i] = fleas[i].split(',');
fleas[i][1] = +fleas[i][1];
currentPos[i] = 0;
}
//FIND IF THE JUMP IS EQUAL OR GREATER THAN THE TRACK LENGTH
for(var b = 0; b < fleasLen; b+= 1){
if(fleas[b][1]<trackLen){
flagLen = 1;
break;
}
}
//IF YES - THE FIRST FLEA IS THE WINNER
if(flagLen === 0){
for(var c = 0; c < fleasLen; c+=1){
currentPos[c] = fleas[c][1]*numJumpsAllowed;
if (currentPos[c]>=trackLen) {
currentPos[c] = currentPos[c]-1;
}
}
winIn = 0;
}
else {
//IF NOT -
//FIND THE LONGEST JUMP
var maxJump = fleas[0][1];
var maxJumpIndex = 0;
for(var d = 0; d < fleasLen; d+=1){
if(fleas[d][1] > maxJump){
maxJump = fleas[d][1];
maxJumpIndex = d;
}
}
//FIND IF LONGEST JUMP*NUMBER OF JUMPS IS MORE THAN THE TRACK LENGTH
if((maxJump*numJumpsAllowed)>trackLen){
//IF YES -
//CHECK IF THERE ARE JUMPS EQUAL IN LENGTH WITH THE MAX LENGTH
var equal = [];
for(var e = 0; e < fleasLen; e+=1){
if(fleas[e][1] === maxJump){
equal.push(e);
}
}
var jumps = Math.round(trackLen/maxJump);
if (equal.length > 0) {
winIn = equal[0];
for(var f = 0; f < fleasLen; f+=1){
if (f!==winIn) {
currentPos[f] = fleas[f][1]*(jumps-1);
}
}
currentPos[winIn] = trackLen-1;
}
else {
//IF NOT FIND THE POSITION OF EACH FLEA WHILE THE FASTEST FLEA REACHES THE END OR FLIES OVER IT
winIn = maxJumpIndex;
for(var f = 0; f < fleasLen; f+=1){
if (f!==maxJumpIndex) {
currentPos[f] = fleas[f][1]*(jumps-1);
}
}
currentPos[winIn] = trackLen-1;
}
}
else{
//IF NOT var maxJump = fleas[0][1];
//CHECK IF THERE ARE JUMPS EQUAL IN LENGTH WITH THE MAX LENGTH
var equal = [];
for(var e = 0; e < fleasLen; e+=1){
if(fleas[e][1] === maxJump){
equal.push(e);
}
}
if (equal.length > 0) {
for(var f = 0; f < fleasLen; f+=1){
currentPos[f] = fleas[f][1]*numJumpsAllowed;
if(currentPos[f]>=trackLen){
currentPos[f] = trackLen-1;
}
}
winIn = equal.length-1;
}
else {
//IF NOT FIND THE POSITION OF EACH FLEA
//fleajump*numberofjumps
for(var f = 0; f < fleasLen; f+=1){
currentPos[f] = fleas[f][1]*numJumpsAllowed;
if(currentPos[f]>=trackLen){
currentPos[f] = trackLen-1;
}
}
winIn = maxJumpIndex;
}
//IF YES FIND THE POSITION OF EACH AND FLEA WITH THE LONGEST JUMP WITH THEGREATEST INDEX
//fleajump*numberofjumps
//MAX JUMP MAX JUMP INDEX=FLEA INDEX
}
}
printHasTags(trackLen);
for (var p = 0; p < fleasLen; p+= 1){
var str = '';
for(var q = 0; q < currentPos[p]; q+=1){
str += '.';
}
str+=fleas[p][0][0].toUpperCase();
for(var d = currentPos[p]+1; d < trackLen; d+= 1){
str+='.';
}
console.log(str);
}
printHasTags(trackLen);
console.log('Winner: ' + fleas[winIn][0])
}
//test = ['3', '29', 'pesho, 9', 'gosho, 10', 'tosho, 7', 'gundi, 1']
//test = ['1', '1', 'pesho, 1', 'gosho, 1']
//test = ['3', '5', 'cura, 1', 'Pepi, 1', 'UlTraFlea, 1', 'BOIKO, 1'];
test = ['10', '19', 'angel, 9', 'Boris, 10', 'Georgi, 3', 'Dimitar, 7']
solve(test);
|
import React from 'react';
import '../assets/css/style.css';
import HeaderDR from './HeaderDR';
import LeftContentDR from './LeftContentDR';
import RightContentDR from './RightContentDR';
export default function DressingRoom(props) {
return (
<div className="container-fluid">
<div className="row">
<HeaderDR />
</div>
<div className="row">
<div className="col-md-8">
<LeftContentDR />
</div>
<div className="col-md-4">
<RightContentDR />
</div>
</div>
</div>
)
}
|
function fnButtons() {
$("#consultar").bind("click", function () {
var datos = new Array();
console.log(post(317));
console.log(post(318));
});
}
function convertirini() {
var DateSplit = this['tcFechaInicio'].value.split("-");
var Year = DateSplit[0];
var Month = DateSplit[1];
var Day = DateSplit[2];
var NewDate = Day + '/' + Month + '/' + Year;
return NewDate;
}
function convertirfin() {
var DateSplit = this['tcFechaFinal'].value.split("-");
var Year = DateSplit[0];
var Month = DateSplit[1];
var Day = DateSplit[2];
var NewDate = Day + '/' + Month + '/' + Year;
return NewDate;
}
function post(type) {
var arrayresult = new Array();
var url = "http://indicadoreseconomicos.bccr.fi.cr/indicadoreseconomicos/WebServices/wsIndicadoresEconomicos.asmx";
var soap = '<?xml version="1.0" encoding="utf-8"?>' +
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soap:Body>' +
'<ObtenerIndicadoresEconomicos xmlns="http://ws.sdde.bccr.fi.cr">' +
'<tcIndicador>' + type + '</tcIndicador>' +
'<tcFechaInicio>' + convertirini() + '</tcFechaInicio>' +
'<tcFechaFinal>' + convertirfin() + '</tcFechaFinal>' +
'<tcNombre>' + "Ronald" + '</tcNombre>' +
'<tnSubNiveles>N</tnSubNiveles>' +
'</ObtenerIndicadoresEconomicos>' +
'</soap:Body>' +
'</soap:Envelope>';
$.ajax({
type: "POST",
url: url,
contentType: "text/xml",
dataType: "xml",
data: soap,
type: "POST",
success: function (data, status, req, xml, xmlHttpRequest, responseXML) {
var myObj = new Array();
$(req.responseXML)
.find('Datos_de_INGC011_CAT_INDICADORECONOMIC').find('INGC011_CAT_INDICADORECONOMIC')
.each(function () {
myObj.push($(this));
});
for (var i = 0; i < myObj.length; i++) {
var arraynode = new Array();
var fecha = myObj[i].find('DES_FECHA').text();
var valor = myObj[i].find('NUM_VALOR').text();
arraynode.push(fecha);
arraynode.push(valor);
arrayresult.push(arraynode);
console.log(arrayresult);
}
},
error: function (jqXHR, textStatus) {
console.log(textStatus);
}
})
return arrayresult;
}
|
const TypeAdvisory = require('../models').TypeAdvisory;
const create = async function (req, res) {
const body = req.body;
if (!body.name || !body.price || (!body.limitNumberRecords && body.type === 1) || !body.description) {
return ReE(res, 'ERROR0011', 400);
}
if (body.type === 2) {
let duplicateTypeAdvisory = await TypeAdvisory.findOne({ type: body.type });
if (duplicateTypeAdvisory) return ReE(res, 'ERROR0014', 409);
}
let typeAdvisories = new TypeAdvisory({
name: body.name,
price: body.price,
type: body.type,
limitNumberRecords: body.limitNumberRecords,
description: body.description,
});
await typeAdvisories.save();
return ReS(res, { message: 'Tạo kiểu câu hỏi thành công', typeAdvisories: typeAdvisories }, 200);
};
module.exports.create = create;
const getAllTypeAdvisories = async function (req, res) {
TypeAdvisory.find({ deletionFlag: { $ne: true } }, function (err, typeAdvisories) {
if (err) return ReS(res, 'ERROR0012', 404);
return ReS(res, { message: 'Tải kiểu câu hỏi thành công', typeAdvisories: typeAdvisories }, 200);
});
};
module.exports.getAllTypeAdvisories = getAllTypeAdvisories;
const getTypeAdvisoriesById = async function (req, res) {
if (!req.params.id) return ReS(res, 'ERROR0010', 400);
TypeAdvisory.findById(req.params.id, function (err, objectAdvisory) {
if (err) return ReS(res, 'ERROR0012', 404);
return ReS(res, { message: 'Tải kiểu câu hỏi thành công', objectAdvisory: objectAdvisory }, 200);
});
};
module.exports.getTypeAdvisoriesById = getTypeAdvisoriesById;
const update = async function (req, res) {
let data = req.body;
if (data.type === 2) {
let duplicateTypeAdvisory = await TypeAdvisory.findOne({
type: 2,
_id: { $ne: data.id },
deletionFlag: { $ne: true },
});
if (duplicateTypeAdvisory) return ReE(res, 'ERROR0014', 409);
}
TypeAdvisory.findByIdAndUpdate(data.id,
{
$set: {
name: data.name,
price: data.price,
limitNumberRecords: data.limitNumberRecords,
description: data.description,
},
},
{ new: true },
function (err, updateTypeAdvisory) {
if (err) TE(err.message);
return ReS(res, {
message: 'Update kiểu câu hỏi thành công',
updateTypeAdvisory: updateTypeAdvisory,
}, 200);
});
};
module.exports.update = update;
const remove = async function (req, res) {
const body = req.body;
if (!body) return ReS(res, 'ERROR0010', 400);
TypeAdvisory.findByIdAndRemove(body.id, function (err, typeAdvisories) {
if (err) TE(err.message);
res.send('Delete success');
});
};
module.exports.remove = remove;
const deleteById = async function (req, res) {
const updateTime = req.query.updateTime;
const typeId = req.params.typeId;
if (!typeId || !updateTime) {
ReE(res, {
status: false,
message: 'Vui lòng nhập userId và updateTime',
}, 400);
}
TypeAdvisory.find({
_id: typeId,
}, (err, results) => {
if (err) {
return ReE(res, err, 500);
}
if (results && results.length === 0) {
return ReE(res, 'Loại tư vấn không tồn tại', 404);
}
let user = results[0];
if (Number(user.updatedAt) !== Number(updateTime)) {
return ReE(res, 'Loại tư vấn này đã được chỉnh sửa, vui lòng refresh và thử lại', 400);
}
user.deletionFlag = true;
user.save((error, status) => {
if (error) {
return ReE(res, 'Xóa loại tư vấn không thành công, vui lòng thử lại', 400);
}
ReS(res, {
status: true,
message: 'Đã xóa thành công ' + user.name,
}, 200);
});
});
};
module.exports.deleteById = deleteById;
|
import React, { useState, useEffect } from 'react';
import { MoedaReal, MonetaryFormat } from '../../utils';
import { hoje, amanha } from '../../constants';
import './styles.css';
const FechamentoCaixa = () => {
const [vendas, setVendas] = useState([]);
const [input, setInput] = useState(0);
const [isFechado, setIsFechado] = useState(false);
const atualizaInput = (e) => {
setInput(e.currentTarget.value);
};
const onSubmit = (e) => {
e.preventDefault();
fetch(`http://pdv/fechamentoDeCaixa/`, {
method: 'POST',
body: JSON.stringify({
cliente: 0,
pago: MonetaryFormat(this.state.input),
formaPg: 'Dinheiro',
operacao: 'Fechamento de caixa'
})
})
.then((response) => response.json())
.then((responseJson) => {
if (responseJson.resp === 'ok') {
window.location.href = '/';
}
});
};
useEffect(() => {
fetch(`${process.env.REACT_APP_URLBASEAPI}exibir/vendas/`, {
method: 'POST',
body: JSON.stringify({
datai: hoje,
dataf: amanha
})
})
.then((response) => response.json())
.then((responseJson) => {
setVendas(responseJson.filter((venda) => venda.dataVenda === hoje));
const fechado = responseJson.filter(
(venda) =>
venda.operacao === 'Fechamento de caixa' &&
venda.dataVenda === amanha
);
fechado.length && setIsFechado(true);
});
}, []);
const total = vendas.length
? vendas.length > 1
? vendas
.map(
(evento) =>
evento.operacao !== 'Fechamento de caixa' &&
parseFloat(evento.pago)
)
.reduce((a, b) => a + b)
: vendas[0].pago
: '0,00';
return (
<div className='fechamento container'>
<div className='text-center'>
<h2>ATENÇÃO!</h2>O valor não pode ser corrigido e <br />
nenhuma venda será realizada após fechamento do caixa.
</div>
<div className='fechamento__saldo'>
Saldo do caixa de hoje: <MoedaReal valor={total} />
</div>
{isFechado ? (
<div className='fechamento__aviso'>Fechamento já realizado hoje</div>
) : (
<form
onSubmit={onSubmit}
name='formFechamento'
className='fechamento__form'>
<label className='fechamento__label'>Valor do troco de amanhã:</label>
<input
className='form-control fechamento__input'
type='text'
placeholder='Valor'
onChange={atualizaInput}
value={input}
/>
<button className='btn btn-success form-control'>Fechar caixa</button>
</form>
)}
</div>
);
};
export default FechamentoCaixa;
|
function register(env) {
env.addGlobal("cta", (guid, align_opt) => handler(env, guid, align_opt));
}
function handler(env, guid, align_opt) {
return env.getCTAManager().render(guid, align_opt);
}
export {
handler,
register as default
};
|
function Combatant(health, attack, name) {
this.health = health;
this.attack = attack;
this.name = name;
this.attackEnemy = function(enemy) {
console.log(
"Enemy with name: " +
enemy.getName() +
" is attacked by " +
this.name +
" for " +
this.attack
);
enemy.setHealth(enemy.getHealth() - this.attack);
console.log("Enemy has : " + enemy.getHealth() + " left");
};
this.getName = function() {
return this.name;
};
this.getHealth = function() {
return this.health;
};
this.setHealth = function(health) {
this.health = health;
};
this.getAttack = function() {
return this.attack;
};
this.isAlive = function() {
return this.health > 0;
};
}
|
module.exports = {
getProduct: async (req, res) => {
const db = req.app.get("db");
allProduct = await db.product.get_product();
return res.status(200).send(allProduct);
},
addOrder: async (req, res) => {
const db = req.app.get("db");
const { total, user_id, quantity } = req.body;
const { product_id } = req.params;
let order;
try {
order = await db.order.add_order(total, user_id, product_id, quantity);
} catch (err) {
console.log(err);
}
return res.status(200).send(order);
},
getUserItems: async (req, res) => {
const { user_id } = req.params;
const db = req.app.get("db");
let items = await db.order.get_items_by_user_id(user_id);
return res.status(200).send(items);
},
deleteItem: (req, res) => {
const { product_id } = req.params;
const db = req.app.get("db");
const updatedCart = db.order.delete_items(product_id);
return res.status(200).send(updatedCart);
},
getTotal: async (req, res) => {
const { user_id } = req.params;
const db = req.app.get("db");
const total = await db.order.get_grand_total(user_id);
return res.status(200).send(total);
},
deleteOrder: (req, res) => {
const { user_id } = req.params;
const db = req.app.get("db");
const finalOrder = db.order.delete_completed_order(user_id);
return res.status(200).send(finalOrder);
},
};
|
const REPOSITORY_NAME = window.location.origin.includes('localhost')
? ''
: 'Readable';
export function getPhoto(id, size) {
return `https://api.adorable.io/avatars/${size ? size : '47'}/${id}.png`;
}
export function capitalize(text) {
return text.charAt(0).toUpperCase() + text.slice(1);
}
// Create GUID
// https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
export function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return (
s4() +
s4() +
'-' +
s4() +
'-' +
s4() +
'-' +
s4() +
'-' +
s4() +
s4() +
s4()
);
}
export function sortBy(array, type = 'date') {
switch (type) {
case 'date':
return array.sort((x, y) => y.timestamp - x.timestamp);
case 'vote':
return array.sort((x, y) => y.voteScore - x.voteScore);
case 'name':
return array.sort((x, y) => {
const text1 = x.author.toUpperCase();
const text2 = y.author.toUpperCase();
return text1 < text2 ? -1 : text1 > text2 ? 1 : 0;
});
case 'title':
return array.sort((x, y) => {
const text1 = x.title.toUpperCase();
const text2 = y.title.toUpperCase();
return text1 < text2 ? -1 : text1 > text2 ? 1 : 0;
});
default:
return array;
}
}
export function getParams(originalPath) {
let path;
if (originalPath.includes('/')) {
path = REPOSITORY_NAME
? originalPath.replace(`/${REPOSITORY_NAME}`, '')
: originalPath;
path = path.replace('/', '');
} else path = originalPath;
const params = path.split('/');
return {
category: params[0] ? params[0] : 'all'
};
}
|
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
*
* (c) Copyright 2009-2014 SAP SE. All rights reserved
*/
jQuery.sap.declare("sap.viz.ui5.controls.common.BaseControlRenderer");sap.viz.ui5.controls.common.BaseControlRenderer={};
sap.viz.ui5.controls.common.BaseControlRenderer.render=function(r,c){};
|
import fire from '../src/Config/fire'
function iamclose(){
fire.auth().signOut().then(function() {
// Sign-out successful.
alert("LogOut SuccessFull")
}).catch(function(error) {
// An error happened.
});
alert("aaaaaa")
}
|
import { ADD_TO_CART, CLEAR_CART, REMOVE_FROM_CART } from "../actions/types";
export default function cartReducer(state,action){
if (action.type === ADD_TO_CART) {
if (action.quantity > 0) {
return {
cart :[...state.cart,{product: action.productInfo ,quantity: action.quantity}]
}
} else {
return state
}
} else if (action.type === REMOVE_FROM_CART) {
const itemIndex = action.index;
const newState = {...state};
newState.cart.splice(itemIndex,1)
return newState;
} else if (action.type === CLEAR_CART) {
const newState = {...state};
newState.cart = []
return newState;
} else {
return state
}
}
|
/*
* @lc app=leetcode.cn id=535 lang=javascript
*
* [535] TinyURL 的加密与解密
*/
// @lc code=start
/**
* Encodes a URL to a shortened URL.
*
* @param {string} longUrl
* @return {string}
*/
var encode = function (longUrl) {
this.map = new Map();
this.id = 0;
this.id++;
this.map.set(this.id, longUrl);
return 'http://tinyurl.com/' + this.id;
};
/**
* Decodes a shortened URL to its original URL.
*
* @param {string} shortUrl
* @return {string}
*/
var decode = function (shortUrl) {
const arr = shortUrl.split('/');
const id = Number(arr[arr.length - 1]);
return this.map.get(id);
};
// @lc code=end
|
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require('cors');
const app = express();
const postRoutes = require('./routes/posts');
app.use(bodyParser.json());
app.use(cors());
app.use(postRoutes);
const PORT = 8000;
const DB_URL ='mongodb+srv://Gavindu:Gavindu@1998@mernapp.3v2bt.mongodb.net/mernCrudretryWrites=true&w=majority'
mongoose.connect(DB_URL)
.then(() =>{
console.log('DB connected');
})
.catch((err) => console.log('DB connection error' ,err));
app.listen(PORT, () =>{
console.log('App is running on ${PORT}');
});
|
import React from 'react';
import {
StyleSheet,
ScrollView
} from 'react-native';
import MenuItem from './MenuItem';
import PDP from './PDP';
const styles = StyleSheet.create({
container: {
backgroundColor: '#F5FCFF'
}
});
type MainMenuProps = {
items: Array<Object>,
navigator: Object
};
export default function MainMenu({ items, navigator }: MainMenuProps) {
const navigateToItem = item => {
navigator.push({
title: item.title || 'Selected',
component: PDP,
passProps: {
item
}
});
};
return (
<ScrollView contentContainerStyle={styles.container}>
{items.map(item => {
const { title, imageSource, listImageSource } = item;
return (
<MenuItem
imageSource={listImageSource || imageSource}
key={title}
title={title}
onPress={() => navigateToItem(item)}
/>
);
})}
</ScrollView>
);
}
|
import MusicClient from '../../lib/music/Client';
const { ipcRenderer } = window.require('electron');
const client = new MusicClient(ipcRenderer);
function load(music) {
return {
type: "LOAD_MUSIC",
data: music,
};
};
function startLoading() {
return {
type: "START_LOAD_MUSIC",
};
};
function completeLoading() {
return {
type: "END_LOAD_MUSIC",
};
};
function startScan(path) {
return {
type: "START_SCAN",
data: path
};
};
function completeScan(path) {
return {
type: "END_SCAN",
data: path
};
};
export function SelectSong(song) {
return {
type: "SELECT_SONG",
data: song
}
}
export function RemoveSelection() {
return {
type: "REMOVE_SELECTION"
}
}
export function Load() {
return dispatch => {
dispatch(startLoading());
client.All().promise.then((music) => {
dispatch(load(music));
dispatch(completeLoading());
});
};
};
export function Scan(path) {
return dispatch => {
dispatch(startScan(path))
client.Import(path).promise.then((music) => {
dispatch(load(music));
dispatch(completeScan(path));
});
};
}
export function UpdateSong(song) {
}
|
const { Entity, clauses } = require("../src/entity");
const { expect } = require("chai");
const moment = require("moment");
const uuidV4 = require("uuid/v4");
/*
todo: add check for untilized SKs to then be converted to filters
*/
let schema = {
service: "MallStoreDirectory",
entity: "MallStores",
table: "StoreDirectory",
version: "1",
attributes: {
id: {
type: "string",
default: () => uuidV4(),
field: "storeLocationId",
},
mall: {
type: "string",
required: true,
field: "mall",
},
store: {
type: "string",
required: true,
field: "storeId",
},
building: {
type: "string",
required: true,
field: "buildingId",
},
unit: {
type: "string",
required: true,
field: "unitId",
},
category: {
type: [
"food/coffee",
"food/meal",
"clothing",
"electronics",
"department",
"misc",
],
required: true,
},
leaseEnd: {
type: "string",
required: true,
validate: (date) =>
moment(date, "YYYY-MM-DD").isValid() ? "" : "Invalid date format",
},
rent: {
type: "string",
required: false,
default: "0.00",
},
adjustments: {
type: "string",
required: false,
},
},
filters: {
rentsLeaseEndFilter: function (
attr,
{ lowRent, beginning, end, location } = {},
) {
return `(${attr.rent.gte(lowRent)} AND ${attr.mall.eq(
location,
)}) OR ${attr.leaseEnd.between(beginning, end)}`;
},
},
indexes: {
store: {
pk: {
field: "pk",
facets: ["id"],
},
},
units: {
index: "gsi1pk-gsi1sk-index",
pk: {
field: "gsi1pk",
facets: ["mall"],
},
sk: {
field: "gsi1sk",
facets: ["building", "unit", "store"],
},
},
leases: {
index: "gsi2pk-gsi2sk-index",
pk: {
field: "gsi2pk",
facets: ["mall"],
},
sk: {
field: "gsi2sk",
facets: ["leaseEnd", "store", "building", "unit"],
},
},
categories: {
index: "gsi3pk-gsi3sk-index",
pk: {
field: "gsi3pk",
facets: ["mall"],
},
sk: {
field: "gsi3sk",
facets: ["category", "building", "unit", "store"],
},
},
shops: {
index: "gsi4pk-gsi4sk-index",
pk: {
field: "gsi4pk",
facets: ["store"],
},
sk: {
field: "gsi4sk",
facets: ["mall", "building", "unit"],
},
},
},
};
describe("Entity", () => {
describe("'client' validation", () => {
let mall = "EastPointe";
let store = "LatteLarrys";
let building = "BuildingA";
let category = "food/coffee";
let unit = "B54";
let leaseEnd = "2020-01-20";
let rent = "0.00";
let MallStores = new Entity(schema);
expect(() =>
MallStores.put({
store,
mall,
building,
rent,
category,
leaseEnd,
unit,
}).go(),
).to.throw("No client defined on model");
});
describe("Schema validation", () => {
let MallStores = new Entity(schema);
it("Should enforce enum validation on enum type attribute", () => {
let [
isValid,
reason,
] = MallStores.model.schema.attributes.category.isValid("BAD_CATEGORY");
expect(!isValid);
expect(reason).to.eq(
"Value not found in set of acceptable values: food/coffee, food/meal, clothing, electronics, department, misc",
);
});
it("should recognize when an attribute's field property is duplicated", () => {
let schema = {
service: "MallStoreDirectory",
entity: "MallStores",
table: "StoreDirectory",
version: "1",
attributes: {
id: {
type: "string",
field: "id",
},
duplicateFieldName: {
type: "string",
field: "id",
},
},
indexes: {
main: {
pk: {
field: "pk",
facets: ["id"],
},
},
},
};
expect(() => new Entity(schema)).to.throw(
`Schema Validation Error: Attribute "duplicateFieldName" property "field". Received: "id", Expected: "Unique field property, already used by attribute id"`,
);
});
it("Should validate regex", () => {
let Test = new Entity({
service: "MallStoreDirectory",
entity: "MallStores",
table: "StoreDirectory",
version: "1",
attributes: {
regexp: {
type: "string",
validate: /^\d{4}-\d{2}-\d{2}$/gi,
},
},
indexes: {
test: {
pk: {
field: "test",
facets: ["regexp"],
},
},
},
});
expect(() => Test.put({ regexp: "1533-15-44" }).params()).to.not.throw();
expect(() => Test.put({ regexp: "1533-1a-44" }).params()).to.throw(
`Invalid value for attribute "regexp": Failed user defined regex.`,
);
});
it("Should not allow for an invalid schema type", () => {
expect(
() =>
new Entity({
service: "MallStoreDirectory",
entity: "MallStores",
table: "StoreDirectory",
version: "1",
attributes: {
regexp: {
type: "raccoon",
},
},
indexes: {
test: {
pk: {
field: "test",
facets: ["regexp"],
},
},
},
}),
).to.throw(
`Invalid "type" property for attribute: "regexp". Acceptable types include string, number, boolean, enum`,
);
});
it("Should prevent the update of the main partition key without the user needing to define the property as read-only in their schema", () => {
let id = uuidV4();
let rent = "0.00";
let category = "food/coffee";
let mall = "EastPointe";
expect(() =>
MallStores.update({ id }).set({ rent, category, id }),
).to.throw("Attribute id is Read-Only and cannot be updated");
expect(() =>
MallStores.update({ id }).set({ rent, category, mall }),
).to.not.throw();
});
it("Should identify impacted indexes from attributes", () => {
let id = uuidV4();
let rent = "0.00";
let category = "food/coffee";
let mall = "EastPointe";
let leaseEnd = "2020/04/27";
let unit = "B45";
let building = "BuildingB";
let store = "LatteLarrys";
let impact1 = MallStores._getIndexImpact({ rent, category, mall });
let impact2 = MallStores._getIndexImpact({ leaseEnd });
let impact3 = MallStores._getIndexImpact({ mall });
let impact4 = MallStores._getIndexImpact(
{ rent, mall },
{ id, building, unit },
);
let impact5 = MallStores._getIndexImpact(
{ rent, leaseEnd, category },
{ store, building, unit, store },
);
expect(impact1).to.deep.equal([
true,
{
incomplete: ["building", "unit", "store", "building", "unit"],
complete: {
facets: { mall, category },
indexes: ["gsi1pk-gsi1sk-index", "gsi2pk-gsi2sk-index"],
},
},
]);
expect(impact2).to.deep.equal([
true,
{
incomplete: ["store", "building", "unit"],
complete: { facets: { leaseEnd }, indexes: [] },
},
]);
expect(impact3).to.deep.equal([
true,
{
incomplete: ["building", "unit"],
complete: {
facets: { mall },
indexes: [
"gsi1pk-gsi1sk-index",
"gsi2pk-gsi2sk-index",
"gsi3pk-gsi3sk-index",
],
},
},
]);
expect(impact4).to.deep.equal([
false,
{
incomplete: [],
complete: {
facets: { mall: "EastPointe" },
indexes: [
"gsi1pk-gsi1sk-index",
"gsi2pk-gsi2sk-index",
"gsi3pk-gsi3sk-index",
],
},
},
]);
expect(impact5).to.deep.equal([
false,
{
incomplete: [],
complete: {
facets: { leaseEnd: "2020/04/27", category: "food/coffee" },
indexes: [],
},
},
]);
});
});
describe("navigate query chains", () => {
let MallStores = new Entity(schema);
it("Should allow for a multiple combinations given a schema", () => {
let mall = "EastPointe";
let store = "LatteLarrys";
let building = "BuildingA";
let id = uuidV4();
let category = "food/coffee";
let unit = "B54";
let leaseEnd = "2020-01-20";
let rent = "0.00";
buildingOne = "BuildingA";
buildingTwo = "BuildingF";
let get = MallStores.get({ id });
expect(get).to.have.keys("go", "params");
let del = MallStores.delete({ id });
expect(del).to.have.keys("go", "params");
let update = MallStores.update({ id }).set({ rent, category });
expect(update).to.have.keys("go", "params", "set");
let put = MallStores.put({
store,
mall,
building,
rent,
category,
leaseEnd,
unit,
});
expect(put).to.have.keys("go", "params");
let queryUnitsBetween = MallStores.query
.units({ mall })
.between({ building: buildingOne }, { building: buildingTwo });
expect(queryUnitsBetween).to.have.keys(
"filter",
"go",
"params",
"rentsLeaseEndFilter",
);
let queryUnitGt = MallStores.query.units({ mall }).gt({ building });
expect(queryUnitGt).to.have.keys(
"filter",
"go",
"params",
"rentsLeaseEndFilter",
);
let queryUnitsGte = MallStores.query.units({ mall }).gte({ building });
expect(queryUnitsGte).to.have.keys(
"filter",
"go",
"params",
"rentsLeaseEndFilter",
);
let queryUnitsLte = MallStores.query.units({ mall }).lte({ building });
expect(queryUnitsLte).to.have.keys(
"filter",
"go",
"params",
"rentsLeaseEndFilter",
);
let queryUnitsLt = MallStores.query.units({ mall }).lt({ building });
expect(queryUnitsLt).to.have.keys(
"filter",
"go",
"params",
"rentsLeaseEndFilter",
);
});
it("Should make scan parameters", () => {
let scan = MallStores.scan.filter(({store}) => store.eq("Starblix")).params();
expect(scan).to.deep.equal({
"ExpressionAttributeNames": {
"#pk": "pk",
"#store": "storeId"
},
"ExpressionAttributeValues": {
":pk": "$mallstoredirectory_1#id_",
":store1": "Starblix"
},
"FilterExpression": "(begins_with(#pk, :pk) AND #store = :store1",
"TableName": "StoreDirectory"
})
})
it("Should check if filter returns string", () => {
expect(() => MallStores.scan.filter(() => 1234)).to.throw("Invalid filter response. Expected result to be of type string");
})
it("Should create parameters for a given chain", () => {
let mall = "EastPointe";
let store = "LatteLarrys";
let building = "BuildingA";
let id = uuidV4();
let category = "food/coffee";
let unit = "B54";
let leaseEnd = "2020-01-20";
let rent = "0.00";
let buildingOne = "BuildingA";
let buildingTwo = "BuildingF";
let unitOne = "A1";
let unitTwo = "F6";
let get = MallStores.get({ id }).params();
expect(get).to.be.deep.equal({
TableName: "StoreDirectory",
Key: { pk: `$mallstoredirectory_1#id_${id}` },
});
let del = MallStores.delete({ id }).params();
expect(del).to.be.deep.equal({
TableName: "StoreDirectory",
Key: { pk: `$mallstoredirectory_1#id_${id}` },
});
let update = MallStores.update({ id })
.set({ mall, store, building, category, unit, rent, leaseEnd })
.params();
expect(update).to.deep.equal({
UpdateExpression:
"SET #mall = :mall, #storeId = :storeId, #buildingId = :buildingId, #unitId = :unitId, #category = :category, #leaseEnd = :leaseEnd, #rent = :rent",
ExpressionAttributeNames: {
"#mall": "mall",
"#storeId": "storeId",
"#buildingId": "buildingId",
"#unitId": "unitId",
"#category": "category",
"#leaseEnd": "leaseEnd",
"#rent": "rent",
},
ExpressionAttributeValues: {
":mall": mall,
":storeId": store,
":buildingId": building,
":unitId": unit,
":category": category,
":leaseEnd": leaseEnd,
":rent": rent,
},
TableName: "StoreDirectory",
Key: {
pk: `$mallstoredirectory_1#id_${id}`,
},
});
let put = MallStores.put({
store,
mall,
building,
rent,
category,
leaseEnd,
unit,
}).params();
expect(put).to.deep.equal({
Item: {
__edb_e__: "MallStores",
storeLocationId: put.Item.storeLocationId,
mall,
storeId: store,
buildingId: building,
unitId: unit,
category,
leaseEnd,
rent,
pk: `$mallstoredirectory_1#id_${put.Item.storeLocationId}`,
gsi1pk: `$MallStoreDirectory_1#mall_${mall}`.toLowerCase(),
gsi1sk: `$MallStores#building_${building}#unit_${unit}#store_${store}`.toLowerCase(),
gsi2pk: `$MallStoreDirectory_1#mall_${mall}`.toLowerCase(),
gsi2sk: `$MallStores#leaseEnd_2020-01-20#store_${store}#building_${building}#unit_${unit}`.toLowerCase(),
gsi3pk: `$MallStoreDirectory_1#mall_${mall}`.toLowerCase(),
gsi3sk: `$MallStores#category_${category}#building_${building}#unit_${unit}#store_${store}`.toLowerCase(),
gsi4pk: `$MallStoreDirectory_1#store_${store}`.toLowerCase(),
gsi4sk: `$MallStores#mall_${mall}#building_${building}#unit_${unit}`.toLowerCase(),
},
TableName: "StoreDirectory",
});
let beingsWithOne = MallStores.query.units({ mall, building }).params();
expect(beingsWithOne).to.deep.equal({
ExpressionAttributeNames: { "#pk": "gsi1pk", "#sk1": "gsi1sk" },
ExpressionAttributeValues: {
":pk": `$MallStoreDirectory_1#mall_${mall}`.toLowerCase(),
":sk1": `$MallStores#building_${building}#unit_`.toLowerCase(),
},
IndexName: "gsi1pk-gsi1sk-index",
TableName: "StoreDirectory",
KeyConditionExpression: "#pk = :pk and begins_with(#sk1, :sk1)",
});
let beingsWithTwo = MallStores.query
.units({ mall, building, store })
.params();
expect(beingsWithTwo).to.deep.equal({
ExpressionAttributeNames: { "#pk": "gsi1pk", "#sk1": "gsi1sk" },
ExpressionAttributeValues: {
":pk": `$MallStoreDirectory_1#mall_${mall}`.toLowerCase(),
":sk1": `$MallStores#building_${building}#unit_`.toLowerCase(),
},
IndexName: "gsi1pk-gsi1sk-index",
TableName: "StoreDirectory",
KeyConditionExpression: "#pk = :pk and begins_with(#sk1, :sk1)",
});
let beingsWithThree = MallStores.query
.units({ mall, building, unit })
.params();
expect(beingsWithThree).to.deep.equal({
ExpressionAttributeNames: { "#pk": "gsi1pk", "#sk1": "gsi1sk" },
ExpressionAttributeValues: {
":pk": `$MallStoreDirectory_1#mall_${mall}`.toLowerCase(),
":sk1": `$MallStores#building_${building}#unit_${unit}#store_`.toLowerCase(),
},
IndexName: "gsi1pk-gsi1sk-index",
TableName: "StoreDirectory",
KeyConditionExpression: "#pk = :pk and begins_with(#sk1, :sk1)",
});
let queryUnitsBetweenOne = MallStores.query
.units({ mall })
.between(
{ building: buildingOne, unit },
{ building: buildingTwo, unit },
)
.params();
expect(queryUnitsBetweenOne).to.deep.equal({
ExpressionAttributeNames: {
"#pk": "gsi1pk",
"#sk1": "gsi1sk",
},
ExpressionAttributeValues: {
":pk": `$MallStoreDirectory_1#mall_${mall}`.toLowerCase(),
":sk1": `$MallStores#building_${buildingOne}#unit_B54#store_`.toLowerCase(),
":sk2": `$MallStores#building_${buildingTwo}#unit_B54#store_`.toLowerCase(),
},
IndexName: "gsi1pk-gsi1sk-index",
TableName: "StoreDirectory",
KeyConditionExpression: "#pk = :pk and #sk1 BETWEEN :sk1 AND :sk2",
});
let queryUnitsBetweenTwo = MallStores.query
.units({ mall, building })
.between({ unit: unitOne }, { unit: unitTwo })
.params();
expect(queryUnitsBetweenTwo).to.deep.equal({
ExpressionAttributeNames: {
"#pk": "gsi1pk",
"#sk1": "gsi1sk",
},
ExpressionAttributeValues: {
":pk": `$MallStoreDirectory_1#mall_${mall}`.toLowerCase(),
":sk1": `$MallStores#building_${building}#unit_${unitOne}#store_`.toLowerCase(),
":sk2": `$MallStores#building_${building}#unit_${unitTwo}#store_`.toLowerCase(),
},
IndexName: "gsi1pk-gsi1sk-index",
TableName: "StoreDirectory",
KeyConditionExpression: "#pk = :pk and #sk1 BETWEEN :sk1 AND :sk2",
});
let queryUnitsBetweenThree = MallStores.query
.units({ mall, building })
.between({ store }, { store })
.params();
expect(queryUnitsBetweenThree).to.deep.equal({
ExpressionAttributeNames: {
"#pk": "gsi1pk",
"#sk1": "gsi1sk",
},
ExpressionAttributeValues: {
":pk": `$MallStoreDirectory_1#mall_${mall}`.toLowerCase(),
":sk1": `$MallStores#building_${building}#unit_`.toLowerCase(),
":sk2": `$MallStores#building_${building}#unit_`.toLowerCase(),
},
IndexName: "gsi1pk-gsi1sk-index",
TableName: "StoreDirectory",
KeyConditionExpression: "#pk = :pk and #sk1 BETWEEN :sk1 AND :sk2",
});
let queryUnitGt = MallStores.query
.units({ mall })
.gt({ building })
.params();
expect(queryUnitGt).to.deep.equal({
ExpressionAttributeNames: { "#pk": "gsi1pk", "#sk1": "gsi1sk" },
ExpressionAttributeValues: {
":pk": `$MallStoreDirectory_1#mall_${mall}`.toLowerCase(),
":sk1": `$MallStores#building_${building}#unit_`.toLowerCase(),
},
IndexName: "gsi1pk-gsi1sk-index",
TableName: "StoreDirectory",
KeyConditionExpression: "#pk = :pk and #sk1 > :sk1",
});
let queryUnitsGte = MallStores.query
.units({ mall })
.gte({ building })
.params();
expect(queryUnitsGte).to.deep.equal({
ExpressionAttributeNames: { "#pk": "gsi1pk", "#sk1": "gsi1sk" },
ExpressionAttributeValues: {
":pk": `$MallStoreDirectory_1#mall_${mall}`.toLowerCase(),
":sk1": `$MallStores#building_${building}#unit_`.toLowerCase(),
},
IndexName: "gsi1pk-gsi1sk-index",
TableName: "StoreDirectory",
KeyConditionExpression: "#pk = :pk and #sk1 >= :sk1",
});
let queryUnitsLte = MallStores.query
.units({ mall })
.lte({ building })
.params();
expect(queryUnitsLte).to.deep.equal({
ExpressionAttributeNames: { "#pk": "gsi1pk", "#sk1": "gsi1sk" },
ExpressionAttributeValues: {
":pk": `$MallStoreDirectory_1#mall_${mall}`.toLowerCase(),
":sk1": `$MallStores#building_${building}#unit_`.toLowerCase(),
},
IndexName: "gsi1pk-gsi1sk-index",
TableName: "StoreDirectory",
KeyConditionExpression: "#pk = :pk and #sk1 <= :sk1",
});
let queryUnitsLt = MallStores.query
.units({ mall })
.lt({ building })
.params();
expect(queryUnitsLt).to.deep.equal({
ExpressionAttributeNames: { "#pk": "gsi1pk", "#sk1": "gsi1sk" },
ExpressionAttributeValues: {
":pk": `$MallStoreDirectory_1#mall_${mall}`.toLowerCase(),
":sk1": `$MallStores#building_${building}#unit_`.toLowerCase(),
},
IndexName: "gsi1pk-gsi1sk-index",
TableName: "StoreDirectory",
KeyConditionExpression: "#pk = :pk and #sk1 < :sk1",
});
});
});
describe("Making keys", () => {
let MallStores = new Entity(schema);
let mall = "EastPointe";
let store = "LatteLarrys";
let building = "BuildingA";
let id = uuidV4();
let category = "coffee";
let unit = "B54";
let leaseEnd = "2020-01-20";
it("Should return the approprate pk and sk for a given index", () => {
let index = schema.indexes.categories.index;
let { pk, sk } = MallStores._makeIndexKeys(
index,
{ mall },
{ category, building, unit, store },
);
expect(pk).to.equal(
"$MallStoreDirectory_1#mall_EastPointe".toLowerCase(),
);
expect(sk)
.to.be.an("array")
.and.have.length(1)
.and.include(
"$MallStores#category_coffee#building_BuildingA#unit_B54#store_LatteLarrys".toLowerCase(),
);
});
it("Should stop making a key early when there is a gap in the supplied facets", () => {
let index = schema.indexes.categories.index;
let { pk, sk } = MallStores._makeIndexKeys(
index,
{ mall },
{ category, building, store },
);
expect(pk).to.equal(
"$MallStoreDirectory_1#mall_EastPointe".toLowerCase(),
);
expect(sk)
.to.be.an("array")
.and.have.length(1)
.and.include(
"$MallStores#category_coffee#building_BuildingA#unit_".toLowerCase(),
);
});
it("Should return the approprate pk and multiple sks when given multiple", () => {
let index = schema.indexes.shops.index;
let { pk, sk } = MallStores._makeIndexKeys(
index,
{ store },
{ mall, building: "building1" },
{ mall, building: "building5" },
);
expect(pk).to.equal(
"$MallStoreDirectory_1#store_LatteLarrys".toLowerCase(),
);
expect(sk)
.to.be.an("array")
.and.have.length(2)
.and.to.have.members([
"$MallStores#mall_EastPointe#building_building1#unit_".toLowerCase(),
"$MallStores#mall_EastPointe#building_building5#unit_".toLowerCase(),
]);
});
it("Should throw on bad index", () => {
expect(() => MallStores._makeIndexKeys("bad_index")).to.throw(
"Invalid index: bad_index",
);
});
it("Should allow facets to be a facet template (string)", () => {
const schema = {
service: "MallStoreDirectory",
entity: "MallStores",
table: "StoreDirectory",
version: "1",
attributes: {
id: {
type: "string",
field: "storeLocationId",
},
date: {
type: "string",
field: "dateTime",
},
prop1: {
type: "string",
},
prop2: {
type: "string",
},
},
indexes: {
record: {
pk: {
field: "pk",
facets: `id_:id#p1_:prop1`,
},
sk: {
field: "sk",
facets: `d_:date#p2_:prop2`,
},
},
},
};
let mallStore = new Entity(schema);
let putParams = mallStore
.put({
id: "IDENTIFIER",
date: "DATE",
prop1: "PROPERTY1",
prop2: "PROPERTY2",
})
.params();
expect(putParams).to.deep.equal({
Item: {
__edb_e__: "MallStores",
storeLocationId: "IDENTIFIER",
dateTime: "DATE",
prop1: "PROPERTY1",
prop2: "PROPERTY2",
pk: "id_identifier#p1_property1",
sk: "d_date#p2_property2",
},
TableName: "StoreDirectory",
});
});
/* This test was removed because facet templates was refactored to remove all electrodb opinions. */
//
// it("Should throw on invalid characters in facet template (string)", () => {
// const schema = {
// service: "MallStoreDirectory",
// entity: "MallStores",
// table: "StoreDirectory",
// version: "1",
// attributes: {
// id: {
// type: "string",
// field: "storeLocationId",
// },
// date: {
// type: "string",
// field: "dateTime",
// },
// prop1: {
// type: "string",
// },
// prop2: {
// type: "string",
// },
// },
// indexes: {
// record: {
// pk: {
// field: "pk",
// facets: `id_:id#p1_:prop1`,
// },
// sk: {
// field: "sk",
// facets: `d_:date|p2_:prop2`,
// },
// },
// },
// };
// expect(() => new Entity(schema)).to.throw(
// `Invalid key facet template. Allowed characters include only "A-Z", "a-z", "1-9", ":", "_", "#". Received: d_:date|p2_:prop2`,
// );
// });
it("Should default labels to facet attribute names in facet template (string)", () => {
const schema = {
service: "MallStoreDirectory",
entity: "MallStores",
table: "StoreDirectory",
version: "1",
attributes: {
id: {
type: "string",
field: "storeLocationId",
},
date: {
type: "string",
field: "dateTime",
},
prop1: {
type: "string",
},
prop2: {
type: "string",
},
},
indexes: {
record: {
pk: {
field: "pk",
facets: `id_:id#:prop1`,
},
sk: {
field: "sk",
facets: `:date#p2_:prop2`,
},
},
},
};
let mallStore = new Entity(schema);
let putParams = mallStore
.put({
id: "IDENTIFIER",
date: "DATE",
prop1: "PROPERTY1",
prop2: "PROPERTY2",
})
.params();
expect(putParams).to.deep.equal({
Item: {
__edb_e__: "MallStores",
storeLocationId: "IDENTIFIER",
dateTime: "DATE",
prop1: "PROPERTY1",
prop2: "PROPERTY2",
pk: "id_identifier#property1",
sk: "date#p2_property2",
},
TableName: "StoreDirectory",
});
});
it("Should allow for mixed custom/composed facets, and adding collection prefixes when defined", () => {
const schema = {
service: "MallStoreDirectory",
entity: "MallStores",
table: "StoreDirectory",
version: "1",
attributes: {
id: {
type: "string",
field: "storeLocationId",
},
date: {
type: "string",
field: "dateTime",
},
prop1: {
type: "string",
},
prop2: {
type: "string",
},
prop3: {
type: "string",
},
},
indexes: {
record: {
pk: {
field: "pk",
facets: `id_:id#:prop1#wubba_:prop3`,
},
sk: {
field: "sk",
facets: ["date", "prop2"],
},
collection: "testing",
},
},
};
let mallStore = new Entity(schema);
let putParams = mallStore
.put({
id: "IDENTIFIER",
date: "DATE",
prop1: "PROPERTY1",
prop2: "PROPERTY2",
prop3: "PROPERTY3",
})
.params();
expect(putParams).to.deep.equal({
Item: {
__edb_e__: "MallStores",
storeLocationId: "IDENTIFIER",
dateTime: "DATE",
prop1: "PROPERTY1",
prop2: "PROPERTY2",
prop3: "PROPERTY3",
pk: "id_identifier#property1#wubba_property3",
sk: "$testing#mallstores#date_date#prop2_property2",
},
TableName: "StoreDirectory",
});
});
it("Should throw on invalid characters in facet template (string)", () => {
const schema = {
service: "MallStoreDirectory",
entity: "MallStores",
table: "StoreDirectory",
version: "1",
attributes: {
id: {
type: "string",
field: "storeLocationId",
},
date: {
type: "string",
field: "dateTime",
},
prop1: {
type: "string",
},
prop2: {
type: "string",
},
},
indexes: {
record: {
pk: {
field: "pk",
facets: `id_:id#p1_:prop1`,
},
sk: {
field: "sk",
facets: `dbsfhdfhsdshfshf`,
},
},
},
};
expect(() => new Entity(schema)).to.throw(
`Invalid key facet template. No facets provided, expected at least one facet with the format ":attributeName". Received: dbsfhdfhsdshfshf`,
);
});
it("Should throw when defined facets are not in attributes: facet template and facet array", () => {
const schema = {
service: "MallStoreDirectory",
entity: "MallStores",
table: "StoreDirectory",
version: "1",
attributes: {
id: {
type: "string",
field: "storeLocationId",
},
date: {
type: "string",
field: "dateTime",
},
prop1: {
type: "string",
},
prop2: {
type: "string",
},
},
indexes: {
record: {
pk: {
field: "pk",
facets: ["id", "prop5"],
},
sk: {
field: "sk",
facets: `:date#p3_:prop3#p4_:prop4`,
},
},
},
};
expect(() => new Entity(schema)).to.throw(
`Invalid key facet template. The following facet attributes were described in the key facet template but were not included model's attributes: "pk: prop5", "sk: prop3", "sk: prop4"`,
);
});
});
describe("Identifying indexes by facets", () => {
let MallStores = new Entity(schema);
let mall = "123";
let store = "123";
let building = "123";
let id = "123";
let category = "123";
let unit = "123";
let leaseEnd = "123";
it("Should match on the primary index", () => {
let { index, keys } = MallStores._findBestIndexKeyMatch({ id });
expect(keys).to.be.deep.equal([{ name: "id", type: "pk" }]);
expect(index).to.be.equal("");
});
it("Should match on gsi1pk-gsi1sk-index", () => {
let { index, keys } = MallStores._findBestIndexKeyMatch({
mall,
building,
unit,
});
expect(keys).to.be.deep.equal([
{ name: "mall", type: "pk" },
{ name: "building", type: "sk" },
{ name: "unit", type: "sk" },
]);
expect(index).to.be.deep.equal(schema.indexes.units.index);
});
it("Should match on gsi2pk-gsi2sk-index", () => {
let { index, keys } = MallStores._findBestIndexKeyMatch({
mall,
leaseEnd,
});
expect(keys).to.be.deep.equal([
{ name: "mall", type: "pk" },
{ name: "leaseEnd", type: "sk" },
]);
expect(index).to.be.deep.equal(schema.indexes.leases.index);
});
it("Should match on gsi3pk-gsi3sk-index", () => {
let { index, keys } = MallStores._findBestIndexKeyMatch({
mall,
category,
});
expect(keys).to.be.deep.equal([
{ name: "mall", type: "pk" },
{ name: "category", type: "sk" },
]);
expect(index).to.be.deep.equal(schema.indexes.categories.index);
});
it("Should match on gsi4pk-gsi4sk-index", () => {
let { index, keys } = MallStores._findBestIndexKeyMatch({ mall, store });
expect(keys).to.be.deep.equal([
{ name: "store", type: "pk" },
{ name: "mall", type: "sk" },
]);
expect(index).to.be.deep.equal(schema.indexes.shops.index);
});
it("Should pick either gsi4pk-gsi4sk-index or gsi1pk-gsi1sk-index because both are viable indexes", () => {
let { index, keys } = MallStores._findBestIndexKeyMatch({
mall,
store,
building,
category,
});
expect(keys).to.be.deep.equal([
{ name: "mall", type: "pk" },
{ name: "category", type: "sk" },
{ name: "building", type: "sk" },
]);
expect(index).to.be.deep.equal(schema.indexes.categories.index);
});
it("Should match not match any index", () => {
let { index, keys } = MallStores._findBestIndexKeyMatch({ unit });
expect(keys).to.be.deep.equal([]);
expect(index).to.be.deep.equal("");
});
});
describe("_expectFacets", () => {
let MallStores = new Entity(schema);
let mall = "mall-value";
let store = "store-value";
let building = "building-value";
let id = "id-value";
let category = "category-value";
let unit = "unit-value";
let leaseEnd = "lease-value";
it("Should find all, pk, and sk matches", () => {
let index = schema.indexes.units.index;
let facets = MallStores.model.facets.byIndex[index];
let all = facets.all.map((facet) => facet.name);
let allMatches = MallStores._expectFacets(
{ store, mall, building, unit },
all,
);
let pkMatches = MallStores._expectFacets(
{ store, mall, building, unit },
facets.pk,
);
let skMatches = MallStores._expectFacets(
{ store, mall, building, unit },
facets.sk,
);
expect(allMatches).to.be.deep.equal({ mall, building, unit, store });
expect(pkMatches).to.be.deep.equal({ mall });
expect(skMatches).to.be.deep.equal({ building, unit, store });
});
it("Should find missing properties from supplied keys", () => {
let index = schema.indexes.units.index;
let facets = MallStores.model.facets.byIndex[index];
let all = facets.all.map((facet) => facet.name);
let allMatches = () => MallStores._expectFacets({ store }, all);
let pkMatches = () =>
MallStores._expectFacets(
{ store, building, unit },
facets.pk,
"partition keys",
);
let skMatches = () =>
MallStores._expectFacets(
{ store, mall, building },
facets.sk,
"sort keys",
);
expect(allMatches).to.throw(
"Incomplete or invalid key facets supplied. Missing properties: mall, building, unit",
);
expect(pkMatches).to.throw(
"Incomplete or invalid partition keys supplied. Missing properties: mall",
);
expect(skMatches).to.throw(
"Incomplete or invalid sort keys supplied. Missing properties: unit",
);
});
});
describe("Filters", () => {
let MallStores = new Entity(schema);
it("Should inject model filters in clauses without causing side effects on the clauses object", () => {
function rentsLeaseEndFilter(
{ rent, leaseEnd, mall } = {},
{ lowRent, beginning, end, location } = {},
) {
return `(${rent.gte(lowRent)} AND ${mall.eq(
location,
)}) OR ${leaseEnd.between(beginning, end)}`;
}
let injected = MallStores._filterBuilder.injectFilterClauses(clauses, {
rentsLeaseEndFilter,
});
let injectedChildren = Object.values(injected).filter(
({ children }) =>
children.includes("rentsLeaseEndFilter") || !children.includes("go"),
);
// Inject children to include the model filter AND a "filter" for inline filters.
expect(injectedChildren)
.to.be.an("array")
.and.have.length(Object.keys(injected).length);
expect(injected).includes.property("rentsLeaseEndFilter");
expect(injected).includes.property("filter");
expect(injected.rentsLeaseEndFilter).to.have.keys(["children", "action"]);
expect(injected.filter).to.have.keys(["children", "action"]);
expect(clauses).to.not.deep.equal(injected);
expect(clauses).to.not.have.key("rentsLeaseEndFilter");
let noSideEffectsOnClauses = Object.values(clauses).every(
({ children }) => !children.includes("rentsLeaseEndFilter"),
);
expect(noSideEffectsOnClauses).to.be.true;
});
it("Should add filtered fields to the begins with params", () => {
let mall = "EastPointe";
let building = "BuildingA";
let lowRent = "50.00";
let beginning = "20200101";
let end = "20200401";
let location = mall;
let buildingAUinits = MallStores.query
.units({ mall, building })
.rentsLeaseEndFilter({ lowRent, beginning, end, location })
.params();
expect(buildingAUinits).to.be.deep.equal({
IndexName: "gsi1pk-gsi1sk-index",
TableName: "StoreDirectory",
ExpressionAttributeNames: {
"#rent": "rent",
"#mall": "mall",
"#leaseEnd": "leaseEnd",
"#pk": "gsi1pk",
"#sk1": "gsi1sk",
},
ExpressionAttributeValues: {
":rent1": "50.00",
":mall1": "EastPointe",
":leaseEnd1": "20200101",
":leaseEnd2": "20200401",
":pk": "$MallStoreDirectory_1#mall_EastPointe".toLowerCase(),
":sk1": "$MallStores#building_BuildingA#unit_".toLowerCase(),
},
KeyConditionExpression: "#pk = :pk and begins_with(#sk1, :sk1)",
FilterExpression:
"(#rent >= :rent1 AND #mall = :mall1) OR (#leaseEnd between :leaseEnd1 and :leaseEnd2)",
});
});
it("Should add filtered fields to the begins with params", () => {
let mall = "EastPointe";
let building = "BuildingA";
let lowRent = "50.00";
let beginning = "20200101";
let end = "20200401";
let location = mall;
let buildingAUinits = MallStores.query
.units({ mall, building })
.rentsLeaseEndFilter({ lowRent, beginning, end, location })
.params();
expect(buildingAUinits).to.be.deep.equal({
IndexName: "gsi1pk-gsi1sk-index",
TableName: "StoreDirectory",
ExpressionAttributeNames: {
"#rent": "rent",
"#mall": "mall",
"#leaseEnd": "leaseEnd",
"#pk": "gsi1pk",
"#sk1": "gsi1sk",
},
ExpressionAttributeValues: {
":rent1": "50.00",
":mall1": "EastPointe",
":leaseEnd1": "20200101",
":leaseEnd2": "20200401",
":pk": "$MallStoreDirectory_1#mall_EastPointe".toLowerCase(),
":sk1": "$MallStores#building_BuildingA#unit_".toLowerCase(),
},
KeyConditionExpression: "#pk = :pk and begins_with(#sk1, :sk1)",
FilterExpression:
"(#rent >= :rent1 AND #mall = :mall1) OR (#leaseEnd between :leaseEnd1 and :leaseEnd2)",
});
});
it("Should add filtered fields to the between params", () => {
let mall = "EastPointe";
let building = "BuildingA";
let lowRent = "50.00";
let beginning = "20200101";
let end = "20200401";
let location = mall;
let category = "food/coffee";
let eastPointeCoffeeShops = MallStores.query
.categories({ mall, category })
.between({ building: buildingOne }, { building: buildingTwo })
.rentsLeaseEndFilter({ lowRent, beginning, end, location })
.params();
expect(eastPointeCoffeeShops).to.be.deep.equal({
IndexName: "gsi3pk-gsi3sk-index",
TableName: "StoreDirectory",
ExpressionAttributeNames: {
"#rent": "rent",
"#mall": "mall",
"#leaseEnd": "leaseEnd",
"#pk": "gsi3pk",
"#sk1": "gsi3sk",
},
ExpressionAttributeValues: {
":rent1": "50.00",
":mall1": "EastPointe",
":leaseEnd1": "20200101",
":leaseEnd2": "20200401",
":pk": "$MallStoreDirectory_1#mall_EastPointe".toLowerCase(),
":sk1": "$MallStores#category_food/coffee#building_BuildingA#unit_".toLowerCase(),
":sk2": "$MallStores#category_food/coffee#building_BuildingF#unit_".toLowerCase(),
},
KeyConditionExpression: "#pk = :pk and #sk1 BETWEEN :sk1 AND :sk2",
FilterExpression:
"(#rent >= :rent1 AND #mall = :mall1) OR (#leaseEnd between :leaseEnd1 and :leaseEnd2)",
});
});
it("Should add filtered fields to the comparison params", () => {
let mall = "EastPointe";
let lowRent = "50.00";
let beginning = "20200101";
let end = "20200401";
let location = mall;
let leaseEnd = "20201231";
let leasesAboutToExpire = MallStores.query
.leases({ mall })
.lte({ leaseEnd })
.rentsLeaseEndFilter({ lowRent, beginning, end, location })
.params();
expect(leasesAboutToExpire).to.be.deep.equal({
IndexName: "gsi2pk-gsi2sk-index",
TableName: "StoreDirectory",
ExpressionAttributeNames: {
"#rent": "rent",
"#mall": "mall",
"#leaseEnd": "leaseEnd",
"#pk": "gsi2pk",
"#sk1": "gsi2sk",
},
ExpressionAttributeValues: {
":rent1": "50.00",
":mall1": "EastPointe",
":leaseEnd1": "20200101",
":leaseEnd2": "20200401",
":pk": "$MallStoreDirectory_1#mall_EastPointe".toLowerCase(),
":sk1": "$MallStores#leaseEnd_20201231#store_".toLowerCase(),
},
KeyConditionExpression: "#pk = :pk and #sk1 <= :sk1",
FilterExpression:
"(#rent >= :rent1 AND #mall = :mall1) OR (#leaseEnd between :leaseEnd1 and :leaseEnd2)",
});
});
});
});
|
import { StyleSheet } from 'react-native';
const onboardingStyles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
button: {
height: 50,
width: 100,
alignItems: 'center',
justifyContent: 'center',
borderRadius: 10
},
headerText: {
fontSize: 24
}
});
export default onboardingStyles;
|
import React from 'react';
import logo from "../images/logo.png";
const Header = () => {
return (
<div>
<nav>
<img className="logoapp" src={logo} alt="Logo le bon burger" />
</nav>
</div>
);
};
export default Header;
|
'use strict';
var knex = require('../../connection.js');
var Node = require('./helpers/create-node.js');
var Way = require('./helpers/create-way.js');
var Relation = require('./helpers/create-relation.js');
var Change = require('./helpers/create-changeset.js');
var serverTest = require('./helpers/server-test');
var testChangeset = new serverTest.testChangeset();
var get = serverTest.createGet('/relations');
function makeNodes(changesetId, ii) {
var nodes = [];
for (var i = 0; i < ii; ++i) {
nodes.push(new Node({ id: -(i+1), changeset: changesetId }));
}
return nodes;
}
describe('Relations endpoint', function() {
after(function (done) {
testChangeset.remove()
.then(function () {
return done();
})
.catch(done);
});
before('Create changeset', function (done) {
testChangeset.create()
.then(function (changesetId) {
var cs = new Change();
var nodes = makeNodes(changesetId, 5);
var way = new Way({id: 1, changeset: changesetId}).nodes(nodes);
var relation = new Relation({id: 11, changeset: changesetId})
.members('node', nodes)
.members('way', way)
.tags({ k: 'test', v: 'relation_endpoint' });
cs.create('node', nodes)
.create('way', way)
.create('relation', relation);
testChangeset.upload(cs.get())
.then(function(res) {
return done();
})
.catch(done);
})
.catch(done);
});
it('Should return a valid relation, using a tag search', function(done) {
get('?test=relation_endpoint').then(function(res) {
res.statusCode.should.eql(200);
var payload = JSON.parse(res.payload);
payload[0].should.have.keys('changeset_id', 'tags', 'id', 'timestamp', 'version', 'visible');
payload[0].tags.should.have.lengthOf(1);
done();
}).catch(done);
});
it('Should return a valid relation, using a member search', function(done) {
knex('current_relation_members')
.where('member_id', 1).andWhere('member_type', 'Way').then(function(member) {
member = member[0];
get('?member=' + member.member_id).then(function(res) {
res.statusCode.should.eql(200);
var payload = JSON.parse(res.payload);
payload[0].should.have.keys('changeset_id', 'tags', 'id', 'timestamp', 'version', 'visible');
(+payload[0].id).should.equal(11);
done();
}).catch(done);
});
});
it('Should return a valid relation, using a relation id', function(done) {
get('/11').then(function(res) {
res.statusCode.should.eql(200);
var payload = JSON.parse(res.payload);
payload[0].members.should.have.lengthOf(6);
payload[0].should.have.keys('changeset_id', 'tags', 'id', 'timestamp', 'version', 'visible', 'members');
payload[0].members.should.have.lengthOf(6);
done();
}).catch(done);
});
});
|
import moment from 'moment';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import utils from 'common/utils';
import { DatePicker } from 'antd';
import { observable, computed, action, toJS } from 'mobx';
import { observer } from 'mobx-react';
import styles from './DateRange.scss';
const PREFIX = 'date-range';
const cx = utils.classnames(PREFIX, styles);
class DateRangeModel {
@observable startValue = null;
@observable endValue = null;
@observable endOpen = false;
}
@observer
class DateRange extends Component {
constructor(props) {
super(props);
this.model = new DateRangeModel();
this.updateDateValue(this.props);
}
componentWillUpdate(props) {
this.updateDateValue(props);
}
updateDateValue = props => {
if (typeof props.startDate !== 'undefined') this.model.startValue = props.startDate;
if (typeof props.endDate !== 'undefined') this.model.endValue = props.endDate;
};
onStartChange = value => {
this.model.startValue = value;
this.props.onStartChange(value);
};
onEndChange = value => {
this.model.endValue = value;
this.props.onEndChange(value);
};
disabledStartDate = startValue => {
const { endValue } = this.model;
if (!startValue || !endValue) {
return false;
}
return startValue.valueOf() > endValue.valueOf();
};
disabledEndDate = endValue => {
const { startValue } = this.model;
if (!endValue || !startValue) {
return false;
}
return endValue.valueOf() <= startValue.valueOf();
};
handleStartOpenChange = open => {
if (!open) {
this.model.endOpen = true;
}
};
handleEndOpenChange = open => {
this.model.endOpen = open;
};
render() {
return (
<div className={PREFIX} style={this.props.style}>
{this.props.showStartDate
? [
<span key={this.props.startLabel} className={cx('label')}>
{this.props.startLabel}
</span>,
<DatePicker
key="null"
disabledDate={this.disabledStartDate}
format="YYYY-MM-DD"
value={this.model.startValue}
placeholder="Start"
onChange={this.onStartChange}
onOpenChange={this.handleStartOpenChange}
style={{ width: 150 }}
size="small"
/>,
]
: null}
{this.props.showEndDate
? [
<span key={this.props.endLabel} className={cx('label')}>
{this.props.endLabel}
</span>,
<DatePicker
key="null"
disabledDate={this.disabledEndDate}
format="YYYY-MM-DD"
value={this.model.endValue}
placeholder="End"
onChange={this.onEndChange}
open={this.model.endOpen}
onOpenChange={this.handleEndOpenChange}
style={{ width: 150 }}
size="small"
/>,
]
: null}
</div>
);
}
}
DateRange.propTypes = {
startDate: PropTypes.any,
endDate: PropTypes.any,
showStartDate: PropTypes.bool,
showEndDate: PropTypes.bool,
startLabel: PropTypes.string,
endLabel: PropTypes.string,
onStartChange: PropTypes.func,
onEndChange: PropTypes.func,
};
DateRange.defaultProps = {
showStartDate: true,
showEndDate: true,
startLabel: '起始时间',
endLabel: '截止时间',
onStartChange: () => {},
onEndChange: () => {},
};
export default DateRange;
|
import React, { useEffect, useState } from 'react'
import { useHistory, useParams } from 'react-router-dom'
import { CSSTransition } from 'react-transition-group'
import Header from '../../components/Header'
import { getSinderDetailRequest } from '../../api/request'
import SongList from '../../components/SongList'
import Icon from '../../components/GlobalIcon'
import './index.scss'
function SingerDetail() {
const [singerDetail, setSingerDetail] = useState(null)
const [showStatus, setShowStatus] = useState(true)
const { id } = useParams()
const history = useHistory()
useEffect(() => {
getSinderDetailRequest(id).then(data => {
setSingerDetail(data)
})
}, [])
return (
<CSSTransition
in={showStatus}
timeout={300}
classNames='fly'
appear={true}
unmountOnExit
onExited={() => history.goBack()}
>
<section className='singer-detail-wrapper'>
<Header title='返回' handleClick={() => setShowStatus(false)}/>
<div className="background">
<img src={singerDetail && singerDetail.artist.picUrl}/>
<div className="filter"></div>
</div>
<div className="collect-btn">
<Icon type='icon-tianjiadao'/>
<span>收藏</span>
</div>
<SongList songList={singerDetail && singerDetail.hotSongs}/>
</section>
</CSSTransition>
)
}
export default SingerDetail
|
import React from "react";
import MainBody from "./MainBody";
import Services from "./Services";
import Header from "./Header";
import Projects from "./Projects";
const HomePage = () => {
document.title = "Home | Lawrence Thomas ";
return (
<div>
<Header />
<MainBody />
<Services />
<Projects />
</div>
);
};
export default HomePage;
|
const { formatWithOptions } = require("util");
var member = ["egoing", "k8805", "hansuk"];
for (var i = 0; i < member.length; i++) {
console.log(member[i]);
}
console.log();
var roles = {
programmer: "egoing",
designer: "k8805",
manager: "hoya",
};
for (var name in roles) {
console.log("object => " + name + " : " + roles[name]);
}
|
function getFavColor() {
return ['mistyrose', 'pink']
}
// var colors = getFavColor()
// var favColor = colors[0]
var [favColor, meh] = getFavColor()
console.log(favColor)
function getPerson() {
return {
name: 'codebusters',
number: 15
}
}
// var { name: wdiName } = getPerson()
// console.log(wdiName)
// var { name: name, number: number } = getPerson()
// console.log(name)
// console.log(number)
// var { name, number } = getPerson()
// console.log(name)
function getWdi() {
return {
name: 'codebusters',
number: 15,
coolbeans: {
stuff: 'meh'
}
}
}
var { name } = getWdi()
console.log(name)
|
function onlyTests(testData) {
// keep the tests with `only` flag set to true
// or keep all the tests if no tests have the `only` flag set to true
const executedTestsData = testData.filter((tcData) => tcData.only);
if (executedTestsData.length === 0) {
return testData;
}
return executedTestsData;
}
function describeJsonData(suiteTitle, testData, testCaseCallback) {
describe(suiteTitle, () => {
let executedTestsData = onlyTests(testData);
for (const tcData of executedTestsData) {
const title = `test ${tcData.testName}`;
if (tcData.skip) {
it.skip(title, () => { });
} else {
it(title, () => testCaseCallback(tcData));
}
}
});
}
module.exports = {
describeJsonData
}
|
$(document).on('turbolinks:load', function () {
$('#product_table').DataTable({
"bAutoWidth": false,
"processing": true,
"info": true,
"stateSave": true,
"serverSide": false,
"ajax": {
"url": "/homepage/get_list_products",
"type": "GET",
"dataSrc":"",
"complete": function(xhr, responseText){
console.log(xhr);
console.log(responseText);
}
},
"columns": [
{ "data": "store" },
{ "data": "name" },
{ "data": "price" },
{ "data": "quantity" },
{ "data": "variant" },
{ "data": "description" },
{
"data": function (data) {
return '<a class="btn btn-info" href="/products/'+ data["product_id"] +'">View</a> '+
'<a class="btn btn-info" href="/products/'+ data["product_id"] +'/edit">Update</a> '+
'<a class="btn btn-danger" href="/products/'+ data["product_id"] +'" data-method="delete">Delete</a>'
}
}
]
});
});
|
//组件化:就是页面的一部分,把页面的一部分进行组件化写在另一个页面,然后导出,便于维护修改
//引入react和属于react的Compontent函数
import React,{Component,Fragment} from 'react'
import * as actionCreator from'./store/actionCreator.js'
import { connect } from 'react-redux'
import './index.css';
import { Input,Button,Row,Col,List } from 'antd';
//容器组件,只负责业务逻辑和数据的处理
//用构造函数继承Compontent构造函数,然后渲染,最后返回html代码
class TodoList extends Component{//自定义组件名字首字母都要大写,而html组件则就是个一个html标签
componentDidMount(){
this.props.handleInit()
}
render(){//render负责渲染页面
const { handleChange,task,handleAdd,handleDelete,list } = this.props
return(
<div className = 'TodoList'>
<Row>
<Col span={18}>
<Input
onChange={handleChange}
value={task}/>
</Col>
<Col span={6}>
<Button type="primary"
className= 'btn' onClick={handleAdd}>
提交
</Button>
</Col>
</Row>
<List
style={{marginTop:10}}
bordered
dataSource={list}
renderItem={(item,index) => (
<List.Item onClick={()=>{handleDelete(index)}}>
{item}
</List.Item>
)}
/>
</div>
)
}
}
//将store里的数据映射到props里
const mapStateToProps = (state) =>{
console.log(state)
return{
list:state.get('todolist').get('list'),
task:state.get('todolist').get('task')
}
}
//将方法映射到组件中,从而返回到this.props里
const mapDispatchToProps =(dispatch)=>{//利用接收的dispatch参数,进行派发action
return{//将方法都需要返回一个对象,
handleChange:(ev) =>{//因为运用了箭头函数,函数内的this由定义时决定,故调用时不用再bind
const val = ev.target.value
dispatch(actionCreator.getChangeItemAction(val))
},
handleAdd:() =>{
dispatch(actionCreator.getAddItemAction())
},
handleDelete:(index)=>{
dispatch(actionCreator.getDelItemAction(index))
},
handleInit:()=>{
dispatch(actionCreator.getRequestInitDataAction())
}
}
}
export default connect(mapStateToProps,mapDispatchToProps)(TodoList);//app通过connnect方法与store进行关联,接收数据和方法
/*react-redux的好处:不用进行constructor从而进行数据的初始化,也不用将更新后的数据再次进行
设置,这些react-dedux都自己做了*/
|
jQuery.fn.shake = function(intShakes, intDistance, intDuration) {
this.each(function() {
$(this).css("position","relative");
for (var x=1; x<=intShakes; x++) {
$(this).animate({left:(intDistance*-1)}, (((intDuration/intShakes)/4)))
.animate({left:intDistance}, ((intDuration/intShakes)/2))
.animate({left:0}, (((intDuration/intShakes)/4)));
}
});
return this;
};
$(window).bind('popstate', function(e){
var hashLink = window.location.hash.replace("#","").split("|")[0]+".html";
if(hashLink != ""){
$('#content').load('view/'+hashLink+'?rnd='+Math.ceil(Math.random()*100000));
}
});
$(document).ready(function(){
var hashLink = window.location.hash.replace("#","").split("|")[0]+".html";
if(hashLink != ""){
$('#content').load('view/'+hashLink+'?rnd='+Math.ceil(Math.random()*100000));
}
$('a.jlink').click(function(){
history.pushState(null, null, this.href);
});
$('#btnLogin').click(function(){
authorize();
});
$('#btnRegister').click(function(){
register();
});
$('#btnWallet').click(function(){
registerWallet();
})
getCurrencies();
});
$(window).bind('popstate', function(e){
var hashLink = window.location.hash.replace("#","").split("|")[0]+".html";
if(hashLink != ""){
$('#content').load('view/'+hashLink+'?rnd='+Math.ceil(Math.random()*100000));
}
});
function register(){
var user = $('#inputEmail').val();
var pwd = $('#inputPassword').val();
$.ajax({
type: "POST",
url: "api/register",
data: {
login: user,
password: pwd
},
statusCode:{
200: function(){
$("#formRegister").html("Thank you.<br/>You can now login.");
},
400: function(){
$("#btnRegister").shake(3,7,400);
}
}
});
}
function registerWallet(){
var currency = $('#currency').val();
$.ajax({
type: "POST",
url: "api/registerWallet",
data: {
currency: currency
},
statusCode:{
200: function(){
$("#user-info").append("You've registered your account");
getCurrencies();
},
400: function(){
$("#btnWallet").shake(3,7,400);
}
}
});
}
function authorize(){
var user = $("#email").val();
var pwd = $("#password").val();
if(user == "" || pwd == "") return;
$.ajax({
type: "POST",
url: "api/login",
data: {
login: user,
password: pwd
},
statusCode: {
200: function(response){
document.cookie = "moneybookeruser="+user+";";
getCurrencies();
$("#content").html("<h1>Welcome</h1>");
},
400: function(response){
$("#btnLogin").shake(3,7,400);
}
}
});
}
function getCurrencies(){
$.ajax({
type: "GET",
url: "api/getCurrencies",
statusCode: {
200: function(response){
$("#walletCurrencies").html("");
for(id in response){
$("#walletCurrencies").append("<li id='"+response[id]+"'>"+response[id]+"</li>");
getWalletInfo(response[id]);
}
$("#content").addClass("hide");
$("#user-info").removeClass("hide");
displayTransactions();
},
401: function(response){
$("#walletCurrencies").append("<li>ERROR!!!!</li>");
$("#content").removeClass("hide");
$("#user-info").addClass("hide");
}
}
});
}
function getWalletInfo(currency) {
$.ajax({
type: "GET",
url: "api/getWalletBalance",
data: {
currency: currency
},
async: false,
statusCode: {
200: function(response){
$("#"+currency).append(" "+response);
}
}
});
}
function addToWallet() {
var amount = $("#addAmount").val();
var currency = $("#cur").val();
$.ajax({
type: "POST",
url: "api/addAmount",
data: {
currency: currency,
amount: amount
},
statusCode: {
200: function(response){
getCurrencies();
}
}
});
}
function withdrawFromWallet() {
var amount = $("#withdrawAmount").val();
var currency = $("#withdrawCurrency").val();
$.ajax({
type: "POST",
url: "api/withdrawAmount",
data: {
currency: currency,
amount: amount
},
statusCode: {
200: function(response){
getCurrencies();
}
}
});
}
function displayTransactions(){
$.ajax({
type: "GET",
url: "api/transactions",
async: false,
statusCode: {
200: function(response){
for(transactionId in response){
$("#transactions").append("<tr id='transaction"+transactionId+"'></tr>");
$("#transaction"+transactionId).append("<td>"+response[transactionId].emailTo+"</td>"+
"<td>"+response[transactionId].emailFrom+"</td>"+
"<td>"+response[transactionId].amount+"</td>"+
"<td>"+response[transactionId].currency+"</td>"+
"<td>"+response[transactionId].status+"</td>");
}
}
}
})
}
|
let factStudents = document.getElementById("fact-students");
let factTeachers = document.getElementById("fact-teachers");
let factActivities = document.getElementById("fact-activities");
let factCourses = document.getElementById("fact-courses");
function count(element, limit) {
let counter = 0;
let i = setInterval(function() {
element.innerText = counter;
counter++;
if (counter === limit + 1) {
clearInterval(i);
}
}, 20);
};
count(factStudents, Number(factStudents.getAttribute("data-number")));
count(factTeachers, Number(factTeachers.getAttribute("data-number")));
count(factActivities, Number(factActivities.getAttribute("data-number")));
count(factCourses, Number(factCourses.getAttribute("data-number")));
|
//document.writelnは、指定された文字列を表示するための命令です。
document.writeln('Hello, World !');
|
// Connect to server
var io = require('socket.io-client'),
config = require('./config.json'),
stats = require('./stats.js'),
ip = '127.0.0.1',
socket = io.connect('http://'+config.host+':'+config.port+'/', {reconnect: true});
// Add a connect listener
socket.on('connect', function() {
// Announce ourselves to the server
stats.getUID(function (uid) {
socket.emit('server.connect', uid);
})
stats.sendStats(socket);
socket.on('reconnect', function () {
// console.log("Reconnecting, updating status to server...");
stats.sendStats(socket);
});
setInterval(function () {
stats.sendStats(socket);
}, 3000);
});
socket.on('connect_error', function (err) {
console.log("OSBotHelper couldn't connect to your server, please check config.");
console.log(err);
});
module.exports = socket;
|
$("add_list").submit(function(event){
alert("inserted successfully");
})
if(window.location.pathname=="/")
{
$ondelete = $(".table tbody td a.del");
$ondelete.click(function()
{
var id = $(this).attr("data-id")
var request ={
"url":`http://localhost:3000/api/list/${id}`,
"method":"DELETE"
}
if(confirm("Want to Delete?")){
$.ajax(request).done(function(response){
alert("Deleted Successfully!");
location.reload();
})
}
})
}
|
import React, {Component} from 'react';
export default class Add extends Component{
render(){
return(
<div className ="add-button">
<button onClick = {this.props.setAccess}>+</button>
</div>
);
}
}
|
const {delay, parsePrice} = require('.')
module.exports = async ({page, origin, destination, departDate, returnDate, goto}) => {
const departDateString = toISOString(departDate)
const returnDateString = toISOString(returnDate)
await page.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36')
// Going to scyscanner
await page.goto('https://skyscanner.com?currency=USD&market=US&locale=en-US')
await delay(1000)
// Typing origin
await page.waitForSelector('#fsc-origin-search')
await page.evaluate((selector) => document.querySelector(selector).click(), '#fsc-origin-search')
await page.focus('#fsc-origin-search')
await page.keyboard.press('Backspace')
await page.type('#fsc-origin-search', origin)
await page.keyboard.press('Tab')
// Typing destination
await page.waitForSelector('#fsc-destination-search')
await page.evaluate((selector) => document.querySelector(selector).click(), '#fsc-destination-search')
await page.focus('#fsc-destination-search')
await page.keyboard.press('Backspace')
await page.type('#fsc-destination-search', destination)
await page.keyboard.press('Tab')
// Choosing first segment
// Opening calendar
await page.evaluate((selector) => document.querySelector(selector).click(), '#depart-fsc-datepicker-button')
await page.waitForSelector('#depart-calendar__bpk_calendar_nav_select')
// Cut first 0 from depart day
let departDay = departDateString.substr(8, 2)
if (departDay.substr(0, 1) === '0') {
departDay = departDay.substr(1, 1)
}
// Select correct month/year in calendar
await page.select('#depart-calendar__bpk_calendar_nav_select', departDateString.substr(0, 7))
// Select correct day in calendar
const dates = await page.$$('button[class^="bpk-calendar-date_bpk-calendar-date"]')
for (let i = 0; i < dates.length; i++) {
let className = await page.evaluate(
date => date.getAttribute('class'),
dates[i],
)
if (className.includes("outside") || className.includes("blocked")) {
continue
}
let buttonSpan = await dates[i].$('span')
let val = await page.evaluate(
span => span.innerText,
buttonSpan,
)
if (val === departDay) {
dates[i].click()
}
}
if (returnDateString !== '') {
// Choosing second segment
// Opening calendar
await page.evaluate((selector) => document.querySelector(selector).click(), '#return-fsc-datepicker-button')
await page.waitForSelector('#return-calendar__bpk_calendar_nav_select')
// Cut first 0 from depart day
let returnDay = returnDateString.substr(8, 2)
if (returnDay.substr(0, 1) === '0') {
returnDay = departDay.substr(1, 1)
}
// Select correct month/year in calendar
await page.select('#return-calendar__bpk_calendar_nav_select', returnDateString.substr(0, 7))
// Select correct day in calendar
const dates = await page.$$('button[class^="bpk-calendar-date_bpk-calendar-date"]')
for (let i = 0; i < dates.length; i++) {
let className = await page.evaluate(
date => date.getAttribute('class'),
dates[i],
)
if (className.includes("outside") || className.includes("blocked")) {
continue
}
let buttonSpan = await dates[i].$('span')
let val = await page.evaluate(
span => span.innerText,
buttonSpan,
)
if (val === returnDay) {
dates[i].click()
}
}
}
const buttons = await page.$$('button[class^="bpk-button_bpk-button"]')
for (let i = 0; i < buttons.length; i++) {
let ariaLabel = await page.evaluate(
button => button.getAttribute('aria-label'),
buttons[i],
)
if (ariaLabel !== null && ariaLabel.toString() === 'Search flights') {
buttons[i].click()
}
}
if (goto) {
return
}
await delay(30000)
const cheapestPriceElement = await page.$('[data-tab="price"] .fqs-price')
const price = await (await cheapestPriceElement.getProperty('textContent')).jsonValue()
return parsePrice(price)
}
function pad(number) {
if (number < 10) {
return '0' + number;
}
return number;
}
function toISOString(date) {
return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate())
}
|
const bcrypt = require('bcrypt');
module.exports = {
/**
* @returns A random number
*/
rng() {
return Math.random().toString(36).substr(2, 6);
},
/**
*
* @param {email} email
* @param {password} pass
* @returns {red} If username or password is empty
* @returns {green} If username and password exist
*/
isEmpty(email, pass) {
if (email.replace(/\s/g, '').length && pass.replace(/\s/g, '').length) {
return 'green';
} else {
return 'red';
}
},
/**
*
* @param {Object} obj
* Checks if object exists
*/
objIsEmpty(obj) {
if (obj) {
return 'goodCookie';
} else {
return 'redirect';
}
},
/**
*
* @param {users} users
* @param {input} input
* Checks if an input exists in the user object
*/
checkExist(users, input) {
let bool;
Object.values(users).forEach((element) => {
console.log(element.email);
console.log(element);
console.log(input);
if (element.email === input) {
bool = true;
}
});
return bool;
},
/**
*
* @param {users} users
* @param {input} input
* Checks if an input object exists in the user object
*/
checkLogin(users, input) {
let out;
Object.values(users).forEach((element) => {
if (bcrypt.compareSync(input.password, element.password) && element.email === input.email) {
out = element.id;
console.log(out);
}
});
return out;
},
/**
*
* @param {db} db
* @param {key} key
* Checks if key exists in object
*/
outDB(db, key) {
let outObj = {};
Object.keys(db).forEach((element) => {
if (element === key) {
outObj = db[element];
}
});
return outObj;
},
/**
*
* @param {urls} urls
* Flattens an object 1 level
*/
innerUrls(urls) {
urls =
Object.assign(
{},
...function _flatten(urls) {
return [].concat(...Object.keys(urls)
.map((k) =>
typeof urls[k] === 'object' ?
_flatten(urls[k]) :
({[k]: urls[k]})
)
);
}(urls));
return urls;
},
};
|
var express = require("express");
var router = express.Router();
// Middleware
const calendarAuth = require("../middleware/calendarAuth");
const checkAuth = require("../middleware/check-auth");
// Controller
const calendarController = require('../controller/calendar');
router.get('/googleOath',checkAuth,calendarController.getGoogleAuthUrl)
router.post('/saveEvents',checkAuth,calendarController.saveEvents)
router.get('/getDatabaseEvents/:userId',checkAuth,calendarController.getDatabaseEvents)
router.get('/addEventsToDatabase',checkAuth,calendarController.addEventsToDatabase)
router.post('/getGoogleEvents',checkAuth,calendarAuth, calendarController.getGoogleEvents)
//iCloud calendar
router.get('/getICloudEvents',checkAuth,calendarController.getICloudEvents)
module.exports = router;
|
const {deployContracts} = require("../scripts/deploy_contracts");
const {expect} = require('chai');
describe("ERC6786", () => {
let erc721Royalty;
let erc721;
let royaltyDebtRegistry;
const tokenId = 666;
beforeEach(async () => {
const contracts = await deployContracts();
erc721Royalty = contracts.erc721Royalty;
erc721 = contracts.erc721;
royaltyDebtRegistry = contracts.royaltyDebtRegistry;
})
it('should support ERC6786 interface', async () => {
await expect(await royaltyDebtRegistry.supportsInterface("0x253b27b0")).to.be.true;
})
it('should allow paying royalties for a ERC2981 NFT', async () => {
await expect(royaltyDebtRegistry.payRoyalties(
erc721Royalty.address,
tokenId,
{value: 1000}
)).to.emit(royaltyDebtRegistry, 'RoyaltiesPaid')
.withArgs(erc721Royalty.address, tokenId, 1000);
})
it('should not allow paying royalties for a non-ERC2981 NFT', async () => {
await expect(royaltyDebtRegistry.payRoyalties(
erc721.address,
tokenId,
{value: 1000}
)).to.be.revertedWithCustomError(royaltyDebtRegistry,'CreatorError')
.withArgs(erc721.address, tokenId);
})
it('should allow retrieving initial royalties amount for a NFT', async () => {
await expect(await royaltyDebtRegistry.getPaidRoyalties(
erc721Royalty.address,
tokenId
)).to.equal(0);
})
it('should allow retrieving royalties amount after payments for a NFT', async () => {
await royaltyDebtRegistry.payRoyalties(
erc721Royalty.address,
tokenId,
{value: 2000}
);
await royaltyDebtRegistry.payRoyalties(
erc721Royalty.address,
tokenId,
{value: 3666}
)
await expect(await royaltyDebtRegistry.getPaidRoyalties(
erc721Royalty.address,
tokenId
)).to.equal(5666);
})
});
|
const express = require("express");
const {
createBook,
getAllBooks,
updateBook,
deleteBook,
getBook,
getPublishedBooks,
} = require("../controllers/bookControllers");
const router = express.Router();
router.route("/books").get(getAllBooks).post(createBook);
router.route("/books/:id").patch(updateBook).delete(deleteBook).get(getBook);
router.route("/books/published").get(getPublishedBooks);
module.exports = router;
|
var webpack = require('webpack');
module.exports = {
entry: [
__dirname + '/index.jsx'
],
module: {
loaders: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel'
},{
test: /\.less$/,
loaders: ["style", "css", "less"]
}
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.less']
},
output: {
path: __dirname + '/static',
publicPath: '/static/',
filename: 'bundle.js'
},
externals: {
'Config': JSON.stringify(process.env.NODE_ENV == 'production' ? {
host_url: "http://manojsinghnegi.com",
} : {
host_url: "http://localhost",
})
},
plugins: [
(process.env.NODE_ENV == 'production' ?
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}) : function () {}),
(process.env.NODE_ENV == 'production' ?
new webpack.optimize.UglifyJsPlugin({
compress:{
warnings: true
}
})
: function () {})
],
devServer: {
contentBase: __dirname + '/dist',
historyApiFallback: true
}
}
|
import React from "react";
import logo from "./logo.svg";
import "./App.css";
import Movie from "./hoc/Movie";
import FunctionalMovie from "./hoc/FunctionalMovie";
import HookUsers from "./hook/HookUsers";
import TodoPage from "./context/TodoPage";
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<TodoPage />
<HookUsers />
<Movie id={1} toolTip="movie_name" />
<FunctionalMovie user="roller" toolTip="another_name" />
</header>
</div>
);
}
export default App;
|
import axios from "axios";
const URL = process.env.REACT_APP_BASE_URL;
export default class noteService {
addNote = (data) => {
console.log(data);
return axios.post(
process.env.REACT_APP_BASE_URL + "/notes/addNotes",
data,
{
headers: {
Authorization: localStorage.getItem("token"),
},
}
);
};
getNotes = () => {
return axios.get(process.env.REACT_APP_BASE_URL + "/notes/getNotesList", {
headers: {
Authorization: localStorage.getItem("token"),
},
});
};
deleteNote = (data) => {
return axios.post(
process.env.REACT_APP_BASE_URL + "/notes/trashNotes",
data,
{
headers: {
Authorization: localStorage.getItem("token"),
},
}
);
};
updateNotes = (data) => {
return axios.post(
process.env.REACT_APP_BASE_URL + "/notes/updateNotes",
data,
{
headers: {
Authorization: localStorage.getItem("token"),
},
}
);
};
updateColor = (data) => {
return axios.post(
process.env.REACT_APP_BASE_URL + "/notes/changesColorNotes",
data,
{
headers: {
Authorization: localStorage.getItem("token"),
},
}
);
};
archiveNotes = (data) => {
return axios.post(
process.env.REACT_APP_BASE_URL + "/notes/archiveNotes",
data,
{
headers: {
Authorization: localStorage.getItem("token"),
},
}
);
};
getArchiveNoteList = () => {
return axios.get(
process.env.REACT_APP_BASE_URL + "/notes/getArchiveNotesList",
{
headers: {
Authorization: localStorage.getItem("token"),
},
}
);
};
getTrashNoteList = () => {
return axios.get(
process.env.REACT_APP_BASE_URL + "/notes/getTrashNotesList",
{
headers: {
Authorization: localStorage.getItem("token"),
},
}
);
};
uploadImage = (data) => {
return axios.post(
process.env.REACT_APP_BASE_URL + "/user/uploadProfileImage",
data,
{
headers: {
Authorization: localStorage.getItem("token"),
},
}
);
};
}
|
function CountAnimals(tur,horse,pigs) {
return (tur*2)+(horse*4)+(pigs*4)
}
console.log(CountAnimals(2,3,5));
console.log(CountAnimals(1,2,3));
console.log(CountAnimals(5,2,8));
|
({
doInit: function (component, event, helper) {
helper.getCart(component, event);
},
nextPage: function (component, event, helper) {
helper.updateCart(component, event);
}
});
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Utils = undefined;
var _mysql = require('mysql');
var _mysql2 = _interopRequireDefault(_mysql);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const Utils = exports.Utils = {
_mysqlConnection() {
const connection = _mysql2.default.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'zxc',
port: '3306',
database: 'blog'
});
return new Promise((resolve, reject) => {
connection.connect(err => {
if (err) {
reject(err);
}
console.log('[connection connect] succeed!');
});
resolve(connection);
});
},
_mysqlQuery(query, params = null) {
return this._mysqlConnection().then(connection => {
const result = new Promise((resolve, reject) => {
connection.query(query, [params], (err, result) => {
if (err) {
reject(err);
}
resolve(result);
});
});
connection.end();
return result;
}, err => {
console.log('[connect] - :' + err);
});
},
saveSite(params) {
const query = 'INSERT INTO site (url) VALUES ?';
return this._mysqlQuery(query, params).then(result => {
return result;
}, err => {
console.log('[query] - ' + err);
});
},
saveUrl(params) {
const query = 'INSERT INTO url (site, url) VALUES ?';
return this._mysqlQuery(query, params).then(result => {
return result;
}, err => {
console.log('[query] - ' + err);
});
},
saveUrlRelations(params) {
const query = 'INSERT INTO urlToUrl (site, origin, destination) VALUES ?';
return this._mysqlQuery(query, params).then(result => {
return result;
}, err => {
console.log('[query] - ' + err);
});
}
};
|
var instru_xC3_xA7_xC3_xB5es_8c =
[
[ "CLASSMANAGER_SERV", "instru_xC3_xA7_xC3_xB5es_8c.html#a5c7b181a46e1bf752e98109ae790381f", null ],
[ "instr_getstatic", "instru_xC3_xA7_xC3_xB5es_8c.html#ad7215ec43e477fd0d714312ff9b2cbc5", null ],
[ "instr_invokeVirtual", "instru_xC3_xA7_xC3_xB5es_8c.html#ac93ee3bf196754a3dd1faca30ea92f45", null ],
[ "returnOpcode", "instru_xC3_xA7_xC3_xB5es_8c.html#acdca2d01b42b11b32c45734e38f681f1", null ],
[ "returnType", "instru_xC3_xA7_xC3_xB5es_8c.html#a30f0eb77494e95a86fe48db2c170684b", null ]
];
|
$(document).ready(function () {
$(".tab1").click(function () {
$(".notice").show();
$(".gallery").hide();
})
$(".tab2").click(function () {
$(".notice").hide();
$(".gallery").show();
})
$(".notice>p>a").click(function () {
$(".pop").show();
$(".bg").show();
})
$(".pop-btn").click(function () {
$(".pop").hide();
$(".bg").hide();
})
$(".bg").click(function(){
$(".pop").hide();
$(".bg").hide();
})
$(".mainmenu>li").hover(
function(){
$(this).find(".submenu").stop().slideDown(200);
},
function(){
$(this).find(".submenu").stop().slideUp(200);
}
);
});
|
import api from './request';
import path from 'path';
const urls = {
root: 'user',
register: () => path.join(urls.root, 'register'),
login: () => path.join(urls.root, 'login')
};
function register(credentials) {
return api.post(urls.register(), credentials);
}
function login(credentials) {
return api.post(urls.login(), credentials)
.then(res => res.data);
}
export default { login, register };
|
var express = require("express");
var app = express();
var surveyTable = [
{
key: "quickPoll",
position: 1,
name: "Quick Poll",
openDate: new Date(),
closedDate: new Date(),
languages: [
{ value: "Mn", viewValue: "Mandarin" },
{ value: "Fr", viewValue: "French" },
{ value: "Ar", viewValue: "Arabic" },
{ value: "Sw", viewValue: "Swedish" },
{ value: "pl", viewValue: "Polish" },
],
},
{
key: "covid19",
position: 2,
name: "Covid-19",
openDate: new Date(),
closedDate: new Date(),
languages: [
{ value: "Gr", viewValue: "German" },
{ value: "fr", viewValue: "French" },
{ value: "Ur", viewValue: "Urdu" },
{ value: "Bh", viewValue: "Bahasa" },
],
},
{
key: "medSurvey",
position: 3,
name: "Medical Store Survey",
openDate: new Date(),
closedDate: new Date(),
languages: [
{ value: "Hi", viewValue: "Hindi" },
{ value: "fr", viewValue: "French" },
{ value: "Ar", viewValue: "Arabic" },
{ value: "Bn", viewValue: "Bengali" },
],
},
{
key: "freshSurvey",
position: 4,
name: "Fresh Store Survey",
openDate: new Date(),
closedDate: new Date(),
languages: [
{ value: "Gr", viewValue: "German" },
{ value: "fr", viewValue: "French" },
{ value: "Ar", viewValue: "Arabic" },
{ value: "En", viewValue: "English" },
],
},
{
key: "retailSurvey",
position: 5,
name: "Retail Servey",
openDate: new Date(),
closedDate: new Date(),
languages: [
{ value: "Ml", viewValue: "Malayalam" },
{ value: "fr", viewValue: "French" },
{ value: "Ar", viewValue: "Arabic" },
{ value: "Tm", viewValue: "Tamil" },
],
},
];
var covidSurvey =[
{ controlType:'dropdown',
key: 'Dropdown Select',
label: 'How would you rate the precautions taken by the Reliance family against COVID-19.',
options: [
{ key: 'amazing', value: 'Amazing' },
{ key: 'great', value: 'Great' },
{ key: 'good', value: 'Good' },
{ key: 'bad', value: 'Bad' },
{ key: 'Unsatisfactory', value: 'Unsatisfactory' },
],
order: 1,
},
{
controlType:'textbox',
key: 'textbox1 input',
label: 'Any new suggestions which could be forwarded to the upper authorities.*',
// value: 'Amazing',
required: true,
order: 2,
},
{
controlType:'textbox',
key: 'textbox2 input',
label: 'Has anyone from your family been treated with COVID-19? Kindly give the name of the member and the relation with you.',
type: 'email',
order: 3,
},
{
controlType:'sChoice',
key: 'Single Choice Questions',
label: 'How would you rate the communications of HRBP regarding the infos of COVID-19.',
options: [
{ key: 'amazing', value: 'Amazing' },
{ key: 'great', value: 'Great' },
{ key: 'good', value: 'Good' },
{ key: 'bad', value: 'Bad' },
],
order: 4,
},
{
controlType:'mChoice',
key: 'Multi Choice Question',
label: 'Select your hobbies from the below list (note: multiple select allowed).',
options: [
{ key: 'reading', value: 'Reading' },
{ key: 'swimming', value: 'Swimming' },
{ key: 'surfing', value: 'Surfing' },
{ key: 'cooking', value: 'Cooking' },
{ key: 'travelling', value: 'Travelling' },
],
order: 5,
}
];
var medSurvey=[
{ controlType:'dropdown',
key: 'Dropdown Select',
label: 'How would you rate the services provided in Reliance Retail?',
options: [
{ key: 'amazing', value: 'Amazing' },
{ key: 'great', value: 'Great' },
{ key: 'good', value: 'Good' },
{ key: 'bad', value: 'Bad' },
{ key: 'Unsatisfactory', value: 'Unsatisfactory' },
],
order: 2,
},
{
controlType:'textbox',
key: 'textbox1 input',
label: 'What Are The Three Qualities A Professional Pharmacist Should Have?*',
// value: 'Amazing',
required: true,
order: 3,
},
{
controlType:'textbox',
key: 'textbox2 input',
label: 'What Are The Record Keeping Procedures That A Pharmacist Have To Do?',
type: 'email',
order: 4,
},
{
controlType:'sChoice',
key: 'Single Choice Questions',
label: 'What Are The Side Effects Of Methadone?',
options: [
{ key: 'amazing', value: 'Amazing' },
{ key: 'great', value: 'Great' },
{ key: 'good', value: 'Good' },
{ key: 'bad', value: 'Bad' },
],
order: 5,
},
{
controlType:'mChoice',
key: 'Multi Choice Question',
label: 'What Are The Errors That A Pharmacist Should Avoid While Dispensing Drug?',
options: [
{ key: 'reading', value: 'Reading' },
{ key: 'swimming', value: 'Swimming' },
{ key: 'surfing', value: 'Surfing' },
{ key: 'cooking', value: 'Cooking' },
{ key: 'travelling', value: 'Travelling' },
],
order: 1,
}];
var quickPoll=[
{ controlType:'dropdown',
key: 'Dropdown Select',
label: 'Have you used this program/app before?',
options: [
{ key: 'amazing', value: 'Amazing' },
{ key: 'great', value: 'Great' },
{ key: 'good', value: 'Good' },
{ key: 'bad', value: 'Bad' },
{ key: 'Unsatisfactory', value: 'Unsatisfactory' },
],
order: 4,
},
{ controlType:'dropdown',
key: 'Dropdown Select',
label: 'Using one word, what do you think is the major challenge event organizers are facing?',
options: [
{ key: 'amazing', value: 'Amazing' },
{ key: 'great', value: 'Great' },
{ key: 'good', value: 'Good' },
{ key: 'bad', value: 'Bad' },
{ key: 'Unsatisfactory', value: 'Unsatisfactory' },
],
order: 5,
},
{
controlType:'textbox',
key: 'textbox1 input',
label: 'What is the biggest cybersecurity threat to your business?*',
// value: 'Amazing',
required: true,
order: 6,
},
{
controlType:'textbox',
key: 'textbox2 input',
label: 'How would you rate the quality of audience interaction when attending online events?',
type: 'email',
order: 1,
},
{
controlType:'sChoice',
key: 'Single Choice Questions',
label: 'If you could bring one thing from the office to your home, what would it be?',
options: [
{ key: 'amazing', value: 'Amazing' },
{ key: 'great', value: 'Great' },
{ key: 'good', value: 'Good' },
{ key: 'bad', value: 'Bad' },
],
order: 2,
},
{
controlType:'mChoice',
key: 'Multi Choice Question',
label: 'What’s the first thing you will do once the quarantine is over?',
options: [
{ key: 'reading', value: 'Reading' },
{ key: 'swimming', value: 'Swimming' },
{ key: 'surfing', value: 'Surfing' },
{ key: 'cooking', value: 'Cooking' },
{ key: 'travelling', value: 'Travelling' },
],
order: 3,
}];
var retailSurvey=[
{ controlType:'dropdown',
key: 'Dropdown Select',
label: 'Were you made to feel welcome during your visit (greeted and/or thanked by one or more associates)?',
options: [
{ key: 'amazing', value: 'Amazing' },
{ key: 'great', value: 'Great' },
{ key: 'good', value: 'Good' },
{ key: 'bad', value: 'Bad' },
{ key: 'Unsatisfactory', value: 'Unsatisfactory' },
],
order: 5,
},
{
controlType:'textbox',
key: 'textbox1 input',
label: 'Were the items appropriately priced?*',
// value: 'Amazing',
required: true,
order: 4,
},
{
controlType:'textbox',
key: 'textbox2 input',
label: 'Was the merchandise high quality?',
type: 'email',
order: 3,
},
{
controlType:'sChoice',
key: 'Single Choice Questions',
label: 'Did the cashier process the transaction quickly and effectively?',
options: [
{ key: 'amazing', value: 'Amazing' },
{ key: 'great', value: 'Great' },
{ key: 'good', value: 'Good' },
{ key: 'bad', value: 'Bad' },
],
order: 2,
},
{
controlType:'mChoice',
key: 'Multi Choice Question',
label: 'Did the store have a reasonable return and exchange policy?',
options: [
{ key: 'reading', value: 'Reading' },
{ key: 'swimming', value: 'Swimming' },
{ key: 'surfing', value: 'Surfing' },
{ key: 'cooking', value: 'Cooking' },
{ key: 'travelling', value: 'Travelling' },
],
order: 1,
}];
var freshSurvey=[
{ controlType:'dropdown',
key: 'Dropdown Select',
label: 'Are traders delivering products stored outside the market area?',
options: [
{ key: 'amazing', value: 'Amazing' },
{ key: 'great', value: 'Great' },
{ key: 'good', value: 'Good' },
{ key: 'bad', value: 'Bad' },
{ key: 'Unsatisfactory', value: 'Unsatisfactory' },
],
order: 4,
},
{
controlType:'textbox',
key: 'textbox1 input',
label: 'Were adequate informations provided to you in the store?*',
// value: 'Amazing',
required: true,
order: 5,
},
{
controlType:'textbox',
key: 'textbox2 input',
label: 'Were the managers and staff members courteous, helpful to you?',
type: 'email',
order: 3,
},
{
controlType:'sChoice',
key: 'Single Choice Questions',
label: 'How will you rate the qualities of the vegetables getting sold in the store?',
options: [
{ key: 'amazing', value: 'Amazing' },
{ key: 'great', value: 'Great' },
{ key: 'good', value: 'Good' },
{ key: 'bad', value: 'Bad' },
],
order: 1,
},
{
controlType:'mChoice',
key: 'Multi Choice Question',
label: 'What are go to items everytime you visit the fresh store',
options: [
{ key: 'reading', value: 'Lecturing' },
{ key: 'swimming', value: 'Marathon' },
{ key: 'surfing', value: 'Walking' },
{ key: 'cooking', value: 'Running' },
{ key: 'travelling', value: 'Singing' },
],
order: 2,
}];
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.get("/", (req, res) => {
res.send("hello");
});
app.get("/table", (req, res) => {
res.json(surveyTable);
});
app.get("/survey/:name", (req, res) => {
var user = req.params.name;
//console.log(req.params);
//console.log(user);
if (user == "quickPoll" )
{
console.log(user);
res.json(quickPoll);
}
if (user == "covid19" )
{
console.log(user);
res.json(covidSurvey);
}
if (user == "medSurvey" )
{
console.log(user);
res.json(medSurvey);
}
if (user == "freshSurvey" )
{
console.log(user);
res.json(freshSurvey);
}
if (user == "retailSurvey" )
{
console.log(user);
res.json(retailSurvey);
}
});
app.listen(3000);
|
/**
* 运费管理
*/
import React, { Component, PureComponent } from 'react';
import {
StyleSheet,
Dimensions,
View,
Text,
Button,
Image,
FlatList,
RefreshControl,
TouchableOpacity,
} from 'react-native';
import Header from '../../components/Header'
import { connect } from 'rn-dva'
import CommonStyles from '../../common/Styles'
import FlatListView from '../../components/FlatListView'
import Content from '../../components/ContentItem'
import * as requestApi from '../../config/requestApi'
import ListEmptyCom from '../../components/ListEmptyCom';
import math from '../../config/math';
const { width, height } = Dimensions.get('window')
function getwidth(val) {
return width * val / 375
}
class FreightManagScreen extends Component {
constructor(props) {
super(props)
this.state={
listName:'freight'
}
}
componentDidMount(){
this.getList(true, false);
}
getList = (isFirst = false, isLoadingMore = false) => {
this.props.fetchList({
witchList:this.state.listName,
isFirst,
isLoadingMore,
paramsPrivate : {
shopId: this.props.userShop.id
},
api:requestApi.mUserPostFeeQList
})
};
renderdestFee = (item) => {
let destFee = item.destFee || {}
let valuateType = item.valuateType
// if(valuateType === 'NONE'){
// return <Text style={styles.itemcontenttxt}>晓可物流</Text>
// }
let defaultNum = destFee.defaultNum //多少内
let defaultFee =math.divide(Number(destFee.defaultFee || 0) ,100) //多少钱
let increNum = destFee.increNum //每增加
let increFee =math.divide(Number(destFee.increFee || 0) ,100) //增加多少钱
if (!defaultNum && !defaultFee && !increNum && !increFee) {
return <Text style={styles.itemcontenttxt}>未设置</Text>
}
if (valuateType === 'BY_NUMBER') {
defaultNum = defaultNum + '件'
increNum = increNum + '件'
} else if(valuateType === 'BY_WEIGHT'){
defaultNum = (math.divide(defaultNum || 0,1000)) + 'kg'
increNum = (math.divide(increNum || 0,1000)) + 'kg'
}else{
defaultNum = (math.divide(defaultNum || 0,1000)) + 'km'
increNum = (math.divide(increNum || 0,1000)) + 'km'
}
return <Text ellipsizeMode='tail' numberOfLines={1} style={styles.itemcontenttxt} >{defaultNum}内{defaultFee}元,每增加{increNum}增加运费{increFee}元</Text>
}
renderItem = (data) => {
let item = data.item
return (
<Content style={styles.itemcontent} key={data.index}>
<View>
<Text style={styles.itemTitle}>{item.storeName}</Text>
{
this.renderdestFee(item)
}
</View>
<TouchableOpacity style={styles.btnItem} onPress={() => { this.handleItem(item) }}>
<Text style={{ color: '#4A90FA' }}>编辑</Text>
</TouchableOpacity>
</Content>
)
}
handleItem = (item) => {
const { navigation } = this.props
navigation.navigate('FreightManagEditor', { itemdata: item,callback:()=>this.getList(false, false)})
}
render() {
const { navigation, longLists } = this.props;
const { listName } = this.state;
return (
<View style={styles.container}>
<Header
navigation={navigation}
goBack={true}
title='运费管理'
/>
<FlatListView
style={styles.flatListView}
renderItem={data => this.renderItem(data)}
store={{
...(longLists[listName] || {}),
page: longLists[listName] && longLists[listName].listsPage || 1
}}
data={longLists[listName] && longLists[listName].lists || []}
numColumns={1}
refreshData={() =>
this.getList(false, false)
}
loadMoreData={() =>
this.getList(false, true)
}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
...CommonStyles.containerWithoutPadding,
alignItems: 'center',
backgroundColor: CommonStyles.globalBgColor
},
flatListView:{
backgroundColor:CommonStyles.globalBgColor,
},
itemcontent: {
// alignItems: 'center',
flexDirection: 'row',
flexWrap: 'nowrap',
width: width - 20,
marginLeft: 10,
borderRadius: 6,
padding:15,
marginBottom:0,
marginTop:0
},
itemTitle: {
fontSize: 14,
color: '#222222'
},
itemcontenttxt: {
fontSize: 12,
color: '#999999',
marginTop: 15,
},
btnItem: {
width: getwidth(60),
height: 22,
borderColor: '#4A90FA',
borderWidth: 1,
borderRadius: 12,
position: 'absolute',
top: 15,
right: 15,
alignItems: 'center',
justifyContent: 'center',
},
})
export default connect(
(state) => ({
userShop:state.user.userShop || {},
longLists:state.shop.longLists || {},
}),
(dispatch) => ({
fetchList: (params={})=> dispatch({ type: "shop/getList", payload: params}),
})
)(FreightManagScreen)
|
const fs = require('fs')
const admin = require('firebase-admin')
const config = require('../firebase.json')
// set up firebase admin connection
admin.initializeApp({
credential: admin.credential.cert(config),
databaseURL: 'https://ruhacksapp.firebaseio.com',
})
const passportConfigFile = './passportConfig.json'
let passportLock = ''
function createPassport (uid) {
const userAppRef = `userApplications/${uid}`
const userPassportRef = `passport/${uid}`
return new Promise((resolve, reject) => {
admin.database().ref(userAppRef).once('value')
.then((snapshot) => {
if (snapshot.val()) {
const userApp = snapshot.val()
const userPassport = {
name: `${userApp.name.first} ${userApp.name.last}`,
state: {
registered: false,
},
}
admin.database().ref(userPassportRef).set(userPassport)
.then(() => resolve(userPassport))
.catch((error) => reject(error))
}
})
.catch((error) => reject(error))
})
}
function getPassport (uid) {
const ref = `passport/${uid}`
return new Promise((resolve, reject) => {
admin.database().ref(ref).once('value')
.then((snapshot) => {
if (snapshot.val()) {
resolve(snapshot.val())
} else {
createPassport(uid)
.then((passport) => resolve(passport))
.catch((error) => {
process.stderr.write(`${error}\n`)
resolve({})
})
}
})
.catch((error) => {
process.stderr.write(`${error}\n`)
resolve({})
})
})
}
function updatePassport (uid, updates) {
const ref = `passport/${uid}/state`
return new Promise((resolve, reject) => {
admin.database().ref(ref).set(updates)
.then(() => resolve(true))
.catch((error) => {
process.stderr.write(`${error}\n`)
resolve(false)
})
})
}
module.exports = function (app) {
// route set up
// app.set('views', './public/views');
// app.set('view engine', 'pug');
app.get('/api/passport/:id', (req, res) => {
if (req.params.id && req.params.id !== '') {
const uid = req.params.id
getPassport(uid)
.then((passport) => res.status(200).send(passport))
.catch((error) => {
process.stderr.write(`${error}\n`)
res.status(500).send({})
})
} else {
res.status(400).send({})
}
})
app.post('/api/passport/:id', (req, res) => {
if (req.params.id && req.params.id !== '' && req.body) {
const uid = req.params.id
const updates = req.body
console.log(updates)
updatePassport(uid, updates)
.then((operationResult) => res.status(200).send(operationResult))
.catch((error) => {
process.stderr.write(`${error}\n`)
res.status(500)
})
} else {
res.status(400)
}
})
app.get('/api/config/passport', (req, res) => {
if (fs.existsSync(passportConfigFile)) {
const fileContents = fs.readFileSync(passportConfigFile)
try {
const jsonData = JSON.parse(fileContents)
res.status(200).send(jsonData)
} catch (error) {
process.stderr.write(`${error}\n`)
res.status(200).send({})
}
} else {
res.status(200).send({})
}
})
app.post('/api/config/passport', (req, res) => {
if (req.body) {
const { lock, data } = req.body
if (passportLock === '') {
passportLock = fs.mkdtempSync('lock')
if (data) {
fs.writeFileSync(passportConfigFile, JSON.stringify(data))
if (fs.existsSync(`./${passportLock}`)) {
// remove lock
fs.rmdirSync(`./${passportLock}`)
passportLock = ''
}
res.status(200).send(true)
} else {
res.status(400).send('Config being edited and locked by another user.')
}
}
}
})
}
|
import React from 'react';
import './style.css';
import {Link} from 'react-router-dom';
const NavBar = ()=>{
return(
<div className="navbars">
<Link to="" className="link">Home</Link>
<Link to="/post" className="nolinks">Post</Link>
<Link to="/signup" className="nolinks">Signup</Link>
<Link to="/login" className="nolinks">Login</Link>
</div>
)
}
export default NavBar
|
import * as Yup from 'yup';
import Student from '../models/Student';
class StudentController {
async store(req, res) {
const schema = Yup.object().shape({
name: Yup.string().required(),
email: Yup.string()
.email()
.required(),
age: Yup.string().required(),
weight: Yup.string().required(),
height: Yup.string().required(),
});
if (!(await schema.isValid(req.body))) {
return res.status(400).json({ error: 'Validation failed' });
}
const { email } = req.body;
const studentExists = await Student.findOne({ where: { email } });
if (studentExists) {
res.status(401).json({ error: 'E-mail already in use' });
}
const student = await Student.create(req.body);
return res.json(student);
}
}
export default new StudentController();
|
import Vue from 'vue'
// 时间格式化
const formatDate = (date, fmt) => {
const newDate = new Date(date)
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (newDate.getFullYear() + '').substr(4 - RegExp.$1.length))
}
const o = {
'M+': newDate.getMonth() + 1,
'd+': newDate.getDate(),
'h+': newDate.getHours(),
'm+': newDate.getMinutes(),
's+': newDate.getSeconds()
}
for (const k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
const str = o[k] + ''
fmt = fmt.replace(RegExp.$1, str)
}
}
return fmt
}
const capitalize = (value) => {
if (!value) { return '' }
value = value.toString()
return value === 'php' ? 'PHP' : value.charAt(0).toUpperCase() + value.slice(1)
}
const strSlice = (val, num) => {
if (!val) { return '' }
val = val.toString()
let textLength = 0
let newStr = ''
for (let i = 0; i < val.length; i++) {
if (val.charAt(i).match(/[\u0391-\uFFE5]/)) {
textLength += 2
} else {
textLength++
}
}
if (val.length < textLength) {
newStr = val.slice(0, num)
} else {
newStr = val.slice(0, num * 2)
}
return val.length > num ? newStr + '...' : newStr
}
const filters = {
formatDate,
capitalize,
strSlice
}
Object.keys(filters).forEach((key) => {
Vue.filter(key, filters[key])
})
export default filters
|
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
import {Helmet} from 'react-helmet';
import ZZ from '../assests/logo-mobile.jpg';
const useStyles = makeStyles({
table: {
minWidth: 650,
},
});
const basic = "$40/month";
const premium = "$72/month";
function createData(name, basic, premium) {
return { name, basic, premium };
}
const rows = [
createData('Vcita account', 'Included', 'Included'),
createData('Logo', 'Included', 'Included'),
createData('Website', 'Not included', 'Included'),
createData('Busniess Card', 'Included', 'Included'),
createData('Barcode', 'Included', 'Included'),
];
export default function PricesTable() {
return (
<>
<Helmet>
<meta charSet="utf-8"/>
<title>Prices</title>
<meta name="description" content="prices for patients account management"/>
</Helmet>
<TableContainer component={Paper} className="price-table-container">
<Table className="prices-table my-xs-5" aria-label="simple table">
<TableHead>
<TableRow>
<TableCell></TableCell>
<TableCell align="right">$40/month</TableCell>
<TableCell align="right">$72/month</TableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map((row) => (
<TableRow key={row.name}>
<TableCell component="th" scope="row">
{row.name}
</TableCell>
<TableCell align="right">{row.basic}</TableCell>
<TableCell align="right">{row.premium}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
<Grid container space={0} className="pt-2 contract-container">
<Grid item md={10} sx={10} xs={10} className="float-right">
<p className="contract-p">اختر الاشتراك المناسب لك واملآ المعلومات بالضغط على الزر ادناه</p>
</Grid>
<Grid item md={10} sx={10} xs={10} className="float-right contract-btn-col pt-md-4">
<a className="pdf-btn" href="https://www.redscheduling.com/contract.pdf">
PDF
</a>
</Grid>
</Grid>
</>
);
}
|
var Vermelho = 'N'
var Verde = 'N'
function setColor(btn) {
var buttom = document.getElementById(btn)
if (btn == "Verde" && Verde == 'N') {
buttom.style.backgroundColor = "green"
buttom.style.color = "white"
Verde = 'S'
} else
if (btn == "Verde" && Verde == 'S') {
buttom.style.backgroundColor = "whitesmoke"
buttom.style.color = "black"
Verde = 'N'
} else
if (btn == "Vermelho" && Vermelho == 'N') {
buttom.style.backgroundColor = "red"
buttom.style.color = "white"
Vermelho = 'S'
} else
if (btn == "Vermelho" && Vermelho == 'S') {
buttom.style.backgroundColor = "whitesmoke"
buttom.style.color = "black"
Vermelho = 'N'
}
}
|
/*
* 从url?id=0001取id
*/
function getParameter(){
var str=window.location.search;
var a_id=str.substring(4,8);
if(a_id){
alert(a_id);
}
}
/*
* 取指定参数
*/
function getParameters(name) {
alert("a");
console.log(name);
var param=window.location.search;
var len = param.length;
var start = query.indexOf(param);
if (start == -1) return "";
start += len + 1;
var end = query.indexOf("&", start);
if (end == -1) return query.substring(start);
return query.substring(start, end);
}
|
/**
* Created by JonIC on 2016-11-09.
*/
url = require('url');
exports.login = function(req, res){
//res.render('index', { title: 'express'});
console.log(req);
// if the man come this app newly then register that man.
// if the man is customer then return non friend, non match, non herself person list.
// then return non match and non friend person's photo list.
var facebookid='fb12345';
var email = req.body.email;
var age = req.body.age;
var name =req.body.name;
var gender =req.body.gender;
var locationx=req.body.locationx;
var locationy=req.body.locationy;
var othergender= req.body.othergender;
var minage = req.body.minage;
var maxage = req.body.maxage;
var minrate = req.body.minrate;
var maxrate = req.body.maxrate;
var distance= req.body.distance;
var showfullname = req.body.showfullname;
var searchbyname = req.body.searchbyname;
var first;
console.log(facebookid);
console.log(name);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var sql = "SELECT facebookid FROM users WHERE facebookid='" + facebookid +"'";//email='"+ email+"' AND age='"+ age +"' AND firstname='"+name+"'";
console.log(sql);
global.mysql.query(sql, function(err,rows){
console.log(rows);
if(err){
console.error(err);
throw err;
}
var first = 0;
if(rows.length == 0){
insert(facebookid, gender, locationx, locationy, email, age, name, showfullname, searchbyname);
first = 1;
sendphoto(facebookid,res, first, minage, maxage, minrate, maxrate,othergender);
}
if(rows.length > 0){
updatemyprofile(facebookid, gender, locationx, locationy, email, age, name,showfullname, searchbyname);
sendphoto(facebookid,res, first, minage, maxage, minrate, maxrate,othergender);
}
});
}
updatemyprofile = function(facebookid, gender, locationx, locationy, email, age, name, showfullname, searchbyname){
var updatequery= "UPDATE" +
" users" +
" SET" +
" showfullname = '"+showfullname+"'," +
" searchbyname = '"+searchbyname+"'," +
" locationx = '"+locationx+"'," +
" locationy = '"+locationy+"'" +
" WHERE facebookid = '"+facebookid+"' ";
global.mysql.query(updatequery, function(err, ruslt){
if(err){
console.log(err);
}
console.log("updated");
});
};
insert = function(facebookid, gender, locationx, locationy, email, age, name, showfullname, searchbyname){
var totalrate =0;
//var locationx = 0;
//var locationy = 0;
var profilephoto = "";
var query = "INSERT INTO users (" +
"facebookid, gender, locationx, locationy, " +
"totalrate, name, age, email," +
"profilephoto,lastname,showfullname, searchbyname" +
" VALUES ('"
+facebookid+"', '" + gender+"', '" +locationx+"', '" +locationy +"', '"
+ totalrate+"', '" +name+"', '" +age+ "', '" +email+"', '"
+ profilephoto + "', '', '" +showfullname+"', '" +searchbyname+"')" ;
global.mysql.query(query,function(err,rows){
if(err){
console.error(err);
throw err;
}
if(rows.length==0){
console.log("aaa") };
});
}
sendphoto = function(facebookid,res, first, minage, maxage, minrate, maxrate,othergender){
var query_match_1 = "SELECT facebookid2 FROM matching WHERE facebookid1='"+facebookid+"'";
var query_match_2 = "SELECT facebookid1 FROM matching WHERE facebookid2='"+facebookid+"'";
var query_friend_1 = "SELECT facebookid2 FROM friend WHERE facebookid1='"+facebookid+"'";
var query_friend_2 = "SELECT facebookid1 FROM friend WHERE facebookid2='"+facebookid+"'";
var match1="";
var match2="";
var friend1="";
var friend2="";
var queryComplete = 0;
global.mysql.query(query_match_1, function(err, rows){
if(err){
console.error(err);
queryComplete = queryComplete+1;
if(queryComplete == 4){
getNonFriendMatch(match1,match2,friend1,friend2,res,facebookid, first, minage, maxage, minrate, maxrate,othergender);
}
}
queryComplete = queryComplete+1;
if(rows.length>0){
for(var i=0; i<rows.length-1; i++){
match1 = match1 + "'" + rows[i].facebookid2 + "' , "
}
match1 = match1 + "'" + rows[rows.length-1].facebookid2 + "' "
}
if(queryComplete == 4){
getNonFriendMatch(match1,match2,friend1,friend2,res,facebookid, first, minage, maxage, minrate, maxrate,othergender);
}
});
global.mysql.query(query_match_2, function(err, rows1){
if(err){
console.error(err);
queryComplete = queryComplete+1;
if(queryComplete == 4){
getNonFriendMatch(match1,match2,friend1,friend2,res,facebookid, first, minage, maxage, minrate, maxrate,othergender);
}
}
queryComplete = queryComplete+1;
if(rows1.length>0){
for(var i=0; i<rows1.length-1; i++){
match2 = match2 + "'" + rows1[i].facebookid1 + "' , "
}
match2 = match2 + "'" + rows1[rows1.length-1].facebookid1 + "' "
}
if(queryComplete==4){
getNonFriendMatch(match1,match2,friend1,friend2,res,facebookid,first, minage, maxage, minrate, maxrate,othergender);
}
});
global.mysql.query(query_friend_1, function(err, rows2){
if(err){
console.error(err);
queryComplete = queryComplete+1;
if(queryComplete == 4){
getNonFriendMatch(match1,match2,friend1,friend2,res,facebookid, first, minage, maxage, minrate, maxrate,othergender);
}
}
queryComplete = queryComplete+1;
if(rows2.length>0){
for(var i=0; i<rows2.length-1; i++){
friend1 = friend1 + "'" + rows2[i].facebookid2 + "' , "
}
friend1 = friend1 + "'" + rows2[rows2.length-1].facebookid2 + "' "
}
if(queryComplete == 4){
getNonFriendMatch(match1,match2,friend1,friend2,res,facebookid,first, minage, maxage, minrate, maxrate,othergender);
}
});
global.mysql.query(query_friend_2, function(err, rows3){
if(err){
console.error(err);
queryComplete = queryComplete+1;
if(queryComplete == 4){
getNonFriendMatch(match1,match2,friend1,friend2,res,facebookid,first, minage, maxage, minrate, maxrate,othergender);
}
}
queryComplete = queryComplete+1;
if(rows3.length>0){
for(var i=0; i<rows3.length-1; i++){
friend2 = friend2 + "'" + rows3[i].facebookid1 + "' , "
}
friend2 = friend2 + "'" + rows3[rows3.length-1].facebookid1 + "' "
}
if(queryComplete == 4){
getNonFriendMatch(match1,match2,friend1,friend2,res,facebookid,first, minage, maxage, minrate, maxrate,othergender);
}
});
}
getNonFriendMatch = function(match1, match2, friend1, friend2,res,facebookid, first, minage, maxage, minrate, maxrate,othergender) {
var MatchAndFriend = match1;
var MatchAndFriend2 = match2;
var MatchAndFriend3 = friend1;
var MatchAndFriend4 = friend2;
var searchIn = "";
var finalMatchF="";
if(finalMatchF == "" && MatchAndFriend != ""){finalMatchF = MatchAndFriend;}
if(finalMatchF == "" && MatchAndFriend2 != ""){
finalMatchF = MatchAndFriend2;
}else if(finalMatchF !="" && MatchAndFriend2 != ""){
finalMatchF = finalMatchF + ", " + MatchAndFriend2;
};
if(finalMatchF == "" && MatchAndFriend3 != ""){
finalMatchF = MatchAndFriend3;
}else if(finalMatchF !="" && MatchAndFriend3 != ""){
finalMatchF = finalMatchF + ", " + MatchAndFriend3;
};
if(finalMatchF == "" && MatchAndFriend4 != ""){
finalMatchF = MatchAndFriend4;
}else if(finalMatchF !="" && MatchAndFriend4 != ""){
finalMatchF = finalMatchF + ", " + MatchAndFriend4;
};
if(finalMatchF == ""){
finalMatchF = facebookid;
}else{
finalMatchF = finalMatchF + ", '"+ facebookid + "'";
}
var query;
if(first == 0){
if(othergender == "male"){ // if male
query = "SELECT facebookid FROM users WHERE facebookid NOT IN(" + finalMatchF +")" +
"AND age >='" + minage+ "' "+
"AND age <='" + maxage+ "' "+
"AND gender='male'" ;
}else if(othergender == "female"){ // if female
query = "SELECT facebookid FROM users WHERE facebookid NOT IN(" + finalMatchF +")" +
"AND age >='" + minage+ "' "+
"AND age <='" + maxage+ "' "+
"AND gender='female'" ;
}else{ // if both
query = "SELECT facebookid FROM users WHERE facebookid NOT IN(" + finalMatchF +")" +
"AND age >='" + minage+ "' "+
"AND age <='" + maxage+ "'";
}
}else{
if(othergender == "male"){ // if male
query = "SELECT facebookid FROM users WHERE " +
" age >='" + minage+ "' "+
"AND age <='" + maxage+ "' "+
"AND gender='male'" ;
}else if(othergender == "female"){ // if female
query = "SELECT facebookid FROM users WHERE " +
" age >='" + minage+ "' "+
"AND age <='" + maxage+ "' "+
"AND gender='female'" ;
}else{ // if both
query = "SELECT facebookid FROM users WHERE" +
" age >='" + minage+ "' "+
"AND age <='" + maxage+ "'";
}
}
global.mysql.query(query, function(err, rows){
if(err){
console.error(err);
throw err;
}
if(rows.length > 0){
for(var i=0; i < rows.length-1; i++){
searchIn = searchIn + "'" + rows[i].facebookid + "', ";
}
searchIn = searchIn + "'" + rows[rows.length-1].facebookid + "'"
//SELECT
//facebookid
//FROM
//users
//WHERE facebookid NOT IN (1, 2)
//AND age >= 0
//AND age < 30
//AND rate >= 0
//AND rate <= 10
var query;
if(othergender == "male"){ // if male
query = "SELECT facebookid, photopath, name FROM photo WHERE facebookid IN ("+ searchIn +") AND rate >='" + minrate + "' AND rate <='" + maxrate +"' ORDER BY Id DESC";
}else if(othergender == "female"){ // if female
query = "SELECT facebookid, photopath , name FROM photo WHERE facebookid IN ("+ searchIn +") AND rate >='" + minrate + "' AND rate <='" + maxrate +"' ORDER BY Id DESC";
}else{ // if both
query = "SELECT facebookid, photopath, name FROM photo WHERE facebookid IN ("+ searchIn +") AND rate >='" + minrate + "' AND rate <='" + maxrate +"' ORDER BY Id DESC";
}
global.mysql.query(query, function(err, result){
if(err){
}
//res.status(200).send(result);
//res.status(200);
if(result != null){
var data = {};
data.retcode = 200;
data.error_msg = "";
data.content = result;
//res.json(data);
return res.send(200,data);
}else{
var data = {};
data.retcode = 300;
data.error_msg = "sorry there is no man";
//res.json(data);
return res.send(200,data);
}
});
}else{
var data = {};
data.retcode = 300;
data.error_msg = "sorry there is no man";
//res.json(data);
return res.send(200,data);
}
});
}
getPhoto = function(search ,res){
var query = "SELECT facebookid, photopath FROM photo WHERE facebookid IN ("+ search +")";
global.mysql.query(query, function(err, result){
if(err){
}
res.json(result);
res.send(200, "success")
});
}
|
//약관세션체크
function checkAgree(next_func){
if(jQuery("#accept_agreement").is(":checked") == false) {
alert('개인정보수집에 동의해 주세요.');
return false;
}
var popupWindow = window.open( "", "auth_popup", "left=200, top=100, status=0, width=450, height=550" );
return eval(next_func+"(popupWindow)");
}
// kcb인증창 띄우기
function jsSubmit(popupWindow){
var okname_frm = document.okname_frm;
if(!popupWindow){
window.open("", "auth_popup", "width=432,height=560,scrollbar=yes");
}
window.name = "";
document.auth_frm.target = "auth_popup";
document.auth_frm.action = "https://safe.ok-name.co.kr/CommonSvl";
document.auth_frm.method = "post";
document.auth_frm.submit();
}
|
const ufo = require('../dist/index')
console.log(ufo)
|
require("../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/personal_package/_query_components/answered_questions" ], {
"185e": function(e, n, o) {
o.r(n);
var a = o("f3e7"), t = o.n(a);
for (var c in a) [ "default" ].indexOf(c) < 0 && function(e) {
o.d(n, e, function() {
return a[e];
});
}(c);
n.default = t.a;
},
"399e": function(e, n, o) {
o.d(n, "b", function() {
return a;
}), o.d(n, "c", function() {
return t;
}), o.d(n, "a", function() {});
var a = function() {
var e = this;
e.$createElement;
e._self._c;
}, t = [];
},
d068: function(e, n, o) {
o.r(n);
var a = o("399e"), t = o("185e");
for (var c in t) [ "default" ].indexOf(c) < 0 && function(e) {
o.d(n, e, function() {
return t[e];
});
}(c);
o("f342");
var r = o("f0c5"), u = Object(r.a)(t.default, a.b, a.c, !1, null, "380c7bc0", null, !1, a.a, void 0);
n.default = u.exports;
},
d8cf: function(e, n, o) {},
f342: function(e, n, o) {
var a = o("d8cf");
o.n(a).a;
},
f3e7: function(e, n, o) {
Object.defineProperty(n, "__esModule", {
value: !0
}), n.default = void 0;
var a = {
props: {
item: Object
}
};
n.default = a;
}
} ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/personal_package/_query_components/answered_questions-create-component", {
"pages/personal_package/_query_components/answered_questions-create-component": function(e, n, o) {
o("543d").createComponent(o("d068"));
}
}, [ [ "pages/personal_package/_query_components/answered_questions-create-component" ] ] ]);
|
// jscs:disable jsDoc
module.exports = function () {
return function ttl (Model, instance, callback) {
this.client.ttl(this.createEphemeralKey(Model, instance.getPrimaryKey()), callback || function () {})
}
}
|
const CONST = require('../../../utils/const.js')
const HTTP = require('../../../utils/http.js')
const INTERACTION = require('../../../utils/interaction.js')
const GET_SCHOOL_RECORD = "/campus_deliver/deliver_list?channel=1&format=json"
function getSchoolRecord(suc, fail) {
var url = CONST.SERVER + GET_SCHOOL_RECORD
HTTP.getRequest(url, null, suc, fail)
}
module.exports.getSchoolRecord = getSchoolRecord
|
'use strict';
const
{
GULP_DEST_KEY,
GULP_WARN_KEY,
createIgnoreResult,
createPluginError,
createTransform,
filterResult,
hasOwn,
isErrorMessage,
makeNPMLink,
organizeOptions,
resolveFormatter,
resolveWriter,
writeResults,
} = require('#util');
const { promisify } = require('util');
function wrapAction(action)
{
if (typeof action !== 'function')
throw TypeError('Argument is not a function');
if (action.length > 1)
action = promisify(action);
return action;
}
const createResultStream =
action =>
{
action = wrapAction(action);
return createTransform
(
async ({ eslint: result }) =>
{
if (result)
await action(result);
},
);
};
const createResultsStream =
action =>
{
action = wrapAction(action);
const results = [];
results.errorCount = 0;
results.warningCount = 0;
results.fixableErrorCount = 0;
results.fixableWarningCount = 0;
results.fatalErrorCount = 0;
return createTransform
(
({ eslint: result }) =>
{
if (result)
{
results.push(result);
// Collect total error/warning count.
results.errorCount += result.errorCount;
results.warningCount += result.warningCount;
results.fixableErrorCount += result.fixableErrorCount;
results.fixableWarningCount += result.fixableWarningCount;
results.fatalErrorCount += result.fatalErrorCount;
}
},
async () =>
{
await action(results);
},
);
};
function getESLintInfo(file)
{
const eslintInfo = file._eslintInfo;
if (eslintInfo != null)
return eslintInfo;
throw createPluginError({ fileName: file.path, message: 'ESLint information not available' });
}
const warn =
(message, gulpWarn = require('fancy-log').warn) =>
gulpWarn(`\x1b[1;37m\x1b[40mgulp-eslint-new\x1b[0m \x1b[30m\x1b[43mWARN\x1b[0m\n${message}`);
function formatMigratedOptionWarningLine({ oldName, newName, formatChanged })
{
let line = ` • ${oldName} → ${newName}`;
if (formatChanged)
line += ' (format changed)';
return line;
}
async function lintFile(eslintInfo, file, quiet, warnIgnored)
{
if (file.isNull())
return;
if (file.isStream())
throw 'gulp-eslint-new doesn\'t support Vinyl files with Stream contents.';
const { eslint } = eslintInfo;
// The "path" property of a Vinyl file should be always an absolute path.
// See https://gulpjs.com/docs/en/api/vinyl/#instance-properties.
const filePath = file.path;
let result;
if (await eslint.isPathIgnored(filePath))
{
// Note: ESLint doesn't adjust file paths relative to an ancestory .eslintignore path.
// E.g., If ../.eslintignore has "foo/*.js", ESLint will ignore ./foo/*.js, instead of
// ../foo/*.js.
if (!warnIgnored)
return;
// Warn that gulp.src is needlessly reading files that ESLint ignores.
result = createIgnoreResult(filePath, eslintInfo.cwd, eslint.constructor);
}
else
{
[result] = await eslint.lintText(file.contents.toString(), { filePath });
// Note: Fixes are applied as part of `lintText`.
// Any applied fix messages have been removed from the result.
if (quiet)
{
// Ignore some messages.
const filter = typeof quiet === 'function' ? quiet : isErrorMessage;
result = filterResult(result, filter);
}
// Update the fixed output; otherwise, fixable messages are simply ignored.
if (hasOwn(result, 'output'))
{
file.contents = Buffer.from(result.output);
result.fixed = true;
}
}
file.eslint = result;
file._eslintInfo = eslintInfo;
}
module.exports = exports =
options =>
{
const { ESLint, eslintOptions, gulpWarn, migratedOptions, quiet, warnIgnored } =
organizeOptions(options);
{
const migratedOptionCount = migratedOptions.length;
if (migratedOptionCount)
{
const migratedOptionWarningText =
migratedOptions.map(formatMigratedOptionWarningLine).join('\n');
const messageIntro =
migratedOptionCount > 1 ?
'The following top-level options passed to gulpESLintNew() have been migrated' :
'The following top-level option passed to gulpESLintNew() has been migrated';
const message =
`${messageIntro}:\n${migratedOptionWarningText}\nSee ${makeNPMLink('legacy-options')
} for more information.`;
warn(message, gulpWarn);
}
}
const eslint = new ESLint(eslintOptions);
const { cwd, fix } = eslintOptions;
const eslintInfo = { cwd, eslint, fix };
return createTransform(file => lintFile(eslintInfo, file, quiet, warnIgnored));
};
exports.result = createResultStream;
exports.results = createResultsStream;
function failOnErrorAction(result)
{
const { messages } = result;
if (messages)
{
const error = messages.find(isErrorMessage);
if (error)
{
throw createPluginError
(
{
name: 'ESLintError',
fileName: result.filePath,
message: error.message,
lineNumber: error.line,
},
);
}
}
}
exports.failOnError = () => createResultStream(failOnErrorAction);
function failAfterErrorAction({ errorCount })
{
if (errorCount)
{
throw createPluginError
(
{
name: 'ESLintError',
message: `Failed with ${errorCount} ${errorCount === 1 ? 'error' : 'errors'}`,
},
);
}
}
exports.failAfterError = () => createResultsStream(failAfterErrorAction);
exports.formatEach =
(formatter, writer) =>
{
writer = resolveWriter(writer);
const eslintToFormatterMap = new Map();
return createTransform
(
async file =>
{
const result = file.eslint;
if (result)
{
const eslintInfo = getESLintInfo(file);
const { eslint } = eslintInfo;
let formatterObj = eslintToFormatterMap.get(eslint);
if (!formatterObj)
{
formatterObj = await resolveFormatter(eslintInfo, formatter);
eslintToFormatterMap.set(eslint, formatterObj);
}
await writeResults([result], formatterObj, writer);
}
},
);
};
const ERROR_MULTIPLE_ESLINT_INSTANCES =
{
name: 'ESLintError',
message: 'The files in the stream were not processed by the same instance of ESLint',
};
exports.format =
(formatter, writer) =>
{
writer = resolveWriter(writer);
const results = [];
let commonInfo;
return createTransform
(
file =>
{
const result = file.eslint;
if (result)
{
const eslintInfo = getESLintInfo(file);
if (commonInfo == null)
commonInfo = eslintInfo;
else
{
if (eslintInfo !== commonInfo)
throw createPluginError(ERROR_MULTIPLE_ESLINT_INSTANCES);
}
results.push(result);
}
},
async () =>
{
if (results.length)
{
const formatterObj = await resolveFormatter(commonInfo, formatter);
await writeResults(results, formatterObj, writer);
}
},
);
};
const getBase = ({ base }) => base;
exports.fix =
({ [GULP_DEST_KEY]: gulpDest = require('vinyl-fs').dest, [GULP_WARN_KEY]: gulpWarn } = { }) =>
{
const ternaryStream = require('ternary-stream');
let warned = false;
const isFixed =
file =>
{
const result = file.eslint;
if (result)
{
const eslintInfo = getESLintInfo(file);
if (eslintInfo.fix == null && !warned)
{
warned = true;
const message =
'gulpESLintNew.fix() received a file that was linted without the option "fix".\n' +
'This is usually caused by a misconfiguration in a gulp task.\n' +
`See ${makeNPMLink('autofix')} for information on how to fix files correctly.\n` +
'If you don\'t want to fix any files, set "fix: false" in the options passed to ' +
'gulpESLintNew() to remove this warning.';
warn(message, gulpWarn);
}
return result.fixed;
}
};
const stream = ternaryStream(isFixed, gulpDest(getBase));
return stream;
};
|
import React, { PureComponent } from 'react';
import {
Text,
View,
Image,
TouchableHighlight,
} from 'react-native';
import screen from '../../common/screen'
import ComicStoreBookComponent from './ComicStoreBookComponent'
export default class ComicStoreFreeComponent extends PureComponent{
render(){
let { cardItem } = this.props;
return(
<View style = {{flexDirection:'column'}}>
<View style = {{flexDirection:'row',justifyContent:'center',paddingLeft:16,paddingRight:16,marginTop:12}}>
<ComicStoreBookComponent
style={{width:screen.width-32, alignSelf:'stretch'}}
bookItem = {cardItem.bookList[0]}
totalWidth = {screen.width-32}
imageWidth = {screen.width-32}
/>
</View>
<View style = {{flexDirection:'row',justifyContent:'space-between',paddingLeft:16,paddingRight:16,marginTop:12}}>
<ComicStoreBookComponent
style={{width:93,alignSelf:'flex-start'}}
bookItem = {cardItem.bookList[1]}
totalWidth = {93}
/>
<ComicStoreBookComponent
style={{width:93,alignSelf:'center'}}
bookItem = {cardItem.bookList[2]}
totalWidth = {93}
/>
<ComicStoreBookComponent
style={{width:93,alignSelf:'flex-end'}}
bookItem = {cardItem.bookList[3]}
totalWidth = {93}
/>
</View>
<View style={{flex:1,height:0.5,backgroundColor:'#f2f2f2',marginTop:12}}/>
<TouchableHighlight
style={{backgroundColor:'#ffffff'}}
underlayColor={'#f2f2f2'}
onPress={this.onMoreClick}>
<View style={{flex:1,flexDirection:'row',alignItems:'center',justifyContent:'center',height:50}}>
<Text>
更多戳这里
</Text>
<Image style={{height:12,width:9}}
source={require('../../images/icon_star_click_more.png')}/>
</View>
</TouchableHighlight>
</View>
);
}
onMoreClick(){
console.log("click more")
}
}
|
import { connect } from "react-redux";
import ScoretablePageView from "./ScoretablePageView";
import fetchScoretable from "../../actions/scoretable/fetchScoretable";
const mapStateToProps = (state, ownProps) => {
return {
loading: state.scoretable.loading,
scoretable: state.scoretable.results
};
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
fetchScoretable: () => {
dispatch(fetchScoretable());
}
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(ScoretablePageView);
|
var app = new Vue({
el: "#app",
data: {
decimal:"",
},
computed:{
binary:{
get: function(){
if (this.decimal !== "") return (this.decimal >>> 0).toString(2);
return "";
},
set: function(newValue){
if(newValue !== ""){
this.decimal = parseInt(newValue,2);
} else {
this.decimal="";
}
}
},
hexadecimal:{
get: function(){
if (this.decimal !== "") return (this.decimal >>> 0).toString(16);
return "";
},
set: function(newValue){
if(newValue !== ""){
this.decimal = parseInt(newValue,16);
} else {
this.decimal="";
}
}
},
}
});
|
console.log('running QUnit from Node');
var qunit = require('./js/lib/qunit').QUnit;
//todo this seems to work but doesn't report anything
qunit.test("a Sample Module", function() {
qunit.ok(true, "this test is fine");
});
qunit.init();
|
import actionTypes from './homeActionTypes';
export function loadTmdbConfig() {
return async (dispatch) => {
let tmdbPosterSizes = [];
let tmdbBackdropSizes = [];
let tmdbSecureBaseUrl = '';
try {
const response = await fetch('/image/config');
const responseData = await response.json();
tmdbPosterSizes = responseData.posterSizes;
tmdbBackdropSizes = responseData.backdropSizes;
tmdbSecureBaseUrl = responseData.secureBaseUrl;
console.log('tmdbPosterSizes: ', tmdbPosterSizes);
console.log('tmdbSecureBaseUrl: ', tmdbSecureBaseUrl);
} catch (err) {
console.log(err);
}
return dispatch({
type: actionTypes.LOAD_TMDB_CONFIG,
tmdbPosterSizes,
tmdbBackdropSizes,
tmdbSecureBaseUrl,
});
};
}
export function selectFilter(filterSelected, movies) {
const filters = {
popularity: 'vote_count',
rating: 'vote_average',
releaseDate: 'release_date',
};
movies.sort((a, b) => {
let movieA = a[filters[filterSelected]];
let movieB = b[filters[filterSelected]];
if (filterSelected === 'releaseDate') {
movieA = new Date(movieA);
movieB = new Date(movieB);
}
return movieB - movieA;
});
console.log('filterSelected: ', filterSelected);
return {
type: actionTypes.SELECT_FILTER,
filterSelected,
movies,
};
}
export function loadMovies() {
return async (dispatch) => {
let movies = [];
try {
const response = await fetch('/movie');
const responseData = await response.json();
movies = responseData.movies.sort((a, b) => b.vote_count - a.vote_count);
console.log('movies: ', movies);
} catch (err) {
console.log(err);
}
return dispatch({
type: actionTypes.LOAD_MOVIES,
movies,
});
};
}
export function listMovies(movieSearchMatches) {
return {
type: actionTypes.LIST_MOVIES,
movieSearchMatches,
};
}
export function resetMatches() {
return {
type: actionTypes.LIST_MOVIES,
movieSearchMatches: [],
};
}
|
/*
The Stanton measure of an array is computed as follows: count the number of 1s in the array.
Let this count be n.
The Stanton measure is the number of times that n appears in the array.
Write a function which takes an integer array and returns its Stanton measure.
Example:
The Stanton measure of [1, 4, 3, 2, 1, 2, 3, 2] is 3, because 1 occurs 2 times in the array and 2 occurs 3 times.
*/
// O(n + n);
function stantonMeasure(arr) {
let n = 0;
for (let i = 0; i < arr.length; i++) {
let num = arr[i];
if (num === 1) {
n += 1;
}
}
let measure = 0;
for (let j = 0; j < arr.length; j++) {
let num = arr[j];
if (num === n) {
measure += 1;
}
}
return measure;
}
// O(n);
function stantonMeasure(arr) {
let freq = {};
for (let i = 0; i < arr.length; i++) {
let num = arr[i];
freq[num] = freq[num] + 1 || 1;
}
let n = freq["1"];
let amountOfTimesNAppears = freq[n];
return amountOfTimesNAppears || 0;
}
|
export const toInteger = num => {
num *= 1
if (num != num) return 0
if (num == 0 || !isFinite(num)) return num
return Math.floor(Math.abs(num))
}
export const toLength = val => {
let len = toInteger(val)
return len <= 0
? 0
: Math.min(len, Number.MAX_SAFE_INTEGER)
}
export const getMethod = (obj, key) => {
let fn = obj[key]
if (fn == null) return
if (typeof fn == "function") return fn
throw new TypeError
}
|
//action的type即使组件内和reducer内不相同页不会报错,抽取出来重新赋值可以避免这种错误并且促会错会报错容易修改
export const CHANG_ITEM = 'change_item'
export const ADD_ITEM = "add_item"
export const DEL_ITEM = "del_item"
export const DATA_LOAD = "data-load"
|
//Library
const express = require('express');
const router = express.Router();
//Builders
const RequestBuilder = require('../builders/RequestBuilder');
//Routes
router.use('/login', require('./login'));
router.use('/articles', require('./articles'));
router.use('/accounts', require('./accounts'));
// router.use('/dockets', require('./dockets'));
router.get('/', function (req, res, next) {
const request = new RequestBuilder({ baseUrl: 'https://google.com' })
.baseSuffix(['apple/done', 'banana'])
.additionalParams({
color: 'purple',
})
.build();
console.log(request);
res.send('index');
});
module.exports = router;
|
import React from "react";
import {Button, Card, message} from "antd";
const success = () => {
const hide = message.loading('Action in progress..', 0);
// Dismiss manually and asynchronously
setTimeout(hide, 2500);
};
const Loading = () => {
return (
<Card title="Loading" className="gx-card">
<Button onClick={success}>Display a loading indicator</Button>
</Card>
);
};
export default Loading;
|
import React, { Component, Suspense } from "react"
import $ from "jquery"
import { Control, LocalForm, Errors } from 'react-redux-form';
import { Row, Label, Col, Container, Breadcrumb, BreadcrumbItem, Button, InputGroupText, InputGroupAddon, InputGroup} from 'reactstrap';
import { Link, BrowserRouter as Router, Route, Switch, Redirect } from "react-router-dom"
import Navbar from './../NavBar.js'
import AllQuestion from "./AllQuestion"
import VotedAns from "./VotedAns"
import UnAnswered from "./UnAnswered"
import Routes from "../../Routes"
import Axios from "axios"
const required = (val) => val && val.length;
const validUrl = (val) => /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/i.test(val);
class Question extends Component {
constructor(props) {
super(props)
this.state = {
question: "",
category: "JEE",
selectedFile: null,
tags: [],
question: []
}
}
componentDidMount() {
$(".custom-file-input").on("change", function () {
var fileName = $(this).val().split("\\").pop();
$(this).siblings(".custom-file-label").addClass("selected").html(fileName);
});
}
onChangeHandler = (e) => {
this.setState({
[e.target.name]: e.target.value,
})
}
onFileChangeHandler = (e) => {
this.setState({
selectedFile: e.target.files[0]
})
}
AddTag = (e) => {
e.preventDefault();
let val = document.getElementById("tag").value;
if (val != "") {
let modTag = this.state.tags;
modTag.push(val);
this.setState({
tags: modTag
})
console.log(modTag)
document.getElementById("tag").value = "";
}
}
handleSubmit = (values) => {
console.log(values)
console.log("SelectedFile is ");
console.log(this.state.selectedFile)
const formData = new FormData();
formData.append("question", values.question);
formData.append("file", this.state.selectedFile);
formData.append("category", values.category);
formData.append("tags", this.state.tags);
console.log(formData);
Axios.post("http://localhost:5005/quora/question/5f3a6c1ec944801a08a6b2f1", formData).then(result => {
console.log(result)
window.location.reload()
}).catch(error => {
console.log("axios error")
console.log(error)
})
debugger;
}
render() {
return (
<>
<Navbar />
<div className="my-4">
<div className="container-lg">
<div className="row">
<div className="col-md-8">
<div>
<div className="d-flex justify-content-between mb-3 d-md-none">
<button type="button" className="btn btn-info " data-toggle="modal" data-target="#questionModal">Ask Question</button>
<div class="">
<select class="custom-select" id="inputGroupSelect01">
<option selected>Categories...</option>
<option value="1">JEE</option>
<option value="2">NEET</option>
<option value="3">Others</option>
</select>
</div>
</div>
<nav>
<div className="nav-tabs-question d-flex justify-content-between">
<div className="nav nav-tabs " id="nav-tab" role="tablist">
<Link to="/qna" className={"nav-item text-dark py-1 border-0 nav-link " + (window.location.pathname === '/qna' ? 'active' : '')} id="nav-home-tab">All</Link>
<Link to="/qna/votes" className={"nav-item text-dark py-1 border-0 nav-link " + (window.location.pathname === '/qna/votes' ? 'active' : '')} id="nav-profile-tab" >Votes</Link>
<Link to="/qna/unanswered" className={"nav-item text-dark py-1 border-0 nav-link " + (window.location.pathname === '/qna/unanswered' ? 'active' : '')} id="nav-contact-tab">UnAnswered</Link>
</div>
<div class="d-none d-md-block">
<select class="custom-select border-0 rounded-0 bg-warning text-white" id="inputGroupSelect01">
<option selected>Categories...</option>
<option value="1">JEE</option>
<option value="2">NEET</option>
<option value="3">Others</option>
</select>
</div>
</div>
<div class="tab-content" id="nav-tabContent">
<Suspense>
<Switch>
{Routes.map((route, index) => {
return route.component ? (
<Route
key={index}
path={route.path}
exact={route.exact}
name={route.name}
render={props => <route.component {...props} />}
/>
) : (null);
})}
<Redirect from="/" to="/index" />
</Switch>
</Suspense>
</div>
</nav>
</div>
</div>
<div className="col-md-4">
<div>
<div>
<button type="button" className="btn btn-info d-none d-md-block w-100" data-toggle="modal" data-target="#questionModal">ASK QUESTION</button>
</div>
<div className="card my-2">
<div className="card-body pb-0">
<h5 className="card-title text-warning pb-2 border-bottom">Stats</h5>
<div className="alert alert-dark py-2 px-3" role="alert">
<h6 className="mb-0">Question (25)</h6>
</div>
<div className="alert alert-dark py-2 px-3" role="alert">
<h6 className="mb-0">Answers (40)</h6>
</div>
<div className="alert alert-dark py-2 px-3" role="alert">
<h6 className="mb-0">Best Answers (5)</h6>
</div>
<div className="alert alert-dark py-2 px-3" role="alert">
<h6 className="mb-0">Tags (5)</h6>
</div>
</div>
</div>
<div className="card my-2">
<div className="card-body pb-2">
<h5 className="card-title text-warning pb-2 border-bottom">Hot Questions</h5>
<div>
<h6 className="small font-weight-bold mb-3">
<a href="#" className="text-decoration-none">How much do web developers earn? What is their salary?</a>
</h6>
<h6 className="small font-weight-bold mb-3">
<a href="#" className="text-decoration-none">Does Google force employees who have offers from Facebook to leave immediately?</a>
</h6>
<h6 className="small font-weight-bold mb-3">
<a href="#" className="text-decoration-none">How to evaluate whether a career coach is beneficial?</a>
</h6>
<h6 className="small font-weight-bold mb-3">
<a href="#" className="text-decoration-none">Why are the British confused about us calling bread rolls “biscuits” when they call bread rolls “puddings”?</a>
</h6>
<h6 className="small font-weight-bold mb-3">
<a href="#" className="text-decoration-none">How do I tell my new employer that I can’t use the computer they gave me?</a>
</h6>
<h6 className="small font-weight-bold mb-3">
<a href="#" className="text-decoration-none">How to evaluate whether a career coach is beneficial?</a>
</h6>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="questionModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header py-2">
<h6 class="modal-title" id="exampleModalLabel">Ask A Question</h6>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<LocalForm onSubmit={(values) => this.handleSubmit(values)}>
<Row className="form-group">
<Col md={12}>
<Control.textarea model=".question"
id="question"
name="question"
rows="3"
placeholder="Ask a Question..."
className="form-control"
validators={{
required
}}
/>
<Errors
className="text-danger"
show="touched"
model=".question"
messages={{
required: 'This is a Required Field!'
}}
/>
</Col>
</Row>
<Row className="form-group">
<Col md={12}>
<Control.file model=".file"
id="file"
name="file"
className="form-controls"
onChange={this.onFileChangeHandler}
/>
</Col>
</Row>
<Row className="form-group">
<Col md={12}>
<Control.select
model=".category"
id="category"
name="category"
className="custom-select"
>
<option value="-1">Categories..</option>
<option value="JEE">JEE</option>
<option value="NEET">NEET</option>
<option value="Others">Others</option>
</Control.select>
</Col>
</Row>
{this.state.tags.length>0? //ternary
<div className="card mb-3">
<div className="card-body text-center p-2">
{this.state.tags.map((tag, index)=>{
return(
<a href="#" class="badge badge-warning mr-2">{tag.toUpperCase()}</a>
)
})}
</div>
</div>:""
}
<Row>
<Col >
<InputGroup className="mb-3">
<Control.text model=".tag"
id="tag"
name="tag"
placeholder="Add Tags"
className="form-control col-md-12"
/>
<InputGroupAddon addonType="append"><Button onClick={this.AddTag}>Add</Button></InputGroupAddon>
</InputGroup>
</Col>
</Row>
<Row className="form-group">
<Col md={{ size: 12 }}>
<Button type="submit" block color="info">
Submit
</Button>
</Col>
</Row>
</LocalForm>
{/* <form onSubmit={(values) => this.handleSubmit(values)}>
<div class="form-group">
<textarea class="form-control" id="question" name="question" rows="3" placeholder="Ask Your Question" onChange={this.onChangeHandler} required></textarea>
</div>
<div class="custom-file mb-3">
<input type="file" class="custom-file-input" id="file" name="file" onChange={this.onFileChangeHandler}/>
<label class="custom-file-label" for="file">Choose file</label>
</div>
<div class="form-group">
<select class="custom-select" id="inputGroupSelect01" name="category" onChange={this.onChangeHandler} required>
<option value="JEE">JEE</option>
<option value="NEET">NEET</option>
<option value="Others">Others</option>
</select>
</div>
{this.state.tags.length>0? //ternary
<div className="card mb-3">
<div className="card-body text-center p-2">
{this.state.tags.map((tag, index)=>{
return(
<a href="#" class="badge badge-warning mr-2">{tag.toUpperCase()}</a>
)
})}
</div>
</div>:""
}
<div class="input-group mb-3">
<input type="text" class="form-control" id="tag" placeholder="Add Tags" />
<div class="input-group-append">
<button class="btn btn-info" onClick={this.AddTag} type="button">ADD</button>
</div>
</div>
<div className="my-3 text-center">
<button type="submit" class="btn btn-primary w-100">Submit Question</button>
</div>
</form> */}
</div>
</div>
</div>
</div>
</div>
</>
)
}
}
export default Question;
|
import { expect, assert } from 'chai';
import request from 'supertest';
const alphaSortFunction = (a, b) => {
if(a.email < b.email) return -1;
if(a.email > b.email) return 1;
return 0;
};
describe('UserController', function() {
const userPath = '/user';
let myRequest;
before(function(){
global.fixtures['user'].sort(alphaSortFunction);
});
describe(`GET ${userPath}`, function(){
beforeEach(function(){
myRequest = request(sails.hooks.http.app)
.get(userPath)
.set('Accept', 'application/json')
});
it('returns the same amount of users as in the fixtures', function(done){
myRequest.end(function(err, res) {
if (err) return done(err);
expect(res.body).to.have.lengthOf(global.fixtures['user'].length);
done();
});
});
it('firstnames match the fixtures', function(done){
myRequest.end(function(err, res) {
if (err) return done(err);
res.body.sort(alphaSortFunction);
for(var i = 0; i < global.fixtures['user'].length;i++){
expect(res.body[i].firstname).to.equal(global.fixtures['user'][i].firstname);
}
done();
});
});
it('surnames match the fixtures', function(done){
myRequest.end(function(err, res) {
if (err) return done(err);
res.body.sort(alphaSortFunction);
for(var i = 0; i < global.fixtures['user'].length;i++){
expect(res.body[i].surname).to.equal(global.fixtures['user'][i].surname);
}
done();
});
});
it('emails match the fixtures', function(done){
myRequest.end(function(err, res) {
if (err) return done(err);
res.body.sort(alphaSortFunction);
for(var i = 0; i < global.fixtures['user'].length;i++){
expect(res.body[i].email).to.equal(global.fixtures['user'][i].email);
}
done();
});
});
});
describe(`POST ${userPath}`, function() {
it('should create user', function (done) {
let firstname = 'Fred';
let surname = 'Bass';
let email = 'foo@example.com';
let password = 'mydemopassword';
let terms = 'on';
request(sails.hooks.http.app)
.post(userPath)
.set('Accept', 'application/json')
.send({ firstname: firstname, surname: surname, email: email, password: password, terms: terms })
.expect('Content-Type', /json/)
.expect(201)
.end(function(err, res) {
if (err) return done(err);
assert.equal(res.body.firstname, firstname);
assert.equal(res.body.surname, surname);
assert.equal(res.body.email, email);
done();
});
});
});
});
|
export const routes = {
gifSearch: "/",
recipesSearch: "/recipesSearch"
};
|
export const AN_OBJECT = {
something: 'something',
};
export const A_STRING = '';
|
// # Quintus platformer example
//
// [Run the example](../quintus/examples/platformer/index.html)
// WARNING: this game must be run from a non-file:// url
// as it loads a level json file.
//
// This is the example from the website homepage, it consists
// a simple, non-animated platformer with some enemies and a
// target for the player.
var score = 0;
window.addEventListener("load",function() {
// Set up an instance of the Quintus engine and include
// the Sprites, Scenes, Input and 2D module. The 2D module
// includes the `TileLayer` class as well as the `2d` componet.
var Q = window.Q = Quintus()
.include("Sprites, Scenes, Input, 2D, Anim, Touch, UI")
// Maximize this game to whatever the size of the browser is
.setup({ maximize: true })
// And turn on default input controls and touch input (for UI)
.controls().touch()
// ## Player Sprite
// The very basic player sprite, this is just a normal sprite
// using the player sprite sheet with default controls added to it.
Q.Sprite.extend("Player",{
// the init constructor is called on creation
init: function(p) {
// You can call the parent's constructor with this._super(..)
this._super(p, {
sheet: "player", // Setting a sprite sheet sets sprite width and height
x: 1100, // You can also set additional properties that can
y: 300 // be overridden on object creation
});
// Add in pre-made components to get up and running quickly
// The `2d` component adds in default 2d collision detection
// and kinetics (velocity, gravity)
// The `platformerControls` makes the player controllable by the
// default input actions (left, right to move, up or action to jump)
// It also checks to make sure the player is on a horizontal surface before
// letting them jump.
this.add('2d, platformerControls');
// Write event handlers to respond hook into behaviors.
// hit.sprite is called everytime the player collides with a sprite
this.on("hit.sprite",function(collision) {
// Check the collision, if it's the Tower, you win!
if(collision.obj.isA("Tower")) {
Q.stageScene("endGame",1, { label: "You Won!" });
this.destroy();
}
});
}
});
// ## Tower Sprite
// Sprites can be simple, the Tower sprite just sets a custom sprite sheet
Q.Sprite.extend("Tower", {
init: function(p) {
this._super(p, { sheet: 'tower' });
}
});
// ## Enemy Sprite
// Create the Enemy class to add in some baddies
Q.Sprite.extend("Enemy",{
init: function(p) {
this._super(p, { sheet: 'enemy', vx: 100 });
// Enemies use the Bounce AI to change direction
// whenver they run into something.
this.add('2d, aiBounce');
// Listen for a sprite collision, if it's the player,
// end the game unless the enemy is hit on top
this.on("bump.left,bump.right,bump.bottom",function(collision) {
if(collision.obj.isA("Player")) {
Q.stageScene("endGame",1, { label: "You Died" });
collision.obj.destroy();
}
});
// If the enemy gets hit on the top, destroy it
// and give the user a "hop"
this.on("bump.top",function(collision) {
if(collision.obj.isA("Player")) {
this.destroy();
collision.obj.p.vy = -300;
score =+ 100;
console.log(score);
}
});
}
});
// ## Level1 scene
// Create a new scene called level 1
Q.scene("level1",function(stage) {
// Add in a repeater for a little parallax action
stage.insert(new Q.Repeater({ asset: "background-wall.jpg", speedX: 0.5, speedY: 0.5 }));
// Add in a tile layer, and make it the collision layer
stage.collisionLayer(new Q.TileLayer({
dataAsset: 'level.json',
sheet: 'tiles' }));
// Create the player and add them to the stage
var player = stage.insert(new Q.Player());
// Give the stage a moveable viewport and tell it
// to follow the player.
stage.add("viewport").follow(player);
// Add in a couple of enemies
stage.insert(new Q.Enemy({ x: 700, y: 0 }));
stage.insert(new Q.Enemy({ x: 700, y: 200 }));
stage.insert(new Q.Enemy({ x: 750, y: 800 }));
stage.insert(new Q.Enemy({ x: 410, y: 300 }));
stage.insert(new Q.Enemy({ x: 600, y: 300 }));
// Finally add in the tower goal
stage.insert(new Q.Tower({ x: 180, y: 50 }));
});
// To display a game over / game won popup box,
// create a endGame scene that takes in a `label` option
// to control the displayed message.
Q.scene('endGame',function(stage) {
var container = stage.insert(new Q.UI.Container({
x: Q.width/2, y: Q.height/2, fill: "rgba(0,0,0,0.5)"
}));
var button = container.insert(new Q.UI.Button({ x: 0, y: 0, fill: "#CCCCCC",
label: "Play Again" }))
var label = container.insert(new Q.UI.Text({x:10, y: -10 - button.p.h,
label: stage.options.label }));
// When the button is clicked, clear all the stages
// and restart the game.
button.on("click",function() {
Q.clearStages();
Q.stageScene('level1');
});
// Expand the container to visibily fit it's contents
// (with a padding of 20 pixels)
container.fit(20);
});
// ## Asset Loading and Game Launch
// Q.load can be called at any time to load additional assets
// assets that are already loaded will be skipped
// The callback will be triggered when everything is loaded
Q.load("sprites.png, sprites.json, level.json, tiles.png, background-wall.jpg", function() {
// Sprites sheets can be created manually
Q.sheet("tiles","tiles.png", { tilew: 32, tileh: 32 });
// Or from a .json asset that defines sprite locations
Q.compileSheets("sprites.png","sprites.json");
// Finally, call stageScene to run the game
Q.stageScene("level1");
});
// ## Possible Experimentations:
//
// The are lots of things to try out here.
//
// 1. Modify level.json to change the level around and add in some more enemies.
// 2. Add in a second level by creating a level2.json and a level2 scene that gets
// loaded after level 1 is complete.
// 3. Add in a title screen
// 4. Add in a hud and points for jumping on enemies.
// 5. Add in a `Repeater` behind the TileLayer to create a paralax scrolling effect.
});
|
import React from "react";
import Card from "@material-ui/core/Card";
import Button from "@material-ui/core/Button";
import axios from "axios";
import Snackbar from "@material-ui/core/Snackbar";
import MuiAlert from "@material-ui/lab/Alert";
import TextField from "@material-ui/core/TextField";
import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogContentText from "@material-ui/core/DialogContentText";
import DialogTitle from "@material-ui/core/DialogTitle";
//import { makeStyles } from '@material-ui/core/styles';
//SMSKEYS
const SEND_SMS_API_KEY =
"ZIoUQdVzuQdrovlrHOktWaJC38xDwwaZzMB0KUJIOyUwNdZ4Gtrza6pBWV3g";
//EMAILKEYS
const sendMail = require("@sendgrid/mail");
const SEND_EMAIL_API_KEY =
"MY_KEY";
sendMail.setApiKey(SEND_EMAIL_API_KEY);
function Alert(props) {
return <MuiAlert elevation={6} variant="filled" {...props} />;
}
// const useStyles = makeStyles((theme) => ({
// root: {
// width: '100%',
// '& > * + *': {
// marginTop: theme.spacing(2),
// },
// },
// }));
var note, note_for_sms, mobile_for_sms;
export default function Notes(props) {
//const classes = useStyles();
const [open, setOpen] = React.useState(false);
const handleClose = () => {
setOpen(false);
};
const [open1, setOpen1] = React.useState(false);
const handleClose1 = () => {
setOpen1(false);
};
const [open2, setOpen2] = React.useState(false);
const [open3, setOpen3] = React.useState({
mobile: "",
});
const [openemailsuccess, setOpenEmailsuccess] = React.useState(false);
const handleCloseEmailSuccess = () => {
setOpenEmailsuccess(false);
};
const [openemailfailure, setOpenEmailFailure] = React.useState(false);
const handleCloseEmailFailure = () => {
setOpenEmailFailure(false);
};
const handleClickOpen = (note) => {
// var note_for_sms;
localStorage.setItem("note_for_sms", note);
console.log(localStorage.getItem("note_for_sms"));
if (localStorage.getItem("mobile_for_sms")) {
setOpen2(false);
Sendsms(localStorage.getItem("mobile_for_sms"));
} else {
setOpen2(true);
}
//setOpen2(true);
};
const handleClose2 = () => {
setOpen2(false);
};
const handlesendsms = (mobileno) => {
// var mobile_for_sms;
setOpen2(false);
localStorage.setItem("mobile_for_sms", mobileno);
//console.log(mobileno);
Sendsms(mobileno);
//Sendsms(open3.mobile);
};
function Sendsms(mobileno) {
//let smsdata = ;
console.log(localStorage.getItem("note_for_sms"));
//note=localStorage.getItem(note_for_sms);
axios
.get(
"https://www.fast2sms.com/dev/bulkV2?authorization=" +
SEND_SMS_API_KEY +
"&route=v3&sender_id=TXTIND&message=" +
localStorage.getItem("note_for_sms") +
"&language=english&flash=0&numbers=" +
mobileno +
""
)
.then((response) => {
// console.log(response.status);
if (response.status == 200) {
setOpen(true);
}
})
.catch((error) => {
setOpen1(true);
});
}
function Sendemail(note_for_email) {
//var nameofclient = localStorage.getItem('note_for_sms');
const message = {
to: "senkottuvelanscientist@gmail.com",
from: { name: "Notey!", email: "notes@learnwithtamil.com" },
subject: "Hello there!",
html: "<h3>The note you have requested is...</h3><br><h1>"+note_for_email+"<h1>",
};
sendMail
.send(message)
.then((response) => setOpenEmailsuccess(true))
.catch((error) => setOpenEmailFailure(true));
}
const { notes } = props;
if (!notes || notes.length === 0) {
return <p className="mt-5">You haven't created any notes.</p>;
} else {
return (
<>
<h4 className="container">Your Notes</h4>
<div className="container mt-4">
<div className="card-columns">
{notes.map((note) => {
return (
<Card id={note.card_id} key={note.id} className="card p-3">
<h6 className="m-0">{note.note}</h6>
<Button
variant="contained"
color="secondary"
className="d-flex ml-auto mt-3 text-capitalize font-weight-bold"
onClick={() => handleClickOpen(note.note)}
>
Send SMS
</Button>
<Button
variant="contained"
color="secondary"
className="d-flex ml-auto mt-3 text-capitalize font-weight-bold"
onClick={() => Sendemail(note.note)}
>
Send Email
</Button>
</Card>
);
})}
</div>
</div>
<Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
<Alert onClose={handleClose} severity="success">
SMS sent successfully!
</Alert>
</Snackbar>
<Snackbar open={open1} autoHideDuration={6000} onClose={handleClose1}>
<Alert onClose={handleClose1} severity="error">
SMS Failed!
</Alert>
</Snackbar>
<Snackbar open={openemailsuccess} autoHideDuration={6000} onClose={handleCloseEmailSuccess}>
<Alert onClose={handleCloseEmailSuccess} severity="success">
Email sent successfully!
</Alert>
</Snackbar>
<Snackbar open={openemailfailure} autoHideDuration={6000} onClose={handleCloseEmailFailure}>
<Alert onClose={handleCloseEmailFailure} severity="error">
Email Failed!
</Alert>
</Snackbar>
<Dialog
open={open2}
onClose={handleClose2}
aria-labelledby="form-dialog-title"
>
<DialogTitle id="form-dialog-title">
Kindly Enter your Mobile No
</DialogTitle>
<DialogContent>
<DialogContentText>
Please don't abuse this service!
</DialogContentText>
<TextField
autoFocus
margin="dense"
id="name"
label="Mobile No"
type="string"
value={open3.mobile}
onChange={(event) => {
const { value } = event.target;
setOpen3({ mobile: value });
}}
defaultValue={localStorage.getItem("mobile_for_sms")}
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose2} color="primary">
Cancel
</Button>
<Button onClick={() => handlesendsms(open3.mobile)} color="primary">
Send
</Button>
</DialogActions>
</Dialog>
</>
);
}
}
|
/* eslint-disable react-native/no-inline-styles */
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow
*/
import React from 'react';
import {View} from 'react-native';
import {Container, Content, Text} from 'native-base';
import RNColorPalette from './react-native-color-picker-lib';
import colorList from './colors';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
pickedColor1: 'orange',
pickedColor2: 'green',
colors: colorList,
};
}
colorPicked = color => {
this.setState({
pickedColor1: color,
});
};
colorPicked2 = color => {
this.setState({
pickedColor2: color,
});
};
AddColor = color => {
this.setState({
colors: [...this.state.colors, color],
});
};
render() {
const {pickedColor1, pickedColor2, colors} = this.state;
return (
<Container>
<Content>
<View style={styles.textContainer}>
<Text style={styles.textStyle}>Color Palette</Text>
</View>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
}}>
<RNColorPalette
colorList={colors}
value={pickedColor2}
onItemSelect={this.colorPicked2}
AddPickedColor={colour => this.AddColor(colour)}
style={{
backgroundColor: pickedColor2,
width: 110,
height: 30,
}}>
<View>
<Text>Default Palette</Text>
</View>
</RNColorPalette>
<RNColorPalette
colorList={colors}
value={pickedColor1}
onItemSelect={this.colorPicked}
AddPickedColor={colour => this.AddColor(colour)}
style={{
backgroundColor: pickedColor1,
width: 110,
height: 30,
}}
platteStyle={{
backgroundColor: '#000',
borderRadius: 10,
}}
plattePosition={{
increaseMargin: 5, // to increase margin from element
// decreaseMargin: 20, to decrease default margin
}}
colorContainerStyle={{
borderRadius: 5,
}}>
<View>
<Text>Custom Palette</Text>
</View>
</RNColorPalette>
</View>
<View style={styles.textContainer}>
<Text style={styles.textStyle}>Color Palette</Text>
</View>
</Content>
</Container>
);
}
}
export default App;
const styles = {
textContainer: {
height: 500,
backgroundColor: '#e6c1c1',
justifyContent: 'center',
alignItems: 'center',
},
textStyle: {
fontSize: 20,
fontWeight: 'bold',
},
};
|
//Exceution Context
//Global
//function
// const asdasd ={
// }
// function Asdas(){
// console.log(this);
// }
// const x = new Asdas();
console.log('1');
console.log('2');
const timeoputId = setTimeout(() => {
console.log('after 5 sec');
}, 5000);
console.log('3');
setTimeout(() => {
console.log('after 2 sec');
clearTimeout(timeoputId);
}, 2000);
const int = setInterval(() => {
console.log('interval');
}, 2000);
setTimeout(() => {
console.log('clearInterval');
clearInterval(int);
}, 10000);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.