text
stringlengths 7
3.69M
|
|---|
import React from 'react'
import PropTypes from 'prop-types'
import {connect} from 'react-redux'
const TopbarVilla = ()=> {
return(
<div className="villa-header">
<p>Header</p>
</div>
)
}
TopbarVilla.propTypes = {
}
const mapStateToProps = state=> ({
})
export default connect(mapStateToProps, {})(React.memo(TopbarVilla))
|
import React, { Component } from 'react';
import Row from './Row'
import Wrapper from './Wrapper'
class DefectTable extends Component {
constructor(props){
super(props);
this.state={
data:[],
}
this.getRows = this.getRows.bind(this);
this.toggleStatus = this.toggleStatus.bind(this);
}
componentWillMount(){
console.log("will mount")
}
componentDidMount(){
console.log("did mount")
let storeData = JSON.parse(localStorage.getItem("defects"));
this.setState({
data:storeData
});
}
toggleStatus(ind){
let newArr = this.state.data.map((element,index)=>{
if(index === ind){
return { ...element,status:(element.status === 'Open' ? 'Closed': 'Open')}
}
else{
return element
}
})
this.setState({
data: newArr
})
}
getRows(){
return this.state.data.map((obj,index)=>{
return <Row key={index} {...obj} toggleStatus={this.toggleStatus} index={index}/>
})
}
render() {
console.log("in render cou t");
return (
<Wrapper>
<p>{this.props.defectCount}</p>
<table>
<tbody>
<tr>
<td>Category</td>
<td>Description</td>
<td>Priority</td>
<td>Status</td>
<td>Change Status</td>
</tr>
{this.getRows()}
</tbody>
</table>
</Wrapper>
);
}
}
export default DefectTable;
|
var google = require('googleapis');
var auth = require('./googleauth');
module.exports = {
getClient: auth(google.calendar, 'v3', ['https://www.googleapis.com/auth/calendar',
'https://mail.google.com/',
'https://www.googleapis.com/auth/gmail.modify',
'https://www.googleapis.com/auth/gmail.compose',
'https://www.googleapis.com/auth/gmail.send'], Wrapper)
};
function Wrapper(client) {
this.client = client;
};
Wrapper.prototype.quickAdd = function(id, text, cb) {
this.client.events.quickAdd({
calendarId: id,
text: text
}, cb);
};
//Wrapper.prototype.getItems = function(id, query, min, max, cb) {
Wrapper.prototype.getItems = function(id, min, max, cb) {
this.client.events.list({
calendarId: id,
//q: "aaa",
timeMin: min,
timeMax: max,
//maxResults : 7
orderBy : "startTime",
singleEvents : true
}, cb);
};
|
$(function () {
initPage(0, 10);
$('.finish').bind('click', function () {
// var result = $('#deal').find('select[name=result]').val();
// var resultDeal = $('#deal').find('select[name=resultDeal]').val();
// var description = $('#deal').find('select[name=description]').val();
var id = $('#finish').find('input[name=id]').val();
// var companyName = $('#deal').find('input[name=companyName]').val();
// var people = $('#deal').find('input[name=people]').val();
// var companyRegisterId = $('#deal').find('input[name=companyRegisterId]').val();
// var department = $('#deal').find('input[name=department]').val();
// var doubleRandomResult = {
// id: id,
// companyName: companyName,
// people: people,
// companyRegisterId: companyRegisterId,
// department: department,
// description: description,
// resultDeal: resultDeal,
// checkDate: '2017-01-18'
// };
var doubleRandomResult;
$.ajax({
url: window.apiPoint + 'double-random-results/' + id,
type: 'GET',
async: false,
dataType: 'json',
success: function (data) {
if (data) {
doubleRandomResult = data;
}
},
});
doubleRandomResult['resultStatus'] = $('#finish').find('select[name=resultStatus]').val();
doubleRandomResult['finishDate'] = '2017-01-18';
$.ajax({
url: window.apiPoint + 'double-random-results',
type: 'PUT',
// 序列化Json对象为Json字符串
data: JSON.stringify(doubleRandomResult),
async: true,
dataType: 'json',
success: function (data) {
if (data) {
location.href = "/app/task/finishedList.html"
}
},
});
});
});
function initPage(page, size) {
var url = window.apiPoint + 'double-random-results/login/unfinish';
console.log(url);
var dataQuery = {
page: page,
size: size,
check: 'checked',
resultDeal: '2'
};
$.ajax({
url: url,
type: 'GET',
// GET请求传递data
data: dataQuery,
async: true,
dataType: 'json',
success: function (data) {
if (data) {
console.log(data);
var result = {};
result['doubleRandomResults'] = data;
console.log(data);
var tpl = [
'{@each doubleRandomResults as it,index}',
'<tr>',
'<td>${it.id}</td>',
'<td>${it.companyName}</td>',
'<td>${it.department}</td>',
'<td>${it.people}</td>',
'<td>${it.doubleRandom.doubleRandomTaskContent}</td>', ,
'<td>${it.doubleRandom.doubleRandomDate}</td>',
'<td>{@if it.result != null}${it.result}{@/if}</td>',
'<td>{@if it.resultStatus != null}{@else if it.result == 2}责令整改{@/if}</td>',
'<td><span class="label label-danger">{@if it.resultDeadline != null}${it.resultDeadline}{@/if}</span></td>',
'<td>',
'<a href="javascript:;" onclick="finish(${it.id})" data-toggle="modal" data-target="#myModal0">整改结果</a>',
'</td>',
'</tr>',
'{@/each}'].join('');
var html = juicer(tpl, result);
$('#tContent').html(html);
}
},
});
};
function finish(id) {
$('#finish').find('input[name=id]').val(id);
}
|
import React, { Component } from 'react'
function Erreur() {
return (
<>
<h1>Erreur 404 : </h1>
<p>L'url n'est pas valide</p>
</>
)
}
export default Erreur;
|
/* global $,window, jQuery, dkBreve, KbOSD */
window.dkBreve = (function (window, $, undefined) {
'use strict';
var DkBreve = function () {
};
DkBreve.prototype = {
/**
* Get current page in ocr pane
*/
getOcrCurrentPage: function () {
var ocrElem = $('.ocr'),
ocrScrollTop = ocrElem[0].scrollTop,
ocrScrollTopOffset = ocrScrollTop + 9, // Magic number 9 is 1 px less than the margin added when setting pages
ocrBreaks = $('.pageBreak', ocrElem);
// TODO: Optimization: Split on length so letters with more than 10 pages uses a binary search approach to figure out the correct page!
var i = 0;
if ($(ocrBreaks[0]).position().top + ocrScrollTopOffset > ocrScrollTop) {
return 1; // user are before the very first pageBreak => page 1
}
while (i < ocrBreaks.length && $(ocrBreaks[i]).position().top + ocrScrollTopOffset <= ocrScrollTop) {
i++;
}
return i + 1;
},
/**
* Scroll to a (one-based) numbered page in the ocr
* @param page
*/
gotoOcrPage: function (page, skipAnimation) {
var that = this,
ocrElem = $('.ocr').first(),
pageCount = $('.pageBreak', ocrElem).length + 1;
if (page < 1 || page > pageCount) {
throw('DkBreve.gotoOcrPage: page "' + page + '" out of bounds.');
}
if (that.animInProgress) {
ocrElem.stop(true, true);
}
if (skipAnimation) {
that.animInProgress = true;
if (page === 1) {
ocrElem[0].scrollTop = 0;
} else {
ocrElem[0].scrollTop = $($('.ocr .pageBreak')[page - 2]).position().top + $('.ocr')[0].scrollTop + 10;
}
setTimeout(function () {
that.animInProgress = false;
}, 0);
} else {
that.animInProgress = true;
if (page === 1) {
ocrElem.animate({scrollTop: 0}, 500, 'swing', function () {
that.animInProgress = false;
}); // scroll to top of text
} else {
ocrElem.animate({
scrollTop: $($('.ocr .pageBreak')[page - 2]).position().top + $('.ocr')[0].scrollTop + 10
}, 500, 'swing', function () {
that.animInProgress = false;
});
}
}
},
onOcrScroll: function () {
var that = dkBreve;
if (!that.animInProgress) {
// this is a genuine scroll event, not something that origins from a kbOSD event
var currentOcrPage = that.getOcrCurrentPage(),
kbosd = KbOSD.prototype.instances[0]; // The dkBreve object should have a kbosd property set to the KbOSD it uses!
if (kbosd.getCurrentPage() !== currentOcrPage) {
that.scrollingInProgress = true;
kbosd.setCurrentPage(currentOcrPage, function () {
that.scrollingInProgress = false; // This is ALMOST enough ... but it
});
}
}
},
onFullScreen: function (e) {
var that = dkBreve, // TODO: This is so cheating, but I only get the contentElement as scope. :-/
fullScreen = e.detail.fullScreen;
that.fullScreen = fullScreen;
if (!fullScreen) {
// just returned from fullscreen - scroll ocr pane accordingly
that.gotoOcrPage(that.kbosd.getCurrentPage(), true);
}
},
onDocumentReady: function () {
var headerFooterHeight = dkBreve.getFooterAndHeaderHeight(),
windowHeight = $(window).innerHeight(),
contentHeight = windowHeight - headerFooterHeight - 10;
dkBreve.setContentHeight(contentHeight);
// Collapse/Expand metadata column
$('.collapseMetadata').click(function (e) {
$(this).closest('.contentContainer').toggleClass('nometa');
});
// set up handler for ocr fullscreen
$('#ocrFullscreenButton').click(function (e) {
// Copy/Pasted from http://stackoverflow.com/questions/7130397/how-do-i-make-a-div-full-screen /HAFE
// if already full screen; exit
// else go fullscreen
if (
document.fullscreenElement ||
document.webkitFullscreenElement ||
document.mozFullScreenElement ||
document.msFullscreenElement
) {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
} else {
var element = $('.ocr').get(0);
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
}
}
});
$('.escFullScreenButton').click(dkBreve.closeFullScreen);
$(window).resize(function () {
dkBreve.onWindowResize.call(dkBreve);
});
},
onKbOSDReady: function (kbosd) {
var that = this;
that.kbosd = kbosd;
if (kbosd.pageCount > 1) { // if there isn't more than one page, no synchronization between the panes are needed.
//currentOcrpage is more than 1 if readed by the URL
var currentOcrPage = that.getOcrCurrentPage();
if (currentOcrPage > 1) {
kbosd = KbOSD.prototype.instances[0]; // The dkBreve object should have a kbosd property set to the KbOSD it uses!
if (kbosd.getCurrentPage() !== currentOcrPage) {
that.scrollingInProgress = true;
kbosd.setCurrentPage(currentOcrPage, function () {
that.scrollingInProgress = false; // This is ALMOST enough ... but it
});
}
} else { // initlaize from osd gragon page instead
that.gotoOcrPage(kbosd.getCurrentPage(), true);
}
$(kbosd.contentElem).on('pagechange', function (e) {
if (!that.scrollingInProgress && !that.fullScreen) {
that.gotoOcrPage(e.detail.page);
}
});
$(kbosd.contentElem).on('fullScreen', that.onFullScreen);
$('.ocr').scroll(this.onOcrScroll);
}
},
onWindowResize: function () {
this.setContentHeight($(window).innerHeight() - this.getFooterAndHeaderHeight());
},
closeFullScreen: function () {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
},
getFooterAndHeaderHeight: function () {
return $('.page_links').outerHeight() +
$('.workNavBar').outerHeight() +
$('h1[itemprop=name]').outerHeight() +
$('.search-widgets').outerHeight() + // FIXME: According to me this shouldn't be necessary, since these are pulled right and thereby out of the flow, but I can observe that the end result lacks approx 32 px.? /HAFE
$('#user-util-collapse').outerHeight() +
$('footer.pageFooter').outerHeight();
},
setContentHeight: function (height) {
if (height > 200) {
$('.contentContainer').css('maxHeight', height);
$('.textAndFacsimileContainer').css('minHeight', height);
}
}
};
return new DkBreve();
})(window, jQuery);
$(document).on('kbosdready', function (e) {
dkBreve.onKbOSDReady(e.detail.kbosd);
});
|
import moment from 'moment/moment';
const _ = require('lodash');
const aws = require('aws-sdk');
const Promise = require('bluebird');
aws.config.setPromisesDependency(Promise);
export default class DynamoHelper {
constructor() {
this.dynamo = new aws.DynamoDB({
region: process.env.REGION,
endpoint: process.env.DYNAMO_ENDPOINT,
});
}
getDynamo() {
return this.dynamo;
}
createTable(name, params) {
return this.dynamo.deleteTable({ TableName: name }).promise().catch(() => null)
.then(() => this.dynamo.createTable(params).promise().catch(() => null));
}
createTableProjects() {
return this.createTable(process.env.DYNAMO_TABLE_PROJECTS, {
TableName: process.env.DYNAMO_TABLE_PROJECTS,
AttributeDefinitions: [
{ AttributeName: 'Project', AttributeType: 'N' },
{ AttributeName: 'Pid', AttributeType: 'S' },
],
KeySchema: [
{ AttributeName: 'Project', KeyType: 'HASH' },
{ AttributeName: 'Pid', KeyType: 'RANGE' },
],
ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 },
});
}
createTableUsers() {
return this.createTable(process.env.DYNAMO_TABLE_USERS, {
TableName: process.env.DYNAMO_TABLE_USERS,
AttributeDefinitions: [
{ AttributeName: 'Project', AttributeType: 'N' },
{ AttributeName: 'Login', AttributeType: 'S' },
],
KeySchema: [
{ AttributeName: 'Project', KeyType: 'HASH' },
{ AttributeName: 'Login', KeyType: 'RANGE' },
],
ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 },
});
}
createTableKbcProjectsUsers() {
return this.createTable(process.env.DYNAMO_TABLE_KBC_PROJECTS_USERS, {
TableName: process.env.DYNAMO_TABLE_KBC_PROJECTS_USERS,
AttributeDefinitions: [
{ AttributeName: 'User', AttributeType: 'N' },
{ AttributeName: 'Pid', AttributeType: 'S' },
],
KeySchema: [
{ AttributeName: 'User', KeyType: 'HASH' },
{ AttributeName: 'Pid', KeyType: 'RANGE' },
],
ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 },
});
}
putProject(projectId, pid, token, expiresOn = null) {
const params = {
Item: {
Project: { N: `${projectId}` },
Pid: { S: pid },
Token: { S: token },
CreatedOn: { S: moment().toJSON() },
CreatedBy: { S: 'me' },
CreatedById: { N: '1' },
},
TableName: process.env.DYNAMO_TABLE_PROJECTS,
};
if (expiresOn) {
params.Item.ExpiresOn = { S: expiresOn };
}
return this.dynamo.putItem(params).promise();
}
putUser(projectId, login, uid) {
return this.dynamo.putItem({
Item: {
Project: { N: `${projectId}` },
Login: { S: login },
Uid: { S: uid },
CreatedOn: { S: moment().toJSON() },
CreatedBy: { S: 'me' },
CreatedById: { N: '1' },
},
TableName: process.env.DYNAMO_TABLE_USERS,
}).promise();
}
putKbcProjectUser(userId, pid) {
return this.dynamo.putItem({
Item: {
User: { N: _.toString(userId) },
Pid: { S: pid },
CreatedOn: { S: moment().toJSON() },
},
TableName: process.env.DYNAMO_TABLE_KBC_PROJECTS_USERS,
}).promise();
}
}
|
angular.module('lisaApp')
.controller('foodReplacementCtrl', ['$scope', '$stateParams', '$rootScope', 'AlimentoService',
function ($scope, $stateParams, $rootScope, AlimentoService) {
$scope.$on('$ionicView.beforeEnter', function (event, viewData) {
viewData.enableBack = true;
});
var sc = $scope;
var rs = $rootScope;
var id = $stateParams.id;
console.log('Buscando alimento tabela de substituicao (id = ' + id + ').');
sc.buscaAlimento = function(){
//AlimentoService.findOne(id)
// .then(function(res){
// return res;
// $scope.$broadcast('scroll.refreshComplete');
//})
return rs.alimentos[id-1];
}
sc.loadGroupAliments = function(){
sc.loading = true;
AlimentoService.findByGroup(sc.alimento.grupo, sc.alimento.id).then(function(res){
sc.alimentosSub = res;
sc.loading = false;
rs.$broadcast('scroll.refreshComplete');
})
}
sc.alimento = sc.buscaAlimento(id);
sc.loadGroupAliments();
}])
|
import {createStore,combineReducers,applyMiddleware} from 'redux'
import {createForms} from 'react-redux-form'
import {com} from './comments'
import {Dish} from './dish'
import {lead} from './lead'
import {prom} from './prom'
import thunk from 'redux-thunk'
import logger from 'redux-logger'
import { Initialfeedback } from './forms'
export const ConfigureStore=()=>{
const store=createStore(//takes enhancer as its seond paramenter
combineReducers({
dis:Dish,com:com,lead:lead,prom:prom,
...createForms({
feedback:Initialfeedback
})
}),applyMiddleware(thunk,logger)
)
return store
}
|
import CartContainer from './CartContainer'
import reducer from './reducer'
export {
CartContainer,
reducer
}
|
$('button').on('click', function () {
$.getJSON('https://akademia108.pl/kurs-front-end/ajax/1-pobierz-dane-programisty.php', function (data) {
var divNew = document.createElement('div');
$(divNew).attr('id', 'dane-programisty');
$('body').append(divNew);
$('#dane-programisty').html(data.imie + ' ' + data.nazwisko + ' ' + data.zawod + ' ' + data.firma);
});
});
|
import "./WorkSectionOne.css";
function WorkSectionOne() {
return(
<>
<section className="Work-SectionOne">
<div className="Work-SectionOne-content-wrapper">
<div className="Work-SectionOne-content-Fitter">
<div className="Work-SectionOne-content-Fitter-Titel">
<h4>Work</h4>
</div>
<div className="Work-SectionOne-content-wrapper-horizontalDivider">
<div>
</div>
</div>
<div className="Work-SectionOne-content-Fitter-Content">
<h3>None.</h3>
<h3>I have just started my journey as a web developer. So if you want to be my first client just hit that contact button.</h3>
<h3>Maybe your site will be proudly represented here soon.</h3>
</div>
</div>
</div>
<div class="ripple-background">
<div class="circle xxlarge shade1"></div>
<div class="circle xlarge shade2"></div>
<div class="circle large shade3"></div>
<div class="circle mediun shade4"></div>
<div class="circle small shade5"></div>
</div>
</section>
</>
);
}
export default WorkSectionOne;
|
const tableRanking = document.getElementById("tableRanking");
const tbody = document.getElementById("ranking");
const toggleSwitch = document.querySelector('.theme-switch input[type="checkbox"]');
const currentTheme = localStorage.getItem('theme') ? localStorage.getItem('theme') : null;
const emojis = [-30, -5, 3, 30];
if (currentTheme) {
document.documentElement.setAttribute('data-theme', currentTheme);
if (currentTheme === 'dark') {
toggleSwitch.checked = true;
}
}
function switchTheme(e) {
if (e.target.checked) {
document.documentElement.setAttribute('data-theme', 'dark');
localStorage.setItem('theme', 'dark');
}
else {
document.documentElement.setAttribute('data-theme', 'light');
localStorage.setItem('theme', 'light');
}
}
toggleSwitch.addEventListener('change', switchTheme, false);
function checkImage(imageSrc, good, bad) {
var img = new Image();
img.onload = good;
img.onerror = bad;
img.src = imageSrc;
}
function showError(type, message) {
let error = document.getElementById("error");
let errorColor = '';
switch (type) {
case 'maintenance':
errorColor = '#f0ad4e';
break;
case 'critical':
errorColor = '#ff4d56';
break;
default:
errorColor = '#000000';
break;
}
if (error) {
error.innerHTML = message;
error.parentElement.style.backgroundColor = errorColor;
} else {
let divErrorMessage = document.createElement("div");
let errorMessage = document.createElement("a");
divErrorMessage.style.width = "100%";
divErrorMessage.style.backgroundColor = errorColor;
divErrorMessage.style.borderRadius = "5px 5px 0 0";
divErrorMessage.style.minWidth = "407px";
errorMessage.id = "error";
errorMessage.innerHTML = message;
divErrorMessage.append(errorMessage);
tableRanking.parentNode.insertBefore(divErrorMessage, tableRanking.previousSibling);
}
}
fetch('https://raw.githubusercontent.com/caferanking/caferanking.github.io/master/ranking.json')
.then(async (data) => {
data = await data.json();
document.getElementById("lastUpdate").innerHTML = 'Última atualização: ' + new Date(data.lastUpdate * 1000).toDate('dd/mm/yyyy _ hh:ii').replace('_', 'às')
if (data.warning)
showError("maintenance", data.warning);
const ranking = Object.entries(data.ranking).sort((a, b) => b[1].messages - a[1].messages).slice(0, 100);
for (const [i, [name, content]] of ranking.entries()) {
if (content.authorId) {
let tr = document.createElement("tr");
let tdPos = document.createElement("td");
let tdName = document.createElement("td");
let tdMessages = document.createElement("td");
let tdAverage = document.createElement("td");
let tdLikes = document.createElement("td");
let tdUsername = document.createElement("a");
tdUsername.className = "user-name";
tdUsername.innerHTML = name;
tdUsername.href = "https://atelier801.com/profile?pr=" + name.replace('#', '%23')
tdUsername.target = "_blank"
let tdPhoto = document.createElement("img");
tdPhoto.src = "http://avatars.atelier801.com/0/0.jpg"
tdPhoto.className = "user-photo";
let imageLikes = document.createElement("img");
for (let index = 0; index < emojis.length; index++) {
emoji = emojis[index];
if (emoji > 0)
emoji = emoji - 1;
if (content.likes <= emoji) {
imageLikes.src = "./img/emojis/"+(index + 1)+".png";
break;
} else if (index == emojis.length - 1) {
imageLikes.src = "./img/emojis/"+(emojis.length + 1)+".png";
}
}
imageLikes.title = content.likes
imageLikes.style.width = "25px";
imageLikes.id = "reputation";
let imageURL = "http://avatars.atelier801.com/" + content.authorId % 10000 + '/' + content.authorId + ".jpg";
checkImage(imageURL, function(){tdPhoto.src = imageURL});
tdPos.append((i + 1).toString());
tdName.append(tdUsername);
tdName.append(tdPhoto)
tdMessages.append(content.messages.toString());
tdLikes.append(imageLikes);
//tdLikes.innerHTML = '<font color="' + (content.likes ? content.likes > 0 ? '#32a852' : '#ff0000' : '#5F5F5F') + '">' + tdLikes.innerHTML + '</font>'
tdAverage.append(content.average.toString());
tr.append(tdPos, tdName, tdMessages, tdLikes);
tbody.append(tr);
}
}
}).catch(err => {
showError("critical", "Oops, parece que algo deu errado! Erro: " + err.message);
});
function myFunction() {
const filter = document.querySelector('#myInput').value.toUpperCase();
const trs = document.querySelectorAll('#tableRanking tr:not(#tablerow)');
trs.forEach(tr => tr.style.display = [...tr.children].find(td => td.innerHTML.toUpperCase().includes(filter)) ? '' : 'none');
}
|
const request = require('request');
const base = 'http://localhost:3000';
const server = require('../../src/server');
describe('routes : index', () => {
describe('GET /', () => {
it('should render a landing page containing "News Your Own Adventure"', (done) => {
request.get(base, (err, res, body) => {
expect(err).toBeNull();
expect(res.statusCode).toBe(200);
done();
});
});
it('should display navigation bar', (done) => {
request.get(base, (err, res, body) => {
expect(body).toContain('Sign In', 'Sign Up');
done();
});
});
it('should include head from partial', (done) => {
request.get(base, (err, res, body) => {
expect(body).toContain('<link rel="stylesheet"');
done();
});
});
it('should display recent news', (done) => {
request.get(base, (err, res, body) => {
expect(body).toContain('class="main-story"');
expect(body).toContain('class="story-card"');
done();
});
});
});
});
|
var express = require('express');
var app = express();
var router = express.Router();
var mongoose = require('mongoose');
var db = 'mongodb://ayondot:mathematics223@ds127878.mlab.com:27878/rocky-bayou-89314';
mongoose.connect(db);
var linkSchema = mongoose.Schema({
link: {
type: String,
unique: true
}
});
var Link = mongoose.model('Link', linkSchema);
app.use('/new', router);
app.get('/', function(req, res){
res.send('Welcome!');
});
app.get('/links', function(req, res){
Link.find({ }, function(err, data){
if(err) return console.error(err);
res.end(JSON.stringify(data, null, '\t'));
});
});
app.get('/:id', function(req, res){
Link.findOne({_id: req.params.id}, function(err, data){
if(err) return console.error(err);
console.log(req.params.id, data);
res.redirect(data.link);
});
});
router.get('/*', function(req, res){
if(req.params['0'].split(':').length === 1)
req.params['0'] = 'http://' + req.params['0']
console.log(req.params['0']);
var newlink = new Link({ link: req.params['0']});
newlink.save(function(err, link){
if(err) return console.error(err);
var response ={
"original_url": req.params['0'],
"short_url": req.headers.host + '/' + link._id
}
res.json(response);
});
});
var port = process.env.PORT || 8080;
app.listen(port, function(){
console.log('app listening on port ' + port);
});
|
function mathIt()
{
var num1 = parseInt(document.getElementById("txtNum1").value)
var num2 = parseInt(document.getElementById("txtNum2").value)
var sum = num1 + num2
var diff = num1- num2
var prod = num1 * num2
var quo = num1 / num2
var buildStringArr = ["{num1} + {num2} = {sum}",
"{num1} - {num2} = {diff}",
"{num1} * {num2} = {prod}",
"{num1} / {num2} = {quo}"]
var output = buildStringArr.join("<br>")
output = output.replace(/{num1}/g, num1)
output = output.replace(/{num2}/g, num2)
output = output.replace("{sum}", sum)
output = output.replace("{diff}", diff)
output = output.replace("{prod}", prod)
output = output.replace("{quo}", quo)
document.getElementById("txtOutput").innerHTML = output
}
|
import {TargetSummary} from '../models';
import APIError from '../lib/APIError';
import httpStatus from 'http-status';
import Constants from '../lib/constants';
/**
* Load targetSummary and append to req.
*/
function load(req, res, next, id) {
TargetSummary.get(id)
.then((targetSummary) => {
req.targetSummary = targetSummary;
return next();
})
.catch(e => next(e));
}
/**
* Get targetSummary
* @returns {TargetSummary}
*/
function get(req, res) {
return req.targetSummary;
}
/**
* Checks if user exists with same email as targetSummary. If not, it creates a new User with the email provided and a default password. Then creates the TargetSummary to reside in the new user
* @returns {TargetSummary}
*/
function create(req, res, next) {
return new TargetSummary(req.body)
.save()
.then(savedTargetSummary => savedTargetSummary)
.catch(e => next(e));
}
/**
* Update existing targetSummary
* @returns {TargetSummary}
*/
function update(req, res, next) {
const targetSummary = req.targetSummary;
for(let prop in req.body){
targetSummary[prop] = req.body[prop];
}
return targetSummary.save()
.then(savedTargetSummary => savedTargetSummary)
.catch(e => next(e));
}
/**
* Get targetSummary list.
* @property {number} req.query.skip - Number of targetSummarys to be skipped.
* @property {number} req.query.limit - Limit number of targetSummarys to be returned.
* @returns {TargetSummary[]}
*/
function list(req, res, next) {
const { limit = 20, skip = 0 } = req.query;
delete req.query.limit;
delete req.query.skip;
let queryObj = buildQuery(req);
return TargetSummary.find(queryObj.length > 0 ? {$or: queryObj} : {})
.sort({ createdAt: -1 })
.skip(skip)
.limit(limit)
.then(targetSummarys => targetSummarys)
.catch(e => next(e));
}
function buildQuery(req){
if (Object.keys(req.query).length === 0) return [];
var array = [];
for (var key in req.query) {
// if (_.indexOf(dateKeys, key) > -1) {
// if (key == 'startDate') {
// array.push({ createdAt: { $gt: req.query[key] } });
// }
// if (key == 'endDate') array.push({ createdAt: { $lt: req.query[key] } });
// } else {
var obj = {};
obj[key] = req.query[key];
array.push(obj);
// }
}
return array;
}
/**
* Delete targetSummary.
* @returns {TargetSummary}
*/
function remove(req, res, next) {
const targetSummary = req.targetSummary;
return targetSummary.remove()
.then(deletedTargetSummary => deletedTargetSummary)
.catch(e => next(e));
}
export default { load, get, create, update, list, remove };
|
import React from 'react'
export const ProgressBar = ({progress}) => {
return (
<div class=" w-3/5 pt-1 ">
<div class="overflow-hidden h-3 mb-4 text-xs flex rounded bg-amber-100">
<div style={{ width: `${progress}%` }} class="bg-gradient-to-r shadow-none flex flex-col text-center whitespace-nowrap text-white justify-center bg-amber-400"></div>
</div>
</div>
)
}
|
import FormInput from './FormInput.component.jsx';
export default FormInput;
|
const Router = require('koa-router');
const mongoose = require('mongoose');
const ChatModel = require('../../models/chat');
const UserModel = require('../../models/user');
const MessageModel = require('../../models/message');
const router = new Router();
router.post('/api/chat/chat-rooms', async ctx => {
await ChatModel
.find({ _id: { $in: (ctx.state.user.info.chats || []).map(mongoose.Types.ObjectId) } })
.then(chats => {
ctx.body = chats;
})
.catch(err => {
console.log(err.statusCode, err.code);
ctx.throw(err.code, err.message);
})
});
router.post('/api/chat/add-user', async ctx => {
const chat = await ChatModel.findByIdAndUpdate(ctx.request.body.chatId, { $push: { users: ctx.request.body.userId} });
const user = await UserModel.findByIdAndUpdate(ctx.request.body.userId, { $push: { ['info.chats']: ctx.request.body.chatId} });
ctx.body = chat;
});
router.post('/api/chat/conversation', async ctx => {
await ChatModel
.findOne({private: true, users: { $all: [ctx.state.userId, ctx.request.body.interlocutorId] }})
.then(chat => {
console.log([ctx.state.userId, ctx.request.body.interlocutorId])
ctx.body = chat;
})
.catch(err => {
console.error(err)
ctx.throw(404, "Cannot find chat room!");
})
});
router.post('/api/chat/create', async ctx => {
const chat = new ChatModel({
name: ctx.request.body.name || 'chat #' + Date.now(),
private: ctx.request.body.private || true,
users: [ ctx.state.userId, ctx.request.body.interlocutorId ]
});
let user;
try {
await chat.save();
user = await UserModel.findByIdAndUpdate(ctx.state.userId, { $push: { ['info.chats']: chat._id } });
} catch (e) {
console.log(e);
ctx.throw(403, "Cannot create chat!");
} finally {
ctx.body = chat;
}
});
router.post('/api/chat/message', async ctx => {
let conversation;
if (!ctx.request.body.chatId && !ctx.request.body.interlocutorId) {
ctx.throw(401, "No message data found!");
}
try {
const chat = await ChatModel.findById(ctx.request.body.chatId);
if (!chat || chat == {}) {
conversation = await ChatModel.findOne({private: true, users: {$all: [ctx.state.userId, ctx.request.body.interlocutorId]}});
} else {
conversation = chat;
}
} catch (e) {
ctx.throw(e);
}
if (!conversation) {
const chat = new ChatModel({
name: 'conversation',
private: true,
users: [ ctx.state.userId, ctx.request.body.interlocutorId ]
});
const message = new MessageModel({
author: ctx.state.userId,
chat: chat._id,
text: ctx.request.body.message
});
try {
await chat.save();
await message.save();
await ChatModel.updateOne({_id: chat._id}, {$push: {messages: message._id}});
await UserModel.updateMany({
_id: {
$in: ([ctx.state.userId, ctx.request.body.interlocutorId]).map(mongoose.Types.ObjectId)
}
}, {
$push: { ['info.chats']: chat._id }
});
ctx.body = Object.assign({}, {
author: await UserModel.findById(message.author),
chat: message.author,
text: message.text,
createdAt: message.createdAt,
_id: message._id
});
} catch (e) {
console.log(e);
ctx.throw(403, "Cannot create message!");
}
} else {
try {
const message = new MessageModel({
author: ctx.state.userId,
chat: conversation._id,
text: ctx.request.body.message
});
await message.save();
await conversation.updateOne({$push: {messages: message._id}});
ctx.body = Object.assign({}, {
author: await UserModel.findById(message.author),
chat: message.author,
text: message.text,
createdAt: message.createdAt,
_id: message._id
});
} catch (e) {
console.log(e)
ctx.throw(403, "Cannot create message!");
}
}
});
router.post('/api/chat/messages', async ctx => {
try {
const chat = await ChatModel.findById(ctx.request.body.chatId);
const users = await UserModel.find({ _id: { $in: chat.users } });
let messages = await MessageModel.find({ _id: { $in: chat.messages } });
messages = messages.map(message => {
return Object.assign({}, {
author: users.find(user => user._id.toString() == message.author.toString()),
chat: chat,
text: message.text,
createdAt: message.createdAt,
_id: message._id
});
});
ctx.body = messages;
} catch (e) {
console.log(e);
ctx.throw(403, "Cannot find messages!");
}
});
router.post('/api/chat/discussion', async ctx => {
const chat = await ChatModel.findById(ctx.request.body.chatId);
ctx.body = chat;
});
module.exports = router;
|
import React from 'react';
import PropTypes from 'prop-types';
const ACTIVE_STYLE = {
color: '#5380F7'
};
function DropdownItem({
isActive,
value,
onSelect
}) {
const handleClick = event => {
onSelect(value);
event.preventDefault();
};
return (
<li style={Object.assign({}, isActive && ACTIVE_STYLE)}>
<a
href="#"
onClick={handleClick}
>
{value}
</a>
</li>
);
}
DropdownItem.propTypes = {
isActive: PropTypes.bool,
value: PropTypes.string.isRequired,
onSelect: PropTypes.func
};
DropdownItem.defaultProps = {
onSelect: () => null
};
export default DropdownItem;
|
import React from 'react';
import { createGlobalStyle } from 'styled-components';
import { useAuthState } from 'react-firebase-hooks/auth';
import { Router, Link } from "@reach/router"
import { SignIn } from './components'
import { Story, Stories, Home, Scene, Character } from './Pages'
import { auth } from './firebase.setup'
const GlobalStyle = createGlobalStyle`
* {
box-sizing: border-box;
}
html, body {
padding: 0;
margin: 0;
background-color: whitesmoke;
}
.App {
width: 50%;
margin: auto;
@media screen and (max-width: 1000px) {
width: 100%;
}
}
`;
function App() {
const [user] = useAuthState(auth)
return (
<>
<GlobalStyle />
<div className="App">
{!user ? (
<SignIn />
) : (
<Router>
<Character path="/character" />
<Character path="/character/:id" />
<Story path="/story" />
<Story path="/story/:id" />
<Stories path="/stories" />
<Scene path="/scene" />
<Scene path="/scene/:id" />
<Home path="/" />
</Router>
)}
</div>
</>
);
}
export default App;
|
import styled from 'styled-components'
const TableCell = styled.div`
flex: ${({ size }) => size};
padding: 8px;
border: 1px solid black;
${({ heading }) => heading && `
font-size: 25px;
text-align: center;
`};
`;
export default TableCell
|
import { createScript } from '../../src/framework/script/script.js';
import { Color } from '../../src/core/math/color.js';
import { AnimComponent } from '../../src/framework/components/anim/component.js';
import { AnimationComponent } from '../../src/framework/components/animation/component.js';
import { Application } from '../../src/framework/application.js';
import { AudioListenerComponent } from '../../src/framework/components/audio-listener/component.js';
import { AudioSourceComponent } from '../../src/framework/components/audio-source/component.js';
import { ButtonComponent } from '../../src/framework/components/button/component.js';
import { CameraComponent } from '../../src/framework/components/camera/component.js';
import { CollisionComponent } from '../../src/framework/components/collision/component.js';
import { ElementComponent } from '../../src/framework/components/element/component.js';
import { Entity } from '../../src/framework/entity.js';
import { JointComponent } from '../../src/framework/components/joint/component.js';
import { LayoutChildComponent } from '../../src/framework/components/layout-child/component.js';
import { LayoutGroupComponent } from '../../src/framework/components/layout-group/component.js';
import { LightComponent } from '../../src/framework/components/light/component.js';
import { ModelComponent } from '../../src/framework/components/model/component.js';
import { ParticleSystemComponent } from '../../src/framework/components/particle-system/component.js';
import { RenderComponent } from '../../src/framework/components/render/component.js';
import { RigidBodyComponent } from '../../src/framework/components/rigid-body/component.js';
import { ScreenComponent } from '../../src/framework/components/screen/component.js';
import { ScriptComponent } from '../../src/framework/components/script/component.js';
import { ScrollbarComponent } from '../../src/framework/components/scrollbar/component.js';
import { ScrollViewComponent } from '../../src/framework/components/scroll-view/component.js';
import { SoundComponent } from '../../src/framework/components/sound/component.js';
import { SpriteComponent } from '../../src/framework/components/sprite/component.js';
import { ZoneComponent } from '../../src/framework/components/zone/component.js';
import { DummyComponentSystem } from './test-component/system.mjs';
import { HTMLCanvasElement } from '@playcanvas/canvas-mock';
import { expect } from 'chai';
describe('Entity', function () {
let app;
beforeEach(function () {
const canvas = new HTMLCanvasElement(500, 500);
app = new Application(canvas);
app.systems.add(new DummyComponentSystem(app));
});
afterEach(function () {
app.destroy();
});
const components = {
anim: AnimComponent,
animation: AnimationComponent,
audiolistener: AudioListenerComponent,
audiosource: AudioSourceComponent,
button: ButtonComponent,
camera: CameraComponent,
collision: CollisionComponent,
element: ElementComponent,
joint: JointComponent,
layoutchild: LayoutChildComponent,
layoutgroup: LayoutGroupComponent,
light: LightComponent,
model: ModelComponent,
particlesystem: ParticleSystemComponent,
render: RenderComponent,
rigidbody: RigidBodyComponent,
screen: ScreenComponent,
scrollview: ScrollViewComponent,
scrollbar: ScrollbarComponent,
script: ScriptComponent,
sound: SoundComponent,
sprite: SpriteComponent,
zone: ZoneComponent
};
describe('#constructor', function () {
it('supports zero arguments', function () {
const entity = new Entity();
expect(entity).to.be.an.instanceof(Entity);
expect(entity.name).to.equal('Untitled');
});
it('supports one argument', function () {
const entity = new Entity('Test');
expect(entity).to.be.an.instanceof(Entity);
expect(entity.name).to.equal('Test');
});
it('supports two arguments', function () {
const entity = new Entity('Test', app);
expect(entity).to.be.an.instanceof(Entity);
expect(entity.name).to.equal('Test');
});
});
describe('#addComponent', function () {
for (const name in components) {
it(`adds a ${name} component`, function () {
// Create an entity and verify that it does not already have the component
const entity = new Entity();
expect(entity[name]).to.be.undefined;
// Add the component
let component = entity.addComponent(name);
expect(component).to.be.an.instanceof(components[name]);
expect(component).to.equal(entity[name]);
expect(entity[name]).to.be.an.instanceof(components[name]);
// Try to add the component again
component = entity.addComponent(name);
expect(component).to.be.null;
expect(entity[name]).to.be.an.instanceof(components[name]);
// Remove the component and destroy the entity
entity.removeComponent(name);
expect(entity[name]).to.be.undefined;
entity.destroy();
});
}
});
const createSubtree = () => {
// Naming indicates path within the tree, with underscores separating levels.
const a = new Entity('a', app);
const a_a = new Entity('a_a', app);
const a_b = new Entity('a_b', app);
const a_a_a = new Entity('a_a_a', app);
const a_a_b = new Entity('a_a_b', app);
a.addChild(a_a);
a.addChild(a_b);
a_a.addChild(a_a_a);
a_a.addChild(a_a_b);
// Add some components for testing clone behaviour
a.addComponent('animation', { speed: 0.9, loop: true });
a.addComponent('camera', { nearClip: 2, farClip: 3 });
a_a.addComponent('rigidbody', { type: 'static' });
a_a.addComponent('collision', { type: 'sphere', radius: 4 });
a_a_b.addComponent('light', { type: 'point', color: Color.YELLOW, intensity: 0.5 });
a_a_b.addComponent('sound', { volume: 0.5, pitch: 0.75 });
return {
a: a,
a_a: a_a,
a_b: a_b,
a_a_a: a_a_a,
a_a_b: a_a_b
};
};
const cloneSubtree = (subtree) => {
const a = subtree.a.clone();
const a_a = a.children[0];
const a_b = a.children[1];
const a_a_a = a_a.children[0];
const a_a_b = a_a.children[1];
return {
a: a,
a_a: a_a,
a_b: a_b,
a_a_a: a_a_a,
a_a_b: a_a_b
};
};
describe('#clone', function () {
it('clones an entity', function () {
const entity = new Entity('Test');
for (const name in components) {
entity.addComponent(name);
}
const clone = entity.clone();
expect(clone).to.be.an.instanceof(Entity);
expect(clone.getGuid()).to.not.equal(entity.getGuid());
expect(clone.name).to.equal('Test');
for (const name in components) {
expect(clone[name]).to.be.an.instanceof(components[name]);
}
});
it('clones an entity hierarchy', function () {
const root = new Entity('Test');
const child = new Entity('Child');
root.addChild(child);
for (const name in components) {
root.addComponent(name);
child.addComponent(name);
}
const clone = root.clone();
expect(clone).to.be.an.instanceof(Entity);
expect(clone.getGuid()).to.not.equal(root.getGuid());
expect(clone.name).to.equal('Test');
for (const name in components) {
expect(clone[name]).to.be.an.instanceof(components[name]);
}
expect(clone.children.length).to.equal(root.children.length);
const cloneChild = clone.findByName('Child');
expect(cloneChild.getGuid()).to.not.equal(child.getGuid());
for (const name in components) {
expect(cloneChild[name]).to.be.an.instanceof(components[name]);
}
root.destroy();
});
it('returns a deep clone of the entity\'s subtree, including all components', function () {
const subtree1 = createSubtree();
const subtree2 = cloneSubtree(subtree1);
// Ensure structures are identical at every level
expect(subtree2.a.name).to.equal('a');
expect(subtree2.a.animation.speed).to.equal(0.9);
expect(subtree2.a.animation.loop).to.equal(true);
expect(subtree2.a.camera.nearClip).to.equal(2);
expect(subtree2.a.camera.farClip).to.equal(3);
expect(subtree2.a_a.name).to.equal('a_a');
expect(subtree2.a_a.collision.radius).to.equal(4);
expect(subtree2.a_a.collision.type).to.equal('sphere');
expect(subtree2.a_a.rigidbody.type).to.equal('static');
expect(subtree2.a_a_b.name).to.equal('a_a_b');
expect(subtree2.a_a_b.light.intensity).to.equal(0.5);
expect(subtree2.a_a_b.light.type).to.equal('point');
expect(subtree2.a_a_b.light.color.equals(Color.YELLOW)).to.be.true;
expect(subtree2.a_a_b.sound.pitch).to.equal(0.75);
expect(subtree2.a_a_b.sound.volume).to.equal(0.5);
expect(subtree2.a_b.name).to.equal('a_b');
expect(subtree2.a_a_a.name).to.equal('a_a_a');
// Ensure we only have the exact number of children that were expected
expect(subtree2.a.children.length).to.equal(2);
expect(subtree2.a_a.children.length).to.equal(2);
expect(subtree2.a_b.children.length).to.equal(0);
expect(subtree2.a_a_a.children.length).to.equal(0);
expect(subtree2.a_a_b.children.length).to.equal(0);
// Ensure copies were created, not references
expect(subtree1.a).to.not.equal(subtree2.a);
expect(subtree1.a.animation).to.not.equal(subtree2.a.animation);
expect(subtree1.a.camera).to.not.equal(subtree2.a.camera);
expect(subtree1.a_a).to.not.equal(subtree2.a_a);
expect(subtree1.a_a.collision).to.not.equal(subtree2.a_a.collision);
expect(subtree1.a_a.rigidbody).to.not.equal(subtree2.a_a.rigidbody);
expect(subtree1.a_b).to.not.equal(subtree2.a_b);
expect(subtree1.a_a_a).to.not.equal(subtree2.a_a_a);
expect(subtree1.a_a_b).to.not.equal(subtree2.a_a_b);
expect(subtree1.a_a_b.light).to.not.equal(subtree2.a_a_b.light);
expect(subtree1.a_a_b.sound).to.not.equal(subtree2.a_a_b.sound);
// Ensure new guids were created
expect(subtree1.a.getGuid()).to.not.equal(subtree2.a.getGuid());
expect(subtree1.a_a.getGuid()).to.not.equal(subtree2.a_a.getGuid());
expect(subtree1.a_b.getGuid()).to.not.equal(subtree2.a_b.getGuid());
expect(subtree1.a_a_a.getGuid()).to.not.equal(subtree2.a_a_a.getGuid());
expect(subtree1.a_a_b.getGuid()).to.not.equal(subtree2.a_a_b.getGuid());
});
it('resolves entity property references that refer to entities within the duplicated subtree', function () {
const subtree1 = createSubtree();
subtree1.a.addComponent('dummy', { myEntity1: subtree1.a_a.getGuid(), myEntity2: subtree1.a_a_b.getGuid() });
subtree1.a_a_a.addComponent('dummy', { myEntity1: subtree1.a.getGuid(), myEntity2: subtree1.a_b.getGuid() });
const subtree2 = cloneSubtree(subtree1);
expect(subtree2.a.dummy.myEntity1).to.equal(subtree2.a_a.getGuid());
expect(subtree2.a.dummy.myEntity2).to.equal(subtree2.a_a_b.getGuid());
expect(subtree2.a_a_a.dummy.myEntity1).to.equal(subtree2.a.getGuid());
expect(subtree2.a_a_a.dummy.myEntity2).to.equal(subtree2.a_b.getGuid());
});
it('resolves entity property references that refer to the cloned entity itself', function () {
const subtree1 = createSubtree();
subtree1.a.addComponent('dummy', { myEntity1: subtree1.a.getGuid() });
subtree1.a_a_a.addComponent('dummy', { myEntity1: subtree1.a_a_a.getGuid() });
const subtree2 = cloneSubtree(subtree1);
expect(subtree2.a.dummy.myEntity1).to.equal(subtree2.a.getGuid());
expect(subtree2.a_a_a.dummy.myEntity1).to.equal(subtree2.a_a_a.getGuid());
});
it('does not attempt to resolve entity property references that refer to entities outside of the duplicated subtree', function () {
const root = new Entity('root', app);
const sibling = new Entity('sibling', app);
const subtree1 = createSubtree();
root.addChild(subtree1.a);
root.addChild(sibling);
subtree1.a.addComponent('dummy', { myEntity1: root.getGuid(), myEntity2: sibling.getGuid() });
const subtree2 = cloneSubtree(subtree1);
expect(subtree2.a.dummy.myEntity1).to.equal(root.getGuid());
expect(subtree2.a.dummy.myEntity2).to.equal(sibling.getGuid());
});
it('ignores null and undefined entity property references', function () {
const subtree1 = createSubtree();
subtree1.a.addComponent('dummy', { myEntity1: null, myEntity2: undefined });
const subtree2 = cloneSubtree(subtree1);
expect(subtree2.a.dummy.myEntity1).to.be.null;
expect(subtree2.a.dummy.myEntity2).to.be.undefined;
});
it('resolves entity script attributes that refer to entities within the duplicated subtree', function () {
const TestScript = createScript('test');
TestScript.attributes.add('entityAttr', { type: 'entity' });
TestScript.attributes.add('entityArrayAttr', { type: 'entity', array: true });
const subtree1 = createSubtree();
app.root.addChild(subtree1.a);
subtree1.a.addComponent('script');
subtree1.a.script.create('test', {
attributes: {
entityAttr: subtree1.a_a.getGuid(),
entityArrayAttr: [subtree1.a_a.getGuid()]
}
});
expect(subtree1.a.script.test.entityAttr.getGuid()).to.equal(subtree1.a_a.getGuid());
expect(subtree1.a.script.test.entityArrayAttr).to.be.an('array');
expect(subtree1.a.script.test.entityArrayAttr.length).to.equal(1);
expect(subtree1.a.script.test.entityArrayAttr[0].getGuid()).to.equal(subtree1.a_a.getGuid());
subtree1.a_a.addComponent('script');
subtree1.a_a.script.create('test', {
attributes: {
entityAttr: subtree1.a.getGuid(),
entityArrayAttr: [subtree1.a.getGuid(), subtree1.a_a_a.getGuid()]
}
});
expect(subtree1.a_a.script.test.entityAttr.getGuid()).to.equal(subtree1.a.getGuid());
expect(subtree1.a_a.script.test.entityArrayAttr).to.be.an('array');
expect(subtree1.a_a.script.test.entityArrayAttr.length).to.equal(2);
expect(subtree1.a_a.script.test.entityArrayAttr[0].getGuid()).to.equal(subtree1.a.getGuid());
expect(subtree1.a_a.script.test.entityArrayAttr[1].getGuid()).to.equal(subtree1.a_a_a.getGuid());
const subtree2 = cloneSubtree(subtree1);
app.root.addChild(subtree2.a);
expect(subtree2.a.script.test.entityAttr.getGuid()).to.equal(subtree2.a_a.getGuid());
expect(subtree2.a.script.test.entityArrayAttr).to.be.an('array');
expect(subtree2.a.script.test.entityArrayAttr.length).to.equal(1);
expect(subtree2.a.script.test.entityArrayAttr[0].getGuid()).to.equal(subtree2.a_a.getGuid());
expect(subtree2.a_a.script.test.entityAttr.getGuid()).to.equal(subtree2.a.getGuid());
expect(subtree2.a_a.script.test.entityArrayAttr).to.be.an('array');
expect(subtree2.a_a.script.test.entityArrayAttr.length).to.equal(2);
expect(subtree2.a_a.script.test.entityArrayAttr[0].getGuid()).to.equal(subtree2.a.getGuid());
expect(subtree2.a_a.script.test.entityArrayAttr[1].getGuid()).to.equal(subtree2.a_a_a.getGuid());
});
it('resolves entity script attributes that refer to entities within the duplicated subtree after preloading has finished', function () {
const TestScript = createScript('test');
TestScript.attributes.add('entityAttr', { type: 'entity' });
TestScript.attributes.add('entityArrayAttr', { type: 'entity', array: true });
app.systems.script.preloading = false;
const subtree1 = createSubtree();
app.root.addChild(subtree1.a);
subtree1.a.addComponent('script');
subtree1.a.script.create('test', {
attributes: {
entityAttr: subtree1.a_a.getGuid(),
entityArrayAttr: [subtree1.a_a.getGuid()]
}
});
expect(subtree1.a.script.test.entityAttr.getGuid()).to.equal(subtree1.a_a.getGuid());
expect(subtree1.a.script.test.entityArrayAttr).to.be.an('array');
expect(subtree1.a.script.test.entityArrayAttr.length).to.equal(1);
expect(subtree1.a.script.test.entityArrayAttr[0].getGuid()).to.equal(subtree1.a_a.getGuid());
subtree1.a_a.addComponent('script');
subtree1.a_a.script.create('test', {
attributes: {
entityAttr: subtree1.a.getGuid(),
entityArrayAttr: [subtree1.a.getGuid(), subtree1.a_a_a.getGuid()]
}
});
expect(subtree1.a_a.script.test.entityAttr.getGuid()).to.equal(subtree1.a.getGuid());
expect(subtree1.a_a.script.test.entityArrayAttr).to.be.an('array');
expect(subtree1.a_a.script.test.entityArrayAttr.length).to.equal(2);
expect(subtree1.a_a.script.test.entityArrayAttr[0].getGuid()).to.equal(subtree1.a.getGuid());
expect(subtree1.a_a.script.test.entityArrayAttr[1].getGuid()).to.equal(subtree1.a_a_a.getGuid());
const subtree2 = cloneSubtree(subtree1);
app.root.addChild(subtree2.a);
expect(subtree2.a.script.test.entityAttr.getGuid()).to.equal(subtree2.a_a.getGuid());
expect(subtree2.a.script.test.entityArrayAttr).to.be.an('array');
expect(subtree2.a.script.test.entityArrayAttr.length).to.equal(1);
expect(subtree2.a.script.test.entityArrayAttr[0].getGuid()).to.equal(subtree2.a_a.getGuid());
expect(subtree2.a_a.script.test.entityAttr.getGuid()).to.equal(subtree2.a.getGuid());
expect(subtree2.a_a.script.test.entityArrayAttr).to.be.an('array');
expect(subtree2.a_a.script.test.entityArrayAttr.length).to.equal(2);
expect(subtree2.a_a.script.test.entityArrayAttr[0].getGuid()).to.equal(subtree2.a.getGuid());
expect(subtree2.a_a.script.test.entityArrayAttr[1].getGuid()).to.equal(subtree2.a_a_a.getGuid());
});
it('does not attempt to resolve entity script attributes that refer to entities outside of the duplicated subtree', function () {
const TestScript = createScript('test');
TestScript.attributes.add('entityAttr', { type: 'entity' });
TestScript.attributes.add('entityArrayAttr', { type: 'entity', array: true });
const subtree1 = createSubtree();
app.root.addChild(subtree1.a);
subtree1.a_a.addComponent('script');
subtree1.a_a.script.create('test', {
attributes: {
entityAttr: app.root.getGuid(),
entityArrayAttr: [subtree1.a.getGuid(), app.root.getGuid()]
}
});
expect(subtree1.a_a.script.test.entityAttr.getGuid()).to.equal(app.root.getGuid());
expect(subtree1.a_a.script.test.entityArrayAttr).to.be.an('array');
expect(subtree1.a_a.script.test.entityArrayAttr.length).to.equal(2);
expect(subtree1.a_a.script.test.entityArrayAttr[0].getGuid()).to.equal(subtree1.a.getGuid());
expect(subtree1.a_a.script.test.entityArrayAttr[1].getGuid()).to.equal(app.root.getGuid());
const subtree2 = cloneSubtree(subtree1);
app.root.addChild(subtree2.a);
expect(subtree2.a_a.script.test.entityAttr.getGuid()).to.equal(app.root.getGuid());
expect(subtree2.a_a.script.test.entityArrayAttr).to.be.an('array');
expect(subtree2.a_a.script.test.entityArrayAttr.length).to.equal(2);
expect(subtree2.a_a.script.test.entityArrayAttr[0].getGuid()).to.equal(subtree2.a.getGuid());
expect(subtree2.a_a.script.test.entityArrayAttr[1].getGuid()).to.equal(app.root.getGuid());
});
it('does not resolve entity script attributes that refer to entities within the duplicated subtree if app.useLegacyScriptAttributeCloning is true', function () {
const TestScript = createScript('test');
TestScript.attributes.add('entityAttr', { type: 'entity' });
TestScript.attributes.add('entityArrayAttr', { type: 'entity', array: true });
const subtree1 = createSubtree();
app.root.addChild(subtree1.a);
subtree1.a.addComponent('script');
subtree1.a.script.create('test', {
attributes: {
entityAttr: subtree1.a_a.getGuid(),
entityArrayAttr: [subtree1.a_a.getGuid()]
}
});
expect(subtree1.a.script.test.entityAttr.getGuid()).to.equal(subtree1.a_a.getGuid());
expect(subtree1.a.script.test.entityArrayAttr).to.be.an('array');
expect(subtree1.a.script.test.entityArrayAttr.length).to.equal(1);
expect(subtree1.a.script.test.entityArrayAttr[0].getGuid()).to.equal(subtree1.a_a.getGuid());
subtree1.a_a.addComponent('script');
subtree1.a_a.script.create('test', {
attributes: {
entityAttr: subtree1.a.getGuid(),
entityArrayAttr: [subtree1.a.getGuid(), subtree1.a_a_a.getGuid()]
}
});
expect(subtree1.a_a.script.test.entityAttr.getGuid()).to.equal(subtree1.a.getGuid());
expect(subtree1.a_a.script.test.entityArrayAttr).to.be.an('array');
expect(subtree1.a_a.script.test.entityArrayAttr.length).to.equal(2);
expect(subtree1.a_a.script.test.entityArrayAttr[0].getGuid()).to.equal(subtree1.a.getGuid());
expect(subtree1.a_a.script.test.entityArrayAttr[1].getGuid()).to.equal(subtree1.a_a_a.getGuid());
app.useLegacyScriptAttributeCloning = true;
const subtree2 = cloneSubtree(subtree1);
app.root.addChild(subtree2.a);
expect(subtree2.a.script.test.entityAttr.getGuid()).to.equal(subtree1.a_a.getGuid());
expect(subtree2.a.script.test.entityArrayAttr).to.be.an('array');
expect(subtree2.a.script.test.entityArrayAttr.length).to.equal(1);
expect(subtree2.a.script.test.entityArrayAttr[0].getGuid()).to.equal(subtree1.a_a.getGuid());
expect(subtree2.a_a.script.test.entityAttr.getGuid()).to.equal(subtree1.a.getGuid());
expect(subtree2.a_a.script.test.entityArrayAttr).to.be.an('array');
expect(subtree2.a_a.script.test.entityArrayAttr.length).to.equal(2);
expect(subtree2.a_a.script.test.entityArrayAttr[0].getGuid()).to.equal(subtree1.a.getGuid());
expect(subtree2.a_a.script.test.entityArrayAttr[1].getGuid()).to.equal(subtree1.a_a_a.getGuid());
});
it('ensures that an instance of a subclass keeps its class prototype', function () {
class UserEntity extends Entity {}
const a = new UserEntity();
const b = a.clone();
expect(b).to.be.an.instanceof(UserEntity);
});
});
describe('#destroy', function () {
it('destroys the entity', function () {
const entity = new Entity();
let destroyed = false;
entity.on('destroy', function () {
destroyed = true;
});
entity.destroy();
expect(destroyed).to.be.true;
});
});
describe('#findByGuid', function () {
it('returns same entity', function () {
const e = new Entity();
expect(e.findByGuid(e.getGuid())).to.equal(e);
});
it('returns direct child entity', function () {
const e = new Entity();
const c = new Entity();
e.addChild(c);
expect(e.findByGuid(c.getGuid())).to.equal(c);
});
it('returns child of child entity', function () {
const e = new Entity();
const c = new Entity();
const c2 = new Entity();
e.addChild(c);
c.addChild(c2);
expect(e.findByGuid(c2.getGuid())).to.equal(c2);
});
it('does not return parent', function () {
const e = new Entity();
const c = new Entity();
e.addChild(c);
expect(c.findByGuid(e.getGuid())).to.equal(null);
});
it('does not return destroyed entity', function () {
const e = new Entity();
const c = new Entity();
e.addChild(c);
c.destroy();
expect(e.findByGuid(c.getGuid())).to.equal(null);
});
it('does not return entity that was removed from hierarchy', function () {
const e = new Entity();
const c = new Entity();
e.addChild(c);
e.removeChild(c);
expect(e.findByGuid(c.getGuid())).to.equal(null);
});
it('does not return entity that does not exist', function () {
expect(app.root.findByGuid('missing')).to.equal(null);
});
});
describe('#findComponent', function () {
it('finds component on single entity', function () {
const e = new Entity();
e.addComponent('anim');
const component = e.findComponent('anim');
expect(component).to.be.an.instanceof(AnimComponent);
});
it('returns null when component is not found', function () {
const e = new Entity();
e.addComponent('anim');
const component = e.findComponent('render');
expect(component).to.be.null;
});
it('finds component on child entity', function () {
const root = new Entity();
const child = new Entity();
root.addChild(child);
child.addComponent('anim');
const component = root.findComponent('anim');
expect(component).to.be.an.instanceof(AnimComponent);
});
it('finds component on grandchild entity', function () {
const root = new Entity();
const child = new Entity();
const grandchild = new Entity();
root.addChild(child);
child.addChild(grandchild);
grandchild.addComponent('anim');
const component = root.findComponent('anim');
expect(component).to.be.an.instanceof(AnimComponent);
});
it('does not find component on parent entity', function () {
const root = new Entity();
const child = new Entity();
root.addChild(child);
root.addComponent('anim');
const component = child.findComponent('anim');
expect(component).to.be.null;
});
});
describe('#findComponents', function () {
it('finds components on single entity', function () {
const e = new Entity();
e.addComponent('anim');
const components = e.findComponents('anim');
expect(components).to.be.an('array');
expect(components.length).to.equal(1);
expect(components[0]).to.be.an.instanceof(AnimComponent);
});
it('returns empty array when no components are found', function () {
const e = new Entity();
e.addComponent('anim');
const components = e.findComponents('render');
expect(components).to.be.an('array');
expect(components.length).to.equal(0);
});
it('finds components on child entity', function () {
const root = new Entity();
const child = new Entity();
root.addChild(child);
child.addComponent('anim');
const components = root.findComponents('anim');
expect(components).to.be.an('array');
expect(components.length).to.equal(1);
expect(components[0]).to.be.an.instanceof(AnimComponent);
});
it('finds components on 3 entity hierarchy', function () {
const root = new Entity();
const child = new Entity();
const grandchild = new Entity();
root.addChild(child);
child.addChild(grandchild);
root.addComponent('anim');
child.addComponent('anim');
grandchild.addComponent('anim');
const components = root.findComponents('anim');
expect(components).to.be.an('array');
expect(components.length).to.equal(3);
expect(components[0]).to.be.an.instanceof(AnimComponent);
expect(components[1]).to.be.an.instanceof(AnimComponent);
expect(components[2]).to.be.an.instanceof(AnimComponent);
});
it('does not find components on parent entity', function () {
const root = new Entity();
const child = new Entity();
root.addChild(child);
root.addComponent('anim');
const components = child.findComponents('anim');
expect(components).to.be.an('array');
expect(components.length).to.equal(0);
});
});
describe('#removeComponent', function () {
it('removes a component from the entity', function () {
const entity = new Entity();
expect(entity.anim).to.be.undefined;
entity.addComponent('anim');
expect(entity.anim).to.be.an.instanceof(AnimComponent);
entity.removeComponent('anim');
expect(entity.anim).to.be.undefined;
entity.destroy();
});
});
});
|
(function(){
function Player(initPlayer){
if(!(Player.prototype.attack instanceof Function)){
Player.prototype.attack=function(mob){
mob.health-=(this.mode>0) ? (this.mode*5>Math.floor(Math.random()*100)?this.dmg*2:this.dmg) : (this.mode*5>Math.floor(Math.random()*100)?0:this.dmg);
return !!mob.health;
};
}
if(!(Player.prototype.block instanceof Function)){
Player.prototype.block=function(){
return this.block>Math.floor(Math.random()*10);
};
}
if(!(Player.prototype.draw instanceof Function)){
Player.prototype.draw=function(map){
map.player.innerHTML="Player\n❤"+this.health+"\n➹"+this.dmg;
};
}
this.dmg=initPlayer.dmg||1;
this.health=initPlayer.health||1;
this.speed=initPlayer.speed||0;
this.draw(initPlayer.map);
}
function Mob(initMob){
if(!(Mob.prototype.attack instanceof Function)){
Mob.prototype.attack=function(player){
if(!player.block()){
player.health-=this.dmg;
return !!player.health;
}
};
}
if(!(Mob.prototype.die instanceof Function)){
Mob.prototype.die=function(map){
map.div[this.position.x+this.position.y*5].textContent="";
map.item[this.position.x][this.position.y]=null;
};
}
if(!(Mob.prototype.draw instanceof Function)){
Mob.prototype.draw=function(map){
console.log(this.position);
map.div[this.position.x+this.position.y*5].innerHTML="Mob\n❤"+this.health+"\n➹"+this.dmg;
};
}
this.position=initMob.position;
this.health=initMob.health;
this.speed=initMob.speed;
this.dmg=initMob.dmg;
this.draw(initMob.map);
}
var battle=function(map,player,mob){
if(player.speed>mob.speed){
mob.health-=player.dmg;
if(mob.health>0){
player.health-=mob.dmg;
}else{
mob.die(map);
return false;
}
}else{
player.health-=mob.dmg;
if(player.health>0){
mob.health-=player.dmg;
}else{
player.health=0;
return false;
}
}
return true;
console.log(player.health,mob.health);
}
var map={player:document.getElementById("infobar"),map:document.getElementById("map"),div:document.getElementsByClassName("step"),item:[[],[],[],[],[]]};
var player;
var initGame=function(map,player){
map.map.onclick=function(e){
var p=e.target.getAttribute("data-id");
if(map.item[p[0]][p[1]] instanceof Mob && battle(map,player,map.item[p[0]][p[1]])){
map.item[p[0]][p[1]].draw(map);
player.draw(map);
}
};
console.log(map);
map.item[1][1] = new Mob({position:{x:1,y:1},health:100,speed:10,dmg:10,map:map});
player=new Player({map:map,dmg:30,health:200,speed:11});
};
initGame(map,player);
})();
|
Application = {
Forms: {
validateFormApplication: function(){
$("#q-form-application").validate({
rules: {
"q-form-application-name": {
required: true,
},
"q-form-application-email": {
required: true,
email: true
},
"q-form-application-mobile": {
required: true,
},
"q-form-application-nationality": {
required: true,
},
"q-form-application-age": {
required: true,
},
"q-form-application-interests": {
required: true,
},
"q-form-application-startdate": {
required: true,
},
"q-form-application-duration": {
required: true,
},
"q-form-application-motivation": {
required: true,
},
},
messages: {
"q-form-application-name": {
required: "Please enter your name.",
},
"q-form-application-email": {
required: "Please enter your e-mail address.",
email: "Please enter a valid e-mail address."
},
"q-form-application-mobile": {
required: "Please enter your mobile number.",
},
"q-form-application-nationality": {
required: "Please select your nationality.",
},
"q-form-application-age": {
required: "Please enter your age.",
},
"q-form-application-interests": {
required: "Please enter your interests.",
},
"q-form-application-startdate": {
required: "Please tell us when you want to start your programme.",
},
"q-form-application-duration": {
required: "Please select the duration of your programme.",
},
"q-form-application-motivation": {
required: "Please enter a motivating letter.",
},
},
errorClass: "q-validation-error",
validClass: "q-validation-success",
showErrors: Site.UI.showErrors,
submitHandler: function(){
// console.log("Submit");
Application.API.postFormAppliction();
}
});
}
},
API: {
postFormAppliction: function() {
var myData = {
"q-form-application-name": $("#q-form-application-name").val(),
"q-form-application-email": $("#q-form-application-email").val(),
"q-form-application-mobile": $("#q-form-application-mobile").val(),
"q-form-application-nationality": $("#q-form-application-nationality").find("option:selected").val(),
"q-form-application-age": $("#q-form-application-age").val(),
"q-form-application-interests": $("#q-form-application-interests").val(),
"q-form-application-startdate": $("#q-form-application-startdate").val(),
"q-form-application-duration": $("[name='q-form-application-duration']").filter(":checked").val(),
"q-form-application-motivation": $("#q-form-application-motivation").val(),
};
console.log(myData);
$.ajax({
// url: "",
url: "/php/application.php",
method: "post",
data: myData,
beforeSend: function() {
Framework.UI.loadingOverlay.add({
type: "dots",
text: "Sending Application..."
});
},
success: function() {
$("#q-form-application")[0].reset();
var n = noty({
theme: "relax",
type: "success",
layout: "bottomCenter",
text: "Thank you! Your application has been sent.",
timeout: 5000
});
},
error: function(data) {
console.log(data);
var n = noty({
theme: "relax",
type: "error",
layout: "bottomCenter",
text: "Whoops! Something went wrong. Please try again, or check back later.",
timeout: 5000
});
},
complete: function() {
Framework.UI.loadingOverlay.hide();
}
});
},
},
reset: function() {
Application.Forms.validateFormApplication();
}
};
Application.reset();
|
// require express
const express = require('express')
const passport = require('passport')
// require Mongoose model of collectionSchema
const Collection = require('../models/collection')
// const Movie = require('./../models/movie')
// require customErrors to detect when to throw error
const customErrors = require('../../lib/custom_errors')
// handle404 for when non-existent doc is requested
const handle404 = customErrors.handle404
// we'll use this function to send 401 when a user tries to modify a resource
// that's owned by someone else
const requireOwnership = customErrors.requireOwnership
// const requireOwnershipBool = customErrors.requireOwnershipBool
// this is middleware that will remove blank fields from `req.body`, e.g.
// { example: { title: '', text: 'foo' } } -> { example: { text: 'foo' } }
const removeBlanks = require('../../lib/remove_blank_fields')
// passing this as a second argument to `router.<verb>` will make it
// so that a token MUST be passed for that route to be available
// it will also set `req.user`
const requireToken = passport.authenticate('bearer', { session: false })
// instantiate a router (mini app that only handles routes)
const router = express.Router()
// CREATE working
router.post('/movies', requireToken, (req, res, next) => {
// store incoming request's movie data
const movieData = req.body.movie
// extract the the collection we want to add the movie to
const collectionId = movieData.collectionId
Collection.findById(collectionId)
.then(handle404)
.then(collection => {
// push movieData into property "movies" (blank array) on the collection
collection.movies.push(movieData)
return collection.save()
})
.then(collection => res.status(201).json({ collection }))
.catch(next)
})
// GET all
// router.get('/movies', requireToken, (req, res, next) => {
// let arrayOfOwnersMovies = []
// Movie.find()
// .then(movies)
// })
// UPDATE working
router.patch('/movies/:id', requireToken, removeBlanks, (req, res, next) => {
// save movie info from request
const movieData = req.body.movie
// save movie id indicated by request
const movieId = req.params.id
// find a collection with a movie that matches movieId
Collection.findOne({ 'movies._id': movieId })
.then(handle404)
.then(collection => {
// make sure user owns movie they want to update
requireOwnership(req, collection)
return collection
})
.then(collection => {
const movie = collection.movies.id(movieId)
// replace movie's data with movieData
movie.set(movieData)
return collection.save()
})
.then(() => res.sendStatus(204))
.catch(next)
})
router.delete('/movies/:id', requireToken, (req, res, next) => {
const movieId = req.params.id
Collection.findOne({ 'movies._id': movieId })
.then(handle404)
.then(collection => {
requireOwnership(req, collection)
return collection
})
.then(collection => {
const movie = collection.movies.id(movieId)
movie.remove()
return collection.save()
})
.then(() => res.sendStatus(204))
.catch(next)
})
module.exports = router
|
import {Record} from './record'
export class Schema{
_records = [] //Array of Record
constructor(){
}
create(recordObject){
let record = new Record(recordObject, this)
this._records.push(record)
return record
}
registerRecord(record){
this._records.push(record)
}
removeRecord(record) {
this._records.splice(this._records.indexOf(record), 1)
}
all(){
return this._records
}
/**
* If multiple records match the given search parameters, then only the first matched record will be returned
* Returns the first matched result
*/
findBy(searchParam){
let [searchAttribute, searchValue] = Object.entries(searchParam)[0]
for (let record of this._records) {
if (record[searchAttribute] == searchValue ){
return record;
}
}
}
}
|
app.controller("addActionController",['$scope','$modalInstance','$http','$timeout','checkUniqueService',"permItemId","aData",function($scope,$modalInstance,$http,$timeout,checkUniqueService,permItemId,aData){
$scope.formData = {};
if(aData){
$scope.formData = aData ;
}else{
$scope.formData.fType = 0;
$scope.formData.useState = 0;
}
$scope.ok = function() {
$scope.formData.useState = parseInt($scope.formData.useState);
$scope.formData.fType = parseInt($scope.formData.fType);
$modalInstance.close($scope.formData);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
//
}]);
|
"use strict";
const express = require("express");
const app = express();
const port = process.env.PORT || 8080;
app.use(express.static(`${__dirname}/dist`));
app.all("*", (req, res) => {
console.log(`[TRACE] Server 404 request: ${req.originalUrl}`);
res.status(200).sendFile(`${__dirname}/dist/index.html`);
});
app.listen(port, () => {
console.log(`App started at port ${port}`);
});
|
import React, { useState, useEffect } from "react";
import { makeStyles } from "@material-ui/core/styles";
import Modal from "@material-ui/core/Modal";
import Backdrop from "@material-ui/core/Backdrop";
import "./SaveFlow.css";
import CrossButtonIcon from "../../Assets/message_card/crossbutton1.svg";
const useStyles = makeStyles((theme) => ({
modal: {
display: "flex",
alignItems: "center",
justifyContent: "center",
},
paper: {
display: "flex",
flexDirection: "column",
position: "relative",
width: "340px",
// height: "250px",
background: "#F0F2F2",
borderRadius: "20px",
},
}));
const DeleteFlow = (props) => {
const classes = useStyles();
const handleClose = () => {
props.setOpen2(false);
};
return (
<div>
<Modal
open={props.open2}
className={classes.modal}
onClose={handleClose}
BackdropComponent={Backdrop}
>
<div className={classes.paper}>
<div className="saveHeader">
<div className="saveHeaderText">Delete Flow</div>
<div
className="delete-icon"
onClick={() => {
props.setOpen2(false);
}}
>
<img src={CrossButtonIcon} alt="x" />
</div>
</div>
<div className="saveBody">
Are you sure you wanna delete this entire flow ?
</div>
<div className="saveFooter">
<button
className="footerCancelDelete"
onClick={() => {
props.setOpen2(false);
}}
>
Cancel
</button>
<button
className="footerDelete"
onClick={() => {
localStorage.removeItem("persist:root");
window.location.reload();
}}
>
Delete
</button>
</div>
</div>
</Modal>
</div>
);
};
export default DeleteFlow;
|
//jshint esversion:6
//API requests
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require('mongoose');
const { Double } = require("mongodb");
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static("public"));
mongoose.connect("mongodb://localhost:27017/wikiDB", {useNewUrlParser: true});
const productSchema = {
title: String,
price: Double
}
const Product = mongoose.model("Product", productSchema);
app.route("/products")
.get(function(req, res){
Product.find(function(err, foundProducts){
if(!err){
res.send(foundProducts);
}else{
res.send(err);
}
});
})
.post(function(req, res){
const newProduct = new Product({
title: req.body.title,
price: req.body.price
});
})
.delete(function(req, res){
Product.deleteMany(function(err){
if(!err){
res.send("Successfully deleted all products");
}else{
res.send(err);
}
});
});
app.route("/products/:productTitle")
.get(function(req, res){
Product.findOne({title: req.params.productTitle}, function(err, foundProduct){
if(foundProduct){
res.send(foundProduct);
}else{
res.send("No products matching that title were found");
}
});
})
.put(function(req, res){
Product.update(
{title: req.params.productTitle},
{title: req.body.title, price: req.body.price},
{overwrite: true},
function(err){
if(!err){
res.send("Successfully updated article");
}
}
);
})
.delete(function(req, res){
Product.deleteOne(
{title: req.params.productTitle},
function(err){
if(!err){
res.send("Successfully deleted specified product");
}else{
res.send(err);
}
}
);
});
app.listen(3000, function(){
console.log("Server started on port 3000");
});
|
isEven = x => x%2 == 0 ? true : false;
find = function (x,fun) {
for(let i of x) {
if(fun(i)) {
return i;
}
}
}
console.log(find([1, 3, 5, 4, 2], isEven));
|
YUI.add("yuidoc-meta", function(Y) {
Y.YUIDoc = { meta: {
"classes": [
"Cycle",
"EventDispatcher",
"Fps",
"Polling"
],
"modules": [
"Gasane"
],
"allModules": [
{
"displayName": "Gasane",
"name": "Gasane",
"description": "Fps, Polling 時間管理eventを発行します"
}
],
"elements": []
} };
});
|
const express = require('express')
const router = express.Router();
const Task = require('../models/task')
const Folder = require('../models/folders')
//ruta de obtencion de folders
router.get('/api/folders', async (req, res) => {
const folders = await Folder.find()
console.log(folders)
res.send(folders)
})
//ruta para agregar folders
router.post('/api/folders', async (req, res) => {
const { title } = req.body;
const folders = new Folder({ title });
await folders.save();
res.json({ status: 'Carpeta guardada' })
})
//ruta para eliminar folders y sus comentarios
router.delete('/api/folders/:id', async (req, res) => {
const folder = await Folder.findOne({ _id: req.params.id })
if (folder) {
await Task.deleteMany({ folder_id: folder._id });
await folder.remove()
}
res.json({ status: 'Carpeta Eliminada' })
})
//ruta para cargar una tarea a un folder
router.post('/api/tasks/:id', async (req, res) => {
const folder = await Folder.findOne({ _id: req.params.id })
console.log(folder)
if (folder) {
const { title, description } = req.body;
const task = new Task({ title, description });
task.folder_id = folder._id
await task.save();
console.log(req.params.id)
res.json({ status: 'Tarea guardada' })
} else {
res.send("fallo")
}
})
//ruta para traer todas las tareas pertenecientes a un folder
router.get('/api/tasks/:id', async (req, res) => {
const tasks = await Task.find({ folder_id: req.params.id });
console.log(tasks)
res.send(tasks)
});
//ruta para traer las tareas a modificar
router.get('/api/tasks/edit/:id', async (req, res) => {
const tasks = await Task.findById(req.params.id);
console.log(tasks)
res.send(tasks)
});
//ruta para actualizar la tarea
router.put('/api/tasks/:id', async (req, res) => {
const { title, description } = req.body
const newTask = { title, description };
await Task.findByIdAndUpdate(req.params.id, newTask)
res.json({ status: 'Task Update' })
})
//ruta para eliminar una tarea
router.delete('/api/tasks/:id', async (req, res) => {
await Task.findByIdAndDelete(req.params.id);
res.json({ status: 'Tarea eliminada' })
})
module.exports = router;
|
export default {
getName(state) {
return state.name
}
}
|
function sum(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw new Error('parameters must be numbers');
}
return a + b;
}
// implemente seus testes aqui
test('sum', () => {
expect(sum(5, 4)).toEqual(9);
})
|
/*
* @Author: cash
* @Date: 2021-08-30 15:59:35
* @LastEditors: cash
* @LastEditTime: 2021-11-05 11:32:53
* @Description: file content
* @FilePath: \hdl-try\vite.config.js
*/
import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
import autoprefixer from 'autoprefixer';
import viteSvgIcons from 'vite-plugin-svg-icons';
function resolvePath(dir) {
return resolve(__dirname, '.', dir);
}
// console.log(process.env);
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, __dirname);
const isProduction = env.VITE_NODE_ENV === 'production';
return {
plugins: [
vue(),
autoprefixer,
// // 自动导入svg图标
viteSvgIcons({
iconDirs: [resolve(process.cwd(), 'src/public')],
symbolId: 'icon-[dir]-[name]',
}),
],
// 项目根目录
root: process.cwd(),
// 在生产中服务时的基本公共路径
base: './',
// 配置中指明将会把 serve 和 build 时的模式都覆盖掉,serve 时默认 'development',build 时默认 'production'
mode: 'development',
// 在开发时会被定义为全局变量,而在构建时则是静态替换
define: '',
// 静态资源服务的文件夹
publicDir: 'assets',
resolve: {
alias: {
'@': resolvePath('src'),
},
},
server: {
port: 8096,
open: true,
overlay: {
warning: false,
errors: true,
},
lintOnSave: false,
proxy: {
// '/api':{
// target::'/',
// changeOrigin:true,
// ws:true,
// rewrite:path=>path.replace(/^\/api/,'')
// }
},
hmr: { overlay: false },
},
build: {
outDir: `dist`,
// 生产环境移除console
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true,
},
},
},
// CSS 预处理器
css: {
//* css模块化
modules: {
// css模块化 文件以.module.[css|less|scss]结尾
generateScopedName: '[name]__[local]___[hash:base64:5]',
hashPrefix: 'prefix',
},
preprocessorOptions: {
less: {
modifyVars: {
// 用于全局导入,以避免需要单独导入每个样式文件。
// reference: 避免重复引用
// hack: `true; @import (reference) "${resolve('src/design/config.less')}";`,
// ↓这行代码下一章讲
// ...generateModifyVars(),
'primary-color': '#F35C1D',
'link-color': '#F35C1D',
'border-radius-base': '4px',
},
javascriptEnabled: true,
},
},
},
optimizeDeps: {
// @iconify/iconify: The dependency is dynamically and virtually loaded by @purge-icons/generated, so it needs to be specified explicitly
include: [
'@iconify/iconify',
'ant-design-vue/es/locale/zh_CN',
'moment/dist/locale/zh-cn',
'ant-design-vue/es/locale/en_US',
'moment/dist/locale/eu',
],
exclude: ['vue-demi'],
},
};
});
|
// for: content/api-streamer/examples.textile
/* eslint-disable no-undef */
const nouns = [
'people',
'history',
'way',
'art',
'world',
'information',
'map',
'two',
'family',
'government',
'health',
'system',
'computer',
'meat',
'year',
'thanks',
'music',
'person',
'reading',
'method',
'data',
'food',
'understanding',
'theory',
'law',
'bird',
'literature',
'problem',
'software',
'control',
'knowledge',
'power',
'ability',
'economics',
'love',
'internet',
'television',
'science',
'library',
'nature',
'fact',
'product',
'idea',
'temperature',
'investment',
'area',
'society',
'activity',
'story',
'industry',
'media',
'thing',
'oven',
'community',
'definition',
'safety',
'quality',
'development',
'language',
'management',
'player',
'variety',
'video',
'week',
'security',
'country',
'exam',
'movie',
'organization',
'equipment',
'physics',
'analysis',
'policy',
'series',
'thought',
'basis',
'boyfriend',
'direction',
'strategy',
'technology',
'army',
'camera',
'freedom',
'paper',
'environment',
'child',
'instance',
'month',
'truth',
'marketing',
'university',
'writing',
'article',
'department',
'difference',
'goal',
'news',
'audience',
'fishing',
'growth',
'income',
'marriage',
'user',
'combination',
'failure',
'meaning',
'medicine',
'philosophy',
'teacher',
'communication',
'night',
'chemistry',
'disease',
'disk',
'energy',
'nation',
'road',
'role',
'soup',
'advertising',
'location',
'success',
'addition',
'apartment',
'education',
'math',
'moment',
'painting',
'politics',
'attention',
'decision',
'event',
'property',
'shopping',
'student',
'wood',
'competition',
'distribution',
'entertainment',
'office',
'population',
'president',
'unit',
'category',
'cigarette',
'context',
'introduction',
'opportunity',
'performance',
'driver',
'flight',
'length',
'magazine',
'newspaper',
'relationship',
'teaching',
'cell',
'dealer',
'finding',
'lake',
'member',
'message',
'phone',
'scene',
'appearance',
'association',
'concept',
'customer',
'death',
'discussion',
'housing',
'inflation',
'insurance',
'mood',
'woman',
'advice',
'blood',
'effort',
'expression',
'importance',
'opinion',
'payment',
'reality',
'responsibility',
'situation',
'skill',
'statement',
'wealth',
'application',
'city',
'county',
'depth',
'estate',
'foundation',
'people',
'history',
'way',
'art',
'world',
'information',
'map',
'two',
'family',
'government',
'health',
'system',
'computer',
'meat',
'year',
'thanks',
'music',
'person',
'reading',
'method',
'data',
'food',
'understanding',
'theory',
'law',
'bird',
'literature',
'problem',
'software',
'control',
'knowledge',
'power',
'ability',
'economics',
'love',
'internet',
'television',
'science',
'library',
'nature',
'fact',
'product',
'idea',
'temperature',
'investment',
'area',
'society',
'activity',
'story',
'industry',
'media',
'thing',
'oven',
'community',
'definition',
'safety',
'quality',
'development',
'language',
'management',
'player',
'variety',
'video',
'week',
'security',
'country',
'exam',
'movie',
'organization',
'equipment',
'physics',
'analysis',
'policy',
'series',
'thought',
'basis',
'boyfriend',
'direction',
'strategy',
'technology',
'army',
'camera',
'freedom',
'paper',
'environment',
'child',
'instance',
'month',
'truth',
'marketing',
'university',
'writing',
'article',
'department',
'difference',
'goal',
'news',
'audience',
'fishing',
'growth',
'income',
'marriage',
'user',
'combination',
'failure',
'meaning',
'medicine',
'philosophy',
'teacher',
'communication',
'night',
'chemistry',
'disease',
'disk',
'energy',
'nation',
'road',
'role',
'soup',
'advertising',
'location',
'success',
'addition',
'apartment',
'education',
'math',
'moment',
'painting',
'politics',
'attention',
'decision',
'event',
'property',
'shopping',
'student',
'wood',
'competition',
'distribution',
'entertainment',
'office',
'population',
'president',
'unit',
'category',
'cigarette',
'context',
'introduction',
'opportunity',
'performance',
'driver',
'flight',
'length',
'magazine',
'newspaper',
'relationship',
'teaching',
'cell',
'dealer',
'finding',
'lake',
'member',
'message',
'phone',
'scene',
'appearance',
'association',
'concept',
'customer',
'death',
'discussion',
'housing',
'inflation',
'insurance',
'mood',
'woman',
'advice',
'blood',
'effort',
'expression',
'importance',
'opinion',
'payment',
'reality',
'responsibility',
'situation',
'skill',
'statement',
'wealth',
'application',
'city',
'county',
'depth',
'estate',
'foundation',
'grandmother',
'heart',
'perspective',
'photo',
'recipe',
'studio',
'topic',
'collection',
'depression',
'imagination',
'passion',
'percentage',
'resource',
'setting',
'ad',
'agency',
'college',
'connection',
'criticism',
'debt',
'description',
'memory',
'patience',
'secretary',
'solution',
'administration',
'aspect',
'attitude',
'director',
'personality',
'psychology',
'recommendation',
'response',
'selection',
'storage',
'version',
'alcohol',
'argument',
'complaint',
'contract',
'emphasis',
'highway',
'loss',
'membership',
'possession',
'preparation',
'steak',
'union',
'agreement',
'cancer',
'currency',
'employment',
'engineering',
'entry',
'interaction',
'mixture',
'preference',
'region',
'republic',
'tradition',
'virus',
'actor',
'classroom',
'delivery',
'device',
'difficulty',
'drama',
'election',
'engine',
'football',
'guidance',
'hotel',
'owner',
'priority',
'protection',
'suggestion',
'tension',
'variation',
'anxiety',
'atmosphere',
'awareness',
'bath',
'bread',
'candidate',
'climate',
'comparison',
'confusion',
'construction',
'elevator',
'emotion',
'employee',
'employer',
'guest',
'height',
'leadership',
'mall',
'manager',
'operation',
'recording',
'sample',
'transportation',
'charity',
'cousin',
'disaster',
'editor',
'efficiency',
'excitement',
'extent',
'feedback',
'guitar',
'homework',
'leader',
'mom',
'outcome',
'permission',
'presentation',
'promotion',
'reflection',
'refrigerator',
'resolution',
'revenue',
'session',
'singer',
'tennis',
'basket',
'bonus',
'cabinet',
'childhood',
];
window.ably = {
...window.ably,
docs: {
DOCS_API_KEY: false,
randomChannelName: nouns[Math.floor(Math.random() * nouns.length)],
onApiKeyRetrieved: () => {},
},
};
function subscribeToCurlRequest(key) {
var ably = new Ably.Realtime(key);
const channelName = window.ably.docs.randomChannelName;
ably.channels.get(channelName).subscribe('greeting', function (message) {
alert(
'That was easy, a message was just received from the REST API on channel "' +
channelName +
'".\n\nGreeting => ' +
message.data,
);
});
}
if (window.ably.docs.DOCS_API_KEY) {
subscribeToCurlRequest(window.ably.docs.DOCS_API_KEY);
} else {
window.ably.docs.onApiKeyRetrieved = subscribeToCurlRequest;
}
|
/*
* top2TopComponent.js
*
* Copyright (c) 2019 H-E-B
* All rights reserved.
*
* This software is the confidential and proprietary information
* of HEB.
*/
'use strict';
/**
* Component to support the page that allows users to manage top 2 top.
*
* @author vn73545
* @since 2.41.0
*/
(function () {
var app = angular.module('productMaintenanceUiApp');
app.component('top2TopComponent', {
templateUrl: 'src/codeTable/top2Top/top2Top.html',
bindings: {
selected: '<'
},
controller: top2TopController
});
top2TopController.$inject = ['$rootScope', '$scope', 'ngTableParams', 'top2TopApi'];
/**
* Constructs for top 2 top Controller.
*/
function top2TopController($rootScope, $scope, ngTableParams, top2TopApi) {
var self = this;
/**
* Constant for EMPTY
* @type {string}
*/
const EMPTY = "";
/**
* Constant for UNKNOWN_ERROR
* @type {string}
*/
const UNKNOWN_ERROR = "An unknown error occurred.";
/**
* Constant for UNSAVED_DATA_CONFIRM_TITLE
* @type {string}
*/
const UNSAVED_DATA_CONFIRM_TITLE = "Confirmation";
/**
* Constant for UNSAVED_DATA_CONFIRM_MESSAGE
* @type {string}
*/
const UNSAVED_DATA_CONFIRM_MESSAGE = "Unsaved data will be lost. Do you want to save the changes before continuing?";
/**
* Constant for TOP_2_TOP_DELETE_MESSAGE_HEADER
* @type {string}
*/
const TOP_2_TOP_DELETE_MESSAGE_HEADER = 'Delete Top 2 Top';
/**
* Constant for TOP_2_TOP_DELETE_CONFIRM_MESSAGE_STRING
* @type {string}
*/
const TOP_2_TOP_DELETE_CONFIRM_MESSAGE_STRING = 'Are you sure you want to delete the selected Top 2 Top?';
/**
* Constant for THERE_ARE_NO_DATA_CHANGES_MESSAGE_STRING
* @type {string}
*/
const THERE_ARE_NO_DATA_CHANGES_MESSAGE_STRING = 'There are no changes on this page to be saved. Please make any changes to update.';
/**
* Constant for UNSAVED_DATA_CONFIRM_MESSAGE_STRING
* @type {string}
*/
const UNSAVED_DATA_CONFIRM_MESSAGE_STRING = 'Unsaved data will be lost. Do you want to save the changes before continuing?';
/**
* Constant for DUPLICATE_TOP_2_TOPS
* @type {string}
*/
const DUPLICATE_TOP_2_TOPS = "Duplicate Top 2 Tops.";
/**
* Constant for ALREADY_EXISTS_TOP_2_TOPS
* @type {string}
*/
const ALREADY_EXISTS_TOP_2_TOPS = "Top 2 Top already exists.";
/**
* Start position of page that want to show on top 2 top table
*
* @type {number}
*/
self.PAGE = 1;
/**
* The number of records to show on the top 2 top table.
*
* @type {number}
*/
self.PAGE_SIZE = 20;
/**
* Start position of current page that want to show on top 2 top table
*
* @type {number}
*/
self.currentPage = 1;
self.data = [];
self.firstSearch = false;
self.tableParams = null;
var previousNameFilter = null;
var previousIdFilter = null;
/**
* String for TOP_2_TOP_NAME_MANDATORY_FIELD_ERROR
* @type {string}
*/
self.TOP_2_TOP_NAME_MANDATORY_FIELD_ERROR = 'Top 2 Top name is a mandatory field.';
/**
* Empty model.
*/
self.EMPTY_MODEL = {
"topToTopId": "",
"topToTopName": ""
};
/**
* Selected edit top 2 top.
* @type {null}
*/
self.selectedTop2Top = null;
/**
* The original, unedited top 2 top.
* @type {null}
*/
self.originalTop2Top = null;
/**
* Selected edited row index.
* @type {null}
*/
self.selectedRowIndex = -1;
/**
* Validation model.
*/
self.validationModel = angular.copy(self.EMPTY_MODEL);
/**
* Validation top 2 top key.
* @type {string}
*/
self.VALIDATE_TOP_2_TOP = 'validateTop2Top';
/**
* Return tab key.
* @type {string}
*/
self.RETURN_TAB = 'returnTab';
self.isAddingTop2Top = false;
self.newTop2Tops = [];
/**
* Component ngOnInit lifecycle hook. This lifecycle is executed every time the component is initialized
* (or re-initialized).
*/
this.$onInit = function () {
self.newSearch();
if ($rootScope.isEditedOnPreviousTab) {
self.error = $rootScope.error;
self.success = $rootScope.success;
}
$rootScope.isEditedOnPreviousTab = false;
};
/**
* Resets the table with current filter. If the table has not been created, create the table. Else reload the
* table.
*/
self.newSearch = function () {
self.isWaitingForResponse = true;
self.firstSearch = true;
self.currentPage = 1;
if (self.tableParams == null) {
self.createTop2TopTable();
} else {
self.tableParams.reload();
}
};
/**
* Create top 2 top table.
*/
self.createTop2TopTable = function () {
self.tableParams = new ngTableParams({
page: self.PAGE, /* show first page */
count: self.PAGE_SIZE /* count per page */
}, {
counts: [],
getData: function ($defer, params) {
self.recordsVisible = 0;
self.data = null;
self.defer = $defer;
self.dataResolvingParams = params;
var includeCounts = false;
var topToTopId = params.filter()["topToTopId"];
var topToTopName = params.filter()["topToTopName"];
if (typeof topToTopId === "undefined") {
topToTopId = EMPTY;
}
if (typeof topToTopName === "undefined") {
topToTopName = EMPTY;
}
if (topToTopId !== previousIdFilter || topToTopName !== previousNameFilter) {
self.firstSearch = true;
}
if (self.firstSearch) {
includeCounts = true;
params.page(self.currentPage);
self.firstSearch = false;
self.startRecord = 0;
}
self.resetSelectedTop2Top();
previousNameFilter = topToTopName;
previousIdFilter = topToTopId;
self.fetchData(includeCounts, params.page() - 1, topToTopId, topToTopName);
}
});
};
/**
* Initiates a call to get the list of attribute maintenance records.
*
* @param includeCounts Whether or not to include getting record counts.
* @param page The page of data to ask for.
* @param topToTopId ID for attribute filtering.
* @param topToTopName the topToTopName for attribute filtering.
*/
self.fetchData = function (includeCounts, page, topToTopId, topToTopName) {
top2TopApi.findAll({
topToTopId: topToTopId,
topToTopName: topToTopName,
page: page,
pageSize: self.PAGE_SIZE,
includeCount: includeCounts
}, self.loadData, self.handleError);
};
/**
* Callback for when the backend returns an error.
*
* @param error The error from the back end.
*/
self.handleError = function (error) {
self.isWaitingForResponse = false;
self.success = null;
self.error = self.getErrorMessage(error);
if (self.isReturnToTab) {
$rootScope.error = self.error;
$rootScope.isEditedOnPreviousTab = true;
}
self.isReturnToTab = false;
};
/**
* Returns error message.
*
* @param error
* @returns {string}
*/
self.getErrorMessage = function (error) {
if (error && error.data) {
if (error.data.message) {
return error.data.message;
} else {
return error.data.error;
}
}
return UNKNOWN_ERROR;
};
/**
* Clear filter.
*/
self.clearFilter = function () {
self.dataResolvingParams.filter()["topToTopId"] = null;
self.dataResolvingParams.filter()["topToTopName"] = null;
self.resetSelectedTop2Top();
self.tableParams.reload();
self.error = EMPTY;
self.success = EMPTY;
};
/**
* Determines if the filter has been cleared or not.
*
* @returns {boolean}
*/
self.isFilterCleared = function () {
if (!self.dataResolvingParams) {
return true;
}
if (!self.dataResolvingParams.filter()["topToTopId"] &&
!self.dataResolvingParams.filter()["topToTopName"]) {
return true
}
return false;
};
/**
* Callback for when data is successfully returned from the backend.
*
* @param results The data returned from the backend.
*/
self.loadData = function (results) {
self.isWaitingForResponse = false;
self.data = results.data;
self.defer.resolve(self.data);
if (results.complete) {
self.totalPages = results.pageCount;
self.totalRecords = results.recordCount;
self.dataResolvingParams.total(self.totalRecords);
}
};
/**
* Add one more row to top 2 top.
*/
self.addRow = function () {
if (self.isValidNewTop2Top()) {
var newTop2Top = self.initEmptyNewTop2Top();
self.newTop2Tops.push(newTop2Top);
if (self.newTop2Tops.length > self.PAGE_SIZE
&& self.newTop2Tops.length % self.PAGE_SIZE === 1) {
self.tableModalParams.page(self.tableModalParams.page() + 1);
$('#addTop2TopModal').find('input:text:visible:first').focus();
}
self.tableModalParams.reload();
}
};
/**
* Validates new top 2 top.
*
* @returns {boolean}
*/
self.isValidNewTop2Top = function () {
var errorMessages = [];
var errorMessage = EMPTY;
self.errorPopup = EMPTY;
for (var i = 0; i < self.newTop2Tops.length; i++) {
self.newTop2Tops[i].addClass = EMPTY;
self.newTop2Tops[i].addTooltip = EMPTY;
if (self.isNullOrEmpty(self.newTop2Tops[i].topToTopName)) {
errorMessage = "<li>" + self.TOP_2_TOP_NAME_MANDATORY_FIELD_ERROR + "</li>";
if (errorMessages.indexOf(errorMessage) == -1) {
errorMessages.push(errorMessage);
}
self.newTop2Tops[i].addClass = 'active-tooltip ng-invalid ng-touched';
self.newTop2Tops[i].addTooltip = self.TOP_2_TOP_NAME_MANDATORY_FIELD_ERROR;
}else if(self.isDuplicatedTopToTopName(self.newTop2Tops, self.newTop2Tops[i].topToTopName)){
errorMessage = "<li>" + DUPLICATE_TOP_2_TOPS + "</li>";
if (errorMessages.indexOf(errorMessage) == -1) {
errorMessages.push(errorMessage);
}
self.newTop2Tops[i].addClass = 'active-tooltip ng-invalid ng-touched';
self.newTop2Tops[i].addTooltip = DUPLICATE_TOP_2_TOPS;
}
}
if (errorMessages.length > 0) {
var errorMessagesAsString = EMPTY;
angular.forEach(errorMessages, function (errorMessage) {
errorMessagesAsString += errorMessage;
});
self.errorPopup = errorMessagesAsString;
return false;
}
return true;
};
/**
* Check duplicated TopToTop name in array.
*
* @returns {boolean}
*/
self.isDuplicatedTopToTopName = function (array, value) {
var count = array.filter(function(obj){return obj.topToTopName.toUpperCase() === value.toUpperCase()}).length;
if(count >= 2) {
return true;
}
return false;
};
/**
* Check object null or empty
*
* @param object
* @returns {boolean} true if Object is null/ false or equals blank, otherwise return false.
*/
self.isNullOrEmpty = function (object) {
return object === null || !object || object === EMPTY;
};
/**
* Handle when click Add button to display the modal.
*/
self.addNewTop2Top = function () {
self.clearMessages();
self.resetSelectedTop2Top();
self.tableParams.reload();
self.isAddingTop2Top = true;
var top2Top = self.initEmptyNewTop2Top();
self.newTop2Tops.push(top2Top);
self.tableModalParams = new ngTableParams({
page: self.PAGE,
count: self.PAGE_SIZE
}, {
counts: [],
debugMode: true,
data: self.newTop2Tops
});
$('#addTop2TopModal').modal({backdrop: 'static', keyboard: true});
$('#addTop2TopModal').on('shown.bs.modal', function () {
$(this).find('input:text:visible:first').attr('title', EMPTY);
$(this).find('input:text:visible:first').removeClass('ng-invalid ng-touched');
$(this).find('input:text:visible:first').focus();
});
};
/**
* Initiate empty top 2 top to display in the modal.
*
* @returns {Object}
*/
self.initEmptyNewTop2Top = function () {
return angular.copy(self.EMPTY_MODEL);
};
/**
* Clear all the messages when click buttons.
*/
self.clearMessages = function () {
self.error = EMPTY;
self.success = EMPTY;
self.errorPopup = EMPTY;
self.newTop2Tops = [];
};
/**
* Handle when click close in add popup but have data changed to show popup confirm.
*/
self.closeModalUnsavedData = function () {
if (self.newTop2Tops.length !== 0 && self.newTop2Tops[0].topToTopName.length !== 0) {
self.titleConfirm = UNSAVED_DATA_CONFIRM_TITLE;
self.messageConfirm = UNSAVED_DATA_CONFIRM_MESSAGE;
$('#confirmModal').modal({backdrop: 'static', keyboard: true});
$('.modal-backdrop').attr('style', ' z-index: 100000; ');
} else {
$('#addTop2TopModal').modal("hide");
self.newTop2Tops = [];
}
};
/**
* Close confirm popup.
*/
self.closeConfirmPopup = function () {
$('#confirmModal').modal("hide");
$('.modal-backdrop').removeAttr("style");
};
/**
* Close add popup and confirm popup.
*/
self.closeAllPopups = function () {
self.allowDeleteTop2Top = false;
self.isAddingTop2Top = false;
if (self.isReturnToTab) {
$('#addTop2TopModal').modal("hide");
$('#confirmModal').on('hidden.bs.modal', function () {
self.returnToTab();
$scope.$apply();
});
} else {
$('#confirmModal').modal("hide");
$('#addTop2TopModal').modal("hide");
}
};
/**
* Removes selected row from modal table.
*
* @param index the index to remove.
*/
self.deleteRow = function (index) {
var removedIndex = index + ((self.tableModalParams.page()-1)*self.PAGE_SIZE);
self.newTop2Tops.splice(removedIndex, 1);
self.tableModalParams.reload().then(function(data) {
if (data.length === 0 && self.tableModalParams.total() > 0) {
self.tableModalParams.page(self.tableModalParams.page() - 1);
self.tableModalParams.reload();
}
});
self.isValidNewTop2Top();
};
/**
* Saves new top 2 tops.
*/
self.saveNewTop2Tops = function () {
if (self.isValidNewTop2Top()
&& (self.newTop2Tops != null && self.newTop2Tops.length > 0)) {
top2TopApi.addTop2Tops(self.newTop2Tops,
function (response) {
if (response.message.indexOf("Successfully") !== -1) {
self.success = response.message;
self.closeAllPopups();
self.isAddingTop2Top = false;
self.tableParams.page(1);
self.reloadTableAfterSave();
}else{
$('#confirmModal').modal("hide");
$('.modal-backdrop').removeAttr("style");
self.handleAddErrorMessage(response);
}
}, function (error) {
$('#confirmModal').modal("hide");
$('.modal-backdrop').removeAttr("style");
self.errorPopup = self.getErrorMessage(error);
});
}else{
$('#confirmModal').modal("hide");
$('.modal-backdrop').removeAttr("style");
}
};
/**
* Reload main table after add new or delete top 2 tops.
*/
self.reloadTableAfterSave = function () {
self.isWaitingForResponse = true;
self.firstSearch = true;
self.currentPage = self.tableParams.page();
self.tableParams.reload();
};
/**
* Add error border on exist fields.
*/
self.handleAddErrorMessage = function (response) {
var tempMsgs = response.data;
self.errorPopup = "<li>" + response.message + "</li>";
for (var i = 0; i < tempMsgs.length; i++) {
for (var j = 0; j < self.newTop2Tops.length; j++) {
if (self.newTop2Tops[j].topToTopName.toUpperCase() === tempMsgs[i].topToTopName.toUpperCase()) {
self.newTop2Tops[j].addClass = 'active-tooltip ng-invalid ng-touched';
self.newTop2Tops[j].addTooltip = ALREADY_EXISTS_TOP_2_TOPS;
}
}
}
};
/**
* Edit top 2 top handle. This method is called when click on edit button.
*
* @param top2Top the top 2 top to handle.
*/
self.editTop2Top = function (top2Top) {
if (self.selectedRowIndex === -1) {
self.originalTop2Top = JSON.stringify(top2Top);
self.error = EMPTY;
self.success = EMPTY;
top2Top.isEditing = true;
self.validationModel = angular.copy(top2Top);
self.selectedTop2Top = top2Top;
self.selectedRowIndex = self.getRowIndex();
}
};
/**
* Calls confirmation modal to confirm delete action.
*
* @param top2Top the top 2 top to delete.
*/
self.deleteTop2Top = function (top2Top) {
self.selectedDeletedTop2Top = top2Top;
self.error = EMPTY;
self.success = EMPTY;
self.titleConfirm = TOP_2_TOP_DELETE_MESSAGE_HEADER;
self.messageConfirm = TOP_2_TOP_DELETE_CONFIRM_MESSAGE_STRING;
self.labelClose = 'No';
self.allowDeleteTop2Top = true;
$('#confirmModal').modal({backdrop: 'static', keyboard: true});
};
/**
* Calls the api to update the top 2 top.
*/
self.updateTop2Top = function () {
self.error = EMPTY;
self.success = EMPTY;
if (self.selectedRowIndex > -1) {
// editing mode.
if (self.isTop2TopChanged()) {
if (self.validateTop2TopBeforeUpdate()) {
self.isWaitingForResponse = true;
var top2TopTemp = angular.copy(self.selectedTop2Top);
delete top2TopTemp['isEditing'];
top2TopApi.updateTop2Top(top2TopTemp,
function (results) {
self.data[self.selectedRowIndex] = angular.copy(results.data);
self.resetSelectedTop2Top();
self.isWaitingForResponse = false;
self.checkAllFlag = false;
self.success = results.message;
if (self.isReturnToTab) {
$rootScope.success = self.success;
$rootScope.isEditedOnPreviousTab = true;
}
self.returnToTab();
},
function (error) {
self.handleError(error);
}
);
}
} else {
self.error = THERE_ARE_NO_DATA_CHANGES_MESSAGE_STRING;
}
} else {
self.error = THERE_ARE_NO_DATA_CHANGES_MESSAGE_STRING;
}
};
/**
* Resets top 2 top back to original state.
* @param index
*/
self.resetTop2Top = function (index) {
self.error = EMPTY;
self.success = EMPTY;
self.data[index] = JSON.parse(self.originalTop2Top);
self.resetSelectedTop2Top();
};
/**
* Returns the disabled status of button by top 2 top id.
*
* @param topToTopId the top 2 top id.
* @returns {boolean} the disable status.
*/
self.isDisabledButton = function (topToTopId) {
return !(self.selectedRowIndex === -1 || self.selectedTop2Top.topToTopId === topToTopId);
};
/**
* Returns the style for icon button.
*
* @param topToTopId the id of top 2 top.
* @returns {*} the style.
*/
self.getDisabledButtonStyle = function (topToTopId) {
if (self.isDisabledButton(topToTopId)) {
return 'opacity: 0.5;'
}
return 'opacity: 1.0;';
};
/**
* Return edited row index.
*
* @returns {number}
*/
self.getRowIndex = function () {
if (self.selectedTop2Top == null) {
return -1;
}
if (self.selectedTop2Top.topToTopId === 0) {
return 0;
}
for (var i = 0; i < self.data.length; i++) {
if (self.data[i].topToTopId === self.selectedTop2Top.topToTopId) {
return i;
}
}
};
/**
* Validates the top 2 top name before updates.
*
* @returns {boolean}
*/
self.validateTop2TopBeforeUpdate = function () {
var errorMessages = [];
var message = EMPTY;
if (!self.validationModel || self.validationModel.topToTopName.trim().length === 0) {
message = '<li>' + self.TOP_2_TOP_NAME_MANDATORY_FIELD_ERROR + '</li>';
errorMessages.push(message);
self.showErrorOnTextBox('topToTopName', self.TOP_2_TOP_NAME_MANDATORY_FIELD_ERROR);
return false;
}
return true;
};
/**
* Show red border on input text.
*
* @param topToTopId if of input text.
*/
self.showErrorOnTextBox = function (topToTopId, message) {
if ($('#' + topToTopId).length > 0) {
$('#' + topToTopId).addClass('ng-invalid ng-touched');
$('#' + topToTopId).attr('title', message);
}
};
/**
* Reset the status add or edit top 2 top.
*/
self.resetSelectedTop2Top = function () {
self.selectedRowIndex = -1;
self.selectedTop2Top = null;
};
/**
* Checks if the top 2 top is changed or not.
*
* @returns {boolean}
*/
self.isTop2TopChanged = function () {
var top2TopTemp = angular.copy(self.selectedTop2Top);
delete top2TopTemp['isEditing'];
return JSON.stringify(top2TopTemp) !== self.originalTop2Top;
};
/**
* This method is used to return to the selected tab.
*/
self.returnToTab = function () {
if (self.isReturnToTab) {
$rootScope.$broadcast(self.RETURN_TAB);
}
};
/**
* Handles errors when name changes.
*/
self.onNameChange = function () {
var value = $('#topToTopName').val();
if (value == null || value === undefined ||
value.trim().length === 0) {
self.showErrorOnTextBox('topToTopName', self.TOP_2_TOP_NAME_MANDATORY_FIELD_ERROR);
}
};
/**
* Calls api to delete the top 2 top.
*/
self.doDeleteTop2Top = function () {
self.closeAllPopups();
self.isWaitingForResponse = true;
top2TopApi.deleteTop2Top({topToTopId: self.selectedDeletedTop2Top.topToTopId},
function (results) {
self.isWaitingForResponse = false;
self.success = results.message;
self.selectedDeletedTop2Top = null;
if (self.tableParams.data.length === 1 && self.tableParams.total() > 0) {
self.tableParams.page(self.tableParams.page() - 1);
}
self.reloadTableAfterSave();
},
function (error) {
self.handleError(error);
}
);
};
/**
* Clear message listener.
*/
$scope.$on(self.VALIDATE_TOP_2_TOP, function () {
if (self.selectedTop2Top != null && self.isTop2TopChanged()) {
self.isReturnToTab = true;
self.allowDeleteTop2Top = false;
self.titleConfirm = UNSAVED_DATA_CONFIRM_TITLE;
self.error = EMPTY;
self.success = EMPTY;
self.messageConfirm = UNSAVED_DATA_CONFIRM_MESSAGE_STRING;
self.labelClose = 'No';
$('#confirmModal').modal({backdrop: 'static', keyboard: true});
} else {
$rootScope.$broadcast(self.RETURN_TAB);
}
});
}
})();
|
import { combineReducers } from 'redux'
import tagsReducer from './tags';
export default combineReducers({
tagsReducer,
})
|
$(document).ready(function(){
// Кешируем объект окна
$window = $(window);
$('section[data-type="background"]').each(function(){
var $bgobj = $(this); // Назначаем объект
$(window).scroll(function() {
// Прокручиваем фон со скоростью var.
// Значение yPos отрицательное, так как прокручивание осуществляется вверх!
var yPos = -($window.scrollTop() / $bgobj.data('speed'));
// Размещаем все вместе в конечной точке
var coords = '50% '+ yPos + 'px';
// Смещаем фон
$bgobj.css({ backgroundPosition: coords });
});
});
});
/*
* Создаем элементы HTML5 для IE
*/
document.createElement("article");
document.createElement("section");
<!-- SLIDER -->
jQuery('#fader img:gt(0)').hide();
setInterval(function(){
jQuery('#fader :first-child')
.fadeTo(700, 0)
.next('img')
.fadeTo(700, 1)
.end()
.appendTo('#fader');
}, 4000);
<!-- SLIDER CLIENTS -->
/*SCRIPT HOVER*/
$(function(){
$('.autocap').dropCaptions({
showSpeed: 1000,
showOpacity: .85,
hideOpacity: .25,
showEasing: 'easeOutBounce',
showDelay: 500,
hideDelay: 1000
});
$('.blacksheep').dropCaptions();
$('.bottom').dropCaptions({
showSpeed: 2000,
hideSpeed: 1000,
showOpacity: 1,
hideOpacity: 0,
showEasing: 'easeOutElastic',
hideEasing: 'easeInQuint',
hideDelay: 2000
});
});
$(function(){
$("#container").clickCarousel({margin: 10});
});
$(document).ready(function(){
$("#p1").hover(function() {
$(this).attr("src","hover.png");
}, function() {
$(this).removeAttr("hover.png");
});
});
$(document).ready(function(){
$("#p2").hover(function() {
$(this).attr("src","hover.png");
}, function() {
$(this).attr("src","images/our_works_2.jpg");
});
});
$(document).ready(function(){
$("#p3").hover(function() {
$(this).attr("src","hover.png");
}, function() {
$(this).attr("src","images/our_works_3.jpg");
});
});
$(document).ready(function(){
$("#p4").hover(function() {
$(this).attr("src","hover.png");
}, function() {
$(this).attr("src","images/our_works_4.jpg");
});
});
$(document).ready(function(){
$("#p5").hover(function() {
$(this).attr("src","hover.png");
}, function() {
$(this).attr("src","images/our_works_5.jpg");
});
});
$(document).ready(function(){
$("#p6").hover(function() {
$(this).attr("src","hover.png");
}, function() {
$(this).attr("src","images/our_works_6.jpg");
});
});
|
'use strict';
import DetectController from './detect.controller';
/**
* @const {Object} DetectComponent
*/
const DetectComponent = {
controller: DetectController,
template: require('./detect.component.html')
};
export default DetectComponent;
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Center from 'react-center';
import Button from '@material-ui/core/Button';
function Square(props) {
return (
<button className="square" onClick={props.onClick}>
{props.value}
</button>
);
}
function chooseOnePlayerGame() {
ReactDOM.unmountComponentAtNode(document.getElementById('root'));
ReactDOM.render(
<ChooseCharacter />,
document.getElementById('root')
);
}
class ChooseNumberOfPlayers extends React.Component {
render() {
return (
<Center>
<div className="playerchoice">
<div>
<h1>{"Welcome to the amazing world of tic-tac-toe!"}</h1>
<h3>{"Your adventure awaits..."}</h3>
</div>
<div className="numplayers">
<div className="oneplayer">
<Button variant="contained" color="primary" onClick={() => chooseOnePlayerGame()}>{"One player"}</Button>
</div>
<div className="twoplayer">
<Button variant="contained" color="secondary" onClick={() => startTwoPlayerGame()}>{"Two players"}</Button>
</div>
</div>
</div>
</Center>
);
}
}
class ChooseCharacter extends React.Component {
render () {
return (
<Center>
<div className="playerchoice">
<div>
<h1>{"Choose your weapon!"}</h1>
</div>
<div className="numplayers">
<div className="oneplayer">
<Button variant="contained" color="primary" onClick={() => startOnePlayerGame(true)}>{"X"}</Button>
</div>
<div className="twoplayer">
<Button variant="contained" color="secondary" onClick={() => startOnePlayerGame(false)}>{"O"}</Button>
</div>
</div>
</div>
</Center>
);
}
}
class Board extends React.Component {
renderSquare(i) {
return <Square
value={this.props.squares[i]}
onClick={() => this.props.onClick(i)}
/>;
}
render() {
return (
<div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
history: [{
squares: Array(9).fill(null),
}],
xIsNext: true,
isTwoPlayerGame: (this.props.humanPlayerIsX === undefined ? true: false),
humanPlayer: (this.props.humanPlayerIsX === undefined ? null : (this.props.humanPlayerIsX ? 'X': 'O')),
computer: (this.props.humanPlayerIsX === undefined ? null : (this.props.humanPlayerIsX ? 'O': 'X')),
status: (this.props.humanPlayerIsX === undefined ? "Next player: X" : (this.props.humanPlayerIsX ? 'Your turn': 'Computer\'s turn')),
};
}
getHistoryAndSquares() {
const history = this.state.history;
const current = history[history.length - 1];
const squares = current.squares.slice();
return [history, squares];
}
handleClick(i) {
var historyAndSquares = this.getHistoryAndSquares();
const history = historyAndSquares[0];
const squares = historyAndSquares[1];
//dont evaluate if we find a winner or the square clicked already has a value
if (calculateWinner(squares) || squares[i])
return;
var status = this.state.status;
//if it is a two player game, check for winner and change status.
if (this.state.isTwoPlayerGame) {
squares[i] = this.state.xIsNext ? 'X': 'O';
status = 'Next player: ' + (this.state.xIsNext ? 'O' : 'X');
var winner = calculateWinner(squares);
if (winner) {
if (winner === 'T')
status = 'It\'s a tie!';
else
status = 'Winner: ' + winner;
}
}
else {
squares[i] = this.state.humanPlayer;
}
this.setState({
history: history.concat([{
squares: squares,
}]),
xIsNext: !this.state.xIsNext,
status: status,
});
}
componentDidMount() {
//if it is one player mode, then start the game with the computer's choice on the board
if (this.state.computer === 'X') {
var historyAndSquares = this.getHistoryAndSquares();
const history = historyAndSquares[0];
const squares = historyAndSquares[1];
var index = minimax(squares, this.state.computer).index;
squares[index] = this.state.computer;
this.setState({
history: history.concat([{
squares: squares,
}]),
xIsNext: !this.state.xIsNext,
status: 'Your turn',
});
}
}
componentDidUpdate() {
var historyAndSquares = this.getHistoryAndSquares();
const history = historyAndSquares[0];
const squares = historyAndSquares[1];
let status = "Your turn ";
//if it is a one player game, then calculate the computer's choice and play
if ((this.state.xIsNext && this.state.computer === 'X') ||
(!this.state.xIsNext && this.state.computer === 'O')) {
var index = minimax(squares, this.state.computer).index;
squares[index] = this.state.computer;
var winner = calculateWinner(squares);
if (winner) {
if (winner === 'T')
status = 'It\'s a tie!';
else
status = (winner === this.state.computer ? "Computer wins!" : " You won!");
}
this.setState({
history: history.concat([{
squares: squares,
}]),
xIsNext: !this.state.xIsNext,
status: status,
});
}
}
handleRestartGame() {
if (this.state.isTwoPlayerGame)
startTwoPlayerGame();
else
startOnePlayerGame((this.state.humanPlayer === 'X' ? true: false));
}
render() {
var historyAndSquares = this.getHistoryAndSquares();
const squares = historyAndSquares[1];
return (
<Center>
<button className="main" onClick={() => chooseNumberOfPlayers()}>
{"Main Menu"}
</button>
<div className="game-info">
<div className="status">{this.state.status}</div>
</div>
<div className="reset-button">
<button className="reset" onClick={() => this.handleRestartGame()}>
{"Restart"}
</button>
</div>
<div className="game">
<div className="game-board">
<Board squares={squares} onClick={(i) => this.handleClick(i)}/>
</div>
</div>
</Center>
);
}
}
function startTwoPlayerGame() {
ReactDOM.unmountComponentAtNode(document.getElementById('root'));
ReactDOM.render(
<Game />,
document.getElementById('root')
);
}
function startOnePlayerGame(isHumanPlayerX) {
ReactDOM.unmountComponentAtNode(document.getElementById('root'));
ReactDOM.render(
<Game humanPlayerIsX={isHumanPlayerX} />,
document.getElementById('root')
);
}
function chooseNumberOfPlayers() {
ReactDOM.unmountComponentAtNode(document.getElementById('root'));
ReactDOM.render(
<ChooseNumberOfPlayers />,
document.getElementById('root')
);
}
function calculateWinner(squares) {
//winning tic-tac-toe board combinations
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
//check if no one has played yet, i.e. it is the beginning of the game
var hasAllNullValues = squares.every(function (val) {
return val === null;
});
if(hasAllNullValues)
return null;
//check if there is at least one empty spot on the board
var hasSomeNullValue = squares.some(function (val) {
return val === null;
});
//when there is no empty spot and we get here, it is a tie
if(!hasSomeNullValue)
return 'T';
return null;
}
function getRemainingSpotsOnBoard(leBoard) {
var emptyIndexes = [];
for(var i = 0; i < leBoard.length; i++) {
if(leBoard[i] === null)
emptyIndexes.push(i);
}
return emptyIndexes;
}
var minimax = function(board, player) {
//get all the spots on the board that have not been played in
var emptySpotsOnBoard = getRemainingSpotsOnBoard(board);
//check to see if there are game ending states of the game(i.e. win, lose, tie)
if (calculateWinner(board) === 'O') {
return {score: -10};
}
else if (calculateWinner(board) === 'X') {
return {score: 10};
}
else if (emptySpotsOnBoard.length === 0) {
return {score: 0};
}
var moves = [];
for (var i = 0; i < emptySpotsOnBoard.length; i++) {
var move = {};
move.index = emptySpotsOnBoard[i];
board[emptySpotsOnBoard[i]] = player;
if (player === 'X') { //computer is X
var result = minimax(board, 'O');
move.score = result.score;
}
else {
var result = minimax(board, 'X');
move.score = result.score;
}
board[emptySpotsOnBoard[i]] = null;
moves.push(move);
}
//when it is the computer's turn, loop over all the moves and choose the one with the maximum score
var bestMove;
if (player === 'X') {
var bestScore = -1000000;
for (var j = 0; j < moves.length; j++) {
if (moves[j].score > bestScore) {
bestScore = moves[j].score;
bestMove = j;
}
}
}
else {
//when it is the human players turn, loop over all the moves and choose the one with the minimum score
var bestScore = 1000000;
for (var j = 0; j < moves.length; j++) {
if (moves[j].score < bestScore) {
bestScore = moves[j].score;
bestMove = j;
}
}
}
return moves[bestMove];
}
chooseNumberOfPlayers();
|
"use strict";
exports.pathCombine = exports.getEscapedFileName = exports.getPathParts = exports.getParentPath = exports.getName = exports.getFileExtension = exports.PATH_SEPARATOR = void 0;
var _iterator = require("../core/utils/iterator");
var PATH_SEPARATOR = '/';
exports.PATH_SEPARATOR = PATH_SEPARATOR;
var getFileExtension = function getFileExtension(path) {
var index = path.lastIndexOf('.');
return index !== -1 ? path.substr(index) : '';
};
exports.getFileExtension = getFileExtension;
var getName = function getName(path) {
var index = path.lastIndexOf(PATH_SEPARATOR);
return index !== -1 ? path.substr(index + PATH_SEPARATOR.length) : path;
};
exports.getName = getName;
var getParentPath = function getParentPath(path) {
var index = path.lastIndexOf(PATH_SEPARATOR);
return index !== -1 ? path.substr(0, index) : '';
};
exports.getParentPath = getParentPath;
var getPathParts = function getPathParts(path, includeFullPath) {
if (!path || path === '/') {
return [];
}
var result = [];
var pathPart = '';
for (var i = 0; i < path.length; i++) {
var char = path.charAt(i);
if (char === PATH_SEPARATOR) {
var nextChar = path.charAt(i + 1);
if (nextChar !== PATH_SEPARATOR) {
if (pathPart) {
result.push(pathPart);
pathPart = '';
}
char = nextChar;
}
i++;
}
pathPart += char;
}
if (pathPart) {
result.push(pathPart);
}
if (includeFullPath) {
for (var _i = 0; _i < result.length; _i++) {
result[_i] = pathCombine(_i === 0 ? '' : result[_i - 1], getEscapedFileName(result[_i]));
}
}
return result;
};
exports.getPathParts = getPathParts;
var getEscapedFileName = function getEscapedFileName(fileName) {
return fileName.replace(/\//g, '//');
};
exports.getEscapedFileName = getEscapedFileName;
var pathCombine = function pathCombine() {
var result = '';
(0, _iterator.each)(arguments, function (_, arg) {
if (arg) {
if (result) {
result += PATH_SEPARATOR;
}
result += arg;
}
});
return result;
};
exports.pathCombine = pathCombine;
|
import React, { Component } from 'react';
import { Container } from 'react-bootstrap';
class PageTitle extends Component {
render() {
return (
<div className="page-title">
<Container><h2>{this.props.title}</h2></Container>
</div>
)
}
}
export default PageTitle;
|
FlowRouter.route('/', {
action: function() {
BlazeLayout.render('layout', { main: 'home', navbar: 'menu' });
},
name: 'home'
});
FlowRouter.route('/logs', {
action: function() {
BlazeLayout.render('logs', { log: 'login' });
},
name: 'logs'
});
// ##### USERS #####
// User route
FlowRouter.route('/users/:id', {
action: function() {
BlazeLayout.render('layout', { main: 'showUser', navbar: 'menu' });
},
name: 'showUser'
});
// ##### CONVERSATIONS #####
// Conversations route
FlowRouter.route('/conversations', {
action: function() {
BlazeLayout.render('layout', { main: 'conversations', navbar: 'menu' });
},
name: 'conversations'
});
// Redirect to register or login template
FlowRouter.route('/login', {
action: function() {
BlazeLayout.render('logs', { log: 'login' });
},
name: 'login'
});
FlowRouter.route('/register', {
action: function() {
BlazeLayout.render('logs', { log: 'register' });
},
name: 'register'
});
// Redirect the user if it is not connected
function redirectIfIsNotLogin(context) {
if (!Meteor.userId()) {
// BlazeLayout.render('logs', { log: 'login' }, {force: true});
FlowRouter.go('/');
} else {
// console.log(context);
}
}
FlowRouter.triggers.enter([redirectIfIsNotLogin], {except: ["login", "register"]});
// Redirect the user if it is not admin
function redirectIfIsNotAdmin(context) {
if (Meteor.user()) {
if (Meteor.user().profile.admin) {
return true;
} else {
FlowRouter.go('chat');
return false;
}
} else {
FlowRouter.go('chat')
}
}
FlowRouter.triggers.enter([redirectIfIsNotAdmin], {only: ["feedBacks", "users"]});
// Redirect the user if it is not Super Admin
function redirectIfIsNotSuperAdmin(context) {
if (Meteor.user()) {
if (Meteor.user().profile.superAdmin) {
return true;
} else {
FlowRouter.go('chat');
return false;
}
} else {
FlowRouter.go('chat')
}
}
FlowRouter.triggers.enter([redirectIfIsNotSuperAdmin], {only: ["users", "newUser", "feedBacks"]});
|
(function(){
var ReportController = function($scope,ReportFactory){
$scope.reports=[];
$scope.isOpen = false;
$scope.matchDate;
var alertSuccessClasses="alert alert-success alert-dismissible";
var alertErorrClasses="alert alert-danger alert-dismissible";
$scope.appliedClasses="alert alert-dismissible hideIt";
function init(){
getReportsByDate(new Date());
}
function getReportsByDate(date){
ReportFactory.getReports(date)
.success(function(reports){
$scope.reports = reports;
})
.error(function(err){
$scope.reports=[];
showMessageBox(alertErorrClasses,"Error",err);
})
}
init();
function showMessageBox(classes,type,message){
$scope.appliedClasses = classes;
$scope.type=type;
$scope.message=message;
$scope.isHide=true;
}
$scope.hideMessage = function(){
$scope.appliedClasses="alert alert-dismissible hideIt";
};
$scope.openCalendar = function(e) {
e.preventDefault();
e.stopPropagation();
$scope.isOpen = true;
};
$scope.getReports = function(isValid){
if(!isValid){
showMessageBox(alertErorrClasses,"Error","Please select date");
}
else{
getReportsByDate($scope.matchDate)
}
}
};
angular.module('vollyboard').controller('ReportController',ReportController);
}());
|
var gulp = require('gulp'),
watch = require('gulp-watch'),
browserSync = require('browser-sync').create();
var SCRIPTS_PATH = './_src/js/**/*.js',
STYLES_PATH = './_src/less/**/*.less',
HTML_PATH = './index.html';
gulp.task('watch', function() {
browserSync.init({
notify: false,
server: {
baseDir: ''
},
host: 'localhost',
port: 8081,
ui: {
port: 8082
}
});
// Description: Watch for change in html and when detected, start html
// task.
watch(HTML_PATH, function() {
browserSync.reload();
});
watch(STYLES_PATH, function() {
// trigger less task
gulp.start('cssInject');
});
watch(SCRIPTS_PATH, function() {
// trigger less task
gulp.start('scriptsRefresh');
});
});
// Task: CSS Inject
// =============================================================================
// Dependencies in brackets. Run cssInject after 'styles' task
// is complete
// cssInject will not run untill less task is completed
gulp.task('cssInject', ['less'], function() {
return gulp.src('./build/styles/styles.css')
.pipe(browserSync.stream());
});
// scriptsRefresh will not run untill less task is completed
gulp.task('scriptsRefresh', ['scripts'], function() {
browserSync.reload();
});
|
var rainRecurringBuildObject = function(controls) {
var obj = {
"enabled":controls.hasClass('rain-recurring-on')
};
if(obj.enabled) {
obj.frequency = controls.find('.rain-recurring-freq option:selected').val();
} else {
controls.find('input[name="recurring"]').val(JSON.stringify(obj));
}
switch(obj.frequency) {
case 'weekly':
var days = [];
var dows = controls.find('.rain-recurring-dow input:checked');
for(var i=0;i<dows.length;i++) {
days.push($(dows[i]).val())
}
obj.dow = days;
break;
case 'monthly':
var doms = controls.find('.rain-recurring-dom input:checked');
var days = [];
for(var i=0;i<doms.length;i++) {
days.push($(doms[i]).val())
}
obj.dom = days;
break;
case 'every':
obj.x = controls.find('.rain-recurring-x').val();
obj.x = controls.find('.rain-recurring-duration').val();
break;
}
if(controls.find('.rain-recurring-public-holidays input:checked').length)
obj.excludePublicHolidays = true;
if(controls.find('.rain-recurring-business input:checked').length)
obj.businessDaysOnly = true;
if(obj.excludePublicHolidays || obj.businessDaysOnly) {
controls.find('.rain-recurring-else').show();
obj.inCase = controls.find('.rain-recurring-else option:selected').val();
}
else
controls.find('.rain-recurring-else').hide();
obj.until = controls.find('.rain-recurring-until option:selected').val();
if(obj.until!='forever')
obj.untilX = controls.find('.rain-recurring-until-x').val();
controls.find('input[name="recurring"]').val(JSON.stringify(obj));
}
$(document).ready(function() {
$('.rain-recurring').bind('click.toggleRecurring',function(e){
var controls = $(this).closest('.controls');
if(controls.hasClass('rain-recurring-on')) {
controls.removeClass('rain-recurring-on');
controls.removeClass('rain-recurring-'+controls.find('.rain-recurring-freq option:selected').val());
} else {
controls.addClass('rain-recurring-on');
controls.addClass('rain-recurring-'+controls.find('.rain-recurring-freq option:selected').val());
}
$('.rain-recurring-until').change();
rainRecurringBuildObject(controls);
});
$('.rain-recurring-freq').bind('change.recurringFreq',function(e){
var controls = $(this).closest('.controls');
controls.removeClass('rain-recurring-daily');
controls.removeClass('rain-recurring-weekly');
controls.removeClass('rain-recurring-fortnightly');
controls.removeClass('rain-recurring-monthly');
controls.removeClass('rain-recurring-quarterly');
controls.removeClass('rain-recurring-yearly');
controls.removeClass('rain-recurring-every');
controls.addClass('rain-recurring-'+controls.find('.rain-recurring-freq option:selected').val());
rainRecurringBuildObject(controls);
});
$('.rain-recurring-dow-day').bind('click.recurringDow',function(e){
var controls = $(this).closest('.controls');
rainRecurringBuildObject(controls);
});
$('.rain-recurring-dom input').bind('click.recurringDom',function(e){
var controls = $(this).closest('.controls');
rainRecurringBuildObject(controls);
});
$('.rain-recurring-until').bind('change.recurringUntil',function(e){
var controls = $(this).closest('.controls');
if($(this).find('option:selected').val()!='forever')
controls.find('.rain-recurring-until-x').show();
else
controls.find('.rain-recurring-until-x').hide();
rainRecurringBuildObject(controls);
});
$('.rain-recurring-until-x').bind('change.recurringUntilX',function(e){
var controls = $(this).closest('.controls');
rainRecurringBuildObject(controls);
});
$('.rain-recurring-public-holidays input').bind('click.recurringPublicHolidays',function(e){
var controls = $(this).closest('.controls');
rainRecurringBuildObject(controls);
});
$('.rain-recurring-business input').bind('click.recurringBusiness',function(e){
var controls = $(this).closest('.controls');
rainRecurringBuildObject(controls);
});
$('.rain-recurring-else').bind('change.recurringElse',function(e){
var controls = $(this).closest('.controls');
rainRecurringBuildObject(controls);
});
});
|
/* since we want to use return and console.log in this case,
I want to use return for the first two and console.log in
the next two. Last will need a conditional workflow management system*/
//1) receives one argument and returns it in all caps1
function shout (input) {
return input.toUpperCase();
}
//2) receives one argument and returns it in all lowercase
function whisper (input) {
return input.toLowerCase();
}
//3) calls console.log() its one argument in all caps
function logShout (input) {
console.log(input.toUpperCase());
}
//4) calls console.log() its one argument in all lowercase
function logWhisper (input) {
console.log(input.toLowerCase());
}
//5) returns "I can't hear you!" if `string` is lowercase
//6) returns "YES INDEED!" if `string` is uppercase
//7) returns "I love you, too." if `string` is "I love you, Grandma."
function sayHiToGrandma (input) {
if (input === "I love you, Grandma.") {
return "I love you, too."
}
else if (input === input.toUpperCase()) {
return "YES INDEED!"
}
else {
return "I can't hear you!"
}
}
|
/*******************************************
* Author: Jonathan Perry
* Date: 12/03/17
* Assignment: CS 340 - Project
*******************************************/
function updateBook(isbn){
$.ajax({
url: '/books/' + isbn,
type: 'PUT',
data: $('#update-book').serialize(), // #update-book: this is our form.
// serialize() encodes a set of form elements as a string
success: function(result){
window.location.replace("./"); // navigate back to the previous page
}
})
};
|
import styled from 'styled-components';
export const Container = styled.div`
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 15px;
`;
export const BoxId = styled.div`
width: 120px;
height: 50px;
font-size: 20px;
font-weight: bold;
display: grid;
place-content: center;
color: #000000;
border-radius: 10px;
background-image: linear-gradient(to right, #e2f3ff 50%, #9dd8ff);
box-shadow: inset 0 0 10px #000000;
`;
export const CircleDisgn = styled.div`
width: 30px;
height: 30px;
border: 3px solid #3eaffa;
border-radius: 50px;
background-image: ${({ color }) =>
!color
? 'linear-gradient(to right, #71e045 50%, #30a103)'
: 'linear-gradient(to right, #fff1b5 50%, #ffd000)'};
box-shadow: 0 0 10px #000000;
`;
|
import { compareNumbers } from './utils.js';
// import functions and grab DOM elements
const btn = document.getElementById('btn');
// initialize state
let targetNumber = Math.floor(Math.random() * 20) + 1;
const userGuess = document.getElementById('input');
const message = document.getElementById('message');
const resetBtn = document.getElementById('reset-btn');
const frog = document.getElementById('frog');
let guessesRemaining = 4;
//console.log(targetNumber);
// set event listeners
btn.addEventListener('click', ()=>{
const userGuessNum = Number(userGuess.value);
guessesRemaining--;
frog.textContent = `You have ${guessesRemaining} guesses left`;
compareNumbers(resetBtn, btn, message, targetNumber, userGuessNum);
if (guessesRemaining === 0 && userGuessNum !== targetNumber) {
message.textContent = 'You are all out of guesses! Game Over!';
btn.disabled = true;
resetBtn.style.visibility = 'visible';
}
//console.log(guessesRemaining);
});
resetBtn.addEventListener('click', ()=>{
btn.disabled = false;
resetBtn.style.visibility = 'hidden';
guessesRemaining = 4;
targetNumber = Math.floor(Math.random() * 20) + 1;
message.textContent = '';
userGuess.value = '';
frog.textContent = `You have ${guessesRemaining} guesses left`;
});
//alert('')
//Math.floor(Math.random()*100);
|
// Esse é um comentário de linha
console.log('Olá Mundo') // Aqui tem outro comentário
// Todo comentário é ignorado pelo motor do JS
/*
Esse é um comentario de bloco de código
Nele podemos comentar várias linhas
*/
|
const env = process.env
const Sequelize = require('sequelize')
const sequelize = new Sequelize(
env.DB_NAME,
env.DB_USER,
env.DB_PASSWORD,
{
host: env.DB_HOST,
port: env.DB_PORT,
dialect: 'mysql',
define: {
underscored: true
},
logging: false
}
)
var db = {};
db.Sequelize = Sequelize
db.sequelize = sequelize
//Models
db.account = require('./account')(sequelize, Sequelize)
db.coinmarketcapTick = require('./coinmarketcap_tick')(sequelize, Sequelize)
db.scanProfile = require('./scan-profile')(sequelize, Sequelize)
db.trigger = require('./trigger')(sequelize, Sequelize)
db.bookmark = require('./bookmark')(sequelize, Sequelize)
db.bookmarkNotification = require('./bookmark-notification')(sequelize, Sequelize)
//account scan bookmarks
db.account.hasMany(db.bookmark)
db.bookmark.belongsTo(db.account)
db.bookmark.belongsTo(db.scanProfile)
db.bookmark.belongsTo(db.trigger)
//bbokmark notifications
db.bookmark.hasMany(db.bookmarkNotification)
db.bookmarkNotification.belongsTo(db.bookmark)
module.exports = db;
|
/***************************************************
* 时间: 7/17/16 10:33
* 作者: zhongxia
* 说明: 数值加减器
***************************************************/
//加载依赖的脚本和样式
(function () {
/**
* 获取当前脚本的目录
* @returns {string}
*/
function getBasePath() {
//兼容Chrome 和 FF
var currentPath = document.currentScript && document.currentScript.src || '';
var paths = currentPath.split('/');
paths.pop();
return paths.join('/');
}
Util.loadCSS(getBasePath() + '/CNumber.css');
})()
function CNumber(selector, config) {
this.selector = selector;
config = config || {};
this.maxVaule = config.maxValue || 200; //最大比例
this.minValue = config.minValue || 25; //最小比例
this.defaultValue = config.defaultValue || 100; //默认值
this.val = config.val; //当前值
this.step = config.step || 25; //步长
this.pointSelector = config.pointSelector || ''; //关联的点读点选择器
this.flag = config.flag || false; //是否需要添加修改的标识
this.canInput = config.canInput || false; //是否可以双击手动输入
this.callback = config.callback; //改变值之后 回调
this.render();
}
/**
* 渲染页面, 绑定事件,初始化变量
*/
CNumber.prototype.render = function () {
var html = this.initHTML();
$(this.selector).html(html);
this.init();
this.setColor();
if (this.flag) {
this.setFlag();
}
}
/**
* 初始化HTML页面
*/
CNumber.prototype.initHTML = function () {
var html = "";
html += '<div class="c-number">'
html += ' <div class="c-number-val">' + (this.val || this.defaultValue) + '</div>'
html += ' <div class="c-number-op">'
html += ' <div class="c-number-op-plus">+</div>'
html += ' <div class="c-number-op-sub">-</div> '
html += ' </div>'
html += '</div>'
return html;
}
/**
* 初始化组件
*/
CNumber.prototype.init = function () {
var that = this;
this.$container = $(this.selector);
this.$val = this.$container.find('.c-number-val')
this.$plus = this.$container.find('.c-number-op-plus');
this.$sub = this.$container.find('.c-number-op-sub');
this.$pointSelector = $(this.pointSelector);
if (this.canInput) {
//双击,可以输入值
this.$val.on('click', function (e) {
that.$val.attr('contenteditable', true);
})
this.$val.on('keydown', function (e) {
if (e.keyCode === 13) {
var val = parseInt(that.$val.text());
that.setVal(val);
that.$val.removeAttr('contenteditable');
that.callback && that.callback(val);
}
})
this.$val.on('blur', function () {
var val = parseInt(that.$val.text());
that.setVal(parseInt(that.$val.text()));
that.$val.removeAttr('contenteditable');
that.callback && that.callback(val);
})
}
//点击加号处理
this.$plus.on('click', function (e) {
e.stopPropagation();
that.val = parseInt(that.$val.text()) || that.defaultValue;
that.val += that.step;
that.val = that.val >= that.maxVaule ? that.maxVaule : that.val;
that.callback && that.callback(that.val)
that.setColor();
that.setFlag();
})
//点击减号处理
this.$sub.on('click', function (e) {
e.stopPropagation();
that.val = parseInt(that.$val.text()) || that.defaultValue;
that.val -= that.step;
that.val = that.val <= that.minValue ? that.minValue : that.val;
that.callback && that.callback(that.val)
that.setColor();
that.setFlag();
})
}
/**
* 设置数值的颜色和值
*/
CNumber.prototype.setColor = function () {
this.setVal(this.val);
}
/**
* 设置数值的颜色, 绿色为- , 橙色为+
*/
CNumber.prototype.setVal = function (val) {
val = val > this.maxVaule ? this.maxVaule : val;
val = val < this.minValue ? this.minValue : val;
this.val = val;
this.$val.text(val)
this.$val
.removeClass('val-sub')
.removeClass('val-default')
.removeClass('val-plus');
if (val > this.defaultValue) {
this.$val.addClass('val-plus')
}
else if (val == this.defaultValue) {
this.$val.addClass('val-default')
}
else {
this.$val.addClass('val-sub')
}
}
/**
* [提供给外部使用]
* 设置数值的颜色, 绿色为- , 橙色为+
* @param $selector 展示值的div
* @param val 值
*/
CNumber.prototype.setColorOut = function ($selector, val) {
var defaultValue = 100;
$selector.text(val);
$selector
.removeClass('val-sub')
.removeClass('val-default')
.removeClass('val-plus');
if (val > defaultValue) {
$selector.addClass('val-plus')
}
else if (val == defaultValue) {
$selector.addClass('val-default')
}
else {
$selector.addClass('val-sub')
}
}
/**
* 设置标识, 标识已经对单个点读点修改过了
*/
CNumber.prototype.setFlag = function () {
this.$pointSelector && this.$pointSelector.attr('data-change', 1) //标记已经修改单个点读点的大小
this.$val && this.$val.attr('data-change', 1);//显示值的div,也加上标识
}
|
function ChangeToTest(){
location.href = "Preguntas/Introduccion.html";
}
function ChangeToConcentrate(){
location.href = "Concentrate/Introduccion.html";
}
|
const baseURL = "https://api.mtb-connect.com:8080";
// const baseURL = "http://127.0.0.1:8000";
export default {
getUsersWithTrails(trailId) {
return fetch(
`${baseURL}/trailusers?trailId=${trailId}`
).then(resp => resp.json());
},
addUserWithTrail(newUser) {
return fetch(`${baseURL}/trailusers`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(newUser)
}).then(resp => resp.json());
},
deleteUserWithTrail(id) {
return fetch(`${baseURL}/trailusers/${id}`, {
method: "DELETE"
});
},
updateUser(updatedUser, userId) {
return fetch(`${baseURL}/users/${userId}`, {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(updatedUser)
})
},
getUser(userId) {
return fetch(`${baseURL}/users/${userId}`).then(resp => resp.json())
}
};
|
import * as firebase from "firebase/app";
import React, { useEffect, useState } from "react";
import "./App.css";
export default function App() {
const [user, setUser] = useState();
useEffect(() => {
firebase.auth().onAuthStateChanged(userData => {
if (userData) {
setUser(userData);
} else {
setUser(null);
}
});
}, []);
const [songs, setSongs] = useState();
useEffect(() => {
if (user) {
// 1. If the user is defined then perform the query
return (
firebase
.firestore()
.collection("songs")
// 2. Query documents with userId equal the current user uid
.where("userId", "==", user.uid)
.onSnapshot(songs => setSongs(songs.docs))
);
} else if (songs) {
// 3. If the user is signed out, clear the fetched songs
setSongs(undefined);
}
// 4. Use the current user uid as the hook dependency
}, [user?.uid]);
if (user === undefined) {
return <div className="App">Loading...</div>;
} else if (user === null) {
return (
<div className="App">
<h1>Please sign in</h1>
<button
onClick={() => {
const provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider);
}}
>
Sign in with Google
</button>
</div>
);
} else {
return (
<div className="App">
<div>
Signed in as {user.email} |{" "}
<button onClick={() => firebase.auth().signOut()}>Sign out</button>
</div>
<h1>My Favourite Tame Impala Songs</h1>
<ul>
{songs
? songs.map(song => {
const data = song.data();
return (
<li key={song.id}>
{song.data().title}{" "}
<input
value={data.rating}
onChange={e =>
song.ref.update({ rating: parseInt(e.target.value) })
}
type="number"
min="0"
max="100"
required
/>{" "}
<button
onClick={e => {
e.preventDefault();
const confirmDelete = window.confirm(
`Do you want to remove ${data.input}?`
);
confirmDelete && song.ref.delete();
}}
>
Remove
</button>
</li>
);
})
: "Loading..."}
</ul>
<h2>Add new song:</h2>
<form name="song" onSubmit={handleSubmit}>
<p>
<label>
Title: <input name="title" required />
</label>
</p>
<p>
<label>
Rating:{" "}
<input name="rating" type="number" min="0" max="100" required />
</label>
</p>
<p>
<button type="submit">Add to chart!</button>
</p>
</form>
</div>
);
}
}
async function handleSubmit(e) {
e.preventDefault();
const form = e.target;
const title = form.title.value;
const rating = parseInt(form.rating.value);
const firestore = firebase.firestore();
firestore.collection("songs").add({ title, rating });
form.reset();
}
|
function countChar(str) {
var output = {
};
var x = 0
for(i = 1; i < str.length; i++) {
if (str[0] === str[i]) {
x++
} else {}
}
output.push(x);
str.spice(0,1);
}
console.log(countChar("test"))
|
function CheckIE()
{
var Browser;
Browser = navigator.userAgent;
if (Browser.indexOf("Trident") == -1)
{
}
else
{
window.alert("It looks like you're using Internet Explorer! The tool will only work in Mozilla Firefox or Google Chrome.")
}
}
window.onload = CheckIE()
|
var express=require('express');
var router=express.Router();
var User=require('../models/userModel');
var Ques=require('../models/quesModel');
var bodyParser=require('body-parser');
router.use(bodyParser.json());
//post question into database
router.route('/question')
.post(function(req,res,next){
req.body.username=req.session.user.username;
var tags=[];
var str=req.body.tags;
//seprating the tags
var l=0,r=0,x=0 ;
for(var i=0;i<str.length;i++)
{
if(str[i]==' ')
{
if(l<r){
tags[x++]=str.substring(l,r);
}
l=r+1;
}
r++;
}
if(l<r){
tags[x++]=str.substring(l,r);
}
//removing duplicacy in tags
tags.sort();
let j=0;
for(let i=0;i<tags.length-1;i++){
if(tags[i]!=tags[i+1])
tags[j++]=tags[i];
}
tags[j++]=tags[tags.length-1];
tags.length=j;
req.body.tags=tags;
console.log(req.body);
//Put the tags in user database
User.findOne({_id:req.session.user._id},function(err,user){
if(err) throw err;
else{
tags=tags.concat(user.tags);
tags.sort();
let j=0;
for(let i=0;i<tags.length-1;i++){
if(tags[i]!=tags[i+1])
tags[j++]=tags[i];
}
tags[j++]=tags[tags.length-1];
tags.length=j;
User.update({_id:req.session.user._id},{$set:{"tags":tags}},function(err,result){
if(err) throw err;
else console.log(result+2);
});
}
});
// res.redirect('/'+req.session.user.username);
Ques.create(req.body,function(err,result){
if(err) throw err;
else console.log(result);
res.redirect('/'+req.session.user.username);
});
});
//..........x...........................x............................x...............................x................
//post answer into database
router.route('/answer/:username/:id')
.post(function(req,res,next){
// console.log(req.body.answer);
Ques.findOneAndUpdate({_id:req.params.id},{
$push:{
answers:{
answer:req.body.answer,
username:req.session.user.username,
},
}
},function(err,result){
if(err) throw err;
else {
let tags=result.tags;
User.findOne({_id:req.session.user._id},function(err,user){
if(err) throw err;
else{
tags=tags.concat(user.tags);
tags.sort();
let j=0;
for(let i=0;i<tags.length-1;i++){
if(tags[i]!=tags[i+1])
tags[j++]=tags[i];
}
tags[j++]=tags[tags.length-1];
tags.length=j;
User.update({_id:req.session.user._id},{$set:{"tags":tags}},function(err,result){
if(err) throw err;
else console.log(result+3);
});
}
});
res.redirect('/'+req.params.username)
}
});
});
//..............x.......................x......................x.......................x.....................x.......
//increment likes of question using ajax
router.route('/queslikes/:quesId')
.post(function(req,res,next){
console.log(req.body);
Ques.findOne({_id:req.params.quesId,likedBy:req.session.user.email},function(err,user){
if(err) throw err;
if (!user){
Ques.update({_id:req.params.quesId},{$inc:{likes:1},$push:{likedBy:req.session.user.email}},function(err,result){
if(err) throw err;
else{
res.json({inc:1});
console.log(result);
}
});
}
else{
Ques.update({_id:req.params.quesId},{$inc:{likes:-1},$pull:{likedBy:req.session.user.email}},function(err,result){
if(err) throw err;
else{
res.json({inc:0});
console.log(result);
}
});
}
});
});
//.................x..................x.....................x.....................x........................x.......
router.route("/ifquesliked")
.post(function(req,res,next){
Ques.findOne({_id:req.body.quesId,likedBy:req.session.user.email},function(err,result){
if(err) throw err;
if(!result) res.json({liked:0});
else res.json({liked:1});
});
});
//...............x...................x........................x....................x.....................x........
//Submit Comment to question
router.route("/comment")
.post(function(req,res,next){
Ques.findOneAndUpdate({_id:req.body.quesId},{
$push:{
comments:{
comment:req.body.comment,
email:req.session.user.email
}
}
},function(err,result){
if(err) throw err;
else{
let tags=result.tags;
User.findOne({_id:req.session.user._id},function(err,user){
if(err) throw err;
else{
tags=tags.concat(user.tags);
tags.sort();
let j=0;
for(let i=0;i<tags.length-1;i++){
if(tags[i]!=tags[i+1])
tags[j++]=tags[i];
}
tags[j++]=tags[tags.length-1];
tags.length=j;
User.update({_id:req.session.user._id},{$set:{"tags":tags}},function(err,result){
if(err) throw err;
else console.log(result+3);
});
}
});
res.json({"done":1});
}
});
})
//.............x.................x..........................x.......................x.......................
//get username for comments from email
router.route("/getusernamefromemail")
.post(function(req,res,next){
User.findOne({email:req.body.email},function(err,user){
if(err) throw err;
if(user){
res.json({"username":user.username});
}
else{
res.json({"username":"not found"});
}
});
});
//....................x.....................x.........................x......................x................
//increment likes of ques-comment
router.route("/quesCommentLikes")
.post(function(req,res,next){
Ques.findOne({_id:req.body.quesId,["comments."+req.body.commentIndex+".likedBy"]:req.session.user.email},function(err,user){
if(err) throw err;
if(user){
// res.json({"inc":0});
Ques.update({_id:req.body.quesId},{
$inc:{
["comments."+req.body.commentIndex+".likes"]:-1,
},
$pull:{
["comments."+req.body.commentIndex+".likedBy"]:req.session.user.email,
}
},function(err,result){
if(err) throw err;
else res.json({"inc":0});
});
}
else{
Ques.update({_id:req.body.quesId},{
$inc:{
["comments."+req.body.commentIndex+".likes"]:1,
},
$push:{
["comments."+req.body.commentIndex+".likedBy"]:req.session.user.email,
}
},function(err,result){
if(err) throw err;
else res.json({"inc":1});
});
}
});
});
//...................x........................x...........................x.................x...............
//check if user has liked the ques-comment
router.route("/ifQuesCommentliked")
.post(function(req,res,next){
Ques.findOne({_id:req.body.quesId,["comments."+req.body.commentIndex+".likedBy"]:req.session.user.email},function(err,result){
if(err) throw err;
else if(result) res.json({"liked":1});
else res.json({"liked":0});
});
});
//....................x.....................x.........................x......................x................
//increment likes of the answer
router.route("/ansLikes")
.post(function(req,res,next){
Ques.findOne({_id:req.body.quesId,["answers."+req.body.ansIndex+".likedBy"]:req.session.user.email},function(err,user){
if(err) throw err;
if(user){
Ques.update({_id:req.body.quesId},{
$inc:{
["answers."+req.body.ansIndex+".likes"]:-1,
},
$pull:{
["answers."+req.body.ansIndex+".likedBy"]:req.session.user.email,
}
},function(err,result){
if(err) throw err;
else res.json({"inc":0});
});
}
else{
Ques.update({_id:req.body.quesId},{
$inc:{
["answers."+req.body.ansIndex+".likes"]:1,
},
$push:{
["answers."+req.body.ansIndex+".likedBy"]:req.session.user.email,
}
},function(err,result){
if(err) throw err;
else res.json({"inc":1});
});
}
});
});
//...................x........................x...........................x.................x...............
//check if user has liked the answer
router.route("/ifAnsliked")
.post(function(req,res,next){
Ques.findOne({_id:req.body.quesId,["answers."+req.body.ansIndex+".likedBy"]:req.session.user.email},function(err,result){
if(err) throw err;
else if(result) res.json({"liked":1});
else res.json({"liked":0});
});
});
//.................x............................x.......................x.....................x.............
//delete question-comment
router.route("/delete/ques-comment/:id/:comId/:username")
.get(function(req,res,next){
Ques.update({_id:req.params.id},{$pull:{comments:{_id:req.params.comId}}},function(err,result){
if(err) throw err;
else{
console.log(result);
res.redirect("/"+req.params.username);
}
});
});
//..........x......................x.........................x...................x..........................
//delete question
router.route("/delete/ques/:id/:redirectpath")
.get(function(req,res,next){
Ques.remove({_id:req.params.id},function(err,result){
if(err) throw err;
else{
console.log("done");
res.redirect("/"+req.params.redirectpath);
}
});
});
//.................x............................x.......................x.....................x.............
//delete answer
router.route("/delete/ans/:id/:ansId/:username")
.get(function(req,res,next){
Ques.update({_id:req.params.id},{$pull:{answers:{_id:req.params.ansId}}},function(err,result){
if(err) throw err;
else{
console.log(result);
res.redirect("/"+req.params.username);
}
});
});
module.exports=router;
|
// Example of Splash, Login and Sign Up in React Native
// https://aboutreact.com/react-native-login-and-signup/
// Import React and Component
import React from 'react';
import {View, Text, StyleSheet} from 'react-native';
import {Thumbnail, ListItem, List, Left} from 'native-base';
import {
DrawerContentScrollView,
DrawerItemList,
} from '@react-navigation/drawer';
import {store} from '../redux/store';
const CustomSidebarMenu = (props) => {
const state = store.getState();
return (
<View style={stylesSidebar.sideMenuContainer}>
<View style={stylesSidebar.profileHeader}>
<List>
<ListItem avatar>
<Left>
{state.user.data != null && state.user.data.avatar != null && (
<Thumbnail source={{uri: state.user.data.avatar}} />
)}
{state.user.data != null && state.user.data.avatar == null && (
<Thumbnail source={require('../assets/images/profile.png')} />
)}
</Left>
</ListItem>
</List>
<Text style={stylesSidebar.profileHeaderText}>
{state.user.data.name}
</Text>
</View>
<DrawerContentScrollView {...props}>
<DrawerItemList
{...props}
labelStyle={stylesSidebar.drawerItemLabel}
itemStyle={stylesSidebar.sideMenuItem}
/>
</DrawerContentScrollView>
</View>
);
};
export default CustomSidebarMenu;
const stylesSidebar = StyleSheet.create({
sideMenuContainer: {
width: '100%',
height: '100%',
backgroundColor: 'white',
color: 'black',
},
profileHeader: {
paddingTop: 40,
flexDirection: 'row',
backgroundColor: '#f2f2f2',
padding: 15,
textAlign: 'center',
},
profileHeaderText: {
color: 'black',
alignSelf: 'center',
paddingHorizontal: 10,
fontWeight: 'bold',
},
sideMenuItem: {
borderBottomColor: '#dddddd',
borderBottomWidth: 1,
},
drawerItemLabel: {
color: '#0099ff',
},
});
|
var bookshelf = require('../config/bookshelf'),
Joi = require('joi'),
AJSValidationError = require('./errors'),
Setting,
Settings;
Setting = bookshelf.Model.extend({
tableName: 'settings',
validate: {
name: Joi.string()
.error(new Error('name', 'name is required'))
.required(),
value: Joi.any()
.error(new AJSValidationError('value', 'value is required'))
.required()
}
});
Settings = bookshelf.Collection.extend({
model: Setting
});
module.exports = {
Setting: bookshelf.model('Setting', Setting),
Settings: bookshelf.collection('Settings', Settings)
};
|
//console.log(5 <= 5)
// AND
// x and y | result
// true and true | true
// true and false | false
// false and false | false
// false and true | false
var age = 11;
var gender = "m";
// if (age >= 18 && gender == 'm')
// console.log("you can join the game cos you are " +age + " years old")
// else
// console.log("You can go and play at home")
if (age >= 18 && gender == "m") {
console.log("you can play PS5 cos you are " + age + " years old");
} else if (age < 18 && age > 10) {
console.log("you can play PS4 cos you are " + age + " years old");
} else {
console.log("You can go and play at home");
}
|
$(document).ready(function(){
$.cookie.json = true;
$.getJSON("api/menu", function(menu) {
var menu = menu.menu;
$.cookie("menu", menu);
console.log("The menu is" + $.cookie("menu"));
var keys = Object.keys(menu);
console.log(keys);
for(var key in menu){
if(key === "sauces"){
$("#tacoMenu").children("div:nth-child(3)").append("<section id = \"" + key +"\"><table><tr><th>Heat Rating</th></tr></table></section>");
}
else if(key === "vegetables"){
$("#tacoMenu").children("div:nth-child(3)").append("<section id = \"" + key +"\"><table></table></section>");
}
else{
$("#tacoMenu").children("div:nth-child(2)").append("<section id = \"" + key +"\"><table><tr><th>Price</th></tr></table></section>");
}
if(key === "type")
$("#type tbody:nth-child(1)").children().children().before("<th>Fillings</th>");
else if(key === "vegetables")
$("#vegetables table").append("<tr><th>Vegetables</th></tr>");
else
$("#" + key + " tbody:nth-child(1)").children().children().before("<th>" + key[0].toUpperCase() + key.substring(1) + "</th>");
};
for(var i = 0; i < keys.length; i++){
var info = menu[keys[i]];
for(var j = 0; j < info.length; j++){
if(keys[i] === "sauces")
$("#" + keys[i] + " tbody").append("<tr><td class = 'name'>"+ info[j].name + "</td><td>"+ info[j].heatRating + "</td></tr>");
else if(keys[i] === "vegetables")
$("#" + keys[i] + " tbody").append("<tr><td class = 'name'>"+ info[j].name + "</td></tr>");
else
$("#" + keys[i] + " tbody").append("<tr><td class = 'name'>"+ info[j].name + "</td><td>$"+ info[j].price.toFixed(2) + "</td></tr>");
}
}
$("#tacoMenu section").addClass("left");
});
});
|
import axios from 'axios';
import translate from '../Translate';
import * as flash from './flashActions';
import * as projectPanel from './projectPanelActions';
export function getAllProjects() {
return function (dispatch) {
axios.get('/projects')
.then(response => dispatch({
type: 'PROJECTS_GET_ALL_SUCCESS',
data: {
projects: response.data
}
}))
.catch(error => dispatch({
type: 'PROJECTS_GET_ALL_ERROR',
data: {}
}));
};
}
export function saveProject(project, isNew) {
return function (dispatch) {
dispatch({
type: isNew ? 'PROJECTS_ADD_NEW_SUCCESS' : 'PROJECTS_UPDATE_SUCCESS',
data: {
project: project
}
});
let body = isNew ? 'Projekt ":project:" został utworzony' : 'Projekt ":project:" został zaktualizowany';
dispatch(flash.success({
body: translate(body, [{ what: 'project', to: project.name }])
}));
};
}
export function deleteProject(project) {
return function (dispatch) {
axios.delete('/projects/' + project.id)
.then(response => {
if (response.data.status === 'ok') {
_deleteSuccess(dispatch, project);
dispatch(projectPanel.hidePanelIfCurrent(project));
dispatch(flash.warning({
body: translate('Projekt ":project:" został usunięty', [{ what: 'project', to: project.name }])
}));
} else {
_deleteError(dispatch, project);
dispatch(flash.error({
body: response.data.error
}));
}
})
.catch(error => {
_deleteError(dispatch, project);
dispatch(flash.error({
body: translate('Wystąpił błąd i projekt ":project:" nie został usunięty', [{ what: 'project', to: project.name }])
}));
});
};
}
function _deleteSuccess(dispatch, project) {
dispatch({
type: 'PROJECTS_DELETE_SUCCESS',
data: {
project: project
}
});
}
function _deleteError(dispatch, project) {
dispatch({
type: 'PROJECTS_DELETE_ERROR',
data: {
project: project
}
});
}
|
/* This is a comment */
function askQuestions() {
var firstName = prompt ('What is your first name');
var lastName = prompt ('What is your last name');
var fullName = firstName + ' ' + lastName;
console.log('User is called ' + fullName);
var userAge = prompt('How old are you?')
userAge = parseInt(userAge);
if (userAge <= 18) {
console.log('User is an adult.');
} else if (userAge >= 13) {
console.log('User is a teenager.');
} else {
console.log('User is a child');
}
// if the users first name is 'General and their last name is NOT assembly' then greet the general
if (firstName == "General" && lastName != "Assembly") {
console.log('welcome general');
}
}
// when the page has loaded
$(function() {
// When the user clicks the image, ask questions
&('img').on('click', askQuestions);
// When the user clicks an h3
$('h3').on('click', function() {
// Hide the next element
$(this).next().slideToggle(50);
});
});
|
angular.module('speakEasy', [
'ngMaterial',
'ui.router',
'starter.home' //should need as a separate module
])
.config( function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('/', {
redirectTo: '/landing'
})
.state('home', {
url: '/home',
templateUrl: '/home/home.html',
controller: 'HomeCtrl'
})
.state('landing', {
url: '/landing',
templateUrl: '/landing/landing.html',
controller: 'LandingCtrl'
})
.state('about', {
url: '/about',
templateUrl: '/about/about.html',
controller: 'AboutCtrl'
})
})
.factory('AttachTokens', function ($window,user,$rootScope) {
var attach = {
request: function (object) {
var jwt = $rootScope.authToken;
if (jwt) {
object.data['x-access-token'] = jwt;
}
object.headers['Allow-Control-Allow-Origin'] = '*';
return object;
}
};
return attach;
})
|
import Link from "next/link";
import Image from "next/image";
//export default function Nav() {
//return (
const Navbar = () => {
return (
<div className="py-12">
<nav className="bg-red-200 shadow-md z-10 py-4 fixed top-0 inset-x-0 rounded-b-xl">
<div className="max-w-5xl px-4 mx-auto">
<div className="flex justify-between">
<div className="flex items-center space-x-12 md:mx-auto">
{/* Home */}
<div className="">
<Link href="/">
<a className="hover:animate-pulse">
<Image
src="/assets/lg-joanita-hor-180x68.svg"
alt="Joanita Festa com Arte"
width={180}
height={68}
/>
</a>
</Link>
</div>
{/* */}
<div className="flex">
<div className="hidden md:flex space-x-6 justify-around font-nunito font-light text-gray-800">
{/* Home */}
<div className="">
<Link href="/">
<a className="hover:text-red-700 hover:font-bold">
<h3>Home</h3>
</a>
</Link>
</div>
{/* */}
{/* Quem Somos */}
<div className="">
<Link href="/quem-somos">
<a className="hover:text-red-700 hover:font-bold">
<h3>Quem Somos</h3>
</a>
</Link>
</div>
{/* */}
{/* Depoimentos */}
{/* <div className="">
<Link href="/depoimentos">
<a className="hover:text-red-700">
<h3>Depoimentos</h3>
</a>
</Link>
</div> */}
{/* */}
</div>
</div>
</div>
{/* Mobile Button */}
<div className="md:hidden flex items-center">
<button id="mobile-menu-button">
<Image src="/assets/menu-burger.svg" width={22} height={20} />
</button>
</div>
</div>
{/* Menu Mobile */}
<div
id="mobile-menu"
className="hidden md:hidden flex justify-between space-x-2 text-xs mt-4 font-nunito"
>
<div className="">
<Link href="/">
<a className="hover:text-red-700">
<h3>Home</h3>
</a>
</Link>
</div>
{/* */}
{/* Quem Somos */}
<div className="">
<Link href="/quem-somos">
<a className="hover:text-red-700">
<h3>Quem Somos</h3>
</a>
</Link>
</div>
{/* */}
{/* depoimentos */}
<div className="">
<Link href="/depoimentos">
<a className="hover:text-red-700">
<h3>Depoimentos</h3>
</a>
</Link>
</div>
{/* */}
</div>
</div>
</nav>
</div>
);
};
export default Navbar;
if (typeof window !== "undefined") {
const btn = document.getElementById("mobile-menu-button");
const menu = document.getElementById("mobile-menu");
btn.addEventListener("click", () => {
menu.classList.toggle("hidden");
});
}
|
import React from 'react';
import Header from './Header'
import Deathmatch from './Deathmatch'
export default () => (
<>
<Header />
<Deathmatch />
</>
)
|
var age = parseInt(prompt("¿Cuál es tu edad?")); //23
// convirtiendo edad a segundos
var ageInSeconds = age*365*24*60*60;
//mostrando edad en la red
document.write("Tu edad es "+ age + " y en segundos sería " + ageInSeconds);
|
export default class ProductoHorarioItem {
IdHorario;
IdProducto;
dia;
horaIni;
horaFin;
fechaIni;
fechaFin;
dias_mes_venta;
activo;
//calculados
tipo;
//CONSTANTES
static POR_DIA_SEMANA = 1;
static TODOS_LOS_DIAS = 3;
static POR_DIA_MES = 2;
static DIAS = ['Domingo','Lunes','Martes','Miercoles','Jueves','Viernes','Sabado']
constructor(IdProducto = null, IdHorario = null, dia = 7, horaIni = '00:00:00', horaFin = '23:59:00', fechaIni = ProductoHorarioItem.getDate(), fechaFin = '2099-12-31', dias_mes_venta = 0, activo = 1) {
this.IdHorario = IdHorario;
this.IdProducto = IdProducto;
this.dia = dia;
this.horaIni = horaIni;
this.horaFin = horaFin;
this.fechaIni = fechaIni;
this.fechaFin = fechaFin;
this.dias_mes_venta = dias_mes_venta;
this.activo = activo;
//calcular tipo:
if(dia!==null && (dia === 7)){
this.tipo = ProductoHorarioItem.TODOS_LOS_DIAS
}else if(dia!==null && (0<= dia && dia<7)){
this.tipo = ProductoHorarioItem.POR_DIA_SEMANA
}else if(dias_mes_venta !== null && (1 <= dias_mes_venta && dias_mes_venta <=31)){
this.tipo = ProductoHorarioItem.POR_DIA_MES
}else{ //default
this.tipo = ProductoHorarioItem.TODOS_LOS_DIAS
}
}
isCreated(){
return this.IdHorario && this.IdHorario >0
}
static FromInput(e){
return new ProductoHorarioItem(e.IdProducto, e.IdHorario, e.dia, e.horaIni, e.horaFin, e.fechaIni, e.fechaFin, e.dias_mes_venta, e.activo);
}
crearParametro(idDelivery,IdSucursal){
return{
cliente_id: idDelivery,
sucursal_id: IdSucursal,
IdHorario:this.IdHorario,
IdProducto:this.IdProducto,
dia:(this.tipo === 1)?this.dia:((this.tipo===3)?7:8),
horaIni:this.horaIni,
horaFin:this.horaFin,
fechaIni:this.fechaIni,
fechaFin:this.fechaFin,
dias_mes_venta:(this.tipo === 2)?this.dias_mes_venta:0,
activo:this.activo,
}
}
toStringDia(){
return ProductoHorarioItem.DIAS[this.dia];
}
static getDate(){
const d = new Date()
return d.getFullYear() + "-" + ('0'+(d.getMonth()+1)).substr(-2) + "-" + ('0'+d.getDate()).substr(-2);
}
static formatFecha(d){
return d.getFullYear() + "-" + ('0'+(d.getMonth()+1)).substr(-2) + "-" + ('0'+d.getDate()).substr(-2) + " " +
('0'+d.getHours()).substr(-2) + ":" + ('0'+d.getMinutes()).substr(-2);
}
static construir(){
return new ProductoHorarioItem()
}
constructorIdProducto(id){
this.IdProducto = id;
return this
}
}
|
var express = require('express');
var router = express.Router();
var axios = require("axios");
//require request and cheerio to scrape
// var request = require('request');
var cheerio = require('cheerio');
//Require models
var db = require("../models");
// var Article = require('../models/scrape.js');
console.log("inside scrape controller");
//index
router.get("/", function (req, res) {
db.Article.find({}).then(function (list) {
var dbdetail = {
data: list
};
res.render("index", dbdetail);
});
});
router.get("/remove/:test",function(req,res){
return db.Article.deleteOne({_id:req.params.id}).then(function(data1){
}).
catch(function(err){
res.json(err);
});
});
router.get("/scrape", function (req, res) {
axios.get("https://www.indeed.com/jobs?q=full-stack+developer&l=Austin%2C+TX&radius=50").then(function (response) {
// Then, we load that into cheerio and save it to $ for a shorthand selector
var $ = cheerio.load(response.data);
var results = [];
// Now, we grab every h2 within an article tag, and do the following:
$("div.title").each(function (i, element) {
title = $(element).children("a").attr("title");
link = "https://indeed.com" + $(element).children("a").attr("href");
// Save these results in an object that we'll push into the results array we defined earlier
results.push({
title: title,
link: link
});
});
// Create a new Article using the `result` object built from scraping
db.Article.create(results)
.then(function (dbArticle) {
// View the added result in the console
if (dbArticle) {
var hbsObject = {
data: dbArticle
};
console.log(hbsObject);
res.redirect("/");
} else {
console.log("Object is null");
}
});
});
});
router.get("/clear", function (req, res) {
console.log("inside the controller");
db.Article.deleteMany({}).then(function (deletedata) {
console.log("clear the collection in the database");
res.redirect("/");
});
});
router.get("/savejob/:id", function (req, res) {
console.log("inside the savejob of controller");
var db1 = new db.Article();
var id = req.params.id;
console.log(id);
// db1.getsavedArticle();
db.Article.findOneAndUpdate({
_id: req.params.id
}, {
savedArticle: true
}, {
new: true
}).then(function (updated) {
if (updated)
console.log("finished the save job controller",updated);
});
});
// Send a message to the client
router.get("/saved", function (req, res) {
console.log("inside the display");
var dbdetail;
db.Article.find({savedArticle:true}).then(function (list) {
dbdetail = {
data: list
};
// console.log(dbdetail);
res.render("saved", dbdetail);
});
});
router.get("/edit/:id", function (req, res) {
console.log("inside the edit");
console.log(req.params.id);
db.Article.find({_id:req.params.id}).populate("note").then(function (list) {
res.json(list);
}).catch(function(err){
res.json(err);
});
});
router.post("/savecomment", function (req, res) {
console.log("inside the save Comment");
console.log("req.body.id::::::"+req.body.id);
var noteObj={
title: req.body.title,
body: req.body.comment
};
console.log("req.body.title"+req.body.title);
console.log("req.body.comment"+req.body.comment);
db.Note.create(noteObj)
.then(function(dbNote) {
return db.Article.findOneAndUpdate({ _id: req.body.id }, { note: dbNote._id }, { new: true });
}).then(function(dbArticle) {
res.json(dbArticle);
})
.catch(function(err) {
// If an error occurred, send it to the client
res.json(err);
});
});
// });
// });
//
module.exports = router;
|
import React, { Component } from 'react';
import { product } from '../product';
export default class ShowShop extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
};
}
// handles form submission
componentDidMount() {
let inventoryUrl = `http://localhost:3030/inventory`;
// fetch call to retrieve inventory from the backend.
fetch (inventoryUrl)
.then(r => r.json() )
.then((json) => {
console.log("Data from fetch", json);
this.setState({items: json});
})
}
render() {
let match = this.props.match;
let category = match.params.id;
let shopItems = this.state.items.map((shopItem) => {
return (
<div className="shopResult" key={shopItem.id}>
<img className="shopImg" src={shopItem.img} />
<div className="shopDesc">
<p className="cost">{shopItem.price}</p>
<p className="desc">{shopItem.description}</p>
</div>
</div>
)
})
return (
<div>
{shopItems}
<div className="inventoryItem">
</div>
</div>
);
}
}
|
function mainButton(){
var newUrl = "../index.html"
document.location.href = newUrl
console.log('Received Event:');
}
function searchButton(){
var newUrl = "../html/test.html"
document.location.href = newUrl
console.log('Received Event:');
}
function messageButton(){
var newUrl = "../html/panel.html"
document.location.href = newUrl
console.log('Received Event:');
}
function mapButton(){
var newUrl = "../html/map.html"
document.location.href = newUrl
console.log('Received Event:');
}
function trashButton(){
var newUrl = "../html/toDoList.html"
document.location.href = newUrl
console.log('Received Event:');
}
|
import Vue from 'vue'
import VueResource from 'vue-resource'
import {API_ROOT} from '../config'
var auth = require("../utils/auth");
Vue.use(VueResource)
// HTTP相关
Vue.http.options.crossOrigin = true
Vue.http.options.xhr = {withCredentials: true}
Vue.http.interceptors.push(function(request,next){
// 这里对请求体进行处理
request.headers = request.headers || {}
if (auth.getCookie('token')) {
request.headers.Authorization = 'Bearer ' + auth.getCookie('token').replace(/(^\")|(\"$)/g, '')
}
next(function (response) {
// 这里可以对响应的结果进行处理
if (response.status === 401) {
auth.signOut();
console.info("err");
//window.location.pathname = '/login'
}
})
})
export const testResource = Vue.resource(API_ROOT + '/test{/act}')
export const workResource = Vue.resource(API_ROOT + '/work{/act}')
export const serverResource = Vue.resource(API_ROOT + '/server{/act}')
export const authResource = Vue.resource(API_ROOT + '/auth{/act}')
export const userResource = Vue.resource(API_ROOT + '/user{/act}')
|
var trex,gamestate="play";
var obsGroup;
var cloudGroup;
var score=0;
var touches=[];
function preload(){
trex1=loadAnimation("trex1.png","trex3.png","trex4.png");
ground1=loadImage("ground2.png");
cloud1=loadImage("cloud.png");
obstacle=loadImage("obstacle1.png");
obstacle2=loadImage("obstacle2.png");
obstacle3=loadImage("obstacle3.png");
obstacle4=loadImage("obstacle4.png");
obstacle5=loadImage("obstacle5.png");
obstacle6=loadImage("obstacle6.png");
restartbutton=loadImage("restart.png");
trexCollider=loadImage("trex_collided.png");
GameOver= loadImage("gameOver.png");
Checkpoint=loadSound("checkPoint.mp3");
Die=loadSound("die.mp3");
Jump=loadSound("jump.mp3");
}
function setup() {
createCanvas(windowWidth,windowHeight);
trex=createSprite (100,height/2,40,70);
trex.addAnimation("t",trex1);
trex.addAnimation("c",trexCollider);
trex.scale= 0.5;
//trex.debug=true;
ground2= createSprite(width/2,height-40,width,10);
//trex.setCollider("circle",0,20,30);
trex.setCollider("rectangle",0,0,30,70,30);
//ground2.shapeColor = 220;
ground2.visible=false;
ground=createSprite(width/2,height-44,400,20);
ground.addImage(ground1);
ground.velocityX = -6;
obsGroup=new Group();
cloudGroup=new Group();
restart= createSprite(width/2,height/2);
restart.addImage(restartbutton);
restart.scale = 0.5;
Overgame= createSprite(width/2+20,height/2+30);
Overgame.addImage(GameOver);
Overgame.scale = 0.5;
}
function draw() {
background("white");
if(gamestate=="play"){
trex.changeAnimation("t",trex1);
if(ground.x<0){
ground.x=200;
}
if(score%200==0){
ground.velocityX=ground.velocityX-1;
obsGroup.setVelocityXEach(ground.velocityX);
//console.log(ground.velocityX);
Checkpoint.play();
}
restart.visible=false;
Overgame.visible=false;
//console.log(touches)
if((keyDown(UP_ARROW))&& trex.y>height-100){
trex.velocityY = -10;
Jump.play();
console.log(touches)
touches=[];
}
score= score+1;
trex.velocityY = trex.velocityY + 0.4;
trex.collide(ground2);
if(frameCount%40==0){//frameCount divisible by 10
var R = Math.round(random(height/8,height/2));
cloud=createSprite(width+20,R);
cloud.addImage(cloud1);
cloud.velocityX = -3;
cloud.depth = 0.5;
//console.log("clouds",cloud.depth);
cloudGroup.add(cloud);
cloud.lifetime = 190;
}
if(frameCount%80==0){//frameCount divisible by 10
var A = Math.round(random(1,6));
var obstacle1 = createSprite(width,height-60);
obsGroup.add(obstacle1);
//obstacle1.addImage(obstacle);
obstacle1.velocityX = -6;
obstacle1.scale = 0.5;
obstacle1.lifetime = 100;
switch(A){
case 1:obstacle1.addImage(obstacle);break;
case 2 :obstacle1.addImage(obstacle2);break;
case 3:obstacle1.addImage(obstacle3);break;
case 4:obstacle1.addImage(obstacle4);break;
case 5:obstacle1.addImage(obstacle5);break;
case 6:obstacle1.addImage(obstacle6);break;
default:break;
}//end of switch
}//end of if obstacle
if(trex.isTouching(obsGroup)){
Die.play();
gamestate="end";
}
}//end of gamestate play
//%(modulus):finds out the remainder
//30%4==2,10%5==0
//random(min,max):produces any number between min and max
if(gamestate=="end"){
trex.changeAnimation("c",trexCollider);
ground.velocityX = 0;
obsGroup.setVelocityXEach(0);
cloudGroup.setVelocityXEach(0);
trex.velocityY = 0;
obsGroup.setLifetimeEach(-1);
cloudGroup.setLifetimeEach(-1);
restart.visible=true;
Overgame.visible= true;
}//end ofgamestate end
if(mousePressedOver(restart)){
gamestate="play";
obsGroup.destroyEach();
cloudGroup.destroyEach();
score= 0;
}
//console.log(trex.y);
//console.log(frameCount);
//console.log(random(1,5));
//console.log(Math.round(2.58455357990));
//console.log(Math.round(random(1,5)));
//console.log(trex.depth);
drawSprites();
textSize(20);
text("score- "+score,120,120);//concatenation
}
|
"use strict";
function loadHeader() {
var headerHTML = "<div class=\"brand mr-md\">\n <a href=\"#\">Gull Vue!</a>\n <small>v1.0.0</small>\n</div>\n<button type=\"button\" class=\"sidebar-toggle btn rounded-circle btn-raised btn-raised-default btn-icon\"\n aria-label=\"Close\">\n <i class=\"ti-menu\"></i>\n <i class=\"ti-close\"></i>\n</button>\n<span class=\"flex-grow-1\"></span>\n<a href=\"http://gull-vue.ui-lib.com/\" class=\"btn btn-link btn-link-secondary mr-md d-none d-sm-block\">Live Preview</a>\n<a href=\"https://github.com/mh-rafi/gull-vue\" class=\"btn btn-link btn-link-secondary mr-md d-none d-sm-block\">Star on\n GitHub</a>\n\n<a href=\"https://github.com/mh-rafi/gull-vue\" class=\"btn btn-raised btn-raised-success\">download</a>\n";
$(".doc-header").html(headerHTML);
// Collapsible sidebar
$(".sidebar-toggle").on("click", function () {
$(".wrapper").toggleClass("sidebar-open");
});
}
|
'use strict';
angular.module('webappV2App')
.provider('Phased', function PhasedProvider() {
// private
var $rootScope,
$http,
$location,
$window,
StatusFactory,
_FBRef,
_FURL,
_appConfig,
_INIT_EVENTS = {
SET_UP : 'Phased:setup',
META_SET_UP : 'Phased:meta',
PROFILE_SET_UP : 'Phased:profileComplete',
TEAM_SET_UP : 'Phased:teamComplete',
MEMBERS_SET_UP : 'Phased:membersComplete',
// TASKS_SET_UP : 'Phased:tasksComplete',
// STATUSES_SET_UP : 'Phased:statusesComplete'
},
_RUNTIME_EVENTS = {
// NB: Phased:login is broadcast immediately after firebase auth
// and therefore before any data has been loaded from the server
LOGIN : 'Phased:login',
LOGOUT : 'Phased:logout',
TEAM_SWITCH : 'Phased:teamSwitch',
STATUS_ADDED : 'Phased:newStatus',
STATUS_CHANGED : 'Phased:changedStatus',
STATUS_DELETED : 'Phased:deletedStatus',
STATUS_DESTROYED : 'Phased:destroyedStatus',
TASK_ADDED : 'Phased:newTask',
TASK_CHANGED : 'Phased:changedTask',
TASK_DELETED : 'Phased:deletedTask',
TASK_DESTROYED : 'Phased:destroyedTask',
PROJECT_ADDED : 'Phased:newProject',
PROJECT_CHANGED : 'Phased:changedProject',
PROJECT_DELETED : 'Phased:deletedProject',
PROJECT_DESTROYED : 'Phased:destroyedProject',
ANNOUNCEMENT_ADDED : 'Phased:newAnnouncement',
ANNOUNCEMENT_CHANGED : 'Phased:changedAnnouncement',
ANNOUNCEMENT_DELETED : 'Phased:deletedAnnouncement'
},
// tasks to do after the indicated events
_toDoAfter = {
SET_UP : [],
META_SET_UP : [],
PROFILE_SET_UP : [],
TEAM_SET_UP : [],
MEMBERS_SET_UP : [],
TASKS_SET_UP : [],
STATUSES_SET_UP : []
},
_CONFIG = {},
_DEFAULTS = {
STATUS_LIMIT : 30,
ANNOUNCEMENTS_LIMIT: 10,
TEAM : {
details : {},
members : {},
statuses : {},
tasks : {},
projects : {},
announcements : {}
}
},
_oldestStatusTime = new Date().getTime(),
_getUTCTimecode;
// public-facing object
var Phased = {
// events
INIT_EVENTS : _INIT_EVENTS,
RUNTIME_EVENTS : _RUNTIME_EVENTS,
// init status flags
SET_UP : false,
LOGGED_IN : false,
META_SET_UP : false,
PROFILE_SET_UP : false,
TEAM_SET_UP : false,
MEMBERS_SET_UP : false,
// TASKS_SET_UP : false,
// STATUSES_SET_UP : false,
meta : {}, // copy of metadata from server. do not overwrite.
authData : false, // copy of authData from firebase authentication callback.
user : {}, // copy of user profile from server with additional uid key
team : angular.copy(_DEFAULTS.TEAM)
}
/*
*
* CONSTRUCTOR
*
* 1. save references to injected services to local var names
* 2. init FB objects
* 3. add event handlers for FB auth and connection states
*/
this.$get = ['$rootScope', '$http', '$location', '$window', 'getUTCTimecode', 'appConfig',
function $get(_$rootScope_, _$http_, _$location_, _$window_, _getUTCTimecode_, _appConfig_) {
$rootScope = _$rootScope_;
$http = _$http_;
$location = _$location_;
$window = _$window_;
_getUTCTimecode = _getUTCTimecode_;
_appConfig = _appConfig_;
Phased._FBRef = _FBRef = new Firebase(_FURL);
// listeners for changes in auth and connection state go here
_FBRef.onAuth(_onAuth);
return Phased;
}];
/*
*
* CONFIG
*
* 1. initialize FBRef
* 2. decide if we're running in 'watch' modes (2-way sync)
* 3. set bounce routes
*/
this.config = function config(prefs = {}) {
return new Promise(function configPromise(fulfill, reject) {
// 1. initialize FBRef
if ('FURL' in prefs) {
_FURL = prefs.FURL;
} else {
// if we don't have firebase our app is dead in the water
console.warn('No Firebase URL set; the Phased app will not run.');
reject();
return;
}
// 2. & 3. --> stash these flags for later usage
_.assign(_CONFIG, prefs);
fulfill();
});
}
/*
*
* INIT
* run after user has logged in
* starts gathering data from server
*/
var _init = function init() {
return new Promise(function initPromise(fulfill, reject) {
console.log('init', Phased);
if (!Phased.META_SET_UP)
_getMeta();
// if the user is logged into a team
if (Phased.authData && Phased.user.currentTeam) {
// initialize the team
if (_CONFIG.WATCH_TEAM)
_watchTeam();
else
_getTeam();
// maybe watch some stuff
if (_CONFIG.WATCH_NOTIFICATIONS)
_watchNotifications();
if (_CONFIG.WATCH_PRESENCE)
_watchPresence();
if (_CONFIG.WATCH_INTEGRATIONS)
_watchIntegrations();
}
fulfill();
});
}
/*
* User has logged out or left the app
* reset PhasedProvider for new _init
*
*/
var _die = function die(source) {
console.log('dying of a ' + source);
// unwatch all events
// team
_FBRef.child(`team/${Phased.team.uid}/details`).off('value'); // team details
_FBRef.child(`team/${Phased.team.uid}/announcements`).off('value'); // announcements
// members
_FBRef.child(`team/${Phased.team.uid}/members`).off('child_added');
_FBRef.child(`team/${Phased.team.uid}/members`).off('child_removed');
_FBRef.child(`team/${Phased.team.uid}/members`).off('child_changed');
for (let uid in Phased.team.members) {
_FBRef.child(`profile/${uid}`).off('value');
}
// 1. user has logged out
if (source.toLowerCase() == 'logout') {
$rootScope.$evalAsync(() => {
// reset all init events
for (let event in _INIT_EVENTS)
Phased[event] = false;
Phased.authData = false;
Phased.LOGGED_IN = false;
Phased.user = {};
Phased.team = angular.copy(_DEFAULTS.TEAM);
// broadcast logout
$rootScope.$broadcast(_RUNTIME_EVENTS.LOGOUT);
});
}
// 2. clean up app before switching teams
else if (source.toLowerCase() == 'team-switch') {
$rootScope.$evalAsync(() => {
// broadcast team switch
// broadcast before blanking team so that die handlers have access to the data they need
$rootScope.$broadcast(_RUNTIME_EVENTS.TEAM_SWITCH);
// reset all init events
for (let event in _INIT_EVENTS) {
if (event !== 'META_SET_UP' && event !== 'PROFILE_SET_UP')
Phased[event] = false;
}
// blank out team
Phased.team = angular.copy(_DEFAULTS.TEAM);
});
}
// 2. normal exit (stash app state here, in localstorage or FB cache key)
else {
}
}
/*
**
** INTERNAL FUNCTIONS
**
*/
//
// ASYNC INTERFACE
//
/*
* Registers a job to be done now or after all events in conditions have happened
*
* eg: _registerAfter('SET_UP', countTo, 5) // will call countTo(5) as soon as Phased.SET_UP
* eg: _registerAfter(['META_SET_UP', 'PROFILE_SET_UP'], countTo, 5) // will call once after both Phased.META_SET_UP and PROFILE_SET_UP have passed
*/
var _registerAfter = function registerAfter(conditions, callback, args) {
// if there is only one condition, make it into an array
if (typeof conditions == 'string')
conditions = [conditions];
// for each condition,
// a) check it is valid
// b) if it's met, remove from remaining conditions to check for
for (var i = conditions.length -1; i >= 0; i--) { // start at end so we can rm els
let event = conditions[i];
if (!(event in _INIT_EVENTS)) {
console.warn(`${event} is not a valid event`);
return;
}
// remove condition if passed
if (Phased[event]) {
conditions.pop(i);
}
}
// if no more conditions remain, do immediately;
if (conditions.length < 1) {
return new Promise((fulfill, reject) => {
callback(args, fulfill, reject);
});
}
// otherwise, register to do after each remaining condition
return new Promise((fulfill, reject) => {
var thisJob = {
callback : callback,
args : args,
fulfill: fulfill,
reject: reject,
conditions: conditions
}
for (var i in conditions) {
let event = conditions[i];
_toDoAfter[event].push(thisJob);
}
});
}
/*
* called to emit a specific event
*
* 1. do all callbacks needing to be done after that event
* only do these if their other conditions have also been met
* 2. set that event's flag to true
* 3. broadcast event through rootScope
*/
var _doAfter = function doAfter(event) {
if (!(event in _INIT_EVENTS)) {
console.warn(`${event} is not a valid event`);
return;
}
$rootScope.$evalAsync(() => {
for (let i in _toDoAfter[event]) {
let job = _toDoAfter[event][i]; // job should be the same object in other locations in _toDoAfter
// check if job has remaining conditions
if (job.conditions.length > 1) {
// more conditions other than this remain; don't do job
// but DO remove own condition (as it has passed)
job.conditions.pop(job.conditions.indexOf(event));
} else {
// no more conditions remain; do job
job.callback(job.args || undefined, job.fulfill, job.reject);
}
}
// clear saved jobs for this event
_toDoAfter[event] = [];
Phased[event] = true;
$rootScope.$broadcast(`${_INIT_EVENTS[event]}`);
_maybeFinalizeSetup();
});
}
/*
* If all _INIT_EVENTS are fired, fire SET_UP
*
*/
var _maybeFinalizeSetup = function maybeFinalizeSetup() {
// do nothing if an event other than SET_UP hasn't passed
// or if SET_UP already passed
if (Phased.SET_UP) return;
for (let event in _INIT_EVENTS) {
if (event != 'SET_UP' && !Phased[event]) return;
}
_doAfter('SET_UP');
}
//
// INTIALIZING FUNCTIONS
//
/*
*
* Gathers all static data, applies to PhasedProvider
*
*/
var _getMeta = function getMeta() {
_FBRef.child('meta').once('value', function(snap) {
_.assign(Phased.meta, snap.val());
_doAfter('META_SET_UP');
});
}
/*
* Gathers team data
*
*/
var _getTeam = function getTeam() {
console.log('getting team...');
var teamID = Phased.team.uid = Phased.user.currentTeam,
props = ['details', 'members', 'statuses'],
completed = [];
var maybeTeamComplete = prop => {
completed.push(prop);
// if props == completed
if (_.xor(props, completed).length == 0)
_doAfter('TEAM_SET_UP');
}
// details
_FBRef.child(`team/${teamID}/details`).once('value', snap => {
_.assign(Phased.team.details, snap.val());
maybeTeamComplete('details');
});
// members
_FBRef.child(`team/${teamID}/members`).once('value', snap => {
_.assign(Phased.team.members, snap.val());
maybeTeamComplete('members');
_getMembers();
});
// statuses (limited)
_FBRef.child(`team/${teamID}/statuses`)
.limitToLast(_DEFAULTS.STATUS_LIMIT).once('value', snap => {
_.assign(Phased.team.statuses, snap.val());
// find oldest status time and save val for pagination
for (var i in Phased.team.statuses) {
if (Phased.team.statuses[i].time < _oldestStatusTime)
_oldestStatusTime = Phased.team.statuses[i].time;
}
_doAfter('STATUSES_SET_UP');
maybeTeamComplete('statuses');
});
}
/*
* Gathers team member profiles
*
*/
var _getMembers = function getMembers() {
var membersCollected = 0,
membersToGet = Object.keys(Phased.team.members).length,
maybeMembersComplete = () => {
membersCollected++;
if (membersCollected == membersToGet)
_doAfter('MEMBERS_SET_UP');
}
for (let uid in Phased.team.members) {
let member = Phased.team.members[uid];
if (uid == Phased.authData.uid) {
_.assign(Phased.team.members[uid].profile, Phased.user);
maybeMembersComplete();
} else {
_FBRef.child(`profile/${uid}`).once('value', snap => {
_.assign(Phased.team.members[uid].profile, snap.val());
maybeMembersComplete();
});
}
}
}
/*
* watches team data
*
*/
var _watchTeam = function watchTeam() {
var teamID = Phased.team.uid = Phased.user.currentTeam,
props = ['details', 'members', 'announcements'],
completed = [],
now = moment.utc().unix();
var maybeTeamComplete = prop => {
if (Phased.TEAM_SET_UP) return;
completed.push(prop);
// if props == completed
if (_.xor(props, completed).length == 0)
_doAfter('TEAM_SET_UP');
}
//
// details
//
_FBRef.child(`team/${teamID}/details`).on('value', snap => {
$rootScope.$evalAsync(() => {
_.assign(Phased.team.details, snap.val());
});
maybeTeamComplete('details');
});
//
// members
// get list of members on team currently
_FBRef.child(`team/${teamID}/members`).once('value', snap => {
_.assign(Phased.team.members, snap.val());
maybeTeamComplete('members');
});
// always keep profile data in sync for any members on team
_FBRef.child(`team/${teamID}/members`).on('child_added', snap => {
let uid = snap.key();
_.assign(Phased.team.members[uid], snap.val());
_watchMember(uid);
});
// delete members from team when removed; also unwatch
_FBRef.child(`team/${teamID}/members`).on('child_removed', snap => {
let uid = snap.key();
_FBRef.child(`team/${teamID}/members/${uid}`).off('value'); // unwatch
$rootScope.$evalAsync(() => {
delete Phased.team.members[uid]; // delete from team
});
});
//
// announcements
//
_FBRef.child(`team/${teamID}/announcements`)
.limitToLast(_DEFAULTS.ANNOUNCEMENTS_LIMIT)
.on('value', snap => {
$rootScope.$evalAsync(() => {
let ann = snap.val();
for (let i in Phased.team.announcements) {
if (!(i in ann))
delete Phased.team.announcements[i];
}
_.assign(Phased.team.announcements, ann);
});
maybeTeamComplete('announcements');
});
}
/*
* Set up data binding for a single member on a team
*
* if MEMBERS_SET_UP hasn't been fired, check if it should be
*/
var _watchMember = function watchMember(uid) {
// set up data binding for members
_FBRef.child(`profile/${uid}`).on('value', snap => {
$rootScope.$evalAsync(() => {
var _newVals = snap.val();
Phased.team.members[uid].profile = Phased.team.members[uid].profile || {};
_.assign(Phased.team.members[uid].profile, _newVals); // add new values
_.forOwn(Phased.team.members[uid].profile, (val, key) => { // remove possibly deleted ones
if (!_newVals.hasOwnProperty(key))
delete Phased.team.members[uid].profile[key];
});
// possibly fire event
if (!Phased.MEMBERS_SET_UP) {
// if any member doesn't have their profile data, don't fire event
for (let i in Phased.team.members) {
if (!Phased.team.members[i].profile) return;
}
_doAfter('MEMBERS_SET_UP');
}
});
});
// always keep profile data in sync for any members on team
_FBRef.child(`team/${Phased.team.uid}/members`).on('child_changed', snap => {
$rootScope.$evalAsync(() => {
var uid = snap.key(), _newVals = snap.val();
_.assign(Phased.team.members[uid], _newVals);
_.forOwn(Phased.team.members[uid], (val, key) => { // remove possibly deleted ones (other than profile)
if (key !== 'profile' && !_newVals.hasOwnProperty(key))
delete Phased.team.members[uid][key];
});
});
});
}
/*
* Set up data binding for a single task on a team
* broadcasts TASK_CHANGED
*/
var _watchTask = function watchTask(uid) {
var teamID = Phased.team.uid;
_FBRef.child(`team/${teamID}/tasks/${uid}`).on('value', snap => {
$rootScope.$evalAsync(() => {
var uid = snap.key(), _newVals = snap.val();
if (!!_newVals) {
_.assign(Phased.team.tasks[uid], _newVals); // add new values
_.forOwn(Phased.team.tasks[uid], (val, key) => { // remove possibly deleted ones
if (!_newVals.hasOwnProperty(key))
delete Phased.team.tasks[uid][key];
});
$rootScope.$broadcast(_RUNTIME_EVENTS.TASK_CHANGED);
} else {
delete Phased.team.tasks[uid];
$rootScope.$broadcast(_RUNTIME_EVENTS.TASK_DELETED);
}
});
});
}
//
// AUTH FUNCTIONS
//
/*
* Similar to the Phased.login callback
*
* 1. stashes user auth data
* 2. saves auth token to default POST request
* 3. broadcast login
* 4. fills user profile data, then calls init
*/
var _onAuth = function onAuth(authData) {
if (authData && 'uid' in authData) {
// 1. stash auth data
Phased.authData = authData;
// 2. use token to authenticate with our server
$http.defaults.headers.post.Authorization = 'Bearer ' + authData.token;
// 3. broadcast login
Phased.LOGGED_IN = true;
$rootScope.$broadcast(_RUNTIME_EVENTS.LOGIN);
// 4.
_fillUserProfile().then(_init);
} else {
// if the user is not logged in, die
_die('logout');
}
}
/*
* Fills logged in user's profile
* called immediately after auth
* broadcasts Phased:profileComplete
*/
var _fillUserProfile = function fillUserProfile() {
return new Promise(function _fillUserProfilePromise(fulfill, reject) {
if (!('uid' in Phased.authData)) {
console.warn('Cannot gather user information; no UID set.');
reject();
return;
}
_FBRef.child('profile/' + Phased.authData.uid).on('value', function (snap) {
$rootScope.$evalAsync(() => {
_.assign(Phased.user, snap.val(), { uid: Phased.authData.uid });
_doAfter('PROFILE_SET_UP');
fulfill();
});
});
});
}
/*
**
** EXTERNAL FUNCTIONS
**
*/
//
// AUTH FUNCTIONS
//
/*
* Log a user in using username and password
*/
Phased.login = function login(email, password) {
return _FBRef.authWithPassword({email: email, password:password});
}
/*
* Logs a user out
*/
Phased.logout = function logout() {
_FBRef.unauth();
}
/*
* Registers a new user using the server API
*/
Phased.registerUser = function registerUser(email, password) {
return new Promise((fulfill, reject) => {
$http.post('api/register/user', {
email : email,
password : password
}).then(res => {
if (res.data.success) {
fulfill(res.data);
} else {
reject(res.data);
}
}, reject);
});
}
/*
* Registers a new team using the server API
*/
Phased.registerTeam = function registerTeam(teamName) {
return new Promise((fulfill, reject) => {
$http.post('api/register/team', {
teamName : teamName,
userID : Phased.user.uid
}).then(res => {
if (res.data.success) {
fulfill(res.data);
} else {
reject(res.data);
}
}, reject);
});
}
/*
* User switches to a different team (already registered)
*/
Phased.switchTeam = function switchTeam(teamID) {
if (!Phased.SET_UP) {
console.log('Cannot switch teams before set up!');
return;
}
_die('team-switch');
_FBRef.child(`profile/${Phased.user.uid}/currentTeam`).set(teamID).then(()=>{
// to be sure
Phased.user.currentTeam = teamID;
_init();
})
}
//
// ANNOUNCEMENTS
//
/**
* Make an announcement to the team
*
* @param {string} name name/title of announcement
* @param {string} description full text of announcment (optional)
* @return {Promise} resolve passed ID of the new announcement
*/
Phased.addAnnouncement = function addAnnouncement(name, description = '') {
return new Promise((fulfill, reject) => {
var data = {
name : name,
description : description,
user : Phased.user.uid,
created : Firebase.ServerValue.TIMESTAMP
}
var newRef = _FBRef.child(`team/${Phased.team.uid}/announcements`).push(data);
var newID = newRef.key();
newRef.then(() => {
fulfill(newID);
}, reject);
});
}
/**
* Edit an announcement
*
* @param {string} ID ID of the announcement to edit
* @param {object} args object with updated name and/or description attributes
*/
Phased.editAnnouncement = function editAnnouncement(ID, args = {}) {
var data = {};
if (args.name)
data.name = args.name;
if (args.description)
data.description = args.description;
if (!ID || typeof ID != 'string') {
throw new Error('ID should be string, got ' + (typeof ID));
}
_FBRef.child(`team/${Phased.team.uid}/announcements/${ID}`).update(data);
}
/**
* Deletes an announcemnet
*
* @param {string} ID ID of the announcement to edit
*/
Phased.deleteAnnouncement = function deleteAnnouncement(ID) {
if (!ID || typeof ID != 'string') {
throw new Error('ID should be string, got ' + (typeof ID));
}
_FBRef.child(`team/${Phased.team.uid}/announcements/${ID}`).remove();
}
})
|
'use strict';
/**
* Adds the passed amount of months to the date and writes the new date and time into the to fields
*
* @requires moment.js
*
* @param months the number of months to add to the from date
* @param pattern the pattern to use for outputting the new date
* @param formName the name of the form to search the input fields in
* @param fromDateName name of the form element containing the from day
* @param fromTimeName name of the form element containing the from time
* @param toDateName name of the form element containing the to day
* @param toTimeName name of the form element containing the to time
*/
function updateDate(months, pattern, formName, fromDateName, fromTimeName, toDateName, toTimeName) {
if (!months) return;
var form = document.forms[formName],
fromDateValue = form.elements[fromDateName].value,
fromTimeValue = form.elements[fromTimeName].value,
toDateField = form.elements[toDateName],
toTimeField = form.elements[toTimeName],
newMonth, toDate, toDateValue;
months = parseInt(months, 10);
if (!fromDateValue) return;
var newDateTo = moment(fromDateValue, pattern.toUpperCase()).add(months,'months');
if (newDateTo.isValid()) {
toDateField.value = newDateTo.format(pattern.toUpperCase());
toTimeField.value = fromTimeValue;
} else {
toDateField.value = '';
toTimeField.value = '';
}
}
|
export default class Keno {
constructor({ n, d, x, y }) {
this.n = n;
this.d = d;
this.x = x;
this.y = y;
this.r = x - y;
}
factorial(num) {
var array = [];
for (var i = 1, res = 1; i < num; array[i - 1] = i, res *= ++i);
return res;
}
combination(n, r) {
return this.factorial(n) / (this.factorial(n - r) * this.factorial(r));
}
probability() {
return this.combination(this.n - this.x, this.d - this.y) * this.combination(this.x, this.y) / this.combination(this.n, this.d);
}
}
|
export default {
label: 'Universe',
id: 'universe',
list: [
{
id: 'reading',
type: 'passage',
label: 'Universe - Notes',
data: {
title: 'Universe',
text: `The Universe is a vast expansion of space. The Universe consists of billions of galaxies, stars, planets, dwarf planets, comets, asteroids, meteoroids and natural satellites. The exact size of the universe is still unknown. Scientists believe that the universe is still expanding outward.
A Galaxy is a huge cluster of stars. Our galaxy Milky way is one among the countless of galaxies in the Universe.
Approximately 4.54 billion years ago, Solar System was a cloud of dust and gas known as Solar Nebula. Due to an explosion, these particles collapsed and began to spin having the sun at centre. The bigger particles which revolve around the sun are called planets. Thus the planet Earth formed.
The Rocky-inner planets are Mercury, Venus, Earth and Mars. They are called Terrestrial planets. The outer planets are Gaseous planets. They are Jupiter, Saturn, Uranus and Neptune. The frozen planets are Uranus and Neptune.
# Rotation
The movement of the earth on its axis is called rotation of the earth. Day and night are caused due to the earth‛s rotation.
# Revolution
The movement of the Earth around the Sun on it‛s axis which is tilted about 23½° is called revolution of the earth. Seasons are caused by Earth‛s revolution.
Life is possible only on the Earth because of the presence of land, air and water.
Venus is called Earth‛s twin. Mars is described as the Red planet. Earth is called the Blue planet. Saturn is the Ringed planet.`
}
},
{
id: 'mcq',
label: 'Multiple Choice Questions',
type: 'mcq',
data: {
editable: true,
title: 'Multiple Choice Questions',
questions: [
{
qText: 'The shape of the Earth is ______.',
options: 'sphere, circle, cube, oval'
},
{
qText: 'We get day and night due to the ________ of Earth.',
options: 'rotation, revolution, shape'
},
{
qText: 'We get different seasons due to the _______ of Earth.',
options: 'revolution, rotation, shape'
},
{
qText: 'Which of the following is not a rocky planet?',
options: 'Saturn, Earth, Mars, Venus'
},
{
qText: 'Which of the following is not a gaseous planet?',
options: 'Mars, Jupiter, Saturn'
},
{
qText: 'Which of the following are frozen planets?',
options: '* Uranus, Saturn, Jupiter, * Neptune'
}
]
}
},
{
label: 'True or False',
id: 'truefalse',
type: 'classifySentence',
data: {
title: 'Classify the below sentences as True or False.',
types: [
{
name: 'True',
text: `Scientists believe that the universe is expanding.
Uranus and Neptune are frozen planets because they are far away from the sun.`
},
{
name: 'False',
text: `Jupiter is the biggest planet in the whole universe.
The size of the universe can be measured.
We get day and night, due to the movement of Earth around the Sun.`
}
]
}
},
{
type: 'match',
label: 'Match ',
id: 'match',
data: {
title: 'Match the Planets with its description',
text: `Earth's twin, Venus
Red Planet, Mars
Blue Planet, Earth
Ringed Planet, Saturn
Farthest Planet, Neptune
Biggest Planet, Jupiter`
}
},
{
label: 'Arrange By Size',
type: 'sorting',
data: {
title: 'Rearrange based on the size (Largest at the top)',
text: 'Universe, Galaxy, Solar System, Sun, Planet, Satellite'
},
id: 'sort'
},
{
label: 'Fill up by drag and drop.',
id: 'fillup',
type: 'matchByDragDrop',
data: {
isPractice: false,
title: 'Drag and drop the words at proper places.',
styles: {
fontSize: '1rem',
dashWidth: 80
},
text: `Life is possible only on the *Earth* because of the presence of land, air and *water*.
Solar System was a cloud of dust and gas known as Solar *Nebula*.
A *galaxy* is a huge cluster of stars.
Our galaxy *Milky* way is one among the countless of galaxies in the Universe.
The outer planets are *gaseous* planets.`
}
}
]
};
|
/**
* https://www.devbridge.com/articles/tonejs-coding-music-production-guide/
* https://tonejs.github.io/docs/13.8.25/PolySynth
* https://www.guitarland.com/MusicTheoryWithToneJS/PlayChords.html
*/
const addOctaveNumbers = (scale, octaveNumber) => scale.map(note => {
const firstOctaveNoteIndex = scale.indexOf('C') !== -1 ? scale.indexOf('C') : scale.indexOf('C#')
const noteOctaveNumber = scale.indexOf(note) < firstOctaveNoteIndex ? octaveNumber - 1 : octaveNumber;
return `${note}${noteOctaveNumber}`
});
const constructMajorChord = (scale, octave, rootNote) => {
const scaleWithOctave = addOctaveNumbers(scale, octave);
const getNextChordNote = (note, nextNoteNumber) => {
const nextNoteInScaleIndex = scaleWithOctave.indexOf(note) + nextNoteNumber - 1;
let nextNote;
if (typeof(scaleWithOctave[nextNoteInScaleIndex]) !== 'undefined') {
nextNote = scaleWithOctave[nextNoteInScaleIndex];
} else {
nextNote = scaleWithOctave[nextNoteInScaleIndex - 7];
const updatedOctave = parseInt(nextNote.slice(1)) + 1;
nextNote = `${nextNote.slice(0,1)}${updatedOctave}`;
}
return nextNote;
}
const thirdNote = getNextChordNote(rootNote, 3);
const fifthNote = getNextChordNote(rootNote, 5);
const chord = [rootNote, thirdNote, fifthNote];
return chord;
}
window.onload = function() {
const lowPass = new Tone.Filter({
frequency: 8000,
}).toMaster();
const snare = new Tone.NoiseSynth({
volume: 5,
noise: {
type: 'white',
playbackRate: 3,
},
envelope: {
attack: 0.001,
decay: 0.20,
sustain: 0.15,
release: 0.03,
},
}).connect(lowPass);
const AMinorScale = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
const AMinorScaleWithOctave = addOctaveNumbers(AMinorScale, 4);
initAudioNodes();
document.getElementById("play-button").addEventListener("click", function() {
// synth.triggerAttackRelease('C4', '8n')
AMinorScaleWithOctave.forEach((note, index) => {
// synth.triggerAttackRelease(note, '4n', (index)*0.5 + 1)
});
if (Tone.Transport.state !== 'started') {
Tone.Transport.start();
} else {
Tone.Transport.stop();
}
playSong();
});
};
|
const nameGirl = 'Mẹ';
const giftUrl = 'http://nodemy.vn';
const eventName = 'Chúc mẹ iu 20-10';
const titleCard = 'Tặng Mẹ';
const contentCard = 'Chúc mẹ của con 20-10 luôn trẻ đẹp và luôn vui vẻ hạnh phúc bên người thương :v';
const giftImage = 'hot-girl.png';
const base64 = '';
const giftImageBase64 = "data:image/png;base64, " + base64;
|
const mongoose = require('mongoose');
const schema = mongoose.Schema;
const schmaName = require('../constants').schemas;
const status = require('../constants').status;
const level=require('../constants/index').level;
var sportSchema = new schema({
name:{type:String},
image:{type:String},
status:{type:String,enum:[status.active,status.deactive],default:status.active},
// capacity:{type:Number},
// level:{type:String,enum:[level.beginner,level.intermediate,level.advanced]}
});
Sport = module.exports = mongoose.model(schmaName.sport, sportSchema)
|
const users = require('./users')
const tickets = require('./tickets')
module.exports = {
users,
tickets
}
|
OC.L10N.register(
"lib",
{
"Unknown filetype" : "غیر معرروف قسم کی فائل",
"Invalid image" : "غلط تصویر",
"today" : "آج",
"yesterday" : "کل",
"last month" : "پچھلے مہنیے",
"last year" : "پچھلے سال",
"seconds ago" : "سیکنڈز پہلے",
"Username" : "اسم صارف",
"Password" : "پاسورڈ",
"Apps" : "ایپز",
"Search" : "تلاش",
"Settings" : "ترتیبات",
"Users" : "صارفین"
},
"nplurals=2; plural=(n != 1);");
|
'use strict';
let num = 10;
function showFirstMessage(text) {
console.log(text);
//функция может перезаписывать переменные из самой функции
num = 20;
}
showFirstMessage("Hello World!");
console.log(num);
function calc(a,b) {
return (a + b);
}
console.log(calc(10, 12));
//return возвращает результат на ружу
//такой вид функции имеет тип - function decloration
function ret() {
let num = 50;
return (num);
}
let anoterNum = ret();
console.log(anoterNum);
//вид function expression, после функции идет ;
const logger = function() {
console.log("hello");
};
logger();
//стрелочная функция (полный вид записи)
const calcu = (a,b) => {
console.log("1");
return (a + b);
};
calcu(1,2);
//сокращенный вид если один аргумент и одна строка выполнения
const calcu1 = a => console.log(a);
calcu1('Hello');
//если 2 аргумента
const calcu2 = (a,b) => a + b;
console.log(calcu2(3,2));
|
"use strict";
var text = "Mensagem";
var age = 29;
var classCampoGrande = true;
var listProgram = ['PHP', 'Java', 'HTML', 'ASP.NET'];
var listNumbers = [20, 30, 40, 40, 10];
// ERROS -> tIPAGEM
//text = 20;
//age = true;
//classCampoGrande = [20,29];
// corretos
text = 'Mensagem 2';
age = 20;
listNumbers = [100, 200, 300];
|
'use strict';
import mongoose from 'mongoose';
var UsersSchema = new mongoose.Schema({
firstname: String,
lastname: String,
emailid: String,
employeeid : Number,
password: String,
active: String,
usertype: String,
lastlogin: Date,
dob: Date,
bloodgroup: String,
phone: Number,
experience: Number,
address: String,
officelocation: String,
description: String,
lastmodified: Date,
designation: String,
companies: Array,
hdroles : Array,
profilefilename : {type : String,default : "undefined"}
});
export default mongoose.model('Users', UsersSchema);
|
'use strict';
var electron = require('electron');
var app = electron.app;
var BrowserWindow = electron.BrowserWindow;
var ipc = require('electron').ipcMain;
var mainWindow = null;
app.on('ready', function() {
mainWindow = new BrowserWindow({
height: 600,
width: 800,
frame: false,
resize: false,
});
mainWindow.loadURL('file://' + __dirname + '/app/index.html');
});
ipc.on('close-main-window', function () {
app.quit();
});
ipc.on('minimize-main-window', function () {
mainWindow.minimize();
});
ipc.on('unmaximize-main-winodw', function() {
mainWindow.unmaximize();
});
ipc.on('maximize-main-window', function()
{
mainWindow.maximize();
});
|
import React, { useState }from "react";
import "../App.css";
function SearchBar(props) {
const [inputValue, setInputValue] = useState({
query: "",
results: {},
loading: false,
message: ""
});
const handleChange = event => {
const query = event.target.value;
setInputValue({ query, loading: true, message: "" });
};
const handleSubmit = event => {
event.preventDefault();
setInputValue({
query: "",
results: {},
loading: false,
message: ""
});
};
return (
<div className="container">
<form>
<label className="search-label" htmlFor="search-input">
<input
type="text"
value={inputValue.query}
id="search-input"
placeholder="Search..."
onChange={handleChange}
onSubmit={() => handleSubmit()}
/>
<i className="fa fa-search search-icon" />
{/* <img className="search-icon" src="https://img.icons8.com/ios-filled/50/000000/search.png" alt="Search Icon" /> */}
</label>
</form>
</div>
);
}
export default SearchBar
|
import React from "react"
import Link from "gatsby-link"
import Helmet from "react-helmet"
export default class Blog extends React.Component {
render() {
return (
<div>
<h1>Blog Posts</h1>
<p>Welcome to blog post 1</p>
<Link to="/">About Hassan A. Elmi</Link>
</div>
)
}
}
|
Promise.delay = function(ms, value){
return new Promise((resolve, reject) => {
if(value && typeof value.then === 'function'){
value.catch(e => reject(e)).then(res => setTimeout(resolve.bind(this, res), ms));
} else setTimeout(resolve.bind(this, value), ms)
})
}
Promise.coroutine = function(generator){
if(generator.constructor.name !== 'GeneratorFunction') throw new Error("Wrong argument");
const itr = generator();
function rec(v) {
const res = itr.next(v);
if (res.done) return res.value;
else new Promise((resolve) => resolve(res.value)).then(x => rec(x));
}
return rec();
}
let p1 = new Promise((resolve, reject) => {
setTimeout(() => resolve("Hello, "), 1000)
})
let p2 = (value) => new Promise((resolve, reject) => {
setTimeout(() => resolve(value + "world!"), 5000)
})
/*
1) const itr = generator() => instance of Generator Object is being created
2) return rec() => recursive function is called
note: it seems to be it's impossible to this iteratively since every iterative approach i tried resulted in heap space overflow.
because the promise is pushed out of the synchronous code
3) const res = itr.next(v) => at first call with undefined argument iterator is being adjusted to the first yield expression
yield evaluates, returns an instance whose value is set to a pending promise.
note: as i understand from the engine's POV it looks like this:
yield args[0]
next(argument)
let res = ...
4) if the returned object's value's done property is true returns the promise
5) else synchronously calls itself passing the obtained value.
the generator function execution has been halted at the moment of assignment, so
.next() passes the value to the waiting variable
res === "Hello, " after the first yield expression execution
6) -> step 3
*/
function* gen(args) {
let res = yield args[0]
res = yield args[1](res)
console.log(res)
}
let arr = [p1, p2];
Promise.coroutine(gen.bind(this, arr));
|
import BlogLayout from './components/BlogLayout';
import BlogDate from './components/BlogDate';
import BlogTitle from './components/BlogTitle';
import BlogBlock from './components/BlogBlock';
const Index = () => (
<div>
<BlogLayout>
<BlogDate>04/02 — 20</BlogDate>
<BlogTitle>OniVim Sucks</BlogTitle>
<BlogBlock>
<p><a href="https://v2.onivim.io">Onivim</a> is a ‘modern modal editor’, combining fancy interface and language features with vim-style modal editing. What’s wrong with that, you may ask?</p>
<p>Apart from <a href="https://github.com/onivim/oni2/issues/550">buggy syntax highlighting</a>, <a href="https://github.com/onivim/oni2/issues/519">broken scrolling</a> and <a href="https://github.com/onivim/oni2/issues?q=is%3Aopen+is%3Aissue+label%3AI-daily-editor-blocker">other bugs</a>. Onivim is <strong>proprietary</strong> software. It is licensed under a commercial <a href="https://github.com/onivim/oni2/blob/master/Outrun-Labs-EULA-v1.1.md">end-user agreement license</a>, which prohibits redistribution in both object code and source code formats.</p>
<p>Onivim’s core editor logic (bits that belong to vim) have been separated from the interface, into libvim. libvim is licensed under MIT, which means, this ‘extension’ of vim is perfectly in adherence to vim’s license text!</p>
<p>Outrun Labs are exploiting this loophole (distributing vim as a library) to commercialize Onivim.</p>
<p>Onivim’s source code is available on <a href="https://github.com/onivim/oni2">GitHub</a>. They do mention that the source code trickles down to the <a href="https://github.com/onivim/oni2-mit">oni2-mit</a> repository, which (not yet) contains MIT-licensed code, <strong>13 months</strong> after initial commit to the original repository.</p>
<p>Want to contribute to Onivim? Don’t. They make a profit out of your contributions. Currently, Onivim is priced at $25, ‘alpha’ pricing which is 75% off the final price! If you are on the lookout for an editor, I would suggest using <a href="https://vim.org">Vim</a>, charityware that actually works, and costs exactly 0 dollars.</p>
</BlogBlock>
</BlogLayout>
<style jsx>{`
a {
color: #666
}
`}</style>
</div>
);
export default Index;
|
import {ComponentMetadata as Component, ViewMetadata as View, bootstrap} from 'angular2/angular2';
import {ProjectTree} from 'project-tree';
@Component({
selector: 'app'
})
@View({
directives: [ProjectTree],
template: `
<project-tree></project-tree>
`
})
class App {
}
bootstrap(App);
|
const fs = require('fs');
//동기예제
//const data = fs.readFileSync('file.md');
//console.log(data);
//비동기예제
fs.readFile('file.md',(err, data)=>{
if(err)throw err;
console.log(data);
});
|
/*global describe: true, expect: true, it: true, jasmine: true */
describe("jsdoc/src/handlers", function() {
var handlers = require('jsdoc/src/handlers');
var runtime = require('jsdoc/util/runtime');
var testParser = jasmine.createParser();
handlers.attachTo(testParser);
it("should exist", function() {
expect(handlers).toBeDefined();
expect(typeof handlers).toEqual("object");
});
it("should export an 'attachTo' function", function() {
expect(handlers.attachTo).toBeDefined();
expect(typeof handlers.attachTo).toEqual("function");
});
describe("attachTo", function() {
it("should attach a 'jsdocCommentFound' handler to the parser", function() {
var callbacks = testParser.listeners("jsdocCommentFound");
expect(callbacks).toBeDefined();
expect(callbacks.length).toEqual(1);
expect(typeof callbacks[0]).toEqual("function");
});
it("should attach a 'symbolFound' handler to the parser", function() {
var callbacks = testParser.listeners("symbolFound");
expect(callbacks).toBeDefined();
expect(callbacks.length).toEqual(1);
expect(typeof callbacks[0]).toEqual("function");
});
it("should attach a 'fileComplete' handler to the parser", function() {
var callbacks = testParser.listeners("fileComplete");
expect(callbacks).toBeDefined();
expect(callbacks.length).toEqual(1);
expect(typeof callbacks[0]).toEqual("function");
});
});
describe("jsdocCommentFound handler", function() {
var sourceCode = 'javascript:/** @name bar */',
result = testParser.parse(sourceCode);
it("should create a doclet for comments with '@name' tags", function() {
expect(result.length).toEqual(1);
expect(result[0].name).toEqual('bar');
});
});
describe("symbolFound handler", function() {
//TODO
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.