text stringlengths 7 3.69M |
|---|
import * as mutationTypes from './mutation-types'
export default {
[mutationTypes.SET_PLAYERS] (state, players) {
state.players = players;
},
[mutationTypes.DELETE_PLAYER] (state, playerId) {
state.players = state.players.filter(player => player._id !== playerId);
},
[mutationTypes.SET_CREATE_PLAYER] (state, createPlayerState) {
state.createPlayer = createPlayerState;
},
[mutationTypes.CREATE_PLAYER] (state, newPlayer) {
state.players = [...state.players, newPlayer];
},
[mutationTypes.DELETE_PLAYER] (state, playerId) {
state.players = state.players.filter(player => {
return player._id.toString() !== playerId.toString();
});
}
} |
const { expect } = require('chai')
const { test1, test2 } = require('./')
describe('Test1 function', () => {
it('test1([1, 2, 3]) === 6', () => {
const result = test1([1, 2, 3]);
expect(result).to.equal(6);
});
it('test1([1, "one", 2, "two", 3, "three"]) === 6', () => {
const result = test1([1, "one", 2, "two", 3, "three"]);
expect(result).to.equal(6);
});
it('test1(["4", "5", "6"]) === 15', () => {
const result = test1(["4", "5", "6"]);
expect(result).to.equal(15);
});
it('test1([4, 5, "test", "", "6"]) === 15', () => {
const result = test1([4, 5, "test", "", "6"]);
expect(result).to.equal(15);
});
});
describe('Test2 function', () => {
it('test2() === 0', () => {
expect(test2()).to.equal(0);
});
it('test2(1)() === 1', () => {
expect(test2(0)()).to.equal(0);
});
it('test2(1)(2)(3)(4)() === 10', () => {
expect(test2(1)(2)(3)(4)()).to.equal(10);
});
it('const t2 = test2(1)(2); t2(3)() === 6; test2(4)() === 7', () =>{
const t2 = test2(1)(2);
expect(t2(3)()).to.equal(6);
expect(t2(4)()).to.equal(7);
})
});
|
const Game = require('./game');
const readline = require('readline');
const reader = readline.createInterface({
output: process.stdout,
input: process.stdin
});
function completionCallback(){
reader.question("wanna go another round bru ?",(res) =>{
if(res === 'yes'){
let game = new Game();
game.run(reader,completionCallback);
}else{
reader.close();
}
});
}
let game = new Game();
game.run(reader,completionCallback);
|
//'use strict'
//this keyword exmplaination
/*
1. Inside an object
2. inside a function
3. Using new operator
*/
//the this keyword in the context of object
let employee = {
"firstname":"Harish",
"lastname":'Kumar',
"department":'HR',
"dependents":[
{
'name':'Suma',
'relationship':'Spouse'
},
{
"name":'Manu',
'relationship':'son'
}
],
getFullName: function(){
console.log(`
The full name of employee is
${this.firstname + this.lastname} `);
}
};
//employee.getFullName();
// 2. this inside the function
let totalPrice = function(tip, stateTax, centralTax){
console.log(this);
//console.log('state tax'+stateTax);
//console.log('central tax '+centralTax);
//console.log( `The total bill is ${this.totalAmount + this.taxAmount/100 * this.totalAmount + tip}`)
}
let obj={totalAmount:500, taxAmount:25}
let obj2={totalAmount:2000, taxAmount:25}
//totalPrice.call(obj2, 20, 5,5);
//totalPrice.apply(obj2, [20, 5,5]);
//totalPrice();
//let result = totalPrice.bind(obj, 40, 5 , 5);
//result();
//this with the new keyword
let Customer = function(){
console.log(`The name of the customer is ${this}`);
}
let c = new Customer();
console.log(c);
|
/**
* Copyright (C) 2009 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
/**
* Manages a form component
*/
function UIForm() {
};
/**
* Get form element with pattern condition
* @param {String} pattern
* The pattern can be Id#Id, example: Account#UIAccountForm
*/
UIForm.prototype.getFormElemt = function(pattern) {
if(pattern.indexOf("#") == -1) return document.getElementById(pattern) ;
var strArr = pattern.split("#") ;
var portlet = document.getElementById(strArr[0]) ;
return eXo.core.DOMUtil.findDescendantById(portlet, strArr[1]) ;
}
/**
* A function that submits the form identified by formId, with the specified action
* If useAjax is true, calls the ajaxPost function from PortalHttpRequest, with the given callback function
* Note: ie bug you cannot have more than one button tag
*/
UIForm.prototype.submitForm = function(formId, action, useAjax, callback) {
if (!callback) callback = null;
var form = this.getFormElemt(formId) ;
//TODO need review try-cactch block for form doesn't use FCK
try {
if (FCKeditorAPI && typeof FCKeditorAPI == "object") {
for ( var name in FCKeditorAPI.__Instances ) {
var oEditor ;
try {
oEditor = FCKeditorAPI.__Instances[name] ;
if (oEditor && oEditor.GetParentForm && oEditor.GetParentForm() == form ) {
oEditor.UpdateLinkedField() ;
}
} catch(e) {
continue ;
}
}
}
} catch(e) {}
form.elements['formOp'].value = action ;
if(useAjax) ajaxPost(form, callback) ;
else form.submit();
} ;
/**
* Submits a form by Ajax, with the given action and the given parameters
* Calls ajaxPost of PortalHttpRequest
* Note: ie bug you cannot have more than one button tag
*/
UIForm.prototype.submitEvent = function(formId, action, params) {
var form = this.getFormElemt(formId) ;
try {
if (FCKeditorAPI && typeof FCKeditorAPI == "object") {
for ( var name in FCKeditorAPI.__Instances ) {
var oEditor = FCKeditorAPI.__Instances[name] ;
if ( oEditor.GetParentForm && oEditor.GetParentForm() == form ) {
oEditor.UpdateLinkedField() ;
}
}
}
} catch(e) {}
form.elements['formOp'].value = action ;
if(!form.originalAction) form.originalAction = form.action ;
form.action = form.originalAction + encodeURI(params) ;
ajaxPost(form) ;
} ;
UIForm.prototype.selectBoxOnChange = function(formId, elemt) {
var selectBox = eXo.core.DOMUtil.findAncestorByClass(elemt, "UISelectBoxOnChange");
var contentContainer = eXo.core.DOMUtil.findFirstDescendantByClass(selectBox, "div", "SelectBoxContentContainer") ;
var tabs = eXo.core.DOMUtil.findChildrenByClass(contentContainer, "div", "SelectBoxContent");
for(var i=0; i < tabs.length; i++) {
tabs[i].style.display = "none";
}
tabs[elemt.selectedIndex].style.display = "block";
} ;
/**
* Sets the value (hiddenValue) of a hidden field (typeId) in the form (formId)
*/
UIForm.prototype.setHiddenValue = function(formId, typeId, hiddenValue) {
var form = document.getElementById(formId) ;
if(form == null){
maskWorkspace = document.getElementById("UIMaskWorkspace");
form = eXo.core.DOMUtil.findDescendantById(maskWorkspace, formId);
}
form.elements[typeId].value = hiddenValue;
} ;
/**
* Returns a string that contains all the values of the elements of a form (formElement) in this format
* . fieldName=value
* The result is a string like this : abc=def&ghi=jkl...
* The values are encoded to be used in an URL
* Only serializes the elements of type :
* . text, hidden, password, textarea
* . checkbox and radio if they are checked
* . select-one if one option is selected
*/
/*
* This method goes through the form element passed as an argument and
* generates a string output in a GET request way.
* It also encodes the the form parameter values
*/
UIForm.prototype.serializeForm = function (formElement) {
var queryString = "";
var element ;
var elements = formElement.elements;
this.addField = function(name, value) {
if (queryString.length > 0) queryString += "&";
queryString += name + "=" + encodeURIComponent(value);
};
for(var i = 0; i < elements.length; i++) {
element = elements[i];
//if(element.disabled) continue;
switch(element.type) {
case "text":
case "hidden":
case "password":
case "textarea" :
this.addField(element.name, element.value.replace(/\r/gi, ""));
break;
case "checkbox":
if(element.checked)
this.addField(element.name, "true");
else
this.addField(element.name, "false");
break;
case "radio":
if(element.checked) this.addField(element.name, element.value);
break;
case "select-one":
if(element.selectedIndex > -1){
this.addField(element.name, element.options[element.selectedIndex].value);
}
break;
case "select-multiple":
for(var j = 0; j < element.options.length; j++) {
if(element.options[j].selected) this.addField(element.name, element.options[j].value);
}
break;
} // switch
} // for
return queryString;
};
eXo.webui.UIForm = new UIForm();
|
import {createStore, combineReducers, applyMiddleware} from 'redux';
import {userReducer} from './reducers/userReducer';
import {libraryReducer} from './reducers/libraryReducer';
import thunk from 'redux-thunk';
import AsyncStorage from '@react-native-community/async-storage';
import {persistStore, persistReducer} from 'redux-persist';
const rootReducer = combineReducers({
user: userReducer,
library: libraryReducer,
});
const persistConfig = {
key: 'studentVideoApp',
storage: AsyncStorage,
timeout: null,
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
export const store = createStore(persistedReducer, applyMiddleware(thunk));
export const persistor = persistStore(store);
|
import React, {useState, useEffect} from 'react';
import logo from './logo.svg';
import './App.css';
import "./table/index.scss";
import Table from "./table/Table";
import EnhancedTableHead from "./table/EnhancedTableHead";
import TableBody from "./table/TableBody";
import TableRow from "./table/TableRow";
import TableCell from "./table/TableCell";
import Checkbox from "./table/Checkbox";
import TableContainer from "./table/TableContainer";
import axios from 'axios';
import Main from "./component/Main";
const headCells = [
{
id: "name",
numeric: false,
disablePadding: true,
label: "ExceptionName"
},
{ id: "Comments/RCA", numeric: true, disablePadding: false, label: "Comments/RCA" },
{ id: "ErrorTitle", numeric: true, disablePadding: false, label: "ErrorTitle" },
{ id: "ErrorMain", numeric: true, disablePadding: false, label: "ErrorMain" },
// { id: "ErrorFeatures", numeric: true, disablePadding: false, label: "ErrorFeatures" },
];
const rows = [
createData("java.lang.IllegalArgumentException", "RuleDataAuditLogUtil", "java.lang.IllegalArgumentException: hasAbsencesInPeriod() :Incomplete/Inconsistent input parameters", "list of features", "RCA/Comments"),
createData("java.lang.IllegalArgumentException", "FBSectUI_Objective", "java.lang.IllegalArgumentException: Illegal string value 'M'. Legal values are 'O', 'G', 'T', 'R', 'S', 'V', 'F', 'W', 'Q', 'C', 'GM+'.", "list of features", "RCA/Comments"),
createData("java.lang.IllegalArgumentException", "0COEMEventEditHandler", "java.lang.IllegalArgumentException: ContentTypeList does not contain a supported content type: image/*;q=0.8", "list of features", "RCA/Comments"),
createData("java.lang.IllegalArgumentException", "RCMAssessmentScoreSubscriber", "Caused by: java.lang.IllegalArgumentException: Object Definition is Null for provided Object Type. Please ensure that the corresponding feature is enabled via Upgrade Center or Provisioning.", "List of features", "RCA/Comments"),
createData("java.lang.IllegalArgumentException", "RuleDataAuditLogUtil", "java.lang.IllegalArgumentException: Object Definition is Null for provided Object Type. Please ensure that the corresponding feature is enabled via Upgrade Center or Provisioning.", "List of features", "RCA/Comments"),
createData("java.lang.IllegalArgumentException", "RuleDataAuditLogUtil", "java.lang.IllegalArgumentException: Mandatory parameters were not supplied.", "list of features", "RCA/Comments"),
]
function createData(ExceptionName, RCA, ErrorTitle, ErrorMain) {
return { ExceptionName, RCA, ErrorTitle, ErrorMain};
}
function getSorting(order, orderBy) {
return order === "desc"
? (a, b) => desc(a, b, orderBy)
: (a, b) => -desc(a, b, orderBy);
}
function desc(a, b, orderBy) {
if (b[orderBy] < a[orderBy]) {
return -1;
}
if (b[orderBy] > a[orderBy]) {
return 1;
}
return 0;
}
function stableSort(array, cmp) {
const stabilizedThis = array.map((el, index) => {
// console.log(el)
return [el, index];
});
stabilizedThis.sort((a, b) => {
const order = cmp(a[0], b[0]);
if (order !== 0) return order;
return a[1] - b[1];
});
return stabilizedThis.map(el => el[0]);
}
function App() {
const [currentTime, setCurrentTime] = useState(1);
const [ExceptionName, setExceptionName] = useState([]);
const [ErrorTitle, setErrorTitle] = useState([]);
const [ErrorMain, setErrorMain] = useState([]);
const [ErrorFeatures, setErrorFeatures] = useState([]);
const [RCA, setRCA] = useState([]);
useEffect (()=>{
fetch('/api/current').then(res => res.json()).then(data => {
setCurrentTime(data.time)
})
}, []);
useEffect (()=>{
fetch('/api/current').then(res => res.json()).then(data => {
setExceptionName(data.exception_name)
})
}, []);
useEffect (()=>{
fetch('/api/current').then(res => res.json()).then(data => {
setErrorTitle(data.error_title)
})
}, []);
useEffect (()=>{
fetch('/api/current').then(res => res.json()).then(data => {
setErrorMain(data.error_main)
})
}, []);
useEffect (()=>{
fetch('/api/current').then(res => res.json()).then(data => {
setErrorFeatures(data.error_features)
})
}, []);
useEffect (()=>{
fetch('/api/current').then(res => res.json()).then(data => {
setRCA(data.RCA)
})
}, []);
let row = {};
var i;
const Rows = [];
var string1, string2, string3, string4;
for (i = 0; i < ExceptionName.length; i++) {
string1 = ExceptionName[i]
string2 = RCA[i]
string3 = ErrorTitle[i]
string4 = ErrorMain[i]
row = createData(string1, string2, string3, string4);
Rows.push(row);
// console.log(row)
};
console.log(rows);
console.log(Rows);
const n = Rows.length;
const myParams = new FormData();
const mydata = {
"firstname": "Dong",
"lastname": "Wu"
};
myParams.append('data', mydata);
fetch ('http://localhost:3000/api/upload',{
method: 'POST',
body: JSON.stringify(mydata),
headers: {
'Content-Type': 'application/json'}
})
.then(response => {
console.log(response);
//Perform action based on response
})
.catch(error => {
console.log(error);
//Perform action based on error
});
const [order, setOrder] = useState("asc");
const [orderBy, setOrderBy] = useState("ErrorTitle");
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(5);
const handleRequestSort = property => {
const isAsc = orderBy === property && order === "asc";
setOrder(isAsc ? "desc" : "asc");
setOrderBy(property);
};
const handleChangePage = (event, newPage) => {
setPage(newPage);
};
const handleChangeRowsPerPage = event => {
setRowsPerPage(parseInt(event.target.value, 20));
setPage(0);
};
console.log("a" - "b");
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1>Central Feedback System ({currentTime} | Error count: {n} )</h1>
</header>
<main className="App-main" key={'this is the main page'}>
<a href="http://localhost:5000/api/upload" className="App-main-button">Load Your Own Log File For Analysis</a>
<br/>
<Main/>
<br/>
<h2>
This is the table of error/exception extract fron the raw log file with noise reduction
</h2>
<TableContainer>
<Table>
<EnhancedTableHead
order={order}
orderBy={orderBy}
headCells={headCells}
onRequestSort={handleRequestSort}
/>
<TableBody>
{stableSort(Rows, getSorting(order, orderBy)).map(
({ExceptionName, RCA, ErrorTitle, ErrorMain}) => (
<TableRow key={RCA}>
<TableCell>
<Checkbox />
</TableCell>
<TableCell className="promo-name"><a href= "http://127.0.0.1:5000/api/log">{ExceptionName}</a></TableCell>
<TableCell>{RCA}</TableCell>
<TableCell>{ErrorTitle}</TableCell>
<TableCell>{ErrorMain}</TableCell>
</TableRow>
)
)}
</TableBody>
</Table>
</TableContainer>
<h1>
Please input your analysis:
</h1>
</main>
</div>
);
}
export default App;
|
'use strict';
const utils = require('../lib/utils');
const errors = require('../lib/errors');
const q = require('../lib/constants/queries');
const Requirement = utils.Requirement;
const query = utils.query;
const GET_REPORT_REQS = [
new Requirement('query', 'season'),
new Requirement('query', 'year'),
];
// Get all stats for a season
function getReport(req) {
var missingReqs = utils.findMissingRequirements(req, GET_REPORT_REQS);
if (missingReqs.length !== 0) {
return errors.createMissingFieldError(missingReqs);
}
var season = req.query.season;
var year = req.query.year;
var inserts = [season, year];
return query(q.SELECT_SEASON_BY_SEASON_YEAR, inserts).then(function(seasons) {
if (seasons.length < 1) {
return errors.create404({
name: 'Season Not Found',
message: 'The requested season (' + season + ' ' + String(year) + ') does not exist in the database'
});
}
var seasonId = seasons[0].season_id;
return query(q.SELECT_SEASON_REPORT, [seasonId, seasonId, seasonId, seasonId]);
});
}
function generateSeasonCSV(req) {
}
function getReportByProgram(req) {
}
module.exports = {
getReport,
generateSeasonCSV,
getReportByProgram,
};
|
console.log("hola banda") |
import React from "react";
import ProfileStatus from "./ProfileStatus/ProfileStatus";
import s from "./ProfileDesc.module.css";
function ProfileDesc(props) {
return (
<div>
<div className={s.name}>{props.profile.fullName}</div>
<ProfileStatus
status={props.status}
updateStatus={props.updateStatus}
isOwner={props.isOwner}
/>
<div className={s.jobLooking}>
<span>Job status: </span>
{props.profile.lookingForAJob === true ? "looking" : "no looking"}
</div>
<div className={s.jobDescription}>
<span>Slogan: </span>
{props.profile.lookingForAJobDescription}
</div>
<div className={s.about}>
<div className={s.title}>About me </div>
{props.profile.aboutMe}
</div>
<div>
<div className={s.title}>Contacts: </div>
<div className={s.contactsWrapper}>{props.contacts}</div>
</div>
</div>
);
}
export default ProfileDesc;
|
// MODELS
module.exports.Token = require('./token.model');
module.exports.Organization = require('./organization.model');
module.exports.Key = require('./key.model');
module.exports.User = require('./user.model');
// SCHEMAS
module.exports.IssueSchema = require('./issue.schema');
module.exports.InvitationSchema = require('./invitation.schema');
|
define(['angular'], function (angular) {
'use strict';
/**
* @ngdoc function
* @name kvmApp.controller:ProjectServerCtrl
* @description
* # ProjectServerCtrl
* Controller of the kubernetesApp
*/
angular.module('kvmApp.controllers.ShowSnapServerCtrl', [])
.controller('ShowSnapServerCtrl', function (ShowSnapService, $scope, $state, $uibModal,Syncservice) {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
$scope.total = 0;
$scope.pageSize = 15;
$scope.page = 1;
$scope.searchKey = '';
$scope.initPage = function(searchKey){
ShowSnapService.fetch({page: $scope.page, pageSize: $scope.pageSize, searchKey:searchKey}).
success(function (data) {
$scope.searchKey = searchKey;
$scope.total = data.total;
$scope.rows = data.rows;
});
};
if ($state.current.needRequest) {
$scope.initPage();
}
$scope.Create = function () {
var allImage = JSON.parse(Syncservice.fetch('/api/v2/mirror/'));
var allproject = JSON.parse(Syncservice.fetch('/api/v2/projectlist/'));
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'add.html',
controller: 'ModalInstanceCtrl',
size: 'lg',
resolve: {
item: function () {
return {};
},
title: function () {
return {'title':'新建','imageList':allImage,'projectlist':allproject};
}
}
});
modalInstance.save = function (item) {console.log(item);
VmService.save(item).
success(function (data) {
modalInstance.close();
$scope.initPage();
});
};
};
$scope.edit = function (i) {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'edit.html',
controller: 'ModalInstanceCtrl',
size: 'lg',
resolve: {
item: function () {
return $scope.rows[i];
},
title: function () {
return {'title':'编辑'};
}
}
});
modalInstance.save = function (item) {
VmService.save(item).
success(function (data) {
console.log(item);
modalInstance.close();
$scope.initPage();
});
};
};
$scope.Start = function (i) {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'start.html',
controller: 'ModalInstanceCtrl',
size: 'lg',
resolve: {
item: function () {
return $scope.rows[i];
},
title: function () {
return {'title':'启动虚拟机'};
}
}
});
modalInstance.Start = function (item) {
VmService.Start(item).
success(function (data) {
console.log(item);
modalInstance.close();
$scope.initPage();
});
};
};
$scope.Stop = function (i) {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'stop.html',
controller: 'ModalInstanceCtrl',
size: 'lg',
resolve: {
item: function () {
return $scope.rows[i];
},
title: function () {
return {'title':'关闭虚拟机'};
}
}
});
modalInstance.Stop = function (item) {
VmService.Stop(item).
success(function (data) {
console.log(item);
modalInstance.close();
$scope.initPage();
});
};
};
$scope.Reboot = function (i) {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'reboot.html',
controller: 'ModalInstanceCtrl',
size: 'lg',
resolve: {
item: function () {
return $scope.rows[i];
},
title: function () {
return {'title':'重启虚拟机'};
}
}
});
modalInstance.Reboot = function (item) {
VmService.Reboot(item).
success(function (data) {
console.log(item);
modalInstance.close();
$scope.initPage();
});
};
};
$scope.Delete = function (i) {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'delete.html',
controller: 'ModalInstanceCtrl',
size: 'lg',
resolve: {
item: function () {
return $scope.rows[i];
},
title: function () {
return {'title':'删除虚拟机'};
}
}
});
modalInstance.Delete = function (item) {
VmService.Delete(item).
success(function (data) {
console.log(item);
modalInstance.close();
$scope.initPage();
});
};
};
$scope.CreateSnapshot = function (i) {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'createsnapshot.html',
controller: 'ModalInstanceCtrl',
size: 'lg',
resolve: {
item: function () {
return $scope.rows[i];
},
title: function () {
return {'title':'创建快照'};
}
}
});
modalInstance.CreateSnapshot = function (item) {
VmService.CreateSnapshot(item).
success(function (data) {
console.log(item);
modalInstance.close();
$scope.initPage();
});
};
};
$scope.Search = function (searchKey) {
$scope.initPage(searchKey);
};
$scope.pageAction = function (page) {
VmService
.fetch({page: page})
.success(function (data) {
$scope.total = data.total;
$scope.rows = data.rows;
});
};
$scope.sendReq = function(id, val){
ProjectService.post('/api/v2/update/rc/' + id, {"rc": val}).then(function(result){
result.data;
});
};
}).filter('cut', function () {
return function (value, wordwise, max, tail) {
if (!value) return '';
max = parseInt(max, 10);
if (!max) return value;
if (value.length <= max) return value;
value = value.substr(0, max);
if (wordwise) {
var lastspace = value.lastIndexOf(' ');
if (lastspace != -1) {
value = value.substr(0, lastspace);
}
}
return value + (tail || '...');
};
});;
});
|
import React from 'react';
import cx from 'classnames';
import PropTypes from 'prop-types';
const Copyright = ( { className } ) => (
<span className={ cx( 'copyright', className ) }>
© { new Date().getFullYear() } Dash Financial Technologies. All Rights
Reserved.
</span>
);
Copyright.propTypes = {
className: PropTypes.string,
};
export default Copyright;
|
const express = require('express');
const router = express.Router();
const product_controller=require('./product_controller')
router.post('/addProduct', product_controller.addProduct)
router.get('/getProducts', product_controller.getProducts)
router.patch('/updateProduct', product_controller.updateProduct)
router.delete('/removeProduct', product_controller.removeProduct)
module.exports = router; |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as i18n from 'lighthouse/core/lib/i18n/i18n.js';
import {auditNotApplicable, auditError} from '../messages/common-strings.js';
import {Audit} from 'lighthouse';
import {isAdIframe} from '../utils/resource-classification.js';
const UIStrings = {
title: 'Ads to page-height ratio is within recommended range',
failureTitle: 'Reduce ads to page-height ratio',
description: 'The ads to page-height ratio can impact user ' +
'experience and ultimately user retention. [Learn more](' +
'https://developers.google.com/publisher-ads-audits/reference/audits/viewport-ad-density' +
').',
displayValue: '{adDensity, number, percent} ads to page-height ratio',
};
const str_ = i18n.createIcuMessageFn(import.meta.url, UIStrings);
/**
* @param {LH.Artifacts.IFrameElement[]} slots
* @param {LH.Artifacts.ViewportDimensions} viewport
* @return {number}
*/
function computeAdLength(slots, viewport) {
// We compute ads to page-height ratio along the vertical axis per the spec.
// On mobile this is straightforward since we can assume single-column
// layouts, but not so on desktop. On desktop we take a sample of various
// vertical lines and return the greatest sum of ad heights along one of
// those lines.
/** @type {Set<number>} */
const scanLines = new Set([
...slots.map((s) => s.clientRect.left),
...slots.map((s) => s.clientRect.right),
].map((x) => Math.min(Math.max(1, x), viewport.innerWidth - 1)));
slots = slots.sort((a, b) => a.clientRect.top !== b.clientRect.top ?
a.clientRect.top - b.clientRect.top :
a.clientRect.bottom - b.clientRect.bottom);
let result = 0;
for (const x of scanLines) {
let adLengthAlongAxis = 0;
let bottomSoFar = 0;
for (const slot of slots) {
if (x < slot.clientRect.left || x > slot.clientRect.right) {
continue;
}
if (slot.isPositionFixed) {
// Count position:fixed ads towards ads to page-height ratio even if
// they overlap.
adLengthAlongAxis += slot.clientRect.height;
continue;
}
// Else we exclude overlapping heights from density calculation.
const delta =
slot.clientRect.bottom - Math.max(bottomSoFar, slot.clientRect.top);
if (delta > 0) {
adLengthAlongAxis += delta;
}
bottomSoFar = Math.max(bottomSoFar, slot.clientRect.bottom);
}
result = Math.max(result, adLengthAlongAxis);
}
return result;
}
/** @inheritDoc */
class ViewportAdDensity extends Audit {
/**
* @return {AuditMetadata}
*/
static get meta() {
return {
id: 'viewport-ad-density',
title: str_(UIStrings.title),
failureTitle: str_(UIStrings.failureTitle),
description: str_(UIStrings.description),
requiredArtifacts: ['ViewportDimensions', 'IFrameElements'],
};
}
/**
* @override
* @param {Artifacts} artifacts
* @return {LH.Audit.Product}
*/
static audit(artifacts) {
const viewport = artifacts.ViewportDimensions;
const slots = artifacts.IFrameElements.filter(
(slot) => isAdIframe(slot) &&
slot.clientRect.width * slot.clientRect.height > 1 );
if (!slots.length) {
return auditNotApplicable.NoVisibleSlots;
}
if (viewport.innerHeight <= 0) {
throw new Error(auditError.ViewportAreaZero);
}
const adsLength = computeAdLength(slots, viewport);
// We measure document length based on the bottom ad so that it isn't skewed
// by lazy loading.
const adsBottom =
Math.max(...slots.map((s) => s.clientRect.top + s.clientRect.height / 2));
// TODO(warrengm): Implement a DocumentDimensions gatherer to ensure that
// we don't exceed the footer.
const documentLength = adsBottom + viewport.innerHeight;
const adDensity = Math.min(1, adsLength / documentLength);
const score = adDensity > 0.3 ? 0 : 1;
return {
score,
numericValue: adDensity,
numericUnit: 'unitless',
displayValue: str_(UIStrings.displayValue, {adDensity}),
};
}
}
export default ViewportAdDensity;
export {UIStrings};
|
import { motion } from 'framer-motion';
import React from 'react';
import './Card.css';
export default function Card ({min, max, name, img, onClose, id}) {
return (
<motion.div
initial={{ scale: 0 }}
animate={{ rotate: 0, scale: 1 }}
transition={{
type: "spring",
stiffness: 260,
damping: 20
}}>
<div className="card">
<div id="closeIcon" className="row">
<button onClick={onClose} className="btn btn-sm btn-danger">X</button>
</div>
<div className="card-body">
<h5 className="card-title">{name}</h5>
<div className="row">
<div className="col-sm-4 col-md-4 col-lg-4">
<p>Min</p>
<p>{min}°</p>
</div>
<div className="col-sm-4 col-md-4 col-lg-4">
<p>Max</p>
<p>{max}°</p>
</div>
<div className="cardImage">
<img src={"http://openweathermap.org/img/wn/"+img+"@2x.png"} width="110" height="110" alt="" />
</div>
</div>
</div>
</div>
</motion.div>
);
}; |
import React from 'react';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import SearchBar from 'react-native-vector-icons/AntDesign';
import HomeBar from 'react-native-vector-icons/Foundation';
import PostBar from 'react-native-vector-icons/Feather';
import ProfileBar from 'react-native-vector-icons/Ionicons';
import HeartBar from 'react-native-vector-icons/AntDesign';
import HomeStackScreen from './home.routes';
import DiscoveryScreen from '../screens/DiscoveryScreen';
import NotificationScreen from '../screens/NotificationScreen';
import PostScreen from '../screens/PostScreen';
import ProfileScreen from '../screens/Profile';
const Tab = createBottomTabNavigator();
const BottomTabNavigator = () => (
<Tab.Navigator
screenOptions={({route}) => ({
tabBarIcon: ({focused, color, size}) => {
if (route.name === 'Home') {
return <HomeBar name="home" size={size} color={color} />;
}
if (route.name === 'Discover') {
return <SearchBar name="search1" size={size} color={color} />;
}
if (route.name === 'Post') {
return <PostBar name="plus-square" size={size} color={color} />;
}
if (route.name === 'Notification') {
return <HeartBar name="hearto" size={size} color={color} />;
}
if (route.name === 'Profile') {
return (
<ProfileBar
name="person-circle-outline"
size={size}
color={color}
/>
);
}
},
})}
tabBarOptions={{
activeTintColor: '#000',
inactiveTintColor: 'gray',
showLabel: false,
}}>
<Tab.Screen name="Home" component={HomeStackScreen} />
<Tab.Screen name="Discover" component={DiscoveryScreen} />
<Tab.Screen name="Post" component={PostScreen} />
<Tab.Screen name="Notification" component={NotificationScreen} />
<Tab.Screen name="Profile" component={ProfileScreen} />
</Tab.Navigator>
);
export default BottomTabNavigator;
|
/*<input type = "radio" name = "lesson" value = "java" onclick = "changeImage(this)">java
<input type = "radio" name = "lesson" value = "oracle" onclick = "changeImage(this)">oracle
<input type = "radio" name = "lesson" value = "xml" onclick = "changeImage(this)">xml
<input type = "radio" name = "lesson" value = "html" onclick = "changeImage(this)">html
<input type = "radio" name = "lesson" value = "javascipt" onclick = "changeImage(this)">javascipt*/
function changeImage(obj){
console.log(obj.value); //console.은 크롬에서 밖에 안된다.
var fd=document.getElementById("fd");
fd.style.display='inline';
switch (obj.value) {
case 'java':
fd.innerHTML="<img src=\"/web/img/아이오닉7.jpg\">"; /*주소에 쌍따옴표가 있으면 역슬러쉬로 해야한다*/
break;
case 'oracle':
break;
case 'xml':
break;
case 'html':
break;
case 'javascipt':
break;
default:
break;
}
} |
describe("SWOS-63: Schema/Model section labeling", () => {
it("should render `Schemas` for OpenAPI 3", () => {
cy
.visit("/?url=/documents/petstore-expanded.openapi.yaml")
.get("section.models > h4")
.contains("Schemas")
})
it("should render `Models` for OpenAPI 2", () => {
cy
.visit("/?url=/documents/petstore.swagger.yaml")
.get("section.models > h4")
.contains("Models")
})
})
|
const async = require('async');
const should = require('should');
const mongodb = require('mongodb');
const highland = require('highland');
const {
getMongoDBConnection
} = require('../../mongo_utils');
const updateHandler = require('./oplog.update');
describe('Update Oplog Handler', () => {
before((done) => {
const document = {
_id: new mongodb.ObjectID('58ad820029abbc9e35aa9a8f'),
title: 'CSS',
context: 'Web user interfaces',
identifier: 'info:fedora/learning:1443',
categoryCounts: [],
contentCategories: [],
associations: [],
description: 'CSS',
metadata: {
node_type: 'NODE',
object_uri: 'info:fedora/learning:1443',
setType: 'concept',
context: 'Web user interfaces',
nodeId: 'jsc430',
description: 'CSS',
identifier: 'info:fedora/learning:1443',
descriptionVerified: false
}
};
const insertDocument = (doc, db, cb) => db.collection('test').insertOne(doc, cb);
async.waterfall([
getMongoDBConnection.bind(null, 'sample'),
insertDocument.bind(null, document)
], done);
});
it('Should Update Oplog Handler', (done) => {
const oplogs = [{
v: 2,
op: 'u',
ns: 'sample.test',
o2: {
_id: new mongodb.ObjectID('58ad820029abbc9e35aa9a8f')
},
o: {
$set: {
title: 'HTML'
}
}
}];
highland((push) => {
oplogs.forEach((oplog) => {
push(null, oplog);
});
push(null, highland.nil);
}).pipe(updateHandler).each((oplog) => {
should.exist(oplog);
oplog.message.title.should.be.exactly('CSS');
oplog.message.context.should.be.exactly('Web user interfaces');
done();
});
});
after((done) => {
const dropCollection = (db, cb) => db.collection('test').remove({}, cb);
async.waterfall([
getMongoDBConnection.bind(null, 'sample'),
dropCollection
], done);
});
});
|
const request = require('supertest'); // framework for testing API
const expect = require('chai').expect; // javascript functionality testing framework
///********test suite for the task*************///
describe('Test for the tasks', () => {
//********TEST 1task************//
it('should return an array with characters names', (done) => {
request('http://localhost:3000')
.get('/people')
.expect('Content-Type', /json/)
.expect(200)
.end((err, res) => {
if (err) return done(err);
expect(res.body).to.be.an('array');
expect(res.body[0]).to.be.a('string');
expect(res.body[0]).to.equal('Luke Skywalker');
expect(res.body[res.body.length-1]).to.equal('Obi-Wan Kenobi');
expect(res.body.length).to.equal(10);
done();
});
});
//********TEST 2nd task*************//
it('should return the biggest planet\'s name and orbital period', (done) => {
request('http://localhost:3000')
.get('/planet')
.expect(200)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) return done(err);
expect(res.body).to.be.an('object');
expect(res.body).to.have.key('Name', 'orbitalPeriod');
done();
});
});
//********TEST for the 3rd task*************//
it('return and array of directors with their films', (done) => {
request('http://localhost:3000')
.get('/films')
.expect(200)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) return done(err);
expect(res.body).to.be.an('array');
expect(res.body.length).to.equal(4);
expect(res.body[0]).to.have.key('films', 'name');
expect(res.body[0].name).to.be.a('string');
expect(res.body[0].name).to.equal('George Lucas');
done();
});
});
//********TEST 4th task*************//
it('should return a object Luke Skywalker with vehicles property used by the character', (done) => {
request('http://localhost:3000')
.get('/vehicles')
.expect(200)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) return done(err);
expect(res.body).to.be.an('object');
expect(res.body).to.have.key('name', 'vehicles');
expect(res.body.name).to.be.a('string');
expect(res.body.name).to.equal('Luke Skywalker');
expect(res.body.vehicles).to.be.an('array');
done();
});
});
})
|
import React from 'react'
import Link from 'gatsby-link'
import Navigation from './Navigation'
const Header = () => (
<div>
<div>
<h1 style={{display: 'inline', fontFamily: 'arial', fontWeight: 400, marginLeft: 2,}}>Clark Carter</h1>
<Navigation />
</div>
</div>
)
const TemplateWrapper = ({ children }) => (
<div>
<Header />
<div>
{children()}
</div>
</div>
)
export default TemplateWrapper
|
// const notesService = require('../../controllers/annotationService')
const objectUtil = require('../../controllers/util')
module.exports = (app) => {
app.put('/api/v1/update', async (req, res) => {
const { body } = req
for (let i = 0; i < body.rows.length; i++) {
const { id } = body.rows[i]
const { keep, discard: update } = objectUtil.split(body.rows[i], ['id'])
console.log({ id, keep, update })
// await notesService.updateNote(id, update)
}
res.sendStatus(200)
})
}
|
import React from 'react';
class ExRatesTable extends React.Component {
render() {
const { data, change } = this.props;
return (
<table>
<tbody>
<tr>
<td>BTC/USD</td>
<td>
<input type="number" name="btcusd" defaultValue={data.btcusd} onChange={(e) => change(e.target)} />
</td>
</tr>
<tr>
<td>BTC/RUR</td>
<td>
<input type="number" name="btcrur" defaultValue={data.btcrur} onChange={(e) => change(e.target)} />
</td>
</tr>
<tr>
<td>USD/RUR</td>
<td>
<input type="number" name="usdrur" defaultValue={data.usdrur} onChange={(e) => change(e.target)} />
</td>
</tr>
<tr>
<td>A USD/RUR</td>
<td>
<input type="number" name="usdrurA" defaultValue={data.usdrurA} onChange={(e) => change(e.target)} />
</td>
</tr>
</tbody>
</table>
);
}
}
export default ExRatesTable;
|
import React, { useState, useContext } from "react";
import {
View,
Text,
StyleSheet,
FlatList,
TouchableOpacity,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import Context from "../context/Context";
const StoreCard = ({ item }) => {
const context = useContext(Context);
const [display, setDisplay] = useState({ display: false });
return (
<TouchableOpacity
onPress={() => {
let toggleDisplay = !display;
setDisplay(toggleDisplay);
}}
>
{!display ? (
<View style={styles.card}>
<View style={styles.verticalLine}></View>
<Text style={styles.titleText}>{item.name}</Text>
<Text style={styles.detailText}>{item.category}</Text>
<Text style={styles.detailText}>{item._id}</Text>
<Text style={styles.detailText}>{item.domain}</Text>
{context.favourites.some(
(favItem) => JSON.stringify(favItem) == JSON.stringify(item)
) ? (
<TouchableOpacity
onPress={() => {
context.toggleFavs(item);
}}
style={styles.icon}
>
<Ionicons name="heart-sharp" size={32} color="red" />
</TouchableOpacity>
) : (
<TouchableOpacity
onPress={() => {
context.toggleFavs(item);
}}
style={styles.icon}
>
<Ionicons name="heart-sharp" size={32} color="grey" />
</TouchableOpacity>
)}
</View>
) : (
<View style={styles.card}>
<View style={styles.verticalLine}></View>
<Text style={styles.titleText}>{item.name}</Text>
<Text style={styles.detailText}>{item.category}</Text>
{context.favourites.some(
(favItem) => JSON.stringify(favItem) == JSON.stringify(item)
) ? (
<TouchableOpacity
onPress={() => {
context.toggleFavs(item);
}}
style={styles.icon}
>
<Ionicons name="heart-sharp" size={32} color="red" />
</TouchableOpacity>
) : (
<TouchableOpacity
onPress={() => {
context.toggleFavs(item);
}}
style={styles.icon}
>
<Ionicons name="heart-sharp" size={32} color="grey" />
</TouchableOpacity>
)}
</View>
)}
</TouchableOpacity>
);
};
const styles = StyleSheet.create({
card: {
flex: 1,
margin: 10,
width: 300,
borderRadius: 10,
backgroundColor: "#E3E3E3",
color: 'blue'
},
titleText:{
marginTop: 10,
marginLeft: 35,
marginBottom: 10,
color: 'rgb(125, 176, 255)',
fontWeight: 'bold',
fontSize: 15
},
detailText: {
marginTop: 10,
marginLeft: 35,
marginBottom: 10,
color: 'rgb(125, 176, 255)'
},
icon: {
position: "absolute",
left: 250,
top: 10,
},
verticalLine: {
position: "absolute",
backgroundColor: "red",
width: 5,
height: "80%",
left: 15,
top: 5,
borderRadius: 5,
},
});
export default StoreCard;
|
"use strict"
const {SimCard} = require('./schemas')
const mongoose = require('mongoose')
//Connect to Mongodb
mongoose.connect('mongodb://localhost/simcards', { promiseLibrary: global.Promise, useCreateIndex: true,useNewUrlParser: true })
const queries = {
provisionSim:async (sim={})=>{
return await new SimCard({
...sim,
}).save()
},
activateSim :async (sim={})=>{
return await SimCard.findOneAndUpdate({
iccid:sim.iccid,
imsi:sim.imsi
},{status:1,msisdn:sim.msisdn},{new:true}).exec()
},
querySubscriberInfo :async (sim={})=>{
return await SimCard.findOne({
msisdn:sim.msisdn
}).exec()
},
adjustAccountBalance :async (sim={})=>{
return await SimCard.findOneAndUpdate({
msisdn:sim.msisdn
},{$inc:{'accountBalance':sim.amount}},{new:true}).exec()
}
}
module.exports = queries |
let validated = true
const errorMessages = {}
let finalErrors = ''
let password = null
const ValidateFields = (field, newValue, prevState) => {
// apply validation rules and get final result
return checkValidationRule(prevState, newValue)
}
// validates fields with required property
const requiredValidation = (prevState, newValue) => {
let thisValidation = true
const { required } = prevState
if (required && newValue) {
if (newValue.length < 2) {
thisValidation = false
}
}
if (required && !newValue) {
thisValidation = false
}
return thisValidation
}
// http://regexlib.com/Search.aspx?k=email&AspxAutoDetectCookieSupport=1
const emailValidation = (prevState, newValue) => {
let thisValidation = true
const { type } = prevState
if (type === 'email') {
thisValidation = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/.test(newValue)
}
return thisValidation
}
// 212-666-1234 format
const phoneValidation = (prevState, newValue) => {
let thisValidation = true
const { type } = prevState
if (type === 'phone') {
thisValidation = /^[2-9]\d{2}-\d{3}-\d{4}$/.test(newValue)
}
return thisValidation
}
// https://stackoverflow.com/questions/19605150/regex-for-password-must-contain-at-least-eight-characters-at-least-one-number-a
const passwordValidation = (prevState, newValue) => {
// min 8 char, @ least 1 letter, @ least 1 number
let thisValidation = true
const { type } = prevState
if (type === 'password') {
password = newValue
thisValidation = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(newValue)
}
return thisValidation
}
const passwordValidation2 = (prevState, newValue) => {
// min 8 char, @ least 1 letter, @ least 1 number
let thisValidation = true
const { type } = prevState
if (type === 'password2') {
thisValidation = newValue === password
}
return thisValidation
}
// all rules and corresponding error messages
const validationRules = [
{
rule: requiredValidation,
errMsg: 'Required Field (min 2 char)'
},
{
rule: emailValidation,
errMsg: 'Must be valid email'
},
{
rule: phoneValidation,
errMsg: 'Must be XXX-XXX-XXXX format'
},
{
rule: passwordValidation,
errMsg: 'Min 8 characters inc 1 lowercase 1 number'
},
{
rule: passwordValidation2,
errMsg: 'Does not match password'
}
]
const checkValidationRule = (prevState, newValue) => {
validationRules.forEach((r) => {
const { rule, errMsg } = r
const validation = rule(prevState, newValue)
if (validation) {
delete errorMessages[errMsg]
} else {
errorMessages[errMsg] = errMsg
}
})
finalErrors = Object.values(errorMessages).join('/ ')
validated = finalErrors === ''
const validationResponse = {
valid: validated,
errMsg: finalErrors
}
return validationResponse
}
export default ValidateFields |
'use strict'
const mongoose = require('mongoose');
let ApiacctSchema = new mongoose.Schema({
name: String,
appid: String,
password: String
});
module.exports = mongoose.model('Apiacct', ApiacctSchema); |
$(document).ready(function() {
$('.modal').on('click', '.add_userinvitee', function() {
var template = $('#userinvitee_fields');
var list_length = $('.userinvitees_list li').length;
console.log(list_length);
var new_invitee_template = Mustache.render(template.html(), {
index: list_length
});
$('.userinvitees_list').append('<li>' + new_invitee_template + '</li>');
});
$('.modal').on('click', '.delete_userinvitee', function() {
$(this).parent().remove();
});
}); |
function square(number) {
return number * number;
}
function noReturn() {
}
// 可以將返回值存到一個變數
var squareValue = square(10);
console.log(squareValue); //100
console.log(square(10) * 10); //1000
console.log(noReturn()); //undefined
|
import articleRepository from '../domain/repositories/article-repository'
const sortByDescendingNumberWithIntegerKey = (list, key) => list.sort((objectA, objectB) => {
if (parseInt(objectA[key], 10) > parseInt(objectB[key], 10)) {
return -1
}
if (parseInt(objectA[key], 10) < parseInt(objectB[key], 10)) {
return 1
}
return 0
})
async function getAllArticles(limit) {
if (limit === '0') {
return articleRepository.getAll()
}
// better would be to use findAll order, but dropboxId is a string!!
const allArticles = await articleRepository.getAll(limit)
const selectLastUntil = sortByDescendingNumberWithIntegerKey(allArticles, 'dropboxId')
return selectLastUntil.slice(0, limit)
}
export default {
getAllArticles,
}
|
export default {
primary: "#F58634",
black: "#000000",
white: "#FFFFFF",
secondary: "#1976D2",
textColorDark: "#2B2B2B",
textColorLight: "#fff",
textColorLightestGrey: "#DBDBDB",
textColorLightGrey: "#CBCBCB",
textColorGrey: "#B7B7B7",
textColorMediumGrey: "#9A9A9A",
textColorDarkGrey: "#9B9B9B",
textColorDanger: "#FC1717",
textColorSuccess: "#00C853",
backgroundColorDark: "#000",
backgroundColorLight: "#fff",
backgroundColorCard: "rgba(255, 255, 255, 0.1)",
descriptionTextCard: "rgba(255, 255, 255, 0.4)",
greyEighty: '#ccc',
};
//Global Colors Config |
//context
function evtIntervalBench(){
let suite = new Benchmark.Suite;
const optInterval = 500
const optTake = 150;
const optEndTime = 3000;
suite.add('eventIntervalWindow cepjs',
function(deferred){
cepjs.interval(optInterval)
.pipe(cepjsOp.take(optTake),
cepjsOp.eventIntervalWindow(['interval event'], ['no event'], optEndTime))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).add('eventIntervalWindow cepjs-most',
function(deferred){
cepjsMost.interval(optInterval)
.pipe(cepjsMostOp.take(optTake),
cepjsMostOp.eventIntervalWindow(['interval event'], ['no event'], optEndTime))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).add('eventIntervalWindow cepjs-mostcore',
function(deferred){
cepjsMostCore.interval(optInterval)
.pipe(cepjsMostCoreOp.take(optTake),
cepjsMostCoreOp.eventIntervalWindow(['interval event'], ['no event'], optEndTime))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).on('cycle', onSuiteCycle)
.on('complete', onSuiteComplete)
.run({'async': true});
}
function fixedIntervalBench(){
let suite = new Benchmark.Suite;
const optInterval = 500
const optTake = 150;
const optStartDelay = 2000;
const optEndTime = 2000;
suite.add('fixedIntervalWindow cepjs',
function(deferred){
cepjs.interval(optInterval)
.pipe(cepjsOp.take(optTake),
cepjsOp.fixedIntervalWindow(new Date(new Date().getTime() + optStartDelay), optEndTime,
cepjs.recurrence.NONE, cepjs.ordering.OCCURRENCE_TIME))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).add('fixedIntervalWindow cepjs-most',
function(deferred){
cepjsMost.interval(optInterval)
.pipe(cepjsMostOp.take(optTake),
cepjsMostOp.fixedIntervalWindow(new Date(new Date().getTime() + optStartDelay), optEndTime,
cepjsMost.recurrence.NONE, cepjsMost.ordering.OCCURRENCE_TIME))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).add('fixedIntervalWindow cepjs-mostcore',
function(deferred){
cepjsMostCore.interval(optInterval)
.pipe(cepjsMostCoreOp.take(optTake),
cepjsMostCoreOp.fixedIntervalWindow(new Date(new Date().getTime() + optStartDelay), optEndTime,
cepjsMostCore.recurrence.NONE, cepjsMostCore.ordering.OCCURRENCE_TIME))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).on('cycle', onSuiteCycle)
.on('complete', onSuiteComplete)
.run({'async': true});
}
function groupByBench(){
let suite = new Benchmark.Suite;
const optInterval = 500
const optTake = 150;
const count = 15;
suite.add('groupBy cepjs',
function(deferred){
cepjs.interval(optInterval)
.pipe(cepjsOp.take(optTake), cepjsOp.tumblingCountWindow(count),
cepjsOp.groupBy('eventTypeId'))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).add('groupBy cepjs-most',
function(deferred){
cepjsMost.interval(optInterval)
.pipe(cepjsMostOp.take(optTake), cepjsMostOp.tumblingCountWindow(count),
cepjsMostOp.groupBy('eventTypeId'))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).add('groupBy cepjs-mostcore',
function(deferred){
cepjsMostCore.interval(optInterval)
.pipe(cepjsMostCoreOp.take(optTake), cepjsMostCoreOp.tumblingCountWindow(count),
cepjsMostCoreOp.groupBy('eventTypeId'))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).on('cycle', onSuiteCycle)
.on('complete', onSuiteComplete)
.run({'async': true});
}
function slidCountBench(){
let suite = new Benchmark.Suite;
const optInterval = 500
const optTake = 150;
const count = 15;
suite.add('slidingCountWindow cepjs',
function(deferred){
cepjs.interval(optInterval)
.pipe(cepjsOp.take(optTake), cepjsOp.slidingCountWindow(count)).subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).add('slidingCountWindow cepjs-most',
function(deferred){
cepjsMost.interval(optInterval)
.pipe(cepjsMostOp.take(optTake), cepjsMostOp.slidingCountWindow(count))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).add('slidingCountWindow cepjs-mostcore',
function(deferred){
cepjsMostCore.interval(optInterval)
.pipe(cepjsMostCoreOp.take(optTake), cepjsMostCoreOp.slidingCountWindow(count))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).on('cycle', onSuiteCycle)
.on('complete', onSuiteComplete)
.run({'async': true});
}
function slidTimeBench(){
let suite = new Benchmark.Suite;
const optInterval = 500
const optTake = 150;
const optTime = 3000;
const optTime2 = 1000;
suite.add('slidingTimeWindow cepjs',
function(deferred){
cepjs.interval(optInterval)
.pipe(cepjsOp.take(optTake), cepjsOp.slidingTimeWindow(optTime, optTime2))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).add('slidingTimeWindow cepjs-most',
function(deferred){
cepjsMost.interval(optInterval)
.pipe(cepjsMostOp.take(optTake), cepjsMostOp.slidingTimeWindow(optTime, optTime2))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).add('slidingTimeWindow cepjs-mostcore',
function(deferred){
cepjsMostCore.interval(optInterval)
.pipe(cepjsMostCoreOp.take(optTake), cepjsMostCoreOp.slidingTimeWindow(optTime, optTime2))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).on('cycle', onSuiteCycle)
.on('complete', onSuiteComplete)
.run({'async': true});
}
function tumbCountBench(){
let suite = new Benchmark.Suite;
const optInterval = 500
const optTake = 150;
const count = 15;
suite.add('tumblingCountWindow cepjs',
function(deferred){
cepjs.interval(optInterval)
.pipe(cepjsOp.take(optTake), cepjsOp.tumblingCountWindow(count))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).add('tumblingCountWindow cepjs-most',
function(deferred){
cepjsMost.interval(optInterval)
.pipe(cepjsMostOp.take(optTake), cepjsMostOp.tumblingCountWindow(count))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).add('tumblingCountWindow cepjs-mostcore',
function(deferred){
cepjsMostCore.interval(optInterval)
.pipe(cepjsMostCoreOp.take(optTake), cepjsMostCoreOp.tumblingCountWindow(count))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).on('cycle', onSuiteCycle)
.on('complete', onSuiteComplete)
.run({'async': true});
}
function tumbTimeBench(){
let suite = new Benchmark.Suite;
const optInterval = 500
const optTake = 150;
const optTime = 5000;
suite.add('tumblingTimeWindow cepjs',
function(deferred){
cepjs.interval(optInterval)
.pipe(cepjsOp.take(optTake), cepjsOp.tumblingTimeWindow(optTime))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).add('tumblingTemporalWindow cepjs-most',
function(deferred){
cepjsMost.interval(optInterval)
.pipe(cepjsMostOp.take(optTake), cepjsMostOp.tumblingTimeWindow(optTime))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).add('tumblingTemporalWindow cepjs-mostcore',
function(deferred){
cepjsMostCore.interval(optInterval)
.pipe(cepjsMostCoreOp.take(optTake), cepjsMostCoreOp.tumblingTimeWindow(optTime))
.subscribe({
next: (value) =>{},
error: (error) =>{},
complete: () =>{
deferred.resolve();
}
});
}, benchOpts
).on('cycle', onSuiteCycle)
.on('complete', onSuiteComplete)
.run({'async': true});
}
|
import React from 'react'
import { render, fireEvent } from '@testing-library/react'
import api from '../../../../service/api'
import LoginDialog from '../index'
const loginSpy = jest.spyOn(api, 'login')
const checkUserSpy = jest.spyOn(api, 'checkUser')
const buildComponent = () => render(<LoginDialog />)
describe('<LoginDialog />', () => {
it('Render the component without crashing', () => {
const { asFragment } = buildComponent()
expect(asFragment())
.toMatchSnapshot()
})
it('Try to call next and get an empty username error', async () => {
const { getByText, findByText } = buildComponent()
const button = getByText('Próximo')
fireEvent.click(button)
expect(await findByText('Insira um nome de usuário ou endereço de e-mail válido'))
.toBeInTheDocument()
})
it('Call next and throw a not found user error', async () => {
const { getByText, getByLabelText, findByText } = buildComponent()
fireEvent.change(getByLabelText('Usuário'), { target: { value: 'testmock' } })
checkUserSpy.mockRejectedValue({ response: { data: { code: 'login1' } } })
fireEvent.click(getByText('Próximo'))
expect(await findByText('Esta conta não existe, insira uma conta diferente ou obtenha uma nova'))
.toBeInTheDocument()
})
it('Call next and changes to the password field', async () => {
const { getByText, getByLabelText, findByLabelText } = buildComponent()
fireEvent.change(getByLabelText('Usuário'), { target: { value: 'test' } })
checkUserSpy.mockResolvedValue({ success: true })
fireEvent.click(getByText('Próximo'))
expect(await findByLabelText('Senha'))
.toBeInTheDocument()
})
it('Types the password in the input and throws a password don\'t match error', async () => {
const { getByText, getByLabelText, findByText, findByLabelText } = buildComponent()
fireEvent.change(getByLabelText('Usuário'), { target: { value: 'test' } })
checkUserSpy.mockResolvedValue({ success: true })
fireEvent.click(getByText('Próximo'))
fireEvent.change(await findByLabelText('Senha'), { target: { value: 'test1234' } })
loginSpy.mockRejectedValue({ response: { data: { code: 'login3' } } })
fireEvent.click(getByText('Acessar'))
expect(await findByText('O usuário e/ou senha está incorreta'))
.toBeInTheDocument()
})
})
|
Template.certificate.helpers({
certificateAddress() {
return Router.current().params.certificateAddress;
},
invalid() {
return Session.get("invalid");
},
valid() {
return Session.get("valid");
},
contractAddress() {
return contractAddress;
}
});
Template.certificate.events({
'click #printPDF' (event, instance) {
html2canvas(window.document.getElementById("certificate"), {
scale: 2
}).then(function (canvas) {
var a = document.createElement('a');
// toDataURL defaults to png, so we need to request a jpeg, then convert for file download.
a.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
a.download = 'Bizancio - Certificado.png';
a.click();
});
},
})
Template.certificate.onCreated(function () {
// Web3 stuff
this.subscribe('templates');
// get certificate data
certificateContract.certificates.call(Router.current().params.certificateAddress, function (error, result) {
if (!error) {
if (result[6] == false) {
Session.set("invalid", true)
return;
}
let certificateData = result
certificateContract.institutions.call(certificateData[2], function (error, institutionData) {
if (institutionData) {
template = Templates.findOne({
address: certificateData[2]
})
Session.set("valid", true)
document.getElementById("diploma").src = template.image;
document.getElementById("name").textContent = certificateData[0];
document.getElementById("course").textContent = certificateData[3];
//document.getElementById("institution").textContent = institutionData[1];
document.getElementById("hours").textContent = certificateData[5].c[0];
document.getElementById("name-professor").textContent = certificateData[7];
document.getElementById("address-professor").textContent = certificateData[8];
document.getElementById("dates").textContent = certificateData[4];
}
});
} else
Session.set("invalid", true)
});
});
|
const { shell } = require('electron');
const parser = require('./parser');
const storage = require('./storage');
const ui = require('./ui');
class App {
constructor(storage, parser, ui) {
this.storage = storage;
this.ui = ui;
this.parser = parser;
}
init() {
this.initEventListeners();
this.initBookmarks();
}
initEventListeners() {
this.ui.selectors.newLinkUrl.addEventListener('keyup', () => {
this.ui.selectors.newLinkSubmit.disabled = !this.ui.selectors.newLinkUrl
.validity.valid;
});
this.ui.selectors.newLinkForm.addEventListener('submit', this.bookmark);
this.ui.selectors.clearStorageButton.addEventListener(
'click',
this.clearBookmarks
);
this.ui.selectors.linksSection.addEventListener('click', evt => {
debugger;
if (evt.target.href) {
evt.preventDefault();
shell.openExternal(evt.target.href);
}
});
}
initBookmarks() {
const booksmarks = this.storage.get();
this.ui.displayBookmarks(booksmarks);
}
bookmark = async evt => {
evt.preventDefault();
this.ui.setLoading(true);
const url = this.ui.selectors.newLinkUrl.value;
const { title, error } = await this.parser.parse(url);
this.ui.clearForm();
this.ui.setLoading(false);
if (error) return this.ui.displayError(error);
this.storage.store(title, url);
this.ui.appendBookmark({ url, title });
};
clearBookmarks = () => {
this.storage.clear();
this.ui.clearBookmarks();
};
}
(function() {
const app = new App(storage, parser, ui);
app.init();
})();
|
var shiftingLetters = function(S, shifts) {
let sum = 0;
let newstring = [];
let alphabet = 'abcdefghijklmnopqrstuvwxyz';
for (let i = shifts.length-1; i >= 0; i--) {
sum += shifts[i];
newstring.unshift(alphabet[(alphabet.indexOf(S[i]) + sum) % 26]);
}
return newstring.join("");
};
console.log(shiftingLetters('ruu', [26,9,17])); |
Markdocs.controller('DocController', function(DocHelper, DocModel, marked, $filter) {
var main = this;
main.statuses = DocModel.getStatuses();
main.categories = DocModel.getCategories();
main.docs = DocModel.getDocs();
main.statusesIndex = DocHelper.buildIndex(main.statuses, 'name');
main.categoriesIndex = DocHelper.buildIndex(main.categories, 'name');
main.setCurrentDoc = function(doc) {
main.currentDoc = doc;
main.currentStatus = doc.status;
main.currentCategory = doc.category;
// logging
console.log(doc);
DocHelper.modal('myModal', true);
};
main.refreshPost = function(post) {
if (typeof main.currentDoc !== 'undefined') {
main.currentDoc.post = marked(post);
}
}
main.createDoc = function() {
// insert new object doc in 0 index.
Array.prototype.insert = function ( index, item ) {
this.splice(index, 0, item );
};
main.docs.insert(0, {
title: "Simple Title",
author: 'Rebecca',
created: $filter('date')(new Date(), "MMMM d, yy"),
status: 'draf',
category: 'doc',
post: '# This is example document.'
});
};
main.setCurrentStatus = function(status) {
if (typeof main.currentDoc !== 'undefined') {
main.currentDoc.status = status;
}
};
main.setCurrentCategory = function(category) {
if (typeof main.currentDoc !== 'undefined') {
main.currentDoc.category = category;
}
};
}); |
import {
Schema,
} from "prosemirror-model";
import {
insertPoint
} from "prosemirror-transform";
import {
procedureXslt
} from "@/assets/js/documents/procedure.xslt.js";
import {
Document
} from "@/assets/js/documents/document.js";
const schema = new Schema({
nodes: {
content: {
content: "procedure",
toDOM(node) {
return ["div", {
class: "content"
}, 0];
},
parseDOM: [{
tag: "div.content"
}]
},
procedure: {
content: "mainProcedure",
toDOM(node) {
return ["div", {
class: "procedure"
}, 0];
},
parseDOM: [{
tag: "div.procedure"
}]
},
mainProcedure: {
content: "proceduralStep+",
toDOM(node) {
return ["div", {
class: "mainProcedure"
}, 0];
},
parseDOM: [{
tag: "div.mainProcedure"
}]
},
proceduralStep: {
content: "(title para*) | para+",
toDOM(node) {
return ["div", {
class: "proceduralStep"
}, 0];
},
parseDOM: [{
tag: "div.proceduralStep"
}]
},
title: {
content: "text*",
attrs: {
level: {
default: 1
}
},
parseDOM: [{
tag: "h1",
attrs: {
level: 1
}
},
{
tag: "h2",
attrs: {
level: 2
}
},
{
tag: "h3",
attrs: {
level: 3
}
},
{
tag: "h4",
attrs: {
level: 4
}
},
{
tag: "h5",
attrs: {
level: 5
}
},
{
tag: "h6",
attrs: {
level: 6
}
}
],
toDOM(node) {
return ["h" + node.attrs.level, {
class: "title"
}, 0]
}
},
para: {
content: "text*",
toDOM(node) {
return ["p", {
class: "para"
}, 0];
},
parseDOM: [{
tag: "p"
}]
},
text: {
inline: true
}
},
topNode: "content"
});
function addProceduralStep() {
return function (state, dispatch) {
let {
$from,
$to
} = state.selection;
const proceduralStepNode = schema.nodes.proceduralStep;
const paraNode = schema.nodes.para;
let point = insertPoint($from.doc, $from.pos, proceduralStepNode);
console.log(dispatch);
if (!point) return false;
if (dispatch) dispatch(state.tr.insert(point, proceduralStepNode.create(null, paraNode.create())));
return true;
}
}
export class Procedure extends Document {
constructor(xml) {
const xsltDom = new DOMParser().parseFromString(
procedureXslt,
"text/xml"
);
super(xml, xsltDom, schema);
this.commands.proceduralStep = addProceduralStep();
}
} |
// Pages
import React from 'react';
import Login from "./pages/Login";
import Admin from "./pages/Admin";
import Trainee from "./pages/trainee";
import { BrowserRouter as Router, Switch, Route} from "react-router-dom";
// auth & redux
import { connect } from "react-redux";
import AuthRoute from "./components/AuthRoute";
import BasicRoute from "./components/BasicRoute";
function App({ checked }) {
return (
<Router>
{checked && (
<Switch>
<Route exact path="/">
<Login />
</Route>
{/* <BasicRoute path="/admin" component={()=> "Access denied"}/> */}
<AuthRoute exact path="/admin">
<Admin />
</AuthRoute>
<BasicRoute path="/trainee">
<Trainee />
</BasicRoute>
<Route path="*" component={()=> "404 Not Found"}/> 1
</Switch>
)}
</Router>
);
}
const mapStateToProps = ({ session }) => ({
checked: session.checked,
});
export default connect(mapStateToProps)(App);
|
// all require file
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
require('dotenv').config();
// database variable
const uri = process.env.DB_PATH;
const app = express();
// PORT
const PORT = process.env.PORT || 8080;
// midlleware
app.use(cors());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
// all route file
app.get('/',(req,res,next)=>{
res.send({
greetings: 'Hello Express'
});
});
// get products data
app.get('/products',(req,res,next)=>{
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("onlineStore").collection("products");
// perform actions on the collection object
collection.find().toArray((err,documents)=>{
if(err) {
console.log(err);
res.status(500).send({message:err});
}
else {
res.send(documents);
}
})
client.close();
});
});
// single product data get
app.get('/products/:key',(req,res)=> {
const key = req.params.key;
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("onlineStore").collection("products");
// perform actions on the collection object
collection.find({key:key}).toArray((err,documents)=>{
if(err) {
console.log(err);
res.status(500).send({message:err});
}
else {
res.send(documents[0]);
}
})
client.close();
});
});
// multiple product data get in one page
app.post('/getProductsByKey',(req,res)=> {
const productKeys = req.body;
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("onlineStore").collection("products");
// perform actions on the collection object
collection.find({key:{$in:productKeys}}).toArray((err,documents)=>{
if(err) {
console.log(err);
res.status(500).send({message:err});
}
else {
res.send(documents);
}
})
client.close();
});
})
// post product data
app.post('/addproduct',(req,res)=>{
const product = req.body;
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("onlineStore").collection("products");
// perform actions on the collection object
collection.insert(product,(err,result)=>{
if(err) {
console.log(err);
res.status(500).send({message:err});
}
else {
res.send(result.ops[0]);
}
})
client.close();
});
});
// palce order
app.post('/placeOrder',(req,res)=> {
const orderDetails = req.body;
orderDetails.orderTime = new Date();
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("onlineStore").collection("orders");
// perform actions on the collection object
collection.insertOne(orderDetails,(err,documents)=>{
if(err) {
console.log(err);
res.status(500).send({message:err});
}
else {
res.send(documents.ops[0]);
}
})
client.close();
});
})
// listen method
app.listen(PORT,()=> {
console.log(`${PORT} Server is Running`);
}); |
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
// 云函数入口函数
const axios = require('axios')
exports.main = async (event, context) => {
const url = event.url
delete event.url
try {
const res = await axios.get(url, {
params: event
})
return res.data;
} catch (e) {
console.error(e);
return e;
}
} |
import React from "react";
import "./App.css";
function App() {
return (
<div className="App">
<div className="board" id="board">
<div className="cell"></div>
<div className="cell"></div>
<div className="cell"></div>
<div className="cell"></div>
<div className="cell"></div>
<div className="cell"></div>
<div className="cell"></div>
<div className="cell"></div>
<div className="cell"></div>
</div>
<div className="winning-message">
<div className="data-winning-message-text"></div>
<button className="restartButton">Restart</button>
</div>
</div>
);
}
export default App;
|
self.addEventListener('push', function (event) {
console.log('[SW] PUSH RECEIVED');
console.log(`[SW] Data : ${event.data.text()}`);
const title = "BELAJAR PUSH";
const options = {
body: event.data.text(),
icon: "images/icon.png",
badge: "images/icon.png",
};
event.waitUntil(self.registration.showNotification(title, options));
});
self.addEventListener('notificationclick', function (event) {
console.log('[SW] Clicked');
event.notification.close();
event.waitUntil(
clients.openWindow('https://google.com')
);
}) |
import React from "react";
import ChatBox from "../../../components/pages/Messenger/ChatBox";
import request from "../../../utils/request";
import { socket } from "../../../utils/socket";
const INITIAL_STATE = {
messages: null,
currentInput: "",
skip: 0,
count: 0,
loadingMessages: false,
loadingMore: false
};
// the number of messages that will be loaded each time
const STEP = 30;
class ChatBoxContainer extends React.PureComponent {
state = {
...INITIAL_STATE
};
componentDidMount() {
this.msgContainerRef = React.createRef();
// get current messages in room
this.getMessages();
}
componentWillUnmount() {
// remove socket's listener that handle incoming msg
socket.removeListener("room_msg", this.handleIncomingMessages);
}
componentWillReceiveProps(nextProps) {
if (
this.props.socketLoaded !== nextProps.socketLoaded &&
nextProps.socketLoaded === true
) {
// handle incoming messages through socket's io
socket.on("room_msg", this.handleIncomingMessages);
}
}
handleIncomingMessages = async msg => {
console.log("received msg:", msg);
// look up in current msg list to check if incoming msg is exist or not
const existMsg = await this.state.messages.find(
item => item.timeTicket === msg.timeTicket
);
if (existMsg) return;
// check incoming msg is belonged to current authUser or not
const { authUser } = this.props;
msg.isAuthOwner = authUser._id === msg.owner._id;
// add new messages to list
await this.setState(prevState => {
const messages = prevState.messages.concat(msg);
return {
messages
};
});
// scroll to bottom to show new messages
this.scrollToBottom();
};
handleScroll = () => {
const msgContainerElement = this.msgContainerRef.current;
// load more previous messages when:
// + if scroll to the top of the msg_container
// + if number of messages in msg_container is less than total messages in room
// (!): scrollTop is the position of the scrollBar
if (
msgContainerElement.scrollTop === 0 &&
!this.state.loadingMore &&
this.state.count > this.state.messages.length
) {
// load previous messages
this.getMoreMessages(msgContainerElement);
}
};
scrollToBottom() {
// does not exec function when ref has not created
if (!this.msgContainerRef || !this.msgContainerRef.current) return;
const msgContainerElement = this.msgContainerRef.current;
const scrollHeight = msgContainerElement.scrollHeight;
const height = msgContainerElement.clientHeight;
const maxScrollTop = scrollHeight - height;
msgContainerElement.scrollTop = maxScrollTop > 0 ? maxScrollTop : 0;
}
async getMoreMessages(msgContainerElement) {
const roomId = this.props.match.params.id;
this.setState({
loadingMore: true
});
try {
const { skip } = this.state;
const sort = {
createdAt: "-1"
};
const query = encodeURI(
`?skip=${skip === 0 ? skip + STEP : skip}&sort=${JSON.stringify(
sort
)}&limit=${STEP}`
);
const res = await request({
url: `/rooms/${roomId}/messages${query}`,
method: "GET"
});
if (res.data.status === "success") {
// load more data success
// get height of msgContainer before adding new messages
let prevHeight = msgContainerElement.scrollHeight;
// add new messages to state
await this.setState(prevState => {
const { authUser } = this.props;
let newMessages = res.data.value.messages;
// check owner of all new messages
newMessages = newMessages.map(msg => {
msg.isAuthOwner = authUser._id === msg.owner._id;
return msg;
});
// create new messages list
let messages = newMessages.concat(prevState.messages);
return {
messages,
skip: prevState.skip + STEP,
loadingMore: false,
count: res.data.value.count
};
});
// keep scrollbar at the position before adding new messages
msgContainerElement.scrollTop =
msgContainerElement.scrollHeight - prevHeight;
} else {
// load more fail
this.setState({
loadingMore: false,
error: res.data.message
});
}
} catch (err) {
// load more fail
this.setState({
loadingMore: false,
error: err
});
console.log("err", err);
}
}
async getMessages() {
const roomId = this.props.match.params.id;
this.setState({
loadingMessages: true
});
try {
const sort = {
createdAt: "-1"
};
const query = encodeURI(`?limit=${STEP}&sort=${JSON.stringify(sort)}`);
const res = await request({
url: `/rooms/${roomId}/messages${query}`,
method: "GET"
});
if (res.data.status === "success") {
const { authUser } = this.props;
let newMessages = res.data.value.messages.reverse();
newMessages.map(msg => {
msg.isAuthOwner = authUser._id === msg.owner._id;
return msg;
});
await this.setState({
loadingMessages: false,
messages: newMessages,
count: res.data.value.count,
skip: STEP
});
this.scrollToBottom();
} else {
this.setState({
loadingMessages: false,
error: res.data.message
});
}
} catch (err) {
this.setState({
loadingMessages: false,
error: err
});
console.log("err", err);
}
}
handleChange = e => {
e.persist();
this.setState({
currentInput: e.target.value
});
};
submit = async e => {
e.preventDefault();
const roomId = this.props.roomInfo._id;
// handle message's value before saving
const messageValue = this.handleMsgValue(this.state.currentInput);
// break if msg value is empty
if (!messageValue) {
return;
}
const owner = this.props.authUser;
// create time ticket to verify this message in other devices through socket
const timeTicket = String(new Date());
// add new message to list
await this.setState(prevState => {
const messages = prevState.messages.concat({
value: messageValue,
type: "text",
owner: owner,
isAuthOwner: true,
timeTicket: timeTicket
});
return {
messages,
currentInput: ""
};
});
// scroll to bottom
this.scrollToBottom();
// deliver message to server
try {
const res = await request({
url: `/messages`,
method: "POST",
data: {
value: messageValue,
roomId,
timeTicket: timeTicket
}
});
} catch (err) {
console.log("err", err);
}
};
handleMsgValue(str) {
return str.trim();
}
render() {
const { messages, currentInput, loadingMore } = this.state;
const { roomInfo } = this.props;
return (
<ChatBox
handleScroll={this.handleScroll}
ref={this.msgContainerRef}
loadingMore={loadingMore}
messages={messages}
roomInfo={roomInfo}
currentInput={currentInput}
handleChange={this.handleChange}
submit={this.submit}
/>
);
}
}
export default ChatBoxContainer;
|
const { Linter, Configuration } = require('tslint');
function runLinter(options, configurationFilePath, files) {
const linter = new Linter(options);
files.forEach(({ filename, content }) => {
const config = Configuration.findConfiguration(configurationFilePath, filename).results;
linter.lint(filename, content, config);
});
return linter.getResult();
}
module.exports = ({ options = { formatter: 'prose' }, configurationFilePath = null } = {}) => (files) => {
try {
const { errorCount, output } = runLinter(options, configurationFilePath, files);
return errorCount > 0 ?
Promise.reject(output) :
Promise.resolve();
} catch (error) {
return Promise.reject(error);
}
};
|
/**
* 验证旧密码是否正确
* 失去焦点的时候提示
**/
function OldPassword(){
var passwordOld = $("#passwordOld").val();//获取前台输入的旧密码
if(passwordOld == null){
layer.msg('您的旧密码不能为空', {time: 1000,/*1s后自动关闭*/ icon: 5});
}else{
$.ajax({
type:"post",
dataType:"json",
data:"passwordOld="+passwordOld,
url:"../../getPasswordByEmailMethod.do",
success:function(data){
if(data.resultcode == "200"){
}else{
layer.msg('您的原始密码错误', {time: 1000,/*1s后自动关闭*/ icon: 5});
$("#passwordOld").val("");
}
}
});
}
}
function tijiao(){
var passwordOld = $("#passwordOld").val();//获取前台输入的旧密码
var password = $("#password").val();//获取前台第一次输入密码
var passwordConfirm = $("#passwordConfirm").val();//获取前台第二次输入密码
if(password != passwordConfirm){
layer.msg('两次密码不一样', {time: 1000,/*1s后自动关闭*/ icon: 2});
}else if(passwordOld == passwordConfirm){
layer.msg('新密码与原始密码一致', {time: 1000,/*1s后自动关闭*/ icon: 2});
}else{
$.ajax({
type:"post",
dataType:"json",
data:"passwordConfirm="+passwordConfirm,
url:"../../upDataPasswordByEmailMethod.do",
success:function(data){
if(data.resultcode == "200"){
layer.msg('修改密码成功', {icon: 1});//默认3秒后自动消失
//0-叹号;1-对号;2-叉号;3-问号;4-锁;5-伤心QQ;6-开心QQ
}else{
layer.msg('修改密码失败', {time: 1000,/*1s后自动关闭*/ icon: 2});
}
}
});
}
} |
"use strict";
var MongoClient = require("mongodb").MongoClient,
cacheManager = require("cache-manager"),
mongoStore = require("../index.js"),
cacheDatabase = "cacheTest",
mongoUri = "mongodb://127.0.0.1:27017/" + cacheDatabase,
collection = "test_node_cache_mongodb_1",
assert = require("assert"),
debug = require('debug')('test'),
util = require('util')
;
const mongoCachePromise = (collection) => {
return new Promise(resolve => {
const mongoCache = cacheManager.caching({
store: mongoStore,
uri: mongoUri,
options: {
collection: collection,
compression: false,
poolSize: 5,
auto_reconnect: true
},
createCollectionCallback: () => {
debug("done creating collection");
return resolve(mongoCache);
}
});
});
};
const delay = async function(ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms);
});
};
describe("node-cache-manager-mongodb", async function() {
var client;
var c;
var mongoCache;
var get, set;
before("connect to mongo", async function() {
mongoCache = await mongoCachePromise(collection);
get = util.promisify(mongoCache.get);
set = util.promisify(mongoCache.set);
client = await MongoClient.connect(mongoUri, { useNewUrlParser: true });
c = client.db(cacheDatabase).collection(collection);
});
describe("set", async function() {
it('check mongo expiry stored correctly', async function() {
await set("test-cookie-0", "test-user", { ttl: 1 });
let r = await c.findOne({key: "test-cookie-0"});
assert.equal(r.value, "test-user", `${r.value} == "test-user"`);
assert(r.expire > Date.now(), `expires is in the future (${r.expire - Date.now()})`);
});
it("value with 1s expiry", async function() {
await set("test-cookie-1", "test-user1", { ttl: 1 });
let v = await get("test-cookie-1");
assert("test-user1" == v, `${v} is 'test-user1'`);
await delay(1010);
v = await get("test-cookie-1");
assert("test-user1" != v, `${v} is not 'test-user1'`);
});
});
after("close connection", function() {
return client.close();
});
});
|
import { StyleSheet } from 'react-native';
import * as theme from '../../../common/theme';
export default StyleSheet.create({
containerScrollable: {
backgroundColor: theme.PrimaryColor
},
container: {
flex: 1,
backgroundColor: theme.PrimaryColor
},
containerImage: {
width: '100%',
height: 226,
borderStyle: 'solid',
borderTopWidth: 3,
borderTopColor: theme.SecondaryColor,
borderBottomWidth: 3,
borderBottomColor: theme.SecondaryColor,
backgroundColor: theme.TertiaryColor
},
containerCharacters: {
borderStyle: 'solid',
borderBottomWidth: 3,
borderBottomColor: theme.SecondaryColor,
},
image: {
width: '100%',
height: 220
},
toolbarContainer: {
padding: 10,
flexDirection: 'row',
},
link: {
color: theme.LinkColor
},
dataContainer: {
padding: 10,
flexDirection: 'row'
},
text: {
color: theme.TextColor,
},
}) |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Field, reduxForm, SubmissionError } from 'redux-form';
import PropTypes from 'prop-types';
import { updateList } from '../../../actions/boardActions';
class EditListForm extends Component {
componentDidMount() {
this.editListField.focus();
}
onSubmit = values => {
const { onEdit, updateList, listId, authToken } = this.props;
if (values.title === '') throw new SubmissionError({ title: 'Can not be blank' });
updateList(values, listId, authToken);
onEdit();
};
renderInputField = field => {
return (
<input
style={{ padding: '4px 2px 4px 3px' }}
type="text"
ref={input => (this.editListField = input)}
className="form-control"
{...field.input}
/>
);
};
render() {
const { handleSubmit, onEdit } = this.props;
return (
<div>
<form onSubmit={handleSubmit(this.onSubmit)}>
<div className="form-group">
<Field name="title" component={this.renderInputField} onBlur={onEdit} />
</div>
</form>
</div>
);
}
}
EditListForm.propTypes = {
listId: PropTypes.string.isRequired,
authToken: PropTypes.string.isRequired,
handleSubmit: PropTypes.func.isRequired,
onEdit: PropTypes.func.isRequired,
updateList: PropTypes.func.isRequired
};
const mapStateToProps = ({ auth }) => {
return { authToken: auth.authToken };
};
export default reduxForm(
(_state, { listId }) => ({
form: `EditListForm-${listId}`
}),
{ updateList }
)(
connect(
mapStateToProps,
{ updateList }
)(EditListForm)
);
|
// What is this, 2007? This is all in one file because I'm too lazy to
// hook up module loading for Babel.
// Gotta check for Safari because getByteFrequencyData returns all 0s :/
// Desktop Safari is fixed, but I guess not iOS?
// https://bugs.webkit.org/show_bug.cgi?id=125031
const ua = navigator.userAgent
const iOS = !!ua.match(/iPad/i) || !!ua.match(/iPhone/i);
const webkit = !!ua.match(/WebKit/i);
const iOSSafari = iOS && webkit && !ua.match(/CriOS/i);
let bandSVG = Snap("#band_svg");
let titleSVG = Snap("#title_svg");
let coverSVG = Snap("#cover");
bandSVG.attr({ viewBox: "-30 -10 340 200" })
titleSVG.attr({ viewBox: "-30 -80 240 200" })
let vol1_letters = ["vol1_v", "vol1_o", "vol1_l", "vol1_1"];
Snap.load("/images/vol1.svg", function(svg) {
vol1_letters = vol1_letters.map(function(id, i) {
let lt = svg.select("#" + id);
titleSVG.append(lt);
return lt;
});
});
let snacky_letters = ["snacky_s", "snacky_n", "snacky_a", "snacky_c",
"snacky_k", "snacky_y"
];
Snap.load("/images/snacky.svg", function(svg) {
snacky_letters = snacky_letters.map(function(id, i) {
let lt = svg.select("#" + id);
bandSVG.append(lt);
return lt;
});
});
let mascot;
const mascotCoords = {
scale: 3.4,
t1: 460,
t2: 520,
r1: 0,
r2: 0
};
Snap.load("/images/mascot_vector.svg", function(svg) {
mascot = svg.select("#mascot");
mascot.transform("s4,t10,50");
coverSVG.append(svg);
scaleMascot();
});
const tracks = [
{
title: "Halftime Show",
src: "01_Halftime%20Show",
track_number: 1
},
{
title: "You're Preapproved!",
src: "02_You're%20Preapproved!",
track_number: 2
},
{
title: "Le Voyage Vers le Canape",
src: "03_Le%20Voyage%20Vers%20le%20Canape",
track_number: 3
},
{
title: "Nugget",
src: "04_Nugget",
track_number: 4
},
{
title: "I Forgot to Get Toilet Paper",
src: "05_I%20Forgot%20to%20Get%20Toilet%20Paper",
track_number: 5
},
{
title: "Ryan's Lament",
src: "06_Ryan's%20Lament",
track_number: 6
},
{
title: "Warm Face After a Cold Day",
src: "07_Warm%20Face%20After%20a%20Cold%20Day",
track_number: 7
}
];
let audio;
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
let analyzeEvent = new Event('analyze');
class AudioAnalyser extends EventEmitter {
constructor(audioCtx, source) {
super();
this.source = source = audioCtx.createMediaElementSource(audio);
this.analyser = audioCtx.createAnalyser();
this.analyser.connect(audioCtx.destination);
this.analyser.fftSize = 2048;
const bufferLength = this.analyser.frequencyBinCount;
this.dataArray = new Uint8Array(bufferLength)
source.connect(this.analyser);
let intervalID = window.setInterval(this.analyze.bind(this), 50);
}
analyze() {
this.analyser.getByteFrequencyData(this.dataArray);
this.emitEvent('analyze', this.dataArray);
}
}
let currentTrack;
let audioState;
let currentAnalyser;
let dancing = true;
const $playControl = document.querySelector("#playPause");
const $nextControl = document.querySelector("#playNext");
const $nowPlaying = document.querySelector("#nowPlaying");
const $toggleDance = document.querySelector("#toggleDance");
const $fallback = document.querySelector("#fallback");
const $fallbackCt = document.querySelector("#fallback .content");
$nextControl.style.display = 'none';
$fallback.style.display = 'none';
if (iOSSafari) {
$toggleDance.style.display = 'none';
$fallback.style.display = 'block';
$fallbackCt.innerHTML = `
<h2>Hey there, Safari user!</h2>
<p>There's some fun visualizations to go along with the audio that unfortunately
don't work on iOS Safari yet. Try this page in Chrome if you wanna see cool stuff,
otherwise enjoy the tunes.
</p>
<a href='#' id='closeFallback'>Close</a>
`;
document.querySelector('#closeFallback').addEventListener('click', function(e) {
e.preventDefault();
$fallbackCt.style.display = 'none';
})
}
$toggleDance.addEventListener('click', toggleDancing);
function toggleDancing(e) {
if (e) {e.preventDefault();}
if (dancing) {
dancing = false;
if (currentAnalyser) {
currentAnalyser.removeListener('analyze', animate);
}
$toggleDance.innerHTML = "Start dancing";
} else {
dancing = true;
if (currentAnalyser) {
currentAnalyser.addListener('analyze', animate);
}
$toggleDance.innerHTML = "Stop dancing";
}
}
function displayTrackInfo(track) {
$nowPlaying.innerHTML = `<h4>${track.track_number}. ${track.title}</h4>`
}
function queueTrack(track) {
let extension;
if (audio) {audio.pause(); audioState = 'paused'};
displayLoading();
audio = new Audio();
audio.crossOrigin = true;
if (audio.canPlayType("audio/mp3")) {
extension = ".mp3";
} else if (audio.canPlayType("audio/ogg")) {
extension = ".ogg";
}
s3URL = "https://s3.amazonaws.com/ross-brown/snacky/";
audio.setAttribute("src", s3URL + track.src + extension);
audio.load();
if (currentAnalyser) {
currentAnalyser.removeListener('analyze', animate);
};
currentAnalyser = new AudioAnalyser(audioCtx);
if (dancing) {
currentAnalyser.addListener('analyze', animate);
}
displayTrackInfo(track);
audio.addEventListener('ended', nextTrack);
audio.addEventListener('canplaythrough', playAudio);
audio.addEventListener('waiting', displayLoading);
};
function displayLoading() {
$playControl.innerHTML = "...";
audioState = 'loading';
}
function fadeIn() {
let fadePoint = 0.5;
let fadeAudio = setInterval(function () {
if ((audio.currentTime < fadePoint) && (audio.volume != 1.0)) {
audio.volume += 0.1;
}
if (audio.volume === 1.0) {
clearInterval(fadeAudio);
}
}, 20);
}
function playAudio() {
if(!audio) {return};
// audio.volume = 0;
audio.play();
// fadeIn();
audioState = 'playing';
$playControl.innerHTML = "Pause";
};
function nextTrack() {
if(typeof currentTrack === 'undefined'){
currentTrack = 0;
} else {
currentTrack++;
};
if (currentTrack === tracks.length ) {
currentTrack = 0;
audioState = 'paused';
}
queueTrack(tracks[currentTrack]);
$nextControl.style.display = 'inline';
}
function pauseTrack() {
$playControl.innerHTML = "Play";
audio.pause();
audioState = 'paused';
}
function resumeTrack() {
$playControl.innerHTML = "Pause";
audio.play();
audioState = 'playing';
}
$playControl.addEventListener("click", function(e) {
e.preventDefault();
if (audioState == 'playing') {
pauseTrack();
} else if (audioState == 'paused') {
resumeTrack();
} else {
nextTrack();
}
});
$nextControl.addEventListener("click", function(e) {
e.preventDefault();
nextTrack();
})
function animate() {
let anData = arguments;
vol1_letters.forEach(function(letter) {
let index = vol1_letters.indexOf(letter);
let offIndex = index+1;
let freq = index + 50;
let scaled = anData[freq]/100
if (scaled < 0.5) {scaled = 0.5};
let hOffset = 0;
if (index > (vol1_letters.length/2)) {
hOffset = index + (anData[freq]/10)/(offIndex*0.5);
} else {
hOffset = index - (anData[freq]/10)/(offIndex*0.5);
}
letter.animate({transform: "s"+ scaled + "t"+ hOffset + "," + 0}, 20);
});
snacky_letters.forEach(function(letter) {
let index = snacky_letters.indexOf(letter)
let freq = index + 300;
let scaled = anData[freq]/100
if (scaled < 0.5) {scaled = 0.5};
if (scaled > 1.5) {scaled = 1.5};
let rAngle = (index + anData[freq] - 50);
if (rAngle < -30) {rAngle = -30};
if (rAngle > 30) {rAngle = 30};
letter.animate({transform: "s"+ scaled + "r"+rAngle + "t10,10"}, 10);
});
let snareLevel = anData[250];
scaleMascot(snareLevel/10);
incrementBgColor(snareLevel);
}
let currentMascotRotate = 0;
let mascotRotateDir = 1;
function scaleMascot(modifier) {
modifier = modifier || 1;
let scale = mascotCoords.scale + (modifier/90);
let t1 = mascotCoords.t1 - modifier;
let t2 = mascotCoords.t2 - modifier;
let r1 = mascotCoords.r1 - modifier;
if (modifier > 9.2) {
// If there's a peak in the frequency...
if (Math.abs(currentMascotRotate - r1) > 1.1) {
// swith dancing directions
if (mascotRotateDir === 1) {
mascotRotateDir = -1;
} else {
mascotRotateDir = 1;
};
}
currentMascotRotate = r1
}
r1 = r1*mascotRotateDir;
let string = `s${scale},t${t1},${t2}r${r1};`
mascot.animate({transform: string}, 30);
}
let colors = [
"#be4f5e", "#ffdd65", "#0b7347", "#fe8721", "#d5cec4", "#e35d0c",
"#7d464b", "#ece6da"
];
let colorIndex = 0;
let currentColorValue = 0;
function incrementBgColor(value) {
if (value > 80 && Math.abs(value - currentColorValue) > 25) {
colorIndex+=1;
if (colorIndex === colors.length ) {colorIndex = 0};
document.querySelector('body').style.backgroundColor = colors[colorIndex];
}
currentColorValue = value;
}
|
import React, {Component} from 'react';
import {Form, Button, Input, Select} from 'antd'
import 'antd/dist/antd.css';
import BaseComponent from "../Base/BaseComponent";
import DynamicList from "../DynamicList/DynamicList";
import ShortcutSelects from "../selects/ShortcutSelects";
import store from "../../store"
import "./css/template-maker.scss"
import templateMaker from "../../js/templateMaker";
const {clipboard} = window.require('electron');
export default class TemplateMaker extends BaseComponent {
state = {
params: [],
notifyParams:[]
}
componentWillMount() {
}
render() {
let {params,notifyParams, template, viewTemplate,compiledTemplate} = this.state;
return (
<div className='template-maker'>
<div className="maker">
<Form onSubmit={e => {
e.preventDefault();
}}>
<Form.Item label='notify-params'>
<DynamicList
defaultList={notifyParams}
renderItem={(item, index) => <div>
<Input placeholder='请输入字段名' onInput={this.$onInput(v => item.key = v)}/>
<Input placeholder='请输入字段值' onInput={this.$onInput(v => item.value = v)}/>
</div>}
/>
</Form.Item>
<Form.Item label='参数'>
<DynamicList
defaultList={params}
renderItem={(item, index) => <div>
<Input placeholder='请输入参数名字' onInput={this.$onInput(v => item.name = v)}/>
<Select style={{width: 220}} onSelect={v=>item.type = v}>
<Select.Option value="Object">对象:{"{a:1,b:2,c:3}"}</Select.Option>
<Select.Option value="Array">数组:[1,2,3,4,5]</Select.Option>
<Select.Option value="String">字符串:12345</Select.Option>
<Select.Option value="Number">数字:123</Select.Option>
</Select>
</div>}
/>
</Form.Item>
<Form.Item label='模板内容'><Input.TextArea onInput={this.$onInput(v => {
let
viewTemplate,
compiledTemplate,
result = templateMaker.make({template:v,params});
try {
compiledTemplate = eval(`(${result})`)().compile({});
} catch (e) {
compiledTemplate = e.message;
}
viewTemplate = compiledTemplate;
this.setState({
template: result,
compiledTemplate,
viewTemplate
})
})}/></Form.Item>
<Form.Item className='tac'><Button onClick={() => {
const {onSubmit} = this.props;
const {shortcuts} = store.getState();
// if (shortcuts.find(i => i.key === this.$getInputValue('key'))) {
//
// }
onSubmit && onSubmit({template, paramsDefined: params});
}} htmlType='submit' type='primary'>生成</Button></Form.Item>
</Form>
</div>
<pre onClick={()=>{
this.isShowCompiledTemplate = !this.isShowCompiledTemplate;
this.setState({
viewTemplate:this.isShowCompiledTemplate ? compiledTemplate : template
})
}}>
{viewTemplate}
</pre>
</div>
);
}
};
|
import React, { Component } from 'react';
import {
Col,
NavbarBrand,
ListGroup,
ListGroupItem
} from 'reactstrap';
import { Link } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faGithub } from '@fortawesome/free-brands-svg-icons';
import Session from "../Session/Session.js";
let pkg = require('../../../package.json');
/// HTML for one element of the navigation list
function SidebarListElement(props) {
return (
<ListGroupItem className="py-4" tag="a" action href={props.href}>
<h5 className="text-center my-auto">{props.text}</h5>
</ListGroupItem>
);
}
class Sidebar extends Component {
render() {
return (
<Col md="2" className="sidebar">
<div className="d-flex flex-column">
<NavbarBrand tag={Link}
to="/"
style={{color: "inherit", "fontSize": "1.75rem" }}
className="mx-auto">
Asset Angels
</NavbarBrand>
<div className="d-flex mx-auto">
<div className="version-number muted my-auto">{pkg ? pkg.version : "Unknown"}</div>
<a className="my-auto ml-2" href="https://github.com/5CS024-Team1/asset-tracker-web/" style={{ color: "black" }}>
<FontAwesomeIcon icon={faGithub} />
</a>
</div>
<Link to="/" className="mx-auto mt-2 mb-4">
<img src={process.env.PUBLIC_URL + '/aa_logo.png'}
alt="Asset Angels logo"
height="250" width="150" />
</Link>
</div>
<ListGroup>
<SidebarListElement text="Dashboard" href={process.env.PUBLIC_URL + '/dashboard'} />
<SidebarListElement text="Assets" href={process.env.PUBLIC_URL + '/assets'} />
{
Session.isUserTypeOrAbove("management") && <SidebarListElement text="Register" href={process.env.PUBLIC_URL + '/assets/register'} />
}
<SidebarListElement text="Reports" href={process.env.PUBLIC_URL + '/reports'} />
{
Session.isAdminUser() && <SidebarListElement className="bg-secondary" text="Users" href={process.env.PUBLIC_URL + '/users'} />
}
</ListGroup>
</Col>
);
}
}
export default Sidebar; |
import { useTips } from './TipDataProvider.js';
import { Tips } from './Tip.js';
let tipCollection = document.querySelector("#tips-list")
export function TipList(){
const allTheTips = useTips();
let tipListHTMLString = "";
for(let i = 0; i < allTheTips.length;i++){
tipListHTMLString += Tips(allTheTips[i]);
}
console.log(tipListHTMLString);
tipCollection.innerHTML = `<h2>My Tips</h2>${tipListHTMLString}`;
} |
import { Model, DataTypes } from "sequelize";
export default class User extends Model {
static init(sequelize) {
return super.init({
id: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
primaryKey: true
},
locale: DataTypes.STRING,
overrideGuildLocale: DataTypes.BOOLEAN
}, {
timestamps: false,
sequelize
});
}
} |
import React, { PureComponent } from "react";
import classNames from "classnames";
const iconName = {
bold: "bold",
italic: "italic",
removeFormat:'trash-o'
};
class MenuButton extends PureComponent {
constructor(props) {
super(props);
this.inClicking = false;
this.state = {
_active: false
};
}
_execCommand(e, type) {
document.execCommand(type, false);
if (this.props.active !== undefined) {
this.inClicking = true;
this.setState(
{
_active: !this.nowActive
},
() => {
this.inClicking = false;
}
);
this.forceUpdate();
}
}
render() {
var iClass = `Rte-icon-${iconName[this.props.type]}`;
if (this.props.active !== undefined) {
const active = this.inClicking ? this.state._active : this.props.active;
iClass = classNames(`Rte-icon-${this.props.type}`, {
active: active
});
this.nowActive = active;
}
return (
<button
className={`Rte-menu-button Rte-menu-${this.props.type}`}
onClick={e => this._execCommand.call(this, e, this.props.type)}
title={this.props.title}
>
<i className={iClass} />
</button>
);
}
}
export default MenuButton;
|
import React from "react";
import { Box, Text, Avatar} from "@chakra-ui/core";
export default function Profile() {
return (
<Box
height="50%"
width="85%"
borderRadius="10px"
p={1}
display="flex"
flexDirection="column"
justifyContent="space-between"
pb={6}
className="profile-card-container"
backgroundColor='whiteAlpha.900'
boxShadow='0px 21px 6px -16px #C0C0C0'
>
<Box
height="25%"
className="profile-background"
backgroundColor="blackAlpha.500"
borderRadius='10px 10px 0px 0px'
textAlign='center'
>
<Avatar src="https://bit.ly/broken-link" height='80px' width='80px' mt={8} border='3px solid white'/>
</Box>
<Box
display="flex"
flexDirection="column"
justifyContent="center"
alignItems="center"
className="profile-info"
>
<Text mt={2} fontWeight="bold">
Filip Martin Jose
</Text>
<Text fontSize="xs" color="gray.400" fontWeight="bold">
Los Angeles
</Text>
<Text
fontSize="xs"
backgroundColor="messenger.500"
borderRadius="30px"
color="whiteAlpha.900"
width="25%"
textAlign="center"
fontWeight="bold"
mt={3}
height="35%"
pt={1}
pb={1}
>
Pro Level
</Text>
</Box>
<Box
display="flex"
justifyContent="space-around"
alignItems="flex-start"
p="auto"
ml={5}
flexDirection="row"
className="profile-stats"
>
<Box p={0} flexBasis="20%">
<Text fontSize="xs" fontWeight="bold" color="gray.400">
Followers
</Text>
<Text fontSize="2xl">980</Text>
</Box>
<Box p={0} flexBasis="20%">
<Text fontSize="xs" fontWeight="bold" color="gray.400">
Projects
</Text>
<Text fontSize="2xl">142</Text>
</Box>
<Box p={0} flexBasis="20%" display="block" flexDirection="column">
<Text fontSize="xs" fontWeight="bold" color="gray.400">
Rank
</Text>
<Text fontSize="2xl">129</Text>
</Box>
</Box>
</Box>
);
}
|
import {
Category,
Story,
Picture,
Content,
Group,
Image,
Obj,
Organization,
User_Organization,
Media
} from './models'
Category.hasMany(Group, {
as: 'groups',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
foreignKey: 'categoryId',
sourceKey: 'id'
})
Category.belongsTo(Image, {
as: 'image',
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
foreignKey: 'imageId',
sourceKey: 'id',
constraints: false
})
Category.belongsTo(Organization, {
as: 'organization',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
foreignKey: 'organizationId',
sourceKey: 'id'
})
Content.belongsTo(Story, {
as: 'story',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
foreignKey: 'storyId',
sourceKey: 'id'
})
Content.belongsTo(Image, {
as: 'image0',
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
foreignKey: 'image0Id',
sourceKey: 'id'
})
Content.belongsTo(Image, {
as: 'image1',
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
foreignKey: 'image1Id',
sourceKey: 'id'
})
Content.belongsTo(Obj, {
as: 'obj',
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
foreignKey: 'objId',
sourceKey: 'id'
})
Content.belongsToMany(Image, {
as: 'additionalImages',
through: 'content_image'
})
Content.belongsToMany(Media, {
as: 'additionalMedias',
through: 'content_media'
})
Group.belongsTo(Category, {
as: 'category',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
foreignKey: 'categoryId',
sourceKey: 'id'
})
Group.belongsTo(Image, {
as: 'image',
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
foreignKey: 'imageId',
sourceKey: 'id'
})
Group.belongsToMany(Story, {
as: 'groups',
through: 'story_group'
})
Image.belongsTo(Organization, {
as: 'organization',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
foreignKey: 'organizationId',
sourceKey: 'id'
})
Image.belongsToMany(Content, {
as: 'contents',
through: 'content_image'
})
Media.belongsTo(Organization, {
as: 'organization',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
foreignKey: 'organizationId',
sourceKey: 'id'
})
Media.belongsToMany(Content, {
as: 'contents',
through: 'content_media'
})
Obj.belongsTo(Image, {
as: 'primaryImage',
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
foreignKey: 'primaryImageId',
sourceKey: 'id'
})
Obj.belongsTo(Media, {
as: 'primaryMedia',
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
foreignKey: 'primaryMediaId',
sourceKey: 'id'
})
Obj.belongsTo(Organization, {
as: 'organization',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
foreignKey: 'organizationId',
sourceKey: 'id'
})
Organization.belongsTo(Image, {
as: 'orgImage',
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
foreignKey: 'orgImageId',
sourceKey: 'id',
constraints: false
})
Organization.belongsTo(Image, {
as: 'locationImage',
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
foreignKey: 'locationImageId',
sourceKey: 'id',
constraints: false
})
Organization.hasMany(Story, {
as: 'stories',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
foreignKey: 'organizationId',
targetKey: 'id'
})
Organization.hasMany(Image, {
as: 'images',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
foreignKey: 'organizationId',
targetKey: 'id'
})
Organization.hasMany(Media, {
as: 'medias',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
foreignKey: 'organizationId',
targetKey: 'id'
})
Organization.hasMany(Obj, {
as: 'objs',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
foreignKey: 'organizationId',
targetKey: 'id'
})
Organization.hasMany(Category, {
as: 'categories',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
foreignKey: 'organizationId',
targetKey: 'id'
})
Organization.hasMany(User_Organization, {
as: 'users',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
foreignKey: 'organizationId',
targetKey: 'id'
})
Story.belongsToMany(Group, {
as: 'groups',
through: 'story_group'
})
Story.belongsToMany(Story, {
as: 'relatedStories',
through: 'story_story'
})
Story.belongsTo(Organization, {
as: 'organization',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
foreignKey: 'organizationId',
sourceKey: 'id'
})
Story.belongsTo(Image, {
as: 'previewImage',
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
foreignKey: 'previewImageId',
sourceKey: 'id'
})
Story.hasMany(Content, {
as: 'contents',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
foreignKey: 'storyId',
targetKey: 'id'
})
User_Organization.belongsTo(Organization, {
as: 'organization',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
foreignKey: 'organizationId',
targetKey: 'id'
})
//
// export async function createAssociations() {
// try {
//
// Category.hasMany(Group, {
// as: "groups"
// })
//
// Category.belongsTo(Image, {
// as: "image"
// })
//
// Category.belongsTo(Organization, {
// as: "organization"
// })
//
//
// Content.belongsTo(Story, {
// as: "story",
// })
//
// Content.belongsTo(Image, {
// as: "image0",
// })
//
// Content.belongsTo(Image, {
// as: "image1",
// })
//
// Content.belongsTo(Obj, {
// as: "obj",
// })
//
// Content.belongsToMany(Image, {
// as: "additionalImages",
// through: "content_image"
// })
//
// Content.belongsToMany(Media, {
// as: "additionalMedias",
// through: "content_media"
// })
//
//
//
// Group.belongsTo(Category, {
// as: "category"
// })
//
// Group.belongsTo(Image, {
// as: "image"
// })
//
// Group.belongsToMany(Story, {
// as: "groups",
// through: "story_group",
// })
//
// Image.hasMany(Group, {
// as: 'groups'
// })
//
// Image.belongsTo(Organization, {
// as: "organization"
// })
//
// Image.belongsToMany(Content, {
// as: "contents",
// through: "content_image"
// })
//
// Media.belongsTo(Organization, {
// as: "organization"
// })
//
// Media.belongsToMany(Content, {
// as: "contents",
// through: "content_media"
// })
//
// Obj.belongsTo(Image, {
// as: "primaryImage"
// })
//
// Obj.hasMany(Content, {
// as: "contents"
// })
//
// Obj.belongsTo(Organization, {
// as: "organization"
// })
//
//
// Organization.hasOne(Image, {
// as: "orgImage",
// })
//
// Organization.hasOne(Image, {
// as: "locationImage",
// })
//
//
// Organization.hasMany(Story, {
// as: "stories",
// })
//
// Organization.hasMany(Image, {
// as: "images"
// })
//
// Organization.hasMany(Media, {
// as: "medias"
// })
//
//
// Organization.hasMany(Obj, {
// as: "objs"
// })
//
// Organization.hasMany(Category, {
// as: "categories",
// constraints: false
// })
//
// Organization.hasMany(User_Organization, {
// as: "users"
// })
//
// Story.belongsToMany(Group, {
// as: "groups",
// through: "story_group",
// })
//
// Story.belongsToMany(Story, {
// as: "relatedStories",
// through: "story_story"
// })
//
// Story.belongsTo(Organization, {
// as: "organization"
// })
//
// Story.belongsTo(Image, {
// as: "previewImage",
// })
//
// Story.hasMany(Content, {
// as: 'contents'
// })
//
// User_Organization.belongsTo(Organization, {
// as: "organization"
// })
//
//
// } catch (ex) {
//
// console.log("createAssociations ex", ex)
// process.exit(1)
// }
// }
|
(function () {
'use strict';
angular.module('experiment')
.directive('circle', circle);
experiment.$inject = ['$injector', 'experimentConfig', 'experiment'];
function circle($injector, experimentConfig, experiment) {
return {
templateUrl: function () {
return toastrConfig.templates.circle;
},
controller: 'CircleController',
link: circleLinkFunction
};
function circleLinkFunction(scope, element,attr,circleCtrl) {
console.log(scope);
console.log(element);
console.log(attr);
console.log(circleCtrl);
}
}
}) |
"use strict";
require("run-with-mocha");
const assert = require("assert");
const testTools = require("./_test-tools")
const AnalyserNodeFactory = require("../../src/factories/AnalyserNodeFactory");
describe("AnalyserNodeFactory", () => {
it("should defined all properties", () => {
const AnalyserNode = AnalyserNodeFactory.create({}, class {});
const properties = testTools.getPropertyNamesToNeed("AnalyserNode");
const notDefined = properties.filter((name) => {
return !Object.getOwnPropertyDescriptor(AnalyserNode.prototype, name);
});
assert(notDefined.length === 0);
});
describe("instance", () => {
describe("constructor", () => {
it("audioContext.createAnalyser()", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = context.createAnalyser();
assert(node instanceof api.AnalyserNode);
});
it("new instance", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = new api.AnalyserNode(context, {});
assert(node instanceof api.AnalyserNode);
});
it("new instance, but @protected", () => {
const api = testTools.createAPI({ protected: true });
const context = new api.AudioContext();
assert.throws(() => {
return new api.AnalyserNode(context, {});
}, TypeError);
});
it("default parameters", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = context.createAnalyser();
assert(node.fftSize === 2048);
assert(node.frequencyBinCount === 1024);
assert(node.maxDecibels === -30);
assert(node.minDecibels === -100);
assert(node.smoothingTimeConstant === 0.8);
});
});
describe("fftSize", () => {
it("works", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = new api.AnalyserNode(context, {
fftSize: 512
});
assert(node.fftSize === 512);
node.fftSize = 256;
assert(node.fftSize === 256);
});
it("throws error", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = new api.AnalyserNode(context, {});
assert.throws(() => {
node.fftSize = 5000;
}, TypeError);
});
});
describe("frequencyBinCount", () => {
it("works", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = new api.AnalyserNode(context, {
fftSize: 512
});
assert(node.frequencyBinCount === 256);
node.fftSize = 256;
assert(node.frequencyBinCount === 128);
});
});
describe("maxDecibels", () => {
it("works", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = new api.AnalyserNode(context, {
maxDecibels: -20
});
assert(node.maxDecibels === -20);
node.maxDecibels = -10;
assert(node.maxDecibels === -10);
});
it("throws error", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = new api.AnalyserNode(context, {});
assert.throws(() => {
node.maxDecibels = node.minDecibels - 10;
}, TypeError);
});
});
describe("minDecibels", () => {
it("works", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = new api.AnalyserNode(context, {
minDecibels: -110
});
assert(node.minDecibels === -110);
node.minDecibels = -120;
assert(node.minDecibels === -120);
});
it("throws error", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = new api.AnalyserNode(context, {});
assert.throws(() => {
node.minDecibels = node.maxDecibels + 10;
}, TypeError);
});
});
describe("smoothingTimeConstant", () => {
it("works", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = new api.AnalyserNode(context, {
smoothingTimeConstant: 0.7
});
assert(node.smoothingTimeConstant === 0.7);
node.smoothingTimeConstant = 0.6;
assert(node.smoothingTimeConstant === 0.6);
});
it("throws error", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = new api.AnalyserNode(context, {});
assert.throws(() => {
node.smoothingTimeConstant = -0.1;
}, TypeError);
});
});
describe("getByteFrequencyData", () => {
it("works", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = context.createAnalyser();
const array = new Uint8Array(node.frequencyBinCount);
node.getByteFrequencyData(array);
});
});
describe("getByteTimeDomainData", () => {
it("works", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = context.createAnalyser();
const array = new Uint8Array(node.fftSize);
node.getByteTimeDomainData(array);
});
});
describe("getFloatFrequencyData", () => {
it("works", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = context.createAnalyser();
const array = new Float32Array(node.frequencyBinCount);
node.getFloatFrequencyData(array);
});
});
describe("getFloatTimeDomainData", () => {
it("works", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = context.createAnalyser();
const array = new Float32Array(node.fftSize);
node.getFloatTimeDomainData(array);
});
});
});
});
|
import React from 'react';
import {
PokedexContainer,
SubContainer,
MiddleDisplay,
} from './Pokedex.styled';
import PokemonMainData from '../PokemonMainData';
import PokemonInfo from '../PokemonInfo';
import { connect } from 'react-redux';
const Pokedex = ({ pokemon }) => {
return (
<PokedexContainer>
<SubContainer>
<PokemonMainData pokemon={pokemon} />
</SubContainer>
<MiddleDisplay />
<SubContainer>
<PokemonInfo pokemon={pokemon} />
</SubContainer>
</PokedexContainer>
);
};
const mapState = ({ pokemons }) => ({
pokemon: pokemons.current,
});
export default connect(mapState)(Pokedex);
|
angular.module("EcommerceModule").controller("ProductFilterSearchController", function ($scope, $stateParams, ProductFilterpageService, CartService){
var routeparamkeyWord = $stateParams.keyWord;
this.keyWord = $stateParams.keyWord;
$scope.pageTitle = "Search: "+ routeparamkeyWord;
$scope.ProductData;
$scope.ProductCount = 0;
$scope.pageIndex = 1;
var maxProductResult = 3;
this.whiteframe = 3;
this.hover = function(ev){
var ele = angular.element(ev.currentTarget);
ele.addClass("md-whiteframe-10dp");
}
this.leave = function(ev){
var ele = angular.element(ev.currentTarget);
ele.removeClass("md-whiteframe-10dp");
}
this.range = function(){
var input = [];
for(var i = 0; i < $scope.ProductCount/maxProductResult; i++){
input.push(i+1);
}
return input;
}
this.openPageIndex = function(index){
$scope.pageIndex = index;
this.handleGetProduct();
}
var getProductBySearch = function(){
ProductFilterpageService.httpGetProductBySearch(routeparamkeyWord, $scope.pageIndex, maxProductResult).then(
function(response){
$scope.ProductData = response.data.object;
},function(error){
console.log(error);
}
)
}
var getProductBySearchCount = function(){
ProductFilterpageService.httpGetProductBySearchCount(routeparamkeyWord).then(
function(response){
$scope.ProductCount = response.data.object;
},function(error){
console.log(error);
}
)
}
this.handleGetProduct = function(){
getProductBySearchCount();
getProductBySearch();
}
this.addProductToCart = function(id){
CartService.addProductToCart(id, $scope.ProductData);
}
this.handleGetProduct();
}); |
export { Button } from './button'
export { Input } from './input'
export { Issue } from './issue'
|
module.exports = require('./getMongoDBConnection');
|
'use strict'
var year = 2018
/*
while(year != 1991){
console.log(" estamos en el: "+year)
year--
}
*/
// do while
var years = 30
do{
alert("solo cuando sea mayor de 25")
years--
}while(years > 25) |
const jwt = require('jsonwebtoken');
//midleware
module.exports= function (req,res,next){
const token = req.header('auth-token');
if (!token) return res.status(401). send('invalid');
try{
const varified =jwt.verify(token,process.env.TOKEN_SECRET);
req.user= varified;
next();
}catch(errr){
res.status(400).send('invalid token ')
}
} |
import React from 'react';
import {Link} from 'react-router-dom';
export class ChapterTestTable extends React.Component{
render(){
return (
<table className="table table-hover">
<thead>
<ChapterTestTableHeader />
</thead>
<tbody>
{Array.isArray(this.props.testList)?
this.props.testList.map((test,index)=>{
return <ChapterTestTableBodyRow key={index}
test={test} {...this.props} />;
})
:<tr><td>Empty list!</td></tr>}
</tbody>
</table>
);
}
};
let ChapterTestTableHeader=(props)=>{
return (
<tr>
<th scope="col" >#ID</th>
<th scope="col" className="desktop-heading">Name</th>
<th scope="col">Description</th>
<th scope="col" className="desktop-heading" >Course</th>
<th scope="col" className="desktop-heading">Subject</th>
<th scope="col" className="desktop-heading" >Chapter</th>
<th scope="col"></th>
</tr>
);
};
class ChapterTestTableBodyRow extends React.Component{
render(){
if(this.props.test){
return (
<tr>
<th scope="row" >{this.props.test.id}</th>
<td className="desktop-heading">{this.props.test.name}</td>
<td>{this.props.test.desc}</td>
<td className="desktop-heading">{this.props.test.courseName?this.props.test.courseName:''}</td>
<td className="desktop-heading">{this.props.test.subjectName?this.props.test.subjectName:''}</td>
<td className="desktop-heading">{this.props.test.chapterName?this.props.test.chapterName:''}</td>
<td><Link to={`${this.props.match.url}/test/`+this.props.test.id}
className="btn btn-primary">Take</Link></td>
</tr>
);
}else{
return <tr>
<td>Test Not found</td>
</tr>;
}
}
}; |
'use strict'
// Currently implemented round robin to the nodes - other startegies, like main node, fallback nodes
// needs to be implemented
var http = require('http')
var https = require('https')
var urlParser = require('url')
/* var optionTemplate = {
host: 'localhost',
path: '/_sql?types',
port: '4200',
method: 'POST',
headers: {
'Connection': 'keep-alive'
}
} */
var httpOptions = []
var httpOptionsBlob = []
var lastUsed = 0
// limit number of sockets
http.globalAgent.maxSockets = 10
function getNextNodeOptions (type) {
lastUsed += 1
if (lastUsed > httpOptions.length - 1) {
lastUsed = 0
}
if (type === 'blob') {
return httpOptionsBlob[lastUsed]
}
return httpOptions[lastUsed]
}
function getRequest (nodeOptions, callback) {
if (nodeOptions.protocol === 'https') {
return https.request(nodeOptions.httpOpt, callback)
}
return http.request(nodeOptions.httpOpt, callback)
}
function parseStringOptions (opt) {
var nodes = opt.split(' ')
var nodeInfos = nodes.map(function (node) {
var urlFields = urlParser.parse(node)
urlFields.protocol = urlFields.protocol.replace(':', '')
return urlFields
})
return nodeInfos
}
module.exports = {
// optionString e.g. "https://localhost:9200 http://myserver:4200"
connect: function connect (optionString) {
var options = parseStringOptions(optionString)
options.forEach(function (e) {
httpOptions.push({
httpOpt: {
host: e.hostname,
port: e.port || 4200,
path: '/_sql?types',
method: 'POST',
headers: {
'Connection': 'keep-alive'
}
},
protocol: e.protocol
})
httpOptionsBlob.push(e.protocol + '://' + e.hostname + ':' + e.port + '/_blobs/')
})
},
getSqlRequest: function getSqlRequest (callback) {
var options = getNextNodeOptions('sql')
return getRequest(options, callback)
},
getBlobUrl: function getBlobUrl () {
return getNextNodeOptions('blob')
},
getHttpOptions: function getHttpOptions () {
return getNextNodeOptions('sql').httpOpt
}
}
|
import React from 'react';
const FilteredListNonReusable = ({ list, side }) => {
const filteredList = list.filter(char => char.side === side);
return filteredList.map(char => (
<div key={char.name}>
<div>Character: {char.name}</div>
<div>Side: {char.side}</div>
</div>
));
}
export default FilteredListNonReusable;
|
export default function UIDropdownDirective () {
return {
restrict: 'A',
link: (scope, element) => {
if (typeof element.dropdown !== 'undefined') {
element.dropdown()
}
}
}
}
|
/**
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('audioCat.state.envelope.ControlPoint');
goog.provide('audioCat.state.envelope.ControlPoint.compareByTime');
goog.require('audioCat.state.envelope.ControlPointChangedEvent');
goog.require('audioCat.utility.EventTarget');
goog.require('goog.math');
/**
* Allows a user to carefully specify bounds of an envelope.
* @param {!audioCat.utility.IdGenerator} idGenerator Generates an ID unique
* throughout the application.
* @param {number} time The time in seconds at which the control point is
* located.
* @param {number} value The value at which the control point is located.
* The value should be within [min, max] as defined by the envelope.
* @constructor
* @extends {audioCat.utility.EventTarget}
*/
audioCat.state.envelope.ControlPoint = function(idGenerator, time, value) {
goog.base(this);
/**
* An ID unique to this control point.
* @private {!audioCat.utility.Id}
*/
this.id_ = idGenerator.obtainUniqueId();
/**
* The time in seconds.
* @private {number}
*/
this.time_ = time;
/**
* The value.
* @private {number}
*/
this.value_ = value;
};
goog.inherits(
audioCat.state.envelope.ControlPoint, audioCat.utility.EventTarget);
/**
* Sets the time-value combination of the control point.
* @param {number} time The new time in seconds.
* @param {number} value The new value.
*/
audioCat.state.envelope.ControlPoint.prototype.set = function(time, value) {
var previousTime = this.time_;
var previousValue = this.value_;
this.time_ = time;
this.value_ = value;
this.dispatchEvent(new audioCat.state.envelope.ControlPointChangedEvent(
previousTime, previousValue, time, value));
};
/**
* @return {number} The time of the control point.
*/
audioCat.state.envelope.ControlPoint.prototype.getTime = function() {
return this.time_;
};
/**
* @return {number} The value of the control point.
*/
audioCat.state.envelope.ControlPoint.prototype.getValue = function() {
return this.value_;
};
/**
* @return {number} The unique ID of the control point.
*/
audioCat.state.envelope.ControlPoint.prototype.getId = function() {
return this.id_;
};
/**
* Static method for comparing two control points by their times.
* @param {!audioCat.state.envelope.ControlPoint} point1
* @param {!audioCat.state.envelope.ControlPoint} point2
* @return {number} A negative number if point1 occurs first, a positive number
* if point2 occurs first. If times are the same, does an ID comparison.
*/
audioCat.state.envelope.ControlPoint.compareByTime = function(point1, point2) {
var time1 = point1.getTime();
var time2 = point2.getTime();
if (goog.math.nearlyEquals(time1, time2)) {
// The arguments are only equal if they have the same ID. This is
// important for binary search to work correctly.
return point1.getId() - point2.getId();
}
return time1 - time2;
};
|
// npm i mysql request
// 然后node执行
'use strict';
const password = '';
const port = '';
const msger = ''; // 消息接受者 为空则不发消息
// 先执行 npm i mysql
const mysql = require('mysql');
const request = require('request');
mysql && console.log('mysql加载成功...');
const args = process.argv.splice(2);
console.log('密码:' + password);
const option = {
host: 'localhost',
user: 'root',
password: password || '',
port: port || '3306',
database: 'mysql',
};
const connection = mysql.createConnection(option);
connection.connect();
console.log('mysql连接' + connection.state);
const selectUsers = `select distinct concat("'", user, "'", "@", "'", host, "'") as user from mysql.user`;
let userList = [];
let grants = '';
let output = '';
connection.query(selectUsers, function (error, results, fields) {
if (error) {
console.log('查询出错');
throw error;
};
userList = results.map(i => i.user);
let L = userList.length;
userList.forEach(user => {
const sql = `show grants for ${user}`;
let connectionI = mysql.createConnection(option);
connectionI.query(sql, function (error, results, fields) {
if (error) {
console.log('查询权限出错');
throw error;
}
let key = Object.keys(results[0])[0];
grants += `${key}\n`;
results.forEach(rowI => {
let str = `${rowI[key]}\n`;
grants += str;
});
L--;
if (L <= 0) {
output += ('数据库审计\n');
output += (`\n`);
output += ('1.当前数据库的用户\n');
output += (userList.join('\n'));
output += (`\n\n`);
output += ('2.当前数据库的用户权限\n');
output += (grants);
console.log(output);
const msgUrl = `http://im.2980.com:8088/sendmsg?digitids=${msger}&content=${encodeURIComponent(output)}`;
msger && request(msgUrl);
}
});
connectionI.end();
});
});
connection.end();
|
var http = require('http');
var fs = require('fs');
http.createServer(function (req, rsp) {
rsp.writeHead(200, {
'Content-Type': 'image/pjpeg'
});
var imgFile = fs.createReadStream('./assets/xp.jpg');
imgFile.pipe(rsp);
}).listen(8089);
console.log('Listening on port 8089 ...'); |
import React from 'react';
import PropTypes from 'prop-types';
import { Redirect } from 'react-router';
import { withStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import { connect } from 'react-redux';
import CircularProgress from '@material-ui/core/CircularProgress';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Divider from '@material-ui/core/Divider';
import Typography from '@material-ui/core/Typography';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import moment from 'moment';
import { history } from '../../configureStore.js';
import { saveComment, getProfesor } from './_actions';
const maxResults = 20;
const styles = theme => ({
root: {
flexGrow: 1,
height: 'calc(100% - 71px)',
},
divider: {
margin: '10px 0 15px 0',
},
container: {
display: 'flex',
textAlign: 'center',
},
card: {
margin: theme.spacing.unit,
},
textField: {
marginLeft: theme.spacing.unit,
marginRight: theme.spacing.unit,
},
results: {
display: 'flex',
flexGrow: 1,
flexWrap: 'wrap',
},
progress: {
margin: theme.spacing.unit * 2,
},
});
class Profesor extends React.Component {
state = {
comment: '',
};
componentDidMount() {
const { profesorId } = this.props.match.params;
this.props.getProfesor(profesorId);
}
componentDidUpdate(prevProps) {
if (!this.props.saving && prevProps.saving) {
// se guardo el comentario, tenemos que borrar la entrada
if (this.state.comment) this.setState({ comment: '' });
}
}
handleChange = name => (event) => {
this.setState({
[name]: event.target.value,
});
};
saveComment = () => {
const { profesorId } = this.props.match.params;
this.props.saveComment(this.state.comment, profesorId);
}
render() {
const {
classes, location, token, comentarios, loading, profesor, saving,
} = this.props;
const results = comentarios;
if (!token) {
return (
<Redirect
to={{
pathname: '/',
state: { from: location },
}}
/>
);
}
return loading ? <CircularProgress className={classes.progress} /> : (
<div>
{profesor ? (
<Typography variant="h4" className={classes.title} color="textSecondary" gutterBottom>
{profesor.nombre}
{' '}
{profesor.apellidos }
</Typography>
) : undefined}
{results.length > 0 ? results.slice(0, maxResults).map(({
id,
Autore,
createdAt,
comentario,
}) => (
<Card key={id} className={classes.card}>
<CardContent>
<Typography color="textSecondary">
{(Autore || { nombre: 'Anónimo' }).nombre}
{' '}
{moment(createdAt).fromNow()}
</Typography>
<Divider className={classes.divider} />
<Typography color="textSecondary">
{comentario}
</Typography>
</CardContent>
</Card>
)) : undefined}
<Card className={classes.card}>
<CardContent>
<TextField
multiline
fullWidth
id="comment"
label="Añadir comentario"
className={classes.textField}
value={this.state.comment}
onChange={this.handleChange('comment')}
margin="normal"
variant="outlined"
/>
<Button
variant="contained"
color="primary"
disabled={saving}
className={classes.button}
onClick={this.saveComment}
>
Guardar Comentario
</Button>
</CardContent>
</Card>
</div>
);
}
}
Profesor.propTypes = {
classes: PropTypes.object,
getProfesor: PropTypes.func,
location: PropTypes.object,
comentarios: PropTypes.array,
saveComment: PropTypes.func,
token: PropTypes.string,
saving: PropTypes.bool,
};
const mapStateToProps = ({ auth, profesor }) => ({
token: auth.token,
comentarios: profesor.data,
loading: profesor.loading,
profesor: profesor.profesor,
saving: profesor.saving,
});
export default connect(mapStateToProps, { getProfesor, saveComment })(withStyles(styles)(Profesor));
|
import Head from 'next/head';
import { connect } from 'react-redux';
import { useEffect } from 'react';
import UserAvailability from '../components/UserAvailability';
import SignUp from '../components/SignUp';
import Layout from '../components/Layout';
import { useRouter } from 'next/router';
import { Spinner } from 'react-bootstrap';
function Home(props) {
let loadScreen = props.user ? <UserAvailability/> : <SignUp/>;
return (
<div className="container">
<Head>
<title>Covid19 Vaccine Notifier</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
{loadScreen}
</main>
</div>
)
}
function mapStateToProps(state) {
return {
user: state.auth.user,
authLoaded: state.auth.authLoaded
}
}
export default connect(mapStateToProps)(Home);
|
'use strict';
import gulp from 'gulp';
import runSequence from 'run-sequence';
gulp.task('dev', ['clean'], function(cb) {
global.isProd = false;
global.env = 'development';
runSequence('browserify', 'watch', cb);
}); |
const chai = require('chai');
const chaiHttp = require('chai-http');
const server = require('../../server.js');
const should = chai.should();
const mongoose = require('mongoose');
const { user } = require('../../models');
// setup chai to use http assertion
chai.use(chaiHttp);
// create our testUser
const testUser = {
username: 'testuser',
password: 'test111',
email: 'test@test.com',
role: 0
};
const testUser2 = {
username: 'testuser2',
password: 'test2222',
email: 'test2@test.com',
role: 0
};
const testUser3 = {
username: 'testuser3',
password: 'test3333',
email: 'test3@test.com',
role: 0
};
const testUser4 = {
username: 'testuser4',
password: 'test4444',
email: 'test4@test.com',
role: 0
};
// start our tests
describe('Users', () => {
// delete test user after testing completed
after(async () => {
await user.deleteMany({ username: 'testuser' })
})
// get all test
it('should return json for request at /users GET', async () => {
const res = await chai.request(server).get(`/users`);
res.should.have.status(200);
res.should.be.json;
});
// get one test
it('should return json for request at /users?_id= GET', async () => {
const newUser = await user.create(testUser);
const res = await chai.request(server).get(`/users?_id=${newUser._id}`);
res.should.have.status(200);
res.should.be.json;
});
// create one test
it('should return json for request at /users?_id= CREATE', async () => {
const newUser = await user.create(testUser2);
const res = await
chai.request(server).post(`/users`).send(testUser2);
res.should.have.status(200);
res.should.be.json;
});
// update one test
it('should return json for request at /users?_id= UPDATE', async () => {
const newUser = await user.create(testUser3);
const updates = {
removed: true
};
const res = await chai.request(server).put(`/users?_id=${newUser._id}`).send(updates);
res.should.have.status(200);
res.should.be.json;
});
// delete one test
it('should return json for request at /users?_id= DELETE', async () => {
const newUser = await user.create(testUser4);
const res = await chai.request(server).delete(`/users?_id=${newUser._id}`);
res.should.have.status(200);
res.should.be.json;
});
});
|
import indexRouter from "./index/employee";
import addRouter from "./add/employee";
import addOrEditRouter from "./add-or-edit/employee";
import removeRouter from "./remove/employee";
import randomRouter from "./random/employee";
import detailRouter from "./detail/employee";
export default [
indexRouter,
addRouter,
addOrEditRouter,
removeRouter,
randomRouter,
detailRouter
];
|
import {combineReducers} from "redux";
import { reducer as formReducer } from "redux-form";
import authReducer from "./authReducer";
import eduReducer from "./eduReducer";
const rootReducer = combineReducers({
form: formReducer,
auth: authReducer,
edu: eduReducer
});
export default rootReducer;
|
var _ = require('lodash');
_.mixin(require('lodash-deep'));
var findParent = function (object, path, callback) {
var parent = object;
var key = path;
var keys = path.split('.');
if (keys.length > 1) {
for (var i = 0, length = keys.length - 1; i < length; i++) {
parent = parent[keys[i]] || (parent[keys[i]] = {});
key = keys[i + 1];
}
}
callback(parent, key);
};
// Tracks dependency loading to trap circular dependencies
var modulesBeingLoaded = [];
/**
* Export both a function to define new modules as well as the factory registry itself.
*
* @usage:
* require('factory')('module', function (factory) {
*
* return {
* foo: function () { return factory.bar; } // bar is loaded lazily
* };
* })
*/
var app = module.exports = function (path, module) {
if (path && module) {
// First see if module exists
var candidate = _.deepGet(app, path);
if ((_.isNull(candidate) && _.isUndefined(candidate))) {
throw new Error('Module ' + path + ' already exists');
}
findParent(app, path, function (factory, key) {
// This closure contains private vars for factory registration
var instance;
Object.defineProperty(factory, key, {
get: function () {
// Circular Dependency check
if (modulesBeingLoaded.indexOf(path) !== -1) {
throw new Error('Circular dependency. ' + path + ' is still being loaded');
}
if (!instance) {
// Mark path as being loaded
modulesBeingLoaded.push(path);
// Load module
instance = module(app);
// Done loading, remove path
modulesBeingLoaded.splice(modulesBeingLoaded.indexOf(path), 1);
}
return instance;
},
enumerable: true,
configurable: true
});
});
}
var dsl = {
// Return helper methods
reset: function () {
for (var key in app) {
delete app[key];
}
}
};
return dsl;
}; |
import test from "tape"
import { push } from ".."
test("push", t => {
t.deepEqual(push(null)([1]), [1, null], "(null)([]) should equal [null]")
t.deepEqual(
push(undefined)([]),
[undefined],
"(undefined)([]) should equal [undefined]"
)
t.deepEqual(push([])([]), [[]], "([])([]) should equal [[]]")
t.deepEqual(
push(1, null, undefined)([]),
[1, null, undefined],
"(1, null, undefined)([]) should equal [1, null, undefined]"
)
t.end()
})
|
const { withExpo } = require('@expo/next-adapter');
const withFonts = require('next-fonts');
const withImages = require('next-images');
module.exports = withExpo(withFonts(withImages({
projectRoot: __dirname,
target: 'serverless'
}))
);
|
'use strict';
var forEach = require('lodash/collection/each');
function signinButtons(elements, config){
forEach(elements, function(el){
window.google.identitytoolkit.signInButton(el, config);
});
}
module.exports = signinButtons;
|
// ------------------- Constants
var BG = 'white';
var HEIGHT = 600;
var WIDTH = 700;
var GRAVITY = .2;
var FRICTION = .9;
var KEYS = {
SPACE: 32,
UP: 38,
RIGHT: 39,
LEFT: 37
};
// ------------------- Vars
var canvas, ctx, gameLoop, player;
var keysPressed = {};
// ------------------- Player class
function Player(opts) {
this.x = opts && opts.x || 0;
this.y = opts && opts.y || 0;
this.width = opts && opts.width || 20;
this.height = opts && opts.height || 20;
this.color = opts && opts.color || 'blue';
this.image = new Image();
this.jumping = false;
this.velX = opts && opts.velX || 0;
this.velY = opts && opts.velY || -5;
this.speed = opts && opts.speed || 3;
}
Player.prototype.draw = function() {
if (this.image) {
ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
} else {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
};
Player.prototype.update = function() {
player.velX *= FRICTION;
player.velY += GRAVITY;
player.x += player.velX;
player.y += player.velY;
this.constrain();
};
Player.prototype.constrain = function() {
if (this.x <= 0) this.x = 0;
if (this.x + this.width > WIDTH) this.x = WIDTH - this.width;
if (this.y >= HEIGHT - this.height) {
this.y = HEIGHT - this.height;
this.jumping = false;
}
};
function initPlayer() {
player = new Player({
width: 100,
height: 163
});
player.y = HEIGHT - player.height;
player.image.src = 'assets/img/player.jpg';
}
// ------------------- Input functions
function onKeydown(e) {
keysPressed[e.keyCode] = true;
}
function onKeyup(e) {
keysPressed[e.keyCode] = false;
}
// ------------------- Main functions
function init() {
canvas = document.createElement('canvas');
ctx = canvas.getContext('2d');
canvas.width = WIDTH;
canvas.height = HEIGHT;
initPlayer();
document.body.appendChild(canvas);
document.addEventListener('keydown', onKeydown);
document.addEventListener('keyup', onKeyup);
gameLoop = function() {
update();
draw();
requestAnimationFrame(gameLoop);
};
requestAnimationFrame(gameLoop);
}
function draw() {
ctx.fillStyle = BG;
ctx.fillRect(0, 0, WIDTH, HEIGHT);
player.draw();
}
function update() {
if (keysPressed[KEYS.UP] || keysPressed[KEYS.SPACE]) {
if(!player.jumping){
player.jumping = true;
player.velY = -player.speed * 2;
}
}
if (keysPressed[KEYS.RIGHT]) player.velX++;
if (keysPressed[KEYS.LEFT]) player.velX--;
player.update();
}
init();
|
import styled from 'styled-components'
export const InputWrapper = styled.div`
width: 100%;
padding: 16px;
box-sizing: border-box;
label {
p {
font-weight: bold;
}
.input {
padding: 16px;
box-sizing: border-box;
width: 100%;
border: 1px solid black;
}
}
` |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const network = require("./network");
const sidebar = require("./sidebar");
const header = require("./sidebar/header");
const buttonCallbacks_1 = require("./sidebar/entriesTreeView/buttonCallbacks");
const tabs = require("./tabs");
const tabsAssets = require("./tabs/assets");
const tabsTools = require("./tabs/tools");
const homeTab = require("./tabs/homeTab");
function start() {
document.body.hidden = false;
// Development mode
if (localStorage.getItem("ValjangEngine-dev-mode") != null) {
const projectManagementDiv = document.querySelector(".project-management");
projectManagementDiv.style.backgroundColor = "#37d";
// According to http://stackoverflow.com/a/12747364/915914, window.onerror
// should be used rather than window.addEventListener("error", ...);
// to get all errors, including syntax errors.
window.onerror = onWindowDevError;
}
// Global controls
const toggleNotificationsButton = document.querySelector(".top .controls button.toggle-notifications");
toggleNotificationsButton.addEventListener("click", onClickToggleNotifications);
if (localStorage.getItem("ValjangEngine-disable-notifications") != null) {
toggleNotificationsButton.classList.add("disabled");
toggleNotificationsButton.title = SupClient.i18n.t("project:header.notifications.enable");
}
else {
toggleNotificationsButton.classList.remove("disabled");
toggleNotificationsButton.title = SupClient.i18n.t("project:header.notifications.disable");
}
sidebar.start();
tabs.start();
network.connect();
}
SupClient.i18n.load([{ root: "/", name: "project" }, { root: "/", name: "badges" }], start);
window.addEventListener("message", onMessage);
function onMessage(event) {
switch (event.data.type) {
case "chat":
homeTab.onMessageChat(event.data.content);
break;
case "hotkey":
onMessageHotKey(event.data.content);
break;
case "openEntry":
tabsAssets.open(event.data.id, event.data.state);
break;
case "setEntryRevisionDisabled":
tabsAssets.setRevisionDisabled(event.data.id, event.data.disabled);
break;
case "openTool":
tabsTools.open(event.data.name, event.data.state);
break;
case "error":
onWindowDevError();
break;
case "forwardKeyboardEventToActiveTab":
onForwardKeyboardEventToActiveTab(event.data.eventType, event.data.ctrlKey, event.data.altKey, event.shiftKey, event.metaKey, event.data.keyCode);
break;
}
}
function onWindowDevError() {
const projectManagementDiv = document.querySelector(".project-management");
projectManagementDiv.style.backgroundColor = "#c42";
return false;
}
function onMessageHotKey(action) {
switch (action) {
case "newAsset":
buttonCallbacks_1.onNewAssetClick();
break;
case "newFolder":
buttonCallbacks_1.onNewFolderClick();
break;
case "searchEntry":
buttonCallbacks_1.onSearchEntryDialog();
break;
case "filter":
buttonCallbacks_1.onToggleFilterStripClick();
break;
case "closeTab":
tabs.onClose();
break;
case "previousTab":
tabs.onActivatePrevious();
break;
case "nextTab":
tabs.onActivateNext();
break;
case "run":
header.runProject();
break;
case "debug":
header.runProject({ debug: true });
break;
case "devtools":
if (SupApp != null)
SupApp.getCurrentWindow().webContents.toggleDevTools();
break;
}
}
function onClickToggleNotifications(event) {
let notificationsDisabled = (localStorage.getItem("ValjangEngine-disable-notifications") != null) ? true : false;
notificationsDisabled = !notificationsDisabled;
if (!notificationsDisabled) {
localStorage.removeItem("ValjangEngine-disable-notifications");
event.target.classList.remove("disabled");
event.target.title = SupClient.i18n.t("project:header.notifications.disable");
}
else {
localStorage.setItem("ValjangEngine-disable-notifications", "true");
event.target.classList.add("disabled");
event.target.title = SupClient.i18n.t("project:header.notifications.enable");
}
}
function onForwardKeyboardEventToActiveTab(eventType, ctrlKey, altKey, shiftKey, metaKey, keyCode) {
const event = new KeyboardEvent(eventType, { ctrlKey, altKey, shiftKey, metaKey });
Object.defineProperty(event, "keyCode", { value: keyCode });
const activePaneElt = tabs.panesElt.querySelector(".pane-container.active");
const activeIframe = activePaneElt.querySelector("iframe");
activeIframe.contentDocument.dispatchEvent(event);
}
|
const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const passport = require('passport')
const app = express()
//
const user = require('./routes/api/user')
const profile = require('./routes/api/profile')
const chat = require('./routes/api/chat')
// mongo config
const dbURI = require('./config/mongo').uri
// 使用body-parser中间件
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
// connect to mongodb
mongoose.connect(dbURI, {useNewUrlParser: true}).then(() => {
console.log('Mongodb Connected')
}).catch(err => {
console.log(err)
})
// 初始化passport
app.use(passport.initialize())
require('./config/passport')(passport)
app.use('/api/user', user)
app.use('/api/profile', profile)
app.use('/api/chat', chat)
const port = process.env.PORT || 5000
app.listen(port, () => {
console.log(`Server running on port:${port}`)
})
|
var chai = require('chai');
var chaiHttp = require('chai-http');
var should = chai.should();
var server= 'https://politrap-api.herokuapp.com'
var got = require('got');
chai.use(chaiHttp);
describe('Evidences', function() {
it('should add a new evidence to database when requested', function(done) {
random_id = '5a03876885614300126960d0';
chai.request(server)
.get('/api/commitments/'+random_id+'/evidences/')
.end(function(err, res){
res.should.have.status(200);
//res.body.should.be.json;
res.body[0].should.be.a('object');
res.body[0].should.have.property('data');
res.body[0].should.have.property('description');
done();
});
});
it('should upload the evidences in the correct format', function(done) {
random_id = '5a03876885614300126960d0';
chai.request(server)
.get('/api/commitments/'+random_id+'/evidences')
.end(function(err, res){
res.should.have.status(200);
//res.body.should.be.json;
res.body[0].should.be.a('object');
res.body[0].should.have.property('data');
res.body[0].data.should.match(/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/)
done();
});
});
});
|
const ExtendableError = require('./ExtendableError')
module.exports = class extends ExtendableError {
constructor () {
super('Token is invalid or has expired', 'WRONG_TOKEN', 406)
}
}
|
var TuiGridUtility = new Object();
TuiGridUtility.setDefaults = function() {
tui.Grid.setLanguage('ko');
tui.Grid.applyTheme('default', {
selection: {
background: '#4daaf9',
border: '#004082'
},
scrollbar: {
background: '#f5f5f5',
thumb: '#d9d9d9',
active: '#c1c1c1'
},
row: {
even: {
background: '#eef2f6'
},
hover: {
background: '#d3ebf6'
}
},
cell: {
normal: {
background: '#fbfbfb',
border: '#e0e0e0',
showVerticalBorder: true
},
header: {
background: '#eee',
border: '#ccc',
showVerticalBorder: true
},
rowHeader: {
border: '#ccc',
showVerticalBorder: true
},
editable: {
background: '#fbfbfb'
},
selectedHeader: {
background: '#d8d8d8'
},
focused: {
border: '#418ed4'
},
disabled: {
text: '#b0b0b0'
}
}
});
$(function() {
$(window).scroll(function(){
var scroll = $(window).scrollTop();
if(scroll>100){
$(".navbar").css("background","#0b70b9");
}
else{
$(".navbar").css("background","transparent");
}
});
});
};
TuiGridUtility.getWhetherCreatedRows = function(gridInstance, rowKey) {
var createRowList = gridInstance.getModifiedRows().createdRows;
var isCreatedRow = false;
$.each(createRowList, function(i, iv) {
if(iv.rowKey == rowKey) {
isCreatedRow = true;
}
});
return isCreatedRow;
}
TuiGridUtility.checkEmptyDataWhenSave = function(gridInstance, excludeColumnName) {
var result = false;
var dataList = gridInstance.getData();
$.each(dataList, function(i, iv) {
$.each(dgMain.getColumns(), function(k, kv) {
if(excludeColumnName.indexOf(kv.name) != -1 || kv.name == 'createDt' || kv.name == 'updateDt' || kv.name == 'manageControl' || kv.name == 'rowKey' || kv.name == 'sortKey') { return; }
if(iv[kv.name] == null || iv[kv.name] == "") { result = true; }
});
});
return result;
}
TuiGridUtility.selectOptionFormatter = function(selectOptions, props) {
var result = "";
$.each(selectOptions, function(i, iv) {
if(props.value == iv.value) {
result = iv.text;
}
});
return result;
}
TuiGridUtility.getImageRenderer = function(props) {
var el = document.createElement('img');
var replaceSrc = '/assets/images/replace_image.png';
var src = replaceSrc;
el.className = 'grid_image'
el.src = src;
el.onerror = function(d) { el.src = replaceSrc; }
this.getElement = function() {
return el;
};
this.render = function(props) {
if(props.value != null && props.value != '') { src = props.value; }
el.src = src;
};
this.render(props);
}; |
var express = require('express');
var mongoose = require('mongoose');
// var db = mongoose.connect('mongodb://localhost/prueba_1');
// var Schema = mongoose.Schema;
var app = express();
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
// var id = req.params.id;
// var empresas = mongoose.model('dc', db);
// empresas.find(function (err, empresa) {
// console.log(empresa);
// if (err) {
// return res.status(500).json({
// message: 'Error when getting empresa.',
// error: err
// });
// }
// return res.json(empresa);
// }).limit(2);
res.send('HOLA BUSCADOR')
});
// router.get('/:id', function(req, res, next) {
// var empresas = db.model('res', new Schema());
// empresas.find(function (err, empresa_sri) {
// if (err) {
// return res.status(500).json({
// message: 'Error when getting empresa.',
// error: err
// });
// }
// return res.json({data: empresa_sri});
// }).limit(2);
// });
module.exports = router; |
function openModal(id) {
$('#' + id).removeClass('closed').addClass('open');
}
function closeModal(id){
$('#' + id).removeClass('open').addClass('closed');
}
|
import React from 'react';
import fakeData from './getUserData';
function UserDetail({ match, history, props }) {
const user = fakeData.filter((user) => {
return String(user.id) === match.params.id;
});
console.log(history)
return (
<div>
<h2>User Detail</h2>
<img src="https://randomuser.me/api/portraits/women/11.jpg" alt=""/>
<div>이름 : {user[0].name}</div>
<div>이메일 : {user[0].email} </div>
<div>모바일 : {user[0].phone}</div>
<button onClick={() => history.goBack()}>Back</button>
</div>
);
}
export default UserDetail;
|
(function () {
"use strict";
angular.module("vcas").controller("IptvCtrl", IptvCtrl);
/* @ngInject */
function IptvCtrl($scope) {
var vm = this;
vm.title = "IPTV";
}
}());
|
var findJudge = function(N, trust) {
let arr = new Array(N+1);
arr.fill(0);
let ans = -1;
trust.forEach(comb => {
arr[comb[0]] = -1;
arr[comb[1]]++;
})
arr.forEach((person, i) => {
if (person === N-1) ans = i;
})
console.log(arr)
return ans;
};
// console.log(findJudge(3, [[1,3],[2,3],[3,1]]))
console.log(findJudge(2, [[1,2]])) |
import React, { Component } from 'react';
import { Control, LocalForm, Errors } from 'react-redux-form';
import { Button, Col, Label, Row } from 'reactstrap';
import './ComponentView.css'
const required = (val) => val && val.length;
const maxLength = (len) => (val) => !(val) || (val.length <= len);
const minLength = (len) => (val) => val && (val.length >= len);
const isNumber = (value) => isNaN(Number(value));
export class NotNeighbourComponent extends Component {
closeCountryFindHandler = (values) => {
let countryCode = values.CountryName.toUpperCase();
const countries = this.props.countries;
this.props.closeCountryFind(countryCode, countries);
}
render() {
//according to the state rendering the data.
let showCountry
if (this.props.closeCountryNotNeighbour) {
showCountry = <div>This is the closest country to it that is not a neighbour: {this.props.closeCountryNotNeighbour} </div>
}
else {
showCountry = <div>Please enter the alphacode country to see the closest country to it that is not a neighbour of that country</div>
}
return (
<div className="container">
<div className="col-12 col-md-9">
<LocalForm className="view" onSubmit={(values) => this.closeCountryFindHandler(values)}>
<Row className="form-group">
<Label htmlFor="CountryName" md={3}><strong>Country Name</strong></Label>
<Col md={5}>
<Row>
<Control.text model=".CountryName" className="form-control" name="CountryName" id="CountryName" placeholder="Please enter the Country Name"
validators={{
required,
minLength: minLength(2),
maxLength: maxLength(15),
isNumber
}} />
<Errors
className="text-danger"
model=".CountryName"
show="touched"
messages={{
required: 'Required',
minLength: 'Must have 3 length',
maxLength: ' Must have 3 length',
isNumber: "Can't use numbers"
}} />
</Row>
</Col>
</Row>
<Button type="submit" value="submit">Find Close Country</Button>
<Row>
<Col><strong>{showCountry}</strong>
</Col>
</Row>
</LocalForm>
</div>
</div>
)
}
}
export default NotNeighbourComponent
|
/*
* Copyright (C) 2021 Radix IoT LLC. All rights reserved.
*/
multipleValuesFactory.$inject = [];
function multipleValuesFactory() {
const empty = {};
class MultipleValues {
constructor(length) {
this.values = Array(length);
this.valuesSet = new Set();
if (length > 0) {
this.valuesSet.add(empty);
}
}
addEmpty(count = 1) {
this.values.length = this.values.length + count;
this.valuesSet.add(empty);
}
addValue(value) {
this.values.push(value);
this.valuesSet.add(value);
}
first() {
return this.values[0];
}
firstNonEmpty() {
return this.values.find(v => !!v);
}
firstNonNull() {
return this.values.find(v => v != null);
}
hasValue(i) {
return this.values.hasOwnProperty(i);
}
getValue(i) {
return this.values[i];
}
hasMultipleValues() {
return true;
}
has(v) {
return this.values.includes(v);
}
hasAny(values) {
return values.some(v => this.values.includes(v));
}
hasEvery(values) {
return values.every(v => this.values.includes(v));
}
isAllEqual() {
//const first = this.first();
//return this.values.every((v, i, arr) => arr.hasOwnProperty(i) && v === first);
try {
return this.valuesSet.size <= 1;
} catch (e) {
// AngularJS does a deep copy of this object when doing debug logging, getting the size of the set subsequently fails
// fall back to using array
const first = this.first();
return this.values.every((v, i, arr) => arr.hasOwnProperty(i) && v === first);
}
}
valueOf() {
if (this.isAllEqual()) {
return this.first();
}
return this;
}
toString() {
if (this.isAllEqual()) {
return String(this.first());
}
//return `<<multiple values (${this.values.length})>>`;
return `<<multiple values (${this.valuesSet.size})>>`;
}
toJSON() {
return this.valueOf();
}
static fromArray(arr) {
const combined = arr.reduce((combined, item, i) => {
return this.combineInto(combined, item, i);
}, null);
if (combined != null) {
return this.replaceEqualValues(combined);
}
}
/**
* The option removeEmptyObjects was added so we didn't send an empty purgePeriod object which caused validation to fail.
* However this also strips the tags object from data points so it is impossible to remove all tags from a data point.
* We add an empty tags object back to the data points in dataPointEditor.js saveMultiple().
*/
static toArray(obj, length, removeEmptyObjects = true) {
return Array(length).fill().map((v, i) => {
return this.splitCombined(obj, i, removeEmptyObjects);
});
}
/**
* Constructs an object with MultipleValues properties from an array of objects
*/
static combineInto(dst, src, index) {
// dst can be a multiple if we previously encountered this key containing a primitive (e.g. null)
if (dst == null || dst instanceof this) {
dst = Array.isArray(src) ? [] : Object.create(Object.getPrototypeOf(src));
}
// check for different dst/src types
const allKeysSet = new Set(Object.keys(src));
Object.keys(dst).forEach(k => allKeysSet.add(k));
allKeysSet.forEach(key => {
const srcValue = src[key];
const dstValue = dst[key];
if (srcValue != null && typeof srcValue === 'object') {
dst[key] = this.combineInto(dstValue, srcValue, index);
} else {
let multiple;
if (dstValue instanceof this) {
multiple = dstValue;
} else if (dstValue != null && typeof dstValue === 'object') {
// previously encountered this key as an object/array, wont override this with a MultipleValues of a primitive
// instead merge an empty object in
dst[key] = this.combineInto(dstValue, Array.isArray(dstValue) ? [] : {}, index);
return;
} else {
dst[key] = multiple = new this(index);
}
if (src.hasOwnProperty(key)) {
multiple.addValue(srcValue);
} else {
multiple.addEmpty();
}
}
});
return dst;
}
/**
* Traverses the object tree and replaces MultipleValues properties which have the same value with the primitive value
*/
static replaceEqualValues(obj) {
Object.keys(obj).forEach(key => {
const value = obj[key];
if (value instanceof this) {
obj[key] = value.valueOf();
} else if (value != null && typeof value === 'object') {
this.replaceEqualValues(value);
} else {
throw new Error('Values should always be an object or array');
}
});
return obj;
}
/**
* Splits a combined object with MultipleValues property values into an array of objects
*/
static splitCombined(src, index, removeEmptyObjects = true) {
const dst = Array.isArray(src) ? [] : Object.create(Object.getPrototypeOf(src));
Object.keys(src).forEach(key => {
const srcValue = src[key];
if (srcValue instanceof this) {
if (srcValue.hasValue(index)) {
dst[key] = srcValue.getValue(index);
}
} else if (srcValue != null && typeof srcValue === 'object') {
const result = this.splitCombined(srcValue, index);
if (!removeEmptyObjects || Object.keys(result).length) {
dst[key] = result;
}
} else {
dst[key] = srcValue;
}
});
return dst;
}
/**
* Checks form controls with untouched MultipleValues models are set to valid
*/
static checkFormValidity(form) {
form.$getControls().forEach(control => {
if (typeof control.$getControls === 'function') {
this.checkFormValidity(control);
} else if (control.$modelValue instanceof this) {
Object.keys(control.$error).forEach(errorName => {
control.$setValidity(errorName, true);
});
}
});
}
static hasMultipleValues(value) {
return value instanceof this || value != null && typeof value === 'object' &&
Object.keys(value).some(k => this.hasMultipleValues(value[k]));
}
}
return MultipleValues;
}
export default multipleValuesFactory; |
import { connect } from "react-redux";
import React, { Component } from "react";
import PropTypes from "prop-types";
import {
BrowserRouter as Router,
Route,
Link,
Switch,
Redirect,
} from "react-router-dom";
import { fetchPosts } from "../actions/posts";
import Home from "./Home";
import Page404 from "./Page404";
import Navbar from "./Navbar";
class App extends Component {
componentDidMount() {
this.props.dispatch(fetchPosts());
}
render() {
const { posts } = this.props;
return (
<Router>
<Navbar />
<Switch>
<Route
exact
path="/"
render={(props) => {
return <Home {...props} posts={posts} />;
}}
/>
<Route component={Page404} />
</Switch>
</Router>
);
}
}
function mapStateToProps(state) {
return {
posts: state.posts,
};
}
App.propTypes = {
posts: PropTypes.array.isRequired,
};
export default connect(mapStateToProps)(App);
|
"use strict";
document.addEventListener('DOMContentLoaded', function () {
$(window).scroll(function () {
var scrollVal = $(this).scrollTop();
// console.log(scrollVal);
if (scrollVal > 10) {
$("header").addClass("scroll");
} else {
$("header").removeClass("scroll");
}
});
$(".js-toggle-trigger").each(function () {
$(this).click(function (e) {
e.stopPropagation();
var target = $(this).data("target");
console.log(target);
$("#" + target).toggleClass("active");
});
});
$(".js-submenuTitle").click(function () {
if ($(this).hasClass("active")) {
$(this).removeClass("active");
$(this).parent().find(".js-submenu").removeClass("active");
} else {
$(".js-submenuTitle").removeClass("active");
$(".js-submenuTitle").parent().find(".js-submenu").removeClass("active");
$(this).addClass("active");
$(this).parent().find(".js-submenu").addClass("active");
}
});
$('.slick_six').slick({
slidesToShow: 6,
responsive: [{
breakpoint: 1024,
settings: {
slidesToShow: 2
}
}]
});
$('.slick_five').slick({
slidesToShow: 5,
responsive: [{
breakpoint: 1024,
settings: {
slidesToShow: 2
}
}]
});
}); |
'use strict';
import BoxModelPropTypes from './propTypes/BoxModelPropTypes';
import FlexboxPropTypes from './propTypes/FlexboxPropTypes';
import TextStylePropTypes from './propTypes/TextStylePropTypes';
import ColorPropTypes from './propTypes/ColorPropTypes';
import { pushWarnMessage } from './promptMessage';
import particular from './particular';
import chalk from 'chalk';
import { requiredParam } from './roro';
import { convertProp } from './transformer';
let allStylePropTypes = {};
/**
* css 属性验证器
*
* @class Validation
*/
class Validation {
/**
* 验证 CSS 属性名、数值
*
* @static
* @param {any} [{ prop, value, selectors = '', position = {} }={}] 属性、数值、选择器、位置等参数
* @returns
* @memberof Validation
*/
static validate({ prop, value, selectors = '', position = {} } = {}) {
const camelCaseProperty = convertProp({ prop }); // 将属性转换成驼峰样式
if (allStylePropTypes[camelCaseProperty]) {
let error = allStylePropTypes[camelCaseProperty](value, prop, selectors);
if (error) {
const message = `line: ${position.start.line}, column: ${
position.start.column
} - ${error.message}`;
console.warn(chalk.yellow.bold(message));
pushWarnMessage(message);
}
return error;
} else if (!particular[camelCaseProperty]) {
const message = `line: ${position.start.line}, column: ${
position.start.column
} - "${prop}: ${value}" is not valid in "${selectors}" selector`;
console.warn(chalk.yellow.bold(message));
pushWarnMessage(message);
}
}
static addValidStylePropTypes(stylePropTypes) {
for (let prop in stylePropTypes) {
allStylePropTypes[prop] = stylePropTypes[prop];
}
}
}
// 添加特定种类的 CSS 验证规则
Validation.addValidStylePropTypes(BoxModelPropTypes);
Validation.addValidStylePropTypes(FlexboxPropTypes);
Validation.addValidStylePropTypes(TextStylePropTypes);
Validation.addValidStylePropTypes(ColorPropTypes);
export default Validation;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.