text
stringlengths 7
3.69M
|
|---|
import React from "react";
import { NavLink } from "react-router-dom"
function Header({
title,
logo = "//",
isDarkMode,
onDarkModeClick,
}) {
return (
<header>
<h1>
<span className="logo">{logo}</span>
{title}
</h1>
<nav>
<NavLink className="button" to="/projects">
All Projects
</NavLink>
<NavLink className="button" to="/new-project">
Add Project
</NavLink>
<button onClick={onDarkModeClick}>
{isDarkMode ? (
<span role="img" label="sun">
☀️
</span>
) : (
<span role="img" label="moon">
🌙
</span>
)}
</button>
</nav>
</header>
);
}
export default Header;
|
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const nodemailer = require("nodemailer");
const { google } = require("googleapis");
const SECRET = require('./SECRET.js');
const app = admin.initializeApp();
// Owner of the `SECRET.REFRESH_TOKEN`. Need to update the token when updating the email.
const EMAIL_SENDER = 'noreply@example.com';
const SCHEDULE = '05 * * * *'; // Format: https://crontab.guru/
exports.scheduledFunctionCrontab = functions.runWith({timeoutSeconds: 540, memory: '1GB'}).pubsub.schedule(SCHEDULE)
.onRun(async () => {
// Do something
});
// https://github.com/akshaybhange/firebase-functions-sendMail-Google-OAuth2
// https://android.jlelse.eu/firebase-functions-send-email-using-google-oauth2-20c552da6b3e
async function sendemails(list) {
const OAuth2 = google.auth.OAuth2;
const oauth2Client = new OAuth2(
SECRET.CLIENT_ID, //client Id
SECRET.CLIENT_SECRET, // Client Secret
"https://developers.google.com/oauthplayground" // Redirect URL
);
oauth2Client.setCredentials({
refresh_token: SECRET.REFRESH_TOKEN
});
const tokens = await oauth2Client.refreshAccessToken();
const accessToken = tokens.credentials.access_token;
const smtpTransport = nodemailer.createTransport({
// https://nodemailer.com/usage/bulk-mail/
pool: true,
maxConnections: 20,
maxMessages: Infinity,
service: "gmail",
auth: {
type: "OAuth2",
user: EMAIL_SENDER,
clientId: SECRET.CLIENT_ID,
clientSecret: SECRET.CLIENT_SECRET,
refreshToken: SECRET.REFRESH_TOKEN,
accessToken: accessToken
}
});
return Promise.all(list.map((content) => {
if (!content) {
return null;
}
const {to, subject, htmlBody} = content;
const mailOptions = {
from: EMAIL_SENDER,
to,
subject,
html: htmlBody,
};
return new Promise((resolve, reject) => {
smtpTransport.sendMail(mailOptions, (error, info) => error ? reject(error) : resolve(info));
}).then((info) => {
functions.logger.log(`Email sent to ${to}: ${subject}`);
}).catch((error) => {
functions.logger.error(`Failed to send to ${to}: ${subject}. ${error.message}`);
});
}));
}
|
import {Client} from 'discord.js';
import {discordToken} from './config.json';
import BlockifyModule from './plugins/Blockify.js';
import AutoModGiphyModule from './plugins/AutoModGiphy.js';
import Whendwalker from './plugins/Whendwalker.js';
const client = new Client();
// Each module exports a function that consumes messages for the module.
// The function will return true if it consumed the message and processing
// should stop.
const modules = [BlockifyModule, AutoModGiphyModule, Whendwalker];
client.once('ready', () => {
console.log('Ready!');
console.log(`Loaded ${modules.length} modules`);
});
client.on('message', (message) => {
for (const runModule of modules) {
if (runModule(message)) {
console.log(`[${message.channel.guild.name}#${message.channel.name}] ${message.author.username}#${message.author.discriminator} (${message.author.id}): ${message.toString()}`);
break;
}
}
});
client.login(discordToken).catch((err) => {
console.log(`Login error: ${err}`);
});
|
const dpi = window.devicePixelRatio || 1
const colors = [
'#E70000',
'#FF8C00',
'#FFEF00',
'#00811F',
'#0044FF',
'#760089'
]
let options = {
size: 100,
lines: false,
overlay: false
}
let canvas = createCanvas()
let interval = null
function createCanvas () {
let canvas = document.createElement('canvas')
canvas.width = window.innerWidth * dpi
canvas.height = window.innerHeight * dpi
document.body.appendChild(canvas)
return canvas
}
function draw (canvas, { size = 10, overlay = false, lines = false }) {
let ctx = canvas.getContext('2d')
let factor = overlay ? 1 : size
let w = canvas.width / factor
let h = canvas.height / factor
const gen = () => {
let m = overlay ? 1 : size
let x = lines ? 0 : (Math.floor(Math.random() * w) * m)
let y = Math.floor(Math.random() * h) * m
return { x, y }
}
const generator = () => {
const { x, y } = gen()
ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)]
ctx.fillRect(x, y, lines ? canvas.width : size, size)
}
return setInterval(generator, 5)
}
interval = draw(canvas, options)
function reset () {
document.body.removeChild(canvas)
canvas = createCanvas()
redo()
}
function toggle (event) {
if (interval) {
clearInterval(interval)
interval = null
event.currentTarget.innerHTML = 'Resume'
} else {
interval = draw(canvas, options)
event.currentTarget.innerHTML = 'Stop'
}
}
function redo () {
clearInterval(interval)
interval = draw(canvas, options)
}
function set (event, what) {
options[what] = event.currentTarget.checked
if (interval) redo()
}
function setSize (event) {
options.size = parseInt(event.currentTarget.value)
if (interval) redo()
}
|
module.exports = ({ env }) => ({
host: '0.0.0.0',
port: process.env.PORT || 8080,
production: true,
admin: {
auth: {
secret: process.env.APP_ADMIN_JWT_SECRET
},
},
});
|
/****************************************************/
/******************** 自定义Element校验规则 *********/
/***************************************************/
/**
* 校验手机号码
*/
export function checkMobile (rule, value, callback) {
if (!value) callback()
const reg = /^[1][3,4,5,7,8][0-9]{9}$/
if (!reg.test(value)) {
callback(new Error('格式不正确'))
} else {
callback()
}
}
/**
* 校验电话 同时验证手机号和固话
* @param rule
* @param value
* @param callback
* @constructor
*/
export function checkPhone (rule, value, callback){
if (!value) callback()
const mobileReg = /^[1][3,4,5,7,8][0-9]{9}$/
const phoneReg = /^([0-9]{3,4}-)?[0-9]{7,8}$/
if (mobileReg.test(value) || phoneReg.test(value)) {
callback()
} else {
callback(new Error('格式不正确'))
}
}
/**
* 校验身份证号码
*/
export function checkCardNo (rule, value, callback) {
if (!value) callback()
const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
if (!reg.test(value)) {
callback(new Error('格式不正确'))
} else {
callback()
}
}
// export function checkNum (rule, value, callback){
// if(!this.buildingsEdit.nameType){
// this.buildingsEdit.begin = ''
// this.buildingsEdit.end = ''
// this.$message({
// type:'warning',
// message:'请先选择类型'
// })
// return false
// }
// if (!value) callback()
// let str= /^[A-Z]$/
// if (!str.test(value) && this.buildingsEdit.nameType === '2'){
// return callback(new Error('请输入大写字母'));
// }
// }
|
import React from 'react';
import {Header} from 'semantic-ui-react'
export default {
mapOptions :(data) => {
return (data || []).map((item) => ({
key: item.id,
value: item.id,
text: <Header content={item.label} subheader={item.iban}/>,
content: <Header content={item.label} subheader={item.iban}/>
}))
},
extractMonthFromDate : (value) => {
return value.slice(5, 7)
},
chartFilter : (list, type, flag) => {
return list.filter((it) => it.type === type).map((it) => flag ? this.extractMonthFromDate(it.balanceDate) : it.amount)
}
};
|
import React from 'react';
export default function HeadCounter() {
return <div></div>;
}
|
module.exports = (sequelize, Sequelize) => {
const CandidateBio = sequelize.define('candidate_bio', {
user_id: {
type: Sequelize.STRING
},
profile_pic: {
type: Sequelize.STRING
},
other_img1: {
type: Sequelize.STRING
},
other_img2: {
type: Sequelize.STRING
},
candidate_idcard:{
type: Sequelize.STRING
},
candidate_info:{
type: Sequelize.TEXT
},
special_telent:{
type: Sequelize.STRING
},
social_responsiblity:{
type: Sequelize.STRING
},
sports:{
type: Sequelize.STRING
},
candidate_resume_video: {
type: Sequelize.STRING
},
candidate_resume:{
type: Sequelize.STRING
}
}, {
freezeTableName: true,
});
return CandidateBio;
}
|
import React from 'react'
import {connect} from 'react-redux'
// import {startPostProfile, startRemoveProfile, startGetProfile} from '../actions/profileAction'
import { MDBContainer, MDBRow, MDBCol, MDBBtn, MDBCard, MDBCardBody, MDBIcon } from 'mdbreact';
class Profile extends React.Component{
constructor (){
super()
this.state= {
fullname : '',
email : '',
mobile: null,
course:'',
location:'',
referralCode:''
}
}
componentDidMount(){
console.log('entered profile componentDidMount')
// this.props.dispatch(startGetProfile(localStorage.getItem('tokenAssessment1')))
}
handleChange= (e)=>{
this.setState({
[e.target.name] : e.target.value
})
}
handleDelete=()=>{
const confirmed= window.confirm('Are you sure?')
if(confirmed){
const id=localStorage.getItem('tokenAssessment1')
const redirect = ()=>{
return this.props.history.push('/')
}
// this.props.dispatch(startRemoveProfile(id,redirect))
}
}
handleSubmit = (e)=>{
e.preventDefault()
const redirect = ()=>{
console.log('redirect function entered')
return this.props.history.push('/')
}
// this.props.dispatch(startPostProfile({...this.state}))
}
render(){
console.log('AddProfile state values ',this.state)
return(
<div className='profile'>
{this.props.profile ?(
<div>
<h1>Profile</h1>
<MDBContainer>
<MDBRow>
<MDBCol md="6" >
<MDBCard>
<MDBCardBody>
<form>
<p className="h4 text-center py-4">CREATE YOUR ACCOUNT</p>
<label
htmlFor="defaultFormCardNameEx"
className="grey-text font-weight-light"
>
Your name
</label>
<input
type="text"
id="defaultFormCardNameEx"
placeholder='John Smith'
className="form-control"
/>
<br />
<label
className="grey-text font-weight-light"
>
Your email
</label>
<input
type="email"
id="defaultFormCardEmailEx"
placeholder='John@gmail.com'
className="form-control"
/>
<br/>
<label
className="grey-text font-weight-light"
>
Mobile
</label>
<input
type="email"
id="defaultFormCardEmailEx"
placeholder='+91 9847568595'
className="form-control"
/>
<br/>
<label
className="grey-text font-weight-light"
>
Select a course
</label>
<select className="browser-default custom-select">
<option>Select a course</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<br/><br/>
<label
className="grey-text font-weight-light"
>
Location
</label>
<input
type="email"
id="defaultFormCardEmailEx"
placeholder='Enter city'
className="form-control"
/>
<br/>
<label
className="grey-text font-weight-light"
>
Referral code(optional)
</label>
<input
type="email"
id="defaultFormCardEmailEx"
placeholder='Enter city'
className="form-control"
/>
<br/>
<div className="text-center mb-3">
<MDBBtn
type="button"
gradient="#b0bec5"
rounded
className="btn-block z-depth-1a"
>
Sign in
</MDBBtn>
</div>
<p className="font-small dark-grey-text text-right d-flex justify-content-center mb-3 pt-2">
Other signup
</p>
<div className="row my-3 d-flex justify-content-center">
<MDBBtn
type="button"
color="white"
rounded
className="z-depth-1a"
>
<MDBIcon fab icon="google-plus-g" className="blue-text" />
</MDBBtn>
<MDBBtn
type="button"
color="white"
rounded
className="mr-md-3 z-depth-1a"
>
<MDBIcon fab icon="facebook-f" className="blue-text text-center" />
</MDBBtn>
</div>
<MDBCol md="7" className="d-flex justify-content-center">
<p className="font-small grey-text mt-3">
click here to
<a
href="/login"
className="dark-grey-text ml-1 font-weight-bold"
>
login
</a>
</p>
</MDBCol>
</form>
</MDBCardBody>
</MDBCard>
</MDBCol>
</MDBRow>
</MDBContainer>
</div>
):(
<h1></h1>
) }
</div>
)
}
}
const mapStateToProps= (state)=>{
console.log('AddProfile page mapStateToProps entered')
return {
profile : []
}
}
export default connect( mapStateToProps)(Profile)
|
var promise = new Promise(function (fulfill, reject) {
setTimeout( () => {
reject('REJECTED!');
}, 3000);
});
promise.then(console.log);
|
const express = require('express');
const meetingsRouter = express.Router();
const dbFunctions = require("./db");
meetingsRouter.get('/', (req, res, next) => {
res.send(dbFunctions.getAllFromDatabase('meetings'));
});
meetingsRouter.post('/', (req, res, next) => {
addToDatabase('meetings', req.query);
res.status(201).send('Meeting Created Successfully');
});
meetingsRouter.delete('/', (req, res, next) => {
db.deleteAllFromDatabase('meetings');
})
module.exports = meetingsRouter;
|
import { handleActions } from "redux-actions";
const initialState = {
news: [],
page: 1,
nextPage: 2,
prevPage: 1,
currentFeed: {},
isLoading: null,
error: null
};
const newsReducer = handleActions(
{
FETCH_NEWS: (state, { isLoading, payload, error }) => {
if (isLoading || error) {
return {
...state,
isLoading,
error
};
}
return {
...state,
news: payload.news,
page: payload.page,
nextPage: payload.page + 1,
prevPage: payload.page > 1 ? payload.page - 1 : 1,
isLoading,
error
};
},
FETCH_FEED: (state, { isLoading, payload, error }) => {
if (isLoading || error) {
return {
...state,
isLoading,
error
};
}
return {
...state,
isLoading,
currentFeed: payload,
error
};
}
},
initialState
);
export default (state, action) => newsReducer(state, action);
|
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (/* function */ callback, /* DOMElement */ element) {
window.setTimeout(callback, 1000 / 60);
};
})();
function GameEngine() {
this.entities = [];
this.newEntities = [];
this.game_ctx = null;
this.background_ctx = null;
this.overlay_ctx = null;
this.surfaceWidth = null;
this.surfaceHeight = null;
this.wave = 0;
this.waveTick = 0;
this.score = 0;
this.active = true;
}
GameEngine.prototype.init = function (game_ctx, background_ctx, overlay_ctx) {
this.game_ctx = game_ctx;
this.background_ctx = background_ctx;
this.overlay_ctx = overlay_ctx;
this.surfaceWidth = this.game_ctx.canvas.width / 2;
this.surfaceHeight = this.game_ctx.canvas.height / 2;
this.startInput();
this.timer = new Timer();
this.wave = 1;
// temp function to show basic animations for prototype. remove for final
this.makeProtoEnemies();
}
GameEngine.prototype.start = function () {
var that = this;
(function gameLoop() {
that.loop();
requestAnimFrame(gameLoop, that.game_ctx.canvas);
})();
}
GameEngine.prototype.startInput = function () {
var that = this;
that.overlay_ctx.canvas.addEventListener("keydown", function (e) {
if (String.fromCharCode(e.which) === ' ') that.spacebar = true;
if (e.keyCode === 37) that.leftkey = true;
if (e.keyCode === 38) that.upkey = true;
if (e.keyCode === 39) that.rightkey = true;
if (e.keyCode === 40) that.downkey = true;
e.preventDefault();
}, false);
}
GameEngine.prototype.addEntity = function (entity) {
this.entities.push(entity);
}
GameEngine.prototype.draw = function () {
this.game_ctx.clearRect(0, 0, this.surfaceWidth * 2, this.surfaceHeight * 2);
this.game_ctx.save();
for (var i = 0; i < this.entities.length; i++) {
if (this.entities[i].removeMe) {
this.increment("score", this.entities[i].value);
this.entities.splice(i,1);
} else {
this.entities[i].draw(this.ctx);
}
}
this.game_ctx.restore();
}
GameEngine.prototype.update = function () {
var entitiesCount = this.entities.length;
for (var i = 0; i < entitiesCount; i++) {
var entity = this.entities[i];
entity.update();
}
}
GameEngine.prototype.loop = function () {
this.clockTick = this.timer.tick();
// reenable waveTick incrememnt went moving past prototype
//this.waveTick += 1;
// 500x + 8000
// first wave gets 26 waves points. if each of these is an asteroid that means
// 26 asteroids are created. average of 5 seconds to kill each one means 130
// seconds to kill all, this equals 7800 ticks, round to 8000 and add 500 ticks
// to each wave. wave points increase by 15 each time or about 3x the increased time
// so the game gets harder in several ways each wave.
if (this.waveTick > (500 * this.wave) + 8000) {
this.waveTick = 0;
this.increment("wave",1);
this.generateWave();
}
this.update();
this.draw();
this.spacebar = null;
this.leftkey = null;
this.upkey = null;
this.downkey = null;
this.rightkey = null;
}
GameEngine.prototype.getX = function(width, x) {
return this.surfaceWidth + x - (width / 2);
}
GameEngine.prototype.getY = function(height, y) {
return this.surfaceHeight + y - (height / 2);
}
GameEngine.prototype.end = function() {
this.changeState();
}
GameEngine.prototype.increment = function(target, amount) {
this.target += amount;
}
GameEngine.prototype.changeState = function() {
if(active) {
this.wave = 0;
this.score = 0;
}
active = !active;
}
GameEngine.prototype.generateWave = function() {
//points worth of enemies generated this wave.
waveValue = (this.wave * 15) + 11;
//chance an alien can spawn. this is < 0 until wave 3.
alienChance = (this.wave * 1.5) - 3;
//chance a powerup can spawn. this is < 0 until wave 2.
powerupChance = (this.wave * 2) - 2;
while (waveValue > 0) {
type = this.getRandomInt(1,100);
/*
if (type - alienChance > 0) {
velocity = {x: velx + 1, y: vely + 1};
value = this.getRandomInt(2,4) * 10;
this.addEntity(new AlienShip(this, angle, velocity, null, x, y, null, value));
waveValue -= value;
} else {
velocity = {x: velx, y: vely};
size = this.getRandomInt(1,3);
this.addEntity(new Asteroid(this, angle, velocity, x, y, size));
waveValue -= size;
}
if (type - powerupChance > 0) {
velocity = {x: velx, y: vely};
this.addEntity(new PowerUp(this, angle, velocity, null, x, y, null));
}
*/
velocity = {x: this.getRandomInt(-4,4), y: this.getRandomInt(-4,4)};
size = this.getRandomInt(1,3);
// this.addEntity(new Asteroid(this, Math.random() * 2 * Math.PI, velocity, this.randOffScreenPoint(), this.randOffScreenPoint(), size));
waveValue -= size;
}
}
GameEngine.prototype.randOffScreenPoint = function() {
side = Math.round(Math.random());
if (side === 0) {
return 0 - this.getRandomInt(this.surfaceWidth + 25, this.surfaceWidth + 50);
} else {
return this.getRandomInt(this.surfaceHeight + 25, this.surfaceHeight + 50);
}
}
GameEngine.prototype.makeProtoEnemies = function() {
this.addEntity(new Asteroid(this, (Math.random() * 2 * Math.PI), {x: -2, y: -1}, -100, 50, 3));
this.addEntity(new Asteroid(this, (Math.random() * 2 * Math.PI), {x: 2, y: 1}, 100, 50, 3));
this.addEntity(new Asteroid(this, (Math.random() * 2 * Math.PI), {x: this.getRandomInt(1,4), y: this.getRandomInt(1,4)}, -200, 200, 2));
this.addEntity(new Asteroid(this, (Math.random() * 2 * Math.PI), {x: this.getRandomInt(1,4), y: this.getRandomInt(1,4)}, -100,-150, 3));
this.addEntity(new Asteroid(this, (Math.random() * 2 * Math.PI), {x: this.getRandomInt(1,4), y: this.getRandomInt(1,4)}, 200, 300, 1));
this.addEntity(new AlienShip(this, (Math.round() * 2 * Math.PI), {x:0, y:-1}, AM.getAsset("./images/alienship.png"), 75, 75, null, 100));
this.addEntity(new Weapon(this, 0, {x:0,y:-1},AM.getAsset("./images/weapon3.png"), 0, 0));
// this.generateWave();
}
GameEngine.prototype.getRandomInt = function(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
GameEngine.prototype.resultVector = function(orig_vec, force_vec) {
var ret = {};
ret.x = orig_vec.x + force_vec.x;
ret.y = orig_vec.y + force_vec.y;
return ret;
}
GameEngine.prototype.resolveVec = function(angle, mag) {
var ret = {};
ret.x = mag * Math.cos(angle);
ret.y = mag * Math.sin(angle);
return ret;
}
GameEngine.prototype.velocityMag = function(vel) {
return Math.sqrt(vel.x * vel.x + vel.y * vel.y);
}
function Timer() {
this.gameTime = 0;
this.maxStep = 0.05;
this.wallLastTimestamp = 0;
}
Timer.prototype.tick = function () {
var wallCurrent = Date.now();
var wallDelta = (wallCurrent - this.wallLastTimestamp) / 1000;
this.wallLastTimestamp = wallCurrent;
var gameDelta = Math.min(wallDelta, this.maxStep);
this.gameTime += gameDelta;
return gameDelta;
}
|
import {StatusBar} from 'expo-status-bar';
import React from 'react';
import {View} from 'react-native';
import Amplify from 'aws-amplify';
import awsmobile from './aws-exports';
import MapRN from './src/components/MapRN';
import Index from './src/components/Index';
import styles from './src/assets/jammStyle';
import TitleText from "./src/components/TitleText";
import Logo from "./src/components/Logo";
import ButtonAlpha from "./src/components/buttons/ButtonAlpha";
Amplify.configure(awsmobile);
// Amplify.configure({
// API: {
// graphql_endpoint: 'http://192.168.1.92:20002/graphql'
// }
// });
export default function App() {
return (
<View style={styles.container}>
<Index/>
<StatusBar style="auto"/>
</View>
);
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
alert("Selamat Datang\n \n \n Di Rumah Sakit");
|
const mix = {
data () {
return {
select: '-->'
}
},
directives: {
searchWarna: {
bind: (el, binding) => {
el.style.backgroundColor = binding.value
}
}
}
}
export default mix
|
import React, { Component } from 'react';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Welcome to Horoscraps!</h1>
</header>
<form name="userInfo">
<ul>
<li>
Your name:
<input type="text" name="firstname"/>
</li>
<li>
Birth month:
<input type="text" name="birthmonth"/>
</li>
<li>
Birth date:
<input type="text" name="birthdate"/>
</li >
<input type="submit" value="Send into the universe"/>
</ul>
</form>
</div>
);
}
}
// Responses
// Ares, you’ll be fired from Forever 21 because Brian ratted you out.
// Don’t wear flip flops on Tuesdays, a pile of shit is headed your way…literally.
export default App;
|
function shortLongShort(shortString, longString) {
if (shortString.length > longString.length) {
[shortString, longString] = [longString, shortString];
}
combinedStrings = shortString + longString + shortString;
console.log(combinedStrings);
}
shortLongShort('abc', 'defgh'); // "abcdefghabc"
shortLongShort('abcde', 'fgh'); // "fghabcdefgh"
shortLongShort('', 'xyz'); // "xyz"
|
angular.module('Factories', []);
require('./factories/questionFactory.js');
require('./factories/loginFactory.js');
require('./factories/databaseFactory.js');
|
../../../../../shared/src/App/FavoritePornstars/models.js
|
import React from "react";
import styled from "styled-components";
import { Header, Container, Divider } from "semantic-ui-react";
import { FacebookButton, GmailButton } from "../SocialNetButtons";
import RegisterForm from "./Form/Container";
import facebook from "../../../assets/facebook.svg";
import google from "../../../assets/google.svg";
import Modal from "../Modal/Container";
const Title = styled(Header)`
&&&& {
text-align: left;
font-size: 24px;
font-weight: 800;
border-bottom: none;
margin: 24px 0;
}
`;
const ButtonsBox = styled(Container)`
&&&& {
width: 100%;
}
`;
const StyledDivider = styled(Divider)`
&&& {
color: #767676;
text-transform: lowercase;
margin: 22px 0;
}
`;
const Image = styled.img`
&&& {
align-self: self-start;
height: 18px;
width: 18px;
margin-right: 12px;
}
`;
const Footer = styled.p`
&&& {
font-size: 16px;
color: #4f4b65;
font-weight: 400;
}
`;
const RegisterAction = styled.a`
font-weight: 700;
color: #483df6;
margin: 0 8px;
cursor: pointer;
&:hover {
color: #483df6;
text-decoration: underline;
text-decoration-color: #483df6;
}
`;
const Login = ({ handleGoogleAuth, handleFacebookAuth, handleLoginModalToggle, reference }) => (
<Modal name="Inicia sesión" ref={reference}>
<Title>Inicia sesión para continuar</Title>
<ButtonsBox>
<RegisterForm />
<StyledDivider horizontal>o continúa con</StyledDivider>
<FacebookButton onClick={handleFacebookAuth}>
<Image src={facebook} />
<span style={{ alignSelf: "flex-end" }}>Facebook</span>
</FacebookButton>
<GmailButton onClick={handleGoogleAuth}>
<Image src={google} />
<span>Google</span>
</GmailButton>
<StyledDivider />
<Footer>
<span>¿No tienes cuenta en Pandora?</span>
<RegisterAction onClick={handleLoginModalToggle} >Regístrate</RegisterAction>
</Footer>
</ButtonsBox>
</Modal>
);
export default Login;
|
import React from 'react';
import $ from 'jquery';
import { Button } from 'react-bootstrap';
class ReactApi extends React.Component {
constructor() {
super();
this.state = {
searchQuery: '',
results: []
};
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
$.ajax({
type: 'GET',
dataType: 'jsonp',
url: `https://itunes.apple.com/search?term=${this.state.searchQuery}&country=us&entity=movie`,
success: data => {
const movies = data.results.map(movie => movie.trackName);
this.setState({
results: movies
});
}
});
// console.log('handleClick');
}
handleChange(e){
this.setState({
searchQuery: e.target.value
});
}
render() {
return (
<div>
<Search
searchQuery={this.state.searchQuery}
handleChange={this.handleChange}
handleClick={this.handleClick} />
<Results results={this.state.results} />
</div>
);
}
}
class Search extends React.Component {
render() {
return (
<div>
<input
type="text"
value={this.props.searchQuery}
onChange={this.props.handleChange} />
<Button bsStyle="primary" onClick={this.props.handleClick}>Bootstrap Send</Button>
</div>
);
}
}
class Results extends React.Component {
render() {
return (
<ul>
{
this.props.results.map((item, i) => <ResultItem item={item} key={i} />)
}
</ul>
);
}
}
class ResultItem extends React.Component {
render() {
return (
<li>{this.props.item}</li>
);
}
}
export default ReactApi;
|
/**
* JS Linting
*/
require('mocha-eslint')([
'assets/js',
'config',
'models',
'routes',
'test',
'app.js'
]);
|
const bcrypt = require('bcryptjs')
const myFunction = async () => {
const pass = "Bibash"
const hashedPassword = await bcrypt.hash(pass, 8)
console.log(hashedPassword)
console.log(await bcrypt.compare(pass, hashedPassword))
}
myFunction()
|
/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext*/
Ext.define('Jarvus.field.Money', {
extend: 'Jarvus.field.Float'
,xtype: 'moneyfield'
,componentCls: 'field-money'
,readValue: function() {
return this.callParent().replace(/[^\d.]/, '');
}
,renderValue: function(value) {
return Ext.util.Format.usMoney(value);
}
,renderEditingValue: function(value) {
return value*1;
}
});
|
Nstagram.Collections.Comments = Backbone.Collection.extend({
model: Nstagram.Models.Comment,
initialize: function (options) {
this.url = '/api/comments/' + options["photo_id"];
}
});
|
import Author from './author';
import {connect} from '../data';
export default connect(({match}) => `${match.url}/data.json`)(Author);
|
const Lap = require('./../model/Lap');
const convertTimeToSeconds = time => {
const [minute, second] = time.split(':').map(Number);
const seconds = minute * 60 + second;
return Number(seconds.toFixed(3));
};
const buildLap = line => {
const lap = new Lap(line);
lap.lapTime = convertTimeToSeconds(lap.lapTime);
return lap;
};
const splitLineInformation = line => {
return line.split(/\s–\s|\s+/);
};
const parseLaps = content => {
try {
return content
.split('\n')
.splice(1)
.map(line => splitLineInformation(line))
.map(line => buildLap(line));
} catch (e) {
throw e;
}
};
const convertNumberToString = (number, includeMinutes = true) => {
const minutes = Math.trunc(number / 60);
const secondsAndMilliseconds = (number - minutes * 60).toFixed(3);
if (includeMinutes) {
return `${minutes}:${secondsAndMilliseconds}`;
}
return secondsAndMilliseconds;
};
module.exports = {
parseLaps,
convertNumberToString,
convertTimeToSeconds,
};
|
import React from 'react';
import { Link } from 'react-router-dom';
import './styles.css';
const FriendList = ({ friendCount, username, friends }) => {
if (!friends || !friends.length) {
return <p className="friend-list-title text-center text-light p-3">{username}, follow someone!</p>;
}
return (
<div>
<h5>
{username} is {friendCount === 1 ? 'following' : 'following'} {friendCount} users
</h5>
{friends.map(friend => (
<button className="friend-btn w-100 display-block mb-2 myAnimeBtn" key={friend._id}>
<Link to={`/profile/${friend.username}`}>{friend.username}</Link>
</button>
))}
</div>
);
};
export default FriendList;
|
const express = require('express');
const router = express.Router();
const db = require("../my_modules/db.js");
const moment = require('moment');
const mysqldb = require("../my_modules/mysqldb.js");
// http://localhost:3000/nodejs/httpTest-mysql?action=findData&whereStr=id=1 and name="xx"&fieldStr=field1,field2&prePageNum=10&currPage=1&sortStr=id ASC|DESC //查询数据
// http://localhost:3000/nodejs/httpTest-mysql?action=findDataLookup&whereStr=id=1 and name="xx"&fieldStr=table1.id,table1.firstname,table1.email,table2.age&prePageNum=10&currPage=1&sortStr=id DESC //查询关联数据
// http://localhost:3000/nodejs/httpTest-mysql?action=insertData&dataArr=[{"name":"mick","age":18},{"name":"tina","age":35}] //插入数据
// http://localhost:3000/nodejs/httpTest-mysql?action=updateData&whereStr=id=1&updateJson={"name":"xx"} //修改数据
// http://localhost:3000/nodejs/httpTest-mysql?action=delData&dataArr=[1,3,5] //删除数据
// http://localhost:3000/nodejs/httpTest-mysql?action=addCol&dataJson={"fieldName":"num","dataType":"INT"} //插入列
// http://localhost:3000/nodejs/httpTest-mysql?action=updateCol&dataJson={"fieldName":"num","fieldNewName":"meg","dataNewType":"TEXT"} //修改列
// http://localhost:3000/nodejs/httpTest-mysql?action=delCol&dataJson={"fieldName":"num"} //删除列
router.get('/', function(req, res, next) {
var dbName = req.baseUrl.split("/")[2];
//返回错误
function returnErr (value) {
console.log(value);
res.send(value);
}
//分配方法
var action = req.query.action;
switch (action){
case "findData":
findData();
break;
case "findDataLookup":
findDataLookup();
break;
default:
returnErr("action错误");
}
//查找关联数据
function findDataLookup () {
//var sql_lookup = "table1 LEFT JOIN table2 ON table1.firstname = table2.firstname"; //2张表
var sql_lookup = "(table1 LEFT JOIN table2 ON table1.firstname = table2.firstname) LEFT JOIN table3 ON table1.firstname = table3.firstname"; //3张表
var fieldStr = req.query.fieldStr;
var whereStr = req.query.whereStr;
var sortStr = req.query.sortStr;
var prePageNum = req.query.prePageNum ? Number(req.query.prePageNum) : 0;
var currPage = req.query.currPage ? Number(req.query.currPage) : 0;
var args = {"prePageNum":prePageNum, "currPage":currPage, "sort":sortStr};
mysqldb.findDataLookup(sql_lookup, whereStr, fieldStr, args, function(err, result, count){
if(err){
returnErr('findDataError:'+ err);
return;
}
//console.log(result);
console.log("查询了" + result.length +"条数据," + "共" + count +"条数据");
var jsonObj = {"code": 0, "msg" : "", "count" : count, "prePageNum": prePageNum, "currPage": currPage, "rows": result};
res.send(jsonObj);
});
}
//查询数据
function findData () {
var whereStr = req.query.whereStr;
var fieldStr = req.query.fieldStr;
var sortStr = req.query.sortStr;
var prePageNum = req.query.prePageNum ? Number(req.query.prePageNum) : 0;
var currPage = req.query.currPage ? Number(req.query.currPage) : 0;
var args = {"prePageNum":prePageNum, "currPage":currPage, "sort":sortStr};
mysqldb.findData(dbName, whereStr, fieldStr, args, function(err, result, count){
if(err){
returnErr('findDataError:'+ err);
return;
}
//console.log(result);
console.log("查询了" + result.length +"条数据," + "共" + count +"条数据");
var jsonObj = {"code": 0, "msg" : "", "count" : count, "prePageNum": prePageNum, "currPage": currPage, "rows": result};
res.send(jsonObj);
});
}
});
router.post('/', function(req, res, next) {
var dbName = req.baseUrl.split("/")[2];
//返回错误
function returnErr (value) {
console.log(value);
res.send(value);
}
//分配方法
console.log(req.body);
var action = req.body.action;
switch (action){
case "insertData":
insertData();
break;
case "updateData":
updateData();
break;
case "delData":
delData();
break;
case "addCol":
addCol();
break;
case "updateCol":
updateCol();
break;
case "delCol":
delCol();
break;
case "sendMail":
sendMailFn();
break;
default:
returnErr("action错误");
}
//插入数据
function insertData () {
if(req.body.dataArr){
try{
var dataArr = JSON.parse(req.body.dataArr);
if(Array.isArray(dataArr) && dataArr.length > 0){
//continue
}else{
returnErr("dataArr错误");
return;
}
}catch(e){
returnErr("dataArr错误");
return;
}
}else{
returnErr("dataArr错误");
return;
}
for(let i=0; i<dataArr.length; i++){
dataArr[i].create_name = req.cookies["logining_node"].username;
dataArr[i].create_time = moment().format("YYYY-MM-DD HH:mm:ss");
}
mysqldb.insertData(dbName,dataArr,function(errArr){
if(errArr.length > 0){
res.send("操作失败:" +errArr.join(","));
return;
}
console.log("插入了" + dataArr.length +"条数据");
res.send("操作成功");
});
}
//修改数据
function updateData () {
if(req.body.whereStr){
var whereStr = req.body.whereStr;
}else{
returnErr("whereStr错误");
return;
}
if(req.body.updateJson){
try{
var updateJson = JSON.parse(req.body.updateJson);
}catch(e){
returnErr("updateJson错误");
return;
}
}else{
returnErr("updateJson错误");
return;
}
updateJson.update_name = req.cookies["logining_node"].username;
updateJson.update_time = moment().format("YYYY-MM-DD HH:mm:ss");
mysqldb.updateData(dbName, whereStr, updateJson, function(err,result){
if(err){
returnErr('updateDataError:'+ err);
return;
}
console.log("修改了" + result.changedRows +"条数据");
if(result.changedRows > 0){
res.send("操作成功");
}else{
res.send("操作失败");
}
});
}
//删除数据
function delData () {
if(req.body.dataArr){
try{
var dataArr = JSON.parse(req.body.dataArr);
if(Array.isArray(dataArr) && dataArr.length > 0){
//continue
}else{
returnErr("dataArr错误");
return;
}
}catch(e){
returnErr("dataArr错误");
return;
}
}else{
returnErr("dataArr错误");
return;
}
mysqldb.deleteData(dbName, dataArr, function(err,result){
if(err){
returnErr('deleteDataError:'+ err);
return;
}
console.log("删除了" + result.affectedRows +"条数据");
if(result.affectedRows > 0){
res.send("操作成功");
}else{
res.send("操作失败");
}
});
}
//插入列
function addCol () {
if(req.body.dataJson){
try{
var dataJson = JSON.parse(req.body.dataJson);
}catch(e){
returnErr("dataJson错误");
return;
}
}else{
returnErr("dataJson错误");
return;
}
if(!dataJson.fieldName || !dataJson.dataType){
returnErr("dataJson错误");
return;
}
var sql = "ADD " + dataJson.fieldName +" "+ dataJson.dataType;
mysqldb.updateCol(dbName, sql, function(err,result){
if(err){
returnErr('addCol:'+ err);
return;
}
console.log("插入列 " + dataJson.fieldName);
res.send("操作成功");
});
}
//修改列
function updateCol () {
if(req.body.dataJson){
try{
var dataJson = JSON.parse(req.body.dataJson);
}catch(e){
returnErr("dataJson错误");
return;
}
}else{
returnErr("dataJson错误");
return;
}
if(!dataJson.fieldName || !dataJson.fieldNewName){
returnErr("dataJson错误");
return;
}
var sql = "CHANGE " + dataJson.fieldName +" "+ dataJson.fieldNewName;
if(dataJson.dataNewType){
sql += " "+dataJson.dataNewType;
}
mysqldb.updateCol(dbName, sql, function(err,result){
if(err){
returnErr('updateCol:'+ err);
return;
}
console.log("修改列 " + dataJson.fieldName);
res.send("操作成功");
});
}
//删除列
function delCol () {
if(req.body.dataJson){
try{
var dataJson = JSON.parse(req.body.dataJson);
}catch(e){
returnErr("dataJson错误");
return;
}
}else{
returnErr("dataJson错误");
return;
}
if(!dataJson.fieldName){
returnErr("dataJson错误");
return;
}
var sql = "DROP " + dataJson.fieldName;
mysqldb.updateCol(dbName, sql, function(err,result){
if(err){
returnErr('delCol:'+ err);
return;
}
console.log("刪除列 " + dataJson.fieldName);
res.send("操作成功");
});
}
//事物
// mysqldb.beginTransaction(function(err){
// returnErr("beginTransaction错误");
// return;
// });
});
module.exports = router;
|
import comento from './comento'
export default {
comento
}
|
const mongoose = require('mongoose');
const { Schema } = mongoose;
const pieSchema = new Schema({
data: {type:Number,required: true},
month:{type:String,required:true}
},{collection:'pie'})
module.exports = pieSchema;
|
const request = require('request')
const userProfiles = new Map()
let config = {}
let logger = console.log
/**
* Setup service
*
* @param cfg
* @param lgr
*/
function setup (cfg, lgr) {
config = cfg
logger = lgr
}
/**
* Get profile
* - get from cache or
* - get from the api and store it in memory cache
*
* @param token
* @returns {*}
*/
function getProfile (token) {
if (userProfiles.has(token)) {
logger('Returning user profile from cache')
return Promise.resolve(userProfiles.get(token))
}
return obtainProfile(token)
.then(profile => {
logger('Returning user profile from api')
userProfiles.set(token, profile)
return profile
})
}
/**
* Ask user service for user profile
*
* @param token
* @returns {Promise}
*/
function obtainProfile (token) {
if (!config.url) {
throw Error('UserInfo requires setup')
}
const options = {
url: config.url,
headers: {
'Authorization': `Bearer ${token}`,
},
}
return new Promise(resolve => {
request(options, (error, response, body) => {
if (error) {
throw Error(error)
}
if (response.statusCode !== 200) {
}
resolve(JSON.parse(body))
})
})
}
module.exports = {
getProfile,
obtainProfile,
setup,
}
|
$(document).ready(function()
{
$("#msgbox").hide();
$(document).on("click","#clickHere",function()
{
$("#clickHere").hide();
$("#msgbox").show();
});
});
$(document).on("click","#done",function()
{
var title=$("#i2").val();
var note=$("#i3").val();
console.log(title);
console.log(note);
var userNote={title:title,note:note};
console.log(userNote);
$.ajax({
url:" http://localhost:8081/api/dashboard",
datatype:"json",
type:"POST",
data:userNote,
success:function(data)
{
console.log(data);
if(data.status){
console.log("this is the response");
}
else {
console.log("this is the else part");
}
},
});
});
|
define([
'cfgs',
'core/core-modules/framework.form',
'core/core-modules/framework.util'
], function (cfgs, form, util) {
let module = {
"define": {
"name": "input-date"
}
};
/**
* 模型
* 筛选条件、表格项、编辑项,校验内容,
*/
/** 处理 网格显示 */
module.grid = (column, tr, value) => {
// 显示时间类型
var format;
if (column.type == 'date') {
format = cfgs.options.defaults.dateformat2;
} else if (column.type == 'datetime') {
format = cfgs.options.defaults.datetimeformat;
}
form.appendDateText(tr, value, format);
};
/** 处理 查询条件 */
module.filter = (column, labelContainer, valueContainer) => {
labelContainer.append(column.text);
var ctrl = $('<input/>')
.addClass('form-control form-date')
.attr('type', 'text')
.attr('id', column.name)
.attr('name', column.name)
.attr('placeholder', '请选择' + column.text + '...');
valueContainer.append(ctrl);
};
/** 处理 预览 */
module.preview = (column, value, labelContainer, valueContainer) => {
labelContainer.append(column.text);
let format;
if (column.type == 'date') {
format = cfgs.options.defaults.dateformat2;
} else if (column.type == 'datetime') {
format = cfgs.options.defaults.datetimeformat;
}
$('<input/>')
.attr('readonly', true)
.addClass('form-control')
.val(util.utcTostring(value, format))
.appendTo(valueContainer);
}
/** 处理 获取筛选结果 */
module.getFilter = (column) => {
var value = $("#" + column.name).val();
if (!value || value == "") {
return;
} else {
return value;
}
};
/** 处理 数据编辑 */
module.editor = (column, value, labelContainer, valueContainer) => {
let format;
if (column.type == 'date') {
format = cfgs.options.defaults.dateformat2;
} else if (column.type == 'datetime') {
format = cfgs.options.defaults.datetimeformat;
}
$("#" + column.name).val(
util.utcTostring(value, format)
);
};
/** 处理 数据有效性验证 */
module.valid = () => {
};
/** 处理 对象销毁 */
module.destroy = () => {
}
return module;
});
|
angular.module('named-views.regi-mover2', [
'ui.router'
])
.config(['$stateProvider',function($stateProvider){
$stateProvider
.state('home.regi-mover2', {
url: 'regi-mover2',
views: {
'content@': {
templateUrl: 'regi-mover2.html'
}
}
}
)
}])
;
|
const knex = require("knex");
const app = require("../src/app");
const helpers = require("./test-helpers");
describe("Meals Endpoints", () => {
let db;
const { testUsers, testMeals, testFoods } = helpers.makeMacroFyFixtures();
before("make knex instance", () => {
db = knex({
client: "pg",
connection: process.env.TEST_DATABASE_URL
});
app.set("db", db);
});
after("disconnect from db", () => db.destroy());
before("cleanup", () => helpers.cleanTables(db));
afterEach("cleanup", () => helpers.cleanTables(db));
context("/api/meals endpoint", () => {
describe(`POST /api/meals`, () => {
context(`Meal validation`, () => {
beforeEach("insert users", () => helpers.seedUsers(db, testUsers));
const requiredFields = [
"user_id",
"meal_name",
"protein",
"carbs",
"fats"
];
const testUser = testUsers[0];
requiredFields.forEach(field => {
const mealPostAttempt = {
user_id: 1,
meal_name: "test-meal",
protein: "20",
carbs: "10",
fats: "8"
};
it(`responds with 400 required error when '${field}' is missing`, () => {
delete mealPostAttempt[field];
return supertest(app)
.post("/api/meals")
.set("Authorization", helpers.makeAuthHeader(testUser))
.send(mealPostAttempt)
.expect(400, {
error: `Missing '${field}' in request body`
});
});
});
context("Happy path", () => {
it(`responds 201, serialized meal`, () => {
const newMeal = {
user_id: 1,
meal_name: "test-meal",
protein: "20",
carbs: "10",
fats: "8"
};
return supertest(app)
.post("/api/meals")
.set("Authorization", helpers.makeAuthHeader(testUser))
.send(newMeal)
.expect(201)
.expect(res => {
expect(res.body).to.have.property("meal_id");
expect(res.body.user_id).to.eql(newMeal.user_id);
expect(res.body.meal_name).to.eql(newMeal.meal_name);
expect(res.body.protein).to.eql(newMeal.protein);
expect(res.body.carbs).to.eql(newMeal.carbs);
expect(res.body.fats).to.eql(newMeal.fats);
expect(res.headers.location).to.eql(
`/api/meals/${res.body.meal_id}`
);
})
.expect(res =>
db
.from("meal_log")
.select("*")
.where("meal_id", res.body.meal_id)
.first()
.then(row => {
expect(row).to.have.property("meal_id");
expect(row.meal_name).to.eql(newMeal.meal_name);
expect(row.protein.toString(10)).to.eql(newMeal.protein);
expect(row.carbs.toString(10)).to.eql(newMeal.carbs);
expect(row.fats.toString(10)).to.eql(newMeal.fats);
})
);
});
});
});
});
describe(`GET /api/meals`, () => {
context(`Given there are no meals in the db`, () => {
beforeEach("insert users and meals", () =>
helpers.seedUsers(db, testUsers)
);
const testUser = testUsers[0];
const user_id = testUser.user_id;
const user = { user_id };
it("GET /api/meals responds with 200 and an empty list", () => {
return supertest(app)
.get("/api/meals")
.set("Authorization", helpers.makeAuthHeader(testUser))
.send(user)
.expect(200, []);
});
});
context("Given there are meals in the db", () => {
beforeEach("insert meals", () =>
helpers.seedMeals(db, testUsers, testMeals)
);
const testUser = testUsers[0];
const user_id = testUser.user_id;
const user = { user_id };
const userMeals = testMeals.filter(meal => meal.user_id === user_id);
const expectedMeals = userMeals.map(meal =>
helpers.makeExpectedMeal(testUser, meal)
);
it("GET /api/meals responds with 200 and the users meals", () => {
return supertest(app)
.get("/api/meals")
.set("Authorization", helpers.makeAuthHeader(testUser))
.send(user)
.expect(200)
.expect(expectedMeals);
});
});
context("Given an xss attack meal", () => {
const testUser = testUsers[0];
const user_id = testUser.user_id;
const user = { user_id };
const { maliciousMeal, expectedMeal } = helpers.makeMaliciousMeal(
testUser
);
beforeEach("seed malicious meal", () => {
helpers.seedMeals(db, testUsers, [maliciousMeal]);
});
it(`removes xss attack content`, () => {
return supertest(app)
.get(`/api/meals/`)
.set("Authorization", helpers.makeAuthHeader(testUser))
.send(user)
.expect(200, [expectedMeal]);
});
});
});
});
context("/api/meals/:id", () => {
describe("GET /api/meals/:id", () => {
const testUser = testUsers[0];
const { maliciousMeal, expectedMeal } = helpers.makeMaliciousMeal(
testUser
);
context("Given there are no meals in the db", () => {
beforeEach("insert users", () => {
helpers.seedUsers(db, testUsers);
});
const testUser = testUsers[0];
it(`Responds with 404 meal not found`, () => {
const mealId = 1;
return supertest(app)
.get(`/api/meals/${mealId}`)
.set("Authorization", helpers.makeAuthHeader(testUser))
.expect(404, { error: `Meal not found` });
});
});
context("Given there are meals in the db", () => {
beforeEach("insert meals", () =>
helpers.seedMeals(db, testUsers, testMeals)
);
const testUser = testUsers[0];
it("Responds with 200 and a meal", () => {
const mealId = 1;
const expectedMeal = helpers.makeExpectedMeal(
testUser,
testMeals[mealId - 1]
);
return supertest(app)
.get(`/api/meals/${mealId}`)
.set("Authorization", helpers.makeAuthHeader(testUser))
.expect(200, expectedMeal);
});
it("Responds with 400 meal not found", () => {
const mealId = 100;
return supertest(app)
.get(`/api/meals/${mealId}`)
.set("Authorization", helpers.makeAuthHeader(testUser))
.expect(404, { error: `Meal not found` });
});
});
context("Given an xss attack meal", () => {
beforeEach("seed malicious meal", () => {
helpers.seedMeals(db, testUsers, [maliciousMeal]);
});
it(`removes xss attack content`, () => {
const testUser = testUsers[0];
return supertest(app)
.get(`/api/meals/${maliciousMeal.meal_id}`)
.set("Authorization", helpers.makeAuthHeader(testUser))
.expect(200, expectedMeal);
});
});
});
describe("GET /api/meals/:id/foods", () => {
const testUser = testUsers[0];
const { maliciousMeal, expectedMeal } = helpers.makeMaliciousMeal(
testUser
);
const { maliciousFood, expectedFood } = helpers.makeMaliciousFood(
testUser,
maliciousMeal.meal_id
);
context("Given no meals in db", () => {
beforeEach("seed users", () => helpers.seedUsers(db, testUsers));
const testUser = testUsers[0];
it("returns 404 meal not found", () => {
return supertest(app)
.get("/api/meals/1/foods")
.set("Authorization", helpers.makeAuthHeader(testUser))
.expect(404, { error: "Meal not found" });
});
});
context("Given there are meals in db", () => {
beforeEach("seed tables", () =>
helpers.seedMacroFyTables(db, testUsers, testMeals, testFoods)
);
const testUser = testUsers[0];
it("responds with 200 and the meals foods", () => {
const mealId = 1;
const expectedFoods = helpers.makeExpectedMealFoods(
mealId,
testFoods
);
return supertest(app)
.get(`/api/meals/${mealId}/foods`)
.set("Authorization", helpers.makeAuthHeader(testUser))
.expect(200, expectedFoods);
});
});
context("Given xss attack foods", () => {
beforeEach("seed tables", () =>
helpers.seedMacroFyTables(
db,
testUsers,
[maliciousMeal],
maliciousFood
)
);
it("removes xss content", () => {
const testUser = testUsers[0];
return supertest(app)
.get(`/api/meals/${maliciousMeal.meal_id}/foods`)
.set("Authorization", helpers.makeAuthHeader(testUser))
.send(testUser)
.expect(200, expectedFood);
});
});
});
describe("DELETE /api/meals/:id", () => {
context("Given there are meals in the db", () => {
beforeEach("seed users and meals", () =>
helpers.seedMeals(db, testUsers, testMeals)
);
const testUser = testUsers[0];
it("responds with 204 removed article", () => {
const deletedMealId = 2;
const expectedMeals = testMeals.filter(
meal => meal.meal_id !== deletedMealId
);
return supertest(app)
.delete(`/api/meals/${deletedMealId}`)
.set("Authorization", helpers.makeAuthHeader(testUser))
.expect(204)
.expect(res =>
db
.from("meal_log")
.select("*")
.then(meals => {
expect(meals).to.eql(expectedMeals);
})
);
});
it("responds with 404 not found", () => {
const deletedMealId = 123;
return supertest(app)
.delete(`/api/meals/${deletedMealId}`)
.set("Authorization", helpers.makeAuthHeader(testUser))
.expect(404, { error: "Meal not found" });
});
});
context("Given there are no meals in the db", () => {
beforeEach("seed users", () => helpers.seedUsers(db, testUsers));
const testUser = testUsers[0];
it("responds with 404 meal not found", () => {
const deletedMealId = 1;
return supertest(app)
.delete(`/api/meals/${deletedMealId}`)
.set("Authorization", helpers.makeAuthHeader(testUser))
.expect(404, { error: "Meal not found" });
});
});
});
});
});
|
import React from "react"
import { Typography } from "@material-ui/core"
const TotalWalletValue = props => {
const USD_SUM = props.sum
//Converter functions are passed down from index.js to keep conversion the same
const EUR_SUM = props.convertUSDtoEUR(USD_SUM)
const CHF_SUM = props.convertUSDtoCHF(USD_SUM)
//----------------------------------------------------------------
//Easy access to change the string being displayed
const USD_display = "Total value: " + USD_SUM + "USD"
const EUR_display = "Total value: " + EUR_SUM + "EUR"
const CHF_display = "Total value: " + CHF_SUM + "CHF"
return (
<Typography align="center" color="primary" style={{ fontSize: "1.2rem" }}>
{console.log("val:" + props.selectedValue)}
{props.selectedValue === "USD"
? USD_display
: props.selectedValue === "EUR"
? EUR_display
: CHF_display}
</Typography>
)
}
export default TotalWalletValue
|
import React from "react";
import svgLogo from "assets/404.svg";
const PageNotFound = () => {
return (
<div className="page-not-found">
<div className="text-center">
<img src={svgLogo} alt="" />
<p className="mt-5">
Welcome to page 404! You are here because you entered the address of a
page <br />
that no longer exists or has been moved to another address
</p>
</div>
</div>
);
};
export default PageNotFound;
|
WMS.module('Articles', function(Articles, WMS, Backbone, Marionette, $, _) {
Articles.Router = Marionette.AppRouter.extend({
appRoutes: {
"articles(/filter/criterion::criterion)": "listArticles",
"articles/:id": "showArticle"
},
header:'articles',
permissionsMap: {
'listArticles':'article:list',
'showArticle':'article:list'
}
});
var controllers = Articles.controllers = {}
, API = {
listArticles: function(criterion) {
if (controllers.list === undefined) {
controllers.list = new Articles.List.Controller();
}
controllers.list.listArticles(criterion);
},
showArticle: function(id) {
if (controllers.show === undefined) {
controllers.show = new Articles.Show.Controller();
}
controllers.show.showArticle(parseInt(id));
}
};
WMS.on('articles:list', function() {
WMS.navigate('articles');
});
WMS.on('articles:filter', function(criterion) {
if (criterion) {
WMS.navigate('articles/filter/criterion:' + criterion);
} else {
WMS.navigate('articles');
}
});
WMS.on('articles:show', function(id) {
WMS.navigate('articles/' + id);
});
WMS.on('before:start', function() {
new Articles.Router({
controller: API
});
});
});
|
// create line graph with chart.js
function createLineChart(data) {
var ctx = $("#lineChart").get(0).getContext("2d");
var myLineChart = new Chart(ctx).Line(data, {
datasetFill: false,
responsive: true
});
}
// create pie chart with chart.js
function createPieChart(data) {
var ctx = $("#pieChart").get(0).getContext("2d");
var myPieChart = new Chart(ctx).Pie(data);
}
|
const Command = require('../../structures/Command');
class Clothes extends Command {
constructor (...args) {
super(...args, {
name: 'c',
aliases: ['clothes', 'ciuchy'],
perms: true,
args: ['Component ID', 'Drawable ID', 'Texture ID', 'Palette ID']
});
}
run (player, command, args) {
const [ componentId, drawableId, textureId, paletteId ] = args;
player.setClothes(parseInt(componentId), parseInt(drawableId), parseInt(textureId), parseInt(paletteId));
}
}
module.exports = Clothes;
|
class MyArray {
constructor(...startingValues) {
this.length = 0;
//spread
this.push(...startingValues);
}
// ... - рест оператор
push(...incomingValues) {
for (const value of incomingValues) {
this[this.length++] = value;
}
return this.length;
}
unshift(...incomingValues) {
for (let i = this.length - 1; i >= 0; i--) {
this[i + incomingValues.length] = this[i];
}
for (let i = 0; i < incomingValues.length; i++) {
this[i] = incomingValues[i];
}
this.length += incomingValues.length;
return this.length;
}
[Symbol.iterator]() {
let i = 0;
const context = this;
return {
next() {
return {
value: context[i++],
done: i < context.length,
};
},
};
}
}
const myArr1 = new MyArray(1, 2, 3, 4);
for (const value of myArr1) {
console.log(value);
}
|
define(['src/FizzBuzz'], function () { return FizzBuzzTest() });
function FizzBuzzTest() {
describe("Should return Fizz when:", function () {
it("is the number three", function () {
expect("Fizz").toEqual(FizzBuzz().transform(3));
});
it("is a three multiple", function () {
expect("Fizz").toEqual(FizzBuzz().transform(6));
})
});
describe("Should return Buzz when:", function () {
it("is the number five", function () {
expect("Buzz").toEqual(FizzBuzz().transform(5));
});
it("is a five multiple", function () {
expect("Buzz").toEqual(FizzBuzz().transform(10));
})
});
describe("Should return the number when:", function () {
it("is not a multiple of five or three", function () {
expect("2").toEqual(FizzBuzz().transform(2));
});
});
describe("Should return FizzBuzz when:", function () {
it("is a multiple of five or three", function () {
expect("FizzBuzz").toEqual(FizzBuzz().transform(15));
});
});
}
|
onload=function(){
var startText;
var restartText;
var welcome;
var gameover;
var spend=0;
var str="";
var bootState = function(game){
this.preload=function(){
game.load.image('loading','assets/preloader.gif');
};
this.create=function(){
game.state.start('loader');
};
}
var loaderState=function(game){
var progressText;
this.init=function(){
var sprite=game.add.image(game.world.centerX,game.world.centerY,'loading');
sprite.anchor={x:0.5,y:0.5};
progressText=game.add.text(game.world.centerX,game.world.centerY+30,'0%',{fill:'#fff',fontSize:'16px'});
progressText.anchor={x:0.5,y:0.5};
};
this.preload=function(){
game.load.image('welcome','assets/background.png');
game.load.image('gameover','assets/background2.png');
game.load.spritesheet('card','./assets/card.png',700/4,787/3,12);
game.load.image('timing','assets/timing.png')
game.load.onFileComplete.add(function(progress){
progressText.text=progress+'%';
});
};
this.create=function(){
if (progressText.text=="100%") {
game.state.start('welcome');
}
};
}
var welcomeState = function(game){
this.init=function(){
game.scale.pageAlignHorizontally=true;
game.scale.pageAlignVertically=true;
game.scale.scaleMode=Phaser.ScaleManager.SHOW_ALL;
}
this.create=function(){
welcome=game.add.image(0,0,'welcome');
welcome.scale.setTo(0.7,0.6);
startText=game.add.text(game.world.centerX,game.world.centerY,'Click anywhere on the screen to start',{fill:'#fff',fontSize:'16px'});
startText.anchor={x:0.5,y:0.5};
game.input.onDown.addOnce(Down, this);
};
}
var gameoverState = function(game){
this.create=function(){
gameover=game.add.image(0,0,'gameover');
gameover.scale.setTo(0.7,0.6);
restartText=game.add.text(game.world.centerX,game.world.centerY,'Click anywhere on the screen to restart',{fill:'#fff',fontSize:'16px'});
restartText.anchor={x:0.5,y:0.5};
var Text=game.add.text(0,0,'游戏成绩:' + spend + '秒',{fill:'#DC143C',fontSize:'21px'})
Text.x=game.world.centerX - Text.width/2;
Text.y=game.world.centerY+Text.height*1.5;
var Text=game.add.text(0,0,'获得称号:' + str,{fill:'#DC143C',fontSize:'21px'})
Text.x=game.world.centerX - Text.width/2;
Text.y=game.world.centerY+Text.height*1.5*2;
game.input.onDown.addOnce(reDown, this);
};
}
var times=0;
var bpre;
var bcur;
var pre=-1;
var cur=-1;
var boolean=false;
var timing;
var gameState = function(game){
this.init=function(){
game.scale.pageAlignHorizontally=true;
game.scale.pageAlignVertically=true;
game.scale.scaleMode=Phaser.ScaleManager.SHOW_ALL;
}
var bmd=[];
var block=[];
var card=[];
var stime=0;
this.create=function(){
//以下代码为获取游戏界面大小
var width=game.world.width/4;
var height=game.world.height/4;
//以下代码为产生贴图数据
for (var i = 0; i < 16; i++) {
bmd[i] = game.add.bitmapData(width,height);
bmd[i].ctx.beginPath();
bmd[i].ctx.rect(0, 0, width, height);
bmd[i].ctx.strokeStyle = "lightgray";
bmd[i].ctx.strokeRect(0,0,width,height);
bmd[i].ctx.fillStyle='dimgray';
}
//以下代码为生成贴图
for (var i = 0; i < bmd.length; i++) {
bmd[i].ctx.fill();
bmd[i].ctx.stroke();
block[i]=game.add.sprite(0, 0, bmd[i]);
block[i].inputEnabled = true;
block[i].tint=0xffffff;//778899
}
//以下代码为层次排列
for (var i = 1; i < block.length; i++) {
if (i%4==0) {
block[i].x=block[0].x;
block[i].y=block[i-1].y+block[i-1].height;
} else {
block[i].x=block[i-1].x+block[i-1].width;
block[i].y=block[i-1].y
}
}
//以下代码为随机排列
var x=0;
var y=0;
var r=0;
var d=0;
for(var i = 0 ; i < block.length; i++){
if (i<8) {block[i].flag=i;}
if (i>7) {block[i].flag=i-8;}
r=GetRandomNum(i,block.length-1);
d=GetRandomNum(i,block.length-1);
x=block[d].x;
y=block[d].y;
block[d].x=block[r].x;
block[d].y=block[r].y;
block[r].x=x;
block[r].y=y;
}
for (var i = 0; i < block.length; i++) {
card[i]=game.add.sprite(block[i].x,block[i].y,'card');
card[i].scale.setTo(0.45);
card[i].frame = block[i].flag;
card[i].alpha = 0;
}
timing = game.add.sprite(0,0,'timing');
timing.x=game.world.centerX - timing.width/2;
timing.y=timing.height;
};
this.update=function(){
for (var i = 0; i < block.length; i++) {
block[i].events.onInputDown.add(onDown, this);
}
var j=0;
for (var i = 0; i < block.length; i++) {
if (block[i].tint==0xff7777) {j++}
if (j==block.length) {
spend = stime;
var sec=0;
game.time.events.loop(Phaser.Timer.SECOND, function(){
sec+=1;
if (sec==1) {
game.state.start('gameover');
}
}, this);
}
}
var t=0;
game.time.events.loop(Phaser.Timer.SECOND, function(){
t=t+1;
stime=t;
if (t<=10) {
str="速记能手"
} else if (t>10 & t < 20) {
str="眼力达人"
} else {
str="无名小卒"
}
if (timing.width <= 0) {
timing.kill();
str="出师未捷"
stime=0;
game.state.start('gameover');
}
}, this);
timing.width-=0.1;
}
function onDown(block){
var i=0;
for (var i = 0; i < 16; i++) {
card[i].alpha=0;
if (block.x==card[i].x & block.y==card[i].y) {
card[i].alpha=1;
}
}
times+=1;
if (times%2==1) {
cur=block.flag;
bcur=block;
} else {
pre=cur;
bpre=bcur;
cur=block.flag;
bcur=block;
if (pre==cur) {
if (bpre==bcur) {return;}
block.flag="";
bpre.tint=0xff7777;
block.tint=0xff7777;
bpre.inputEnabled = false;
block.inputEnabled = false;
for (var i = 0; i < 16; i++) {
card[i].alpha=0;
}
}
}
}
}
function Down(){
startText.destroy();
game.state.start('main');
}
function reDown(){
restartText.destroy();
game.state.start('main');
}
var game=new Phaser.Game(320,480,Phaser.CANVAS);
game.state.add('boot',bootState);
game.state.add('loader',loaderState);
game.state.add('welcome',welcomeState);
game.state.add('main',gameState);
game.state.add('gameover',gameoverState);
game.state.start('boot');
}
function GetRandomNum(Min,Max){
var Range = Max - Min;
var Rand = Math.random();
return(Min + Math.round(Rand * Range));
}
|
import {
POST_USER_ANSWERS_QUESTION_REQUEST,
POST_USER_ANSWERS_QUESTION_SUCCESS,
POST_USER_ANSWERS_QUESTION_FAILURE,
GET_USER_ANSWERS_QUESTION_REQUEST,
GET_USER_ANSWERS_QUESTION_SUCCESS,
GET_USER_ANSWERS_QUESTION_FAILURE,
} from '../constants/userAnswersQuestion.constants';
import api from '../services/api';
//SALVE USER QANSWER QUESTION
export const saveUserAnswersQuestion = (idUser, idQuestion, answer, check) => (dispatch) => {
dispatch({ type: POST_USER_ANSWERS_QUESTION_REQUEST });
api.post('/saveUserAnswers', { idUser, idQuestion, answer, check })
.then(() => {
dispatch({ type: POST_USER_ANSWERS_QUESTION_SUCCESS });
})
.catch((error) => {
const { response: err } = error;
const message = err && err.data ? err.data.message : 'Erro desconhecido';
dispatch({ type: POST_USER_ANSWERS_QUESTION_FAILURE, message });
});
}
//GET USER QANSWER QUESTION
export const getAnswerQuestion = (idUser, idQuestion) => (dispatch) => {
dispatch({ type: GET_USER_ANSWERS_QUESTION_REQUEST });
api.post('/userAnswersQuestion', { idUser, idQuestion })
.then((res) => {
const { data } = res;
dispatch({ type: GET_USER_ANSWERS_QUESTION_SUCCESS, data });
})
.catch((error) => {
const { response: err } = error;
const message = err && err.data ? err.data.message : 'Erro desconhecido';
dispatch({ type: GET_USER_ANSWERS_QUESTION_FAILURE, message });
});
};
|
(function () {
'use strict';
angular.module('events.admin')
.directive('manageEvent', manageEventDirective);
function manageEventDirective () {
ManageEventDirectiveCtrl.$inject = ['$scope', '$log'];
return {
restrict: 'A',
templateUrl: 'partials/admin/manage-event/manage-an-event.html',
controller: ManageEventDirectiveCtrl,
controllerAs: 'manageEvent'
};
function ManageEventDirectiveCtrl ($scope, $log) {
var manageEvent = this;
}
}
})();
|
const fs = require('fs');
const data = new Float32Array([
0, 0, 0, 0,
150, 0, 1, 0,
0, 150, 0, 1
]);
fs.writeFile('data.data', data, { mode: null }, console.log);
|
import React, { Component } from "react";
import { Route } from "react-router-dom";
import { connect } from "react-redux";
import CollectionOverview from "../../components/collection-overview/CollectionOverview";
import CollectionPage from "../collection/CollectionPage";
import { fetchCollectionsStartAsync } from "../../redux/shop/shop.actions";
import WithSpinner from "../../components/with-spinner/WithSpinner";
const CollectionsOverviewWithSpinner = WithSpinner(CollectionOverview);
const CollectionPageWithSinner = WithSpinner(CollectionPage);
class Shop extends Component {
componentDidMount() {
const {fetchCollectionsStartAsync} = this.props;
fetchCollectionsStartAsync();
}
render() {
const { match,isCollectionFetching,isCollectionLoaded } = this.props;
return (
<div className="shop-page">
<Route
exact
path="/shop"
render={props => (
<CollectionsOverviewWithSpinner isLoading={!isCollectionLoaded} {...props} />
)}
/>
<Route
path={`${match.path}/:collectionId`}
render={props => (
<CollectionPageWithSinner isLoading={!isCollectionLoaded} {...props} />
)}
/>
</div>
);
}
}
const mapStateToProps = state => {
return {
isCollectionFetching: state.shop.isFetching,
isCollectionLoaded: !!state.shop.collections
};
};
const mapDispatchToProps = dispatch => {
return {
fetchCollectionsStartAsync: () => dispatch(fetchCollectionsStartAsync())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Shop);
|
import Row from "../row";
import "./board.css";
function Board() {
const arr = new Array(8).fill().map((a, i) => <Row rowNumber={i} />);
return arr;
}
export default Board;
|
// External libraries
const mongoConnection = require('rps-mongoconnection-module');
module.exports = mongoConnection;
|
module.exports = function(collection){
collection.find({}).toArray(function(err,res){
if (err) {return console.log(err)}
console.log(res);
});
}
|
const Command = require("../handlers/command.js");
module.exports = class extends Command {
constructor(client, filePath) {
super(client, filePath, {
name: "commands",
aliases: ["cmds"]
});
}
execute(message) {
const prefix = this.client.config.prefix;
message.reply('شوف خاصك :wink:');
message.author.send(`\`\`\`md\nCommands for ${this.client.user.username}\n---------------------------\n`
+`> ${prefix}create\n" + "لتشغيل قيف اواي\n`
+`> ${prefix}delete\n" + "حذف القيف اواي السابق\n`
+`> ${prefix}draw\n" + "فرض التعادل \n`
+`> ${prefix}redraw\n" + "اعادة اختيار فائز\n`
+`> ${prefix}invite\n" + "دعوة البوت الى سيرفرك\n`
+`> ${prefix}server\n" + "سيرفر البوت الاصلي\n`
+`> ${prefix}ping\n" + "سرعة اتصال البوت\`\`\``);
}
};
|
import React from 'react';
const Loading = React.memo(() => {
return (
<div className='italic'>
Loading...
</div>
)
})
export default Loading
|
import React, {useState} from 'react';
function SinglePostHooks(props) {
const post = props.post
const [state, setState ] = useState({
subject: props.post.get("subject"),
body: props.post.get("body"),
by: props.post.get("by"),
like: props.post.get("like"),
deleted: props.post.get("deleted"),
showinput: false
})
const onLike = () => {
if(post.get("like") === 'Like'){
post.set({like: 'Unlike'});
}
else{
post.set({like: 'Like'});
}
setState({...state, like: post.get("like")});
}
const onEdit = () => {
setState({...state, showinput: true});
}
const onDelete = () => {
post.set({deleted: true});
setState({...state, deleted: true});
}
const updateSubject = e => {
setState({...state, subject: e.target.value})
}
const updateBody = e => {
setState({...state, body: e.target.value})
}
const updateBy = e => {
setState({...state, by: e.target.value})
}
const onUpdate = () => {
post.set({subject: state.subject,
body: state.body,
by: state.by
});
setState({...state, showinput: false});
}
const onCancel = () => {
setState({ ...state,
subject: post.get("subject"),
body: post.get("body"),
by: post.get("by"),
showinput:false
});
}
if(state.showinput) {
return (
<tr>
<td><input className="form-control subject-input" value={state.subject} onChange={updateSubject} /></td>
<td><input className="form-control body-input" value={state.body} onChange={updateBody} /></td>
<td><input className="form-control by-input" value={state.by} onChange={updateBy} /></td>
<td><button className="btn btn-success like-post" onClick={onLike}>{state.like}</button>
<button className="btn btn-warning update-post" onClick={onUpdate}>Update</button>
<button className="btn btn-danger cancel" onClick={onCancel}>Cancel</button>
</td>
</tr>
);
}
else if(!state.deleted){
return(
<tr>
<td><span className="subject">{state.subject}</span></td>
<td><span className="body">{state.body}</span></td>
<td><span className="by">{state.by}</span></td>
<td><button className="btn btn-success like-post" onClick={onLike}>{state.like}</button>
<button className="btn btn-warning edit-post" onClick={onEdit}>Edit</button>
<button className="btn btn-danger delete-post" onClick={onDelete}>Delete</button>
</td>
</tr>
);
}
else{
return null;
}
}
export default SinglePostHooks;
|
const readCourses = (router, asyncHandler, Course, User) => {
router.get('/courses', asyncHandler(async (req, res) => {
// find all courses, excluding certain attributes
const courses = await Course.findAll({
attributes: { exclude: ['createdAt', 'updatedAt'] },
// include associated User as matching alias 'userInfo', excluding certain attributes
include: {
model: User,
attributes: {
exclude: ['password', 'createdAt', 'updatedAt']
},
}
});
// send all courses
res.status(200).json(courses);
}));
};
module.exports = readCourses;
|
import React, { useState } from "react";
import { Route, Switch, BrowserRouter as Router } from "react-router-dom";
import Login from "./components/Login";
import Signup from "./components/Signup";
import Dashboard from "./components/dashboard";
import NotFound from "./components/NotFound";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
const App = () => {
const [loggedOut, setLoggedOut] = useState(true);
return (
<Router>
<ToastContainer />
<Switch>
<Route
exact
path="/"
render={(props) => <Login {...props} loggedOut={loggedOut} setLoggedOut={setLoggedOut} />}
/>
<Route
exact
path="/signup"
render={(props) => <Signup {...props} loggedOut={loggedOut} setLoggedOut={setLoggedOut} />}
/>
<Route
exact
path="/dashboard"
render={(props) => <Dashboard {...props} loggedOut={loggedOut} setLoggedOut={setLoggedOut} />}
/>
<Route component={NotFound} />
</Switch>
</Router>
);
};
export default App;
|
import React , { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity
} from 'react-native' ;
class Layout extends Component {
constructor() {
super()
this.state = {
inputText: "",
calculationText: ""
}
this.operations = ['C' ,'/' , 'X' , '-' , '+']
}
calculateResult(){
const text = this.state.inputText
//parse Text
this.setState({
calculationText: eval(text)
})
}
validate(){
const text = this.state.inputText
switch(text.slice(-1)){
case '+':
case '-':
case '*':
case '/':
return false
}
return true
}
buttonPressed(text) {
if(text == '='){
return this.validate() && this.calculateResult()
}
this.setState({
inputText: this.state.inputText+text
})
}
operate (operations) {
switch(operations){
case 'C':
const text = this.state.inputText.split('')
text.pop()
this.setState({
inputText: text.join('')
})
break
case '+':
case '-':
case '*':
case '/':
const lastChar = this.state.inputText.split('').pop()
if(this.operations.indexOf(lastChar) > 0) return
if(this.state.text == "") {
return
}
this.setState({
inputText: this.state.inputText + operations
})
}
}
render() {
let elems = [[7,8,9] , [4,5,6] , [1,2,3] ,['.',0,'=']] , rows = []
//Number Buttons
for (let i=0; i < 4; i++){
let row = []
for(let j=0; j < 3; j++){
row.push(<TouchableOpacity key={elems[i][j]} onPress={() => this.buttonPressed(elems[i][j])} style = {styles.btn}>
<Text style ={styles.btnText}>{elems[i][j]}</Text>
</TouchableOpacity>)
}
rows.push(<View key={i} style = {styles.row}>{row}</View>)
}
//Operation Buttons
let ops = []
for(let i=0; i<5; i++){
ops.push(<TouchableOpacity key={this.operations[i]} onPress={() => this.operate(this.operations[i])} style = {styles.btn}>
<Text style ={[styles.btnText, styles.white]}>{this.operations[i]}</Text>
</TouchableOpacity>
)
}
return (
<View style = {styles.container}>
<View style = {styles.input}>
<Text style={styles.inputText}>{this.state.inputText}</Text>
</View>
<View style = {styles.calculation}>
<Text style = {styles.calculationText}>{this.state.calculationText}</Text>
</View>
<View style = {styles.buttons}>
<View style = {styles.numbers}>{rows}</View>
<View style = {styles.operations}>{ops}</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex:1
},
inputText:{
fontSize: 30,
color: 'black'
},
btnText: {
fontSize: 34,
color: 'white'
},
white: {
color: 'white'
},
btn:{
flex: 1,
alignItems: 'center',
alignSelf: 'stretch',
justifyContent: 'center'
},
calculationText:{
fontSize: 38,
color: 'black'
},
row: {
flexDirection: 'row',
flex: 1,
justifyContent: 'space-around',
alignItems: 'center'
},
input: {
flex: 2,
backgroundColor : 'white',
justifyContent: 'center',
alignItems: 'flex-end'
},
calculation:{
flex: 1,
backgroundColor: 'white',
justifyContent: 'center',
alignItems: 'flex-end'
},
buttons: {
flex: 7,
flexDirection: 'row'
},
numbers: {
flex: 3,
backgroundColor: '#434343'
},
operations: {
flex: 1,
backgroundColor: '#636363',
justifyContent: 'space-around',
alignItems: 'stretch'
}
})
export default Layout;
|
document.onkeyup = KeyCheck;
var tbox = document.getElementById('a_tbox')
var tetris = document.createElement('canvas');
tetris.height=300;
tetris.width=600;
document.body.appendChild(tetris);
board=
[
[0,0,0,0,0,0,0,0,0,0,],//a
[0,0,0,0,0,0,0,0,0,0,],
[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,]
];
//remove quotation marks
//rotatedtimes==r
//piece==p
//intervalID ==i
//lines ==l
//endleft ==x
//endright ==u
//endp ==t
//(db==j)
var i;
choosep()
t = 0
u =0
x =0
r = 0
speed=200
y=0
l=0
start()
//convert()
//pause()
function start2()
{
convert()
pause()
}
function pause(){i = setInterval("caws()", speed)}
//functions
function choosep()
{
p=Math.floor(Math.random()*7)
//starts at 0
//p=3 //debugging //uncomment this line
//p=6
}
function convert()
{
a2=a*30
b2=b*30
c2=c*30
d2=d*30
f2=f*30
g2=g*30
h2=h*30
j2=j*30
a7=a;b7=b
plotspecified()
a7=c;b7=d
plotspecified()
a7=f;b7=g
plotspecified()
a7=h;b7=j
plotspecified()
}
function unplot()
{
a7=a;b7=b
unplotspecified()
a7=c;b7=d
unplotspecified()
a7=f;b7=g
unplotspecified()
a7=h;b7=j
unplotspecified()
}
function start()
{
if (p ==1)
{
a=4
b=0
c=5
d=0
f=4
g=1
h=5
j=1
}
if (p ==2)
{
a=4
b=0
c=4
d=1
f=5
g=1
h=6
j=1
}
if (p ==3)
{
a=6
b=0
c=4
d=1
f=5
g=1
h=6
j=1
}
if (p ==0)
{
a=5
b=0
c=4
d=1
f=5
g=1
h=6
j=1
}
if (p ==4)
{
a=4
b=0
c=5
d=0
f=5
g=1
h=6
j=1
}
if (p ==5)
{
a=5
b=0
c=6
d=0
f=4
g=1
h=5
j=1
}
if (p ==6)
{
a=4
b=0
c=5
d=0
f=6
g=0
h=7
j=0
}
}
function down()
{
++b
++d
++g
++j
}
function ifend()
{ //do we even need function ?
b3=b+1
d3=d+1
g3=g+1
j3=j+1
if (board[b3][a] == 1)
{
t =1//make more like caws one
}
else if (board[d3][c] == 1)
{
t=1
}
else if (board[g3][f] == 1)
{
t=1
}
else if (board[j3][h] == 1)
{
t = 1
}
}
function caws()/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{
//rotatep()
checkend()
end=0
if(b>18){end=1}
if(d>18){end=1}
if(g>18){end=1}
if(j>18){end=1}
if(end==0)
{
ifend()
if (t == 0)
{
unplot()////////////////////
down() ////////////////////
convert()
}
else
{
board [b][a] = 1
board [d][c] = 1
board [g][f] = 1
board [j][h] = 1
newp()
t=0
}
}
else
{
board [b][a] = 1
board [d][c] = 1
board [g][f] = 1
board [j][h] = 1
newp()
t=0
}
}
function pleft()
{
ifleft()
if (x ==0)
{
unplot()
--a
--c
--f
--h
convert()
}
x =0
}
function pright()
{
ifright()
if (u ==0)
{
unplot()
++a
++c
++f
++h
convert()
}
u = 0
}
function newp()
{
choosep()
start()
convert()
r = 0
}
function ifright()
{ //do we even need function ?
a3=a+1
c3=c+1
f3=f+1
h3=h+1
if (board[b][a3] == 1)
{
u =1
}
else if (board[d][c3] == 1)
{
u=1
}
else if (board[g][f3] == 1)
{
u=1
}
else if (board[j][h3] == 1)
{
u = 1
}
if(a3==10){u=1}
if(c3==10){u=1}
if(f3==10){u=1}
if(h3==10){u=1}
}
function ifleft()
{
a4=a-1
c4=c-1
f4=f-1
h4=h-1
if (board[b][a4] == 1)
{
x =1
}
else if (board[d][c4] == 1)
{
x=1
}
else if (board[g][f4] == 1)
{
x=1
}
else if (board[j][h4] == 1)
{
x = 1
}
if(a4==-1){x=1}
if(c4==-1){x=1}
if(f4==-1){x=1}
if(h4==-1){x=1}
}
function rotatep()
{
unplot()
if (p ==2)
{
if (r == 3)
{
//++a
a=f-1
b=g-1
c=f-1
d=g
h=f+1
j=g
r = 99////////////////////
}
if (r == 2)
{
//++a
a=a-2
--c
++d
++h
--j
r = 3
}
if (r == 1)
{
//++a
++a
b=b+2
c=c+2
++d
++f
--j
r = 2
}
if (r == 0)
{
//++a
/*
++c
d=d-2
--f
g=g-2
h=h-2
*/
a=a+2
++c
--d
--h
++j
//goes into bottom
r = 1
}
}//end p == 2 (not 1)!!
if(p == 3)
{
if(r == 3)
{
--c
++d
a=a+2
--j;++h
r = 98
}
if(r == 2)
{
b=b-2
++c
--d
--h
++j
r = 3
}
if(r == 1)
{
a=a-2
--c;--d
++h;++j
r = 2
}
if(r == 0)
{
b=b+2
++c
++d
--h
--j
r = 1
}
if(r==98){r=0}
}//end p==3
if(p == 5)
{
if(r == 1)
{
f=f-2
d=d-2
r = 99
}
if(r == 0)
{
f=f+2
d=d+2
r=1
}
}
if(p == 4)
{
if(r == 1)
{
b=b-2
h=h+2
r =99//here
//r = 0 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
if(r == 0)//here
{
b=b+2
h=h-2
r=1
}
//
}
if(p==6)
{
if(r == 1)
{
--a
++b
++f
--g
h=h+2
j=j-2
r = 99
}
if(r == 0)
{
++a
--b
--f
++g
h=h-2
j=j+2
r = 1
}
}
//
if(p == 0)
{
if(r == 3)
{
++a
--b
++h
++j
--c
--d
r = 99
}
if(r == 2)
{
--h
--j
r = 3
}
if(r == 1)
{
--a
++b
r = 2
}
if(r == 0)
{
++c
++d
r = 1
}
}//==0
if(r==99){r=0}
convert()
}//end function
function checkend()
{
v=0
//w=18///////
s=0
z=0;y=0;//some things might not be set to 0
for(w=0;w<20;++w)//if not, put w=18 cck
{
for(s=0,v=0,z=0,y=0;s==0;++y)
{
if (y==10){s=1}
if(board[w][z]==1){++z}else{s=1}
if(z==10){v=1;s=1}
if(v==1){r=w;++l;movedown()}
if(v==1){++l}
}
}
////
var txt2 = l;
var box1 = document.getElementById('score');
if (box1)
{
box1.value = txt2
}
}
function movedown()
{
for(w=r;w<20;--w){
for(z=0;z<10;++z){
u=w-1
board[w][z]=0;a7=z;b7=w;unplotspecified()
if(board[u][z]==1){board[u][z]=0;board[w][z]=1;a7=z;b7=u;unplotspecified();b7=w;plotspecified()}
}
}
}
function unplotspecified()
{
a8=a7*30
b8=b7*30
example = document.getElementById('tetris');
context = example.getContext('2d');
context.fillStyle = "rgb(255,255,255)";
context.fillRect(a8, b8, 30, 30);
}
function plotspecified()
{
a8=a7*30
b8=b7*30
example = document.getElementById('tetris');
context = example.getContext('2d');
context.fillStyle = "rgb(255,0,0)";
context.fillRect(a8, b8, 30, 30);
}
function KeyCheck(e)
{var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID)
{ case 19:
//document.Form1.KeyName.value = "Pause";
break;
case 37:
pleft();
break;
case 38:
rotatep();
break;
case 39:
pright();
break;
case 40:
caws();
break;
}
}
function speedup(){speed=speed-10;
var txt = speed;
var tbox = document.getElementById('a_tbox');
if (tbox)
{
tbox.value = txt;
}
clearInterval(i);pause()
}
function speeddown(){speed=speed+10;
var txt = speed;
var tbox = document.getElementById('a_tbox');
if (tbox)
{
tbox.value = txt;
}
clearInterval(i);pause()
}
|
function arrayToList(array)
{
var list = null;
for (var i = array.length - 1; i >= 0; i--)
{
list = { value: array[i], rest: list };
}
return list;
}
function arrayToListRec(array, index)
{
var list = {};
if (array[index] == undefined)
{
return null;
}
else
{
list.value = array[index];
list.rest = arrayToListRec(array, index + 1);
return list;
}
}
function listToArray(list)
{
var array = [];
for (var node = list; node; node = node.rest)
{
array.push(node.value);
}
return array;
}
function listToArrayRec(list)
{
var array = [];
if (list.rest == null)
{
return array.concat(list.value);
}
else
{
array.push(list.value);
array = array.concat(listToArrayRec(list.rest));
return array;
}
}
function prepend(value, list)
{
return { value: value, rest: list };
}
function nth(list, index)
{
if (!list)
{
return undefined;
}
else if (index == 0)
{
return list.value;
}
else
{
return nth(list.rest, index - 1);
}
}
function inputArray(count)
{
var array = [];
for (var i = 0; i < count; i++)
{
var element = Number(prompt("Введите " + i + " элемент:"));
if (!isNaN(element))
{
array[i] = element;
}
else
{
throw new Error("Не верные входные данные!!!");
}
}
return array;
}
function execTask3()
{
try
{
var count = Number(prompt("Введите количество элементов массива(целое число):"));
if (!isNaN(count) && count % 1 == 0)
{
var array = inputArray(count);
document.write("Полученные массив: " + array);
document.write("<br>Полученный список: " + arrayToListRec(array, 0));
document.write("<br>Массив: " + listToArrayRec(arrayToListRec(array, 0)));
document.write("<br>Добавлление: " + prepend(20, null));
document.write("<br>Получение 2-ого элемента: " + nth(arrayToListRec(array, 0), 2));
}
else
{
alert("Не верные входные данные!!!");
}
}
catch (e)
{
alert(e.message);
}
}
|
import React, { useContext, useState } from 'react';
import { EmployeeContext } from '../contexts/EmployeeContext';
const AddEmployee = () => {
const { addEmployee } = useContext(EmployeeContext);
const formValue = {
fullname: '', age: '', position: ''
}
const [ form, setForm ] = useState(formValue);
const { fullname, age, position } = form
const handleInput = e => {
const { name, value } = e.target
setForm(prevState => ({
...prevState, [name]: value
}))
}
const submitForm = e => {
e.preventDefault();
addEmployee(fullname, age, position);
}
return (
<>
<form onSubmit={submitForm}>
<div>
<input type="text" placeholder="Enter fullname" name="fullname"
value={fullname} onChange={handleInput}/>
</div>
<div>
<input type="number" placeholder="Enter age" name="age"
value={age} onChange={handleInput}/>
</div>
<div>
<input type="text" placeholder="Enter position" name="position"
value={position} onChange={handleInput}/>
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
</>
);
}
export default AddEmployee;
|
import React, { Component } from 'react';
import { DragSource } from 'react-dnd';
/**
* We use to connect the React DnD event handlers to some node in the component
* We use to pass some knowledge about the dragging state to our component
* With that we inject that special props into the component
* @param connect: DnD documentation the description
* @param monitor: DnD documentation the description
* @returns {{connectDragSource: , isDragging: }}
*/
function collect(connect, monitor) {
return {
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
};
}
/** It describes how the drag source reacts to the drag and drop events.
* @returns {Object}
*/
const widgetSource = {
beginDrag(props) {
// We need the type property to know if we can drop the widget
return {
widgetId: props.id,
type: props.type
}
},
canDrag(props){
return true;
}
};
class Dragboard extends Component {
render() {
const { type, text, connectDragSource, isDragging } = this.props;
const opacity = isDragging? 0.4 : 1;
return connectDragSource(
<div className="col-lg-12 widget-border drag" style={{opacity}}>{text} ({type})</div>
);
}
}
Dragboard.PropTypes = {
id: React.PropTypes.string.isRequired,
type: React.PropTypes.string.isRequired,
text: React.PropTypes.string.isRequired,
connectDragSource: React.PropTypes.func.isRequired,
isDragging: React.PropTypes.func.isRequired
};
// We wrap our component with DragSource to make it draggable.
// DragSource is a higher-order component accepting three required parameter
export default DragSource(props => props.type, widgetSource, collect)(Dragboard);
|
import { convertArrayToTree } from '@/utils/collection';
const getChildMenuByIndex = (menus = [], index = 0) => {
if (!menus.length) return [];
return menus[parseInt(index, 10)].children;
};
export default {
treeMenu(state, getters) {
const convertMenu = state.menu.menuList.map(item => {
item.alias = item.url || '/';
return item;
});
return convertArrayToTree(convertMenu, 'menuCode', 'parentId');
},
// childMenus(state, getters) {
// const convertMenu = state.menu.menuList.map(item => {
// item.alias = item.url || '/';
// return item;
// });
// const treeMenu = convertArrayToTree(convertMenu, 'menuCode', 'parentId');
// return getChildMenuByIndex(treeMenu, state.menu.selectedFirstLevelIndex);
// },
};
|
import data from '../data/data.json';
const initalState = {
itemsList: data,
cart: [],
wishlist: [],
// qty: 0
}
const rootReducer = (state = initalState, action) => {
switch (action.type) {
case 'ADD_TO_CART': {
let itemExistsInCart = state.cart.find( item => item.id === action.item.id);
if(!itemExistsInCart){
return {
...state,
cart: [...state.cart, action.item]
}
}
return{
...state
}
}
case 'ADD_TO_WISHLIST':{
let itemExistsInWishlist = state.wishlist.find( item => item.id === action.item.id);
if(!itemExistsInWishlist){
return {
...state,
wishlist: [...state.wishlist, action.item]
}
}
return{
...state
}
}
case 'ADD_REMOVE_QUANTITY':{
let selectedQty = 'selectedQty'
state.itemsList[action.index][selectedQty]=action.selectedQty;
return {
...state,
itemList: state.itemsList
}
}
case 'REMOVE_FROM_CART': {
let newCart = state.cart.filter( item => item.id !== action.item.id)
return {
...state,
cart: newCart
}
}
default:
return state;
}
}
export default rootReducer;
|
// creating a module
// there are two ways of creating a module
// you can create or chain as many as controllers you want in this single file
/**
* Scope is an object that refers to the application model.
* Definition [Scope]:- is the binding part between ___ and ___
* is an {} with properties and methods
* is available to both view and controller
*/
/**
* Module :- is a container for different parts of your app - containing controllers, services, filters, directives
*/
/**
* controllers:- controls the data of AngularJS application
* are regular JS objects
*/
angular
.module('myApp', [])
.controller('appController', ['$scope', function($scope) {
console.log($scope); // shit loads of properties in the $scope object, similar to your window object
$scope.name = 'parent container';
$scope.text = 'You always need a parent container/module and there will always be one parent container so that you can link it to the html using ng-app attribute';
$scope.subtext= "However you split parent container/module into any number of discreet sub modules/container."
$scope.scenario = "consider an application with one CMS part and cusomer facing application."
}]);
|
import React, { Component } from "react";
import "./Featured.css";
const Featured = props => {
return (
<div className="card-columns">
{props.profiles.map(val => (
<div class="card">
<img class="card-img-top" src={val.imageURL} />
<div class="card-body">
<h5 class="card-title">{val.name}</h5>
{val.live === "y" ? (
<p class="liveFeatured text-success">Live Now</p>
) : null}
<p class="card-text">{val.desc}</p>
</div>
</div>
))}
</div>
);
};
export default Featured;
|
let btn = document.querySelector("#btn");
let outPut = document.querySelector("#outPut");
let random = [Math.floor(Math.random() * 10)];
function randomGame() {
let input = document.querySelector("#input").value;
if (input == random) {
outPut.innerHTML = `you guessed right, it was ${random}!!!`;
document.querySelector("#playAgain").innerHTML = "Refresh to play again"
} else if (input > random) {
outPut.innerHTML = "Too High!";
} else if (input < random) {
outPut.innerHTML = "Too Low!";
}
}
|
import React, {Component, PropTypes} from 'react';
import {CrewCharacter, CrewUpgrade} from '../components';
import {LEADER_REGEXP} from '../constants/RegExps';
import {isUpgradable} from '../utils/UpgradeValidations';
export default class CrewList extends Component {
render() {
const {
characters,
actions,
selectedFaction,
leaderName,
ssLimit,
upgrades
} = this.props;
const roles = ['leader', 'follower'];
let tableRows = [];
let index = -1;
// Loop through leader & follower sections of crew list
for (let i = 0; i < roles.length; i++) {
const thisRole = roles[i];
// Add section labels
tableRows.push(
<tr key={index++}>
<th>{thisRole}</th>
<th colSpan="10"></th>
</tr>
);
// Create array of all table rows
tableRows = tableRows.concat(
characters
// Filter for characters that have been added,
// segmented by leader/follower
.filter(character => {
const correctRole = LEADER_REGEXP.test(thisRole) ?
character.isLeader : !character.isLeader;
return character.count > 0 && correctRole;
})
.map(character => {
const {characterUpgrades, count} = character;
let characterRows = [];
// Return character components
for (let j = 0; j < count; j++) {
characterRows.push(
<CrewCharacter
key={index++}
actions={actions}
role={thisRole}
character={character}
characters={characters}
selectedFaction={selectedFaction}
leaderName={leaderName}
ssLimit={ssLimit}
version={j}
upgrades={upgrades} />
);
// If character is upgradable, separate individuals
// into different components;
// otherwise, roll them up into one row
if (!isUpgradable) {
break;
}
// Add upgrade row(s) below associated character
for (let k = 0; k < characterUpgrades.length; k++) {
const thisUpgrade = characterUpgrades[k];
const {versions} = thisUpgrade;
// The 'versions' array associates upgrades with
// specific instances of upgradable characters
for (let l = 0; l < versions.length; l++) {
const thisVersion = versions[l];
// Check if this upgrade is associated with
// this character version
if (parseFloat(thisVersion) === j) {
characterRows.push(
<CrewUpgrade
actions={actions}
character={character}
selectedFaction={selectedFaction}
upgrade={thisUpgrade}
upgrades={upgrades}
characterUpgrades={characterUpgrades} />
);
break;
}
}
}
}
return characterRows;
})
);
}
return (
<div className="app-section">
<table className="table">
<thead>
<tr>
<th></th>
<th>Count</th>
<th>Name</th>
<th>Faction</th>
<th>Station</th>
<th>Limit</th>
<th>Characteristics</th>
<th>Cost</th>
<th>Cache</th>
<th>Upgrades</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
{tableRows}
</tbody>
</table>
</div>
);
}
}
CrewList.propTypes = {
characters: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired,
selectedFaction: PropTypes.string.isRequired,
leaderName: PropTypes.string,
ssLimit: PropTypes.number.isRequired,
upgrades: PropTypes.array.isRequired
};
|
var config = {
type: 'line',
data: {
labels: [],
datasets: []
},
options: {
maintainAspectRatio: false,
responsive: false,
title: {
display: true,
// text: 'Chart.js Line Chart'
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
// scaleLabel: {
// display: true,
// labelString: '时间'
// }
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: '次数'
}
}]
}
}
}
function main ({utils, chart}) {
const { getColorByLabel } = utils
var createSheet = function({label, data}) {
const color = getColorByLabel(label)
return {
fill: false,
label,
data,
backgroundColor: color,
borderColor: color,
}
}
function update(channel_id, res) {
chart.options.title = {
display: true,
text: `頻道: ${channel_id.toUpperCase()}, 統計時間: ${moment(res.now).format('lll')}`
}
chart.data.labels = res.x.reverse().map(x =>{
return moment(x).format('MM/DD LT')
})
// myChart.data.datasets[0].data = res.data
chart.data.datasets = []
Object.keys(res.sheets).forEach(k =>{
let s = createSheet({label: k, data: res.sheets[k]})
chart.data.datasets.push(s)
})
chart.update()
}
return {
update
}
}
export default {
name: '近24小時',
size: '12',
className: 'recents',
main, config
}
|
var cmajor = {};
cmajor.yo = function () {
var oscs = [], o, i, freqs = [261.63, 329.63, 392];
freqs.forEach(function(freq) {
o = audio_context.createOscillator();
o.frequency.value = freq;
o.connect(audio_context.destination);
o.noteOn(0);
oscs.push(o);
});
this.oscs = oscs;
fire('play', '\n - ' + freqs.join('Hz\n - '));
};
cmajor.no = function () {
this.oscs.forEach(function(o) {
o.noteOff(0);
});
fire('stop');
};
|
function loader(element) {
return new Promise((resolve, reject) => {
element.addEventListener('load', () => {
resolve();
});
element.addEventListener('error', e => {
reject(e);
});
document.head.appendChild(element);
});
}
function importScript(url) {
const script = document.createElement('script');
script.src = url;
return loader(script);
}
let element;
console.log('todomvc load');
define({
async bootstrap() {
console.log('todomvc bootstrap');
if (customElements.get('my-todo')) {
return Promise.resolve();
}
return importScript('../libs/lit-element-todomvc.js');
},
async mount({ container }) {
console.log('todomvc mount');
element = document.createElement('my-todo');
container.appendChild(element);
},
async unmount({ container }) {
console.log('todomvc unmount');
container.removeChild(element);
},
async unload() {
console.log('todomvc unload');
element = null;
}
});
|
'use strict';
const path = require('path');
const fs = require('fs');
const electron = require('electron');
const app = electron.app;
const appMenu = require('./menu');
const config = require('./config');
const tray = require('./tray');
if (require('electron-squirrel-startup')) return;
require('electron-debug')();
require('electron-dl')();
let mainWindow;
let isQuitting = false;
let oldtitle;
const isAlreadyRunning = app.makeSingleInstance(() => {
if (mainWindow) {
if (mainWindow.isMinimized()) {
mainWindow.restore();
}
mainWindow.show();
}
});
if (isAlreadyRunning) {
app.quit();
}
function updateBadge(messageCount) {
// Set badge
if (process.platform === 'darwin') {
app.dock.setBadge(messageCount ? messageCount[1] : '');
} else {
tray.setBadge(messageCount);
}
}
function checkMessages(title) {
// Update badge
// How many new messages on new title?
const messageCount = (/\(([0-9]+)\)/).exec(title);
// How many messages I had?
const messageCountOld = (/\(([0-9]+)\)/).exec(oldtitle);
// No unread messages, do nothing than setting badge to 0
if (!messageCount) {
const indexCount = (/inbox/i).exec(title);
if (indexCount) {
oldtitle = 0;
updateBadge(0);
}
return;
}
// No new messages, do nothing.
if (messageCountOld && messageCount[1] <= messageCountOld[1]) {
updateBadge(0);
return;
}
oldtitle = title;
}
function createMainWindow() {
const lastWindowState = config.get('lastWindowState');
const isDarkMode = config.get('darkMode');
const win = new electron.BrowserWindow({
title: app.getName(),
show: false,
x: lastWindowState.x,
y: lastWindowState.y,
width: lastWindowState.width,
height: lastWindowState.height,
icon: process.platform === 'linux' && path.join(__dirname, 'static/Icon.png'),
minWidth: 1000,
minHeight: 700,
autoHideMenuBar: true,
titleBarStyle: 'hidden-inset',
darkTheme: isDarkMode, // GTK+3
backgroundColor: isDarkMode ? '#192633' : '#fff',
webPreferences: {
preload: path.join(__dirname, 'browser.js'),
nodeIntegration: false,
plugins: true
}
});
if (process.platform === 'darwin') {
win.setSheetOffset(40);
}
win.loadURL('https://mail.protonmail.com/login');
win.on('close', e => {
if (!isQuitting) {
e.preventDefault();
if (process.platform === 'darwin') {
app.hide();
} else {
win.hide();
}
}
});
win.on('page-title-updated', (e, title) => {
e.preventDefault();
checkMessages(title);
});
return win;
}
app.on('ready', () => {
electron.Menu.setApplicationMenu(appMenu);
mainWindow = createMainWindow();
tray.create(mainWindow);
const page = mainWindow.webContents;
page.on('dom-ready', () => {
page.insertCSS(fs.readFileSync(path.join(__dirname, 'browser.css'), 'utf8'));
page.insertCSS(fs.readFileSync(path.join(__dirname, 'themes/dark-mode.css'), 'utf8'));
if (process.platform === 'darwin') {
page.insertCSS(fs.readFileSync(path.join(__dirname, 'themes/osx-fix.css'), 'utf8'));
}
mainWindow.show();
});
page.on('new-window', (e, url) => {
e.preventDefault();
electron.shell.openExternal(url);
});
});
app.on('activate', () => {
mainWindow.show();
});
app.on('before-quit', () => {
isQuitting = true;
if (!mainWindow.isFullScreen()) {
config.set('lastWindowState', mainWindow.getBounds());
}
});
|
function _init() {
px = 300
py = 300
sx = 300
sy = 200
vx = 1.4
vy = 0
MG = 300
font('30px Moonbeam')
}
sign = Math.sign
function _main() {
sx += vx
sy += vy
rx = sx-px
ry = sy-py
r2 = rx*rx + ry*ry
f = MG / r2
dvx = sign(rx) * f * rx*rx / r2
dvy = sign(ry) * f * ry*ry / r2
vx -= dvx
vy -= dvy
status(`t1:${fc.t1} t2:${fc.t2} t3:${fc.t3} t4:${fc.t4}`)
}
function _draw() {
cls(0)
pen(3)
//camera(-300,-300,2,2)
//camera(Math.random()*10,Math.random()*10)
//camera(0,0)
circfill(px,py,12,1)
circfill(sx,sy,2,2)
print("¶®ΨѦ",sx+10,sy+10,3)
color(1)
line(sx,sy,sx+10*vx,sy+10*vy)
rectfill(10,10,50,50,1)
xrect(100,500,55,55,2,1,true)
xrect(100,500,45,45,0,0.8,true)
//camera(Math.random()*10-5,Math.random()*10-5)
color(2)
xprint('Au',100,500)
shapefill(200,500, [50,0,50,50,0,50,-25,25],1)
print("Hail to Crail",300,500,5)
print("dv = 1.432",300,550,5)
color(5)
line(100,50,100,100)
line(100,150)
line(150,150)
snap = snapshot(true,0,0,20,20)
ctx.drawImage(snap,20,20)
}
|
import React, { memo } from 'react';
import styles from './styles.module.css';
function Button({ onClick, children }) {
return (
<button onClick={onClick} className={styles.button}>
{children}
</button>
);
}
export default memo(Button);
|
import React from "react";
import '../../App.css';
function Columbine() {
return (
<div className="header-modal">
<div className="flexContainer">
<div className="flexside">
<h3>Wellsite Geologist</h3>
<h4>Fort Worth, TX / Midland, TX</h4>
<h4>2019 - Present</h4>
</div>
<div className="flexmiddle"></div>
<div className="flexsideCenter">
<h3>Columbine Corp</h3>
</div>
</div>
<hr class="solid"></hr>
<h5>Supervisor: Garrick Budrow</h5>
<h5>  Provide real-time descriptions of geologic formation while drilling oil and gas wells in the Permian Basin.</h5>
<h5>  Monitor and manage gas data to ensure safe work practices are maintained and communicated with clients.</h5>
</div>
)
}
export default Columbine
|
import { GetPlans } from '../services/plans';
import { Emitter } from '../../../helpers/emitter';
class PlansController {
static async Get(req, res) {
let response;
try {
const plans = await GetPlans(req.query);
if (plans.length) {
response = {
status: 200,
data: plans,
};
} else {
response = {
status: 404,
data: plans,
message: 'Nenhum registro encontrado :/',
};
}
} catch (err) {
res.status(500);
response = {
status: 500,
message: err,
};
}
return Emitter(res, response);
}
}
export default PlansController;
|
/// <reference types="cypress" />
context('Casos de Sucesso', () => {
beforeEach(() => {
cy.visit('/')
})
it('Cadastro com sucesso ', () => {
const EMAIL = "test"+new Date().getTime()+"@test.com"
const SENHA = "Va654321"
cy.cadastro("Test Bossa",EMAIL,SENHA,"Va654321",true)
cy.get('button.bbox-button.margin-top-big.bg-blue-base').click()
cy.get('.padding-left-tiny').click()
cy.login(EMAIL,SENHA)
cy.get('.margin-vertical-big').click()
cy.get('.font-size-huge').should('have.text', '\n\t\t\tOlá, Test\n\t\t')
})
})
|
// vue.config.js
module.exports = {
publicPath:
process.env.NODE_ENV === "production" ? "/presentation_template/" : "/",
chainWebpack: config => {
const svgRule = config.module.rule("svg");
svgRule.uses.clear();
svgRule
.use("vue-svg-loader")
.loader("vue-svg-loader")
.options({
svgo: {
plugins: [{ cleanupIDs: false }, { removeUnknownsAndDefaults: false }]
}
});
config.module
.rule("vue")
.use("vue-loader")
.tap(args => {
args.compilerOptions.whitespace = "preserve";
});
}
};
|
// Ex
let vielle_dame = {
age: 80,
nom: {
prenom: "murielle",
nom: "rodriguez",
},
moral: "mal",
objet: "canne",
parler (){
if (this.moral == "mal" ) {
alert("Vous me dérangrez bande salade rabes " + "coup de " + this.objet)
} else{
alert("bonjour " + vieil_homme.nom)
}
}
}
let vieil_homme = {
nom: "Luc",
adoucir (){
vielle_dame.moral = "bien"
}
}
vielle_dame.parler()
vieil_homme.adoucir()
vielle_dame.parler()
|
import React from 'react'
import { Grid, Col, Image } from 'react-bootstrap'
import '../style/footer.css'
import Navigation from '../components/Navigation'
const Footer = () => {
return (
<div className={'footer-container'}>
<Grid>
<Col xs={12} sm={12} smOffset={2} >
<Image src={'assets/logo-large.png'} className={'footer-logo'}/>
<Navigation/>
<p className={'copyright'}>© larson.media 2018</p>
</Col>
</Grid>
</div>
)
}
export default Footer
|
#!/usr/bin/env node
const PdfService = require('./index');
const commandLineArgs = require('command-line-args');
const path = require('path');
const optionDefinitions = [
{ name: 'pagePath', type: String, alias: 'p', defaultOption: `${__dirname}/index.html` },
{ name: 'serverUrl', alias: 'u', type: String },
{ name: 'templateParams', alias: 't', type: String },
{ name: 'templateHelpers', alias: 'h', type: String },
];
const options = commandLineArgs(optionDefinitions);
options.templateSystem = {};
if (options.templateParams) {
options.templateSystem.params = require(path.resolve(options.templateParams)); // eslint-disable-line
}
if (options.templateHelpers) {
options.templateSystem.helpers = require(path.resolve(options.templateHelpers)); // eslint-disable-line
}
const pdfService = new PdfService(options);
pdfService.watch(options.pagePath, options);
|
import Ember from 'ember';
import C from 'ui/utils/constants';
import { denormalizeName } from 'ui/services/settings';
export default Ember.Controller.extend({
github : Ember.inject.service(),
endpoint : Ember.inject.service(),
access : Ember.inject.service(),
settings : Ember.inject.service(),
githubConfig : Ember.computed.alias('model.githubConfig'),
confirmDisable : false,
errors : null,
testing : false,
error : null,
saved : false,
saving : false,
haveToken : false,
organizations : null,
scheme : Ember.computed.alias('githubConfig.scheme'),
isEnterprise: false,
secure : true,
createDisabled: function() {
if (!this.get('haveToken')) {
return true;
}
if ( this.get('isEnterprise') && !this.get('githubConfig.hostname') )
{
return true;
}
if ( this.get('testing') )
{
return true;
}
}.property('githubConfig.{clientId,clientSecret,hostname}','testing','isEnterprise', 'haveToken'),
providerName: function() {
if ( !!this.get('githubConfig.hostname') ) {
return 'authPage.github.enterprise';
} else {
return 'authPage.github.standard';
}
}.property('githubConfig.hostname'),
numUsers: function() {
return this.get('model.allowedIdentities').filterBy('externalIdType',C.PROJECT.TYPE_GITHUB_USER).get('length');
}.property('model.allowedIdentities.@each.externalIdType','wasRestricted'),
numOrgs: function() {
return this.get('model.allowedIdentities').filterBy('externalIdType',C.PROJECT.TYPE_GITHUB_ORG).get('length');
}.property('model.allowedIdentities.@each.externalIdType','wasRestricted'),
destinationUrl: function() {
return window.location.origin+'/';
}.property(),
updateEnterprise: function() {
if ( this.get('isEnterprise') ) {
var match;
var hostname = this.get('githubConfig.hostname')||'';
if ( match = hostname.match(/^http(s)?:\/\//i) ) {
this.set('secure', ((match[1]||'').toLowerCase() === 's'));
hostname = hostname.substr(match[0].length).replace(/\/.*$/,'');
this.set('githubConfig.hostname', hostname);
}
}
else
{
this.set('githubConfig.hostname', null);
this.set('secure', true);
}
this.set('scheme', this.get('secure') ? 'https://' : 'http://');
},
enterpriseDidChange: function() {
Ember.run.once(this,'updateEnterprise');
}.observes('isEnterprise','githubConfig.hostname','secure'),
protocolChoices: [
{label: 'https:// -- Requires a cert from a public CA', value: 'https://'},
{label: 'http://', value: 'http://'},
],
actions: {
save: function() {
this.send('clearError');
this.set('saving', true);
let githubConfig = Ember.Object.create(this.get('githubConfig'));
githubConfig.setProperties({
'clientId' : (githubConfig.get('clientId')||'').trim(),
'clientSecret' : (githubConfig.get('clientSecret')||'').trim(),
});
this.get('model').setProperties({
'provider' : 'githubconfig',
'enabled' : false, // It should already be, but just in case..
'accessMode' : 'unrestricted',
'allowedIdentities' : [],
});
this.get('github').setProperties({
hostname : githubConfig.get('hostname'),
scheme : githubConfig.get('scheme'),
clientId : githubConfig.get('clientId')
});
this.get('model').save().then((/*resp*/) => {
// we need to go get he new token before we open the popup
// if you've authed with any other services in v1-auth
// the redirect token will be stale and representitive
// of the old auth method
this.get('github').getToken().then((resp) => {
this.get('access').set('token', resp);
this.setProperties({
saving: false,
saved: true,
haveToken: true,
});
}).catch((err) => {
this.setProperties({
saving: false,
saved: false,
haveToken: false,
});
this.send('gotError', err);
});
}).catch(err => {
this.setProperties({
saving: false,
saved: false,
haveToken: false,
});
this.send('gotError', err);
});
},
authenticate: function() {
this.send('clearError');
this.set('testing', true);
this.get('github').authorizeTest((err,code) => {
if ( err )
{
this.send('gotError', err);
this.set('testing', false);
}
else
{
this.send('gotCode', code);
this.set('testing', false);
}
});
},
gotCode: function(code) {
this.get('access').login(code).then(res => {
this.send('authenticationSucceeded', res.body);
}).catch(res => {
// Github auth succeeded but didn't get back a token
this.send('gotError', res.body);
});
},
authenticationSucceeded: function(auth) {
this.send('clearError');
this.set('organizations', auth.orgs);
let model = this.get('model').clone();
model.setProperties({
'enabled': true,
'accessMode': 'restricted',
'allowedIdentities': [auth.userIdentity],
});
let url = window.location.href;
model.save().then(() => {
// Set this to true so the token will be sent with the request
this.set('access.enabled', true);
return this.get('userStore').find('setting', denormalizeName(C.SETTING.API_HOST)).then((setting) => {
if ( setting.get('value') )
{
this.send('waitAndRefresh', url);
}
else
{
// Default the api.host so the user won't have to set it in most cases
if ( window.location.hostname === 'localhost' ) {
this.send('waitAndRefresh', url);
} else {
setting.set('value', window.location.origin);
return setting.save().then(() => {
this.send('waitAndRefresh', url);
});
}
}
});
}).catch((err) => {
this.set('access.enabled', false);
this.send('gotError', err);
});
},
waitAndRefresh: function(url) {
$('#loading-underlay, #loading-overlay').removeClass('hide').show();
setTimeout(function() {
window.location.href = url || window.location.href;
}, 1000);
},
promptDisable: function() {
this.set('confirmDisable', true);
Ember.run.later(this, function() {
this.set('confirmDisable', false);
}, 10000);
},
gotError: function(err) {
if ( err.message )
{
this.send('showError', err.message + (err.detail? '('+err.detail+')' : ''));
}
else
{
this.send('showError', 'Error ('+err.status + ' - ' + err.code+')');
}
this.set('testing', false);
},
showError: function(msg) {
this.set('errors', [msg]);
window.scrollY = 10000;
},
clearError: function() {
this.set('errors', null);
},
disable: function() {
this.send('clearError');
let model = this.get('model').clone();
model.setProperties({
'allowedIdentities': [],
'accessMode': 'unrestricted',
'enabled': false,
'githubConfig': {
'hostname': null,
'clientSecret': '',
}
});
model.save().then(() => {
this.get('access').clearSessionKeys();
this.set('access.enabled',false);
this.send('waitAndRefresh');
}).catch((err) => {
this.send('gotError', err);
}).finally(() => {
this.set('confirmDisable', false);
});
},
},
});
|
import React, { Component, Fragment } from 'react';
import {
Text, View,
StyleSheet,
Dimensions,
TouchableOpacity,
Alert,StatusBar
} from 'react-native';
import Header from '../components/Header';
import getStringToColor from '../utils/getStringToColor';
import Course from '../utils/Course';
import AsyncStorage from "@react-native-community/async-storage";
const { width, height } = Dimensions.get('window');
import Spinner from 'react-native-loading-spinner-overlay';
import { format, compareAsc } from 'date-fns'
const styles = StyleSheet.create({
container: {
flex: 1,
top: 0,
left: 0,
backgroundColor: '#f9f9f9'
},
title: {
color: '#222c69',
fontWeight: '700',
fontSize: 16,
},
next_perv: {
color: '#222c69'
},
main: { backgroundColor: "#fff", display: 'flex', flex: 1, flexDirection: 'row', justifyContent: 'space-between' },
left_time: { height: '100%', width: 40, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'space-between' },
lineStyle: { backgroundColor: '#eee', height: StyleSheet.hairlineWidth, width: width * 2 },
head_h: {
height: 30,
textAlignVertical: 'center',
textAlign: 'center',
backgroundColor: '#fafafa',
padding: 0,
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: '#eee'
},
head_w: {
flex: 1
},
left_w: {
width: 40,
textAlign: 'center',
backgroundColor: '#fafafa',
flex: 1,
textAlignVertical: 'center'
},
week: {
flexGrow: 1,
},
week_day: {
display: 'flex', flexDirection: 'row', flex: 1
},
week_day_item_box: {
flex: 1,
margin: 2,
// marginLeft: 1,
// marginRight: 1,
overflow: 'hidden'
},
week_day_item: {
flex: 1,
// backgroundColor: "#dac",
borderRadius: 4,
padding: 4,
paddingLeft: 2,
paddingRight: 2,
height: "100%",
overflow: 'hidden',
textAlign: 'center',
},
item_title: {
color: '#fff',
fontWeight: '600',
fontSize: 11,
lineHeight: 14,
textAlign: 'center',
marginBottom:2
},
item_info: {
fontSize: 10,
color: '#fff',
textAlign: 'center',
lineHeight: 13
},
spinnerTextStyle: {
color: '#f000'
}
});
function getDate(now = 0) {
return {
data: format(Date.now() + now * 7 * 24 * 60 * 60 * 1000, 'yyyy-MM-dd'),
m: format(Date.now() + now * 7 * 24 * 60 * 60 * 1000, 'M'),
};
}
getDate.c = 0;
export class Curriculum extends Component {
constructor(props) {
super(props);
let day = new Date().getDay();
// if (day === 0) {
// day = 7;
// }
this.state = {
courses: [],
timetable: [],
week: {},
week_day: day,
loginName: "",
spinner: true,
c_date: getDate().data,
c_month: getDate().m
};
}
static navigationOptions = {
title: '课表',
};
getData = async (loginName, currentWeek) => {
if (currentWeek >= this.state.week.totalWeek) return;
if (currentWeek <= 0) return;
if (this.getData.stat === 1) return;
this.getData.stat = 1;
this.setState({
spinner: true
});
const oldWeekIndex = this.state.week && this.state.week.currentWeek;
week = currentWeek && { ...this.state.week, currentWeek } || await Course.getWeek();
if (week) {
this.setState({ week });
const { timetable, courseList: courses } = await Course.getCourseData(week.currentWeek, loginName);
console.warn('oldWeekIndex', oldWeekIndex);
if (oldWeekIndex) {
getDate.c -= oldWeekIndex > currentWeek ? 1 : -1;
console.warn(getDate.c);
}
const datex = getDate(getDate.c);
courses.unshift(courses.pop())
this.setState({ courses: courses, spinner: false, timetable, c_date: datex.data, c_month: datex.m });
}
this.getData.stat = 0;
}
showCurrentInfo = async (course) => {
const str = course.reduce((a, b) => a + b + '\n', '');
Alert.alert(
course[0] || '无法显示',
str
);
}
async componentWillMount() {
StatusBar.setBarStyle('dark-content');
const loginName = await AsyncStorage.getItem('loginName');
const courses = await AsyncStorage.getItem(loginName + 'courses');
const timetable = await AsyncStorage.getItem(loginName + 'timetable');
const week = await AsyncStorage.getItem(loginName + 'week');
const courses_time = await AsyncStorage.getItem(loginName + 'courses_time');
const oldTime = new Date(parseInt(courses_time));
this.setState({
loginName
});
if (new Date().getDate() === oldTime.getDate() && courses) {
try {
this.setState({
courses: JSON.parse(courses),
week: JSON.parse(week || {}),
spinner: false,
timetable: JSON.parse(timetable || []),
});
return;
} catch (error) { }
}
for (let i = 0; i < 3; i++) {
try {
await this.getData(loginName);
AsyncStorage.setItem(loginName + 'courses', JSON.stringify(this.state.courses));
AsyncStorage.setItem(loginName + 'week', JSON.stringify(this.state.week));
AsyncStorage.setItem(loginName + 'courses_time', Date.now().toString());
return;
} catch (error) {
this.getData.stat = 0;
console.warn(error);
}
this.getData.stat = 0;
}
this.setState({
spinner: false
});
Alert.alert("好像出了点小问题,等会再试吧");
}
render() {
const { courses, week, week_day, loginName, timetable, c_date, c_month } = this.state;
return (
<View style={styles.container}>
<Header
isL={true}
center={
<View style={{ flex: 1, alignItems: "center" }}>
<Text style={styles.title}>第{week.currentWeek}周</Text>
<Text style={{ color: '#424c89' }}>{c_date}</Text>
</View>
}
left={
<TouchableOpacity onPress={() => { this.getData(loginName, week.currentWeek - 1) }}>
<Text style={styles.next_perv}>上一周</Text>
</TouchableOpacity>
}
right={
<TouchableOpacity onPress={() => { this.getData(loginName, week.currentWeek + 1) }}>
<Text style={styles.next_perv}>下一周</Text>
</TouchableOpacity>
}
/>
{/* loading */}
<Spinner
visible={this.state.spinner}
textContent={'Loading...'}
textStyle={styles.spinnerTextStyle}
/>
{/* 主要内容块 */}
<View style={styles.main}>
{/* 左边的时间 */}
<View style={styles.left_time}>
<Text style={[styles.head_h, styles.left_w, { flex: 0 }]}>{c_month}月</Text>
{
timetable.map((item, index) => (
<Fragment key={String(Math.random())}>
<Text key={String(Math.random())} style={styles.left_w}>{index + 1}{'\n'}<Text style={{ fontSize: 10 }}>{(item.length && item[item.length - 1] || '').replace('-', '\n')}</Text></Text>
<View key={String(Math.random())} style={styles.lineStyle}></View>
</Fragment>
))
}
</View>
{/* 主要的 */}
<View style={styles.week}>
{/* 上面的日期 */}
<View style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between' }}>
{
['日', '一', '二', '三', '四', '五', '六'].map((item, index) => (
<Text style={[styles.head_w, styles.head_h, week_day === (index) ? { backgroundColor: "#eee" } : {}]} key={item}>周{item}</Text>
))
}
</View>
{/* 下面课程内容 */}
<View style={styles.week_day}>
{/* 一周 */}
{
courses.map((item, index) => (
<View key={index} style={{ flex: 1 }}>
{
item.map(course => course.length && (
<TouchableOpacity key={Math.random().toString()} style={styles.week_day_item_box} onPress={() => { this.showCurrentInfo(course) }}>
<View style={[styles.week_day_item, course && { backgroundColor: getStringToColor(course[1] || '') } || {}]}>
<Text style={styles.item_title}>{course && course[0]}</Text>
<Text style={styles.item_info}>@{course.length === 9 && course[5] || course[6]}</Text>
</View>
</TouchableOpacity>
) || <View key={Math.random().toString()} style={styles.week_day_item_box}></View>)
}
</View>
))
}
</View>
</View>
</View>
</View>
);
}
}
export default Curriculum;
|
let count = 0;
const counter = {
increment() {
count += 1;
},
getCount() {
return count;
}
};
const app = (counter) => {
counter.increment();
};
test('app() with mock counter .toHaveBeenCalledTimes(1)', () => {
const mockCounter = {
increment: jest.fn()
};
app(mockCounter);
expect(mockCounter.increment).toHaveBeenCalledTimes(1);
});
test('app() with jest.spyOn(counter) .toHaveBeenCalledTimes(1)', () => {
const incrementSpy = jest.spyOn(counter, 'increment');
app(counter);
expect(incrementSpy).toHaveBeenCalledTimes(1);
});
|
/**
* Created by wuyin on 2016/5/18.
*/
|
import Component from './Component';
export default class Shot extends Component {
getInfo() {
return this.info;
}
update() {
this.info.x += 20;
}
draw() {
const {x, y, w, h} = this.getInfo();
this.ctx.beginPath();
this.ctx.rect(x, y, w, h);
this.ctx.fillStyle = 'red';
this.ctx.fill();
this.ctx.closePath();
this.update();
}
}
|
/* Copyright 2021 F5 Networks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* jshint ignore: start */
'use strict';
require('core-js');
const fs = require('fs-extra');
const https = require('https');
const url = require('url');
const extract = require('extract-zip');
const axios = require('axios');
const Ajv = require('ajv');
const merge = require('deepmerge');
const Mustache = require('mustache');
const semver = require('semver');
const fast = require('@f5devcentral/f5-fast-core');
const TeemDevice = require('@f5devcentral/f5-teem').Device;
const drivers = require('../lib/drivers');
const { SecretsSecureVault } = require('../lib/secrets');
const FsTemplateProvider = fast.FsTemplateProvider;
const DataStoreTemplateProvider = fast.DataStoreTemplateProvider;
const StorageDataGroup = fast.dataStores.StorageDataGroup;
const AS3Driver = drivers.AS3Driver;
const TransactionLogger = fast.TransactionLogger;
const IpamProviders = require('../lib/ipam');
const pkg = require('../package.json');
const endpointName = 'fast';
const projectName = 'f5-appsvcs-templates';
const mainBlockName = 'F5 Application Services Templates';
const bigipHost = (process.env.FAST_BIGIP_HOST && `${process.env.FAST_BIGIP_HOST}`) || 'http://localhost:8100';
const bigipUser = process.env.FAST_BIGIP_USER || 'admin';
const bigipPassword = process.env.FAST_BIGIP_PASSWORD || '';
let bigipStrictCert = process.env.FAST_BIGIP_STRICT_CERT || true;
if (typeof bigipStrictCert === 'string') {
bigipStrictCert = (
bigipStrictCert.toLowerCase() === 'true'
|| bigipStrictCert === '1'
);
}
const ajv = new Ajv({
useDefaults: true
});
ajv.addFormat('checkbox', /.*/);
ajv.addFormat('table', /.*/);
ajv.addFormat('password', /.*/);
ajv.addFormat('text', /.*/);
ajv.addFormat('grid-strict', /.*/);
ajv.addFormat('textarea', /.*/);
// Disable HTML escaping
Mustache.escape = function escape(text) {
return text;
};
const configPath = process.AFL_TW_ROOT || `/var/config/rest/iapps/${projectName}`;
const templatesPath = process.AFL_TW_TS || `${configPath}/templatesets`;
const uploadPath = process.env.FAST_UPLOAD_DIR || '/var/config/rest/downloads';
const scratchPath = `${configPath}/scratch`;
const dataGroupPath = `/Common/${projectName}/dataStore`;
const configDGPath = `/Common/${projectName}/config`;
const configKey = 'config';
// Known good hashes for template sets
const supportedHashes = {
'bigip-fast-templates': [
'55e71bb2a511a1399bc41e9e34e657b2c0de447261ce3a1b92927094d988621e', // v1.13
'42bd34feb4a63060df71c19bc4c23f9ec584507d4d3868ad75db51af8b449437', // v1.12
'84904385ccc31f336b240ba1caa17dfab134d08efed7766fbcaea4eb61dae463', // v1.11
'64d9692bdab5f1e2ba835700df4d719662b9976b9ff094fe7879f74d411fe00b', // v1.10
'89f6d8fb68435c93748de3f175f208714dcbd75de37d9286a923656971c939f0', // v1.9
'fbaee3fd9ecce14a2d90df8c155998749b49126e0eb80267e9b426c58677a164', // v1.8.1
'42650496f8e1b00a7e8e6a7c148a781bb4204e95f09f66d7d89af5793ae0b8b7', // v1.8
'83df55f23066fd0ac205ce3dca2c96ffd71e459914d7dcf205f3201fb1570427', // v1.7
'9b65c17982fd5f83a36576c1a55f2771a0011283db8221704925ee803b8dbd13', // v1.6
'48316eb5f20c6f3bc4e78ad50b0d82fae46fc3c7fa615fe438ff8f84b3a3c2ea', // v1.5
'99bf347ba5556df2e8c7100a97ea4c24171e436ed9f5dc9dfb446387f29e0bfe', // v1.4
'e7eba47ac564fdc6d5ae8ae4c5eb6de3d9d22673a55a2e928ab59c8c8e16376b', // v1.3
'316653656cfd60a256d9b92820b2f702819523496db8ca01ae3adec3bd05f08c', // v1.2
'985f9cd58299a35e83851e46ba7f4f2b1b0175cad697bed09397e0e07ad59217' // v1.0
]
};
class FASTWorker {
constructor(options) {
options = options || {};
this.state = {};
this.baseUserAgent = `${pkg.name}/${pkg.version}`;
this.incomingUserAgent = '';
this.isPublic = true;
this.isPassThrough = true;
this.WORKER_URI_PATH = `shared/${endpointName}`;
this.driver = new AS3Driver({
endPointUrl: `${bigipHost}/mgmt/shared/appsvcs`,
userAgent: this.baseUserAgent,
bigipUser,
bigipPassword,
strictCerts: bigipStrictCert
});
this.storage = options.templateStorage || new StorageDataGroup(dataGroupPath);
this.configStorage = options.configStorage || new StorageDataGroup(configDGPath);
this.templateProvider = new DataStoreTemplateProvider(this.storage, undefined, supportedHashes);
this.fsTemplateProvider = new FsTemplateProvider(templatesPath, options.fsTemplateList);
this.teemDevice = new TeemDevice({
name: projectName,
version: pkg.version
});
this.secretsManager = options.secretsManager || new SecretsSecureVault();
this.transactionLogger = new TransactionLogger(
(transaction) => {
const [id, text] = transaction.split('@@');
this.logger.info(`FAST Worker [${id}]: Entering ${text}`);
},
(transaction, _exitTime, deltaTime) => {
const [id, text] = transaction.split('@@');
this.logger.info(`FAST Worker [${id}]: Exiting ${text}`);
this.logger.fine(`FAST Worker [${id}]: ${text} took ${deltaTime}ms to complete`);
}
);
this.ipamProviders = options.ipamProviders;
this.endpoint = axios.create({
baseURL: bigipHost,
auth: {
username: bigipUser,
password: bigipPassword
},
httpsAgent: new https.Agent({
rejectUnauthorized: bigipStrictCert
})
});
this.requestTimes = {};
this.requestCounter = 1;
this.provisionData = null;
this.as3Info = null;
this._hydrateCache = null;
this._provisionConfigCache = null;
}
hookCompleteRestOp() {
// Hook completeRestOperation() so we can add additional logging
this._prevCompleteRestOp = this.completeRestOperation;
this.completeRestOperation = (restOperation) => {
this.recordRestResponse(restOperation);
return this._prevCompleteRestOp(restOperation);
};
}
validateConfig(config) {
return Promise.resolve()
.then(() => ajv.compile(this.getConfigSchema()))
.then((validate) => {
const valid = validate(config);
if (!valid) {
return Promise.reject(new Error(
`invalid config: ${validate.errors}`
));
}
return Promise.resolve(config);
});
}
getConfig(reqid) {
reqid = reqid || 0;
const defaultConfig = {
deletedTemplateSets: [],
enableIpam: false,
ipamProviders: [],
disableDeclarationCache: false
};
return Promise.resolve()
.then(() => this.enterTransaction(reqid, 'gathering config data'))
.then(() => Promise.all([
this.configStorage.getItem(configKey),
this.driver.getSettings()
]))
.then(([config, driverSettings]) => {
if (config) {
return Promise.resolve(Object.assign(
{},
defaultConfig,
driverSettings,
config
));
}
return Promise.resolve()
.then(() => {
this.logger.info('FAST Worker: no config found, loading defaults');
})
.then(() => this.configStorage.setItem(configKey, defaultConfig))
.then(() => this.configStorage.persist())
.then(() => defaultConfig);
})
.then((config) => {
this.exitTransaction(reqid, 'gathering config data');
return Promise.resolve(config);
})
.catch((e) => {
this.logger.severe(`FAST Worker: Failed to load config: ${e.stack}`);
return Promise.resolve(defaultConfig);
});
}
getConfigSchema() {
let baseSchema = {
$schema: 'http://json-schema.org/schema#',
title: 'FAST Settings',
type: 'object',
properties: {
deletedTemplateSets: {
type: 'array',
items: {
type: 'string'
},
uniqueItems: true,
options: {
hidden: true
}
},
disableDeclarationCache: {
title: 'Disable AS3 Declaration Cache',
type: 'boolean',
description: [
'Do not cache AS3 declarations.',
'This ensures FAST is always using up-to-date declarations from AS3,',
'which is only an issue if something other than FAST (e.g., config sync) is modifying AS3 config.',
'Disabling declaration caching will negatively impact FAST performance.'
].join(' ')
},
enableIpam: {
title: 'Enable IPAM for Official F5 FAST Templates (Experimental/Beta)',
description: '**NOTE: An IPAM provider must be configured to deploy a valid application using IPAM.**',
type: 'boolean'
},
ipamProviders: {
title: 'IPAM Providers (Experimental/Beta)',
description: 'Configure IPAM providers that can be used in FAST templates to automatically manage IP addresses',
type: 'array',
items: {
oneOf: this.ipamProviders.getSchemas()
}
}
},
required: [
'deletedTemplateSets'
]
};
baseSchema = fast.guiUtils.modSchemaForJSONEditor(baseSchema);
return merge(this.driver.getSettingsSchema(), baseSchema);
}
saveConfig(config, reqid) {
reqid = reqid || 0;
let prevConfig;
return Promise.resolve()
.then(() => this.enterTransaction(reqid, 'saving config data'))
.then(() => this.configStorage.getItem(configKey, config))
.then((data) => {
prevConfig = data;
})
.then(() => this.configStorage.setItem(configKey, config))
.then(() => {
if (JSON.stringify(prevConfig) !== JSON.stringify(config)) {
return this.recordTransaction(
reqid, 'persisting config',
this.configStorage.persist()
);
}
return Promise.resolve();
})
.then(() => this.exitTransaction(reqid, 'saving config data'))
.catch((e) => {
this.logger.severe(`FAST Worker: Failed to save config: ${e.stack}`);
});
}
encryptConfigSecrets(newConfig, prevConfig) {
return Promise.all((newConfig.ipamProviders || []).map(provider => Promise.resolve()
.then(() => {
const prevProvider = prevConfig.ipamProviders.filter(
x => x.name === provider.name
)[0];
if (prevProvider && prevProvider.password === provider.password) {
return Promise.resolve(provider.password);
}
return this.secretsManager.encrypt(provider.password || '');
})
.then((password) => {
provider.password = password;
})));
}
handleResponseError(e, description) {
description = description || 'request';
if (e.response) {
const errData = JSON.stringify({
status: e.response.status,
body: e.response.data
}, null, 2);
return Promise.reject(new Error(`failed ${description}: ${errData}`));
}
return Promise.reject(e);
}
/**
* Worker Handlers
*/
onStart(success, error) {
this.hookCompleteRestOp();
// instantiate here to ensure logger instance is ready
this.ipamProviders = new IpamProviders({
secretsManager: this.secretsManager,
transactionLogger: this.transactionLogger,
logger: this.logger
});
this.logger.fine(`FAST Worker: Starting ${pkg.name} v${pkg.version}`);
this.logger.fine(`FAST Worker: Targetting ${bigipHost}`);
const startTime = Date.now();
let config;
let saveState = true;
return Promise.resolve()
// Automatically add a block
.then(() => {
const hosturl = url.parse(bigipHost);
if (hosturl.hostname !== 'localhost') {
return Promise.resolve();
}
return Promise.resolve()
.then(() => this.enterTransaction(0, 'ensure FAST is in iApps blocks'))
.then(() => this.endpoint.get('/mgmt/shared/iapp/blocks'))
.catch(e => this.handleResponseError(e, 'to get blocks'))
.then((results) => {
const matchingBlocks = results.data.items.filter(x => x.name === mainBlockName);
const blockData = {
name: mainBlockName,
state: 'BOUND',
configurationProcessorReference: {
link: 'https://localhost/mgmt/shared/iapp/processors/noop'
},
presentationHtmlReference: {
link: `https://localhost/iapps/${projectName}/index.html`
}
};
if (matchingBlocks.length === 0) {
// No existing block, make a new one
return this.endpoint.post('/mgmt/shared/iapp/blocks', blockData);
}
// Found a block, do nothing
return Promise.resolve({ status: 200 });
})
.catch(e => this.handleResponseError(e, 'to set block state'))
.then(() => this.exitTransaction(0, 'ensure FAST is in iApps blocks'));
})
// Load config
.then(() => this.getConfig(0))
.then((cfg) => {
config = cfg;
})
.then(() => this.setDeviceInfo())
// Get the AS3 driver ready
.then(() => this.recordTransaction(
0, 'ready AS3 driver',
this.driver.loadMixins()
))
.then(() => this.recordTransaction(
0, 'sync AS3 driver settings',
Promise.resolve()
.then(() => this.gatherProvisionData(0, false, true))
.then(provisionData => this.driver.setSettings(config, provisionData, true))
.then(() => this.saveConfig(config, 0))
))
// Load template sets from disk (i.e., those from the RPM)
.then(() => this.enterTransaction(0, 'loading template sets from disk'))
.then(() => this.recordTransaction(
0, 'gather list of templates from disk',
this.fsTemplateProvider.listSets()
))
.then((fsSets) => {
const deletedSets = config.deletedTemplateSets;
const ignoredSets = [];
const sets = [];
fsSets.forEach((setName) => {
if (deletedSets.includes(setName)) {
ignoredSets.push(setName);
} else {
sets.push(setName);
}
});
this.logger.info(
`FAST Worker: Loading template sets from disk: ${JSON.stringify(sets)} (skipping: ${JSON.stringify(ignoredSets)})`
);
if (sets.length === 0) {
// Nothing to do
saveState = false;
return Promise.resolve();
}
this.templateProvider.invalidateCache();
return DataStoreTemplateProvider.fromFs(this.storage, templatesPath, sets);
})
.then(() => this.exitTransaction(0, 'loading template sets from disk'))
// Persist any template set changes
.then(() => saveState && this.recordTransaction(0, 'persist template data store', this.storage.persist()))
// Done
.then(() => {
const dt = Date.now() - startTime;
this.logger.fine(`FAST Worker: Startup completed in ${dt}ms`);
})
.then(() => success())
// Errors
.catch((e) => {
this.logger.severe(`FAST Worker: Failed to start: ${e.stack}`);
error();
});
}
onStartCompleted(success, error, _loadedState, errMsg) {
if (typeof errMsg === 'string' && errMsg !== '') {
this.logger.error(`FAST Worker onStart error: ${errMsg}`);
return error();
}
this.generateTeemReportOnStart();
return success();
}
setDeviceInfo() {
// If device-info is unavailable intermittently, this can be placed in onStart
// and call setDeviceInfo in onStartCompleted
// this.dependencies.push(this.restHelper.makeRestjavadUri(
// '/shared/identified-devices/config/device-info'
// ));
return Promise.resolve()
.then(() => this.recordTransaction(0, 'fetching device information',
this.endpoint.get('/mgmt/shared/identified-devices/config/device-info'))
.then((response) => {
const data = response.data;
if (data) {
this.deviceInfo = {
hostname: data.hostname,
platform: data.platform,
platformName: data.platformMarketingName,
product: data.product,
version: data.version,
build: data.build,
edition: data.edition,
fullVersion: `${data.version}-${data.build}`
};
}
}));
}
/**
* TEEM Report Generators
*/
sendTeemReport(reportName, reportVersion, data) {
const documentName = `${projectName}: ${reportName}`;
const baseData = {
userAgent: this.incomingUserAgent
};
return this.teemDevice.report(documentName, `${reportVersion}`, baseData, data)
.catch(e => this.logger.error(`FAST Worker failed to send telemetry data: ${e.stack}`));
}
generateTeemReportOnStart() {
return this.gatherInfo()
.then(info => this.sendTeemReport('onStart', 1, info))
.catch(e => this.logger.error(`FAST Worker failed to send telemetry data: ${e.stack}`));
}
generateTeemReportApplication(action, templateName) {
const report = {
action,
templateName
};
return Promise.resolve()
.then(() => this.sendTeemReport('Application Management', 1, report))
.catch(e => this.logger.error(`FAST Worker failed to send telemetry data: ${e.stack}`));
}
generateTeemReportTemplateSet(action, templateSetName) {
const report = {
action,
templateSetName
};
return Promise.resolve()
.then(() => {
if (action === 'create') {
return Promise.all([
this.templateProvider.getNumTemplateSourceTypes(templateSetName),
this.templateProvider.getNumSchema(templateSetName)
])
.then(([numTemplateTypes, numSchema]) => {
report.numTemplateTypes = numTemplateTypes;
report.numSchema = numSchema;
});
}
return Promise.resolve();
})
.then(() => this.sendTeemReport('Template Set Management', 1, report))
.catch(e => this.logger.error(`FAST Worker failed to send telemetry data: ${e.stack}`));
}
generateTeemReportError(restOp) {
const uri = restOp.getUri();
const pathElements = uri.pathname.split('/');
let endpoint = pathElements.slice(0, 4).join('/');
if (pathElements[4]) {
endpoint = `${endpoint}/item`;
}
const report = {
method: restOp.getMethod(),
endpoint,
code: restOp.getStatusCode()
};
return Promise.resolve()
.then(() => this.sendTeemReport('Error', 1, report))
.catch(e => this.logger.error(`FAST Worker failed to send telemetry data: ${e.stack}`));
}
/**
* Helper functions
*/
generateRequestId() {
const retval = this.requestCounter;
this.requestCounter += 1;
return retval;
}
enterTransaction(reqid, text) {
this.transactionLogger.enter(`${reqid}@@${text}`);
}
exitTransaction(reqid, text) {
this.transactionLogger.exit(`${reqid}@@${text}`);
}
recordTransaction(reqid, text, promise) {
return this.transactionLogger.enterPromise(`${reqid}@@${text}`, promise);
}
filterTemplates(templateNames) {
if (!templateNames) {
return Promise.resolve([]);
}
return Promise.resolve(templateNames)
.then(tmplList => Promise.all(tmplList.map(
x => this.templateProvider.fetch(x.name || x).then(tmpl => [x, tmpl])
.catch((e) => {
if (e.message.match(/Could not find template set/)) {
return Promise.resolve(undefined);
}
return Promise.reject(e);
})
)))
.then(tmpls => tmpls.filter(x => x && !x[1].bigipHideTemplate))
.then(tmpls => tmpls.map(x => x[0]));
}
gatherTemplateSet(tsid) {
return Promise.all([
this.templateProvider.hasSet(tsid)
.then(result => (result ? this.templateProvider.getSetData(tsid) : Promise.resolve(undefined)))
.then((tsData) => {
if (tsData) {
return Promise.resolve(tsData);
}
return Promise.resolve()
.then(() => this.fsTemplateProvider.hasSet(tsid))
.then(result => (result ? this.fsTemplateProvider.getSetData(tsid) : undefined))
.then((fsTsData) => {
if (fsTsData) {
fsTsData.enabled = false;
}
return fsTsData;
});
}),
this.driver.listApplications()
])
.then(([tsData, appsList]) => {
if (!tsData) {
return Promise.reject(new Error(`Template set ${tsid} does not exist`));
}
if (typeof tsData.enabled === 'undefined') {
tsData.enabled = true;
}
tsData.templates.forEach((tmpl) => {
tmpl.appsList = appsList
.filter(x => x.template === tmpl.name)
.map(x => `${x.tenant}/${x.name}`);
});
return tsData;
})
.then(tsData => this.filterTemplates(tsData.templates)
.then((templates) => {
tsData.templates = templates;
return tsData;
}))
.catch(e => ({
name: tsid,
hash: '',
templates: [],
enabled: false,
error: e.message
}));
}
gatherInfo(requestId) {
requestId = requestId || 0;
const info = {
version: pkg.version,
as3Info: {},
installedTemplates: []
};
return Promise.resolve()
.then(() => this.recordTransaction(
requestId, 'GET to appsvcs/info',
this.endpoint.get('/mgmt/shared/appsvcs/info', {
validateStatus: () => true // ignore failure status codes
})
))
.then((as3response) => {
info.as3Info = as3response.data;
this.as3Info = info.as3Info;
})
.then(() => this.enterTransaction(requestId, 'gathering template set data'))
.then(() => this.templateProvider.listSets())
.then(setList => Promise.all(setList.map(setName => this.gatherTemplateSet(setName))))
.then((tmplSets) => {
info.installedTemplates = tmplSets;
})
.then(() => this.exitTransaction(requestId, 'gathering template set data'))
.then(() => this.getConfig(requestId))
.then((config) => {
info.config = config;
})
.then(() => info);
}
gatherProvisionData(requestId, clearCache, skipAS3) {
if (clearCache) {
this.provisionData = null;
this._provisionConfigCache = null;
}
return Promise.resolve()
.then(() => {
if (this.provisionData !== null) {
return Promise.resolve(this.provisionData);
}
return this.recordTransaction(
requestId, 'Fetching module provision information',
this.endpoint.get('/mgmt/tm/sys/provision')
)
.then(response => response.data);
})
.then((response) => {
this.provisionData = response;
})
.then(() => {
if (this._provisionConfigCache !== null) {
return Promise.resolve(this._provisionConfigCache);
}
return this.getConfig(requestId);
})
.then((config) => {
this._provisionConfigCache = config;
})
.then(() => {
const tsInfo = this.provisionData.items.filter(x => x.name === 'ts')[0];
if (tsInfo) {
return Promise.resolve({ status: (tsInfo.level === 'nominal') ? 200 : 404 });
}
return this.recordTransaction(
requestId, 'Fetching TS module information',
this.endpoint.get('/mgmt/shared/telemetry/info', {
validateStatus: () => true // ignore failure status codes
})
);
})
.then((response) => {
const config = this._provisionConfigCache;
this.provisionData.items.push({
name: 'ts',
level: (response.status === 200 && config.enable_telemetry) ? 'nominal' : 'none'
});
})
.then(() => {
if (skipAS3 || (this.as3Info !== null && this.as3Info.version)) {
return Promise.resolve(this.as3Info);
}
return this.recordTransaction(
requestId, 'Fetching AS3 info',
this.endpoint.get('/mgmt/shared/appsvcs/info', {
validateStatus: () => true // ignore failure status codes
})
)
.then(response => response.data);
})
.then((response) => {
this.as3Info = response;
})
.then(() => Promise.all([
Promise.resolve(this.provisionData),
Promise.resolve(this.as3Info)
]));
}
checkDependencies(tmpl, requestId, clearCache) {
return Promise.resolve()
.then(() => this.gatherProvisionData(requestId, clearCache))
.then(([provisionData, as3Info]) => {
const provisionedModules = provisionData.items.filter(x => x.level !== 'none').map(x => x.name);
const as3Version = semver.coerce(as3Info.version || '0.0');
const tmplAs3Version = semver.coerce(tmpl.bigipMinimumAS3 || '3.16');
const deps = tmpl.bigipDependencies || [];
const missingModules = deps.filter(x => !provisionedModules.includes(x));
if (missingModules.length > 0) {
return Promise.reject(new Error(
`could not load template (${tmpl.title}) due to missing modules: ${missingModules}`
));
}
if (!semver.gte(as3Version, tmplAs3Version)) {
return Promise.reject(new Error(
`could not load template (${tmpl.title}) since it requires`
+ ` AS3 >= ${tmpl.bigipMinimumAS3} (found ${as3Version})`
));
}
let promiseChain = Promise.resolve();
tmpl._allOf.forEach((subtmpl) => {
promiseChain = promiseChain
.then(() => this.checkDependencies(subtmpl, requestId));
});
const validOneOf = [];
let errstr = '';
tmpl._oneOf.forEach((subtmpl) => {
promiseChain = promiseChain
.then(() => this.checkDependencies(subtmpl, requestId))
.then(() => {
validOneOf.push(subtmpl);
})
.catch((e) => {
if (!e.message.match(/due to missing modules/)) {
return Promise.reject(e);
}
errstr = `\n${errstr}`;
return Promise.resolve();
});
});
promiseChain = promiseChain
.then(() => {
if (tmpl._oneOf.length > 0 && validOneOf.length === 0) {
return Promise.reject(new Error(
`could not load template since no oneOf had valid dependencies:${errstr}`
));
}
tmpl._oneOf = validOneOf;
return Promise.resolve();
});
const validAnyOf = [];
tmpl._anyOf.forEach((subtmpl) => {
promiseChain = promiseChain
.then(() => this.checkDependencies(subtmpl, requestId))
.then(() => {
validAnyOf.push(subtmpl);
})
.catch((e) => {
if (!e.message.match(/due to missing modules/)) {
return Promise.reject(e);
}
return Promise.resolve();
});
});
promiseChain = promiseChain
.then(() => {
tmpl._anyOf = validAnyOf;
});
return promiseChain;
});
}
getPropsWithChild(schema, childName, recurse) {
const subSchemas = [
...schema.allOf || [],
...schema.oneOf || [],
...schema.anyOf || []
];
const props = Object.entries(schema.properties || {})
.reduce((acc, curr) => {
const [key, value] = curr;
if (value[childName]) {
acc[key] = value;
}
if (value.items) {
if (value.items[childName]) {
acc[`${key}.items`] = value.items;
} else if (value.items.oneOf) {
const prop = value.items.oneOf.find(i => i[childName]);
if (typeof prop !== 'undefined') {
acc[key] = prop;
}
}
}
return acc;
}, {});
if (recurse) {
subSchemas.map(subSchema => Object.assign(props, this.getPropsWithChild(subSchema, childName)));
}
return props;
}
hydrateSchema(tmpl, requestId, clearCache) {
const schema = tmpl._parametersSchema;
const subTemplates = [
...tmpl._allOf || [],
...tmpl._oneOf || [],
...tmpl._anyOf || []
];
if (clearCache) {
this._hydrateCache = null;
}
const ipFromIpamProps = this.getPropsWithChild(schema, 'ipFromIpam');
const enumFromBigipProps = this.getPropsWithChild(schema, 'enumFromBigip');
const propNames = Object.keys(enumFromBigipProps)
.concat(Object.keys(ipFromIpamProps));
if (propNames.length > 0) {
this.logger.fine(
`FAST Worker [${requestId}]: Hydrating properties: ${JSON.stringify(propNames, null, 2)}`
);
}
if (!this._hydrateCache) {
this._hydrateCache = {};
}
return Promise.resolve()
.then(() => {
if (ipFromIpamProps.length === 0) {
return Promise.resolve();
}
if (this._hydrateCache.__config) {
return Promise.resolve();
}
return this.getConfig(requestId)
.then((config) => {
this._hydrateCache.__config = config;
});
})
.then(() => Promise.all(subTemplates.map(x => this.hydrateSchema(x, requestId))))
.then(() => {
const config = this._hydrateCache.__config;
Object.values(ipFromIpamProps).forEach((prop) => {
if (config.ipamProviders.length === 0) {
prop.enum = [null];
} else {
prop.enum = config.ipamProviders.map(x => x.name);
}
});
})
.then(() => Promise.all(Object.values(enumFromBigipProps).map((prop) => {
const epStubs = Array.isArray(prop.enumFromBigip) ? prop.enumFromBigip : [prop.enumFromBigip];
const endPoints = epStubs.map(x => `/mgmt/tm/${x}?$select=fullPath`);
return Promise.resolve()
.then(() => Promise.all(endPoints.map(endPoint => Promise.resolve()
.then(() => {
if (this._hydrateCache[endPoint]) {
return this._hydrateCache[endPoint];
}
return this.recordTransaction(
requestId, `fetching data from ${endPoint}`,
this.endpoint.get(endPoint)
)
.then((response) => {
const items = response.data.items;
this._hydrateCache[endPoint] = items;
return items;
});
})
.then((items) => {
if (items) {
return Promise.resolve(items.map(x => x.fullPath));
}
return Promise.resolve([]);
})
.catch(e => this.handleResponseError(e, `GET to ${endPoint}`))
.catch(e => Promise.reject(new Error(`Failed to hydrate ${endPoint}\n${e.stack}`))))))
.then(itemsArrays => itemsArrays.flat())
.then((items) => {
if (items.length !== 0) {
prop.enum = items;
} else {
prop.enum = [null];
}
});
})))
.then(() => schema);
}
removeIpamProps(tmpl, requestId) {
const subTemplates = [
...tmpl._allOf || [],
...tmpl._oneOf || [],
...tmpl._anyOf || []
];
if (!this._hydrateCache) {
this._hydrateCache = {};
}
return Promise.resolve()
.then(() => Promise.all(subTemplates.map(x => this.removeIpamProps(x, requestId))))
.then(() => {
if (this._hydrateCache.__config) {
return Promise.resolve(this._hydrateCache.__config);
}
return this.getConfig(requestId)
.then((config) => {
this._hydrateCache.__config = config;
return Promise.resolve(config);
});
})
.then((config) => {
if (config.enableIpam) {
return Promise.resolve();
}
const schema = tmpl._parametersSchema;
const props = schema.properties;
const ipamProps = Object.keys(props).filter(x => x.endsWith('_ipam'));
ipamProps.forEach((propName) => {
delete props[propName];
});
if (schema.dependencies) {
Object.entries(schema.dependencies).forEach(([key, value]) => {
value = value.filter(x => !x.endsWith('use_ipam'));
if (value.length === 0) {
delete schema.dependencies[key];
} else {
schema.dependencies[key] = value;
}
});
}
return Promise.resolve();
});
}
convertPoolMembers(reqid, apps) {
reqid = reqid || 0;
const convertTemplateNames = [
'bigip-fast-templates/http',
'bigip-fast-templates/tcp',
'bigip-fast-templates/microsoft_iis'
];
const newApps = [];
apps.forEach((app) => {
const convert = (
convertTemplateNames.includes(app.template)
&& app.view.pool_members
&& app.view.pool_members.length > 0
&& typeof app.view.pool_members[0] === 'string'
);
if (convert) {
app.view.pool_members = [{
serverAddresses: app.view.pool_members,
servicePort: app.view.pool_port || 80
}];
delete app.view.pool_port;
newApps.push(app);
this.logger.info(
`FAST Worker [${reqid}]: updating pool_members on ${app.tenant}/${app.name}`
);
}
});
let promiseChain = Promise.resolve();
if (newApps.length > 0) {
promiseChain = promiseChain
.then(() => this.recordTransaction(
reqid, 'Updating pool members',
this.endpoint.post(`/mgmt/${this.WORKER_URI_PATH}/applications/`, newApps.map(app => ({
name: app.template,
parameters: app.view
})))
))
.then((resp) => {
this.logger.info(
`FAST Worker [${reqid}]: task ${resp.data.message[0].id} submitted to update pool_members`
);
});
}
return promiseChain
.then(() => apps);
}
releaseIPAMAddressesFromApps(reqid, appsData) {
let config;
let promiseChain = Promise.resolve();
appsData.forEach((appDef) => {
let view;
if (appDef.metaData) {
if (Object.keys(appDef.metaData.ipamAddrs || {}) === 0) {
return;
}
view = appDef.metaData;
} else {
if (Object.keys(appDef.ipamAddrs || {}) === 0) {
return;
}
view = appDef;
}
promiseChain = promiseChain
.then(() => {
if (config) {
return Promise.resolve(config);
}
return this.getConfig(reqid)
.then((c) => { config = c; });
})
.then(() => this.ipamProviders.releaseIPAMAddress(reqid, config, view));
});
return promiseChain;
}
fetchTemplate(reqid, tmplid) {
return Promise.resolve()
.then(() => this.recordTransaction(
reqid, 'fetching template',
this.templateProvider.fetch(tmplid)
))
// Copy the template to avoid modifying the stored template
.then(tmpl => fast.Template.fromJson(JSON.stringify(tmpl)))
.then((tmpl) => {
tmpl.title = tmpl.title || tmplid;
return Promise.resolve()
.then(() => this.checkDependencies(tmpl, reqid, true))
.then(() => this.hydrateSchema(tmpl, reqid, true))
.then(() => {
// Remove IPAM features in official templates if not enabled
if (tmplid.split('/')[0] !== 'bigip-fast-templates') {
return Promise.resolve();
}
return this.removeIpamProps(tmpl, reqid);
})
.then(() => tmpl);
});
}
renderTemplates(reqid, data) {
const appsData = [];
const lastModified = new Date().toISOString();
let config = {};
let appsList = [];
let promiseChain = Promise.resolve()
.then(() => this.getConfig(reqid))
.then((configData) => {
config = configData;
})
.then(() => this.driver.listApplicationNames())
.then((listData) => {
appsList = listData.map(x => `${x[0]}/${x[1]}`);
});
data.forEach((tmplData) => {
if (!tmplData.name) {
promiseChain = promiseChain
.then(() => Promise.reject(new Error('name property is missing')));
return;
}
if (!tmplData.parameters) {
promiseChain = promiseChain
.then(() => Promise.reject(new Error('parameters property is missing')));
return;
}
if (typeof tmplData.allowOverwrite === 'undefined') {
tmplData.allowOverwrite = true;
}
const tsData = {};
const [setName, templateName] = tmplData.name.split('/');
const ipamAddrs = {};
promiseChain = promiseChain
.then(() => {
if (!setName || !templateName) {
return Promise.reject(new Error(
`expected name to be of the form "setName/templateName", but got ${tmplData.name}`
));
}
return Promise.resolve();
})
.then(() => this.recordTransaction(
reqid, `fetching template set data for ${setName}`,
this.templateProvider.getSetData(setName)
))
.then(setData => Object.assign(tsData, setData))
.then(() => this.fetchTemplate(reqid, tmplData.name))
.catch(e => Promise.reject(new Error(`unable to load template: ${tmplData.name}\n${e.stack}`)))
.then((tmpl) => {
const schema = tmpl.getParametersSchema();
const ipFromIpamProps = this.getPropsWithChild(schema, 'ipFromIpam', true);
return this.ipamProviders.populateIPAMAddress(ipFromIpamProps, tmplData, config, reqid, ipamAddrs)
.then(() => tmpl);
})
.then(tmpl => this.recordTransaction(
reqid, `rendering template (${tmplData.name})`,
tmpl.fetchAndRender(tmplData.parameters)
))
.then(rendered => JSON.parse(rendered))
.then(decl => Promise.resolve()
.then(() => this.driver.getTenantAndAppFromDecl(decl))
.then(([tenantName, appName]) => `${tenantName}/${appName}`)
.then((tenantAndApp) => {
if (!tmplData.allowOverwrite && appsList.includes(tenantAndApp)) {
return Promise.reject(new Error(
`application ${tenantAndApp} already exists and "allowOverwrite" is false`
));
}
return Promise.resolve();
})
.then(() => decl))
.catch(e => Promise.resolve()
// Release any IPAM IP addrs
.then(() => this.ipamProviders.releaseIPAMAddress(reqid, config, { ipamAddrs }))
// Now re-reject
.then(() => Promise.reject(new Error(`failed to render template: ${tmplData.name}\n${e.stack}`))))
.then((decl) => {
const appData = {
appDef: decl,
metaData: {
template: tmplData.name,
setHash: tsData.hash,
view: tmplData.parameters,
lastModified,
ipamAddrs
}
};
appsData.push(appData);
const oldAppData = tmplData.previousDef || {};
if (oldAppData.ipamAddrs) {
this.ipamProviders.releaseIPAMAddress(reqid, config, oldAppData, ipamAddrs);
}
});
});
promiseChain = promiseChain
.then(() => appsData);
return promiseChain;
}
/**
* HTTP/REST handlers
*/
recordRestRequest(restOp) {
// Update driver's user agent if one was provided with the request
const userAgent = restOp.getUri().query.userAgent;
this.incomingUserAgent = userAgent || '';
this.driver.userAgent = userAgent ? `${userAgent};${this.baseUserAgent}` : this.baseUserAgent;
// Record the time we received the request
this.requestTimes[restOp.requestId] = Date.now();
// Dump information to the log
this.logger.fine(
`FAST Worker [${restOp.requestId}]: received request method=${restOp.getMethod()}; path=${restOp.getUri().pathname}; userAgent=${this.incomingUserAgent}`
);
}
recordRestResponse(restOp) {
const minOp = {
method: restOp.getMethod(),
path: restOp.getUri().pathname,
status: restOp.getStatusCode()
};
const dt = Date.now() - this.requestTimes[restOp.requestId];
const msg = `FAST Worker [${restOp.requestId}]: sending response after ${dt}ms\n${JSON.stringify(minOp, null, 2)}`;
delete this.requestTimes[restOp.requestId];
if (minOp.status >= 400) {
this.logger.info(msg);
} else {
this.logger.fine(msg);
}
}
genRestResponse(restOperation, code, message) {
let doParse = false;
if (typeof message !== 'string') {
message = JSON.stringify(message, null, 2);
doParse = true;
}
message = message
.replace(/</g, '<')
.replace(/>/g, '>');
if (doParse) {
message = JSON.parse(message);
}
restOperation.setStatusCode(code);
restOperation.setBody({
code,
message
});
this.completeRestOperation(restOperation);
if (code >= 400) {
this.generateTeemReportError(restOperation);
}
return Promise.resolve();
}
getInfo(restOperation) {
return Promise.resolve()
.then(() => this.gatherInfo(restOperation.requestId))
.then((info) => {
restOperation.setBody(info);
this.completeRestOperation(restOperation);
})
.catch(e => this.genRestResponse(restOperation, 500, e.stack));
}
getTemplates(restOperation, tmplid) {
const reqid = restOperation.requestId;
if (tmplid) {
const uri = restOperation.getUri();
const pathElements = uri.pathname.split('/');
tmplid = pathElements.slice(4, 6).join('/');
return Promise.resolve()
.then(() => this.fetchTemplate(reqid, tmplid))
.then((tmpl) => {
restOperation.setBody(tmpl);
this.completeRestOperation(restOperation);
})
.catch((e) => {
if (e.message.match(/Could not find template/)) {
return this.genRestResponse(restOperation, 404, e.stack);
}
return this.genRestResponse(restOperation, 400, `Error: Failed to load template ${tmplid}\n${e.stack}`);
});
}
return Promise.resolve()
.then(() => this.recordTransaction(
reqid, 'fetching template list',
this.templateProvider.list()
.then(tmplList => this.filterTemplates(tmplList))
))
.then((templates) => {
restOperation.setBody(templates);
this.completeRestOperation(restOperation);
})
.catch(e => this.genRestResponse(restOperation, 500, e.stack));
}
getApplications(restOperation, appid) {
const reqid = restOperation.requestId;
if (appid) {
const uri = restOperation.getUri();
const pathElements = uri.pathname.split('/');
const tenant = pathElements[4];
const app = pathElements[5];
return Promise.resolve()
.then(() => this.recordTransaction(
reqid, 'GET request to appsvcs/declare',
this.endpoint.get('/mgmt/shared/appsvcs/declare')
))
.then(resp => resp.data[tenant][app])
.then(appDef => this.convertPoolMembers(reqid, [appDef]))
.then((appDefs) => {
restOperation.setBody(appDefs[0]);
this.completeRestOperation(restOperation);
})
.catch(e => this.genRestResponse(restOperation, 404, e.stack));
}
return Promise.resolve()
.then(() => this.recordTransaction(
reqid, 'gathering a list of applications from the driver',
this.driver.listApplications()
))
.then(appsList => this.convertPoolMembers(reqid, appsList))
.then((appsList) => {
restOperation.setBody(appsList);
this.completeRestOperation(restOperation);
});
}
getTasks(restOperation, taskid) {
const reqid = restOperation.requestId;
if (taskid) {
return Promise.resolve()
.then(() => this.recordTransaction(
reqid, 'gathering a list of tasks from the driver',
this.driver.getTasks()
))
.then(taskList => taskList.filter(x => x.id === taskid))
.then((taskList) => {
if (taskList.length === 0) {
return this.genRestResponse(restOperation, 404, `unknown task ID: ${taskid}`);
}
restOperation.setBody(taskList[0]);
this.completeRestOperation(restOperation);
return Promise.resolve();
})
.catch(e => this.genRestResponse(restOperation, 500, e.stack));
}
return Promise.resolve()
.then(() => this.recordTransaction(
reqid, 'gathering a list of tasks from the driver',
this.driver.getTasks()
))
.then((tasksList) => {
restOperation.setBody(tasksList);
this.completeRestOperation(restOperation);
})
.catch(e => this.genRestResponse(restOperation, 500, e.stack));
}
getTemplateSets(restOperation, tsid) {
const queryParams = restOperation.getUri().query;
const showDisabled = queryParams.showDisabled || false;
const reqid = restOperation.requestId;
if (tsid) {
return Promise.resolve()
.then(() => this.recordTransaction(
reqid, 'gathering a template set',
this.gatherTemplateSet(tsid)
))
.then((tmplSet) => {
restOperation.setBody(tmplSet);
if (tmplSet.error) {
return Promise.reject(new Error(tmplSet.error));
}
this.completeRestOperation(restOperation);
return Promise.resolve();
})
.catch((e) => {
if (e.message.match(/No templates found/) || e.message.match(/does not exist/)) {
return this.genRestResponse(restOperation, 404, e.message);
}
return this.genRestResponse(restOperation, 500, e.stack);
});
}
return Promise.resolve()
.then(() => this.recordTransaction(
reqid, 'gathering a list of template sets',
(showDisabled) ? this.fsTemplateProvider.listSets() : this.templateProvider.listSets()
))
.then(setList => this.recordTransaction(
reqid, 'gathering data for each template set',
Promise.all(setList.map(x => this.gatherTemplateSet(x)))
))
.then(setList => ((showDisabled) ? setList.filter(x => !x.enabled) : setList))
.then((setList) => {
restOperation.setBody(setList);
this.completeRestOperation(restOperation);
})
.catch(e => this.genRestResponse(restOperation, 500, e.stack));
}
getSettings(restOperation) {
const reqid = restOperation.requestId;
return Promise.resolve()
.then(() => this.getConfig(reqid))
.then((config) => {
restOperation.setBody(config);
this.completeRestOperation(restOperation);
})
.catch(e => this.genRestResponse(restOperation, 500, e.stack));
}
getSettingsSchema(restOperation) {
return Promise.resolve()
.then(() => {
const schema = this.getConfigSchema();
restOperation.setBody(schema);
this.completeRestOperation(restOperation);
})
.catch(e => this.genRestResponse(restOperation, 500, e.stack));
}
onGet(restOperation) {
const uri = restOperation.getUri();
const pathElements = uri.pathname.split('/');
const collection = pathElements[3];
const itemid = pathElements[4];
restOperation.requestId = this.generateRequestId();
this.recordRestRequest(restOperation);
try {
switch (collection) {
case 'info':
return this.getInfo(restOperation);
case 'templates':
return this.getTemplates(restOperation, itemid);
case 'applications':
return this.getApplications(restOperation, itemid);
case 'tasks':
return this.getTasks(restOperation, itemid);
case 'templatesets':
return this.getTemplateSets(restOperation, itemid);
case 'settings':
return this.getSettings(restOperation);
case 'settings-schema':
return this.getSettingsSchema(restOperation);
default:
return this.genRestResponse(restOperation, 404, `unknown endpoint ${uri.pathname}`);
}
} catch (e) {
return this.genRestResponse(restOperation, 500, e.stack);
}
}
postApplications(restOperation, data) {
const reqid = restOperation.requestId;
if (!Array.isArray(data)) {
data = [data];
}
// this.logger.info(`postApplications() received:\n${JSON.stringify(data, null, 2)}`);
let appsData;
return Promise.resolve()
.then(() => this.renderTemplates(reqid, data))
.catch((e) => {
let code = 400;
if (e.message.match(/Could not find template/)) {
code = 404;
}
return Promise.reject(this.genRestResponse(restOperation, code, e.stack));
})
.then((renderResults) => {
appsData = renderResults;
})
.then(() => {
appsData.forEach((appData) => {
this.generateTeemReportApplication('modify', appData.template);
});
return appsData;
})
.then(() => this.recordTransaction(
reqid, 'requesting new application(s) from the driver',
this.driver.createApplications(appsData)
))
.catch((e) => {
if (restOperation.getStatusCode() >= 400) {
return Promise.reject();
}
return this.releaseIPAMAddressesFromApps(reqid, appsData)
.then(() => Promise.reject(this.genRestResponse(
restOperation,
400,
`error generating AS3 declaration\n${e.stack}`
)));
})
.then((response) => {
if (response.status >= 300) {
return this.genRestResponse(restOperation, response.status, response.body);
}
return this.genRestResponse(restOperation, response.status, data.map(
x => ({
id: response.body.id,
name: x.name,
parameters: x.parameters
})
));
})
.catch((e) => {
if (restOperation.getStatusCode() < 400) {
this.genRestResponse(restOperation, 500, e.stack);
}
});
}
_validateTemplateSet(tspath) {
const tmplProvider = new FsTemplateProvider(tspath);
return tmplProvider.list()
.then((templateList) => {
if (templateList.length === 0) {
return Promise.reject(new Error('template set contains no templates'));
}
return Promise.resolve(templateList);
})
.then(templateList => Promise.all(templateList.map(tmpl => tmplProvider.fetch(tmpl))));
}
postTemplateSets(restOperation, data) {
const tsid = data.name;
const reqid = restOperation.requestId;
const setpath = `${uploadPath}/${tsid}.zip`;
const scratch = `${scratchPath}/${tsid}`;
const onDiskPath = `${templatesPath}/${tsid}`;
if (!data.name) {
return this.genRestResponse(restOperation, 400, `invalid template set name supplied: ${tsid}`);
}
if (!fs.existsSync(setpath) && !fs.existsSync(onDiskPath)) {
return this.genRestResponse(restOperation, 404, `${setpath} does not exist`);
}
// Setup a scratch location we can use while validating the template set
this.enterTransaction(reqid, 'prepare scratch space');
fs.removeSync(scratch);
fs.mkdirsSync(scratch);
this.exitTransaction(reqid, 'prepare scratch space');
return Promise.resolve()
.then(() => this.enterTransaction(reqid, 'extract template set'))
.then(() => {
if (fs.existsSync(onDiskPath)) {
return fs.copy(onDiskPath, scratch);
}
return new Promise((resolve, reject) => {
extract(setpath, { dir: scratch }, (err) => {
if (err) return reject(err);
return resolve();
});
});
})
.then(() => this.exitTransaction(reqid, 'extract template set'))
.then(() => this.recordTransaction(
reqid, 'validate template set',
this._validateTemplateSet(scratchPath)
))
.catch(e => Promise.reject(new Error(`Template set (${tsid}) failed validation: ${e.message}. ${e.stack}`)))
.then(() => this.enterTransaction(reqid, 'write new template set to data store'))
.then(() => this.templateProvider.invalidateCache())
.then(() => DataStoreTemplateProvider.fromFs(this.storage, scratchPath, [tsid]))
.then(() => {
this.generateTeemReportTemplateSet('create', tsid);
})
.then(() => this.storage.persist())
.then(() => this.storage.keys()) // Regenerate the cache, might as well take the hit here
.then(() => this.exitTransaction(reqid, 'write new template set to data store'))
.then(() => this.getConfig(reqid))
.then((config) => {
if (config.deletedTemplateSets.includes(tsid)) {
config.deletedTemplateSets = config.deletedTemplateSets.filter(x => x !== tsid);
return this.saveConfig(config, reqid);
}
return Promise.resolve();
})
// Automatically convert any apps using the old pool_members definition
.then(() => {
if (tsid !== 'bigip-fast-templates') {
return Promise.resolve();
}
return this.recordTransaction(
reqid, 'converting applications with old pool_members definition',
this.convertPoolMembers(reqid)
);
})
.then(() => this.genRestResponse(restOperation, 200, ''))
.catch((e) => {
if (e.message.match(/failed validation/)) {
return this.genRestResponse(restOperation, 400, e.message);
}
return this.genRestResponse(restOperation, 500, e.stack);
})
.finally(() => fs.removeSync(scratch));
}
postSettings(restOperation, config) {
const reqid = restOperation.requestId;
return Promise.resolve()
.then(() => this.validateConfig(config))
.catch(e => Promise.reject(this.genRestResponse(
restOperation, 422,
`supplied settings were not valid:\n${e.message}`
)))
.then(() => this.getConfig(reqid))
.then(prevConfig => this.encryptConfigSecrets(config, prevConfig))
.then(() => this.gatherProvisionData(reqid, true))
.then(provisionData => this.driver.setSettings(config, provisionData))
.then(() => this.saveConfig(config, reqid))
.then(() => this.genRestResponse(restOperation, 200, ''))
.catch((e) => {
if (restOperation.getStatusCode() < 400) {
this.genRestResponse(restOperation, 500, e.stack);
}
});
}
postRender(restOperation, data) {
const reqid = restOperation.requestId;
if (!Array.isArray(data)) {
data = [data];
}
// this.logger.info(`postRender() received:\n${JSON.stringify(data, null, 2)}`);
return Promise.resolve()
.then(() => this.renderTemplates(reqid, data))
.catch((e) => {
let code = 400;
if (e.message.match(/Could not find template/)) {
code = 404;
}
return Promise.reject(this.genRestResponse(restOperation, code, e.stack));
})
.then(rendered => this.releaseIPAMAddressesFromApps(reqid, rendered)
.then(() => rendered))
.then(rendered => this.genRestResponse(restOperation, 200, rendered))
.catch((e) => {
if (restOperation.getStatusCode() < 400) {
this.genRestResponse(restOperation, 500, e.stack);
}
});
}
onPost(restOperation) {
const body = restOperation.getBody();
const uri = restOperation.getUri();
const pathElements = uri.pathname.split('/');
const collection = pathElements[3];
restOperation.requestId = this.generateRequestId();
this.recordRestRequest(restOperation);
try {
switch (collection) {
case 'applications':
return this.postApplications(restOperation, body);
case 'templatesets':
return this.postTemplateSets(restOperation, body);
case 'settings':
return this.postSettings(restOperation, body);
case 'render':
return this.postRender(restOperation, body);
default:
return this.genRestResponse(restOperation, 404, `unknown endpoint ${uri.pathname}`);
}
} catch (e) {
return this.genRestResponse(restOperation, 500, e.message);
}
}
deleteApplications(restOperation, appid, data) {
const reqid = restOperation.requestId;
const uri = restOperation.getUri();
const pathElements = uri.pathname.split('/');
if (appid) {
data = [`${pathElements[4]}/${pathElements[5]}`];
} else if (!data) {
data = [];
}
if (typeof data === 'string') {
// convert empty string to an empty array
data = [];
}
const appNames = data.map(x => x.split('/'));
return Promise.resolve()
.then(() => this.recordTransaction(
reqid, 'requesting application data from driver',
Promise.all(appNames.map(x => this.driver.getApplication(...x)))
))
.then(appsData => this.releaseIPAMAddressesFromApps(reqid, appsData))
.then(() => this.recordTransaction(
reqid, 'deleting applications',
this.driver.deleteApplications(appNames)
))
.then((result) => {
restOperation.setHeaders('Content-Type', 'text/json');
restOperation.setBody(result.body);
restOperation.setStatusCode(result.status);
this.completeRestOperation(restOperation);
})
.then(() => {
this.generateTeemReportApplication('delete', '');
})
.catch((e) => {
if (e.message.match('no tenant found')) {
return this.genRestResponse(restOperation, 404, e.message);
}
if (e.message.match('could not find application')) {
return this.genRestResponse(restOperation, 404, e.message);
}
return this.genRestResponse(restOperation, 500, e.stack);
});
}
deleteTemplateSets(restOperation, tsid) {
const reqid = restOperation.requestId;
if (tsid) {
return Promise.resolve()
.then(() => this.recordTransaction(
reqid, `gathering template set data for ${tsid}`,
this.gatherTemplateSet(tsid)
))
.then((setData) => {
const usedBy = setData.templates.reduce((acc, curr) => {
acc.push(...curr.appsList);
return acc;
}, []);
if (usedBy.length > 0) {
return Promise.reject(
new Error(`Cannot delete template set ${tsid}, it is being used by:\n${JSON.stringify(usedBy)}`)
);
}
return Promise.resolve();
})
.then(() => this.recordTransaction(
reqid, 'deleting a template set from the data store',
this.templateProvider.removeSet(tsid)
))
.then(() => this.getConfig(reqid))
.then((config) => {
config.deletedTemplateSets.push(tsid);
return this.saveConfig(config, reqid);
})
.then(() => {
this.generateTeemReportTemplateSet('delete', tsid);
})
.then(() => this.recordTransaction(
reqid, 'persisting the data store',
this.storage.persist()
.then(() => this.storage.keys()) // Regenerate the cache, might as well take the hit here
))
.then(() => this.genRestResponse(restOperation, 200, 'success'))
.catch((e) => {
if (e.message.match(/failed to find template set/)) {
return this.genRestResponse(restOperation, 404, e.message);
}
if (e.message.match(/being used by/)) {
return this.genRestResponse(restOperation, 400, e.message);
}
return this.genRestResponse(restOperation, 500, e.stack);
});
}
return Promise.resolve()
.then(() => this.recordTransaction(
reqid, 'gathering a list of template sets',
this.templateProvider.listSets()
))
.then((setList) => {
let promiseChain = Promise.resolve();
setList.forEach((set) => {
promiseChain = promiseChain
.then(() => this.recordTransaction(
reqid, `deleting template set: ${set}`,
this.templateProvider.removeSet(set)
));
});
return promiseChain
.then(() => this.recordTransaction(
reqid, 'persisting the data store',
this.storage.persist()
))
.then(() => this.getConfig(reqid))
.then((config) => {
config.deletedTemplateSets = [...new Set(config.deletedTemplateSets.concat(setList))];
return this.saveConfig(config, reqid);
});
})
.then(() => this.genRestResponse(restOperation, 200, 'success'))
.catch(e => this.genRestResponse(restOperation, 500, e.stack));
}
deleteSettings(restOperation) {
return Promise.resolve()
.then(() => this.configStorage.deleteItem(configKey))
.then(() => this.genRestResponse(restOperation, 200, 'success'))
.catch(e => this.genRestResponse(restOperation, 500, e.stack));
}
onDelete(restOperation) {
const body = restOperation.getBody();
const uri = restOperation.getUri();
const pathElements = uri.pathname.split('/');
const collection = pathElements[3];
const itemid = pathElements[4];
restOperation.requestId = this.generateRequestId();
this.recordRestRequest(restOperation);
try {
switch (collection) {
case 'applications':
return this.deleteApplications(restOperation, itemid, body);
case 'templatesets':
return this.deleteTemplateSets(restOperation, itemid);
case 'settings':
return this.deleteSettings(restOperation);
default:
return this.genRestResponse(restOperation, 404, `unknown endpoint ${uri.pathname}`);
}
} catch (e) {
return this.genRestResponse(restOperation, 500, e.stack);
}
}
patchApplications(restOperation, appid, data) {
if (!appid) {
return Promise.resolve()
.then(() => this.genRestResponse(
restOperation, 400, 'PATCH is not supported on this endpoint'
));
}
const reqid = restOperation.requestId;
const uri = restOperation.getUri();
const pathElements = uri.pathname.split('/');
const tenant = pathElements[4];
const app = pathElements[5];
const newParameters = data.parameters;
return Promise.resolve()
.then(() => this.recordTransaction(
reqid, 'Fetching application data from AS3',
this.driver.getApplication(tenant, app)
))
.then(appData => this.recordTransaction(
reqid, 'Re-deploying application',
this.endpoint.post(`/mgmt/${this.WORKER_URI_PATH}/applications`, {
name: appData.template,
parameters: Object.assign({}, appData.view, newParameters)
})
))
.then(resp => this.genRestResponse(restOperation, resp.status, resp.data))
.catch(e => this.genRestResponse(restOperation, 500, e.stack));
}
patchSettings(restOperation, config) {
const reqid = restOperation.requestId;
let combinedConfig = {};
return Promise.resolve()
.then(() => this.getConfig(reqid))
.then(prevConfig => this.encryptConfigSecrets(config, prevConfig)
.then(() => prevConfig))
.then((prevConfig) => {
combinedConfig = Object.assign({}, prevConfig, config);
})
.then(() => this.validateConfig(combinedConfig))
.catch(e => Promise.reject(this.genRestResponse(
restOperation, 422,
`supplied settings were not valid:\n${e.message}`
)))
.then(() => this.gatherProvisionData(reqid, true))
.then(provisionData => this.driver.setSettings(combinedConfig, provisionData))
.then(() => this.saveConfig(combinedConfig, reqid))
.then(() => this.genRestResponse(restOperation, 200, ''))
.catch((e) => {
if (restOperation.getStatusCode() < 400) {
this.genRestResponse(restOperation, 500, e.stack);
}
});
}
onPatch(restOperation) {
const body = restOperation.getBody();
const uri = restOperation.getUri();
const pathElements = uri.pathname.split('/');
const collection = pathElements[3];
const itemid = pathElements[4];
restOperation.requestId = this.generateRequestId();
this.recordRestRequest(restOperation);
try {
switch (collection) {
case 'applications':
return this.patchApplications(restOperation, itemid, body);
case 'settings':
return this.patchSettings(restOperation, body);
default:
return this.genRestResponse(restOperation, 404, `unknown endpoint ${uri.pathname}`);
}
} catch (e) {
return this.genRestResponse(restOperation, 500, e.stack);
}
}
}
module.exports = FASTWorker;
|
const db = require('./index')
const bcrypt = require('bcrypt')
const User = db.sequelize.define('user', {
name: { type: db.Sequelize.STRING, unique: true },
password: { type: db.Sequelize.STRING },
access_token: { type: db.Sequelize.STRING },
}, {
classMethods: {},
tableName: 'user',
freezeTableName: true,
underscored: true,
timestamps: true,
paranoid: true,
hooks: {
afterValidate: (user, options) => {
user.access_token = bcrypt.hashSync(user.password, 8)
}
},
})
module.exports = User
|
// this is the mysql database plugin for accessing the queue store
var mysql = require('mysql');
// app opens the connection once only
var connect = function(app, host, port, database, user, password) {
connection = mysql.createConnection({
'host' : host,
'user' : user,
'password' : password,
'database' : database
});
connection.connect();
app.QueueProvider.connection = connection;
console.log("Queue Bound to Application");
};
// close connection
var end = function(app,callback) {
connection.end(function(err) {
return callback(err);
});
}
var getBatch = function(app,callback) {
// test if already in the queue if so throw an error
// get batchNo from msg or app.json obejct
// get queueName and message from app.body.json object and body.raw
var batchNo = "5";
var queueName = app.body.json["soap:Body"]["itk:QueueMessage"]["itk:QueueName"];
var cmd = 'SELECT CONVERT(message USING utf8) as message, messageId from queue WHERE queuename = "' + queueName +'" and status = 0 LIMIT ' + batchNo;
var items = new Array();
app.QueueProvider.connection.query(cmd, function(err, rows, fields) {
if (err) throw err;
for (var i =0; i < rows.length; i++){
// create an in statement and execute at the end
items[i] = {};
items[i].messageId = rows[i].messageId;
items[i].message = rows[i].message;
var updatecmd = 'update queue set status = 1 WHERE queuename = "' + queueName +'" and status = 0 and messageId = "' + rows[i].messageId +'"';
app.QueueProvider.connection.query(updatecmd, function(err, rows, fields) {
});
// build up the response message here
}
return callback(items, null);
});
}
var add = function(app, queueName, callback) {
// test if already in the queue if so throw an error
// get msg id from msg or app.json obejct
// get queueName and message from app.body.json object and body.raw
var msg = app.body.json;
var messageId = msg['soap:Header']['wsa:MessageID'];
var data = app.QueueProvider.connection.escape(app.body.raw);
var cmd = 'INSERT INTO queue (messageId, queueName, message, datereceived) values ("' + messageId +'", "' + queueName + '", "' + data +'", NOW())';
console.log(cmd);
app.QueueProvider.connection.query(cmd, function(err, rows, fields) {
return callback(err);
});
}
var isQueued = function(app,queueName,callback) {
var cmd = 'SELECT TOP ' + batchNo +' from queue WHERE queuename = "' + queueName +'" and status = 1';
app.QueueProvider.connection.query(cmd, function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
}
/* status of message
0 - ready to retrieve
1 - retrieved pending confirmation
2 - confirmation received - pending archiving
*/
var update = function (app, callback) {
// test if already in the queue if so throw an error
var msg = app.body.json;
var queueName = msg['soap:Body']['itk:QueueConfirmMessageReceipt']['itk:QueueName'];
// group these into a batch statement and execute per batch
var MessageHandle = msg['soap:Body']['itk:QueueConfirmMessageReceipt']['itk:MessageHandle'];
for (var i = 0; i< MessageHandle.length; i++){
cmd = 'UPDATE queue SET status = 2 WHERE queueName = "' + queueName +'" and messageId = "' + MessageHandle[i] + '"';
console.log(MessageHandle[i]);
app.QueueProvider.connection.query(cmd, function(err, rows, fields) {
});
}
return callback();
}
var archive = function (id, queueName, callback) {
// move into archive table
}
exports.connect = connect;
exports.archive = archive;
exports.update = update;
exports.isQueued = isQueued;
exports.add = add;
exports.getBatch = getBatch;
exports.end = end;
|
'use strict';
//let x = alert('Alert Prompt Confirm');
//let x = prompt('Сколько тебе лет?');
//let x = confirm('Ты самый умный?');
//
//console.log(`Значение Х: ${x}`);
let name = prompt('Как тебя зовут?');
console.log(`Привет, ${name}`);
|
"use strict";
const util = require('util');
const Message = require(__dirname + '/message');
const REQUIRED_ARGUMENTS = ["url"];
function UrlMessage(url, optionalKeyboard, optionalTrackingData, timestamp, token, minApiVersion) {
this.url = url ? encodeURI(url) : null;
UrlMessage.super_.apply(this, [REQUIRED_ARGUMENTS, optionalKeyboard, optionalTrackingData, timestamp, token, minApiVersion]);
}
util.inherits(UrlMessage, Message);
UrlMessage.fromJson = function(jsonMessage, timestamp, token) {
return new UrlMessage(jsonMessage.media, null, jsonMessage.tracking_data, timestamp, token);
};
UrlMessage.getType = function() {
return "url";
};
UrlMessage.prototype.toJson = function() {
return {
"type": UrlMessage.getType(),
"media": this.url
};
};
module.exports = UrlMessage;
|
(function () {
angular
.module('myApp')
.controller('teacherScoreController', teacherScoreController)
teacherScoreController.$inject = ['$state', '$scope', '$rootScope', '$filter'];
function teacherScoreController($state, $scope, $rootScope, $filter) {
// ****************** router: teacherGiveScore ****************************
$rootScope.setData('showMenubar', true);
$rootScope.setData('backUrl', "groupRoot");
$scope.question = $rootScope.settings.question;
$rootScope.safeApply();
$scope.$on('$destroy', function () {
if ($scope.groupRef) $scope.groupRef.off('value')
if ($scope.answerRef) $scope.answerRef.off('value')
if ($scope.qstRef) $scope.qstRef.off('value')
})
$scope.init = function () {
$rootScope.setData('loadingfinished', false);
$scope.getStudentsInGroup();
$scope.getanswers();
$scope.getState();
}
$scope.getStudentsInGroup = function () {
$scope.groupRef = firebase.database().ref('StudentGroups');
$scope.groupRef.on('value', function (studentGroups) {
$scope.studentsInGroup = [];
var studentGroup = studentGroups.val();
for (var studentKey in studentGroup) {
var obj = studentGroup[studentKey];
if (Object.values(obj).indexOf($rootScope.settings.groupKey) > -1) {
$scope.studentsInGroup.push(studentKey);
}
}
$scope.ref_1 = true
$scope.finalCalc()
})
}
$scope.getanswers = function () {
$scope.answerRef = firebase.database().ref('NewAnswers/' + $scope.question.code + '/answer');
$scope.answerRef.on('value', function (snapshot) {
$scope.allAnswers = snapshot.val() || {};
$scope.ref_2 = true
$scope.finalCalc()
});
}
$scope.getState = function () {
$scope.qstRef = firebase.database().ref('Questions/' + $scope.question.key);
$scope.qstRef.on('value', function (snapshot) {
let question = snapshot.val() || {}
$scope.showScore = question.showScore ? question.showScore : false
$scope.showFeedback = question.showFeedback ? question.showFeedback : false
$scope.ref_3 = true
$scope.finalCalc()
});
}
$scope.finalCalc = function () {
if (!$scope.ref_1 || !$scope.ref_2 || !$scope.ref_3) return
$scope.answers = {}
for (userKey in $scope.allAnswers) {
if ($scope.studentsInGroup.indexOf(userKey) > -1) {
$scope.answers[userKey] = $scope.allAnswers[userKey]
}
}
$rootScope.safeApply()
$rootScope.setData('loadingfinished', true);
}
$scope.scoreChanged = function (key) {
firebase.database().ref('NewAnswers/' + $scope.question.code + '/answer/' + key + '/score').set($scope.answers[key].score);
}
$scope.feedbackChanged = function (key) {
firebase.database().ref('NewAnswers/' + $scope.question.code + '/answer/' + key + '/feedback').set($scope.answers[key].feedback);
}
$scope.changeShowScore=function(showScore){
firebase.database().ref('Questions/' + $scope.question.key+'/showScore').set(showScore)
}
$scope.changeShowFeedback=function(showFeedback){
firebase.database().ref('Questions/' + $scope.question.key+'/showFeedback').set(showFeedback)
}
}
})();
|
const fetch = require('https');
const zApiKey = "d436351503c1a24f2215626e78067a16";
exports.handler = async (event) => {
console.log("getZomatoRestaurants");
var lat = event.latitude;
var lng = event.longitude;
const urlBase = 'developers.zomato.com';
var latitude = "lat=" + lat + "&";
var longitude = "lon=" + lng;
var path = "/api/v2.1/geocode?" + latitude + longitude;
var options = {
"hostname": urlBase,
"path": path,
"method": 'GET',
"headers": {'Accept': 'application/json', 'user-key': zApiKey}
};
return new Promise((resolve, reject) => {
fetch.get(options, (resp) => {
var data = '';
resp.on('data', (chunk) => {
data+=chunk;
});
resp.on('end', () => {
data = JSON.parse(data);
resolve(data);
});
resp.on('error', (err) => {
console.error(err);
});
});
});
};
|
const Discord = require('discord.js');
const bot = new Discord.Client();
module.exports.run = async (bot, message, args) => {
let sImage = bot.guild.displayAvatarURl
let sEmbed = new Discord.RichEmbed()
.setColor('RANDOM')
.setThumbnail(sImage)
.setDescription(bot.guild.name)
.addField('Serverdaki kişi sayısı ')
}
module.exports.help = {
name: "sunucubilgi",
}
|
const express = require('express');
const router = express.Router();
const userSchema = require('../models/user');
const deviceSchema = require('../models/device');
const snmpAgentSchema = require('../models/snmp_agent');
const agentController = require('../controllers/snmpagents');
const deviceController = require('../controllers/devices');
const authController = require('../controllers/auth');
/* GET API home page */
router.get('/', function(req, res, next) {
//Return version=1 in json
res.jsonp({
'v' : '1'
});
});
router.route('/agents')
.get(agentController.findAllSNMPAgents)
.post(agentController.addSNMPAgent);
router.route('/agent/:id')
.get(agentController.findSNMPAgentById)
.put(agentController.updateSNMPAgent)
.delete(agentController.deleteSNMPAgent);
router.route('/devices')
.get(deviceController.findAllDevices)
.post(deviceController.addDevice);
router.route('/device/:id')
.get(deviceController.findDeviceById)
.put(deviceController.updateDevice)
.delete(deviceController.deleteDevice);
router.route('/auth/authenticate')
.get(authController.authenticateUser);
router.get('/user/:id', function(req, res, next) {
if(req.param.id && req.param.id != ''){
userSchema.findOne({'local.username' : req.param.id},(err,doc)=>{
if(err) res.status(500,err.message);
res.status(200).jsonp(doc);
});
}else{
userSchema.find({},(err,doc)=>{
if(err) res.status(500,err.message);
res.status(200).jsonp(doc);
});
}
});
module.exports = router;
|
const React = require("react");
const NotFound = () => (
<div>
<p>404!</p>
</div>
)
export default NotFound
|
import { merge, withStatus, withBody } from "litera";
import { isDatabaseError } from "./utils";
// probably move to litera-knex-error-handler
export const errorHandler = atom => async (req, data) => {
try {
return await atom(req, data);
} catch (err) {
if (isDatabaseError(err)) {
return merge(
withStatus(400),
process.env.NODE_ENV !== "production" &&
withBody("Knex request failure")
);
}
throw err;
}
};
|
const {google} = require('googleapis');
const authorize = require("./sheets_auth");
// Main code (using sheets_auth)
authorize(listMajors);
/**
* Prints the names and majors of students in a sample spreadsheet:
* @see https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
* @param {google.auth.OAuth2} auth The authenticated Google OAuth client.
*/
function listMajors(auth) {
const sheets = google.sheets({version: 'v4', auth});
sheets.spreadsheets.values.get({
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
range: 'Class Data!A2:E',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const rows = res.data.values;
if (rows.length) {
console.log('Name, Major:');
// Print columns A and E, which correspond to indices 0 and 4.
rows.map((row) => {
console.log(`${row[0]}, ${row[4]}`);
});
} else {
console.log('No data found.');
}
});
}
|
import {mergeReducer, isFunction} from './index';
function checkAsyncHandlers (handlers) {
const {onWait, onSuccess, onFail} = handlers;
const errMessage = (fnName) => `Expected that the ${fnName} will be a function, and will returns new state`;
if (!isFunction(onWait)) {
throw new Error(errMessage('onWait'));
}
if (!isFunction(onSuccess)) {
throw new Error(errMessage('onSuccess'));
}
if (!isFunction(onFail)) {
throw new Error(errMessage('onFail'));
}
}
/**
*
* @param {String} name
* @param {Object} options
* @returns {Function}
*/
export function createAction (name, options = {}) {
const WAIT = `WAIT@${name}`;
const SUCCESS = `SUCCESS@${name}`;
const FAIL = `FAIL@${name}`;
const type = name;
const {action, async, storeKey, handlers, handler, initialState} = options;
let reducer;
if (!initialState) {
throw new Error('Initial state should not be null or undefined');
}
if (!storeKey) {
throw new Error(`Store key at action ${name} not defined`);
}
if (async) {
checkAsyncHandlers(handlers);
reducer = (state = initialState, action) => {
switch(action.type) {
case WAIT: return handlers.onWait(state, action);
case SUCCESS: return handlers.onSuccess(state, action);
case FAIL: return handlers.onFail(state, action);
default: return state;
}
};
}
else {
if (!isFunction(handler)) {
throw new Error(`Expected that synchronous action ${name} handler will be a function, and it will returns new state`)
}
reducer = (state = initialState, action) => action.type === name ? handler(state, action) : state;
}
mergeReducer(storeKey, reducer);
return function (...args) {
return (function () {
const {promise, type: excludeTypeFromActionIfExists, ...actionPayload} = action.apply(undefined, args);
if (async) {
if (!isFunction(promise)) {
throw new Error(`Async action ${name} should return promise property of Function type`);
}
else {
return {types: [WAIT, SUCCESS, FAIL], promise, ...actionPayload}
}
}
else {
return {type, ...actionPayload};
}
})();
}
}
function defaultAction() { return {}; }
export function createActions(options = Object.assign({},defaults)) {
const {actions, initialState: globalInitialState, storeKey: globalStoreKey} = options;
if (!Object.keys(actions)) {
throw new Error('No any action passed');
}
return Object.entries(actions).reduce((res, [actionName, actionOptions]) => {
const {
async: optionAsync,
initialState,
storeKey,
action,
handler,
handlers,
} = actionOptions;
const async = optionAsync || !!handlers;
res[actionName] = createAction(actionName, {
async,
action: action || defaultAction,
handler,
handlers,
initialState: initialState || globalInitialState,
storeKey: storeKey || globalStoreKey,
});
return res;
}, {});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.