text stringlengths 7 3.69M |
|---|
const path = require("path");
const { merge } = require("webpack-merge");
const base = require("../base/webpack.base");
module.exports = merge(base({
tsConfigFile: 'config/modules/definitelyTypedTransformer/tsconfig.json'
}), {
entry: {
index: './definitelyTypedTests/src/index.ts'
},
output: {
path: path.resolve(__dirname, "../../../definitelyTypedTests/dist")
}
});
|
const {app,BrowserWindow} = require('electron')
const electron=require
//Ruta donde se encuentra nuestro proyecto
const path = require('path')
//Ruta pero en formato URL
const url = require('url')
//constantes para impresion en PDF
const fs= require('fs')//sistemas de archivos
const os=require('os')//sistemas operativo
//llamada o procedimiento interno
const ipc=electron.ipcMain
//interfaz de comandos o terminal
const shell=electron.shell
//evento para imprimir un PDF
ipc.on('print-to-pdf', function(event){
const pdfPath=path.join(os.tmpdir(), 'print.pdf')
const win=BrowserWindow.fromWebContenst(event.sender)
win.webContents.printToPDF({},function(error,data){
if(error) throw error
fs.writeFile(pdfPath,data,function(error){
if (error) {
throw error
}
shell.openExternal('file://'+pdfPath)
})
})
})
let PantallaPrincipal;
function muestraPantallaPrincipal(){
PantallaPrincipal = new BrowserWindow({
width:1024,
height:768
})
PantallaPrincipal.on('closed',function(){
PantallaPrincipal = null
})
PantallaPrincipal.loadURL(url.format({
pathname: path.join(__dirname,'index.html'),
protocol: 'file',
slashes: true
}))
//Abre la pantalla de Inspección, donde se encuentra
//la consola de Chrome dentro de electron.
PantallaPrincipal.openDevTools();
PantallaPrincipal.show()
}
//La aplicación ejecuta este evento cuando
//el archivo main.js se carga en memoria.
app.on('ready',muestraPantallaPrincipal) |
// understands how to filter a dataset
function DataFilter(data){
this._data = data;
}
DataFilter.prototype = {
filter: function(filter){
out = [];
if (typeof filter === 'undefined'){
filter = ''; // default value
}else{
filter = filter.toLowerCase();
}
for (var i=0; i< this._data.length; i++){
if (this._data[i].tags.toLowerCase().indexOf(filter) !== -1 ||
this._data[i].name.toLowerCase().indexOf(filter) !== -1
){
out.push(this._data[i]);
}
}
return out;
},
};
module.exports = DataFilter
|
import express from "express";
const router = express.Router({ mergeParams: true });
import { getCart, setCart } from "../handlers/routes/cart";
router
.route("/")
.get(getCart)
.put(setCart);
export default routerCombiner => {
routerCombiner.use("/cart", router);
};
|
var photos = [
{"file": "1.jpg", "title": "First photo", "description": "1 photo description"},
{"file": "2.jpg", "title": "Second photo", "description": "2 photo description"},
{"file": "3.jpg", "title": "Third photo", "description": "3 photo description"},
{"file": "4.jpg", "title": "Fourth photo", "description": "4 photo description"},
{"file": "5.jpg", "title": "Fifth photo", "description": "5 photo description"},
{"file": "6.jpg", "title": "Sixth photo", "description": "6 photo description"},
{"file": "7.jpg", "title": "Seventh photo", "description": "7 photo description"},
{"file": "8.jpg", "title": "Eighth photo", "description": "8 photo description"},
{"file": "9.jpg", "title": "Ninth photo", "description": "9 photo description"},
{"file": "10.jpg", "title": "Tenth photo", "description": "10 photo description"}
];
var imageIndex = 0;
var photoAmount = photos.length;
var hero = document.querySelector('.hero-photo');
hero.style.backgroundImage = "url(photos/" + photos[imageIndex]["file"] + ")";
var titleText = document.querySelector('.title');
var descriptionText = document.querySelector('.description');
var tumbnails = document.querySelector('.tumbnail-images');
var rightArrow = document.querySelector('.next');
var leftArrow = document.querySelector('.previous');
var firstTumb = tumbnails.children[0];
var secondTumb = tumbnails.children[1];
var thirdTumb = tumbnails.children[2];
var fourthTumb = tumbnails.children[3];
var fifthTumb = tumbnails.children[4];
createTumbnails();
rightArrow.addEventListener('click', moveRight);
leftArrow.addEventListener('click', moveLeft);
// loop-ba:
firstTumb.addEventListener('click', goToPhoto);
secondTumb.addEventListener('click', goToPhoto);
thirdTumb.addEventListener('click', goToPhoto);
fourthTumb.addEventListener('click', goToPhoto);
fifthTumb.addEventListener('click', goToPhoto);
function validateIndex() {
if (imageIndex === photoAmount) {
imageIndex = 0;
} else if (imageIndex < 0) {
imageIndex = photoAmount;
}
}
function moveRight(event) {
imageIndex++;
validateIndex();
changePhoto();
createTumbnails();
}
function moveLeft(event) {
imageIndex--;
validateIndex();
changePhoto();
createTumbnails();
}
function changePhoto() {
hero.style.backgroundImage = "url(photos/" + photos[imageIndex]["file"] + ")";
titleText.innerHTML = photos[imageIndex]["title"]
descriptionText.innerHTML = photos[imageIndex]["description"];
}
// function drawInLoop () {
// for (var i = 0; i < 4; i++) {
// drawTumbnail(i, imageIndex);
// }
// }
//
//
// function drawTumbnail (state, imgIndex) {
// tumbnails.children[state].style.backgroundImage = "url(photos/" + photos[imgIndex]["file"] + ")";
// tumbnails.children[state].dataset.index = photos[imgIndex];
// }
function createTumbnails () {
tumbnails.children[2].style.backgroundImage = "url(photos/" + photos[imageIndex]["file"] + ")";
tumbnails.children[2].dataset.index = imageIndex;
if (imageIndex === 0) {
tumbnails.children[0].style.backgroundImage = "url(photos/" + photos[photoAmount-2]["file"] + ")";
tumbnails.children[0].dataset.index = photos[photoAmount-2];
tumbnails.children[1].style.backgroundImage = "url(photos/" + photos[photoAmount-1]["file"] + ")";
tumbnails.children[1].dataset.index = photos[photoAmount-1];
tumbnails.children[3].style.backgroundImage = "url(photos/" + photos[imageIndex+1]["file"] + ")";
tumbnails.children[3].dataset.index = imageIndex+1;
tumbnails.children[4].style.backgroundImage = "url(photos/" + photos[imageIndex+2]["file"] + ")";
tumbnails.children[4].dataset.index = imageIndex+2;
} else if (imageIndex === 1) {
tumbnails.children[0].style.backgroundImage = "url(photos/" + photos[photoAmount-1]["file"] + ")";
tumbnails.children[0].dataset.index = photos[photoAmount-1];
tumbnails.children[1].style.backgroundImage = "url(photos/" + photos[imageIndex-1]["file"] + ")";
tumbnails.children[1].dataset.index = imageIndex-1;
tumbnails.children[3].style.backgroundImage = "url(photos/" + photos[imageIndex+1]["file"] + ")";
tumbnails.children[3].dataset.index = imageIndex+1;
tumbnails.children[4].style.backgroundImage = "url(photos/" + photos[imageIndex+2]["file"] + ")";
tumbnails.children[4].dataset.index = imageIndex+2;
} else if (imageIndex === photoAmount-1) {
tumbnails.children[0].style.backgroundImage = "url(photos/" + photos[imageIndex-2]["file"] + ")";
tumbnails.children[0].dataset.index = imageIndex-2;
tumbnails.children[1].style.backgroundImage = "url(photos/" + photos[imageIndex-1]["file"] + ")";
tumbnails.children[1].dataset.index = imageIndex-1;
tumbnails.children[3].style.backgroundImage = "url(photos/" + photos[0]["file"] + ")";
tumbnails.children[3].dataset.index = 0;
tumbnails.children[4].style.backgroundImage = "url(photos/" + photos[1]["file"] + ")";
tumbnails.children[4].dataset.index = 1;
} else if (imageIndex === photoAmount-2) {
tumbnails.children[0].style.backgroundImage = "url(photos/" + photos[imageIndex-2]["file"] + ")";
tumbnails.children[0].dataset.index = imageIndex-2;
tumbnails.children[1].style.backgroundImage = "url(photos/" + photos[imageIndex-1]["file"] + ")";
tumbnails.children[1].dataset.index = imageIndex-1;
tumbnails.children[3].style.backgroundImage = "url(photos/" + photos[imageIndex+1]["file"] + ")";
tumbnails.children[3].dataset.index = imageIndex+1;
tumbnails.children[4].style.backgroundImage = "url(photos/" + photos[0]["file"] + ")";
tumbnails.children[4].dataset.index = 0;
} else {
tumbnails.children[1].style.backgroundImage = "url(photos/" + photos[imageIndex-1]["file"] + ")";
tumbnails.children[1].dataset.index = imageIndex-1;
tumbnails.children[0].style.backgroundImage = "url(photos/" + photos[imageIndex-2]["file"] + ")";
tumbnails.children[0].dataset.index = imageIndex-2;
tumbnails.children[3].style.backgroundImage = "url(photos/" + photos[imageIndex+1]["file"] + ")";
tumbnails.children[3].dataset.index = imageIndex+1;
tumbnails.children[4].style.backgroundImage = "url(photos/" + photos[imageIndex+2]["file"] + ")";
tumbnails.children[4].dataset.index = imageIndex+2;
}
}
console.log(this.dataset.index);
function goToPhoto (event) {
imageIndex = parseInt(this.dataset.index);
validateIndex();
changePhoto();
createTumbnails();
}
console.log(imageIndex-1);
console.log(imageIndex-2);
console.log(imageIndex);
console.log(imageIndex+1);
console.log(imageIndex+2);
|
(function($, Strophe) {
/**
* Conversation
* Class representing a conversation between two users.
*/
window.Conversation = function(params) {
// Required parameters
var _params = {
httpBind: null,
roomId: null,
userId: null,
sid: null,
rid: null,
device: null
};
$.extend(_params, params);
var _conn = null,
_roomUsername = null,
_attached = false,
_listeners = {},
_pingInterval = null,
_pingTime = 15;
var init = function() {
_roomUsername = params.userId+'_'+params.device;
// Connect to XMPP server
_conn = new Strophe.Connection(params.httpBind);
// Start pinging
startPinging();
// _conn.rawInput = rawInput;
// _conn.rawOutput = rawOutput;
// Attach to the BOSH session
var nextRID = parseInt(params.rid, 10) + 1;
_conn.attach(params.userId, params.sid, nextRID, connectHandler);
};
var startPinging = function() {
if (_conn) {
stopPinging();
}
// Start pinging
_pingInterval = setInterval(function() {
// Ping
_conn.sendIQ($iq({to: _conn.service, from: _conn.jid, type: "get"}).c('ping', {xmlns: "urn:xmpp:ping"}));
}, _pingTime*1000);
};
var stopPinging = function() {
if (_pingInterval) {
clearInterval(_pingInterval);
_pingInterval = null;
}
};
var rawInput = function(data) {
console.log('RECV', JSON.stringify(data, null, 2));
};
var rawOutput = function(data) {
console.log('SENT', JSON.stringify(data, null, 2));
};
var connectHandler = function(status) {
switch(status) {
case Strophe.Status.CONNECTED:
case Strophe.Status.ATTACHED:
onAttach();
break;
case Strophe.Status.DISCONNECTED:
onDis_connect();
break;
}
};
var onAttach = function() {
_attached = true;
// Send initial presence
_conn.send(
new Strophe.Builder('presence')
.cnode(Strophe.xmlElement('priority', '1'))
);
// Enter the room
_conn.send(
new Strophe.Builder('presence', {
to: params.roomId + '/'+_roomUsername
})
);
// Listen for messages
_conn.addHandler(function(message) {
var body = message.getElementsByTagName('body');
var delay = message.getElementsByTagName('delay');
if (body.length > 0) {
// console.log("Message stanza received", message);
triggerListener('message', {
// Is this message from the current user
own: (message.getAttribute('from').indexOf('/'+params.userId) !== -1),
content: body[0].textContent,
time: (delay.length) ? delay[0].getAttribute('stamp') : false
});
stopPinging();
startPinging();
}
return true;
}, null, 'message');
};
var triggerListener = function(eventName, param) {
if (_listeners.hasOwnProperty(eventName)) {
_listeners[eventName](param);
}
};
var onDisconnect = function() {
_attached = false;
};
init();
return {
sendMessage: function(message) {
if (!_attached) {
return;
}
var msg = new Strophe.Builder('message', {
from: params.userId,
to: params.roomId,
type: 'groupchat'
})
.cnode(Strophe.xmlElement('body', message));
stopPinging();
_conn.send(msg);
startPinging();
},
// Attach event
on: function(eventName, listener) {
_listeners[eventName] = listener;
},
disconnect: function() {
_conn.flush();
_conn.disconnect();
}
};
};
})(window.jQuery, window.Strophe);
|
module.exports = {
fakeKeeper: require('./fakeKeeper'),
fakeWallet: require('./fakeWallet')
}
|
import React, {Component} from 'react';
import { connect } from 'react-redux';
import NavButton from '../../../../components/NavButton/NavButton';
import {showFinal, incrementActiveId, decrementActiveId} from '../Topbar/topBarActions';
import './navbar.css';
class Navbar extends Component {
constructor (props) {
super(props);
this.decrementStep = this.decrementStep.bind(this);
this.incrementStep = this.incrementStep.bind(this);
this.defineNextButtonClass = this.defineNextButtonClass.bind(this);
this.defineClickHandler = this.defineClickHandler.bind(this);
this.definePrevButtonClass = this.definePrevButtonClass.bind(this);
this.completeSurvey = this.completeSurvey.bind(this);
}
decrementStep () {
if (this.props.activeStep > 1)
this.props.decrementActiveId();
}
incrementStep () {
if (this.props.isTransitionAllowed)
this.props.incrementActiveId();
}
defineNextButtonClass () {
if (this.props.activeStep === this.props.stepsNumber) return 'final';
if (!this.props.isTransitionAllowed) return 'inactive';
return 'active';
}
definePrevButtonClass () {
if (this.props.activeStep === 1) return 'inactive';
return 'active';
}
defineClickHandler () {
return this.props.activeStep === this.props.stepsNumber
? this.completeSurvey
: this.incrementStep;
}
completeSurvey () {
if (this.props.isTransitionAllowed) this.props.showFinal();
}
render() {
return <div className="navbar">
<NavButton onClick={this.decrementStep}
classModifier={this.definePrevButtonClass()}>
<div>
<span className="navbutton__link"><</span>
<span className="navbutton__text">Предыдущий</span>
</div>
</NavButton>
<NavButton onClick={this.defineClickHandler()}
classModifier={this.defineNextButtonClass()}>
{this.props.activeStep === this.props.stepsNumber ?
<span className="navbutton__text">Завершить</span> :
<div>
<span className="navbutton__text">Следующий</span>
<span className="navbutton__link">></span>
</div>
}
</NavButton>
</div>
}
}
const mapStateToProps = (state) => ({
activeStep: state.topBar.activeElementId,
stepsNumber: state.topBar.stepsNumber,
isTransitionAllowed: state.transitionInfo.isTransitionAllowed
});
const mapDispatchToProps = (dispatch) => ({
incrementActiveId: () => dispatch(incrementActiveId()),
decrementActiveId: () => dispatch(decrementActiveId()),
showFinal: () => dispatch(showFinal())
});
export default connect(mapStateToProps, mapDispatchToProps)(Navbar); |
///The Spread Operator with the array...
//The Arrow Function...
var addNumber = (x, y, z) => (console.log(x + y + z))
//Array..
let nums = [3, 2, 1]
//Calling the function..
addNumber(...nums)
//Adding inner of the array with Sread Operator...
let boys = ['Asad', 'Anik', 'Hossain']
let total = ['Bill', ...boys, 'Gates', 'Steven']
console.log(total)
|
/*TMODJS:{"version":30,"md5":"fe8fe0f18c9799e9deacfbacf5f3898a"}*/
define(function(require) {
return require("../template")("info/list", function($data, $id) {
var $helpers = this, $escape = $helpers.$escape, data = $data.data, $out = "";
$out += '<section class="info_wrap m_b"> <section class="info"> <div class="inner clearfix"> <dl class="clearfix pt_7"> <dt class="fl mr_10"> <img src="';
$out += $escape(data.user_pic);
$out += '" alt="';
$out += $escape(data.nickname);
$out += '" width="60"> </dt> <dd class="fl ml_20 mt_5"> <h3 class="mb_10 white">';
$out += $escape(data.nickname);
$out += '</h3> <h4 class="white">';
$out += $escape(data.user_id);
$out += '</h4> <h4 class="white"> <a class="white" href="/lgwx/index.php/wap/user/logout?urlkey=login&service_id=';
$out += $escape(data.service_id);
$out += '">退出登录</a> </h4> </dd> </dl> </div> </section> </section> <section class="personal clearfix mb_15 mt_25"> <ul script-role="data_wrap" class="mb_25"> <li> <a href="';
$out += $escape(data.goodsLikeUrl);
$out += '" class="clearfix"> <span class="icon fl"></span> <span class="fl">我收藏的商品</span> <span class="fr font_16">></span> </a> </li> <li> <a href="';
$out += $escape(data.shopLikesUrl);
$out += '" class="clearfix"> <span class="icon fl"></span> <span class="fl">我关注的店铺</span> <span class="fr font_16">></span> </a> </li> <li> <a href="';
$out += $escape(data.notesUrl);
$out += '" class="clearfix"> <span class="icon fl"></span> <span class="fl">我的装修笔记</span> <span class="fr font_16">></span> </a> </li> <li> <a href="javascript:;" class="clearfix"> <span class="icon fl"></span> <span class="fl">我的优惠活动</span> <span class="fr font_16">></span> </a> </li> <li> <a href="';
$out += $escape(data.couponLikesUrl);
$out += '" class="clearfix"> <span class="icon fl"></span> <span class="fl">我的订阅</span> <span class="fr font_16">></span> </a> </li> </ul> <h3 class="mb_10">您可以使用会员编号和登录密码在电脑上</h3> <h3 class="pb_30">登录JIA178.COM同步查看</h3> </section>';
return new String($out);
});
}); |
$(document).ready(function () {
'use strict';
/*========================================================================
Header carousel
==========================================================================*/
$('.carousel').carousel({
interval: 5000,
pause: 'none'
});
/*========================================================================
Header Menu
==========================================================================*/
$('.toggle-menu').jPushMenu();
/*========================================================================
Owl cCarousel
==========================================================================*/
$("#hireme_slide").owlCarousel({
navigation : true, // Show next and prev buttons
slideSpeed : 300,
paginationSpeed : 400,
singleItem:true,
autoPlay: true
});
$("#sponsor_slide").owlCarousel({
autoPlay: 3000, //Set AutoPlay to 3 seconds
items : 5,
itemsDesktop : [1199,3],
itemsDesktopSmall : [979,3],
itemsTablet : [768,3],
itemsMobile : [480,1],
navigation : true,
navigationText : false,
pagination : false
});
$("#testmonial_slide").owlCarousel({
navigation : true, // Show next and prev buttons
autoPlay: 3000,
paginationSpeed : 400,
singleItem:true,
items : 1,
navigation : false,
});
/*========================================================================
Wow Animation
==========================================================================*/
$(".fancybox").fancybox();
/*========================================================================
Wow Animation
==========================================================================*/
setTimeout(function(){
$('body').addClass('loaded');
$('h1').css('color','#222222');
}, 3000);
/*========================================================================
Wow Animation
==========================================================================*/
var wow = new WOW({
mobile: false
});
wow.init();
}); |
/**
* Import Phaser dependencies using `expose-loader`.
* This makes then available globally and it's something required by Phaser.
* The order matters since Phaser needs them available before it is imported.
*/
import PIXI from 'expose-loader?PIXI!phaser-ce/build/custom/pixi.js';
import p2 from 'expose-loader?p2!phaser-ce/build/custom/p2.js';
import Phaser from 'expose-loader?Phaser!phaser-ce/build/custom/phaser-split.js';
import Boot from './states/boot';
// import Preload from 'states/preload';
import Menu from './states/menu';
import Game from './states/game';
import GameOver from './states/gameover';
import GameManager from './components/manager';
let manager = new GameManager();
var game = new Phaser.Game(1700, 900, Phaser.AUTO);
game.state.add('Boot', Boot);
// game.state.add('Preloader', Preload);
game.state.add('Menu', new Menu(game, manager));
game.state.add('Game', new Game(game, manager));
game.state.add('GameOver', new GameOver(game, manager));
game.state.start('Boot'); |
"use strict";
const firstPlayer = {
name: 'Baltasis',
color: 'white'
}
const secondPlayer = {
name: 'Juodasis',
color: 'black'
}
const board = {
selector: '#checkers',
styleSelector: 'style',
width: 8,
height: 8,
color: [firstPlayer.color, secondPlayer.color]
} |
(function (scope) {
const {SIZES, Tank,Bullet} = scope;
class GameObjectsFactory {
constructor(width, height) {
this.bounds = {width, height};
}
createTank(leftPosition, direction, color, image) {
const {height} = this.bounds;
const {HEIGHT,} = SIZES.TANK;
const top = (height - HEIGHT) / 2;
return new Tank(leftPosition, top, direction, color, image);
}
createBullet(top, left , color) {
const bullet = new Bullet(top, left,color);
return bullet;
}
createEnemy() {
const {width,height} = this.bounds;
const {HEIGHT,WIDTH} =SIZES.ENEMY;
const top = parseInt(Math.random() * (height-HEIGHT));
const left = parseInt(Math.random() * (width-WIDTH));
return {
left,
top,
};
}
createRandomObject(name){
const {width,height} = this.bounds;
const {HEIGHT,WIDTH} =SIZES.FRUIT;
const top = parseInt(Math.random() * (height-HEIGHT));
const left = parseInt(Math.random() * (width-WIDTH));
return {
name,
left,
top,
};
}
}
scope.GameObjectsFactory = GameObjectsFactory;
}(window)); |
import * as actionTypes from "./actionTypes";
import axios from "axios";
const instance = axios.create({
baseURL: "https://api-chatr.herokuapp.com/"
});
const setLoading = () => ({
type: actionTypes.SET_MESSAGES_LOADING
});
export const fetchMessageList = channelID => {
return async dispatch => {
dispatch(setLoading());
try {
const res = await instance.get(`channels/${channelID}`);
const messageList = res.data;
dispatch({
type: actionTypes.FETCH_MESSAGE_LIST,
payload: messageList
});
} catch (error) {
console.error(error);
}
};
};
export const fetchMessageListWithTimestamp = (channelID, timestamp) => {
return async dispatch => {
// dispatch(setLoading());
try {
const res = await instance.get(
`channels/${channelID}/?latest=${timestamp}`
);
const messageList = res.data;
dispatch({
type: actionTypes.FETCH_MESSAGE_LIST_WITH_TIMESTAMP,
payload: messageList
});
} catch (error) {
console.error(error);
}
};
};
export const postMessage = (message, channelID) => {
return async dispatch => {
try {
const res = await instance.post(`channels/${channelID}/send/`, message);
} catch (error) {
console.error(error.response.data);
}
};
};
export const filterMessages = query => {
return {
type: actionTypes.FILTER_MESSAGES,
payload: query
};
};
// old fetch messageList
// export const fetchMessageList = channelID => {
// return dispatch => {
// // dispatch(setLoading());
// instance
// .get(`channels/${channelID}`)
// .then(res => res.data)
// .then(messageList =>
// dispatch({
// type: actionTypes.FETCH_MESSAGE_LIST,
// payload: messageList
// })
// )
// .catch(err => console.error(err));
// };
// };
// old postMessages
// export const postMessage = (message, channelID) => {
// return dispatch => {
// instance
// .post(`channels/${channelID}/send/`, message)
// .catch(error => console.error(error.response.data));
// };
// };
|
const express = require('express')
const router = express.Router()
// controllers
const {listAllStations, createStations} = require('../controllers/stations')
//routes
router.get('/stations', listAllStations);
router.post('/stations/create', createStations)
module.exports = router |
import React from 'react';
import Slot from "./components/Slot"
//this is a new project in react
//slote Machine
class Newapp extends React.Component {
render() {
return (
<>
<Slot a="hi" b="hi" c="hi"/>
<Slot a="kjk" b="hasan" c="sakib "/>
<Slot a="😍" b="😍" c="😍"/>
</>
);
}
}
export default Newapp; |
$(function() {
var app = new window.modules.app();
// инициаизация
app.init($('.app'), [45.116751, 34.158592], 9);
app.domElem.on('init', function() {
app._addPlacemark([45.116751, 34.158592], 'Крым', 'Привет NAMASTE ;)');
app._addPlacemark([45.122584, 34.056969], '1', 'пыщь!');
app._addPlacemark([45.060327, 33.919640], '2', 'добра тебе ^_^');
app._addPlacemark([44.659871, 33.991051], '3', 'однажды один хороший человек...');
});
});
|
angular
.module("verificaciones")
.controller("FoliosCtrl", FoliosCtrl);
function FoliosCtrl($scope, $meteor, $reactive, $state, $stateParams, toastr) {
let rc = $reactive(this).attach($scope);
this.action = true;
this.subscribe('folios',()=>{
return [{}]
});
this.subscribe('usuarios',()=>{
return [{"profile.estatus": true, roles: ["Analista"]}]
});
this.subscribe('zona',()=>{
return [{estatus: true}]
});
this.helpers({
folios : () => {
return Folios.find();
},
usuarios: ()=> {
return Meteor.users.find({roles : ["Analista"]});
},
zonas : () => {
return Zona.find();
}
});
this.nuevo = true;
this.nuevoFolio = function()
{
this.action = true;
this.nuevo = !this.nuevo;
this.folio = {};
};
this.guardar = function(folio,form)
{
if(form.$invalid){
toastr.error('Error al guardar los datos.');
return;
}
folio.estatus = "1";//Pendiente
folio.usuarioInserto = Meteor.userId();
Folios.insert(folio);
toastr.success('Guardado correctamente.');
this.folio = {};
$('.collapse').collapse('hide');
this.nuevo = true;
form.$setPristine();
form.$setUntouched();
$state.go('root.folios');
};
this.editar = function(id)
{
this.folio = Folios.findOne({_id:id});
this.action = false;
$('.collapse').collapse('show');
this.nuevo = false;
};
this.actualizar = function(folio,form)
{
if(form.$invalid){
toastr.error('Error al guardar los datos.');
return;
}
console.log(folio);
var idTemp = folio._id;
delete folio._id;
folio.usuarioActualizo = Meteor.userId();
Folios.update({_id:idTemp},{$set:folio});
toastr.success('Actualizado correctamente.');
$('.collapse').collapse('hide');
this.nuevo = true;
form.$setPristine();
form.$setUntouched();
};
this.cambiarEstatus = function(id)
{
var folio = Folios.findOne({_id:id});
if(folio.estatus == true)
folio.estatus = false;
else
folio.estatus = true;
Folios.update({_id:id}, {$set : {estatus : folio.estatus}});
};
this.getAnalista = function(usuario_id)
{
var usuario = Meteor.users.findOne({_id:usuario_id});
if (usuario)
return usuario.profile.nombre;
};
this.getZona = function(zona_id)
{
var zona = Zona.findOne({_id:zona_id});
if (zona)
return zona.nombre;
};
}; |
Ext.define('Accounts.view.main.MainView', {
extend: 'Ext.form.Panel',
xtype: 'mainView',
requires : ['Accounts.store.AccComboStore'],
title: 'Daily Transactions',
layout: 'anchor',
scrollable : true,
listeners : {
'afterrender' : function(){
var combo = Ext.getCmp('mainAcc');
combo.focus();
}
},
items : [{
xtype: 'fieldset',
width : 825,
height : 200,
layout : 'anchor',
items: [{
xtype: 'datefield',
width : 180,
labelWidth : 50,
id : 'mainDate',
allowBlank : true,
fieldLabel : 'Date',
style : {
marginLeft : '15px'
},
format : 'd/m/Y',
renderer : Ext.util.Format.dateRenderer('d/m/Y'),
listeners : {
'beforerender' : function(){
var current = new Date();
var date = Ext.getCmp('mainDate');
date.setValue(current);
},
'change' : function(){
var cGrid = Ext.getCmp('creditGrid');
var cStore = cGrid.getStore();
var dGrid = Ext.getCmp('debitGrid');
var dStore = dGrid.getStore();
cStore.removeAll();
dStore.removeAll();
var panel = Ext.getCmp('topEdit');
var amt = Ext.getCmp('mainAmt');
var desc = Ext.getCmp('mainDesc');
var mode = Ext.getCmp('mainMode');
var combo = Ext.getCmp('mainAcc');
var qty = Ext.getCmp('mainQty');
var name = panel.getComponent('mainAcc');
name.setValue('');
combo.setValue('');
mode.setValue('Credit');
if(qty.isDisabled() == false){
qty.setValue(0);
qty.setDisabled(true);
}
amt.setValue(0);
desc.setValue('');
}
}
},{
xtype : 'displayfield',
id : 'mainName',
hidden : 'true'
},{
xtype : 'fieldset',
border : false,
layout: 'column',
id : 'topEdit',
items : [{
xtype : 'combo',
allowBlank: false,
typeAhead : true,
fieldLabel : 'Type',
labelAlign : 'top',
labelWidth : 50,
width : 90,
value : 'Credit',
id : 'mainMode',
store : [
['Credit', 'Credit'],
['Debit', 'Debit']
]
},{
xtype: 'combobox',
id : 'mainAcc',
width : 200,
valueField : 'accId',
reference: 'accounts',
publishes: 'value',
displayField : 'name',
emptyText : 'Account',
store: {
type: 'accComboStore'
},
style : {
margin : '30px 0px 0px 10px'
},
defaultListConfig: { loadingText: null, loadMask: false },
queryMode: 'local',
listConfig: {
itemTpl: [
'<div data-qtip="{name}: {type}">{name} ({type})</div>'
]
},
listeners : {
'beforequery' : function(){
var combo = Ext.getCmp('mainAcc');
var store = combo.getStore();
store.reload();
},
'specialkey' : function(field, e){
if (e.getKey() == e.BACKSPACE) {
var amt = Ext.getCmp('mainAmt');
var qty = Ext.getCmp('mainQty');
amt.setValue(0);
qty.setValue(0);
amt.setDisabled(true);
qty.setDisabled(true);
}
},
'select' : function(){
var item = Ext.getCmp('mainAcc');
var name = Ext.getCmp('mainName');
Ext.Ajax.request({
url : '/accounts/viewAccount?id=' + item.getValue(),
success : function(response, request){
//console.log(response);
var resp = Ext.decode(response.responseText);
var acc = Ext.create('Accounts.model.Account', resp);
//console.log(acc);
var type = acc.get('type');
var qty = Ext.getCmp('mainQty');
var amt = Ext.getCmp('mainAmt');
amt.setDisabled(false);
if(type == 'Commodity'){
qty.setDisabled(false);
qty.setValue(1);
qty.focus();
qty.selectText();
}
else{
qty.setValue(0);
qty.setDisabled(true);
amt.focus();
amt.selectText();
}
name.setValue(acc.get('name'));
},
failure : function(response, request){
console.log(request);
}
});
}
}
},{
xtype: 'numberfield',
width : 70,
disabled : true,
name: 'numberfield1',
id : 'mainQty',
fieldLabel: 'Quantity',
labelAlign : 'top',
emptyText : 0,
minValue: 0,
maxValue: 50,
style : {
marginLeft : '10px'
}
},{
xtype : 'textfield',
value : 'Details',
id : 'mainDesc',
emptyText : 'Details',
width : 250,
style : {
margin : '30px 0px 0px 10px'
}
},{
xtype: 'numberfield',
width : 100,
value: 0,
minValue: 0,
disabled : true,
hideTrigger: true,
enableKeyEvents : true,
id : 'mainAmt',
style : {
margin : '30px 0px 0px 10px'
},
listeners : {
'change' : function(){
var amt = Ext.getCmp('mainAmt');
var button = Ext.getCmp('mainBtn');
if(amt.getValue() > 0){
button.setDisabled(false);
}
else{
button.setDisabled(true);
}
},
'specialkey' : function(f,e){
if(e.getKey() == Ext.event.Event.ENTER){
var btn = Ext.getCmp('mainBtn');
btn.handler.call(btn.scope);
}
}
}
}]
},{
xtype : 'fieldset',
layout : 'column',
border : false,
items : [{
xtype : 'button',
text : 'Add',
id : 'mainBtn',
disabled : true,
style : {
width : '100px',
float : 'right',
margin : '10px'
},
handler : function(){
var amt = Ext.getCmp('mainAmt');
var desc = Ext.getCmp('mainDesc');
var mode = Ext.getCmp('mainMode');
var name = Ext.getCmp('mainName');
var qty = Ext.getCmp('mainQty');
var cTotal = Ext.getCmp('creditTotal');
var dTotal = Ext.getCmp('debitTotal');
if(mode.getValue() == 'Credit'){
var acc = Ext.create('Accounts.model.daily.Credit');
acc.set('accName', name.getValue());
acc.set('description', desc.getValue());
acc.set('amount', amt.getValue());
if(qty.isDisabled()){
acc.set('quantity', '');
}
else{
acc.set('quantity', qty.getValue());
}
var grid = Ext.getCmp('creditGrid');
var accStore = grid.getStore();
accStore.add(acc);
cTotal.setValue(accStore.sum('amount'));
}
else{
var acc = Ext.create('Accounts.model.daily.Debit');
acc.set('accName', name.getValue());
acc.set('description', desc.getValue());
acc.set('amount', amt.getValue());
if(qty.isDisabled()){
acc.set('quantity', '');
}
else{
acc.set('quantity', qty.getValue());
}
var grid = Ext.getCmp('debitGrid');
var accStore = grid.getStore();
accStore.add(acc);
dTotal.setValue(accStore.sum('amount'));
}
name.setValue('');
var combo = Ext.getCmp('mainAcc');
combo.setValue('');
combo.focus();
var qty = Ext.getCmp('mainQty');
if(qty.isDisabled() == false){
qty.setValue(0);
qty.setDisabled(true);
}
amt.setValue(0);
desc.setValue('');
}
}]
}]
},{
xtype: 'panel',
width : 1100,
height : 290,
layout : 'column',
items : [{
xtype : 'panel',
width : 500,
height : 290,
style: {
marginLeft: '15px'
},
items : [{
xtype : 'grid',
title : 'Credit',
width : 500,
scrollable : true,
height : 250,
layout : 'fit',
id : 'creditGrid',
store : {
type : 'creditStore'
},
columns : [
{ text: 'Account', dataIndex: 'accName', flex : 1 },
{ text: 'Description', dataIndex: 'description', width : 200 },
{ text: 'Quantity', dataIndex: 'quantity', width : 90},
{ text: 'Amount', dataIndex: 'amount', width : 100}
]
},{
xtype : 'fieldset',
items : [{
xtype : 'displayfield',
fieldLabel : 'Total',
layout : 'fit',
id : 'creditTotal',
width : 500,
style : {
paddingLeft : '300px'
}
}]
}]
},{
xtype : 'panel',
width : 500,
height : 290,
style: {
marginLeft: '50px'
},
items : [{
xtype : 'grid',
title : 'Debit',
width : 500,
scrollable : true,
height : 250,
id : 'debitGrid',
store : {
type : 'debitStore'
},
columns : [
{ text: 'Account', dataIndex: 'accName', flex : 1 },
{ text: 'Description', dataIndex: 'description', width : 200 },
{ text: 'Quantity', dataIndex: 'quantity', width : 90},
{ text: 'Amount', dataIndex: 'amount', width : 100}
]
},{
xtype : 'fieldset',
items : [{
xtype : 'displayfield',
fieldLabel : 'Total',
width : 500,
height : 30,
layout : 'fit',
id : 'debitTotal',
style : {
paddingLeft : '300px'
}
}]
}]
}]
}]
}); |
function gtag_formsent_conversion(destination) {
gtag('event', 'conversion', {'send_to': destination});
}
//Event snippet for Click on Link conversion page
function gtag_click_conversion(url, destination) {
const callback = function() {
if (typeof url !== "undefined") {
window.location = url;
}
};
gtag("event", "conversion", {
send_to: destination,
event_callback: callback
});
return false;
}
const opts = {
facebook_es: "AW-697005015/-SrXCPyDiMABENfnrcwC",
facebook_en: 'AW-697005015/L1DqCMP5_r8BENfnrcwC',
linkedin_es: "AW-697005015/P0M2CImCiMABENfnrcwC",
linkedin_en: 'AW-697005015/u4jmCIKC7b8BENfnrcwC',
phone_es: 'AW-697005015/EPjHCNKnurYBENfnrcwC',
phone_en: 'AW-697005015/CGpXCML_rrYBENfnrcwC',
email_es: 'AW-697005015/ax6ICLeeurYBENfnrcwC',
email_en: 'AW-697005015/qMpwCPfdo7YBENfnrcwC',
signform_es: 'AW-697005015/XeniCIGYurYBENfnrcwC',
signform_en: 'AW-697005015/8YtECNPjrrYBENfnrcwC',
joinus_es: 'AW-697005015/_SZLCN3hrrYBENfnrcwC',
joinus_en: 'AW-697005015/55VRCOXarrYBENfnrcwC',
signup_es: 'AW-697005015/h04SCM28o7YBENfnrcwC',
signup_en: 'AW-697005015/g74pCOf0ubYBENfnrcwC'
}
export { gtag_formsent_conversion, gtag_click_conversion, opts }; |
// Script to set up the application database
// DO NOT EDIT THIS FILE DIRECTLY - configuration values are interpolated from .env by scripts/generate-db-init-script.js
db.createUser({
user: '{{username}}',
pwd: '{{password}}',
roles: [
{
role: 'dbOwner',
db: 'remotr'
}
]
})
db.daemons.insertOne({ document: 'test', tags: ['test'], content: 'test' })
db.daemons.deleteOne({ document: { $eq: 'test' } })
|
import "../styles/scss/main.scss";
const LogIn = () => {
const view = `
<div class="login-box">
<div class="login-head">
<h1>Вход</h1>
</div>
<section class="login-box-form">
<div class="login-title">
В войдите в свой аккаунт
</div>
<form id="login">
<div>
<div class="wrap-input">
<input type="email" name="email" id="userName" placeholder="enter your email" class="email-input">
</div>
<div class="wrap-input">
<input type="text" name="password" id="userPw" placeholder="password" class="password-input" autocomplete="off">
</div>
</div>
<div class="wrap-input-btn">
<button type="submit">Login</button>
</div>
</form>
<div class="another-links">
<a href="/#/signup">Account registration</a>
</div>
</section>
</div>
</div>
`;
return view;
};
export default LogIn; |
/* eslint-disable prettier/prettier */
$(document).ready(() => {
$("#dogService").click(() => {
$("#dog-services").toggle();
});
$("#catService").click(() => {
$("#cat-services").toggle();
});
$("#rabbitService").click(() => {
$("#rabbit-services").toggle();
});
});
document.addEventListener("DOMContentLoaded", () => {
/* initialize the external events
-----------------------------------------------------------------*/
const containerEl = document.getElementById("pet-services-list");
new FullCalendar.Draggable(containerEl, {
itemSelector: ".fc-event",
eventData: function(eventEl) {
return {
// eslint-disable-next-line prettier/prettier
title: eventEl.innerText.trim(),
overlap: false,
constraint: "businessHours",
extendedProps: { animal: "Dog", apptId: -1 },
};
},
});
/* initialize the calendar
-----------------------------------------------------------------*/
let currentUser = "";
$.get("/api/user_data").then((data) => {
currentUser = data.email;
});
function toggleModal(displayMessage) {
$("#msgModal").text(displayMessage);
const modal = $("#msgModal");
modal.addClass("is-active");
}
const calendarEl = document.getElementById("calendar");
const calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: "prev,next today",
center: "title",
right: "timeGridWeek,timeGridDay,listMonth",
},
height: "auto",
visibleRange: function(currentDate) {
// Generate a new date for manipulating in the next step
const startDate = new Date(currentDate.valueOf());
const endDate = new Date(currentDate.valueOf());
// Adjust the start & end dates, respectively
startDate.setDate(startDate.getDate() - 1); // One day in the past
endDate.setDate(endDate.getDate() + 30); // 30 days into the future
return { start: startDate, end: endDate };
},
slotMinTime: "08:00:00",
slotMaxTime: "19:00:00",
allDaySlot: false,
navLinks: true, // can click day/week names to navigate views
businessHours: true, // display business hours
editable: true,
selectable: true,
nowIndicator: true,
businessHours: [
// specify an array instead
{
daysOfWeek: [1, 2, 3, 4, 5],
startTime: "08:00", // 8am
endTime: "19:00", // 7pm
},
{
daysOfWeek: [0, 6],
startTime: "12:00", // 12
endTime: "15:00", // 3pm
},
],
initialView: "timeGridWeek",
editable: true,
droppable: true, // this allows things to be dropped onto the calendar
eventClick: function(arg) {
if (currentUser !== arg.event.extendedProps.userEmail) {
toggleModal("You may only delete your own appointments.");
arg.revert();
return;
}
if (confirm("Are you sure you want to delete this event?")) {
if (arg.event.extendedProps.apptId > 0) {
$.ajax({
method: "DELETE",
url: "/api/appointments/" + arg.event.extendedProps.apptId,
}).then(() => {
console.log("Deleted appointment", arg.event);
});
}
arg.event.remove();
}
},
eventDrop: function(info) {
if (currentUser !== info.event.extendedProps.userEmail) {
toggleModal("You may only modify your own appointments.");
info.revert();
return;
}
//save to database
// eslint-disable-next-line vars-on-top
// eslint-disable-next-line no-var
const newAppt = {
id: info.event.extendedProps.apptId,
// eslint-disable-next-line camelcase
appointment_time: info.event.start.toISOString(),
};
if (info.event.extendedProps.apptId > 0) {
// Send the update POST request.
$.ajax("/api/appointments/", {
type: "PUT",
data: newAppt,
}).then(() => {
console.log("updated appointment", newAppt);
// Reload the page to get the updated list
//location.reload();
});
}
},
eventReceive: function(info) {
//save to database
// eslint-disable-next-line vars-on-top
// eslint-disable-next-line no-var
const newAppt = {
email: currentUser,
// eslint-disable-next-line camelcase
appointment_time: info.event.start.toISOString(),
animal: "Dog",
service: info.event.title,
};
// Send the POST request.
$.ajax("/api/appointments", {
type: "POST",
data: newAppt,
}).then((response) => {
console.log("created new appointment", newAppt);
info.event.extendedProps.apptId = response;
// Reload the page to get the updated list
location.reload();
});
},
events: function(serviceEvents, callback) {
//add call to backend mysql database for saved appointments
$.ajax({
url: "/api/appointments",
method: "GET",
}).then((response) => {
// eslint-disable-next-line prefer-const
let serviceEvents = [];
for (let i = 0; i < response.length; i++) {
const obj = response[i];
const ev = {
title: obj.service + " (" + obj.email.split("@")[0] + ")",
start: obj.appointment_time,
overlap: false,
constraint: "businessHours",
extendedProps: {
apptId: obj.id,
userEmail: obj.email,
},
};
serviceEvents.push(ev);
}
callback(serviceEvents);
});
},
});
calendar.render();
});
|
function runTest()
{
FBTest.openNewTab(basePath + "script/3985/issue3985.html", function(win)
{
FBTest.enableScriptPanel(function(win)
{
FBTest.progress("Wait till the iframe is loaded");
var url = basePath + "script/3985/issue3985-iframe.js";
FBTest.setBreakpoint(null, url, 3, null, function()
{
FBTest.progress("Reload");
FBTest.reload(function()
{
// Wait for breakpoint hit.
FBTest.waitForBreakInDebugger(null, 3, true, function(row)
{
FBTest.progress("Click continue button");
FBTest.clickContinueButton();
FBTest.testDone();
});
FBTest.waitForDisplayedBreakpoint(null, url, 3, function(row)
{
// Click a button.
var frame = win.document.getElementById("testFrame");
FBTest.click(frame.contentDocument.getElementById("trigger"));
});
});
});
});
});
} |
../../js/Clarity.js |
import React, { Component } from "react";
export default class Hog extends Component {
constructor() {
super();
this.state = {
detailsShow: false
}
}
handleClick = () => {
this.setState({ detailsShow: !this.state.detailsShow })
}
render() {
const hog = this.props.hog
return (
<div className="ui eight wide column" className="pigTile">
<h1>{hog.name}</h1>
<img src={hog.image} alt={hog.name} onClick={this.handleClick}></img>
{this.state.detailsShow &&
<div>
<h3>Speciality: {hog.specialty}</h3>
<h3>Piggy Greased?</h3>
{hog.greased ? <p>This piggy is greasy!</p> : <p>No grease here!</p>}
<h3>Weight: {hog.weight}</h3>
<h3>Highest Medal Achieved: </h3>
<p>{hog["highest medal achieved"]}</p>
</div>
}
</div>
)
}
} |
//import liraries
import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity } from 'react-native';
import firebase from 'firebase';
// create a component
class EmailAndPassword extends Component {
state={
email:'',
password:'',
error:'',
loading:false
}
onButtonPress=()=>{
firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password)
.then(this.onLoginSuccess)
.catch(err=>{
this.setState({
error: err.message
})
})
}
onLoginSuccess =() =>{
this.setState({
error:'',
loading:false
})
}
render() {
return (
<View style={styles.container}>
<TextInput
placeholder="email"
style={styles.input}
value={this.state.email}
onChangeText={email=>this.setState({email})}
/>
<TextInput
placeholder="password"
style={styles.input}
value={this.state.password}
onChangeText={password=>this.setState({password})}
secureTextEntry={true}
/>
<TouchableOpacity style={styles.buttonContainer} onPress={this.onButtonPress}>
<Text style={styles.buttonText}>Login</Text>
</TouchableOpacity>
<Text style={styles.errText}>
{this.state.error}
</Text>
</View>
);
}
}
// define your styles
const styles = StyleSheet.create({
container: {
flex: 1,
padding:20
},
input:{
height:40,
paddingLeft:10,
marginBottom:15,
borderRadius:5,
fontSize:15
},
errText:{
fontSize:20,
color:'red',
alignSelf:'center',
},
buttonText:{
textAlign:'center',
color:'#fff',
fontWeight:'bold',
fontSize:20
},
buttonContainer:{
backgroundColor:'blue',
padding:15,
borderRadius:8
}
});
//make this component available to the app
export default EmailAndPassword;
|
import React from "react";
import { Header } from "@primer/components"
import styles from "./header.module.scss";
export const AppHeader = () => {
return <Header>
<Header.Item>
<Header.Link href="#" fontSize={2}>
ITEM
</Header.Link>
</Header.Item>
</Header>
}
|
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
firstName: {
type: String,
trim: true,
required: "First Name is Required",
},
lastName: {
type: String,
trim: true,
required: "Last Name is Required",
},
password: {
type: String,
trim: true,
required: "Password is Required",
validate: [({ length }) => length >= 6, "Password should be longer."],
},
email: {
type: String,
unique: true,
match: [/.+@.+\..+/, "Please enter a valid e-mail address"],
},
userCreated: {
type: Date,
default: Date.now,
},
projectsInProgress: [
{
type: Schema.Types.ObjectId,
ref: "Project",
},
],
projectsComplete: [
{
type: Schema.Types.ObjectId,
ref: "Project",
// deployed_url: String
},
],
lastUpdated: Date,
fullName: String,
});
UserSchema.methods.setFullName = function () {
this.fullName = `${this.firstName} ${this.lastName}`;
return this.fullName;
};
UserSchema.methods.lastUpdatedDate = function () {
this.lastUpdated = Date.now();
return this.lastUpdated;
};
const User = mongoose.model("User", UserSchema);
// ! bcrypt password function here
// function CheckPassword(inputtxt) {
// var passw = user.password;
// if (inputtxt.value.match(passw)) {
// alert("Correct Password");
// return true;
// } else {
// alert("Wrong Password...!");
// return false;
// }
// }
module.exports = User;
// projectsComplete: [
// {
// project_id: Number,
// deployed_url: String,
// required: false,
// },
// ],
//or should we do this?
// projectsInProgress: [{
// type: Schema.Types.ObjectId,
// ref: "Project"
// }],
// projectsComplete: [{
// type: Schema.Types.ObjectId,
// ref: "Project"
// }],
// projectsInProgress: [{
// project_id: Number,
// required: false
// }],
|
var controller = require('../controllers/searchController');
const routes = (app) => {
app.route('/search')
.get(controller.searchget)
}
module.exports = routes; |
import React, { createContext, useContext, useReducer } from 'react'
import appReducer from './appReducer'
import appStateDefaults from './appState'
export const AppContext = createContext(undefined)
// eslint-disable-next-line react/prop-types
export const AppContextProvider = ({ children }) => (
<AppContext.Provider value={useReducer(appReducer, appStateDefaults)}>
{children}
</AppContext.Provider>
)
export default () => useContext(AppContext)
|
import React, { Component } from 'react'
import Nav from '.././components/Navigation'
import SP from '.././components/SinglePage'
import img from '.././img/img2.jpg'
class Blog_csgo extends Component {
render() {
return (
<>
<Nav title="PUBG"/>
<SP url="/best-games" img={img} text="PlayerUnknown's Battlegrounds" />
</>
)
}
}
export default Blog_csgo |
import React, { useState } from "react";
import axios from "axios";
import Card from '@material-ui/core/Card';
import Layout from '../components/layout.jsx';
import CardContent from '@material-ui/core/CardContent';
import TextForm from '../components/textform.jsx';
import Divider from '@material-ui/core/Divider';
import Button from '@material-ui/core/Button';
import { useHistory } from 'react-router';
import Alert from '@material-ui/lab/Alert';
import Password from "../components/password.jsx";
export default function Login(props){
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const history = useHistory();
const [err, setErr] = useState(false);
const onChangeEmail = (e) => {
setEmail(e.target.value);
}
const onChangePassword = (e) => {
setPassword(e.target.value);
}
const onLogin = async (e) => {
e.preventDefault();
try {
const response = await axios.post('/api/login', {
email: email, password: password
});
localStorage.setItem('token', response.data.token);
history.push('/');
} catch(err) {
if(err.response.status === 401){
setErr(true);
return;
}
alert(err);
}
}
return (
<Layout header="Login">
<div className="max-w-lg m-auto">
<Card>
<CardContent>
<div className="text-center my-2">Login</div>
<Divider />
<form onSubmit={onLogin}>
<div className="my-2">
<TextForm
label="email"
value={email}
onChange={onChangeEmail}
fullWidth
/>
</div>
<div className="my-2">
<Password
label="password"
value={password}
onChange={onChangePassword}
fullWidth
/>
</div>
{ err ?
<div>
<Alert severity="error">メールアドレスまたはパスワードが違います</Alert>
</div>
: null
}
<div className="my-4 text-center">
<Button
type="submit"
variant="contained"
color="primary"
disabled={email.length == 0 || password.length == 0}
>
Sign in
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
</Layout>
)
} |
module.exports = function() {
var AppControllerService = require('../app-controller-service/index.js'),
UserController = new AppControllerService('users'),
GroupController = new AppControllerService('groups'),
$participantInput = $('input[name="participants"]'),
$participantDropdown = $('.participant-dropdown'),
$selectedParticipantsContainer = $('.selected-participants-container'),
$inviteLabel = $('.invite-label'),
$deleteDiscussionLink = $('.delete-discussion-link'),
$deleteDiscussionModal = $('.delete-discussion-modal'),
$deleteDiscussionAction = $('.delete-discussion-action'),
$discussionForm = $('.discussion-form form'),
formEndpoint = $discussionForm.attr('action'),
formAction = $discussionForm.attr('data-action'),
action = $discussionForm.attr('action'),
discussionId = $discussionForm.attr('data-id'),
openClass = 'open',
addAction = 'add',
removeAction = 'remove',
participantIndex = -1,
enterKey = 13,
downArrowKey = 40,
upArrowKey = 38,
actionKeyCodes = [enterKey, downArrowKey, upArrowKey],
titleValue,
descriptionValue,
$selectedParticipant,
selectedParticipants = [],
userSearchQuery,
foundUsers;
/**
* Gets the value of a form fields
* @param {string}
* @return {any}
*/
function getFormFieldValue(field) {
return $('input[name="' + field + '"]').val();
}
/**
* Updates the participant dropdown markup
* @param {array}
*/
function updateParticipantDropdown(users) {
$participantDropdown.addClass(openClass);
users.forEach(function(user) {
$participantDropdown.append('<div data-id="' + user._id + '" data-fullName="' + user.fullName + '" data-picture="' + user.picture + '" class="participant"><img class="img img-circle" src="' + user.picture + '"><span>' + user.fullName + '</span></div>');
});
}
/**
* Clears the participants dropdown
*/
function clearParticipantDropdown() {
$participantDropdown.html('');
$participantDropdown.removeClass(openClass);
participantIndex = -1;
}
/**
* Updates the selected participants view
* @param {string}
* @param {string}
*/
function updateSelectedParticipantView(participant, action) {
$participantInput.val('');
$participantInput.focus();
$inviteLabel.html('');
if (action === addAction) {
$selectedParticipantsContainer.append('<div class="selected-participant" data-id="' + participant.attr('data-id') + '" data-html="true" data-toggle="tooltip" data-placement="top" title="' + participant.attr('data-fullName')+ '<br><small>(Click to remove)</small>"><img class="img img-circle" src="' + participant.attr('data-picture') + '"></div>');
} else if (action === removeAction) {
$('.selected-participant[data-id=' + participant.attr('data-id') + ']').remove();
}
}
/**
* Populate the selected participants if in edit view
*/
$('.selected-participant').each(function() {
selectedParticipants.push($(this).attr('data-id'));
});
/**
* When a participant is selected, add them to selected participants and
* update the view
*/
$('body').on('click', '.participant', function() {
$selectedParticipant = $(this);
selectedParticipants.push($selectedParticipant.attr('data-id'));
updateSelectedParticipantView($selectedParticipant, addAction);
clearParticipantDropdown();
});
/**
* When a selected participant is clicked, remove them from the view and state
*/
$('body').on('click', '.selected-participant', function() {
$selectedParticipant = $(this);
$('.tooltip').remove();
selectedParticipants = selectedParticipants.filter(function(participant) {
return participant !== $selectedParticipant.attr('data-id');
});
updateSelectedParticipantView($selectedParticipant, removeAction);
if (selectedParticipants.length === 0) {
$inviteLabel.html('(optional)');
}
});
/**
* When a user searches for participants, fetch users and show the dropdown
* with the returned users
*/
$participantInput.on('keyup', function(event) {
if (actionKeyCodes.indexOf(event.which) > -1) {
return false;
}
userSearchQuery = event.target.value.replace(/[^a-zA-Z ]/g, "");
if (userSearchQuery.trim().length > 0) {
UserController.get(userSearchQuery, function(err, users) {
if (!err) {
clearParticipantDropdown();
foundUsers = users.filter(function(user) {
return selectedParticipants.indexOf(user._id) === -1;
});
if (foundUsers.length > 0) {
updateParticipantDropdown(foundUsers);
}
}
});
} else {
clearParticipantDropdown();
}
});
/**
* Let a user select participants using keys
*/
$participantInput.on('keydown', function(event) {
var key = event.which;
var $participants = $('.participant');
if (key === enterKey) {
$($('.participant').get(participantIndex)).click();
$participants.removeClass('key-over');
event.preventDefault();
}
if (key === downArrowKey) {
if ($participants.length - 1 !== participantIndex) {
participantIndex++;
$participants.removeClass('key-over');
$($('.participant').get(participantIndex)).addClass('key-over');
}
}
if (key === upArrowKey) {
if (participantIndex !== 0) {
participantIndex--;
$participants.removeClass('key-over');
$($('.participant').get(participantIndex)).addClass('key-over');
}
}
});
/**
* Handle the form submission
*/
$discussionForm.on('submit', function(event) {
event.preventDefault();
titleValue = getFormFieldValue('title');
descriptionValue = getFormFieldValue('description');
if (formAction === 'create') {
GroupController.post({
title: titleValue,
description: descriptionValue,
participants: selectedParticipants,
}, function(err, response) {
window.location.href = '/groups/' + response._id;
});
}
if (formAction === 'edit') {
GroupController.post({
title: titleValue,
description: descriptionValue,
participants: selectedParticipants,
}, function(err, response) {
window.location.href = '/groups';
}, formEndpoint);
}
});
$deleteDiscussionLink.on('click', function() {
$deleteDiscussionModal.modal();
});
$deleteDiscussionAction.on('click', function() {
GroupController.post({}, function(err, response) {
window.location.href = '/groups';
}, '/groups/delete/' + discussionId);
});
};
|
function init() {
var x = $('#coordinate_x').val().replace(',', '.'),
y = $('#coordinate_y').val().replace(',', '.'),
address = $('#current_address').val(),
title_on_marker = $('#marker_head').val();
if (x != 'None' && y != 'None') {
$('#map').css('height', '400px');
myMap = new ymaps.Map('map', {
center: [x, y],
zoom: 15
});
myMap.behaviors.disable('scrollZoom');
var content = '';
if (title_on_marker) {
content += '<b>' + title_on_marker + '</b><br>';
}
content += address;
var placemark = new ymaps.Placemark(
[x, y], {
balloonContent: content
}, {
preset: 'islands#icon',
iconColor: '#0095b6'
});
myMap.geoObjects.add(placemark);
placemark.balloon.open();
}
}
$(document).ready(function($) {
ymaps.ready(init);
}); |
import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import { check } from 'meteor/check';
export const Organizations = new Mongo.Collection('organizations');
Meteor.methods({
createOrg(org) {
try {
let orgId = Organizations.insert(org);
return { _id: orgId };
} catch(exception) {
return exception;
}
}
});
Organizations.schema = new SimpleSchema({
_id: {
type: String, regEx: SimpleSchema.RegEx.Id
},
name: {
type: String
},
website_url: {
type: String
},
facebook_url: {
type: String, optional: true
},
twitter_url: {
type: String, optional: true
},
email: {
type: String
},
image_url: {
type: String
},
short_description: {
type: String
},
description: {
type: String
},
userId: {
type: String, regEx: SimpleSchema.RegEx.Id
}
});
Organizations.attachSchema(Organizations.schema);
Organizations.helpers({
});
|
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'GG.' });
});
router.get('/login' , (req, res, next) => {
res.json({message:'Hi sir.'});
});
router.post('/users/login' , (req, res, next) => {
let userName = req.body.userName;
let passWord = req.body.passWord;
console.log( 'User name: ' + userName + ' PWD: ' + passWord );
res.json({signin:1});
});
router.get('/users' , (req, res, next) => {
userArray = [
{ name: 'gum', tel: '01129292', email: 'gum@gmail.com' }
, { name: 'num', tel: '01238431', email: 'num@gmail.com' }
, { name: 'hum', tel: '01231234', email: 'hum@gmail.com' }
, { name: 'sum', tel: '01231231', email: 'sum@gmail.com' }
, { name: 'aum', tel: '01231232', email: 'aum@gmail.com' }
]
res.json(userArray);
});
router.get('/v1/partner/partnerProfile/vatAddress.json?', function (req, res, next) {
// /v1/partner/partnerProfile/vatAddress.json?filter=(&($lastUpd_key>=$date&time)($lastUpd_key<=$date&time)(dataType=$value))
console.log(req.query);
product = {
"resultCode": "20000",
"resultDescription": "Success",
"resultData": [
{
"locationCode_key0": "293840",
"ownerLocationCode_data": "",
"companyAbbr_key1": "Entronica",
"vatBranchNo_key2": "สำนักงานใหญ่",
"vatAddress_data": "บริษัท เอนโทรนิก้า จำกัด 31 อาคารพญาไทบิวดิ้ง ชั้นที่ 10 ห้องเลขที่ 107-108 ถนน พญาไท แขวง ถนนพญาไท เขต ราชเทวี กรุงเทพมหานคร 10400",
"created_data": "",
"createdBy_data": "",
"lastUpd_data": "",
"lastUpdBy_data": "",
"modificationNum_data": ""
},{
"locationCode_key0": "293840",
"ownerLocationCode_data": "qq",
"companyAbbr_key1": "Entronica",
"vatBranchNo_key2": "สำนักงานใหญ่",
"vatAddress_data": "กก สสหป 6666 111 3กด สสส กกกกกก 10400 ",
"created_data": "",
"createdBy_data": "",
"lastUpd_data": "",
"lastUpdBy_data": "",
"modificationNum_data": ""
},{
"locationCode_key0": "293840",
"ownerLocationCode_data": "",
"companyAbbr_key1": "Entronica",
"vatBranchNo_key2": "สำนักงานใหญ่",
"vatAddress_data": "กก สสหป 6666 111 3กด สสส กกกกกก 10400 ",
"created_data": "",
"createdBy_data": "",
"lastUpd_data": "",
"lastUpdBy_data": "",
"modificationNum_data": ""
},{
"locationCode_key0": "293840",
"ownerLocationCode_data": "",
"companyAbbr_key1": "Entronica",
"vatBranchNo_key2": "สำนักงานใหญ่",
"vatAddress_data": "กก สสหป 6666 111 3กด สสส กกกกกก 10400 ",
"created_data": "",
"createdBy_data": "",
"lastUpd_data": "",
"lastUpdBy_data": "",
"modificationNum_data": ""
},{
"locationCode_key0": "293840",
"ownerLocationCode_data": "",
"companyAbbr_key1": "Entronica",
"vatBranchNo_key2": "สำนักงานใหญ่",
"vatAddress_data": "กก สสหป 6666 111 3กด สสส กกกกกก 10400 ",
"created_data": "",
"createdBy_data": "",
"lastUpd_data": "",
"lastUpdBy_data": "",
"modificationNum_data": ""
},{
"locationCode_key0": "293840",
"ownerLocationCode_data": "",
"companyAbbr_key1": "Entronica",
"vatBranchNo_key2": "สำนักงานใหญ่",
"vatAddress_data": "กก สสหป 6666 111 3กด สสส กกกกกก 10400 ",
"created_data": "",
"createdBy_data": "",
"lastUpd_data": "",
"lastUpdBy_data": "",
"modificationNum_data": ""
},{
"locationCode_key0": "293840",
"ownerLocationCode_data": "",
"companyAbbr_key1": "Entronica",
"vatBranchNo_key2": "สำนักงานใหญ่",
"vatAddress_data": "กก สสหป 6666 111 3กด สสส กกกกกก 10400 ",
"created_data": "",
"createdBy_data": "",
"lastUpd_data": "",
"lastUpdBy_data": "",
"modificationNum_data": ""
},{
"locationCode_key0": "293840",
"ownerLocationCode_data": "",
"companyAbbr_key1": "Entronica",
"vatBranchNo_key2": "สำนักงานใหญ่",
"vatAddress_data": "กก สสหป 6666 111 3กด สสส กกกกกก 10400 ",
"created_data": "",
"createdBy_data": "",
"lastUpd_data": "",
"lastUpdBy_data": "",
"modificationNum_data": ""
},{
"locationCode_key0": "293840",
"ownerLocationCode_data": "",
"companyAbbr_key1": "Entronica",
"vatBranchNo_key2": "สำนักงานใหญ่",
"vatAddress_data": "กก สสหป 6666 111 3กด สสส กกกกกก 10400 ",
"created_data": "",
"createdBy_data": "",
"lastUpd_data": "",
"lastUpdBy_data": "",
"modificationNum_data": ""
},
{
"locationCode_key0": "13215",
"ownerLocationCode_data": "",
"companyAbbr_key1": "AIS",
"vatBranchNo_key2": "สำนักงานใหญ่",
"vatAddress_data": "xxxd ffdsfasdfกกdsfasdfasd ททท 10500 ",
"created_data": "",
"createdBy_data": "",
"lastUpd_data": "",
"lastUpdBy_data": "",
"modificationNum_data": ""
},{
"locationCode_key0": "293840",
"ownerLocationCode_data": "",
"companyAbbr_key1": "Entronica",
"vatBranchNo_key2": "สำนักงานใหญ่",
"vatAddress_data": "กก สสหป 6666 111 3กด สสส กกกกกก 10400 ",
"created_data": "",
"createdBy_data": "",
"lastUpd_data": "",
"lastUpdBy_data": "",
"modificationNum_data": ""
},
{
"locationCode_key0": "13215",
"ownerLocationCode_data": "",
"companyAbbr_key1": "AIS",
"vatBranchNo_key2": "สำนักงานใหญ่",
"vatAddress_data": "xxxd ffdsfasdfกกdsfasdfasd ททท 10500 ",
"created_data": "",
"createdBy_data": "",
"lastUpd_data": "",
"lastUpdBy_data": "",
"modificationNum_data": ""
},{
"locationCode_key0": "293840",
"ownerLocationCode_data": "",
"companyAbbr_key1": "Entronica",
"vatBranchNo_key2": "สำนักงานใหญ่",
"vatAddress_data": "กก สสหป 6666 111 3กด สสส กกกกกก 10400 ",
"created_data": "",
"createdBy_data": "",
"lastUpd_data": "",
"lastUpdBy_data": "",
"modificationNum_data": ""
},
{
"locationCode_key0": "13215",
"ownerLocationCode_data": "",
"companyAbbr_key1": "AIS",
"vatBranchNo_key2": "สำนักงานใหญ่",
"vatAddress_data": "xxxd ffdsfasdfกกdsfasdfasd ททท 10500 ",
"created_data": "",
"createdBy_data": "",
"lastUpd_data": "",
"lastUpdBy_data": "",
"modificationNum_data": ""
}
]
};
// var myJsonString = JSON.stringify({lastUpd_key:'',lastUpd_key1:''});
// var myJsonString = req.query;
console.log("Response :" + product);
res.json(product);
});
module.exports = router;
|
$(document).ready(function() {
$(document).on('submit', '#registration_form', function(e){
var path = window.location.pathname;
var page = path.split("/").pop();
e.preventDefault();
var email = $('#email').val();
var password = $('#password').val();
var name = $('#name').val();
var surName = $('#surName').val();
var phone = $('#phone').val();
var isValid = true;
$(".error").remove();
if (email.length < 5 || email.length > 25) {
$('#email').after('<span class="error">Enter a valid email</span>');
isValid = false;
} else {
var regEx = /[a-zA-Z]+@{1}[a-zA-Z]+\.{1}[a-zA-Z]{2,25}/;
var validEmail = regEx.test(email);
if (!validEmail) {
$('#email').after('<span class="error">Enter a valid email</span>');
isValid = false;
}
}
if (phone.length < 6 || phone.length > 12) {
$('#phone').after('<span class="error">Enter a valid phone</span>');
isValid = false;
} else {
var regEx = /[+]{0,1}\d{6,12}/;
var validPhone = regEx.test(phone);
if (!validPhone) {
$('#phone').after('<span class="error">Enter a valid phone</span>');
isValid = false;
}
}
if (password.length > 0) {
var regExPass = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{5,30}$/;
var validPass = regExPass.test(password);
if (!validPass) {
$('#password').after('<span class="error">Password must be at least 5 symbols long, contains digits and capital letters</span>');
isValid = false;
}
}
if (name.length < 2 || name.length > 30) {
$('#name').after('<span class="error">Name must be 2-30 characters long</span>');
isValid = false;
}
if (surName.length < 2 || surName.length > 35) {
$('#surName').after('<span class="error">Surname must be 2-35 symbols long</span>');
isValid = false;
}
if(isValid){
$('#registration_form')[0].submit();
}
});
});
|
"use strict";
// Express
const app = require("express")();
// Models
const { Product } = require("./models");
// DB Connection
const mongoose = require("mongoose");
mongoose.Promise = require("bluebird");
app.use((req, res, next) => {
mongoose
.connect("mongodb://localhost/async_development", {
useMongoClient: true
})
.then(() => next());
});
// Utility Functions
/////////////////////
const display = (res, items) => {
let lines = [];
items.forEach(item => {
lines.push([`${item.name}: $${item.price}`]);
});
lines = lines.join("<br>");
res.writeHead(200, { "Content-Type": "text/html" });
res.end(lines);
};
const opts = {
most: () => [{}, {}, { sort: { price: -1 } }],
least: most => [{ category: most.category }, {}, { sort: { price: 1 } }],
sum: (most, least) => {
return [
[
{
$match: {
category: most.category,
_id: { $nin: [most._id, least._id] }
}
},
{ $group: { _id: "$category", price: { $sum: "$price" } } },
{ $project: { price: 1, name: "Sum" } }
]
];
}
};
// Async Strategies
///////////////////
app.get("/callback", (req, res) => {
const errCall = e => {
res.status(500).end(e.stack);
};
Product.findOne(...opts.most(), (err, most) => {
if (err) return errCall(err);
Product.findOne(...opts.least(most), (err, least) => {
if (err) return errCall(err);
Product.aggregate(...opts.sum(most, least), (err, sum) => {
if (err) return errCall(err);
display(res, [most, least, sum[0]]);
});
});
});
});
app.get("/promise", (req, res) => {
let most;
let least;
Product.findOne(...opts.most())
.then(m => {
most = m;
return Product.findOne(...opts.least(most));
})
.then(l => {
least = l;
return Product.aggregate(...opts.sum(most, least));
})
.then(sum => {
display(res, [most, least, sum[0]]);
})
.catch(e => res.status(500).end(e.stack));
});
app.get("/async", async (req, res) => {
try {
const most = await Product.findOne(...opts.most());
const least = await Product.findOne(...opts.least(most));
const sum = await Product.aggregate(...opts.sum(most, least));
display(res, [most, least, sum[0]]);
} catch (e) {
res.status(500).end(e.stack);
}
});
// Load Server
app.listen(2000, "localhost", () => {
console.log("Good to go!");
});
|
/* eslint-disable react/display-name */
import React from 'react'
import { withTranslation } from 'react-i18next'
import { Container, Row, Card } from 'reactstrap'
import Header from '../components/Headers/Header.jsx'
import DataTable from 'react-data-table-component'
import orderBy from 'lodash/orderBy'
import CustomLoader from '../components/Loader/CustomLoader'
import { reviews } from '../apollo/server'
import { useQuery, gql } from '@apollo/client'
const REVIEWS = gql`
${reviews}
`
const Ratings = props => {
const { data, loading, error } = useQuery(REVIEWS)
const columns = [
{
name: 'Name',
sortable: true,
selector: 'order.user.name',
cell: row => <>{row.order.user.name}</>
},
{
name: 'Product Title',
cell: row => <>{row.product.title}</>
},
{
name: 'Review',
sortable: true,
selector: 'description',
cell: row => <>{row.description}</>
},
{
name: 'Ratings',
sortable: true,
selector: 'rating',
cell: row => <>{row.rating}</>
}
]
const propExists = (obj, path) => {
return path.split('.').reduce((obj, prop) => {
return obj && obj[prop] ? obj[prop] : ''
}, obj)
}
const customSort = (rows, field, direction) => {
const handleField = row => {
if (field && isNaN(propExists(row, field))) {
return propExists(row, field).toLowerCase()
}
return row[field]
}
return orderBy(rows, handleField, direction)
}
const handleSort = (column, sortDirection) =>
console.log(column.selector, sortDirection, column)
const { t } = props
return (
<>
<Header />
{/* Page content */}
<Container className="mt--7" fluid>
{/* Table */}
<Row>
<div className="col">
<Card className="shadow">
{error ? (
<tr>
<td>
{t('Error')}! ${error.message}
</td>
</tr>
) : (
<DataTable
title={t('Ratings')}
columns={columns}
data={data ? data.allReviews : []}
pagination
progressPending={loading}
progressComponent={<CustomLoader />}
onSort={handleSort}
sortFunction={customSort}
defaultSortField="order.user.name"
/>
)}
</Card>
</div>
</Row>
</Container>
</>
)
}
export default withTranslation()(Ratings)
|
document.querySelector(".right_side").style.background="#d3c26f";
|
const config = require("../config.json");
const Discord = require("discord.js");
const {
getRandomMeme,
getLocalRandomMeme
} = require(`@blad3mak3r/reddit-memes`);
function formatNumber(num) {
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
};
const subreddits_tattoo = [
`Best_tattoos`,
`tattoos`
];
module.exports.run = async(client, message, args, prefix) => {
const chosenSub = subreddits_tattoo[Math.floor(Math.random() * subreddits_tattoo.length - 1)];
getRandomMeme(chosenSub).then(m => {
const memeEmbed = new Discord.MessageEmbed()
.setFooter("Requested by " + message.author.tag, message.author.avatarURL())
.setColor(config.embedColor)
.setImage(m.image)
.addField(`Subreddit`, `r/${m.subreddit}`)
.addField(`Author`, `${m.author}`)
.addField(`Upvotes`, `${m.ups}`)
.setTimestamp();
message.channel.send(memeEmbed);
}).catch(console.error);
};
module.exports.help = {
name: "tattoo",
aliases: []
}
|
'use strict'
const ChattingRoom = require('./ChattingRoom');
function Rooms(){
this.rooms = new Array();
}
Rooms.prototype.addRoom = function(repsId){
let chattingRoom = new ChattingRoom(repsId);
rooms.push(chattingRoom);
return chattingRoom;
};
Rooms.prototype.deleteRoom = function(repsId){
let index = this.rooms.findIndex((room) => {
room.isRoom(repsId);
});
return index >= 0 ? this.rooms.splice(index, 1) : false;
};
Rooms.prototype.join = function(repsId, user){
let room = this.rooms.find((room) => {
return room.isRoom(repsId);
});
if(room){
room = this.addRoom(repsId);
}
room.addUser(user);
};
module.exports = exports = new Rooms();
|
import React, {createContext, useState, useEffect} from 'react';
import axios from 'axios';
export const NewsContext = createContext()
export const NewsContextProvider = (props) => {
const [data, setData] = useState();
const apiKey = 'http://newsapi.org/v2/everything?domains=lemonde.fr&apiKey=8d459dea89ba417dade27ccaf780a285';
useEffect(() => {
axios.get(apiKey).then((response) => setData(response.data)).catch((error) => console.log(error));
}, []);
return(
<NewsContext.Provider value={{ data }}>
{ props.children }
</NewsContext.Provider>
)
}
|
import React from "react";
import HomeHeaderBootstrap from "../reusableComponents/HomeHeaderBootstrap";
import ResourcesLIst from "./ResourcesList";
import StickyFooter from "../reusableComponents/stickyFooter";
const Resources = () => {
return (
<div className="main-container">
<div className="container">
<HomeHeaderBootstrap />
<ResourcesLIst />
</div>
<StickyFooter />
</div>
);
};
export default Resources;
|
import Koa from 'koa'
import { getPage } from './github.js'
import { get, set } from './cache.js'
const app = new Koa();
const githubApiToken = process.env.GITHUB_API_TOKEN
app.use(async ctx => {
const cached = get()
if (cached) {
return ctx.body = cached
}
const page = await getPage(githubApiToken)
set(page)
ctx.body = page
});
app.listen(process.env.PORT || 3000)
|
(function(w, d){
const cl = console.log
const create_modal = new bootstrap.Modal(d.getElementById('create_modal'))
const create_first_modal = new bootstrap.Modal(d.getElementById('create_first_modal'))
const add_note_modal = new bootstrap.Modal(d.getElementById('add_note_modal'))
const add_survey_modal = new bootstrap.Modal(d.getElementById('add_survey_modal'))
// create_first_modal.show()
add_survey_modal.show()
const create_event_btn = d.getElementById('create_event_btn')
if(create_event_btn) create_event_btn.addEventListener('click', function(event){
create_modal.show()
})
const card_create_first = d.getElementById('card_create_first')
const card_create_second = d.getElementById('card_create_second')
if(card_create_first) card_create_first.addEventListener('click', show_create_modal)
if(card_create_second) card_create_second.addEventListener('click', show_create_modal)
function show_create_modal(event){
// cl(create_meeting_title)
create_meeting_title.innerText = this.title
create_first_modal.show()
create_modal.hide()
}
const add_note_btn = d.getElementById('add_note_btn')
if(add_note_btn) add_note_btn.addEventListener('click', function(event){
add_note_modal.show()
})
const card_add_survey = d.getElementById('card_add_survey')
if(card_add_survey) card_add_survey.addEventListener('click', function(event){
add_survey_modal.show()
create_modal.hide()
})
// datepicker('#date_inp')
const options = {
format:'d.m.Y H:i',
}
jQuery('#date_inp1').datetimepicker(options)
jQuery('#date_inp2').datetimepicker(options)
jQuery('#date_inp3').datetimepicker(options)
}(window, document))
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ProjectCard from './ProjectCard/ProjectCard';
import classes from './Project.module.css';
import {
getAsync,
postAsync,
putAsync,
deleteAsync,
} from '../../../../../tool/api-helper';
import { languageHelper } from '../../../../../tool/language-helper';
import addIcon from '../../assets/add.svg';
const translation = [
{
project: '项目',
addProject: '+ 添加项目',
noProject: '无项目',
},
{
project: 'Project',
addProject: '+ Add Project',
noProject: 'No Project',
},
];
const text = translation[languageHelper()];
class Project extends Component {
constructor(props) {
super(props);
this.state = {
cards: [],
adding: false,
addingCard: null,
};
}
cancelAdding = () => {
this.setState({ ...this.state, addingCard: null, adding: false });
};
async postRequest(content) {
await postAsync(
'/applicants/' + this.props.requestID + '/projects',
content
);
// console.log(`posting ${content} and response is ${response}`)
}
async putRequest(id, content) {
await putAsync(
'/applicants/' + this.props.requestID + '/projects/' + id,
content
);
// console.log(`putting ${content} with id ${id} and response is ${response}`)
}
async deleteRequest(id) {
await deleteAsync(
'/applicants/' + this.props.requestID + '/projects/' + id
);
// console.log(`deleting ${id} and response is ${response}`)
}
async getRequest() {
let data = await getAsync(
'/applicants/' + this.props.requestID + '/projects'
);
// console.log('getting'+data);
let temp =
data && data.content && data.content.data && data.status.code === 2000
? data.content.data.map(e => {
return (
<ProjectCard
key={e.id}
data={e}
deleteHandler={this.deleteHandler}
saveHandler={this.saveHandler}
/>
);
})
: [];
this.setState(
(prevState)=>{
return {...prevState, cards: temp, adding: false, addingCard: null };}
);
}
// get work data set requestedData and cards in state
async componentDidMount() {
// console.log('componentDidMout');
await this.getRequest();
}
// delte data on server, delete data in state.cards
deleteHandler = async id => {
await this.deleteRequest(id);
await this.getRequest();
};
// save data locally and send back to server
saveHandler = async (content, id, mode) => {
if (mode === 'add') {
// console.log('adding');
await this.postRequest(content);
await this.getRequest();
} else if (mode === 'update') {
// console.log('updating');
await this.putRequest(id, content);
await this.getRequest();
}
};
// addhandler only create a empty cards
// update the data in server and local happens in saveHandler
addHandler = () => {
if (this.state.adding === true) {
alert('请先完成当前编辑');
return;
}
// make a hard copy
// let temp = this.state.cards.splice(0);
let temp = (
<ProjectCard
id="addingCard"
deleteHandler={this.deleteHandler}
saveHandler={this.saveHandler}
cancel={this.cancelAdding}
/>
);
this.setState({
...this.state,
addingCard: temp,
adding: true,
});
};
render() {
// console.log('rendering'+this.state.cards);
let toShow;
if (this.state.cards.length === 0 && this.state.addingCard === null) {
toShow = (
<div className={classes.Project}>
<div className={classes.row}>
<p className={classes.SectionName}>{text.project}</p>
<img
className={classes.addIcon}
src={addIcon}
alt="icon"
onClick={this.addHandler}
/>
</div>
<div className={classes.Container}>
<p>{text.noProject}</p>
</div>
</div>
);
} else {
toShow = (
<div className={classes.Project}>
<div className={classes.row}>
<p className={classes.SectionName}>{text.project}</p>
<img
className={classes.addIcon}
src={addIcon}
alt="icon"
onClick={this.addHandler}
/>
</div>
<div className={classes.Container}>{this.state.cards}</div>
{this.state.addingCard}
</div>
);
}
return toShow;
}
}
Project.propTypes = {
requestID: PropTypes.string.isRequired,
};
export default Project;
|
define(['jquery', 'echarts'], ($, echarts) => {
let module = {};
let chart;
module.init = (el) => {
var chart = echarts.init(document.getElementById(el));
var options = {
title: {
text: '预算 vs 开销',
subtext: '纯属虚构'
},
tooltip: {
trigger: 'axis'
},
legend: {
orient: 'vertical',
x: 'right',
y: 'bottom',
data: ['预算分配', '实际开销']
},
polar: [{
indicator: [{
text: '销售',
max: 6000
},
{
text: '管理',
max: 16000
},
{
text: '信息技术',
max: 30000
},
{
text: '客服',
max: 38000
},
{
text: '研发',
max: 52000
},
{
text: '市场',
max: 25000
}
]
}],
calculable: true,
series: [{
name: '预算 vs 开销',
type: 'radar',
data: [{
value: [4300, 10000, 28000, 35000, 50000, 19000],
name: '预算分配'
},
{
value: [5000, 14000, 28000, 31000, 42000, 21000],
name: '实际开销'
}
]
}]
};
chart.setOption(options);
$(window).on('resize', chart.resize);
};
module.destroy = () => {
if (chart) {
$(window).off('resize', chart.resize);
}
};
return module;
}); |
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('ListItem', new Schema({
name: {
type: String,
required: true
},
quantity: {
type: Number,
required: true
},
unit: {
type: String,
required: true
},
listId: {
type:mongoose.Schema.Types.ObjectId,
ref: 'List'
},
checked: {
type: Boolean,
required: true,
default: false
}
})); |
//Função da mascara para substituir valores
function mask(element, maskName) {
setTimeout(function () {
var valor = maskName(element.value);
if (valor != element.value) {
element.value = valor;
}
}, 1);
}
//Função para aplicar a mascara em cima de um elemento na pagina (id)
function mascarar(element, maskName) {
if (document.getElementById(element)) {
document.getElementById(element).oninput = function () {
mask(this, maskName);
}
}
}
function mTel(v) {
var r = v.replace(/\D/g,"");
r = r.replace(/^0/,"");
if (r.length > 10) {
// 11+ digitos. Formata como 5+4.
r = r.replace(/^(\d\d)(\d{5})(\d{4}).*/,"($1)$2-$3");
}
else if (r.length > 5) {
// 6..10 digitos. Formata como 4+4
r = r.replace(/^(\d\d)(\d{4})(\d{0,4}).*/,"($1)$2-$3");
}
return r;
}
function mCpf(v) {
var r = v.replace(/\D/g,"");
r = r.replace(/^0/,"");
r = r.replace(/^(\d{3})(\d{3})(\d{3})(\d{2}).*/,"$1.$2.$3-$4");
return r;
}
function mCep(v) {
var r = v.replace(/\D/g,"");
r = r.replace(/^(\d{8}).*/,"$1");
return r;
}
function mUf(v) {
var r = v.replace(/[^a-zA-Z]/g,"");
r = r.replace(/^(\D{2}).*/,"$1");
r = r.toUpperCase()
return r;
}
//Realiza funções assim que a tela inicia
window.onload = function () {
mascarar('cpf', mCpf);
mascarar('cpftxt', mCpf);
mascarar('telefone', mTel);
mascarar('cep', mCep);
mascarar('uf', mUf);
} |
function showList(){
document.getElementById("addList").style.display = "block";
document.getElementById("cover").style.display = "block";
}
function showThing(){
document.getElementById("addThing").style.display = "block";
document.getElementById("cover").style.display = "block";
}
function hideAll(){
document.getElementById("addList").style.display = "none";
document.getElementById("addThing").style.display = "none";
document.getElementById("cover").style.display = "none";
}
function check_list(){
if(document.getElementById("listName").value == "")return false;
return true;
}
function check_search(){
if(document.getElementById("search_content").value == "") return false;
return true;
}
function deleteThing(id,list){
location.href = "/delete?id="+id+"&list="+list;
return;
}
function removeThing(id){
location.href = "/remove?id="+id;
return;
}
function getDay(year,month){
var days = [31,28,31,30,31,30,31,31,30,31,30,31];
if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) days[1]++;
return days[month-1];
}
function check_thing(){
var title = document.getElementById("title").value;
var year = document.getElementById("year").value;
var month = document.getElementById("month").value;
var day = document.getElementById("day").value;
var thing_tip = document.getElementById("thing_tip");
if(title == ""){
return false;
}
if(year == "" || isNaN(year) || year < 1000 || year > 10000){
return false;
}
if(month == "" || isNaN(month) || month < 1 || month > 12){
return false;
}
if(day == "" || isNaN(day) || day < 1 || day > getDay(year,month)){
return false;
}
return true;
}
|
import { useState, useEffect } from 'react';
import { Container, Row, Col } from 'react-bootstrap';
import {fs, auth} from '../../../config/firebase.js'
import {EncomendasItem} from './indivudal-item/encomenda-item.js';
const EncomendasList = () => {
const [items, setItems] = useState([]);
useEffect(() => {
auth.onAuthStateChanged(user=>{
if(user){
fs.collection('Encomendas-list').onSnapshot(snapshot => {
const newItem = // Variável com vetor de itens do map seguinte:
snapshot.docs.map((doc) => ({ //Faz um map na lista de documentos da seleção
ID: doc.id,
...doc.data(),
}));
newItem.map((individualItem) => { //Faz um map no vetor de itens do newItem
if (individualItem.uid === user.uid.toString()) {
setItems((prevState) => [...prevState, individualItem]);
}
})
})
}
})
}, [])
//Renderizar tabela database
return (
<Container>
<Row id="table-title">
<Col className="d-flex justify-content-between align-items-center">
<h1>Minhas encomendas</h1>
</Col>
</Row>
<Row id="table-header">
<Row id="table-Item-header">
<Col xs={4}>Número do Pedido</Col>
<Col xs={3}>Titulo</Col>
<Col xs={2}>Status</Col>
<Col xs={3}>Data</Col>
</Row>
</Row>
<Row id="table-body">
{items.length > 0 && (<>
<EncomendasItem items={items} />
</>)}
{items.length < 1 && (
<div className='container-fluid'>Por favor, espere....</div>
)}
</Row>
</Container>
)
};
export default EncomendasList; |
function createDrawObject(name,model,cubeColor,fakeColor,eyePos,lightPos,spin,translation,scale) {
var pickObj= new Object();
pickObj.name = name;
pickObj.model = model;
pickObj.cubeColor = cubeColor;
pickObj.fakeColor = fakeColor;
pickObj.eyePos = eyePos;
pickObj.lightPos = lightPos;
pickObj.spin = spin;
pickObj.translation = translation;
pickObj.scale = scale;
pickObj.draw = true;
return pickObj;
} |
define(["app"],
function (app) {
var Tracker = Backbone.Model.extend({
testGaAccount : "UA-65962807-1",
testBaiduAccount : "d91da0c4c2d6f4f817bf6826f16cec40",
initialize: function (opt) {
var gaAccount = this.testGaAccount;
var baiduAccount = this.testBaiduAccount;
if (opt && app.isProduction) {
if (opt.gaAccount && opt.gaAccount != "") {
gaAccount = opt.gaAccount;
}
if (opt.baiduAccount && opt.baiduAccount != "") {
baiduAccount = opt.baiduAccount;
}
}
// google analytics
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script', app.assetsPath + 'js/app/vendor/utils/ga-analytics.js','ga');
ga('create', gaAccount, 'auto');
// baidu
window._hmt = window._hmt || [];
window._hmt.push(['_setAccount', 'd91da0c4c2d6f4f817bf6826f16cec40']);
window._hmt.push(['_setAutoPageview', false]);
/*
(function() {
var hm = document.createElement("script");
hm.src = "//hm.baidu.com/hm.js?d91da0c4c2d6f4f817bf6826f16cec40";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
*/
},
pv: function (name) {
name = "/" + name;
ga('send', 'pageview', name);
window._hmt.push(['_trackPageview', name]);
},
event: function (category, action, name) {
//ga('send', 'event', 'button', 'click', name);
ga('send', 'event', category, action, name);
window._hmt.push(['_trackEvent', category, action, name]);
}
});
// Return the module for AMD compliance.
return Tracker;
});
|
/* global document */
System
.import("app.module")
.then(() =>
angular
.element(document)
.ready(() => angular.bootstrap(document, ["app"], {strictDi: true}))
);
|
import React from 'react';
import styles from './styles/splash.scss';
import BlockchainDemo from './components/BlockchainDemo';
import ArrowWrapper from './components/ArrowWrapper';
const Splash = () => {
return (
<div className={`row ${styles.container1}`}>
<BlockchainDemo />
<ArrowWrapper />
</div>
);
};
export default Splash;
|
async function fetchInitialDeals() {
try {
const response = await fetch('https://bakesaleforgood.com/api/deals');
const responseJson = await response.json();
return responseJson;
} catch (error) {
console.error(error);
}
}
async function fetchDealDetail(dealId) {
try {
const response = await fetch(`https://bakesaleforgood.com/api/deals/${dealId}`);
const responseJson = await response.json();
return responseJson;
} catch (error) {
}
}
export default {
fetchInitialDeals,
fetchDealDetail,
};
|
import React, { Component } from 'react';
import {Link, withRouter} from 'react-router-dom';
import { connect } from 'react-redux';
class DashboardMenu extends Component {
constructor(props) {
super(props);
console.log("props ===>", props);
this.state = {
match : props.match,
path: (props && props.location) ? props.location.pathname: '/dashboard',
menus : [
{title: 'Dashboard', link: '/home'},
{title: 'Profile', link: '/profile'},
{title: 'Services', link: '/services'},
{title: 'Branding & Script', link: '/branding'},
{title: 'polling', link: '/polling'},
{title: 'Question', link: '/question'},
{title: 'Plan info', link: '/planinfo'}
]
}
}
render() {
const {path, menus} = this.state;
console.log(path);
return (
<div className="client-menu">
{menus.map( (menu, index) => <Link key= {index} className={ (path == '/dashboard' + menu.link)? 'active': ''} to={'/dashboard' + menu.link}>{menu.title}</Link>)}
</div>
);
}
}
function mapStateToProps(state) {
const {match} = state;
return {
match
};
}
const connectedRegisterPage = connect(mapStateToProps)(withRouter(DashboardMenu));
export { connectedRegisterPage as DashboardMenu };
|
class Turtle {
constructor(x, y) {
this.x = x;
this.y = y;
this.location = {
'x': x,
'y': y
};
this.direction = "e";
this.walked = [];
this.xMax = 0;
this.xArray = [];
this.yMax = 0;
this.yArray = [];
}
right() {
if (this.direction === "e") {
this.direction = "s"
} else if (this.direction === "s") {
this.direction = "w"
} else if (this.direction === "w") {
this.direction = "n"
} else if (this.direction === "n") {
this.direction = "e"
} else {
console.log("Invalid direction, resetting to East")
this.direction = "e"
}
return this
}
left() {
if (this.direction === "e") {
this.direction = "n"
} else if (this.direction === "n") {
this.direction = "w"
} else if (this.direction === "w") {
this.direction = "s"
} else if (this.direction === "s") {
this.direction = "e"
} else {
console.log("Invalid direction, resetting to East")
this.direction = "e"
}
return this
}
allPoints(pt) {
return this.walked.push(pt);
}
forward(steps) {
for (let i = 0; i < steps; i++) {
this.allPoints(this.location)
if (this.direction === "e") {
this.location = Object.assign({},
this.location, {
x: this.location['x'] + 1
}
)
} else if (this.direction === "s") {
this.location = Object.assign({},
this.location, {
y: this.location['y'] + 1
}
)
} else if (this.direction === "w") {
this.location = Object.assign({},
this.location, {
x: this.location['x'] - 1
}
)
} else if (this.direction === "n") {
this.location = Object.assign({},
this.location, {
y: this.location['y'] - 1
}
)
}
}
return this;
}
maxX(){
for(let i of this.walked){
this.xArray.push(i.x)
}
this.xMax = Math.max(...this.xArray);
return this;
}
maxY(){
for(let i of this.walked){
this.yArray.push(i.y)
}
this.yMax = Math.max(...this.yArray);
return this;
}
print(){
this.allPoints(this.location);
this.maxX();
this.maxY();
let myArray = arrayGen(this.xMax,this.yMax);
let tempArray = [];
for (let position of this.walked) {
myArray[position.y][position.x] = 1
}
for (let arr of myArray){
tempArray.push(arr.join(" "));
}
console.log(tempArray.join("\n"));
return this;
}
}
function arrayGen(width, height) {
let array = [], row = [];
while (width-- > -1) row.push(0);
while (height-- > -1) array.push(row.slice());
return array;
}
const first = new Turtle(0, 0)
first.forward(3).right().forward(2).left().forward(1).print(); |
import React from "react";
import Table from "./Table";
import Form from "../Forms/Form";
class App extends React.Component {
state = {
characters: [
{
name: 'D-Dog',
job: 'Ju Jitsu Man',
},
{
name: 'B-Dog',
job: 'Meme Lord',
},
{
name: 'Z-Dog',
job: 'Big Boi',
},
{
name: 'M-Dog',
job: 'Teacher/Da Man',
},
],
};
removeCharacter = index => {
const { characters } = this.state;
this.setState({
characters: characters.filter((character, i) => {
return i !== index
}),
});
}
editCharacter = index => {
const { characters } = this.state;
this.setState({
characters: characters.filter((character, i) => {
character.set()
}),
});
}
handleSubmit = character => {
this.setState({ characters: [...this.state.characters, character] });
}
render() {
const { characters } = this.state;
return (
<div className="container">
<Table characterData={characters} removeCharacter={this.removeCharacter} />
<Form handleSubmit={this.handleSubmit} />
</div>
)
}
}
export default App |
import { renderString } from '../../src/index';
describe(`A color picker module`, () => {
it(`unnamed case 0`, () => {
const html = renderString(`{% color "color" %}`);
});
it(`unnamed case 1`, () => {
const html = renderString(`{% color "my_color_picker", label="Choose a color", color="#000000", no_wrapper=True %}`);
});
}); |
/**
* creates the resizer object
* @return {Objects} resizer object with Various helper methods.
*/
var resizer = d3scomos.resizer = (function(){
/**
* return the resize handle
* @return {[type]} [description]
*/
var dragSE = d3.behavior.drag()
//.origin(Object)
.on("dragstart",dragSEStart)
.on("drag", dragSE)
.on("dragend",dragSEEnd);
var dragSEStart = function(d){
d3.event.sourceEvent.stopPropagation();
//console.warn('drag SE Started');
}
var dragSE = function(d){
d3.event.stopPropagation();
//console.warn('dragging SE');
var thisNode = this;
if(d3.event.dx && d3.event.dy ){
thisNode.attr('x', parseFloat(thisNode.attr('x')) + d3.event.dx);
thisNode.attr('y',parseFlaot(thisNode.attr('y'))+d3.event.dy);
}
}
var dragSEEnd = function(d){
//console.warn('drag se eneded');
}
/**
* Sets up the resizer around provided node.
* @param {D3 selector} node d3 selector pointing node.
* @param {Number} resizerType resizer type value 0- 4 point ,1-8 point.
* @return {} sets up the resizer UI with provided settings.
*/
var setupResizer = function (node,resizerType){
//add group elem to the node with reisizer classed
//add respective rects
//add proper classes to these
resizerType = resizerType || 0;
var nodeData = node.datum();
var rDimensions = node.select('path').node().getBBox();
//console.warn(node.select('path').node().getBBox())
var nodeH = rDimensions.height;
var nodeW = rDimensions.width;
var h = 7;
var w = 7;
//var resizerG = node.append('g').classed('resizer',true)
//add NW
var NWRect = node.append('rect').classed('resizer',true).classed('rNW',true)
.attr('x',-w).attr('y',-h)
.attr('height',h).attr('width',w);
//add NE
var NERect = node.append('rect').classed('resizer',true).classed('rNE',true)
.attr('x',nodeW).attr('y',-h)
.attr('height',h).attr('width',w);
//add SE
var SERect = node.append('rect').classed('resizer',true).classed('rSE',true)
.attr('x',nodeW).attr('y',nodeH)
.attr('height',h).attr('width',w);
//add SW
var SWRect = node.append('rect').classed('resizer',true).classed('rSW',true)
.attr('x',-w).attr('y',nodeH)
.attr('height',h).attr('width',w);
if(resizerType == 1){
var NRect = node.append('rect').classed('resizer',true).classed('rN',true)
.attr('x',nodeW/2).attr('y',-h)
.attr('height',h).attr('width',w);
var ERect = node.append('rect').classed('resizer',true).classed('rE',true)
.attr('x',nodeW).attr('y',nodeH/2)
.attr('height',h).attr('width',w);
var SRect = node.append('rect').classed('resizer',true).classed('rS',true)
.attr('x',nodeW/2).attr('y',nodeH)
.attr('height',h).attr('width',w);
var WRect = node.append('rect').classed('resizer',true).classed('rW',true)
.attr('x',-w).attr('y',nodeH/2)
.attr('height',h).attr('width',w);
}
}
/**
* update resize handlers
* @param {D3 Selector} node d3 selector with resizer attached to it.
* @return {} updates the resizer based on the nwe sise data.
*/
var updateResizer = function(node){
if(!node)
node = d3.select('.resizer');
var nodeData = node.datum();
var rDimensions = node.select('path').node().getBBox();
//console.warn(node.select('path').node().getBBox())
var nodeH = rDimensions.height;
var nodeW = rDimensions.width;
var h = 7;
var w = 7;
node.each(function(){
var NWRect = node.select('.rNW')
.attr('x',-w).attr('y',-h)
.attr('height',h).attr('width',w);
var NERect = node.select('.rNE')
.attr('x',nodeW).attr('y',-h)
.attr('height',h).attr('width',w);
var SERect = node.select('.rSE')
.attr('x',nodeW).attr('y',nodeH)
.attr('height',h).attr('width',w);
var SWRect = node.select('.rSW')
.attr('x',-w).attr('y',nodeH)
.attr('height',h).attr('width',w);
var NRect = node.select('.rN')
.attr('x',nodeW/2).attr('y',-h)
.attr('height',h).attr('width',w);
var ERect = node.select('.rE')
.attr('x',nodeW).attr('y',nodeH/2)
.attr('height',h).attr('width',w);
var SRect = node.select('.rS')
.attr('x',nodeW/2).attr('y',nodeH)
.attr('height',h).attr('width',w);
var WRect = node.select('.rW')
.attr('x',-w).attr('y',nodeH/2)
.attr('height',h).attr('width',w);
})
}
/**
* resizes the current shape based on the resizeStatus vlaues.
* @param {
* isResizing:Boolean ,activeResizeHandle:String,
* node:{D3 selector},
* event:{D3 drag event}}; resizeStatus params required to process this resize event
* @return {} handles the drag shape resize and redraw, transform etc for both
* node shape and resize handlers
*/
var processResize = function(resizeStatus){
var thisNode = resizeStatus.node;
var thisData = thisNode.datum();
var event = resizeStatus.event;
var aspectRatio = thisData.iWidth / thisData.iHeight;
if(resizeStatus.activeResizeHandle === 'rN'){
var oldHeight = thisData.iHeight;
thisData.iHeight -= event.dy;
if(thisData.iHeight < 10 ) thisData.iHeight = 10;
thisData.position.iY -= thisData.iHeight - oldHeight;
}
else if(resizeStatus.activeResizeHandle === 'rE'){
thisData.iWidth += event.dx;
if(thisData.iWidth < 10 ) thisData.iWidth = 10;
}
else if(resizeStatus.activeResizeHandle === 'rS'){
thisData.iHeight += event.dy;
if(thisData.iHeight < 10 ) thisData.iHeight = 10;
}
else if(resizeStatus.activeResizeHandle === 'rW'){
var oldWidth = thisData.iWidth;
thisData.iWidth -= event.dx;
if(thisData.iWidth < 10 ) thisData.iWidth = 10;
thisData.position.iX -= thisData.iWidth - oldWidth;
}
else if(resizeStatus.activeResizeHandle === 'rNE'){
//rule width follows height
thisData.iHeight -= event.dy;
if(thisData.iHeight < 10 ) thisData.iHeight = 10;
thisData.iWidth = thisData.iHeight * aspectRatio;
//thisData.position.iX += event.dx;
thisData.position.iY += event.dy;
}
else if(resizeStatus.activeResizeHandle === 'rSE'){
//rule width follows height
thisData.iHeight += event.dy;
if(thisData.iHeight < 10 ) thisData.iHeight = 10;
thisData.iWidth = thisData.iHeight * aspectRatio;
//thisData.position.iX += event.dx;
//thisData.position.iY += event.dy;
}
else if(resizeStatus.activeResizeHandle === 'rSW'){
//rule width follows height
var oldWidth = thisData.iWidth;
thisData.iHeight += event.dy;
if(thisData.iHeight < 10 ) thisData.iHeight = 10;
thisData.iWidth = thisData.iHeight * aspectRatio;
thisData.position.iX += oldWidth - thisData.iWidth;
//thisData.position.iY += event.dy;
}
else if(resizeStatus.activeResizeHandle === 'rNW'){
//rule width follows height
var oldWidth = thisData.iWidth;
thisData.iHeight -= event.dy;
if(thisData.iHeight < 10 ) thisData.iHeight = 10;
thisData.iWidth = thisData.iHeight * aspectRatio;
thisData.position.iX -= thisData.iWidth - oldWidth;
thisData.position.iY += event.dy;
}
modelHelper.updateNodeView(thisNode)
updateResizer(thisNode);
//update affecting links
d3.selectAll('.link').attr('d', function(d){return shapeUtil.getPathCoordsForLine(d.source, d.target, d.role)});
}
/**
* Finds removes any resizers on from the page
* @return {D3 selection} selection of deleted resizers
*/
var clearAllResizers = function(){
return d3.selectAll('.resizer').remove();
}
return {
/**
* adds the resizer to the passed in node.
* @param {D3 selector} node vaid d3 selector to the target node.
* @return {D3 selector} d3 selector pointing to this node.
* @throws {Error} if invalid node is passed
*/
addResizer:function(node){
//console.warn(node);
if(!node)
throw new Error('Empty node value passed');
if(! (node instanceof d3.selection))
throw new Error('Pass valid d3 Selector');
if(node.size() == 0)
throw new Error('Empty d3 selctor passed');
//remove resizers if any
clearAllResizers();
//construct resizer rects assuming
if(node.datum().getEntityType() === 'Compartment')
setupResizer(node,1);
else
setupResizer(node);
},
// /**
// * finds and updates all resizer handlers or only node if node is passed
// * @param {D3 Selector} node d3 selector with resizer attached to it.
// * @return {} updates the resizer based on the nwe sise data.
// */
// updateResizer:function(node){
// updateResizer(node);
// },
/**
* resizes the current shape based on the resizeStatus vlaues.
* @param {
* isResizing:Boolean ,activeResizeHandle:String,
* node:{D3 selector},
* event:{D3 drag event}}; resizeStatus params required to process this resize event
* @return {[type]} [description]
* //NOTE: no need to rest this method seperately as this will be called internally by the
* drag method, as resize and drag behaviours are now triggered from same handler
*/
processResize:function(resizeStatus){
//process this reszie if true resize
//maybe validate resizeStatus params
//TODO: add param validation here
if(resizeStatus.isResizing == true){
processResize(resizeStatus);
}
},
/**
* clears any resizer on the current page unless node is passed.
* @return {D3 selector} d3 selector pointing to this node.
*/
clearResizer:function(){
return d3.selectAll('.resizer').remove();
},
/**
* updates the resizer hanldes by readding them on selected node.
* @return {} checks if only one node is selected and adds the resizer hanldes.
*/
updateResizer:function(){
this.clearResizer();
var _selection = d3.selectAll('.selected');
//proceed if only one item is selcted
if ( _selection.size() == 1 && !_selection.classed('reaction-node') && !_selection.classed('link')){
this.addResizer(_selection);
}
}
}
})();
|
"use strict";
var _ = require('lodash');
var models = require('../models');
var logger = require('../logger');
var FeedbackMeta = module.exports;
FeedbackMeta.findById = function (uuid, callback) {
models.FeedbackMeta.findById(uuid).then(function (data) {
return callback(null, data);
}, function (err) {
logger.error(err);
return callback(err);
});
};
FeedbackMeta.create = function (feedbackMeta, callback) {
models.FeedbackMeta.create(feedbackMeta).then(function (data) {
return callback(null, models.getPlainObject(data));
}, function (err) {
logger.error(err);
return callback(err);
});
};
FeedbackMeta.update = function (feedbackMeta, condition, callback) {
models.FeedbackMeta.update(feedbackMeta, {where: condition}).then(function (data) {
return callback(null, data);
}, function (err) {
logger.error(err);
return callback(err);
});
};
FeedbackMeta.delete = function (condition, callback) {
models.FeedbackMeta.destroy({where: condition}).then(function (data) {
return callback(null, data);
}, function (err) {
logger.error(err);
return callback(err);
});
};
FeedbackMeta.listAndCount = function (condition, order, callback) {
order = order || [['createdAt', 'DESC']];
var filter = {
where: condition,
order: order
};
models.FeedbackMeta.findAndCountAll(filter).then(function (data) {
return callback(null, data);
}, function (err) {
logger.error(err);
return callback(err);
});
};
FeedbackMeta.listAll = function (attributes, condition, callback) {
models.FeedbackMeta.findAll({
attributes: attributes,
where: condition
}).then(function (data) {
return callback(null, models.getPlainArray(data));
}, function (err) {
logger.error(err);
return callback(err);
});
};
FeedbackMeta.findAll = function (condition, order, callback) {
order = order || [['createdAt', 'DESC']];
var filter = {
where: condition,
order: order
};
models.FeedbackMeta.findAll(filter).then(function (data) {
return callback(null, models.getPlainArray(data));
}, function (err) {
logger.error(err);
return callback(err);
});
}; |
/**
* Service
*/
angular.module('ngApp.systemAlert').
factory('SystemAlertService', function ($http, config, SessionService) {
var getAllSystemAlerts = function (trackSystemAlert) {
return $http.post(config.SERVICE_URL + '/SystemAlert/GetSystemAlerts', trackSystemAlert);
};
var getSystemAlertDetail = function (operationZoneId, systemAlertId) {
return $http.get(config.SERVICE_URL + '/SystemAlert/GetSystemAlertDetail', {
params: {
operationZoneId: operationZoneId,
systemAlertId: systemAlertId
}
});
};
var saveUpdateSystemAlerts = function (frayteSystemAlert) {
return $http.post(config.SERVICE_URL + '/SystemAlert/SaveUpdateSystemAlerts', frayteSystemAlert);
};
var GetTimeZones= function () {
return $http.get(config.SERVICE_URL + '/Shipment/GetInitials');
};
var GetPublicSystemAlert = function (OperationZoneId, currentDate) {
return $http.get(config.SERVICE_URL + '/SystemAlert/GetPublicSystemAlerts', {
params: {
OperationZoneId: OperationZoneId,
currentDate: currentDate
}
});
};
var DeleteSystemAlert = function (systemAlertId) {
return $http.get(config.SERVICE_URL + '/SystemAlert/DeleteSystemAlert', {
params: {
systemAlertId: systemAlertId
}
});
};
var GetPublicSystemAlertDetail = function (OperationZoneId, systemAlertHeading) {
return $http.get(config.SERVICE_URL + '/SystemAlert/GetPublicSystemAlertDetail', {
params: {
OperationZoneId: OperationZoneId,
systemAlertHeading: systemAlertHeading
}
});
};
var SystemAlertHeadingAvailability = function (OperationZoneId, systemAlertHeading) {
return $http.get(config.SERVICE_URL + '/SystemAlert/SystemAlertHeadingAvailability', {
params: {
OperationZoneId: OperationZoneId,
systemAlertHeading: systemAlertHeading
}
});
};
return {
GetAllSystemAlerts: getAllSystemAlerts,
GetSystemAlertDetail: getSystemAlertDetail,
SaveUpdateSystemAlerts: saveUpdateSystemAlerts,
GetTimeZones: GetTimeZones,
GetPublicSystemAlert: GetPublicSystemAlert,
GetPublicSystemAlertDetail: GetPublicSystemAlertDetail,
SystemAlertHeadingAvailability: SystemAlertHeadingAvailability,
DeleteSystemAlert: DeleteSystemAlert
};
}); |
var mocha = require('mocha')
var chai = require('chai')
var expect = chai.expect
var SpyJSONToHarnessJSON = require('../src/SpyJSONToHarnessJSON')
mocha.describe('Spy JSON to Harness JSON', function () {
mocha.it('One Variable', function () {
var spyJSON = {
testedFunctionCall: 'testFunction(a)',
result: 'NOTSET',
variables:
[{
name: 'a',
values: [{
timing: 'Initial',
value: 2
}]
}
],
functions: []
}
var expectedJSON = [
{ variableDefinition: { name: 'a', value: 2 } }
]
expect(SpyJSONToHarnessJSON(spyJSON)).to.deep.equal(expectedJSON)
})
mocha.it('One Function', function () {
var spyJSON = {
testedFunctionCall: 'testFunction(a)',
result: 8,
variables: [],
functions: [{
name: 'a',
traffic: [{
callNumber: 0,
arguments: [1, 5],
returnValue: 6
}, {
callNumber: 1,
arguments: [5, -3],
returnValue: 2
}]
}]
}
var expectedJSON = [
{
functionHarness: [
{
variableDefinition: {
name: 'MOCK0_DB',
value: [{
arguments: [1, 5],
returnValue: 6
}, {
arguments: [5, -3],
returnValue: 2
}]
}
}, { variableDefinition: { name: 'MOCK0_counter', value: 0 } },
{
functionDefinition: {
name: 'a',
content: [
{ validateInputAndGetOutput: { function: 'a', DB: 'MOCK0_DB', counter: 'MOCK0_counter', returnVariable: 'output' } },
{ increaseCounterByOne: { counter: 'MOCK0_counter' } },
{ returnOutput: { returnVariable: 'output' } }]
}
}
]
}, { testFunctionAssertion: { result: 8, testFunctionCall: 'testFunction(a)' } }
]
expect(SpyJSONToHarnessJSON(spyJSON)).to.deep.equal(expectedJSON)
})
}) |
import React, { useContext } from "react";
import { StyledLink, SvgIcon } from "@common/Generic.js";
import { ThemeContext } from "@common/Layout";
import { Help } from "@styles/svg/Buttons";
import styled from "styled-components";
const StyledSvg = styled(SvgIcon)`
width: 3vh;
height: 3vh;
margin: 1vh;
`;
export const AboutLink = () => {
const colors = useContext(ThemeContext);
return (
<StyledLink
title="about"
colors={colors}
cover
direction="right"
bg={colors.background}
duration={1.5}
to="/about"
>
<StyledSvg color={colors.violet} svg={Help} />
</StyledLink>
);
};
|
import gql from 'graphql-tag'
export const getAllVideos = gql`
query VideoPaginator($first: Int!, $page: Int) {
videos(first: $first, page: $page) {
data {
id
title
video_url
}
}
}
`
|
/* eslint no-new-object: 'off' */
const assert = require('assert');
const obvl = require('../');
describe('OBVL', () => {
let fallbackValue = { a: 1, b: 2, c: 3 };
it('should return `value` when `value` is Object.', () => {
let emptyObject = {};
let objectInstance = new Object();
assert.strictEqual(obvl(emptyObject, fallbackValue), emptyObject);
assert.strictEqual(obvl(objectInstance, fallbackValue), objectInstance);
});
it('should return `fallbackValue` when `value` is not Object.', () => {
assert.strictEqual(obvl(null, fallbackValue), fallbackValue);
assert.strictEqual(obvl([1, 2, 3], fallbackValue), fallbackValue);
assert.strictEqual(obvl(0, fallbackValue), fallbackValue);
assert.strictEqual(obvl('string', fallbackValue), fallbackValue);
assert.strictEqual(obvl(Symbol('symbol'), fallbackValue), fallbackValue);
});
});
|
import React from 'react';
import { Switch, Route, Redirect } from 'react-router';
import dashboard from './dashboard/dashboard';
import Login from './login/Login';
import PrivateRoute from './auth-guard';
const ReactRouter = props => {
return (
<Switch>
<Route exact path="/login" component={Login} />
<PrivateRoute path="/dashboard" component={dashboard} />
<Redirect from="*" to="/login" />
</Switch>
);
};
export default ReactRouter;
|
import React, {useState} from "react";
import AddUser from "./components/Users/AddUser";
import UserList from "./components/Users/UserList";
const DUMMY_USERS = [
{
name: "Ai",
age: 31,
id: "e1",
},
{
name: "Kevin",
age: 35,
id: "e2",
},
{
name: "Gavin",
age: 37,
id: "e3",
},
];
function App() {
const [users, setUsers] = useState(DUMMY_USERS);
const addUserHandler = (userFromAddUser) => {
setUsers((prevUsers) => {
return [userFromAddUser, ...prevUsers];
});
};
return (
<React.Fragment>
<h1>VIP List</h1>
<AddUser onAddUser={addUserHandler} />
<UserList users={users} />
</React.Fragment>
);
}
export default App;
|
import { Schema, arrayOf } from 'normalizr';
import bookSchema from './bookSchema';
const author = new Schema('author', {
idAttribute: 'name',
});
author.define({
books: arrayOf(bookSchema),
});
export default author;
|
'use strict';
angular.module('questionnaire2', [
'questionnaire2.service'
]);
|
/*
* Создайте функцию truncate(str, maxlength), которая проверяет длину строки str и, если она превосходит maxlength, заменяет конец str на "…", так, чтобы её длина стала равна maxlength.
Результатом функции должна быть та же строка, если усечение не требуется, либо, если необходимо, усечённая строка.
Например:
truncate("Вот, что мне хотелось бы сказать на эту тему:", 20) = "Вот, что мне хотело…"
truncate("Всем привет!", 20) = "Всем привет!"*/
alert(truncate('text', 2));
function truncate(text, maxlength) {
return text.length < maxlength ?
text : text.slice(0, maxlength - 1) + '...';
} |
var game = {
nums: [[0]],
price:[[1]],
cash: 1,
counter: [],
}
var check = 0;
function init() {
setInterval(loop, 50);
updateTable();
}
function loop() {
check++;
var nums = game.nums;
var cps;
for (var i = 0; i < nums.length; i++) {
if(i == 0) for (var j = 0; j < nums[0].length; j++) j === 0 ? cps = nums[0][j] : cps *= nums[0][j] + 1;
for (var j = 0; j < nums[i].length; j++)if(i > 0) nums[i - 1][j] += nums[i][j];
if (nums[i][nums[i].length - 1] >= 1) {
nums[i].push(0);
game.price[i].push(i + 1 * nums[i].length);
}
if (nums[nums.length-1][i] >= 10) {
nums.push([0]);
game.price.push([i + 1 * nums[i].length]);
}
}
document.getElementById("count").innerHTML = "Cash: " + game.cash.toFixed(2)+ "<br>" + "+" + cps + "/s";
cps /= 20;
game.cash += cps;
game.nums = nums;
if(check%10 === 0)updateTable();
}
function updateTable() {
var table = document.getElementById("main");
for (var i = 0; i < game.nums.length; i++) {
if (i+1 > table.rows.length) table.insertRow(i);
var row = table.rows[i];
for (var j = 0; j < game.nums[i].length; j++) {
if (j+1 > row.cells.length) row.insertCell(j);
var cell = row.cells[j];
cell.innerHTML ="<div><b> Number: " + game.nums[i][j] + "</b><br><button onclick='buy(" + i + "," + j + ")' style='width:100%'>Buy 1 <br> cost: " + game.price[i][j] + "</button></div>";
}
}
}
function buy(n1, n2) {
if (game.cash >= game.price[n1][n2]) {
game.cash -= game.price[n1][n2];
game.nums[n1][n2] += 1;
game.price[n1][n2] *= n1 + 1 * n2 + 1;
updateTable();
}
} |
import React, { Component } from 'react';
import { Typography } from '@material-ui/core';
import { withStyles } from '@material-ui/core/styles';
import svg from '../../images/undraw_moonlight_5ksn.svg';
const styles = {
root: {
display: 'flex',
flexDirection: 'column',
width: '100%',
height: '100%',
alignItems: 'center',
justifyContent: 'center',
margin: 'auto',
position: 'absolute',
top: 0,
left: 0,
},
errorText: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
marginBottom: '20px',
},
title: {
textAransform: 'uppercase',
},
subtitle: {
textAransform: 'uppercase',
},
svg: {
width: '250px',
}
};
class ForbiddenPage extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const { classes } = this.props;
return (
<div className={classes.root}>
<div className={classes.errorText}>
<Typography className={classes.title} variant="h3">403</Typography>
<Typography className={classes.subtitle} variant="h5">Forbidden</Typography>
</div>
<img
src={svg}
className={classes.svg}
/>
</div>
);
}
}
export default withStyles(styles)(ForbiddenPage);
|
import React from 'react';
// MATERIAL COMPONENTS
import { makeStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
// COMPONENTS
import DataTableRow from './DataTableRow';
const useStyles = makeStyles({
table: {
minWidth: 650
}
});
const DataTable = ({ data, isDeath = false }) => {
const classes = useStyles();
const createData = (state, country, cases, changes) => {
return { state, country, cases, changes };
};
const rows = data.map(row => {
const totalCases = row[Object.keys(row)[Object.keys(row).length - 1]];
const changes =
Number(row[Object.keys(row)[Object.keys(row).length - 1]]) -
Number(row[Object.keys(row)[Object.keys(row).length - 2]]);
return createData(
row['Province/State'],
row['Country/Region'],
totalCases,
changes
);
});
return (
<TableContainer component={Paper}>
<Table className={classes.table} aria-label='simple table'>
<TableHead>
<TableRow>
<TableCell>State</TableCell>
<TableCell align='center'>Country</TableCell>
<TableCell align='center'>
{isDeath ? 'Tolls' : 'Total Cases'}
</TableCell>
<TableCell align='center'>Changes Since Last Day</TableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map((row, key) => (
<DataTableRow row={row} key={key} />
))}
</TableBody>
</Table>
</TableContainer>
);
};
export default DataTable;
|
const fs = require('fs');
//逐步操作
//1.打开文件 fs.openSync(path[, flags, mode])
//path为文件的路径
//flag用于表明需要什么操作,
//w-打开文件用于写入。如果文件不存在则创建文件,如果文件已存在则截断文件。
//'a' - 打开文件用于追加。如果文件不存在,则创建该文件。
// const fd = fs.openSync('./01-aa.txt','w');//fd相当于一个打开文件成功后返回的标识
const fd = fs.openSync('./01-aa.txt','a');//fd相当于一个打开文件成功后返回的标识
//2.写入内容 fs.writeSync(fd, buffer[, offset[, length[, position]]])
//fd就是把文件成功后的标识传入
//buffer就是传入一个buffer数据,后面的可写可不写
// fs.writeSync(fd,'hai');
fs.writeSync(fd,'plmm');
//3.保存文件并退出
fs.closeSync(fd);
//合并操作 fs.writeFileSync(file, data[, options]),分别是文件名,需要传入的数据,且options中也可以
//传入flag,表明操作
fs.writeFileSync('./01-aa.txt',',可不可以加个WX ?',{flag:'a'}) |
'use strict';
describe("StateEvent Unit Tests", function() {
beforeEach(module('myApp'));
var $httpBackend;
var StateEvent;
beforeEach(inject(function($injector, _StateEvent_) {
StateEvent = _StateEvent_;
$httpBackend = $injector.get('$httpBackend');
$httpBackend.when('GET', 'http://mywifi.dev:8080/api/v1/boxes/123/state_events')
.respond(200, [{}]);
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should have sent a GET request to the state_events query API', function() {
var result = StateEvent.query({box_id: 123})
$httpBackend.expectGET('http://mywifi.dev:8080/api/v1/boxes/123/state_events')
$httpBackend.flush();
});
})
|
import React,{Component} from 'react';
import {View,Text,StyleSheet,FlatList,AsyncStorage,Image,StatusBar,TouchableOpacity,ImageBackground} from 'react-native';
import jwt from 'jwt-decode';
import api from '../services/api';
class Consultas extends Component{
static navigationOptions={
header:null,
};
constructor(props){
super(props);
this.state={
lista:[],
nome:"",
token:"",
id:"",
data: [],
loading: false,
}
}
sair=async()=>{
return alert("SPMEDICALGROUP"),this.props.navigation.navigate("AuthStack");
}
buscar = async()=>{
const value= await AsyncStorage.getItem("spmed");
this.setState({nome:jwt(value).nome});
this.setState({token:value});
return(jwt(value).tipo);
}
listar = async() =>{
const value= await AsyncStorage.getItem("spmed");
var config= {
headers:{
'Content-Type': 'application/json',
'Authorization': 'Bearer '+value}
};
if (this.state.loading) return;
this.setState({loading:true});
const resposta = await api.get("/agendamentos/usuarios",config);
const dados = resposta.data;
this.setState({lista:dados,loading:false});
}
ListaVazia = () => {
return (
<View>
<Image
source={require("../assets/img/pranchetinha.png")}
style={styles.img2}
/>
<Text style={{textAlign: 'center',color:"#777",fontWeight:"100"}}>Nenhuma Consulta Ainda...</Text>
<View style={styles.imgLogo}>
<Image
source={require("../assets/img/Ativo1.png")}
/>
<Text style={styles.spmed}>©SpmedGroup</Text>
</View>
</View>
);
}
componentDidMount(){
this.listar();
this.buscar();
}
render(){
return(
<View style={{backgroundColor:"white"}}>
<StatusBar translucent backgroundColor="white" barStyle="dark-content"/>
<View style={styles.Cabecalho}>
<Text style={styles.CabTitulo}>SPMEDICAL
<Text style={{color: '#80e289'}}>
GROUP
</Text>
</Text>
<Image
source={require("../assets/img/icon.png")}
style={styles.img}
/>
<Text style={styles.NomeUsuario}>{this.state.nome}</Text>
<Text style={styles.exit} onPress={this.sair}>Sair</Text>
</View>
<View>
<Text style={styles.titulo}>CONSULTAS</Text>
</View>
<FlatList
data={this.state.lista}
keyExtractor={item=>item.id.toString()}
renderItem={this._renderizaLista}
ListEmptyComponent={this.ListaVazia}
showsVerticalScrollIndicator={false}
vertical={true}
/>
</View>
);
}
_renderizaLista = ({item}) =>(
<View style={styles.Getlist}>
<View >
<Text style={{color:"#999"}} >Paciente</Text>
<Text style={{fontWeight:"300",color:"black",fontSize:17,fontFamily:"notoserif"}} >{item.idPacienteNavigation.idUsuarioNavigation.nome}</Text>
</View>
<View style={styles.medico} >
<Text style={{color:"#999"}}>Médico</Text>
<Text style={{fontWeight:"300",color:"black",fontSize:17}} >{item.idMedicoNavigation.idUsuarioNavigation.nome}</Text>
</View>
<View style={styles.data}>
<Text style={{color:"#999"}} >Data</Text>
<Text style={{fontWeight:"300",color:"black",fontSize:15}} >{item.dtAgendamento}</Text>
</View>
<View style={styles.situacao}>
<Text style={{color:"#999"}}>Situação</Text>
<Text style={{fontWeight:"300",color:"black",fontSize:17}} >{item.idSituacaoNavigation.nome}</Text>
</View>
<View style={styles.descricao}>
<Text style={{textAlign:"center",backgroundColor:"#80bdde",color:"white"}}>Descrição
</Text>
<Text style={{fontWeight:"200",color:"black",textAlign:"center",fontSize:12}}>{item.descricao}</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
Cabecalho:{
height:70,
fontStyle:"italic",
borderRadius:100,
marginTop:20,
},
CabTitulo:{
color:"#80bdde",
fontWeight:"100",
fontFamily:"sans-serif-light",
fontSize:25,
textAlign:"left",
marginLeft:15,
marginTop:15,
textShadowColor: '#f1f1f1',
textShadowOffset: {width: -2, height: 1},
textShadowRadius: 1
},
titulo:{
color:"#80aade",
textAlign:"center",
position:"relative",
left:155,
height:30,
width:120,
fontSize:21,
fontStyle:"italic",
fontFamily:"sans-serif-light",
},
Getlist:{
marginTop:30,
flexDirection:"row",
backgroundColor:"white",
height:150,
//F1FAFF
backgroundColor:"#F1FAFF",
borderBottomColor:"#333",
borderTopWidth:1,
borderTopColor:"#80bdde",
borderBottomWidth:0.5,
},
data:{
position:"relative",
left:50,
},
descricao:{
position:"relative",
top:70,
right:50,
width:125,
height:70,
borderWidth:0.5,
borderColor:"#ccc",
},
situacao:{
position:"relative",
left:90,
height:20,
},
medico:{
position:"absolute",
width:120,
top:50,
left:0,
},
NomeUsuario:{
position:"absolute",
right:20,
top:17,
width:100,
color:"white",
textAlign:"center",
backgroundColor:"#80aade",
borderTopRightRadius:20,
},
img:{
width:40,
height:40,
position:"absolute",
zIndex:-1,
right:0,
display:"none",
marginTop:15,
opacity:0.5,
},
img2:{
opacity:0.1,
width:100,
height:100,
position:"relative",
left:"40%",
marginTop:100
},
exit:{
position:"absolute",
right:2,
backgroundColor:"#80e289",
textAlign:"center",
width:70,
height:23,
fontSize:15,
top:50,
color:"white",
borderTopLeftRadius:20,
},
imgLogo:{
alignItems:"center",
marginTop:240,
opacity:0.4,
},
imgDescription:{
width:30,
height:30,
backgroundColor:"#80bdde",
},
});
export default Consultas;
|
/* Mongolian initialisation for the jQuery UI date picker plugin. */
$(document).ready(function() { //alert('alert1');
$.datepicker.regional['mn'] = {clearText: 'Effacer', clearStatus: '',
closeText: 'Хаах',
prevText: 'Өмнөх',
nextText: 'Дараах',
currentText: 'Одоо',
monthNames: ['1 дүгээр сар','2 дугаар сар','3 дугаар сар','4 дүгээр сар','5 дугаар сар','6 дугаар сар',
'7 дугаар сар','8 дугаар сар','9 дүгээр сар','10 дугаар сар','11 дүгээр сар','12 дугаар сар'],
monthNamesShort: ['1 сар','2 сар','3 сар','4 сар','5 сар','6 сар',
'7 сар','8 сар','9 сар','10 сар','11 сар','12 сар'],
dayNames: ['Ням','Даваа','Мягмар','Лхагва','Пүрэв','Баасан','Бямба'],
dayNamesShort: ['Ням','Дав','Мяг','Лха','Пүр','Баа','Бям'],
dayNamesMin: ['Ня','Да','Мя','Лх','Пү','Ба','Бя'],
dateFormat: 'yy-mm-dd', firstDay: 0};
// alert('alert2');
$.datepicker.setDefaults($.datepicker.regional['mn']);
});
|
// Install node.js, navigate to the app.build.js file path,
// and then run this command: "node js/libs/r.js -o js/app/config/build-single.js"
//
// Version optimizing app file sample.js
({
baseUrl: "../../",
paths: {
jquery: "empty:" // CDN
},
out: "../sample.min.js",
name: 'app/sample'
})
|
Array.prototype.quickSort = function(){
quickSortHelper(this, 0, this.length-1);
function quickSortHelper(arr,start,end){
if(start<end){
var part = partition(arr,start,end);
quickSortHelper(arr,start,part-1);
quickSortHelper(arr,part+1,end);
}
}
function partition(arr,start,end){
var pivot = arr[end];//哨兵
var i = start ;
for(var j= start;j <end;j++){
if(arr[j]<pivot){
swap(arr, i,j);
i++;
}
}
swap(arr,i,end);
return i;
}
function swap(arr,i,j){
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
};
var quickSort = function(arr) {
if(arr.length <= 1) return arr; // 递归停止条件
// 选取基准值
var pivotIndex = Math.ceil(arr.length / 2);
var pivot = arr.splice(pivotIndex, 1)[0]; // 基准值
var left = [], right = [];
// 如果大于基准值,移到数组right中;小于基准的值,移到数组left中
for(var i=0; i< arr.length; i++) {
arr[i] > pivot ? right.push(arr[i]) : left.push(arr[i]);
}
return quickSort(left).concat([pivot], quickSort(right));
};
function quickSort3(arr,left,right){
if(left<right){
var key = arr[left];
var low = left;
var high = right;
while(low<high){
while(low<high&&arr[high]>=key){
high--;
}
arr[low] = arr[high];
while(low<high&&arr[low]<=key){
low++;
}
arr[high] = arr[low];
}
arr[low] = key;
console.log(arr);
/*console.log(arr);
console.log(left);
console.log(low-1);
console.log(low+1);
console.log(right);*/
quickSort3(arr,left,low-1);
quickSort3(arr,low+1,right);
}else{
return 0;
}
}
var arr = [500, 21, 32, 155, 43,789,234,890,21,36,8,123,901,51,77];
quickSort3(arr,0,arr.length-1);
//console.log("123:",arr); |
const mongoose = require('mongoose');
let PaymentsHistorySchema = mongoose.Schema({
userID: {type: String, ref: 'User'},
amount: {type: Number},
remainMoney: {type: Number},
fromUser: {type: String, ref: 'User'},
typeAdvisoryID: {type: String, ref: 'TypeAdvisory'},
status: {type: Number},
createdAt: {
type: Number,
default: new Date().getTime()
},
updatedAt: {
type: Number,
default: new Date().getTime()
},
deletionFlag: {type: Boolean, default: false}
});
let PaymentsHistory = module.exports = mongoose.model('PaymentsHistory', PaymentsHistorySchema);
PaymentsHistorySchema.pre('save', async function (next) {
const currTime = new Date().getTime();
this.updatedAt = currTime;
if (this.isNew) {
this.createdAt = currTime;
}
next();
});
|
function multiProcessOutput() {
const outputData = {};
return {
generateOutput() {
const realOutput = [];
const processesOutput = Object.keys(outputData);
for(let i = 0; i < processesOutput.length; i++) {
const processOutput = outputData[processesOutput[i]];
const itemsProcessed = Object.keys(processOutput);
for(let j = 0; j < itemsProcessed.length; j++) {
const itemOutput = processOutput[itemsProcessed[j]];
realOutput.push({ item: itemsProcessed[j], ...itemOutput });
}
}
return realOutput;
},
addData(processId, itemId, itemData) {
outputData[processId] = outputData[processId] || {};
outputData[processId][itemId] = itemData;
}
};
}
module.exports = {
createNew() {
return multiProcessOutput();
}
};
|
const Lesson = require("../models/lessonModel");
const Teacher = require("../models/teacherModel")
/**
* Récupérer la liste des professeurs
* @param {*} req
* @param {*} res
*/
exports.getTeachers = (req, res) => {
Teacher.getTeachers((err, data) => {
if (err) {
res.status(500).send({
message: "Une erreur s'est produite au niveau du serveur !",
status: 500
});
} else {
res.status(200).send(data);
}
})
};
/**
* Récupérer un professeur selon son identifiant
* @param {*} req
* @param {*} res
*/
exports.getTeacher = (req, res) => {
let id = req.params.id;
Teacher.getTeacherById(id, (err, data) => {
if (err) {
res.status(500).send({
message: "Une erreur s'est produite au niveau du serveur !",
status: 500
});
} else {
if (data) {
res.status(200).send(data);
} else {
res.status(404).send({
message: `Le professeur avec l'id '${id}' n'existe pas !`,
status: 404
});
}
}
})
}
/**
* Supprimer un professeur à l'aide de son identifiant
* @param {*} req
* @param {*} res
*/
exports.deleteTeacher = (req, res) => {
let id = req.params.id;
Lesson.deleteLessonByTeacher(id, (err, data) => {
if (err) {
res.status(500).send({
message: "Une erreur s'est produite au niveau du serveur !",
status: 500
});
} else {
Teacher.deleteTeacher(id, (err, data) => {
if (err) {
res.status(500).send({
message: "Une erreur s'est produite au niveau du serveur !",
status: 500
});
} else {
if (data.affectedRows != 0) {
res.status(200).send({ message: `Le professeur avec l'id '${id}' a été supprimé avec succès !`, status: 200 });
} else {
res.status(404).send({ message: `Le professeur avec l'id '${id}' n'existe pas !`, status: 404 });
}
}
});
}
})
}
/**
* Modifier les données d'un professeur à l'aide de son identifiant
* et des données à modifier
* @param {*} req
* @param {*} res
*/
exports.updateTeacher = (req, res) => {
let name = req.body.name;
let id = req.params.id;
let teacher = new Teacher(name);
Teacher.updateTeacher(id, teacher, (err, data) => {
if (err) {
if (err.code === 'ER_DUP_ENTRY') {
res.status(409).send({
message: "Ce professeur existe déjà !",
status: 409
});
} else {
res.status(500).send({
message: "Une erreur s'est produite au niveau du serveur !",
status: 500
});
}
} else {
if (data.affectedRows) {
res.status(201).send({
message: "Modification effectuée avec succès",
status: 201
});
} else {
res.status(404).send({ message: `Le professeur avec l'id '${id}' n'existe pas !`, status: 404 });
}
}
})
}
exports.saveTeacher = (req, res) => {
let name = req.body.name;
if (!name) {
return res.status(400).send({
message: "Le nom du professeur n'est pas mentionné !",
status: 400
})
}
const teacher = new Teacher(name);
teacher.saveTeacher((err, data) => {
if (err) {
if (err.code === 'ER_DUP_ENTRY') {
res.status(409).send({
message: "Ce professeur existe déjà !",
status: 409
});
} else {
res.status(500).send({
message: "Une erreur s'est produite au niveau du serveur !",
status: 500
});
}
} else {
if (data.affectedRows) {
res.status(201).send({
message: `Le professeur ${name} a été ajouté !`,
status: 201
});
}
}
})
}; |
app.service('httpInterceptors', ['$timeout', '$rootScope', function($timeout, $rootScope) {
return {
request: function(config) {
log(config);
warn("Request Received : " + Date());
return config;
},
response: function(config) {
log(config);
warn("Response Received : " + Date());
if (config.status == 200) {
myToast.show();
$timeout(function() {
$rootScope.toastMessage = config.data.result || config.data.message;
}, 1);
}
return config;
},
requestError: function(config) {
log(config);
warn("Request Error : " + Date());
return config;
},
responseError: function(config) {
log(config);
warn("Response Error : " + Date());
// if (config.status == 404) {
// myToast.show();
// $timeout(function() {
// $rootScope.toastMessage = config.data.result || config.data.message;
// }, 1);
// } else if (config.status == 401) {
// myToast.show();
// $timeout(function() {
// $rootScope.toastMessage = config.data.result || config.data.message;
// }, 1);
// } else if (config.status == 501) {
// myToast.show();
// $timeout(function() {
// $rootScope.toastMessage = "Servers Not Available";
// }, 1);
// } else if (config.status == 500) {
// myToast.show();
// $timeout(function() {
// $rootScope.toastMessage = "Servers Not Available.Internal Error";
// }, 1);
// }
if (config.status == 500) {
myToast.show();
$timeout(function() {
$rootScope.toastMessage = "Servers Not Available.Internal Error";
}, 1);
}
return config;
}
}
}]); |
import { Component } from 'react';
import Link from 'next/link';
import Header from '../components/header';
import withEnvAndCookies from '../lib/withEnvAndCookies';
class HomePage extends Component {
render() {
return (
<main>
<Header />
<h3>Test: {process.env.SHOP_SLUG}</h3>
<section>
<p>
This is another page of the SSR example, you accessed it{' '}
<strong>{this.props.isServer ? 'server' : 'client'} side</strong>.
</p>
<p>You can reload to see how the page change.</p>
<Link href="/about">
<a>Go to About Me</a>
</Link>
</section>
<pre>{JSON.stringify(this.props, null, 2)}</pre>
<p>test browser: {process.browser ? 'ja' : 'nej'}</p>
</main>
);
}
}
export default withEnvAndCookies(HomePage);
|
// Copyright (C) 2018-Present Masato Nomiyama
import React from 'react'
import { withStyles } from '@material-ui/core/styles'
import Typography from '@material-ui/core/Typography'
import { theme, style } from '../theme'
const customStyle = theme => {
return {
...style,
body: {
margin: '0 0 0 16px',
},
year: {
fontFamily: [
'"Helvetica Neue"',
theme.typography.fontFamily,
].join(','),
},
emptyYear: {
fontFamily: [
'"Helvetica Neue"',
theme.typography.fontFamily,
].join(','),
color: '#FFFFFF',
}
}
}
const renderItem = (props, item) => {
return (
<div className={`${props.className}-item`}>
<Typography
variant='subheading'
className={
item.isEmptyTitle ? props.classes.emptyYear : props.classes.year
}
>
{item.title}
</Typography>
<Typography
variant='body2'
className={[
`${props.className}-item-body`,
props.classes.body,
].join(' ')}
>
{item.body}
</Typography>
</div>
)
}
const HomeBiography = props => {
return (
<div className={props.className}>
{renderItem(props, {
title: '2018.11',
body: 'Takram 参加',
})}
{renderItem(props, {
title: '2018.09',
body: '東京大学大学院 情報理工学系研究科 知能機械情報学専攻 修士号取得',
})}
{renderItem(props, {
title: '2017.04',
body: 'Takram インターン 参加',
})}
{renderItem(props, {
title: '2016.11',
body: '富士フイルム インフォマティクス研究所 インターン 参加',
})}
{renderItem(props, {
title: '2016.04',
body: '東京大学大学院 情報理工学系研究科 知能機械情報学専攻 入学',
})}
{renderItem(props, {
title: '2016.04',
body: '廣瀬・谷川・鳴海研究室 所属',
isEmptyTitle: true,
})}
{renderItem(props, {
title: '2016.03',
body: '東京大学 工学部 機械情報工学科 学士号取得',
})}
{renderItem(props, {
title: '2015.08',
body: 'Honda Research Institutes インターン 参加',
})}
{renderItem(props, {
title: '2015.04',
body: '廣瀬・谷川・鳴海研究室 所属',
})}
{renderItem(props, {
title: '2014.06',
body: '東京大学 工学部 海外ヒストリックラリー参戦プロジェクト 参加',
})}
{renderItem(props, {
title: '2014.04',
body: '東京大学 工学部 機械情報工学科 進学',
})}
{renderItem(props, {
title: '2012.09',
body: '東京大学×博報堂 brand design studio 参加',
})}
{renderItem(props, {
title: '2012.04',
body: '東京大学 教養学部 理科一類 入学',
})}
{renderItem(props, {
title: '2012.03',
body: '海城高等学校 卒業',
})}
{renderItem(props, {
title: '1993.04',
body: '埼玉県川口市生まれ',
})}
</div>
)
}
export default withStyles(customStyle)(HomeBiography)
|
import { put, takeLatest } from 'redux-saga/effects';
import axios from 'axios';
function* getGrowingRoom(action) {
try {
// get growing room data
let response = yield axios.get('api/process/growing_room');
console.log(`growing room `, response);
// set table to redux state
yield put({ type: 'SET_GROWING_ROOM', payload: response.data });
let types = yield axios.get('api/process/growing_room/types')
yield put({type: 'SET_GROWING_ROOM_TYPES', payload: types.data})
} catch (error) {
console.log('Error getting growing room data', error);
alert('Sorry error getting data.')
}
}
function* getGrowingRoomSaga() {
yield takeLatest('GET_GROWING_ROOM', getGrowingRoom);
}
export default getGrowingRoomSaga;
|
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var CategorySchema = new Schema({
title: { type: String, required: true, maxLength: 100 },
color: { type: String, default: "white" },
active: { type: Boolean, default: true, required: true },
});
module.exports = mongoose.model("Category", CategorySchema);
|
const redisClient = require('../redisClient');
function Users(){
this.client = redisClient.getRedis();
};
module.exports = new Users();
// Insert the redis online key
Users.prototype.upsert = function (connectionId,meta){
this.client.hset(
'online',
meta._id,
JSON.stringify({
connectionId,
meta,
when: Date.now()
}),
err =>{
if(err){
console.log(err);
}
}
)
};
// delete the redis online key
Users.prototype.remove = function(_id){
this.client.hdel(
'online',
_id,
err=>{
if(err)
{
console.log(err);
}
}
)
};
Users.prototype.list = function (callback){
let activeusers = []
this.client.hgetall(
'online',
function(err,users){
if(err)
{
console.log(err);
return callback([]);
}
for (let user in users){
activeusers.push(JSON.parse(users[user]));
}
return callback(activeusers);
}
)
}; |
test('test one', () => {
let text = 'testing';
expect(text).toBe('testing');
}); |
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import NewsArticle from './NewsArticle';
const Container = styled.div`
display: flex;
flex-wrap: wrap;
gap: 10px;
width: 100%;
justify-content: center;
align-items: center;
`;
const NewsContainer = ({ articles }) => (
<Container>
{articles.map((article) => (
<NewsArticle article={article} />
))}
</Container>
);
export default NewsContainer;
NewsContainer.propTypes = {
articles: PropTypes.arrayOf(PropTypes.shape()).isRequired,
};
|
const express = require("express");
const session = require('express-session');
const fs = require('fs');
const port = 3000;
const app = express();
let reviews = [];
app.set('views', './templates');
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(session({
secret: 'my-secret',
resave: true,
saveUninitialized: true,
cookie: {
httpOnly: false
}
}));
app.get('/', function (req, res) {
if (req.query.newReview) reviews.push(req.query.newReview);
res.render('index', {reviews});
});
app.listen(port, () => console.log(`The server is listening at http://localhost:${port}`));
|
class Contact{
constructor(){
}
}
class ContactSuccess{
constructor(){
this.bindAllButton();
}
bindAllButton(){
$("button#homepage-redirect").click(() => {
window.location.href = "/";
})
}
}
(() => {
switch (window.location.pathname.replaceAll("/", "")) {
case "kontakt":
let ct = new Contact();
break;
case "kontaktsuccess":
let cs = new ContactSuccess();
break;
default:
console.error("Error in contact.js.\nThe script does not know what document it is in")
break;
}
})() |
// pages/consultant_activity/lottery.js
Page({data: {}}) |
import { render, screen } from "@testing-library/react"
import Applicant from "./Applicant"
test("renders an applicant", () => {
render(
<Applicant
id="my-id"
name="my name"
description="my description"
thumb="/my/thumb/url"
/>
)
const nameElement = screen.getByText(/my name/i)
expect(nameElement).toBeInTheDocument()
expect(nameElement).toHaveClass("name")
const descriptionElement = screen.getByText(/my description/i)
expect(descriptionElement).toBeInTheDocument()
expect(descriptionElement).toHaveClass("description")
const thumbElement = screen.queryByAltText(/my name Thumb/i)
expect(thumbElement).toBeInTheDocument()
expect(thumbElement).toHaveClass("thumb")
})
|
import React, { useState, useEffect } from 'react';
import ProjectsList from './ProjectsList';
import SingleProject from './SingleProject';
import { makeStyles } from '@material-ui/core/styles';
import ProjectsForm from './ProjectsForm';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import Fab from '@material-ui/core/Fab';
import AddIcon from '@material-ui/icons/Add';
import Dialog from '@material-ui/core/Dialog';
import DialogContent from '@material-ui/core/DialogContent';
const useStyles = makeStyles(theme => ({
root: {
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-around',
backgroundColor: theme.palette.background.paper,
},
root2: {
flexGrow: 1,
},
gridList: {
width: 800,
},
contain: {
align: 'center',
},
paper: {
padding: theme.spacing(2),
textAlign: 'center',
color: theme.palette.text.secondary,
},
}));
const Projects = () => {
const classes = useStyles();
const [open, setOpen] = useState(false);
const [open2, setOpen2] = useState(false);
const [allProjects, setAllProjects] = useState([]);
const [singleProject, setSingleProject] = useState([]);
const [onDelete, setDelete] = useState(false);
const [getInfo, setGetInfo] = useState(false);
useEffect(() => {
fetch('https://homestead-studios.firebaseio.com/projects.json')
.then(response => response.json())
.then(responseData => {
const loadedProjects = [];
console.log('DATA FROM FIREBASE =====', responseData);
for (let key in responseData) {
loadedProjects.push({
id: key,
imgUrl: responseData[key].imgUrl,
col: responseData[key].col,
description: responseData[key].description,
});
}
setAllProjects(loadedProjects.reverse());
});
}, []);
const addProjectHandler = project => {
fetch('https://homestead-studios.firebaseio.com/projects.json', {
method: 'POST',
body: JSON.stringify(project),
headers: { 'Content-Type': 'application/json' },
})
.then(response => {
return response.json();
})
.then(responseData => {
setAllProjects(prevProjects => [
{ id: responseData.name, ...project },
...prevProjects,
]);
});
};
const removeProjectHandler = id => {
fetch(`https://homestead-studios.firebaseio.com/projects/${id}.json`, {
method: 'DELETE',
}).then(response => {
setAllProjects(prevProjects =>
prevProjects.filter(project => project.id !== id),
);
});
};
const closeDialog = () => {
setOpen(false);
};
const openDialog = () => {
setOpen2(true);
};
const selectProject = index => {
setSingleProject(index);
};
return (
<React.Fragment>
<div className={classes.root}>
<Grid item xs={11}>
<ProjectsList
projects={allProjects}
onRemoveItem={removeProjectHandler}
open2={openDialog}
selectProject={selectProject}
onDelete={onDelete}
getInfo={getInfo}
/>
</Grid>
<Grid item xs={1}>
<Paper className={classes.paper}>
<Fab
onClick={() => setOpen(true)}
color='secondary'
aria-label='add'
size='small'
>
<AddIcon />
</Fab>
</Paper>
<Paper className={classes.paper}>
<Fab
onClick={() => {
!onDelete ? setDelete(true) : setDelete(false);
setGetInfo(true);
}}
color='secondary'
aria-label='add'
size='small'
>
<i class='fas fa-minus'></i>
</Fab>
</Paper>
<Paper className={classes.paper}>
<Fab
onClick={() => {
!getInfo ? setGetInfo(true) : setGetInfo(false);
setDelete(false);
}}
color='secondary'
aria-label='add'
size='small'
>
<i class='fas fa-info'></i>
</Fab>
</Paper>
</Grid>
</div>
<Dialog
style={{ zIndex: 302 }}
open={open}
onClose={() => setOpen(false)}
align='center'
PaperProps={{
style: {
marginTop: '4em',
paddingTop: '2em',
paddingBottom: '2em',
},
}}
>
<DialogContent>
<ProjectsForm
onAddProject={addProjectHandler}
setOpen={closeDialog}
/>
</DialogContent>
</Dialog>
<Dialog
style={{ zIndex: 302 }}
open={open2}
onClose={() => setOpen2(false)}
align='center'
PaperProps={{
style: {
maxHeight: '100%',
maxWidth: '100%',
},
}}
>
<DialogContent>
<SingleProject projects={allProjects} singleProject={singleProject} />
</DialogContent>
</Dialog>
</React.Fragment>
);
};
export default Projects;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.