text
stringlengths 7
3.69M
|
|---|
import { connect } from 'react-redux';
import {Action} from '../../../../action-reducer/action';
import {getPathValue} from '../../../../action-reducer/helper';
import helper from '../../../../common/common';
import ChangeDialog from './ChangeDialog';
import showPopup from '../../../../standard-business/showPopup';
import {fetchAllDictionary, setDictionary2} from "../../../../common/dictionary";
const STATE_PATH = ['temp'];
const action = new Action(STATE_PATH);
const getSelfState = (rootState) => {
return getPathValue(rootState, STATE_PATH);
};
const cancelActionCreator = () => (dispatch) => {
dispatch(action.assign({visible: false}));
};
const okActionCreator = () => async (dispatch, getState) => {
const {value, controls} = getSelfState(getState());
if (!helper.validValue(controls, value)) {
dispatch(action.assign({valid: true}));
return;
}
dispatch(action.assign({confirmLoading: true}));
const {returnCode, returnMsg} = await helper.fetchJson(`/api/config/car_manager/change`, helper.postOption(value));
if (returnCode !== 0) {
dispatch(action.assign({confirmLoading: false}));
helper.showError(returnMsg);
return;
}
dispatch(action.assign({visible: false, res: true}));
};
const changeActionCreator = (key, value) => async (dispatch) => {
dispatch(action.assign({[key]: value}, 'value'));
};
const exitValidActionCreator = () => (dispatch) => {
dispatch(action.assign({valid: false}));
};
const mapStateToProps = (state) => {
return getSelfState(state);
};
const actionCreators = {
onOk: okActionCreator,
onCancel: cancelActionCreator,
onChange: changeActionCreator,
onExitValid : exitValidActionCreator,
};
const buildDialogState = async (id) => {
const config = {
title: '变更状态',
ok: '确定',
cancel: '取消',
controls: [
{key: 'carState', title: '车辆状态', type: 'select', dictionary: 'car_state', required: true},
{key: 'reason', title: '变更说明', type: 'text', span: 2, required: true}
]
};
const dic = await fetchAllDictionary();
const car_state = dic.result.car_state.filter(item => item.value !== 'car_state_user' && item.value !== 'car_state_stop');
setDictionary2({...dic.result, car_state}, config.controls);
global.store.dispatch(action.create({
...config,
value: {id},
visible: true,
confirmLoading: false,
}));
};
/*
* 功能:变更状态对话框
* 参数:id: 【必需】待变更状态的记录id
* 返回值:成功返回true,取消或关闭时返回空
*/
export default async (id) => {
await buildDialogState(id);
const Container = connect(mapStateToProps, actionCreators)(ChangeDialog);
return showPopup(Container, {}, true);
};
|
import Marca from "../models/marca.model.js";
async function insertMarca(marca) {
try {
return await Marca.create(marca);
} catch(err) {
throw err;
}
}
async function updateMarca(marca) {
try {
return await Marca.update(marca, {
where: {
marcaId: marca.id
}
});
} catch(err) {
throw err;
}
}
async function getMarcas() {
try {
return await Marca.findAll();
} catch(err) {
throw err;
}
}
async function getMarca(id) {
try {
return await Marca.findByPk(id);
} catch(err) {
throw err;
}
}
async function deleteMarca(id) {
try {
await Marca.destroy({
where: {
marcaId: id
}
});
} catch(err) {
throw err;
}
}
export default {
insertMarca,
updateMarca,
getMarcas,
getMarca,
deleteMarca
}
|
const BugBounty = artifacts.require("SolidifiedBugBounty");
const SolidifiedProxy = artifacts.require("SolidifiedProxy");
const Dai = artifacts.require("MockDai");
module.exports = function(deployer) {
// deployer
// .deploy(Dai)
// .then(instance => {
// return deployer.deploy(BugBounty, instance.address);
// })
// .then(instance => {
// return deployer.deploy(SolidifiedProxy, instance.address);
// });
};
|
function Platform(ability)
{
this.x = random(0, width); //Platform's x position
this.y = height; //Platform starts at the bottom of the screen
this.color = 'blue'; //Color of platform, default is blue for the normal platform
this.type = 0; //Type is ability of the platform, 0 meaning normal, 1 meaning jump
this.show = function() //Function to display rocks
{
noStroke();
fill(this.color);
rect(this.x, this.y, 100, 20);
}
this.chooseAbility = function()
{
var ability = int(random(0, 3));
this.type = ability;
if (this.type == 1)
{
this.color = 'green';
}
else if (this.type == 2)
{
this.color = 'white';
}
}
this.deletePlatform = function(i) // When platform goes off screen delete it
{
if (this.y < -20) //Make sure platform is twenty pixels off the screen
{
platforms.splice(i, 1);
}
}
this.raise = function() //Function to raise platform up three pixels
{
this.y -= 3;
}
}
|
import React from 'react';
import { Home, About, Projects, Techs } from './pages';
import './App.css';
import { Menu } from './components';
function App() {
return (
<div className="app-container">
<Menu />
<div name="home" className="app-section" id="home">
<Home />
</div>
<div name="about" className="app-section" id="about">
<About />
</div>
<div name="techs" className="app-section" id="techs">
<Techs />
</div>
<div name="projects" className="app-section" id="projects">
<Projects />
</div>
</div>
);
}
export default App;
|
function getGame(games, gameId){
for(let i =0; i < games.length; i++){
if(games[i].id === gameId){
return games[i];
}
}
return null;
}
var seed = new Date().getTime();
function random() {
let x = Math.sin(seed++) * 10000;
return x - Math.floor(x);
}
function getRandomColor(){
let letters = '0123456789ABCDEF';
let color = '#';
for(let i = 0; i < 6; i++){
color += letters[Math.floor(random()*16)];
}
return color;
}
let link = 'http://localhost:3000';
exports.getGame = getGame;
exports.getRandomColor = getRandomColor;
exports.link = link;
|
import React from 'react'
import { connect } from 'react-redux'
import { NavLink } from 'react-router-dom'
import { addDemon } from '../../../actions/demonActions'
import DemonFinderForm from '../../demon-finder/forms/DemonFinderForm'
class AddDemonPage extends React.Component {
handleAddOnSubmit = (demon) => {
this.props.addDemon(demon)
this.props.history.push('/demons')
}
render() {
return (
<div>
<h1>Add Demon Page</h1>
<NavLink to="/demons">Back to demon list</NavLink>
<div>
<ol>
<li>Give your demon suiting a title</li>
<li>Think about your demon in terms of what,when,why, how.
<ul>
<li>What makes the demon take over?</li>
<li>When does this demon take over?</li>
<li>Why...</li>
<li>How can you manage this demon?</li>
</ul>
</li>
<li>Write down your thoughts and process of managing this demon</li>
</ol>
<div>
<h2>Demon</h2>
<DemonFinderForm
demon={this.props.demon}
handleSubmit={this.handleAddOnSubmit}
/>
</div>
</div>
</div>
)
}
}
const mapDispatchToProps = (dispatch) => ({
addDemon: (demon) => dispatch(addDemon(demon))
})
export default connect(null, mapDispatchToProps)(AddDemonPage)
|
const fs = require('fs')
const pReadFile = url => {
return new Promise((resolve, reject) => {
fs.readFile(url, 'utf8', (err, data) => {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
}
const pa = pReadFile('../a.txt').then(data => data).catch(err=>err)
const pb = pReadFile('../b.txt').then(data => data).catch(err=>err)
const pc = pReadFile('../c.txt').then(data => data)
const p = Promise.race([pa, pb, pc])
p.then(data => console.log(data))
.catch(err => console.log(`失败了: ${err}`))
|
import logo from './logo.svg';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Component } from 'react';
//import Login from './pages/Login';
//import Login from './pages/Login';
//import VistaPrincipal from './pages/vistaPrincipal';
import Router from './Router';
//import firebase from './Access/firebase';
export default class App extends Component {
render(){
return(
<div className="App">
<Router />
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
</header>
</div>
);
}
}
/* export default function App() {
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
</header>
</div>
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Login</Link>
</li>
<li>
<Link to="/vistaPrincipal">VistaPrincipal</Link>
</li>
</ul>
</nav>
<Switch>
<Route path="/">
<Login />
</Route>
<Route path="/vistaPrincipal">
<VistaPrincipal />
</Route>
</Switch>
</div>
</Router>
);
}
Login = () => {
return <h2>Home</h2>;
}
VistaPrincipal = () => {
return <h2>About</h2>;
}
*/
|
import React, {Component} from 'react';
import {MDBSelectOption} from 'mdbreact';
import SkillCard from './SkillCard/SkillCard';
import classes from './Skill.module.css';
import {getAsync} from '../../../../../tool/api-helper';
import {languageHelper} from '../../../../../tool/language-helper';
import addIcon from '../../assets/add.svg';
const translation = [
{
skill: '技能',
addSkill: '+ 添加技能',
noSkill: '无技能',
},
{
skill: 'Skill',
addSkill: '+ Add Skill',
noSkill: 'No Skill',
},
];
const text = translation[languageHelper()];
class skill extends Component {
constructor(props) {
super(props);
this.state = {
cards: [],
allSkills: [],
};
this.date = null;
}
// get work data set requestedData and cards in state
async componentDidMount() {
// this api is now currently unavailable
let data = await getAsync(
'/applicants/' + this.props.requestID + '/skills', // eslint-disable-line
true
);
console.log(data); // eslint-disable-line
let allSkillsData = await getAsync('/applicants/skills/', true);
const tempAllSkills =
allSkillsData &&
allSkillsData.content &&
allSkillsData.status.code === 2000
? allSkillsData.content.map((e, i) => {
return (
<MDBSelectOption key={i} value={e.id}>
{e.name}
</MDBSelectOption>
);
})
: [];
let temp =
data && data.content && data.status.code === 2000
? data.content.map((e, i) => {
return (
<SkillCard
key={i}
id={i}
data={e}
options={tempAllSkills}
deleteHandler={this.deleteHandler}
saveHandler={this.saveHandler}
/>
);
})
: [];
this.setState({...this.state, cards: temp, allSkills: tempAllSkills});
}
async componentDidUpdate() {
}
// delte data on server, delete data in state.cards
deleteHandler = id => {
// TODO: delete data on server according to id
// make a hard copy
let temp = this.state.cards.splice(0);
temp.forEach((e, i) => {
if (e.key == id) {
temp.splice(i, 1);
return;
}
});
this.setState(
{
cards: temp,
},
() => {
// prepare the data to be sent back to server
let dataToSend = this.state.cards.map(e => { // eslint-disable-line
return e.props.data;
});
}
);
};
// save data locally and send back to server
saveHandler = (newCertification, id) => {
// TODO: update server with new saved cards
// PUT {...this.state.requestedData, newEducation}
// timestamp
this.date = new Date();
const time = this.date.getTime();
// make a hard copy
let temp = this.state.cards.splice(0);
temp.forEach((e, i) => {
if (e.key == id) {
temp.splice(
i,
1,
<SkillCard
key={time}
id={time}
data={newCertification}
deleteHandler={this.deleteHandler}
saveHandler={this.saveHandler}
/>
);
return;
}
});
this.setState(
{
cards: temp,
},
() => {
// prepare data to be sent back to server
let dataToSend = this.state.cards.map(e => { // eslint-disable-line
return e.props.data;
});
}
);
};
// addhandler only create a empty cards in state.cards
// update the data in server and local happens in saveHandler
addHandler = () => {
// timestamp
// make a hard copy
let temp = this.state.cards.concat(
<SkillCard
key={this.state.cards.length}
id={this.state.cards.length}
deleteHandler={this.deleteHandler}
saveHandler={this.saveHandler}
/>
);
this.setState({
cards: temp,
});
};
render() {
let toShow;
if (this.state.cards.length === 0) {
toShow = (
<div className={classes.Skill}>
<div className={classes.row}>
<p className={classes.SectionName}>{text.skill}</p>
<img
className={classes.addIcon}
src={addIcon} alt="icon"
onClick={this.addHandler}
/>
</div>
<p>{text.noSkill}</p>
</div>
);
} else {
toShow = (
<div className={classes.Skill}>
<div className={classes.row}>
<p className={classes.SectionName}>{text.skill}</p>
<img
className={classes.addIcon}
src={addIcon} alt="icon"
onClick={this.addHandler}
/>
</div>
{this.state.cards}
</div>
);
}
return toShow;
}
}
export default skill;
|
// Default settings
var myColumns = 4;
var mySearchString = '';
var myCatImages = {};
// Remove all row and graph divs
var clearDashboards = function() {
$('div.dashboards div.row').remove();
}
// Grab configuration blob and construct our graph urls
var renderDashboards = function(owner) {
var myUrl = '';
if (window.location.pathname.match(/dashboards/)) {
// Normal dashboard view with optional search
myUrl = window.location.pathname;
if (mySearchString.length > 0) {
myUrl += '?search=' + encodeURI(mySearchString);
}
} else {
// Home page view of favorited dashboards
myUrl = '/dashboards?favorites=true'
}
$.ajax({
accepts: {json: 'application/json'},
cache: false,
dataType: 'json',
error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
url: myUrl
}).done(function(d) {
if (d.length === 0) {
console.log('No dashboards found');
return;
}
var row = 0;
$('div.dashboards').append('<div class="row"></div>');
for (var i in d) {
row = Math.floor( i / myColumns );
var spanSize = ( 12 / myColumns );
if (($('div.dashboards div.row').length - 1) !== row) {
$('div.dashboards').append('<div class="row"></div>');
}
var cardWrapper = '<a href="/dashboards/' + d[i].uuid + '"><span id="' + d[i].uuid + '" class="dashboard span' + spanSize + '"></span></a>';
$($('div.dashboards div.row')[row]).append(cardWrapper);
$($($($('div.dashboards div.row')[row]) + 'span.dashboard.span' + spanSize)[i]).append('<span class="star">☆</span>');
var cardDashboardName = '<span class="name" id="' + d[i].uuid + '">' + d[i].name + '</span>';
$($($($('div.dashboards div.row')[row]) + 'span.dashboard.span' + spanSize)[i]).append(cardDashboardName);
var cardGraphCount = '<span class="count">' + d[i].graph_count + '</span>';
$($($($('div.dashboards div.row')[row]) + 'span.dashboard.span' + spanSize)[i]).append(cardGraphCount);
}
// Cat Mode
if (useCatMode !== '') {
$.ajax({
accepts: {json: 'application/json'},
cache: false,
dataType: 'json',
error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
url: '/cats/' + d.length
}).done(function(cats) {
var cards = $('.row a span.dashboard')
for (var i=0; i < cards.length; i++) {
myCatImages[$(cards[i]).attr('id')] = {};
myCatImages[$(cards[i]).attr('id')]['url'] = cats[i];
$(cards[i]).css('background-image', 'url(' + myCatImages[ $(cards[i]).attr('id') ]['url'] + ')');
$(cards[i]).hover(function() {
$(this).css('background-image', 'none');
}, function() {
$(this).css('background-image', 'url(' + myCatImages[ $(this).attr('id') ]['url'] + ')');
});
}
});
}
// Apply star to our favorite dashboards
$.ajax({
accepts: {json: 'application/json'},
cache: false,
dataType: 'json',
error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
url: '/favorites'
}).done(function(d) {
if (d.length === 0) {
console.log('No favorites found');
return;
}
for (var i in d) {
$('.dashboards .row a span#' + d[i]).addClass('favorite');
}
});
});
};
// Delete a dashboard
var deleteDashboard = function(uuid, cb) {
return $.ajax({
accepts: {json: 'application/json'},
cache: false,
dataType: 'json',
error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
type: 'DELETE',
url: '/dashboards/' + uuid
}).done(function(d) {
console.log('Dashboard ' + uuid + ' successfully deleted');
cb();
});
};
// Initial page load
renderDashboards();
// Search form
$('input.search-query').keypress(function(e) {
if (e.which === 13) {
mySearchString = $('input.search-query').attr('value');
clearDashboards();
renderDashboards();
return false;
}
});
// Render search reset button transition
$('i.reset-search.icon-remove-circle').hover(function() {
$(this).addClass('hover');
}, function() {
$(this).removeClass('hover');
});
// Clear search form
$('i.reset-search.icon-remove-circle').click(function() {
$('input.search-query').val('');
mySearchString = '';
clearDashboards();
renderDashboards();
return false;
});
|
function validate()
{
// var book = document.forms["myForm"]["ISBN"].value;
console.log($('#ISBN').val());
var book = $('#ISBN').val();
if(isNaN(book))
{
console.log("Not a number");
alert("Entered ISBN is not a number.");
}else{
if (book.length == 10 || book.length == 13 ) {
loadData();
}
else{
var jsitem = $('#items');
jsitem.text("");
alert("Enter the correct ISBN");
}
}
return false;
}
function loadData() {
var $jsitem = $('#items');
var $book=$('#ISBN').val();
$jsitem.text("");
$.ajax({
url: "http://xisbn.worldcat.org/webservices/xid/isbn/"+$book+"?method=getMetadata&format=json&fl=*",
type: 'POST',
dataType: 'jsonp',
xhrFields: { withCredentials: false },
accept: 'application/json'
}).done(function(data) {
var status = data.stat;
var articles = data.list;
if(status === "ok")
{
$("#secondframe").css("visibility", "visible");
$jsitem.append('<H5><i>The details of the book searched</H5>');
$.each(articles, function( key, val ) {
$jsitem.append('Title Of The Book: <i><b> '+val.title+
'</b></i> <li>Written '+val.author+'</li><li> Edition: <i>'+val.ed+
'</i></li> <li> Year of Publication: <i> '+val.year+
'<i> </li> <li> <a href="'+val.url+'" target="_blank">Click here to open the related Worldcat page</a></li>');
});
}
else{
alert("Bad ISBN, please try another one.");
}
}).fail( function( xmlHttpRequest, statusText, errorThrown ) {
alert(
"Your form submission failed.\n\n"
+ "XML Http Request: " + JSON.stringify( xmlHttpRequest )
+ ",\nStatus Text: " + statusText
+ ",\nError Thrown: " + errorThrown );
});
return false;
};
$('#myForm').submit(validate);
|
const mongoose = require("mongoose");
const schema = mongoose.Schema;
const roomSchema = schema({
index: Number,
namespace: { type: schema.Types.ObjectId, ref: "namespace" },
title: String,
});
const Room = mongoose.model("room", roomSchema);
module.exports = Room;
|
gulp.task('markdown', function() {
getMarkdownContent()
return gulp.src('src/posts/*.md')
.pipe(gulp.dest('public'))
})
// gulp.task('default', gulp.series(''))
|
function Footer(){
return(
<>
<div className="pb-2 bg-white sm:w-full">
<div className="container flex flex-col items-center justify-center pt-4 mt-24 ">
<div className="flex flex-col items-center mt-24 border-t-2 border-gray-300">
<div className="py-6 text-center sm:w-2/3">
<p className="mb-2 text-xs font-bold text-grey-500">
© 2020 by Tove Platell
</p>
</div>
</div>
</div>
</div>
</>
)
}
export default Footer;
|
import { Review, Item } from "../../models";
export const createReview = async (req, res, next) => {
try {
const item = await Item.findById(req.params.item_id);
const review = await Review.create(req.body.review);
item.reviews.push(review);
await item.save();
const populatedReview = await review
.populate("author", "email")
.execPopulate();
return res.status(200).json(populatedReview);
} catch (err) {
next(err);
}
};
export const updateReview = async (req, res, next) => {
try {
let review = await Review.findByIdAndUpdate(
req.params.review_id,
req.body.review,
{ new: true }
);
return res.status(200).json(review);
} catch (err) {
next(err);
}
};
export const deleteReview = async (req, res, next) => {
try {
await Review.findByIdAndDelete(req.params.review_id);
return res.sendStatus(204);
} catch (err) {
next(err);
}
};
|
import { connect } from 'react-redux';
// Du composant qui a besoin de data ou d'actions
// eslint-disable-next-line import/no-unresolved
import Register from 'src/components/Register';
// Action Creators
import { changeValue, register, getErrorMessage } from '../actions/auth';
// == Data / state
// Notre composant à besoin de données depuis le state ?
// On prépare un objet avec les props attendues par le composant
const mapStateToProps = (state) => ({
email: state.auth.email,
username: state.auth.username,
password: state.auth.password,
confirmedPassword: state.auth.confirmedPassword,
errorConnection: state.auth.errorConnection,
errorMessages: state.auth.errorMessages,
});
// == Actions / dispatch
// Notre composant à besoin d'agir sur le state ?
// On prépare un objet avec les props attendues par le composant
const mapDispatchToProps = (dispatch) => ({
changeValue: (name, value) => {
dispatch(changeValue(name, value));
},
register: () => {
dispatch(register());
},
getErrorMessage: (bool, message) => {
dispatch(getErrorMessage(bool, message));
},
});
// création du lien : container
// connect(redux)(react) - connect(ce dont on a besoin)(qui en a besoin)
const RegisterContainer = connect(mapStateToProps, mapDispatchToProps)(Register);
export default RegisterContainer;
|
import DS from 'ember-data';
export default DS.Model.extend({
airport: DS.attr(),
city: DS.attr(),
class: DS.attr(),
comment: DS.attr(),
dateAdded: DS.attr(),
ident: DS.attr(),
manufacturer: DS.attr(),
model: DS.attr(),
name: DS.attr(),
photo: DS.attr(),
street: DS.attr(),
type: DS.attr(),
year: DS.attr(),
});
|
module.exports = {
extends: 'eslint-config-airbnb',
parserOptions: {
// This is to avoid eslint complaining:
// 'use strict' is unnecessary inside of modules
// we need 'use strict' on node4 because only in strict mode do
// block-scoped let/const operate.
sourceType: 'script',
},
rules: {
// Again, override airbnb so that it allows a use strict in node4
strict: ['error', 'safe'],
// Allow 'use strict' to have the shebang line for bin/cli.js
'lines-around-directive': ['error', 'always']
}
}
|
import React from "react";
import "./style.css";
import NavBar from "./Navbar.js";
import TopSection from "./Section.js";
import Buttom from "./Buttom";
const App = () => {
return (
<div>
<NavBar />
<TopSection />
<Buttom />
</div>
);
};
export default App;
|
const request = require('supertest')
const server = require('../../Server/server.js')
const db = require('../../data/dbConfig.js')
afterEach(async () => {
return await db('users').truncate();
});
describe('REGISTER ROUTE', () => {
it('should return 201 w/ CORRECT shape', async () => {
const mock_newUser = {
name: "Billy",
email: "Bill@Billy.com",
password: "TacoMan",
admin: false,
donations: 0
}
const res = await request(server).post('/register').send(mock_newUser)
expect(res.status).toBe(201)
})
it('should return 422 w/ INCORRECT shape', async () => {
const mock_newUser = {
name: "Billy",
password: "TacoMan",
}
const res = await request(server).post('/register').send(mock_newUser)
expect(res.status).toBe(422)
})
})
|
/**
* Created by Oleksandr Lapchuk
*/
define(['./../module'], function (services) {
services.factory('CustomResponse', ['ErrorMessages', function (ErrMsg) {
"use strict";
var self = this;
this.do = function (response, callback) {
response.
success(function (data) {
callback(data);
}).
error(function (data, status) {
ErrMsg.show({'message': data.error, 'status': status})
});
};
return this;
}]);
});
|
// for convention we put first the name of the module SLASH and the name of the action
// action-types names
// are string that are going to describe the action that we will execute
// en mvc seria como el nombre del controlador
const INCREMENTAR = 'CONTADOR/INCREMENTAR'
const DECREMENTAR = 'CONTADOR/DECREMENTAR'
const SETEAR = 'CONTADOR/SETEAR'
// action-creators
// are functions that will create objects with the format that reducers accept to dispatch the actions
// by convention we should put the name in lowercase
export const incrementar = () => ({
type: INCREMENTAR
})
export const decrementar = () => ({
type: DECREMENTAR
})
// we can add data with the payload property
export const setear = payload => ({
type: SETEAR,
payload
})
const initialState = 0
// Reducer
// all of our reducers have to return immutable objects
// export default function (state = initialState, action-creators) {
export default function (state = initialState, action) {
// console.log(action)
// action types
switch (action.type) {
case INCREMENTAR:
return state + 1
case DECREMENTAR:
return state - 1
case SETEAR:
return action.payload
default:
return state
}
}
|
const { test } = require("..")
const { Safe } = require('../safe')
test('Testando o teste', ({ task }) => {
task('Um \"teste\" deve ser um \"teste\"', ({ expect }) => {
expect("teste").to.equal("teste")
})
task('Finalizando os trabalhos', ({ expect, finishIf }) => {
const valorEsperado = null
expect(Safe(valorEsperado).isSafe).to.equal(true)
finishIf(
"valorEsperado é null, os demais testes não precisam ser executados",
!Safe(valorEsperado).isSafe
)
// ...
expect(valorEsperado).to.equal("valor esperado")
// ...
})
})
test('Estamos seguros?', ({ task }) => {
task('Dibrando nulls e undefineds', ({ expect }) => {
expect(Safe(null).isNull).to.equal(true)
expect(Safe(undefined).isUndefined).to.equal(true)
expect(Safe("Tô safe!").isSafe).to.equal(true)
})
task('O que vale é o que cada um tem dentro de si', ({ expect }) => {
expect(Safe([]).isEmpty).to.equal(true)
expect(Safe([1, 2, 3]).isEmpty).to.equal(false)
})
})
|
const express = require('express');
const app = express();
const routers = require('./routers')
const bodyParser = require('body-parser');
const port = process.env.PORT || 8080;
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use((_, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept');
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Object.entries(routers).forEach(
([routeName, router]) => app.use(`/${routeName}`, router)
)
app.get('/', (req, res) => res.render('index'));
app.listen(port, () =>
console.log('Our app is running on http://localhost:' + port)
);
|
//API KEY's should virtually always be hidden by a config var or within an ignored config file, in this case we are not
export default class Config{
constructor(){
this.API_KEY = '032393f752702efbd93f839f09666d46'
}
getKey(){
return this.API_KEY;
}
}
|
import React, { Component } from 'react';
import { Divider } from 'antd';
import 'antd/dist/antd.css';
import EditableCommitteeTable from './EditableCommitteeTable';
import AddMemberAssignment from './AddMemberAssignment';
export default class CommitteesTable extends Component {
constructor(props) {
super(props);
this.rerenderParentCallback = this.rerenderParentCallback.bind(this);
}
rerenderParentCallback() {
this.props.rerenderParentCallback();
}
render() {
const columns = [
{
title: 'Name',
dataIndex: 'name',
editable: false,
inputType: 'text',
},
{
title: 'Start Date',
dataIndex: 'start_date',
editable: true,
inputType: 'date',
},
{
title: 'End Date',
dataIndex: 'end_date',
editable: true,
inputType: 'date',
},
{
title: 'Total Slots',
dataIndex: 'total_slots',
editable: false,
inputType: 'number',
},
];
return (
<div>
<Divider type="horizontal" orientation="left">
Committees
</Divider>
<div style={{ marginBottom: 16 }}>
<AddMemberAssignment
buttonLabel="Add Committee"
endpoint="api/committees"
email={this.props.email}
rerenderParentCallback={this.rerenderParentCallback}
/>
<EditableCommitteeTable
data={this.props.data}
email={this.props.email}
columns={columns}
rerenderParentCallback={this.rerenderParentCallback}
/>
</div>
</div>
);
}
}
|
const data = new Date(2020, 09, 17);
console.log(data.getFullYear());
// let data = new Date();
// data.setYear('2020');
// data.setMonth('09');
// data.setDate('17');
// console.log(data);
|
/***
* Class dhtmlxPagination
* Author Lucas Tiago de Moraes
* Class create pagination to dhtmlx
***/
var dhtmlxPagination = {
cell: null, // cell layout
parent: 'pagination', // id of HTML element which will be used as parent (or object itself), mandatory
icon_path: null, // {string} defines an url where necessary user embedded icons are located (setIconsPath)
skin: null, // name of skin, optional (string)
callback: null, // function callback
align: 'center',
total_entries: 0,
entries_per_page: 1,
current_page: 1,
total_numbers: 10,
first_page: null,
last_page: null,
previous_page: null,
next_page: null,
/*** Method Start ***/
Start: function(){
var self = this;
var datapage = new DataPage(self.total_entries, self.entries_per_page, self.current_page, self.total_numbers);
if (self.cell && datapage.last_page() > 1) {
self.cell.attachStatusBar(
{
text: '<div id="' + self.parent + '"></div>',
paging: true
}
);
var config = [];
config['parent'] = self.parent;
self.icon_path ? config['icon_path'] = self.icon_path : null;
self.skin ? config['skin'] = self.skin : null;
var array = [], num = 0;
if (self.first_page && datapage.current_page > 1) {
if (array[0]) {
array[num] = {
type: 'separator'
};
num++;
}
array[num] = {
id: 1,
type: 'button',
text: '<div id="first_page">' + self.first_page + '</div>',
userdata: {
page: 1
}
};
num++;
}
if (self.previous_page && datapage.current_page > 1) {
if (array[0]) {
array[num] = {
type: 'separator'
};
num++;
}
array[num] = {
id: datapage.previous_page(),
type: 'button',
text: '<div id="previous_page">' + self.previous_page + '</div>'
};
num++;
}
for(var number in datapage.array_numbers()){
if (array[0]) {
array[num] = {
type: 'separator'
};
num++;
}
if (number == datapage.current_page) {
array[num] = {
id: number,
type: 'button',
text: '<div id="current_page">' + number + '</div>',
enabled: true
};
}else{
array[num] = {
id: number,
type: 'button',
text: '<div class="numbers">' + number + '</div>'
};
}
num++;
}
if (self.next_page && datapage.current_page < datapage.last_page()) {
array[num] = {
type: 'separator'
};
num++;
array[num] = {
id: datapage.next_page(),
type: 'button',
text: '<div id="next_page">' + self.next_page + '</div>'
};
num++;
}
if (self.last_page && datapage.current_page < datapage.last_page()) {
array[num] = {
type: 'separator'
};
num++;
array[num] = {
id: datapage.last_page(),
type: 'button',
text: '<div id="last_page">' + self.last_page + '</div>'
};
num++;
}
config['items'] = array;
var pagination = new dhtmlXToolbarObject(config);
pagination.attachEvent("onClick", function(id){
datapage = new DataPage(self.total_entries, self.entries_per_page, id, self.total_numbers);
self.callback(id, datapage.skipped(), datapage.entries_per_page);
});
if (self.align == 'left') {
document.getElementById(self.parent).style.paddingLeft = '6px';
}
if (self.align == 'center') {
var width_parent = document.getElementById(self.parent).offsetWidth;
width_parent /= 2;
width_parent = parseInt(width_parent);
var width_div = document.getElementById(self.parent).getElementsByTagName('div')[0].offsetWidth;
width_div /= 2;
width_div = parseInt(width_div);
var width = parseInt(width_parent - width_div);
document.getElementById(self.parent).style.paddingLeft = width+'px';
}
if (self.align == 'right') {
var width_parent = document.getElementById(self.parent).offsetWidth;
var width_div = document.getElementById(self.parent).getElementsByTagName('div')[0].offsetWidth;
var width = parseInt(width_parent - width_div);
width -= 10;
document.getElementById(self.parent).style.paddingLeft = width+'px';
}
}
}
};
|
$(document).ready(function () {
initSavedJobSkillScoreCalculation();
});
function getJobSeekerAppliedJobs() {
var apiUrlJobSeekerAppliedJobs = GetWebAPIURL() + '/api/JobSeekerAppliedJobs/';
var dataObjJobSeekerAppliedJobs;
$.ajax({
url: apiUrlJobSeekerAppliedJobs,
type: 'GET',
async: false,
headers: app.securityHeaders(),
contentType: "application/json; charset=utf-8",
success: function (data) {
dataObjJobSeekerAppliedJobs = data;
},
error: function (xhr, status, error) {
alert('Error :' + status);
}
});
return dataObjJobSeekerAppliedJobs;
}
function getSavedJobsList() {
var dataobjJobList;
var apiUrlJobList = GetWebAPIURL() + '/api/JobSeekerSavedJobs/';
$.ajax({
url: apiUrlJobList,
type: 'GET',
async: false,
headers: app.securityHeaders(),
contentType: "application/json; charset=utf-8",
success: function (data) {
dataobjJobList = data;
},
error: function (xhr, status, error) {
alert('Erooororlang :' + status);
}
});
return dataobjJobList;
}
var dataobjJobPrerequisiteList = getPrerequisiteList();
function initSavedJobSkillScoreCalculation() {
var dataObjJobSeeker = getHeaderDetails();
viewModel.firstname = ko.observable(dataObjJobSeeker.FirstName);
viewModel.lastname = ko.observable(dataObjJobSeeker.LastName);
var dataobjSavedJobList = getSavedJobsList();
var dataobjJobSkillList = getSkillList();
var dataJobSeekerSkillListObj = getJobSeekerSkills();
var gaf = 1;
viewModel.scoreDetails = ko.observableArray();
viewModel.jobSkillsDetails = ko.observableArray();
viewModel.savedJobs = ko.observableArray();
viewModel.savedApplyCheck = ko.observable('1');
viewModel.applyCheck = ko.observable('1');
viewModel.salary = ko.observableArray();
var dataSalaryObj = getSalaryLookup();
for (da in dataSalaryObj) {
viewModel.salary.push({ name: dataSalaryObj[da].Name, id: dataSalaryObj[da].Id });
}
for (daJobs in dataobjSavedJobList) {
for (daJobSkill in dataobjJobSkillList) {
if (dataobjSavedJobList[daJobs].JobId == dataobjJobSkillList[daJobSkill].JobId) {
var score = new fillSavedJobScoreDetails(dataobjJobSkillList[daJobSkill], dataJobSeekerSkillListObj);
viewModel.scoreDetails.push(score);
}
}
var totalSkillScoreJobSeeker = 0;
var totalSkillScoreEmployer = 0;
for (var i = 0; i < viewModel.scoreDetails().length; i++) {
var gaf = 1;
var res = 0;
var skillScoreJobSeeker = 0;
var skillScoreEmployer = 0;
if (viewModel.scoreDetails()[i].jobSeekerSkillScore() > 0) {
res = Math.abs(viewModel.scoreDetails()[i].jobSeekerSkillScore() - viewModel.scoreDetails()[i].employerSkillProficiency());
skillScoreJobSeeker = ((viewModel.scoreDetails()[i].employerSkillProficiency() - res) * viewModel.scoreDetails()[i].employerSkillImportance()) / gaf;
totalSkillScoreJobSeeker = totalSkillScoreJobSeeker + skillScoreJobSeeker;
skillScoreEmployer = viewModel.scoreDetails()[i].employerSkillProficiency() * viewModel.scoreDetails()[i].employerSkillImportance();
totalSkillScoreEmployer = totalSkillScoreEmployer + skillScoreEmployer;
}
else {
skillScoreJobSeeker = 0;
totalSkillScoreJobSeeker = totalSkillScoreJobSeeker + 0;
skillScoreEmployer = viewModel.scoreDetails()[i].employerSkillProficiency() * viewModel.scoreDetails()[i].employerSkillImportance();
totalSkillScoreEmployer = totalSkillScoreEmployer + skillScoreEmployer;
}
var skillValues = new computedJobSkillScoreSavedJobs(viewModel.scoreDetails()[i], skillScoreJobSeeker, skillScoreEmployer);
viewModel.jobSkillsDetails.push(skillValues);
}
var temp = 0;
temp = Math.round((totalSkillScoreJobSeeker * 100) / totalSkillScoreEmployer);
createJobListForJobseekerSavedJobs(temp, dataobjSavedJobList[daJobs], viewModel.jobSkillsDetails(), dataobjJobSkillList);
viewModel.scoreDetails.removeAll();
}
viewModel.noOfSavedJobs = dataobjSavedJobList.length;
}
function fillSavedJobScoreDetails(objScore, dataJobSeekerSkillListObj) {
var self = this;
self.employerSkillProficiency = ko.observable();
self.employerSkillImportance = ko.observable();
self.jobSeekerSkillScore = ko.observable();
self.jobId = ko.observable();
self.skillMMapId = ko.observable();
if (objScore) {
self.employerSkillProficiency(objScore.SkillScore);
self.employerSkillImportance(objScore.SkillImportance);
self.jobId(objScore.JobId);
self.skillMMapId(objScore.SkillMapId);
for (da in dataJobSeekerSkillListObj) {
if (dataJobSeekerSkillListObj[da].SkillMapId == objScore.SkillMapId) {
self.jobSeekerSkillScore(dataJobSeekerSkillListObj[da].ProficiencyId);
break;
}
}
if (!self.jobSeekerSkillScore() > 0) {
self.jobSeekerSkillScore(0)
}
}
}
function computedJobSkillScoreSavedJobs(objComputedScore, skillScoreJobSeeker, skillScoreEmployer) {
var self = this;
var tempRes = 0;
self.jobId = ko.observable();
self.skillMMapId = ko.observable();
self.jobSeekerSkillScore = ko.observable();
if (objComputedScore) {
self.jobId(objComputedScore.jobId());
self.skillMMapId(objComputedScore.skillMMapId());
tempRes = Math.round((skillScoreJobSeeker * 100) / skillScoreEmployer);
self.jobSeekerSkillScore(tempRes);
}
}
function createJobListForJobseekerSavedJobs(totalSkillScoreJobSeeker, dataobjJobs, jobSkillsDetails, dataobjJobSkillList) {
var listJob = new createJobSeekerJobsSavedList(totalSkillScoreJobSeeker, dataobjJobs, jobSkillsDetails, dataobjJobSkillList);
viewModel.savedJobs.push(listJob);
}
function createJobSeekerJobsSavedList(totalSkillScoreJobSeeker, objJobs, jobSkillsDetails, dataobjJobSkillList) {
var self = this;
if (objJobs) {
var jobDetails = getJobDetails(objJobs.JobId);
var dataObjCompanyDetails = getCompanyDetails(jobDetails.CompanyId);
self.jobId = objJobs.JobId;
self.totalSkillScore = totalSkillScoreJobSeeker;
self.employerName = dataObjCompanyDetails.CompanyName;
self.jobPosition = jobDetails.JobPosition;
self.companyLocation = dataObjCompanyDetails.City;
self.datePosted = jobDetails.PostingDate;
self.dateApplied = 'Feb 12,2014';
self.jobStatus = 'Filled';
self.salaryRange = ko.computed(function () {
for (var j = 0; j < viewModel.salary().length; j++) {
if (viewModel.salary()[j].id == jobDetails.JobSalary) {
return viewModel.salary()[j].name;
}
}
}, this);
self.jobDescription = jobDetails.JobDescription;
self.jobViews = jobDetails.JobViews;
self.applicants = jobDetails.ApplicantsNumber;
self.applicantsSkillScore = jobDetails.ApplicantAverage;
self.prerequisites = ko.observableArray();
for (var k = 0; k < dataobjJobPrerequisiteList.length; k++) {
if (dataobjJobPrerequisiteList[k].JobId == objJobs.JobId) {
self.prerequisites.push({ designExperience: dataobjJobPrerequisiteList[k].PrerequisiteName });
}
}
self.requiredSkills = ko.observableArray();
if (jobSkillsDetails) {
for (var i = 0; i < jobSkillsDetails.length; i++) {
if (jobSkillsDetails[i].jobId() == objJobs.JobId) {
var name = getSkillName(jobSkillsDetails[i], dataobjJobSkillList);
self.requiredSkills.push({ skillName: name, skillScore: jobSkillsDetails[i].jobSeekerSkillScore() });
}
}
}
}
}
viewModel.applyJobs = function (objExpand) {
var jobApplyCheck = 1;
var dataObjJobSeekerAppliedJobs = getJobSeekerAppliedJobs();
if (dataObjJobSeekerAppliedJobs.length != 0) {
for (var i = 0; i < dataObjJobSeekerAppliedJobs.length; i++) {
if (objExpand.jobId == dataObjJobSeekerAppliedJobs[i].JobId) {
alert("Job already applied");
jobApplyCheck = 0;
break;
}
}
}
if (jobApplyCheck == 1) {
window.location = "AppliedJobs.html?&jobId=" + objExpand.jobId;
}
}
|
var map, marker;
var geocoder = new google.maps.Geocoder();
var streetInp, houseInp;
var addBtn;
var address;
var updateTimeout, busy = false;
$(document).ready(function() {
map = initializeMap({
maxZoom: 17,
zoom: 15,
center: new google.maps.LatLng(55.752819, 37.623018)
});
streetInp = $('input[name="street"]');
houseInp = $('input[name="house"]');
addBtn = $('#addHouseBtn');
google.maps.event.addListener(map, 'click', mapOnClick);
streetInp.on('input', function() {
clearTimeout(updateTimeout);
updateTimeout = setTimeout(inputUpdated, 1500);
});
houseInp.on('input', function() {
clearTimeout(updateTimeout);
updateTimeout = setTimeout(inputUpdated, 1500);
});
addBtn.click(send);
});
function inputUpdated() {
if (busy) {
clearTimeout(updateTimeout);
return updateTimeout = setTimeout(inputUpdated, 3000);
}
busy = true;
var street = streetInp.val();
var house = houseInp.val();
geocoder.geocode({
address: 'город москва улица ' + street + ' ' + house
}, function(result) {
address = result[0];
updateMap();
busy = false;
});
}
function updateMap (address) {
address = address || window.address;
map.setCenter(address.geometry.location);
if (marker) marker.setMap(null);
marker = new google.maps.Marker({
map: map,
position: address.geometry.location
});
}
function send () {
while (busy) {}
if (!address || address.geometry.location_type != 'ROOFTOP')
// ToDo запилить отображение ошибки;
return console.log('error');
$.post('/linkHouse',
{
address: address.formatted_address,
lat: address.geometry.location.lat(),
lng: address.geometry.location.lng()
}, function(result) {
location.replace('/addCase');
});
}
function mapOnClick (e) {
geocoder.geocode({'latLng': e.latLng}, function(result, status) {
if (status === "OK")
address = result[0];
update();
});
}
|
import { useState } from "react";
import { connect } from "react-redux";
import _dateToString from "../utils/_dateToString";
import _generateId from "../utils/_generateId";
import { addTodo } from "../actions/todoActions";
import Description from "./Description";
import { Input, DatePicker, Badge, Popover, notification } from "antd";
import "../styles/index.scss";
const TodoInput = ({ category, addTodo }) => {
const [text, setText] = useState("");
const [date, setDate] = useState("");
const [description, setDescription] = useState("");
const [datePicker, setPickerStatus] = useState(false);
const save = () => {
if (text === "") {
notification.error({
message: "Error",
description: "Todo name is required",
});
return false;
}
const todo = { text, date, description, category, complete: false, id: _generateId() };
addTodo({ todo });
setText("");
setDescription("");
setDate("");
};
const togglePicker = (date) => {
date && setDate(date._d);
setPickerStatus(!datePicker);
};
const handleKeyDown = (e) => {
if (e.key == "Enter")
save();
};
const handleOnChange = (e) =>
setText(e.target.value);
return (
<div className="todo">
<DatePicker
placeholder="set deadline"
className="todo__datepicker"
open={datePicker}
format="YYYY-MM-DD HH:mm"
showTime={{ format: "HH:mm" }}
onOk={togglePicker}
/>
<div className="form todo__form">
<div className="wrapper form__wrapper">
<Input placeholder="What needs to be done?"
size="large"
value={ text }
onKeyDown={handleKeyDown}
onChange={handleOnChange}
allowClear/>
<div style={{ display: text ? "flex" : "none" }} className="info wrapper__info">
<Badge className="info__badge" onClick={togglePicker}>
<a> { _dateToString(date) || "Set a deadline" } </a>
</Badge>
<Popover title="Note description"
placement="bottomRight"
trigger="click"
content={<Description
editable={true}
description={description}
setDescription={setDescription}
/>}>
<a className="info__description">
{ !description ? "Add description" : "Edit description" }
</a>
</Popover>
</div>
</div>
</div>
</div>
);
};
export default connect(state => state.todo, { addTodo })(TodoInput);
|
// JavaScript source code
var methods = [];
var numGuideChannels = 1;
const settings = require("../settings/settings.json");
var client;
var guild;
var anonMembers = [];
methods.init = function (c, guildIn, anonMembersIn) {
client = c;
guild = guildIn;
anonMembers = anonMembersIn;
}
methods.addMember = function (member) {
var guild = member.guild;
var numChannels = guild.channels.size;
guild.createChannel(member.id, 'text', [{
// Deny @everyone
id: guild.id,
deny: ['VIEW_CHANNEL']
}, {
// Allow the member
id: member.id,
deny: ['MANAGE_MESSAGES'],
allow: ['VIEW_CHANNEL','SEND_MESSAGES']
}, {
// Allow the bot
id: client.user.id,
allow: ['VIEW_CHANNEL', 'MANAGE_MESSAGES', 'SEND_MESSAGES']
}]).then(channel => {
console.log("Trying to move channel " + channel.name + " to position: " + numChannels - 1);
channel.edit({'topic':member.id})
guild.setChannelPosition(channel, numChannels-1);
}).catch(console.error);
}
methods.removeMember = function (member) {
var guild = member.guild;
var numChannels = guild.channels.length;
var channel = null;
for (var i = 0; i < guild.channels.array().length; i++) {
console.log("memberID:" + member.id + " channelID:" + guild.channels.array()[i].name);
if (member.id === guild.channels.array()[i].name) {
channel = guild.channels.array()[i];
}
}
if (channel === "undefined" || channel == null) {
console.log("Could not find the channel to remove! Returning...")
return;
}
channel.delete()
.then(console.log)
.catch(console.error);
/*
for (var i = 0; i < guild.channels.array().length; i++) {
guild.channels.array()[i].delete();
}
*/
}
module.exports = methods;
|
var ModalView = Backbone.View.extend({
template: App.templates.modal_form,
attributes: {
"class" : "modal"
},
events: {
"click" : "cancelItem",
"click .mark_completed" : 'complete',
"submit .new_form" : "newTodo",
"submit .update_form" : "updateTodo"
},
newTodo: function(e) {
e.preventDefault();
var todoObj = this.$("form").serializeArray();
$.ajax({
context: this,
url: "/todos",
type: "POST",
data: todoObj,
success: function(json) {
App.trigger('addItem', json);
this.$el.toggle();
}
});
},
getUpdateObj: function(data, completed) {
var newObj = { completed: completed };
data.forEach(function(obj) {
newObj[obj.name] = obj.value;
});
return newObj;
},
updateTodo: function(e) {
e.preventDefault();
var currentTodo = this.model;
var id = currentTodo.get("id");
var completed = currentTodo.get('completed');
var formData = this.$("form").serializeArray();
var newObj = this.getUpdateObj(formData, completed);
$.ajax({
context: this,
url: "/todos/" + id,
type: "PUT",
data: newObj,
success: function(json) {
currentTodo.set(json);
this.$el.toggle();
currentTodo.collection.trigger('change');
}
});
},
complete: function(e) {
e.preventDefault();
var $f = this.$("form");
var id;
var $tr;
if ($f.hasClass("new_form")) {
alert("Item must be created and saved before marked complete");
} else {
id = this.model.get("id");
$tr = $("#" + id);
this.$(".update_form").trigger("submit");
$tr.trigger("click");
}
},
cancelItem: function(e) {
if (this.$el[0] !== e.target) {
return;
}
this.$el.fadeOut(250, (function() {
this.$el.remove();
}).bind(this));
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
$("main").append(this.$el);
this.$el.fadeIn(500);
this.$("#title").focus();
},
initialize: function() {
this.render();
}
});
|
const CrypVideo = artifacts.require("CrypVideo");
module.exports = function(deployer) {
deployer.deploy(CrypVideo);
};
|
import React,{Component} from 'react';
import two from './2.png';
import ReactDOM from 'react-dom'
import Build from './build'
import swal from 'sweetalert';
import firebase from 'firebase';
import loginImg from './loginImg.jpg';
import SignUp from './signUp'
import NavbarWithDropDown from './navbarWithDropDown'
require("./login.css");
export default class Login extends Component
{
componentDidMount()
{
// REMOVE LOGIN BUTTON
if(document.getElementById('orderButtonDesktop'))
document.getElementById('orderButtonDesktop').style="display:none";
if(document.getElementById('orderButtonMobile'))
document.getElementById('orderButtonMobile').style="display:none";
// Successfully removed login button
document.getElementById('signUp').addEventListener('click',function()
{
ReactDOM.render(<SignUp />,document.getElementById('main'));
});
document.getElementById('fbLogin').addEventListener('click',function()
{
// swal("Oops","Due to cambridge Analytica case, Facebook login is currently disabled!\inconvenience is deeply regreted.\nPlease select some other option to login ",'warning');
var provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
swal("Welcome "+user.displayName+"!","Let's place a piping hot Order!","https://media.giphy.com/media/lGEcfJBvXSTy8/giphy.gif");
ReactDOM.render(<NavbarWithDropDown />,document.getElementById('navbar'));
ReactDOM.render(<Build />,document.getElementById('main'));
// ...
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
swal(errorMessage);
// ...
});
});
document.getElementById('googleLogin').addEventListener('click',function()
{
var provider = new firebase.auth.GoogleAuthProvider();
console.log('google');
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
swal("Welcome "+user.displayName+"!","Let's place a piping hot Order!","https://media.giphy.com/media/lGEcfJBvXSTy8/giphy.gif");
ReactDOM.render(<NavbarWithDropDown />,document.getElementById('navbar'));
ReactDOM.render(<Build />,document.getElementById('main'));
// ...
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
swal(errorMessage);
});
});
document.getElementById('logIn').addEventListener('click',function()
{
var email=document.getElementById('inputEmail').value;
var password=document.getElementById('inputPassword').value;
if(!(email&&password))
swal("Kindly fill in all fields");
else
{
firebase.auth().signInWithEmailAndPassword(email, password).then(function(user)
{
if(!user.emailVerified)
swal("Welcome "+user.displayName,"One more step left.Kindly verify email to continue");
else
{
swal("Welcome "+user.displayName+"!","Let's place a piping hot Order!","https://media.giphy.com/media/lGEcfJBvXSTy8/giphy.gif");
ReactDOM.render(<NavbarWithDropDown />,document.getElementById('navbar'));
ReactDOM.render(<Build />,document.getElementById('main'));
}
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if(errorCode=="auth/invalid-email")
swal("Email address is invalid");
else if(errorCode=="auth/user-not-found")
{
swal("New User?Let's sign Up");
document.getElementById('signUp').click();
}
else swal(errorMessage);
// ...
});
}
});
}
render()
{
function build(user)
{
swal("Welcome "+user+"!","Let's place a piping hot Order!","https://media.giphy.com/media/lGEcfJBvXSTy8/giphy.gif");
ReactDOM.render(<NavbarWithDropDown />,document.getElementById('navbar'));
ReactDOM.render(<Build />,document.getElementById('main'));
}
return(
<div>
<div className="container">
<div className="card card-container">
<img id="profile-img" className="profile-img-card" src={loginImg} style={{width: '129px',height: '102px'}} />
<p id="profile-name" className="profile-name-card"></p>
<span id="reauth-email" className="reauth-email"></span>
<input type="email" id="inputEmail" className="form-control" placeholder="Email address" required autoFocus />
<input type="password" id="inputPassword" className="form-control" placeholder="Password" required />
<div id="remember" className="checkbox">
<label>
<input type="checkbox" value="remember-me" /> Remember me
</label>
</div>
<button className="btn btn-lg btn-primary btn-block btn-signin" id='logIn'>Sign in</button>
New User?
<button className="btn btn-lg btn-primary btn-block btn-signin" id='signUp'>Sign Up</button>
<a href="#" className="forgot-password">
Forgot the password?
</a>
<button className="loginBtn loginBtn--facebook" id='fbLogin'>
Login with Facebook
</button>
<button className="loginBtn loginBtn--google" id='googleLogin'>
Login with Google
</button><br />
<button className="btn btn-primary" onClick={()=>build("Guest")}>
<center>Guest Login</center>
</button><br/>
</div>
</div>
</div>
);
}
}
|
var express = require("express");
var morgan = require("morgan");
var consign = require("consign");//serve para organizar os endpoints
const app = express();
app.use(morgan("dev"));
consign()
.include("libs/config.js")
.then("db.js")
.then("libs/middlewares.js")
.then("routes")
.then("libs/boot.js")
.into(app);
//pag 50
|
// The museum of incredible dull things
// The museum of incredible dull things wants to get rid of some exhibitions. Miriam, the interior architect, comes up with a plan to remove the most boring exhibitions. She gives them a rating, and then removes the one with the lowest rating.
// However, just as she finished rating all exhibitions, she's off to an important fair, so she asks you to write a program that tells her the ratings of the items after one removed the lowest one. Fair enough.
// Task
// Given an array of integers, remove the smallest value. Do not mutate the original array/list. If there are multiple elements with the same value, remove the one with a lower index. If you get an empty array/list, return an empty array/list.
// Don't change the order of the elements that are left.
// Examples
// * Input: [1,2,3,4,5], output= [2,3,4,5]
// * Input: [5,3,2,1,4], output = [5,3,2,4]
// * Input: [2,2,1,2,1], output = [2,2,2,1]
// function removeSmallest(numbers) {
// throw "TODO: removeSmallest";
// }
//parameters
//an array of integers
// return
//return sorted array with lowest number removed
// Examples
// * Input: [1,2,3,4,5], output= [2,3,4,5]
// * Input: [5,3,2,1,4], output = [5,3,2,4]
// * Input: [2,2,1,2,1], output = [2,2,2,1]
//pseudocode
//need to not mutate the array
//need to look through each element of the array
// need to set a counter that looks for the smallest number and removes it
// const removeSmallest = numbers => {
// let smallestNum = 0;
// for (let i =0; i <= numbers.length; i++) {
// if (numbers[i +1] < numbers[i] ){
// smallestNum = i + 1;
// numbers.splice(smallestNum, 1);
// }
// }
// return numbers
// }
//error searchs
//Malformed arrow function parameter list - https://forum.vuejs.org/t/uncaught-syntaxerror-malformed-arrow-function-parameter-list-on-custom-filter/56964/2
// const removeSmallest = numbers => {
// //this is going to hold the value of the smallest number in the array
// let smallestNum = Math.min(...numbers);
// //this is going to hold the index of the smallest number in the array
// let indexOfSmallNum = numbers.indexOf(smallestNum);
// //this is going to look at each element in the array
// console.log(smallestNum);
// console.log(indexOfSmallNum)
// // return numbers.splice(indexOfSmallNum, 1)
// let finalArr = numbers.splice(indexOfSmallNum, 1)
// return finalArr;
// }
//running into the problem that I need a copy of my array to remidy the solution
//refactored using .slice
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
// Remove 1 element at index 3
// let myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']
// let removed = myFish.splice(3, 1)
// myFish is ["angel", "clown", "drum", "sturgeon"]
// removed is ["mandarin"]
// const removeSmallest = numbers => {
// //this needs to be a copy
// let copyNumbers = numbers.slice(0)
// //this is going to hold the value of the smallest number in the array
// let smallestNum = Math.min(...numbers);
// //this is going to hold the index of the smallest number in the array
// let indexOfSmallNum = numbers.indexOf(smallestNum);
// //this is going to look at each element in the array
// console.log(smallestNum);
// console.log(indexOfSmallNum)
// console.log(copyNumbers) // [5,3,2,1,4]
// //using filter
// //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
// //remove the smallest
// //let finalNumbers = copyNumbers.splice(indexOfSmallNum,1) // [1]
// let finalNumbers = copyNumbers.splice(3,1); // [1]
// return finalNumbers
// }
//decided to move on from this method because I was running into issues somewhere.
//** I figured out why this wasn't working
//https://stackoverflow.com/questions/49021164/splice-not-removing-element-from-array
// I was stuck on the problem for couple of hours. I did figure out that when you splice an array it does returns the element that was spliced from the original array.
// let originalArray = ["Apples","Oranges","Kiwi"];
// let newArray = originalArray.splice(0,1);
// console.log(newArray);
// I was expecting the modified originalArray in the spliced variable but instead it returns the element that was spliced. The answer was to
// console.log(originalArray);
// Whatever splice returns, we might not need that, we need to check our originalArray since it's the one that got sliced. The originalArray consists my expected answer which was ["Oranges","Kiwi"]
//using filter
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
//remove the smallest
// const removeSmallest = numbers => {
// //this is going to hold the value of the smallest number in the array
// let smallestNum = Math.min(...numbers);
// //this is going to hold the index of the smallest number in the array
// let indexOfSmallNum = numbers.indexOf(smallestNum);
// console.log(smallestNum);
// console.log(indexOfSmallNum)
// // console.log(copyNumbers)
// let finalNumbers = numbers.filter(ratings => ratings !== numbers[indexOfSmallNum])
// return finalNumbers
// }
//refactored
// const removeSmallest = numbers => numbers.filter(ratings => ratings !== numbers[numbers.indexOf(Math.min(...numbers))]);
//needed to reconsider making sure I just remove the smallest index of the smallest num
const removeSmallest = numbers => {
//copy of array
let copyNumbers = numbers.slice(0)
//empty array to hold to hold the locations of smallest number
let indexOfSmallNum = [];
//this is the smallest number of the array
let smallestNum = Math.min(...numbers)
//loop that looks to each element and checks to see if the value at index of element is equal to the smallestNum
//if it is then the index is pushed to the indexOfSmallNum array
for (let i = 0; i <= numbers.length; i++){
// needed to add this to make sure it would return an empty array
if (numbers.length === 0) {
return indexOfSmallNum;
}
else if (numbers[i] <= smallestNum){
indexOfSmallNum.push(i);
}
}
//this will select the smallest index from the indexOfSmallNum array
let smallestIndex = indexOfSmallNum.slice(0,1)
console.log(smallestIndex)
console.log(smallestNum)
console.log(indexOfSmallNum);
console.log(numbers[smallestIndex])
//this will hold the value for the spliced number
let finalNumbers = [...numbers.splice(smallestIndex, 1)]
//return the original modified array
return numbers
}
console.log(removeSmallest([2,2,1,2,1])) //[2,2,2,1]
// ultimately I ended up needed to have a copy of the original array that I could mutate with splice and return the copied array.
//can also destructure the array when you go to slice and it will let you complete the function with out a copy
|
$("document").ready(function() {
/*Meniu */
$(".drop1").hide();
$(".drop2").hide();
var timeOutStire;
var timeOutCampioni;
$("#stire").mouseenter(function(){
clearTimeout(timeOutStire);
$(".drop2").hide();
$(".drop1").show();
});
$("#stire").mouseleave(function(){
timeOutStire=setTimeout(function(){$(".drop1").hide();},500);
});
$(".drop1").mouseenter(function(){
clearTimeout(timeOutStire);
});
$(".drop1").mouseleave(function(){
timeOutStire=setTimeout(function(){$(".drop1").hide();},500);
});
$("#campioni").mouseenter(function(){
clearTimeout(timeOutCampioni);
$(".drop1").hide();
$(".drop2").show();
});
$("#campioni").mouseleave(function(){
timeOutCampioni=setTimeout(function(){$(".drop2").hide();},500);
});
$(".drop2").mouseenter(function(){
clearTimeout(timeOutCampioni);
});
$(".drop2").mouseleave(function(){
timeOutCampioni=setTimeout(function(){$(".drop2").hide();},500);
});
$("#introducere").mouseenter(function(){
$(".drop1").hide();
$(".drop2").hide();
});
$("#contact").mouseenter(function(){
$(".drop1").hide();
$(".drop2").hide();
});
});
|
import React, { useContext, useState } from "react";
import { Redirect } from "react-router";
import registerUser from "../../api-calls/requests/registerUser";
import { GlobalContext } from "../../context/GlobalContext";
export default function Register() {
const { setAlertMessages } = useContext(GlobalContext);
const [registerSuccess, setRegisterSuccess] = useState(false);
const authRegister = async e => {
e.preventDefault();
const { username, email, password, password2 } = e.target;
const usernameValidation = new RegExp("^[0-9a-zA-Z]*$");
const usernameValidated = usernameValidation.test(username.value);
if (
!username.value ||
!email.value ||
!password.value ||
!password2.value ||
!usernameValidated
) {
setAlertMessages([
"Fields must not be left blank, Username must contain only alphanumeric characters",
]);
return;
}
if (password.value === password2.value && password.value.length > 7) {
const success = await registerUser(
username.value,
email.value,
password.value
);
if (success) {
setRegisterSuccess(true);
setAlertMessages(["Account Created Please Login"]);
} else {
setAlertMessages(["Something went wrong, try again"]);
}
} else {
setAlertMessages([
"Passwords must match and be at least 8 characters long",
]);
}
};
if (registerSuccess) {
return <Redirect to="/login" />;
}
return (
<form onSubmit={authRegister}>
<label htmlFor="email">Email</label>
<input type="email" id="email" name="email" placeholder="Email*"></input>
<label htmlFor="username">Username</label>
<input
type="text"
id="username"
name="username"
placeholder="Username*"
></input>
<label htmlFor="password">Password</label>
<input
type="password"
id="password"
name="password"
placeholder="Password*"
autoComplete="new-password"
></input>
<label htmlFor="password2">Confirm Password</label>
<input
type="password"
id="password2"
name="password2"
placeholder="Password*"
autoComplete="new-password"
></input>
<button type="submit">Sign Up</button>
</form>
);
}
|
import Button from "./Components/Button/Button";
const App = () => {
const colors = ["blue", "red", "yellow"];
return <Button data= {colors}/>
}
export default App;
|
// @ts-check
import { useConnect as useConn } from "reshow-flux";
import MemoReturn from "../organisms/MemoReturn";
import connectOptions from "../../connectOptions";
import * as React from "react";
/**
* @typedef {object} GetReturnOptions
* @property {string} [displayName]
* @property {function} [useConnect]
* @property {string[]} [cleanProps]
* @property {object} [options]
*/
/**
* @typedef {object} ReturnProps
* @property {import("reshow-flux-base").StoreObject} store
* @property {import("../../connectOptions").InitStatesProps} initStates
* @property {{[key: string]: string[]}} [pathStates]
* @property {string[]} [excludeStates]
* @property {import("react").ReactChild} [children]
* @property {boolean} [backfillProps]
*/
/**
* @param {GetReturnOptions} props
* @returns {React.ElementType}
*/
const getReturn = ({
displayName = "Return",
useConnect,
cleanProps,
options,
} = {}) => {
useConnect = useConnect || useConn({ ...connectOptions, ...options });
/**
* @param {ReturnProps} props
*/
const Return = (props) => {
const { children, backfillProps, ...otherProps } = props;
const state = /** @type function*/(useConnect)(props);
const nextProps = backfillProps
? {
...state,
...connectOptions.reset(otherProps, cleanProps),
}
: {
...connectOptions.reset(otherProps, cleanProps),
...state,
};
return <MemoReturn props={nextProps}>{children}</MemoReturn>;
};
Return.displayName = displayName;
return Return;
};
const Return = getReturn();
export default Return;
export { getReturn };
|
var express = require('express');
var router = express.Router();
let user = require('../models/User');
let correo = require('../models/Mail');
let rutas = require('../models/Rutas');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.post('/createuser', async function(req, res, next){
if (!req.body){
return res.status(401).json({message: 'No envio parametros de autenticacion.'});
}
try{
var newUser = new user(req.body)
newUser.token = newUser.generateAuthToken()
newUser.tipoUser = 'cliente'
newUser.confirmado = false
await newUser.save()
correo.enviaCorreo(newUser, 'Bienvenida', (err) =>{
if(!err){
res.status(400).json({error: err})
}
})
return res.status(200).json({
newUser,
error: ''
})
} catch(error) {
return res.status(400).json({error})
}
});
router.get('/confirm/:token', async function(req, res, next){
try{
var usuario = await user.findByIdu(req.params.token)
if(usuario.confirmado === true){
return res.status(400).json({error: 'Usuario ya confirmado.'})
}
usuario.confirmado = true
await usuario.save()
correo.enviaCorreo(usuario, 'Confirmacion', (err) =>{
if(!err){
res.status(400).json({error: err})
}
})
return res.status(200).json({error:''})
} catch(error){
return res.status(400).json({error})
}
});
router.post('/confirm', async function(req, res, next){
try{
var usuario = await user.findByCredentials(req.body.token)
if(usuario.confirmado === true){
return res.status(400).json({error: 'Usuario ya confirmado.'})
}
usuario.confirmado = true
await usuario.save()
correo.enviaCorreo(usuario, 'Confirmacion', (err) =>{
if(!err){
res.status(400).json({error: err})
}
})
return res.status(200).json({error:''})
} catch(error){
return res.status(400).json({error})
}
});
router.post('/recuperaPassword', async function(req, res, next){
try{
var usuario = await user.findemail(req.body.email)
if(!usuario){
return res.status(400).json({error: 'Usuario no existe.'})
}
correo.enviaCorreo(usuario, 'ResetPassw', (err) =>{
if(!err){
res.status(400).json({error: err})
}
})
return res.status(200).json({usuario, error:''})
} catch(error){
return res.status(400).json({error})
}
});
router.post('/updatePassword', async function(req, res, next){
try{
console.log(req.body.user)
var usuario = await user.findByIdu(req.body.user.id)
if(usuario.confirmado === false){
return res.status(400).json({error: 'Usuario ya confirmado.'})
}
usuario.password = req.body.user.password
await usuario.save()
/*correo.enviaCorreo(usuario, 'UdpPassw', (err) =>{
if(!err){
res.status(400).json({error: err})
}
})*/
return res.status(200).json({usuario, error:''})
} catch(error){
return res.status(400).json({error})
}
});
router.post('/deleteUser', async function(req, res, next){
try{
var usuario = await user.findByCredentials(req.body.token)
var infodelete = await user.deleteOne({ _id: usuario._id})
return res.status(200).json({infodelete,
error:''})
} catch(error){
return res.status(400).json({error})
}
});
router.post('/createRutas', async function(req, res, next){
try{
var rutas = new Rutas(req.body.ruta)
rutas.save()
return res.status(200).json({rutas,
error:''})
}catch(error){
return res.status(400).json({error})
}
});
router.post('/getRutas', async function(req, res, next){
try{
var rutas = await Rutas.findTypeUser(req.body.user.tipoUser)
return res.status(200).json({rutas,
error:''})
}catch(error){
return res.status(400).json({error})
}
});
router.post('/login', async function(req, res, next){
try{
var usuario = await user.findLogin(req.body.user.email, req.body.user.password)
return res.status(200).json({usuario,
error:''})
}catch(error){
return res.status(400).json({error})
}
})
router.post('/getInfo', async function(req, res, next){
try{
var usuario = await user.findByCredentials(req.body.token)
return res.status(200).json({usuario,
error:''})
} catch(error){
return res.status(400).json({error})
}
});
module.exports = router;
|
import styles from "./businessPanel.module.css"
import Image from 'next/image'
import { useEffect, useState } from "react"
const BusinessPanel=({text,picture}) =>{
const [active,setActive] = useState("1")
const [visible,setVisible] = useState(false)
const handleClick = (e) => {
setActive(e.target.id)
}
return (
<>
<div className={styles.container}>
<div className={styles.infoDisplay}>
<div className={styles.pictureContainer}>
<Image className={styles.picture} width={600} height={400} src={picture} alt="cute cat" />
<div className={styles.pictureBackgroundBlack}></div>
<div className={styles.pictureBackgroundGold}></div>
</div>
<div className={styles.textContainer}>
<div className={styles.infoPicker}>
<p onClick={handleClick} id="1" className={active==="1"? `${styles.infoElementActive} ${styles.infoElement}`:styles.infoElement}>
Financial Decisions
</p>
<p onClick={handleClick} id="2" className={active==="2"? `${styles.infoElementActive} ${styles.infoElement}`:styles.infoElement}>
Strategy Insights
</p>
<p onClick={handleClick} id="3" className={active==="3"? `${styles.infoElementActive} ${styles.infoElement}`:styles.infoElement}>
Best Practices
</p>
</div>
{active==="1"?
<>
<h2 className={styles.title}> Financial Decisions</h2>
<div className={styles.subTextContainer}>
<ul className={styles.listContainer}>
<li className={styles.listElement}>Business Plans</li>
<li className={styles.listElement}> Assessment of New Projects</li>
<li className={styles.listElement}>Financial and Performance Analysis</li>
<li className={styles.listElement}>Implementation of Financial Tools</li>
<li className={styles.listElement}>Financing and Liquidity Optimisation</li>
</ul>
<p className={styles.description}>
We have reviewed hundreds of businesses and ventures and can help you optimize the financial side of your company. </p>
</div>
</>:active==="2"?<>
<h2 className={styles.title}> Strategy Insights</h2>
<div className={styles.subTextContainer}>
<ul className={styles.listContainer}>
<li className={styles.listElement}>Comprehensive Strategic Review and Recommandations</li>
<li className={styles.listElement}> Assessment of Positioning, Strengths, Weaknesses and Opportunities</li>
<li className={styles.listElement}>Assessment of Competitive Landscape and Industry Trends</li>
<li className={styles.listElement}>Transformative Strategic Projects</li>
</ul>
<p className={styles.description}>
Competition is difficult but we can help you navigate your industry more easily so you can ultimately find your footing in your ecosystem.
</p>
</div>
</>:
<>
<h2 className={styles.title}> Best Practices</h2>
<div className={styles.subTextContainer}>
<ul className={styles.listContainer}>
<li className={styles.listElement}>Sales</li>
<li className={styles.listElement}> Marketing</li>
<li className={styles.listElement}>Corporate Image</li>
<li className={styles.listElement}>HR</li>
<li className={styles.listElement}>Legal</li>
</ul>
<p className={styles.description}>Running your business can be tough because owners usually have to be jacks of all trades and there are only so many hours in a day. We can help you make your business more efficient and save you time by helping you implement best practices. </p>
</div>
</>}
</div>
</div>
</div>
</>
)
}
export default BusinessPanel
|
//search-box component
import React from "react";
import './search-box.style.css';
export const Searchbox = ({placeholder, handleChange}) => {
return <input className="searchBox"
type="search" size="30"
placeholder = {placeholder}
onChange = {handleChange}
/>
}
|
let findTheOldest = function(people) {
let res = 0;
let oldest = 0;
people.forEach((person, index) => {
if (getAge(person) > oldest) {
oldest = getAge(person);
res = index;
}
});
return people[res]
}
function getAge(person) {
let yod = new Date().getFullYear();
(person.yearOfDeath === undefined) ? yod : yod = person.yearOfDeath;
return yod - person.yearOfBirth
}
const test = [
{
name: 'Carly',
yearOfBirth: 1942,
yearOfDeath: 1970,
},
{
name: 'Ray',
yearOfBirth: 1962,
yearOfDeath: 2011
},
{
name: 'Jane',
yearOfBirth: 1912,
},
]
console.log(findTheOldest(test))
module.exports = findTheOldest
|
// polyfill
if (!Object.create) {
Object.create = function (o) {
if (arguments.length > 1) {
throw new Error('Object.create implementation'
+ ' only accepts the first parameter.');
}
function F() {}
F.prototype = o;
return new F();
};
}
var person = {
firstname: 'Default',
lastname: 'Default',
greet: function() {
return 'Hi ' + this.firstname;
}
};
var john = Object.create(person);
// john.firstname = 'John';
// john.lastname = 'Doe';
console.log(john);
// Examining polyfill more closely
// NOTE: this creates a new object named "F"...see console.log...
myPolyfill = function (obj) {
function F() {}
F.prototype = obj;
return new F();
};
var jane = myPolyfill(person);
console.log(jane);
|
//logs.js
let util = require('../../utils/util.js');
let wechat = require("../../utils/wechat");
let amap = require("../../utils/amap");
var app = getApp();
Page({
data: {
loading:false,
cindex: "0",
types: ["getDrivingRoute", "getWalkingRoute", "getTransitRoute", "getRidingRoute"],
markers: [],
polyline: [],
distance: '',
distance_data: '',
cost: '',
cost_data: '',
time: '',
time_data: '',
transits: [],
city: "",
name: "",
startname: "",
desc: "",
friend:{
payphone: '',
payname: '',
},
},
onLoad(e) {
this.setData({
loading: true
})
wx.showLoading(); //加载
let { latitude, longitude, latitude2, longitude2, city, name, startname, desc } = e;
let markers = [
{
iconPath: "/images/mapicon_navi_s.png",
id: 0,
latitude,
longitude,
width: 23,
height: 33
}, {
iconPath: "/images/mapicon_navi_e.png",
id: 1,
latitude: latitude2,
longitude: longitude2,
width: 24,
height: 34
}
];
this.setData({
latitude, longitude, latitude2, longitude2, markers, city, name,startname, desc
});
this.getRoute();
this.setData({
loading: false
})
wx.hideLoading(); //加载
},
changeType(e) {
let { id } = e.target.dataset;
let { cindex } = this.data;
if (id == cindex) return;
this.setData({ cindex: id });
this.getRoute();
},
getRoute() {
let { latitude, longitude, latitude2, longitude2, types, cindex, city } = this.data;
let type = types[cindex];
let origin = `${longitude},${latitude}`;
let destination = `${longitude2},${latitude2}`;
amap.getRoute(origin, destination, type, city)
.then(d => {
// console.log(d);
this.setRouteData(d, type);
})
.catch(e => {
console.log(e);
})
},
setRouteData(d, type) {
if (type != "getTransitRoute") {
let points = [];
if (d.paths && d.paths[0] && d.paths[0].steps) {
let steps = d.paths[0].steps;
wx.setStorageSync("steps", steps);
steps.forEach(item1 => {
let poLen = item1.polyline.split(';');
poLen.forEach(item2 => {
let obj = {
longitude: parseFloat(item2.split(',')[0]),
latitude: parseFloat(item2.split(',')[1])
}
points.push(obj);
})
})
}
this.setData({
polyline: [{
points: points,
color: "#0091ff",
width: 6
}]
});
}
else {
if (d && d.transits) {
let transits = d.transits;
transits.forEach(item1 => {
let { segments } = item1;
item1.transport = [];
segments.forEach((item2, j) => {
if (item2.bus && item2.bus.buslines && item2.bus.buslines[0] && item2.bus.buslines[0].name) {
let name = item2.bus.buslines[0].name;
if (j !== 0) {
name = '--' + name;
}
item1.transport.push(name);
}
})
})
this.setData({ transits });
}
}
if (type == "getDrivingRoute") {
console.log("车程:",d.paths[0]);
if (d.paths[0] && d.paths[0].distance) {
this.setData({
distance: '距离约' + d.paths[0].distance + '米',
distance_data: d.paths[0].distance
});
}
if (d.taxi_cost) {
this.setData({
cost: '车费约' + parseInt(d.taxi_cost) + '元',
time: '时间约' + parseInt(d.paths[0].duration / 60) + '分钟',
cost_data: parseInt(d.taxi_cost),
time_data: parseInt(d.paths[0].duration / 60)
});
}
}
else if (type == "getWalkingRoute" || type == "getRidingRoute") {
if (d.paths[0] && d.paths[0].distance) {
this.setData({
distance: '距离:' + d.paths[0].distance + '米'
});
}
if (d.paths[0] && d.paths[0].duration) {
this.setData({
cost: parseInt(d.paths[0].duration / 60) + '分钟'
});
}
}
else if (type == "getRidingRoute") {
}
},
goDetail() {
let url = `/pages/info/info`;
wx.navigateTo({ url });
},
nav() {
let { latitude2, longitude2, name, desc } = this.data;
wx.openLocation({
latitude: +latitude2,
longitude: +longitude2,
name,
address: desc
});
},
toAddinfo(){
console.log("帮朋友叫");
let url =`../../pages/helpFriends/helpFriends`;
wx.navigateTo({ url }) ;
},
showFriendInfo(data) {
console.log("index-showFriendInfo(data):{}",data);
console.log("index-showFriendInfo(payphone):{}",data.payphone);
let { payphone, payname } = data;
this.setData({
friend: { payphone, payname }
})
},
clearFriend(){
this.setData({
friend:{
payphone: '',
payname: '',
}
});
wx.showToast({ // 显示Toast
title: '清除成功',
icon: 'success',
duration: 1000
});
// wx.hideToast() // 隐藏Toast
},
callCarer(){
var nickname = app.gloableData.nickname;
var mobilePhone = app.gloableData.mobilePhone;
var that = this;
console.log("1111:",nickname)
if(!nickname){
wx.showModal({
title: '未登录',
content: '请先登录,再进行操作',
success: function (res) {
if (res.confirm) {
let url =`/pages/user/user`;
wx.switchTab({ url }) ;
} else {
console.log('取消')
}
}
})
}else{
if(!mobilePhone){
console.log("清先获取手机号")
}
//将订单信息存储到数据库
wx.request({
url: app.gloableData.baseUrl + '/order/addOrder', //写自己的服务器
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST",
data: {
openId: app.gloableData.openid,
startPlace: that.data.startname,
endPlace: that.data.name,
distance: that.data.distance_data,
costAmt: that.data.cost_data,
costTime: that.data.time_data,
mobilePhone:app.gloableData.mobilePhone,
orderStatus: '00' //订单状态 00-未接单 01-已接单 02-取消 03-执行中 04-执行完成 05-未支付 06-已支付
},
success: function (s_da) {
console.log(s_da)
console.log(s_da.data.message)
if(s_da.data.code != 200){
console.log("保存失败")
}else{
console.log("保存成功")
}
},
fail: function () {
console.log("保存失败")
}
})
console.log("呼叫代驾");
let { friend } = this.data;
let { payphone, payname } = friend;
let url =`../../pages/callcar/callcar?payname=${payname}`;
wx.navigateTo({ url }) ;
}
},
getPhoneNumber: function (e) {
var that = this;
console.log("手机号加密信息:",e);
console.log(e.detail.errMsg == "getPhoneNumber:ok");
if (e.detail.errMsg == "getPhoneNumber:ok") {
// wx.request({
// url: 'http://localhost/index/users/decodePhone',
// data: {
// encryptedData: e.detail.encryptedData,
// iv: e.detail.iv,
// sessionKey: that.data.session_key,
// uid: "",
// },
// method: "post",
// success: function (res) {
// console.log(res);
// }
// })
}
},
});
|
// Call the dataTables jQuery plugin
$(document).ready(function()
{
var t = $('#deliveredTable').DataTable();
$.ajax(
{
type : "POST",
url : './php/get-data.php',
data : {stat : true},
dataType : "json",
success : function(data)
{
var datas = data;
var length = datas.length;
for (var i = 0; i < length; i++)
{
var trackno = datas[i]['track_no'];
var branch = datas[i]['branch'];
var date = datas[i]['date'];
var status = datas[i]['status'];
var id = datas[i]['id'];
var date_received = datas[i]['date_received'];
t.row.add(
[
trackno,
branch,
date,
date_received,
'<button class="btn btn-info" data-toggle="modal" data-target=".remarksModal" style="width:100%; height:15%" onclick="remark('+id+')"><i class="fa fa-eye"></i> View</button>'
]).draw( false );
}
}
});
});
|
/*
* Copyright (C) 2013 salesforce.com, 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.
*/
/*jslint sub: true */
/**
* @description The crypto adapter for Aura Storage Service.
*
* This adapter provides AES-CBC encryption, using the browser Web Cryptography API
* (https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#dfn-GlobalCrypto)
* with a server-provided key, persisting into the IndexedDB adapter.
*
* Unlike other storage adapters this adapter does not automatically register itself. Use
* <auraStorage:crypto/> in the <auraPreInitBlock/> section of the app's template
* to register this adapter. Doing so guarantees that CryptoAdapter.setKey() will be invoked
* with a server-provided cryptographic key.
*
* Please note:
* 1. If the runtime environment doesn't support the Web Cryptography API the adapter is not
* registered.
* 2. After registration and before a cryptographic key is provided, all crypto adapters
* enter an initialization stage. Get, put, and remove operations are queued until
* the key is set. If a key is never provided then the operations appear paused. It's
* thus paramount to always provide a key. <auraStorage:crypto/> ensures this
* happens.
* 3. If an invalid cryptographic key is provided, the adapter automatically falls
* back to the memory adapter to provide secure but non-persistent storage.
*
* @constructor
*/
function CryptoAdapter(config) {
this.instanceName = config["name"];
this.debugLogging = config["debugLogging"];
this.key = undefined;
// we need a key before we can process get/set
this.ready = undefined;
this.pendingRequests = [];
// utils to convert to/from ArrayBuffer and Object
this.encoder = new window["TextEncoder"]();
this.decoder = new window["TextDecoder"]();
this.config = config;
// default storage is indexeddb (alternative is memory adapter)
// TODO - this indirection is used by auraStorageTest:cryptoFailedAdapter. this needs to be improved.
var adapterClass = $A.storageService.getAdapterConfig(Aura.Storage.IndexedDBAdapter.NAME)["adapterClass"];
this.adapter = new adapterClass(config);
// this.adapter = new Aura.Storage.IndexedDBAdapter(config)
this.mode = CryptoAdapter.NAME;
// async initialize. if it completes successfully, process the queue;
// otherwise reject all pending and future operations.
var that = this;
this.initialize()
.then(
function() {
that.executeQueue(true);
},
function() {
// reject on initialize should never happen because we fallback to non-crypto memory storage
that.executeQueue(false);
}
);
}
/** Name of adapter. */
CryptoAdapter.NAME = "crypto";
/** Log levels */
CryptoAdapter.LOG_LEVEL = {
INFO: { id: 0, fn: "log" },
WARNING: { id: 1, fn: "warning" }
};
/** Encryption algorithm. */
CryptoAdapter.ALGO = "AES-CBC";
/** Initialization vector length (bytes). */
CryptoAdapter.IV_LENGTH = 16;
/** A sentinel value to verify the key against pre-existing data. */
CryptoAdapter.SENTINEL = "cryptoadapter";
/** The Web Cryptography API */
CryptoAdapter.engine = window["crypto"] && (window["crypto"]["subtle"] || window["crypto"]["webkitSubtle"]);
/** Promise that resolves with the per-application encryption key. */
CryptoAdapter.key = new Promise(function(resolve, reject) {
// exposing this resolve/reject isn't pretty but there were issues
// with a nested non-prototype function (ie placing CryptoAdapter.setKey
// in this function). so instead we expose these and delete them after
// setKey() is called.
CryptoAdapter._keyResolve = resolve;
CryptoAdapter._keyReject = reject;
});
/**
* Sets the per-application encryption key.
* @param {ArrayBuffer} rawKey the raw bytes of the encryption key
*/
CryptoAdapter["setKey"] = function(rawKey) {
// note: @export is configured only for prototypes so must use array syntax to avoid mangling
// note: because this is not instance specific there's no config indicating verbosity, so
// always log with $A.log directly
var resolve = CryptoAdapter._keyResolve;
var reject = CryptoAdapter._keyReject;
var log;
// only allow one invocation and
delete CryptoAdapter["setKey"];
delete CryptoAdapter._keyResolve;
delete CryptoAdapter._keyReject;
if (!(rawKey instanceof ArrayBuffer)) {
log = "CryptoAdapter cannot import key of wrong type (" + typeof rawKey + "), rejecting";
$A.warning(log);
reject(new Error(log));
return;
}
CryptoAdapter.engine["importKey"](
"raw", // format
rawKey, // raw key as an ArrayBuffer
CryptoAdapter.ALGO, // algorithm of key
false, // don't allow key export
["encrypt", "decrypt"] // allowed operations
)
.then(
function(key) {
// it's possible for key import to fail, which we treat as a fatal
// error. all pending and future operations will fail.
if (!key) {
log = "CryptoAdapter crypto.importKey() returned no key, rejecting";
$A.warning(log);
reject(new Error(log));
return;
}
$A.log("CryptoAdapter crypto.importKey() successfully imported key");
resolve(key);
},
function(e) {
log = "CryptoAdapter crypto.importKey() failed, rejecting: " + e;
$A.warning(log);
reject(new Error(log));
}
);
};
/**
* Registers crypto adapter.
*/
CryptoAdapter["register"] = function() {
// if a browser supports crypto it'll expose window.crypto. unfortunately the crypto operations will
// fail unless they're run on a "secure origins" (like HTTPS and localhost). see http://sfdc.co/bO9Hok.
// unfortunately adapter registration must be synchronous otherwise the adapter is not available in
// time for aura's boot cycle and thus the "actions" store. so manually check https (production) and
// localhost (dev).
//
// moreover, indexeddb needs to be useable (browser implemented properly) in order to use crypto so we
// first check for indexeddb. when both are unavailable or unusable, memory storage will become the default.
if ($A.storageService.isRegisteredAdapter(CryptoAdapter.NAME)) {
$A.warning("CryptoAdapter already registered");
return;
}
if (!$A.storageService.isRegisteredAdapter(Aura.Storage.IndexedDBAdapter.NAME)) {
$A.warning("CryptoAdapter cannot register because it requires IndexedDB");
return;
}
var secure = window.location.href.indexOf('https') === 0 || window.location.hostname === "localhost";
if (!secure) {
$A.warning("CryptoAdapter cannot register because it requires a secure origin");
return;
}
if (!CryptoAdapter.engine) {
$A.warning("CryptoAdapter cannot register because it requires Web Cryptography API");
return;
}
$A.storageService.registerAdapter({
"name": CryptoAdapter.NAME,
"adapterClass": CryptoAdapter,
"secure": true,
"persistent": true
});
};
/**
* Returns the name of the adapter.
* @returns {String} name of adapter
*/
CryptoAdapter.prototype.getName = function() {
return CryptoAdapter.NAME;
};
CryptoAdapter.prototype.fallbackToMemoryAdapter = function(e) {
this.log(CryptoAdapter.LOG_LEVEL.WARNING, "initialize(): falling back to memory storage", e);
$A.metricsService.transaction("aura", "memoryCryptoStorage");
this.mode = Aura.Storage.MemoryAdapter.NAME; // "memory";
// TODO - this indirection is used by auraStorageTest:cryptoFailedAdapter. this needs to be improved.
var adapterClass = $A.storageService.getAdapterConfig(Aura.Storage.MemoryAdapter.NAME)["adapterClass"];
this.adapter = new adapterClass(this.config);
// this.adapter = new Aura.Storage.MemoryAdapter(this.config);
};
/**
* Initializes the adapter by waiting for the app-wide crypto key to be set,
* then validates the key works for items already in persistent storage. Several
* error scenarios to detect:
* - invalid key provided -> fallback to memory storage
* - valid key is provided but can't fetch what's in storage -> clear then use crypto with new key
* - valid key is provided but doesn't match what's in storage -> clear then use crypto with new key
* @private
*/
CryptoAdapter.prototype.initialize = function() {
var that = this;
if (!$A.util.isLocalStorageEnabled()) {
this.fallbackToMemoryAdapter("DisabledLocalStorage");
// do not throw an error so the promise moves to resolve state
return Promise["resolve"]();
}
return CryptoAdapter.key
.then(
function keyReceived(key) {
// it's possible for key generation to fail, which we treat as a fatal
// error. all pending and future operations will fail.
if (!key) {
throw new Error("CryptoAdapter.key resolved with no key."); // move to reject state
}
that.key = key;
},
function noKeyReceived(e) {
throw new Error("CryptoAdapter.key rejected: " + e); // maintain reject state
}
).then(
function verifySentinel() {
function handleInvalidSentinel() {
// decryption failed so clear the store. do not re-throw to remain using crypto with new key.
that.log(CryptoAdapter.LOG_LEVEL.INFO, "initialize(): encryption key is different so clearing storage");
$A.metricsService.transaction("aura", "initializeCryptoStorage");
return that.adapter.clear();
}
// check if existing data can be decrypted. note the use of getItemsInternal() to bypass the queue.
return new Promise(function(resolve, reject) {
that.log(CryptoAdapter.LOG_LEVEL.INFO, "initialize(): verifying sentinel");
that.getItemsInternal([CryptoAdapter.SENTINEL], resolve, reject, true);
}).then(
function(values) {
// if sentinel value is incorrect then clear the store. remain using crypto with new key.
if (!values[CryptoAdapter.SENTINEL] || values[CryptoAdapter.SENTINEL]["value"] !== CryptoAdapter.SENTINEL) {
return handleInvalidSentinel();
}
// new key matches key used in store. existing values remain.
},
handleInvalidSentinel
);
}
).then(
undefined,
function initFailedSoFallbackToMemory(e) {
that.fallbackToMemoryAdapter(e);
// do not throw an error so the promise moves to resolve state
}
).then(
function() {
// underlying store is setup, either as crypto or memory fallback. this store
// is now ready for use.
return that.setSentinelItem();
}
);
};
/**
* Gets whether the crypto adapter is running in standard mode (secure and persistent) or fallback
* mode (secure and not persistent).
*
* @returns {Boolean} True if the adapter is secure and persistent; false if the adapter is secure
* and not persistent.
*/
CryptoAdapter.prototype.isCrypto = function() {
return this.mode === CryptoAdapter.NAME;
};
/**
* Runs the stored queue of requests.
* @param {Boolean} readyState true if the adapter is ready; false if the adapter is in permanent error state
* @private
*/
CryptoAdapter.prototype.executeQueue = function(readyState) {
if (this.ready === undefined) {
this.ready = readyState;
if (!this.ready) {
this.log(CryptoAdapter.LOG_LEVEL.WARNING, "executeQueue(): entered permanent error state. All future operations will fail. Failing " + this.pendingRequests.length + " enqueued operations.");
} else {
this.log(CryptoAdapter.LOG_LEVEL.INFO, "executeQueue(): entered ready state. Processing " + this.pendingRequests.length + " operations.");
}
}
var queue = this.pendingRequests;
this.pendingRequests = [];
for (var i = 0; i < queue.length; i++) {
if (!this.ready) {
// adapter is in permanent error state, reject all queued promises
queue[i]["reject"](new Error(this.getInitializationError()));
} else {
try {
// run the queued logic, which will resolve the promises
queue[i]["execute"](queue[i]["resolve"], queue[i]["reject"]);
} catch (e) {
var message = "executeQueue(): error processing queue: "+e;
this.log(CryptoAdapter.LOG_LEVEL.WARNING, message);
queue[i]["reject"](new Error("CryptoAdapter."+message));
}
}
}
};
/**
* Gets the error message when adapter fails to initialize.
* @private
*/
CryptoAdapter.prototype.getInitializationError = function() {
// should use same format as log()
return "CryptoAdapter '" + this.instanceName + "' adapter failed to initialize";
};
/**
* Enqueues a function to execute.
* @param {function} execute the function to execute
* @returns {Promise} a promise that resolves when the function is executed
* @private
*/
CryptoAdapter.prototype.enqueue = function(execute) {
var that = this;
// adapter is ready so execute immediately
if (this.ready === true) {
return new Promise(function(resolve, reject) { execute(resolve, reject); });
}
// adapter is in permanent error state
else if (this.ready === false) {
return Promise["reject"](new Error(this.getInitializationError()));
}
// adapter not yet initialized
return new Promise(function(resolve, reject) {
that.pendingRequests.push({ "execute":execute, "resolve":resolve, "reject":reject});
if (that.ready !== undefined) {
// rare race condition. intentionally do not pass a new ready state.
that.executeQueue();
}
});
};
/**
* Returns adapter size.
* @returns {Promise} a promise that resolves with the size in bytes
*/
CryptoAdapter.prototype.getSize = function() {
return this.adapter.getSize();
};
/**
* Retrieves items from storage.
* @param {String[]} [keys] The set of keys to retrieve. Undefined to retrieve all items.
* @param {Boolean} [includeExpired] True to return expired items, false to not return expired items.
* @returns {Promise} A promise that resolves with an object that contains key-value pairs.
*/
CryptoAdapter.prototype.getItems = function(keys /*, includeExpired*/) {
// TODO - optimize by respecting includeExpired
var that = this;
var execute = function getIems(resolve, reject) {
that.getItemsInternal(keys, resolve, reject);
};
return this.enqueue(execute);
};
/**
* Retrieves items from storage.
* @param {String[]} keys The keys of the items to retrieve.
* @param {Function} resolve Promise resolve function.
* @param {Function} reject Promise resolve function.
* @param {Boolean} includeInternalKeys True to return internal keys (eg sentinel), otherwise they are
* excluded from the return value.
* @private
*/
CryptoAdapter.prototype.getItemsInternal = function(keys, resolve, reject, includeInternalKeys) {
var that = this;
this.adapter.getItems(keys)
.then(
function(values) {
if (!that.isCrypto()) {
return values;
}
var decrypted = {};
function decryptSucceeded(k, decryptedValue) {
// do not return the sentinel. note that we did verify it decrypts correctly.
if (k !== CryptoAdapter.SENTINEL || includeInternalKeys) {
decrypted[k] = decryptedValue;
}
}
function decryptFailed() {
// decryption failed. do not add the key to decrypted to indicate we
// do not have the key. do not rethrow to return the promise to resolve state.
}
var promises = [];
var promise, value;
for (var key in values) {
value = values[key];
if ($A.util.isUndefinedOrNull(value)) {
// should never get back a non-crypto payload. treat is as though
// the underlying adapter doesn't have it.
} else {
promise = that.decrypt(key, value)
.then(
decryptSucceeded.bind(undefined, key),
decryptFailed
);
promises.push(promise);
}
}
return Promise["all"](promises)
.then(function() {
return decrypted;
});
}
)
.then(
function(decrypted) {
resolve(decrypted);
},
function(e) {
reject(e);
}
);
};
/**
* Decrypts a stored cached entry.
* @param {String} key The key of the value to decrypt.
* @param {Object} value The cache entry to decrypt.
* @returns {Promise} Promise that resolves with the decrypted item.
* @private
*/
CryptoAdapter.prototype.decrypt = function(key, value) {
var that = this;
if (!value || !value["value"]) {
return Promise["reject"](new Error("CryptoAdapter.decrypt() value is malformed for key"+key));
}
return CryptoAdapter.engine["decrypt"](
{
"name": CryptoAdapter.ALGO,
"iv": value["value"]["iv"]
},
that.key,
value["value"]["cipher"]
)
.then(
function(decrypted) {
var obj = that.arrayBufferToObject(new Uint8Array(decrypted));
return {"expires": value["expires"], "value": obj};
},
function(err) {
that.log(CryptoAdapter.LOG_LEVEL.WARNING, "decrypt(): decryption failed for key "+key, err);
throw new Error(err);
}
);
};
/**
* Converts an object to an ArrayBuffer.
* @param {Object} o The object to convert.
* @private
*/
CryptoAdapter.prototype.objectToArrayBuffer = function(o) {
// can't JSON serialize undefined so store a (unencrypted) empty buffer
if (o === undefined) {
return new ArrayBuffer(0);
}
// json encode to a string
var str = $A.util.json.encode(o);
// string to array buffer
return this.encoder["encode"](str);
};
/**
* Converts an ArrayBuffer to object.
* @param {ArrayBuffer} ab The ArrayBuffer to convert.
* @private
*/
CryptoAdapter.prototype.arrayBufferToObject = function(ab) {
// array buffer to string
var str = this.decoder["decode"](ab);
//if empty buffer, we stored undefined
if (str === "") {
return undefined;
}
// string (of json) to object
return JSON.parse(str);
};
/**
* Stores entry used to determine whether encryption key provided can decrypt the store.
* @returns {Promise} Promise that resolves when the item is stored.
*/
CryptoAdapter.prototype.setSentinelItem = function() {
return new Promise(function(resolve, reject) {
var now = new Date().getTime();
// shape must match AuraStorage#buildPayload
var tuple = [
CryptoAdapter.SENTINEL,
{
"value": CryptoAdapter.SENTINEL,
"created": now,
"expires": now + 15768000000 // 1/2 year
},
0
];
// note the use of setItemsInternal() to bypass the queue.
this.setItemsInternal([tuple], resolve, reject);
}.bind(this));
};
/**
* Stores items in storage.
* @param {Array} tuples An array of key-value-size pairs. Eg <code>[ [key1, value1, size1], [key2, value2, size2] ]</code>.
* @returns {Promise} A promise that resolves when the items are stored.
*/
CryptoAdapter.prototype.setItems = function(tuples) {
var that = this;
return this.enqueue(function(resolve, reject) {
that.setItemsInternal(tuples, resolve, reject);
});
};
/**
* Encrypts a tuple.
* @param {Array} tuple An array of key-value-size.
* @return {Promise} Promise that resolves to a tuple of key-encrypted value-size.
*/
CryptoAdapter.prototype.encryptToTuple = function(tuple) {
var that = this;
return new Promise(function(resolve, reject) {
var itemArrayBuffer;
try {
// if json serialization errors then reject
itemArrayBuffer = that.objectToArrayBuffer(tuple[1]["value"]);
} catch (e) {
that.log(CryptoAdapter.LOG_LEVEL.WARNING, "encryptToTuple(): serialization failed for key " + tuple[0], e);
reject(e);
return;
}
// generate a new initialization vector for every item
var iv = window["crypto"]["getRandomValues"](new Uint8Array(CryptoAdapter.IV_LENGTH));
CryptoAdapter.engine["encrypt"](
{
"name": CryptoAdapter.ALGO,
"iv": iv
},
that.key,
itemArrayBuffer
)
.then(
function (encrypted) {
var storable = {
"expires": tuple[1]["expires"],
"value": {"iv": iv, "cipher": encrypted}
};
resolve([tuple[0], storable, tuple[2]]);
},
function (err) {
that.log(CryptoAdapter.LOG_LEVEL.WARNING, "encryptToTuple(): encryption failed for key " + tuple[0], err);
reject(err);
}
);
});
};
/**
* Stores items in storage.
* @param {Array} tuples An array of key-value-size pairs.
* @param {Function} resolve Promise resolve function.
* @param {Function} reject Promise resolve function.
* @private
*/
CryptoAdapter.prototype.setItemsInternal = function(tuples, resolve, reject) {
var that = this;
if (!this.isCrypto()) {
resolve(this.adapter.setItems(tuples));
return;
}
// encrypt into tuples
var promises = [];
var tuple;
for (var i = 0; i < tuples.length; i++) {
tuple = tuples[i];
promises.push(this.encryptToTuple(tuple));
}
Promise["all"](promises).then(
function(encryptedTuples) {
resolve(that.adapter.setItems(encryptedTuples));
},
function (err) {
var keys = tuples.map(function(t) { return t[0]; });
that.log(CryptoAdapter.LOG_LEVEL.WARNING, "setItemsInternal(): transaction error for keys "+keys.toString(), err);
reject(err);
}
);
};
/**
* Removes items from storage.
* @param {String[]} keys The keys of the items to remove.
* @returns {Promise} A promise that resolves when all items are removed.
*/
CryptoAdapter.prototype.removeItems = function(keys) {
var that = this;
return this.enqueue(function(resolve, reject) {
that.removeItemsInternal(keys, resolve, reject);
});
};
/**
* Removes items from storage.
* @param {String[]} keys The kets of the items to remove.
* @param {Function} resolve Promise resolve function.
* @param {Function} reject Promise resolve function.
*/
CryptoAdapter.prototype.removeItemsInternal = function(keys, resolve, reject) {
// note: rely on AuraStorage key prefixing to avoid clashing with sentinel key
this.adapter.removeItems(keys).then(resolve, reject);
};
/**
* Clears storage.
* @returns {Promise} a promise that resolves when the store is cleared
*/
CryptoAdapter.prototype.clear = function() {
return this.adapter.clear()
.then(
function() {
return this.setSentinelItem();
}.bind(this)
);
};
/**
* Sweeps over the store to evict expired items.
* @returns {Promise} a promise that resolves when the sweep is complete.
*/
CryptoAdapter.prototype.sweep = function() {
// underlying adapter may sweep the sentinel so always re-add it
return this.adapter.sweep()
.then(
function() {
return this.setSentinelItem();
}.bind(this)
);
};
/**
* Deletes this storage.
* @returns {Promise} a promise that resolves when storage is deleted
*/
CryptoAdapter.prototype.deleteStorage = function() {
return this.adapter.deleteStorage();
};
/**
* Suspends eviction.
*/
CryptoAdapter.prototype.suspendSweeping = function() {
if (this.adapter.suspendSweeping) {
this.adapter.suspendSweeping();
}
};
/**
* Resumes eviction.
*/
CryptoAdapter.prototype.resumeSweeping = function() {
if (this.adapter.resumeSweeping) {
this.adapter.resumeSweeping();
}
};
/**
* @returns {Boolean} whether the adapter is secure.
*/
CryptoAdapter.prototype.isSecure = function() {
return true;
};
/**
* @returns {Boolean} whether the adapter is persistent.
*/
CryptoAdapter.prototype.isPersistent = function() {
return this.mode === CryptoAdapter.NAME;
};
/**
* Logs a message.
* @param {CryptoAdapter.LOG_LEVEL} level log line level
* @param {String} msg the log message
* @param {Object} [obj] optional log payload
* @private
*/
CryptoAdapter.prototype.log = function (level, msg, obj) {
if (this.debugLogging || level.id >= CryptoAdapter.LOG_LEVEL.WARNING.id) {
$A[level.fn]("CryptoAdapter '"+this.instanceName+"' "+msg, obj);
}
};
Aura.Storage.CryptoAdapter = CryptoAdapter;
// export crypto adapter as $A.storageService.CryptoAdapter exposing effectively
// only the non-mangled functions. not using @export because it exports the
// constructor function which is not desired.
AuraStorageService.prototype["CryptoAdapter"] = CryptoAdapter;
|
const path = require('path');
let config = {};
// production mode
config.PROD = true;
// enable or disable admin api
config.ADMIN_ENABLED = true;
// the key used to verify admin stuff
config.ADMIN_PKEY = process.env.MONITOR_ADMIN_KEY || "EOS5WJtphnj2KfsPL3mxNqgsGcdGqwSBPpVjgPGYrJTiKsQGKrsQj";
// mongo uri and options
config.MONGO_URI = process.env.MONGO_URI || 'mongodb://localhost:27017/TLSweb';
config.MONGO_NODE_URI = process.env.MONGO_NODE_URI || 'mongodb://localhost:27017/TELOS';
config.MONGO_OPTIONS = {
socketTimeoutMS: 30000,
keepAlive: true,
reconnectTries: 30000,
useNewUrlParser: true
};
// default api endpoint
config.MAIN_API_ENDPOINT = process.env.API_NODE_ENDPOINT || 'https://testnet.eos.miami' ;
config.MAIN_API_CHAIN_ID = process.env.API_NODE_CHAINID || 'e17615decaecd202a365f4c029f206eee98511979de8a5756317e2469f2289e3' ;
config.FAUCET_KEY_PROVIDER = process.env.FAUCET_KEY_PROVIDER || '';
// cron processes (aggregation of main stat - actions, transactions, accounts, analytics)
config.CRON = true;
config.CRON_API = process.env.CRON_API_NODE_ENDPOINT || config.MAIN_API_ENDPOINT;
config.TPS_ENABLE = false;
config.MAX_TPS_TIME_UPDATE = 5000;
config.eosInfoConfigs = {
mainNet: {
chainId: config.MAIN_API_CHAIN_ID,
httpEndpoint: config.MAIN_API_ENDPOINT,
name: "Main Net",
key: "mainNet"
},
};
// eosjs
config.eosConfig = {
chainId: config.MAIN_API_CHAIN_ID,
keyProvider: config.FAUCET_KEY_PROVIDER,
httpEndpoint: config.MAIN_API_ENDPOINT,
expireInSeconds: 60,
keyPrefix: "EOS",
broadcast: true,
sign: true,
debug: false,
// logger: {
// log: console.log,
// error: console.error
// }
};
// api url for producers list
config.customChain = process.env.PRODUCERS_QUERY_ENDPOINT || config.MAIN_API_ENDPOINT;
config.apiV = 'v1'; // api version
config.RAM_UPDATE = 5 * 60 * 1000; // time for ram update - /api/api.*.socket
config.HISTORY_UPDATE = 5 * 60 * 1000; // time for stats update - /api/api.*.socket
config.MAX_BUFFER = 500000; // max buffer size for child processes (kb) - /crons
config.blockUpdateTime = 1900; // mainpage upades frequency - /api/api.*.socket in ml sec
config.offsetElementsOnMainpage = 6; // blocks on mainpage
config.limitAsync = 15; // max threads for async.js module
// log4js
config.logger = {
appenders: {
out: {
type: 'stdout'
},
server: {
type: 'file',
filename: path.join(__dirname, './server/logs/server.log'),
},
socket_io: {
type: 'file',
filename: path.join(__dirname, './server/logs/socket_io.log'),
},
accounts_daemon: {
type: 'file',
filename: path.join(__dirname, './server/logs/accounts_daemon.log'),
},
accounts_analytics: {
type: 'file',
filename: path.join(__dirname, './server/logs/accounts_analytics.log'),
},
global_stat: {
type: 'file',
filename: path.join(__dirname, './server/logs/global_stat.log'),
},
ram_bot: {
type: 'file',
filename: path.join(__dirname, './server/logs/ram_bot.log'),
}
},
categories: {
default: {
appenders: ['out'],
level: 'error'
},
server: {
appenders: ['out', 'server'],
level: 'error'
},
socket_io: {
appenders: ['out', 'socket_io'],
level: 'error'
},
accounts_daemon: {
appenders: ['out', 'accounts_daemon'],
level: 'error'
},
accounts_analytics: {
appenders: ['out', 'accounts_analytics'],
level: 'error'
},
global_stat: {
appenders: ['out', 'global_stat'],
level: 'error'
},
ram_bot: {
appenders: ['out', 'ram_bot'],
level: 'error'
}
}
};
// note : we haven't looked into the stuff below
// slack notifications
config.loggerSlack = {
alerts: {
type: '',
token: '',
channel_id: '',
username: '',
}
};
// telegram alert bot
config.telegram = {
ON: false,
TOKEN: '',
TIME_UPDATE: 5000
};
let endpoint = config.MAIN_API_ENDPOINT.split(":");
endpoint[1] = endpoint[1].substring(2);
endpoint[2] = (typeof endpoint[2] === "string" ? parseInt(endpoint[2]) : 0) || (endpoint[0] === 'https' ? 443 : 80);
// wallet api config
config.walletAPI = {
blockchain: 'TELOS',
host: endpoint[1],
port: endpoint[2],
chainId: config.MAIN_API_CHAIN_ID,
keyPrefix: "EOS",
protocol: endpoint[0],
};
config.client = {
faucet: process.env.FAUCET_ENABLED || false,
networkType: process.env.NETWORK_TYPE || 'main'
}
module.exports = config;
|
import { createStore, applyMiddleware, compose, combineReducers } from "redux";
import thunk from "redux-thunk";
import logger from "redux-logger";
import authReducers from "../reducers/authReducers";
import friendsReducer from "../reducers/friendsReducer";
const reducers = combineReducers({
friends: friendsReducer,
auth: authReducers
});
export default createStore(
reducers,
compose(
applyMiddleware(thunk, logger),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
|
"use strict";
// console.log('I'm awesome');
console.log("'I'm awesome");
|
import React, { PureComponent } from 'react'
import { View, Button, StyleSheet, Dimensions } from 'react-native'
export default class MenuScreen extends PureComponent {
static navigationOptions = {
header: null
}
render() {
return (
<View style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
width: Dimensions.get('window').width,
padding: 10,
flexWrap: 'wrap',
}}>
<View style={styles.menuLink}>
<Button
title="Maintenance Services"
onPress={() => this.props.navigation.navigate('MaintenanceServices')}
/>
</View>
<View style={styles.menuLink}>
<Button
title="Customer Relation Management"
onPress={() => this.props.navigation.navigate('CustomerRelationManagement')}
/>
</View>
<View style={styles.menuLink}>
<Button
title="Spare Part"
onPress={() => this.props.navigation.navigate('SparePart')}
/>
</View>
<View style={styles.menuLink}>
<Button
title="Asset Tracking"
onPress={() => this.props.navigation.navigate('AssetTracking')}
/>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
menuLink: {
flex: 1,
flexGrow: 1,
flexShrink: 1,
justifyContent: 'center',
padding: 10,
width: Dimensions.get('window').width
}
})
|
P.views.workouts.schedule = {};
|
const express = require('express');
const app = express();
import { setupApp } from './app';
//Setup the db's if not setup.
import { initDB, truncateTables } from './db-init.js';
initDB();
truncateTables();
//configure the app.
setupApp(app);
app.listen(process.env.PORT || 3000, function () {
console.log('listening on ' + (process.env.PORT || 3000));
});
|
const connection = require('../database/connection')
module.exports = {
async index(page = 1) {
const [countPage] = await connection('incidents').count()
const result = await connection('incidents')
.join('ongs', 'ongs.id', '=', 'incidents.ong_id')
.limit(5)
.offset((page - 1) * 5)
.select([
'incidents.*',
'ongs.name',
'ongs.name',
'ongs.email',
'ongs.whatsapp',
'ongs.city',
'ongs.uf'
])
return {
result,
countPage
}
},
async create(data, ong_id) {
const {
title,
description,
value
} = data
const [id] = await connection('incidents').insert({
title,
description,
value,
ong_id
})
return {
id
}
},
async delete(id, ong_id) {
const incident = await connection('incidents')
.where('id', id)
.select('ong_id')
.first()
if (incident.ong_id !== ong_id) {
return {
status: 401,
error: 'Operation not permitted'
}
}
await connection('incidents').where('id', id).delete()
return {
status: 204
}
}
}
|
module.exports = {
extends: [
"plugin:flowtype/recommended",
"airbnb",
"prettier",
"prettier/flowtype",
"prettier/react"
],
plugins: ["flowtype"],
rules: {
"class-methods-use-this": 0,
"react/destructuring-assignment": 0,
"react/sort-comp": 0,
"react/jsx-filename-extension": 0,
"flowtype/require-valid-file-annotation": [2, "always"]
}
};
|
var cheerio = require('cheerio');
var request = require('request');
var redis = require('redis');
var client = redis.createClient();
var bnspowerurl = 'http://bns.power.plaync.com/tag/list?object=채집제작&category=';
request({
method: 'GET',
url: bnspowerurl + '약왕원'
}, function(err, response, body) {
if (err) return console.error(err);
$ = cheerio.load(body);
$('tr').each(function(i) {
if ( i == 0 ) return;
// result
var ritem_id = $('td.production img', this).attr('item-data');
var ritem_icon = $('td.production img', this).attr('src');
var ritem_name = $('td.production img', this).attr('alt');
var ritem_cnt = $('dt', this).text().match(/\d+/)[0];
console.log('id : ' + ritem_id);
console.log('icon : ' + ritem_icon);
console.log('name : ' + ritem_name);
console.log('cnt : ' + ritem_cnt);
client.hset("r:"+ritem_id, "name", ritem_name);
client.hset("r:"+ritem_id, "icon", ritem_icon);
// material
$('td.material p', this).each(function(i) {
console.log('>material index : ' + i);
var mitem_id = $('img', this).attr('item-data');
var mitem_icon = $('img', this).attr('src');
var mitem_name = $('img', this).attr('alt');
var mitem_cnt = $(this).text().match(/\d+/)[0];
console.log('>id : ' + mitem_id);
console.log('>icon : ' + mitem_icon);
console.log('>name : ' + mitem_name);
console.log('>cnt : ' + mitem_cnt);
client.hset("m:"+mitem_id, "name", mitem_name);
client.hset("m:"+mitem_id, "icon", mitem_icon);
client.sadd("cr:"+ritem_id+":"+ritem_cnt, mitem_id+":"+mitem_cnt);
});
console.log('==============================================');
});
/*
$('li.collection-card').each(function() {
var href = $('a.collection-card-image', this).attr('href');
if (href.lastIndexOf('/') > 0) {
console.log($('h3', this).text());
}
});
*/
});
//client.quit();
|
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
function loadScore() {
'use strict';
var username = getUrlParameter('username'),
user = Object.create(null),
http = new XMLHttpRequest(),
text = "<table><tr><th>Grade</th><th>Comments</th></tr>";
user.username = username;
console.log(user);
http.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
var json = JSON.parse(this.responseText);
if(json.Publish === "True"){
text+= "<tr><td>"+json.Grade+"</td><td>"+json.Comments+"</td></tr>";
text += "</table>";
document.body.innerHTML += text;
}
else {
alert("Teacher has not published your score yet!");
window.location.href = "Student.html?username="+username;
}
return false;
}
};
http.open('POST', 'php/getScore.php', true);
http.send(JSON.stringify(user));
}
function loadTest() {
'use strict';
var http = new XMLHttpRequest(),
count = 1;
http.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
var json = JSON.parse(this.responseText);
for (var row in json) {
if(count === 1){
document.getElementById("Q1Description").innerHTML += json[row].Question;
document.getElementById("Q1Topic").innerHTML += json[row].Topic;
document.getElementById("Q1Restraint").innerHTML += json[row].Restraint;
document.getElementById("Q1Points").innerHTML += json[row].Points;
}
if(count === 2){
document.getElementById("Q2Description").innerHTML += json[row].Question;
document.getElementById("Q2Topic").innerHTML += json[row].Topic;
document.getElementById("Q2Restraint").innerHTML += json[row].Restraint;
document.getElementById("Q2Points").innerHTML += json[row].Points;
}
if(count === 3){
document.getElementById("Q3Description").innerHTML += json[row].Question;
document.getElementById("Q3Topic").innerHTML += json[row].Topic;
document.getElementById("Q3Restraint").innerHTML += json[row].Restraint;
document.getElementById("Q3Points").innerHTML += json[row].Points;
}
count++;
}
return false;
}
};
http.open('GET', 'php/loadTest.php', true);
http.send();
}
function TakeTest() {
'use strict';
var Q1 = document.getElementById("Q1").value,
Q2 = document.getElementById("Q2").value,
Q3 = document.getElementById("Q3").value,
username = getUrlParameter('username'),
test = Object.create(null),
http = new XMLHttpRequest();
test.Q1 = Q1;
test.Q2 = Q2;
test.Q3 = Q3;
test.username = username;
console.log(test);
http.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
var json = JSON.parse(this.responseText);
if(json.valid === 'valid'){
alert("Test Successfully Completed!");
window.location.href = "Student.html?username="+username;
}
}
return false;
};
http.open('POST', 'php/TakeTest.php', true);
http.send(JSON.stringify(test));
return false;
}
|
$('.burger').click(function(){
$(this).toggleClass('burger-clc');
$('.menu a').toggleClass('menu-move');
$('.line-1').toggleClass('line-1-clc');
$('.line-2').toggleClass('line-2-clc');
$('.line-3').toggleClass('line-3-clc');
if ($('.line-1').hasClass('line-1-clc')) {
var noneClass = function(){
$('.burger').removeClass('burger-clc');
$('.menu a').removeClass('menu-move');
$('.line-1').removeClass('line-1-clc');
$('.line-2').removeClass('line-2-clc');
$('.line-3').removeClass('line-3-clc');
};
setTimeout(noneClass, 15000);
} else {
return false;
}
});
|
jest.mock("../src/request-handler", () => jest.fn());
|
import randomInt from '../utils.js';
import playGame from '../index.js';
const gameRules = 'Find the greatest common divisor of given numbers.';
const gcd = (a, b) => {
if (b) {
return gcd(b, a % b);
}
return Math.abs(a);
};
const genRound = () => {
const num1 = randomInt(0, 100);
const num2 = randomInt(0, 100);
const question = `${num1} ${num2}`;
const correctAnswer = gcd(num1, num2).toString();
return [question, correctAnswer];
};
const startGame = () => playGame(gameRules, genRound);
export default startGame;
|
import uuid from 'uuid/v4';
import {
oauth,
oauth_base_urls,
api_base_urls,
providers,
} from '../../lib/config';
import request from '../../lib/http';
const { github, bitbucket, gitlab } = oauth;
export async function requestGithubUserProfile(token) {
try {
const baseUrl = api_base_urls.GITHUB;
const response = await request(
baseUrl,
'/user',
'GET',
providers.GITHUB,
token,
null
);
const { login, email, avatar_url } = response.data;
return { login, email, avatar_url };
} catch (error) {
console.error(
`Error fetching Github user profile using token: ${token} \n ${error}`
);
return null;
}
}
export async function requestBitbucketUserProfile(token) {
try {
const baseUrl = api_base_urls.BITBUCKET;
const accountRequest = request(
baseUrl,
'/user',
'GET',
providers.BITBUCKET,
token,
null
);
const emailRequest = request(
baseUrl,
'/user/emails',
'GET',
providers.BITBUCKET,
token,
null
);
// We need to make 2 separate api requests for getting username and email
// becausing fucking Bitbucket Api doesn't give both details in single api such as `account`. #FML.
const [accountResponse, emailResponse] = await Promise.all([
accountRequest,
emailRequest,
]);
const result = {};
result.username = accountResponse.data.username;
result.uuid = accountResponse.data.uuid;
result.avatar_url = accountResponse.data.links.avatar.href;
const [primaryAccount] = emailResponse.data.values.filter(
email => email.is_primary === true
);
result.email = primaryAccount.email;
return result;
} catch (error) {
console.error(
`Error fetching Bitbucket user profile using token: ${token} \n ${error}`
);
return null;
}
}
export async function requestGitlabUserProfile(token) {
try {
const baseUrl = api_base_urls.GITLAB;
const response = await request(
baseUrl,
'/user',
'GET',
providers.GITLAB,
token,
null
);
const { username, email, avatar_url } = response.data;
return { username, email, avatar_url };
} catch (error) {
console.error(
`Error fetching Gitlab user profile using token: ${token} \n ${error}`
);
return null;
}
}
export function getOauthUrlsForBasicInfo(provider) {
const state = uuid();
const REDIRECT_URI = 'ssh-git://oauth/basic';
let url;
switch (provider) {
case providers.GITHUB:
url = `${oauth_base_urls.GITHUB}/authorize?client_id=${github.client_id}&scope=${github.scopes.basic}&state=${state}&redirect_uri=${REDIRECT_URI}`;
break;
case providers.BITBUCKET:
url = `${oauth_base_urls.BITBUCKET}/authorize?client_id=${bitbucket.client_id}&scope=${bitbucket.scopes.basic}&response_type=token&state=${state}&redirect_uri=${REDIRECT_URI}`;
break;
case providers.GITLAB:
url = `${oauth_base_urls.GITLAB}/authorize?client_id=${gitlab.client_id}&scope=${gitlab.scopes.basic}&response_type=token&state=${state}&redirect_uri=${REDIRECT_URI}`;
break;
default:
throw new Error(
'Invalid provider provided for generating oauth url for getting user info'
);
}
return { url, state };
}
|
import Vue from "../../dist/vue.mjs";
// import api from "../../util.mjs";
export default {
state: {
visualizationTypes: {},
types: {}
},
mutations: {
addTSVisualizationType(state, v) {
Vue.set(state.visualizationTypes, v.key, v.component);
},
addTSType(state, v) {
Vue.set(state.types, v.key, v);
}
},
};
|
import React, { Component } from 'react'
import styled from 'styled-components'
import Card from '../Card'
import Heading, { HeadingSmall } from '../Heading'
/**
* In this very basic component, display a list of data
* contained in the provided `content` variable below.
*
* Don't overthink it, this is super basic.
*/
const content = [
"I'm a list item!",
'Hey look, I am too!',
"I'm another list item."
]
export default class List extends Component {
render() {
return (
<Card>
<Heading>List Component</Heading>
<HeadingSmall>This component displays a list.</HeadingSmall>
{/* display list here */}
</Card>
)
}
}
const UnorderedList = styled.ul`
list-style: none;
padding: 0;
`
const ListItem = styled.li`
margin-bottom: 4px;
`
|
const os = require('os')
const utils = {
/**
* Gets the version of Windows
* @param {string} [version=os.release()] Release value to test
*
* @returns {number} Major & minor of Windows (8.0, 8.1, 10)
*/
getWindowsVersion (version = os.release()) {
let match = version.match(/^(\d+).?(\d+).?(\*|\d+)$/)
if (match === null) {
return version
}
// We got major, minor
if (match.length > 2 && match[1] === '6' && match[2] === '1') {
return '7.0'
} else if (match.length > 2 && match[1] === '6' && match[2] === '2') {
return '8.0'
} else if (match.length > 2 && match[1] === '6' && match[2] === '3') {
return '8.1'
} else if (match.length > 2 && match[1] === '10' && match[2] === '0') {
return '10.0'
} else if (match.length > 2) {
return `${match[1]}.${match[2]}`
} else {
return version
}
}
}
module.exports = utils
|
let Parent = {
name:'parent',
share: [1,2,3],
log:function () {
return this.name
}
}
let child = Object.create(Parent)
|
function palenumber(number) {
var myNum = number;
var stringNum = number.toString();
var stringRev = stringNum.split('');
stringRev = stringRev.reverse()
stringRev = stringRev.join('');
console.log(stringNum);
if (stringNum != stringRev) {
palenumber(number+1);
}
}
palenumber(1234);
|
import Vue from 'vue';
export class ModelIndex {
constructor(internal) {
this.internal = internal;
}
column() {
return this;
}
data() {
return this;
}
isValid() {
return this;
}
model() {
return this;
}
parent() {
return this;
}
row() {
return this;
}
sibling(row, column) {
return row && column && this;
}
siblingAtColumn(column) {
return column && this;
}
siblingAtRow(row) {
return row && this;
}
}
const AbstractItemModel = Vue.extend({
props: {},
methods: {},
});
export default AbstractItemModel;
|
/*
* Programming Quiz: Facebook Friends
*
Directions:
Create an object called facebookProfile. The object should have 3 properties:
your name
the number of friends you have, and
an array of messages you've posted (as strings)
The object should also have 4 methods:
postMessage(message) - adds a new message string to the array
deleteMessage(index) - removes the message corresponding to the index provided
addFriend() - increases the friend count by 1
removeFriend() - decreases the friend count by 1
*/
// your code goes here
var facebookProfile = {
name: "Bosco",
friends: 12,
messages: ["hello world", "Is there somebody out there?", "bye!"],
postMessage: function (message) {
facebookProfile.messages.push(message);
},
deleteMessage: function (index) {
facebookProfile.messages.splice(index,1);
},
addFriend: function () {
return facebookProfile.friends += 1;
},
removeFriend: function () {
return facebookProfile.friends -= 1;
}
};
|
// public/scripts/mailingController.js
(function() {
'use strict';
var MailingController = [
'$scope',
'$anchorScroll',
'$uibModal',
'modalService',
'mailingService',
'spinnerService',
function MailingController(
$scope,
$anchorScroll,
$uibModal,
modalService,
mailingService,
spinnerService) {
var ctrl = this;
var apiUrl = '/api/';
var getUrl = apiUrl;
var _page = 0;
$scope.contacts = [];
$scope.search = '';
$scope.parseInt = function(input, radix){
return parseInt(input, radix);
}
$scope.searchAsync = function (query) {
$http.get('/api/mailinglists/' + query).success(function(data){
$scope.results.length = 0;
$scope.results = data;
});
};
$scope.loadList = function(listId){
$scope.mailinglist = {};
spinnerService.show('mailingSpinner');
mailingService.getMailinglist(listId).then(function(data) {
$scope.mailinglist = data;
spinnerService.hide('mailingSpinner');
});
}
ctrl.getMailinglists = function(){
spinnerService.show('mailingSpinner');
mailingService.getMailinglists().then(function(data) {
$scope.mailinglists = data;
spinnerService.hide('mailingSpinner');
});
}
$scope.loadPage = function(){
ctrl.getMailinglists();
}
}];
angular
.module('touchpoint')
.controller('MailingController', MailingController)
})();
|
import React, { PureComponent } from "react";
import {
Input,
Button,
Snackbar,
Grid,
withStyles,
Typography,
Paper
} from "@material-ui/core";
import Papa from "papaparse";
import { uploadStyle } from "./dashboardStyle";
class UploadData extends PureComponent {
constructor(props) {
super(props);
this.rows = [];
this.state = {
snack: undefined
};
}
sendData = allData => {
return new Promise((resolve, reject) => {
let promises = allData.map(data =>
this.props.firebase
.database()
.ref(this.props.sensorId + "/" + data["time-stamp"].toString())
.set(data)
);
Promise.all(promises)
.then(done => resolve("Data uploaded to Firebase!"))
.catch(error => reject(error.message));
});
};
handleResult = result => {
document.getElementById("upload-file").value = "";
this.rows = [];
this.setState({
snack: result
});
};
closeSnack = () => {
this.setState({
snack: undefined
});
};
handleFile = event => {
const elem = document.getElementById("upload-file");
const file = elem.files[0];
if (file) {
Papa.parse(file, {
header: true,
skipEmptyLines: true,
dynamicTyping: true,
error: (err, file, inputElem, reason) => {
this.handleResult("Parsing error!");
},
step: (row, parser) => {
if (row.errors.length === 0 && row.data["time-stamp"]) {
this.rows.push(row.data);
} else {
parser.abort();
}
},
complete: results => {
if (results.meta.aborted) {
this.handleResult("File or data was malformed!");
} else {
this.sendData(this.rows.slice())
.then(msg => {
this.handleResult(msg);
})
.catch(msg => this.handleResult(msg));
}
}
});
} else {
this.handleResult("Select a file!");
}
};
render() {
const { classes } = this.props;
return (
<Grid container spacing={3} direction="column" alignItems="center">
<Grid item>
<Paper className={classes.paper}>
<Typography variant="h6" color="primary" gutterBottom>
Upload your CSV file
</Typography>
<Snackbar
anchorOrigin={{
vertical: "bottom",
horizontal: "right"
}}
open={this.state.snack !== undefined}
autoHideDuration={4000}
onClose={this.closeSnack}
message={<span>{this.state.snack}</span>}
/>
<Input className={classes.input} id="upload-file" type="file" />
<Button color="primary" onClick={this.handleFile}>
Upload
</Button>
</Paper>
</Grid>
</Grid>
);
}
}
export default withStyles(uploadStyle)(UploadData);
|
define({
name: 'four'
});
|
'use strict'
const stampit = require('stampit')
const URI = require('urijs')
const plugin = require('@nihiliad/janus/uri-factory/plugin')
const worldcat = stampit()
.methods({
fields () {
return {
author: 'au',
title: 'ti',
subject: 'kw'
}
},
baseUri () {
return URI({
protocol: 'https',
hostname: 'www.worldcat.org' // search
})
},
uriFor (search, scope, field) {
if (!search) {
return [
this.emptySearchWarning,
this.emptySearchUri()
]
}
const warnings = []
if (field) {
if (!(field in this.fields())) {
warnings.push('Unrecognized field: "' + field + '"')
} else {
search = this.fields()[field] + ':' + search
}
}
const uri = this.baseUri()
const segments = ['search']
const queryParams = {
q: search
}
return [
warnings.join(' '),
uri.segmentCoded(segments).addQuery(queryParams)
]
}
})
module.exports = plugin.compose(worldcat)
|
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin");
const MergeWebpackConfig = require("webpack-merge");
const DefaultWebpackConfig = require("./webpack.config");
const webpack = require("webpack");
const buidlConfig = MergeWebpackConfig(DefaultWebpackConfig, {
mode: "production",
output: {
filename: "js/[name].js",
path: path.resolve(__dirname, "dist"),
pathinfo: true
},
optimization: {
minimize: true,
minimizer: [
new TerserWebpackPlugin({
terserOptions: {
compress: true
}
}),
new OptimizeCssAssetsWebpackPlugin()
],
mergeDuplicateChunks: true
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
}),
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: "./src/pug/index.pug",
minify: {
removeEmptyAttributes: true,
removeComments: true,
removeTagWhitespace: true
}
}),
new MiniCssExtractPlugin({
filename: "css/[name].css",
chunkFilename: "css/vendor.css"
})
]
});
module.exports = buidlConfig;
|
/* Job status
After a conversion/compilation begins, the client receives a unique
job ID. When the processing has finished the traslation/compilation
output (artifacts) and logs are accessible via the ID of the job for
some arbitrary cleanup timeout (e.g. 1 hour, or a day).
The client can request information, current status and links to
compiled artifacts via this endpoint.
Returns:
- `HTTP/404` - when the job ID is not found (e.g. has already been cleaned up)
- `HTTP/204` - processing is still not finished, no results yet
- `HTTP/200` + `json` - processing finished, artifact metadata is in the
returned json.
*/
const cors = require('cors')
const corsConfig = { allowedHeaders: 'QUEUE_LENGTH_HEADER' }
const {
rootdir,
QUEUE_LENGTH_HEADER,
} = require(__filename.replace(/\bmodules\b.*/,'config.js'))()
const jobs = require(rootdir+'/modules/lib/jobs')
module.exports = function(app) {
app.use('/api/v1/job/:jobid', cors(corsConfig), jobRequest)
app.use('/api/v1/jobs', cors(corsConfig), jobListing)
}
function jobRequest(req, res) {
const jobid = req.params.jobid
const job = jobs.status(jobid)
console.log('Polling for ', jobid, job)
res.setHeader(QUEUE_LENGTH_HEADER, job.queue)
// Job is ready
if (job.status === 'ready') {
res.json(job.info)
// Job is still in the queue (waiting for) being processed
} else if (job.status === 'queued') {
res.status(204).json({ queue: job.queue||0 })
// Job does not exist
} else {
res.status(404).send()
}
}
function jobListing(req, res) {
let queue = jobs.dumpQueue()
let listing = {
jobs: queue
}
console.log(queue)
res.json(listing)
}
|
goog.provide('morning.parallax.ui.ImageElement');
goog.require('goog.net.ImageLoader');
goog.require('goog.style');
goog.require('goog.ui.registry');
goog.require('goog.uri.utils');
goog.require('morning.parallax.ui.Element');
/**
* @constructor
* @extends {morning.parallax.ui.Element}
*/
morning.parallax.ui.ImageElement = function()
{
goog.base(this);
};
goog.inherits(morning.parallax.ui.ImageElement,
morning.parallax.ui.Element);
/**
* @param {Element} el
*/
morning.parallax.ui.ImageElement.prototype.decorateInternal = function(el)
{
goog.base(this, 'decorateInternal', el);
var image = goog.style.getComputedStyle(this.getElement(), 'backgroundImage');
if (!image)
{
// Computed Style couldn't be retrieved (IE8)
this.dispatchEvent(morning.parallax.ui.Element.EventType.LOAD);
return;
}
var src = image.match(/url\((.*?)\)/)[1];
var loader = new goog.net.ImageLoader();
var path = goog.uri.utils.getPath(src).replace(/"/g, '');
loader.addImage(this.makeId('img'), path);
this.getHandler().listen(loader, goog.net.EventType.COMPLETE,
this.handleLoadComplete_);
loader.start();
};
/**
* @param {goog.events.Event} e
* @private
*/
morning.parallax.ui.ImageElement.prototype.handleLoadComplete_ = function(e)
{
this.dispatchEvent(morning.parallax.ui.Element.EventType.LOAD);
};
/** @inheritDoc */
morning.parallax.ui.ImageElement.prototype.isLoadable = function()
{
return true;
};
/**
* Register this control so it can be created from markup.
*/
goog.ui.registry.setDecoratorByClassName(
'prlx-image-element',
function() {
return new morning.parallax.ui.ImageElement();
}
);
|
var express = require('express'),
router = express.Router();
var crypto = require('crypto');
var uid = "0952752498";
var pwd = "";
router.put('/session', function (req, res) {
var mysqlQuery = req.mysqlQuery;
var Account = req.body['account'],
token = req.body['token'];
var AccountNo = parseInt(token, 16);
if (!Account || !token) {
return;
}
var cmd = "select * from AccountTbl where Account = ?";
mysqlQuery(cmd, [Account], function (err, result) {
if (err) {
return;
}
if (result == '') {
res.status(400).send('使用者不存在');
return;
}
if (result[0].Account != Account || result[0].AccountNo != AccountNo) {
res.status(400).send('token錯誤');
return;
} else if (result[0].Enable == 0) {
res.status(400).send('使用者被拒絕存取');
return;
} else {
res.status(200).send({});
return;
}
});
});
router.post('/session', function (req, res, next) {
var mysqlQuery = req.mysqlQuery;
var Account = req.body['email'],
Password = req.body['password'];
if (!Account || !Password) {
return;
}
var cmd = "select * from AccountTbl where Account = ?";
console.log(`Account=${Account}&Password=${Password}`);
mysqlQuery(cmd, [Account], function (err, result) {
if (err) {
console.log(`err=${JSON.stringify(err)}`);
return;
}
if (result == '') {
res.status(400).send('Auth fail.');
return;
}
if (result[0].Account != Account || result[0].Password != Password) {
res.status(400).send('Auth fail.');
return;
} else if (result[0].Enable == 0) {
res.status(400).send('使用者被拒絕存取');
return;
} else {
var token = result[0].AccountNo.toString(16);
if (token.length == 1) {
token = "000" + token;
} else if (token.length == 2) {
token = "00" + token;
} else if (token.length == 3) {
token = "0" + token;
}
res.status(200).send({ token: token });
return;
}
});
});
router.put('/user', function (req, res) {
var Account = req.body['account'],
Password = req.body['password'],
token = req.body['token'];
if (!Account || !Password || !token) {
return;
}
var phonetoken = 'cectphone' + Account;
var md5 = crypto.createHash('md5');
phonetoken = md5.update(phonetoken).digest('hex').substring(0, 8);
if (token != phonetoken) {
res.status(401).send('Auth fail.');
return;
}
var mysqlQuery = req.mysqlQuery;
// check Account exist
mysqlQuery('SELECT Account FROM AccountTbl WHERE Account = ?', Account, function (err, rows) {
if (err) {
console.log(err);
}
var count = rows.length;
if (count > 0) {
res.status(400).send('The email has already been taken.');
return;
} else {
var sql = {
Account: Account,
Password: Password,
Name: Account,
CreateDate: Date.now() / 1000
};
//console.log(sql);
mysqlQuery('INSERT INTO AccountTbl SET ?', sql, function (err, rows) {
if (err) {
console.log(err);
}
mysqlQuery('SELECT * FROM AccountTbl WHERE Account = ?', Account, function (err, rows) {
var AccountNo = rows[0].AccountNo;
var token = AccountNo.toString(16);
if (token.length == 1) {
token = "000" + token;
} else if (token.length == 2) {
token = "00" + token;
} else if (token.length == 3) {
token = "0" + token;
}
res.status(200).send({ token: token });
return;
});
});
}
});
});
router.get('/fw/list', function (req, res) {
res.status(200).send([]);
return;
});
router.get('/info-model', function (req, res) {
res.status(200).send({});
return;
});
router.post('/sendsms', function (req, res, next) {
var mysqlQuery = req.mysqlQuery;
var Account = req.body['phone'];
if (!Account) {
return;
}
mysqlQuery('SELECT Account FROM AccountTbl WHERE Account = ?', Account, function (err, rows) {
if (err) {
console.log(err);
}
var count = rows.length;
if (count > 0) {
res.status(400).send('The phone has already been taken.');
return;
} else {
var phonetoken = 'cectphone' + Account;
var md5 = crypto.createHash('md5');
phonetoken = md5.update(phonetoken).digest('hex').substring(0, 8);
var api = "https://oms.every8d.com/API21/HTTP/sendSMS.ashx";
var msg = `Your%20token%20is%20${phonetoken}`
var url = `${api}?UID=${uid}&PWD=${pwd}&SB=&MSG=${msg}&DEST=${Account}`;
var request = require('request');
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
res.status(200).send({});
}
});
});
router.post('/resetsms', function (req, res, next) {
var mysqlQuery = req.mysqlQuery;
var Account = req.body['phone'];
if (!Account) {
return;
}
mysqlQuery('SELECT * FROM AccountTbl WHERE Account = ?', Account, function (err, rows) {
if (err) {
console.log(err);
}
var count = rows.length;
if (count == 0) {
res.status(400).send('Auth fail.');
return;
} else {
var password = rows[0].Password;
var api = "https://oms.every8d.com/API21/HTTP/sendSMS.ashx";
var msg = `Your%20password%20is%20${password}`
var url = `${api}?UID=${uid}&PWD=${pwd}&SB=&MSG=${msg}&DEST=${Account}`;
var request = require('request');
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
res.status(200).send({});
}
});
});
router.post('/sendmail', function (req, res, next) {
var mysqlQuery = req.mysqlQuery;
var Account = req.body['email'];
if (!Account) {
return;
}
mysqlQuery('SELECT Account FROM AccountTbl WHERE Account = ?', Account, function (err, rows) {
if (err) {
console.log(err);
}
var count = rows.length;
if (count > 0) {
res.status(400).send('The email has already been taken.');
return;
} else {
var mail = req.mailTransport;
var phonetoken = 'cectphone' + Account;
var md5 = crypto.createHash('md5');
phonetoken = md5.update(phonetoken).digest('hex').substring(0, 8);
mail.sendMail({
from: 'no-reply <cect@cectco.com>',
to: Account + ' <' + Account + '>',
subject: 'Welcome to register CECT',
html: '<h1>' + phonetoken +
'</h1><p>This is your registration key. </p>' +
'<p>If you have not applied to register, please ignore this mail.</p>'
}, function (err) {
if (err) {
console.log('Unable to send email: ' + err);
}
});
res.status(200).send({});
}
});
});
router.post('/reset', function (req, res, next) {
var mysqlQuery = req.mysqlQuery;
var Account = req.body['email'];
if (!Account) {
return;
}
mysqlQuery('SELECT * FROM AccountTbl WHERE Account = ?', Account, function (err, rows) {
if (err) {
console.log(err);
}
var count = rows.length;
if (count == 0) {
res.status(400).send('Auth fail.');
return;
} else {
var mail = req.mailTransport;
var password = rows[0].Password;
mail.sendMail({
from: 'no-reply <cect@cectco.com>',
to: Account + ' <' + Account + '>',
subject: 'Forget your CECT password?',
html: '<h1>' + password +
'</h1><p>This is your password. </p>' +
'<p>If you have not applied to get password, please ignore this mail.</p>'
}, function (err) {
if (err) {
console.log('Unable to send email: ' + err);
}
});
res.status(200).send({});
}
});
});
router.post('/payment', function (req, res, next) {
var mysqlQuery = req.mysqlQuery;
var Account = req.body['account'];
var token = req.body['token'];
var AccountNo = parseInt(token, 16);
var DevNo = req.body['serial'];
var CardNo = req.body['code'].trim();
if (!Account || !token || !DevNo || !CardNo) {
return;
}
mysqlQuery('SELECT * FROM AccountTbl WHERE Account = ?', Account, function (err, rows) {
if (err) {
console.log(err);
}
var count = rows.length;
if (count == 0) {
res.status(400).send('Auth fail.');
return;
} else {
if (rows[0].AccountNo != AccountNo) {
res.status(400).send('token錯誤');
return;
} else if (rows[0].Enable == 0) {
res.status(400).send('使用者被拒絕存取');
return;
} else {
mysqlQuery('SELECT * FROM DeviceTbl WHERE DevNo = ?'
, DevNo, function (err, device) {
if (err) {
console.log(err);
}
var count = device.length;
if (count == 0) {
res.status(400).send('There is no this DevNo.');
return;
} else {
mysqlQuery('SELECT * FROM PaymentTbl WHERE CardNo = ?'
, CardNo, function (err, payment) {
if (err) {
console.log(err);
}
var count = payment.length;
if (count == 0) {
res.status(400).send('There is no this payment CardNo.');
return;
} else {
if (payment[0].Used == 1) {
res.status(400).send('This payment CardNo has been used.');
return;
} else {
var addTime = 31536000;
if (payment[0].CardMonth) {
addTime = payment[0].CardMonth * 30 * 24 * 60 * 60;
}
var ExpireDate = device[0].ExpireDate;
if (ExpireDate - Date.now() / 1000 > 0) {
ExpireDate += addTime;
} else {
ExpireDate = Date.now() / 1000 + addTime;
}
var sql = {
Used: 1,
Account: Account,
AccountNo: AccountNo,
PayDate: Date.now() / 1000,
DevNo: DevNo
};
mysqlQuery('UPDATE PaymentTbl SET ? WHERE CardNo = ?'
, [sql, payment[0].CardNo], function (err, result) {
if (err) {
console.log(err);
}
mysqlQuery('UPDATE DeviceTbl SET ExpireDate = ? WHERE DevNo = ?'
, [ExpireDate, device[0].DevNo], function (err, result2) {
if (err) {
console.log(err);
}
res.status(200).send({});
var topic = `WAWA/${token}/U`;
var paylod = JSON.stringify({ action: "list" });
var mqttClient = req.mqttClient;
mqttClient.publish(topic, paylod, { qos: 1, retain: false });
return;
});
});
}
}
});
}
});
}
}
});
});
module.exports = router;
|
function Animal(name) {
this.name = name;
this.speed = 0;
}
Animal.prototype.run = function() {
console.log(this.name + " is run");
};
function Rabbit(name) {
Animal.apply(this, arguments);
}
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;
Rabbit.prototype.run = function() {
Animal.prototype.run.apply(this);
console.log(this.name + " is jumped");
};
let rabbit = new Rabbit("Jack");
rabbit.run();
|
var util = require('util');
var fs = require('fs');
module.exports = function (file) {
var imgObj = {
url : "",
info : {}
};
log.info("file" + util.inspect(file));
imgObj.url = "/uploads/" + file.name;
imgObj.info = file;
if (file.size === 0) {
log.info("No image found!");
}
fs.exists(file.path, function(exists) {
if(exists) {
log.info("Got your file!");
} else {
log.info("Well, there is no magic for those who don’t believe in it!");
}
});
return imgObj;
};
|
/*
* @lc app=leetcode.cn id=482 lang=javascript
*
* [482] 密钥格式化
*/
// @lc code=start
/**
* @param {string} s
* @param {number} k
* @return {string}
*/
var licenseKeyFormatting = function(s, k) {
s = s.toUpperCase().split('-').join('');
var arr = [];
while (s.length--) {
if (s.length > k) {
arr.unshift(s.slice(-k));
s = s.slice(0, s.length - k);
} else {
arr.unshift(s);
s = '';
}
}
return arr.join('-');
};
// @lc code=end
|
import React from 'react';
import { connect } from 'react-redux';
import { addCountry } from '../../actions/countries';
import { clearResults } from '../../actions/search';
import { formatTime } from '../../services/formatting';
import { Card, Button, Image, Transition } from 'semantic-ui-react';
class SearchItem extends React.Component {
handleClick = (e) => {
e.preventDefault()
this.props.addCountry(this.props.country.country)
this.props.clearResults()
this.props.history.push('/countries')
}
render() {
const s = this.props.country.country
return(
<Transition animation='vertical flip' duration={800} transitionOnMount={true}>
<Card key = {s.id} centered={true}>
<Card.Content>
<h2>{s.country_name} - {s.league_name}</h2>
<h3><strong>{s.match_status}</strong></h3>
<h5>{s.match_hometeam_name} vs. {s.match_awayteam_name}</h5>
{ s.status === "FT" ? <h5>Home Team Score: {s.match_hometeam_score} Away Team Score: {s.match_awayteam_score}</h5> : null }
</Card.Content>
<Card.Content extra>
<Button basic color='teal' onClick={this.handleClick} content='Add to My KickOff' attached='bottom'/>
</Card.Content>
</Card>
</Transition>
)
}
}
function mapDispatchToProps(dispatch) {
return {
addCountry: (country) => {
dispatch(addCountry(country))
},
clearResults: () => {
dispatch(clearResults())
}
}
}
function mapStateToProps(state) {
return {
results: state.search.results
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SearchItem)
|
$(window).scroll( function(){
$('.fadeIn').each(function(i) {
var bottom_of_object = $(this).offset().top + $(this).outerHeight() - 200 ;
var bottom_of_window = $(window).scrollTop() + $(window).height();
var result = (bottom_of_object - bottom_of_window) ;
if( result < 0 ){
var j = i%3 ;
$(this).delay((j++) * 300).animate({'opacity':'1'},1000);
}
});
});
|
import React, { useContext } from 'react';
import { ScrollView, StyleSheet } from 'react-native';
import { Text } from '../../common';
import { translate } from '../../i18n';
import { ThemeContext } from '../../theme';
const DetailScreen = ({ route, navigation }) => {
const { theme } = useContext(ThemeContext);
return (
<ScrollView style={styles.container(theme)}>
<Text bold type="heading">{translate('detailScreen.heading')}</Text>
</ScrollView>
);
};
const styles = StyleSheet.create({
container: theme => ({
backgroundColor: theme.backgroundColor,
})
});
DetailScreen.propTypes = {};
DetailScreen.defaultProps = {};
export default DetailScreen;
|
import actionTypes from 'constants/action-types';
import reducer from './notifications';
const initialState = [
{
id: 1,
text: 'Notification 1'
},
{
id: 2,
text: 'Notification 2'
},
{
id: 3,
text: 'Notification 3'
}
];
describe('Notification reducer', () => {
it('should return the initial notifications stored in the state', () => {
expect(reducer(initialState, {})).toEqual(initialState);
});
it('should add a new notification in the state', () => {
const newNotf = {
text: 'Lorem ipsum'
};
const updatedState = reducer(undefined, {
type: actionTypes.notification.ADD,
payload: newNotf
});
expect(updatedState).toMatchObject([
newNotf
]);
});
it('should delete the existing notification from the state', () => {
const updatedState = reducer(initialState, {
type: actionTypes.notification.DELETE,
payload: 2
});
const matchObject = [...initialState];
matchObject.splice(1, 1);
expect(updatedState).toMatchObject(matchObject);
});
});
|
// ==========================================================================
// Project: SRCHR - mainPage
// Copyright: ©2011 jphpsf
// ==========================================================================
// This page describes the main user interface for this application.
SRCHR.mainPage = SC.Page.design({
// The main pane is made visible on screen as soon as the app is loaded.
// It contains several child views.
mainPane: SC.MainPane.design({
// We have 3 child views:
// form is the top area where the user types his query
// search is the results area with history on the left and results on the right
// status is a status bar for user notices
childViews: 'form search status'.w(),
// The form includes the logo on the left and text input + search button
// and checkboxes to pick sources on the right
form: SC.View.design({
layout: { top: 0, left: 0, right: 0, height: 96},
childViews: 'logo query sourcePicker'.w(),
anchorLocation: SC.ANCHOR_TOP,
// This will be the area for the title and/or logo on the left
logo: SC.View.design({
layout: { height: 36, left: 30, width: 210, top: 30},
classNames: ['logo']
}),
// This will be the area where the user types a query and hit search
query: SC.FormView.design({
layout: { height: 36, left: 210, width: 800, top: 12},
childViews: 'queryInput'.w(),
queryInput: SC.FormView.row('', SC.View.design(SC.FlowedLayout, {
childViews: 'searchBox searchButton'.w(),
// This is our search text input
searchBox: SC.TextFieldView.design({
layout: { width: 410, height: 24 },
classNames: ['search'],
value: 'Search term',
hint: 'Type your search term here and press "Find it!"',
valueBinding: 'SRCHR.searchController.searchString'
}),
// This is the search button which on click will call SRCHR.searchController.findIt
searchButton: SC.ButtonView.design({
toolTip: 'Click to search',
layout: { width: 60, height: 24},
title: 'Find it!',
//hasIcon: YES,
//icon: 'search'
target: 'SRCHR.searchController',
action: 'findIt'
})
}))
}),
// The list of sources to search from: this is a simple group of checkboxes
// See the source for SourceCheckboxesView in views/source_checkboxes.js
sourcePicker: SRCHR.SourceCheckboxesView.design({
layout: { height: 40, left: 230, width: 800, top: 56}
})
}),
// This is the area of the app where we display recent searches on the left
// and results on the right
search: SC.View.design({
layout: { top: 97, left: 0, right: 0, bottom: 36},
childViews: 'recents results'.w(),
// This is a simple list of recent searches
recents: SC.ScrollView.design({
hasHorizontalScroller: NO,
// Added this to get the borders, got the idea from the SC.TabView, is
// it the right way to do it?
renderDelegateName: 'wellRenderDelegate',
layout: { left: 20, width: 190, bottom: 20, top: 13 },
backgroundColor: 'white',
contentView: SC.ListView.design({
classNames: [ 'history' ],
rowHeight: 25,
// Here we override the default list item rendering and create our own with a custom
// view SRCHR.SearchItemView (used sc-gen view)
exampleView: SRCHR.SearchItemView,
// Bind to the search controller to get the content in
contentBinding: 'SRCHR.searchController.arrangedObjects',
selectionBinding: 'SRCHR.searchController.selection',
// This is a computer property that will display a search term with the
// associated sources (see model)
contentValueKey: 'term',
// This to allow deletion if user press delete key
canDeleteContent: YES,
// On double click we need to use the target selection as our current search
target: 'SRCHR.searchController',
action: 'loadRecent'
})
}),
// This is an area that will contain the results for a give search
// TODO: make this dynamic like the checkboxes
results: SC.TabView.design({
layout: { left: 240, right: 20, bottom: 20, top: 0 },
itemTitleKey: 'tab',
itemValueKey: 'panel',
itemIconKey: 'icon',
value: 'SRCHR.mainPage.mainPane.search.results.noResults',
items: [
{ tab: 'Flickr', icon: static_url('flickr-icon'), panel: 'SRCHR.mainPage.mainPane.search.results.flickrResults' },
{ tab: 'Yahoo!', icon: static_url('yahoo-icon'), panel: 'SRCHR.mainPage.mainPane.search.results.yahooResults' },
{ tab: 'Upcoming', icon: static_url('upcoming-icon'), panel: 'SRCHR.mainPage.mainPane.search.results.upcomingResults' },
{ tab: 'Twitter', icon: static_url('twitter-icon'), panel: 'SRCHR.mainPage.mainPane.search.results.twitterResults' }
],
tabLocation: SC.TOP_LOCATION,
noResults: SC.LabelView.design({
layout: { top: 0, right:0, left: 0, bottom:0 },
backgroundColor: 'white',
value: ' No results'
}),
yahooResults: SC.LabelView.design({
layout: { top: 0, right:0, left: 0, bottom:0 },
backgroundColor: 'white',
value: ' No results on Yahoo (NOT IMPLEMENTED)'
}),
flickrResults: SC.LabelView.design({
layout: { top: 0, right:0, left: 0, bottom:0 },
backgroundColor: 'white',
value: ' No results on Flickr (NOT IMPLEMENTED)'
}),
upcomingResults: SC.LabelView.design({
layout: { top: 0, right:0, left: 0, bottom:0 },
backgroundColor: 'white',
value: ' No results on Upcoming (NOT IMPLEMENTED)'
}),
twitterResults: SC.LabelView.design({
layout: { top: 0, right:0, left: 0, bottom:0 },
backgroundColor: 'white',
value: ' No results on Twitter (NOT IMPLEMENTED)'
})
})
}),
// This is a status bar in which we'll show notices to the user
status: SC.ToolbarView.design({
layout: { bottom: 0, left: 0, right: 0, height: 36 },
childViews: 'status'.w(),
anchorLocation: SC.ANCHOR_BOTTOM,
status: SC.LabelView.design({
layout: { centerY: 0, right:10, left: 10, height:20 },
fontWeight: SC.BOLD_WEIGHT,
valueBinding: 'SRCHR.statusController.status'
})
})
})
});
|
import React, { Component } from 'react';
import '../css/PrintableComponent.css';
class PrintableComponent extends Component {
render () {
return (
<div>
<p>This will be printed</p>
<a href="https://github.com/mmarotti">Cool github profile</a>
</div>
)
}
}
export default PrintableComponent;
|
/*编写自定义的JavaScript函数maskingKeyboard(),
在该函数中屏蔽键盘的回车键、退格键、F5键、Ctrl+N组合键、Shift+F10组合键*/
function maskingKeyboard(){
var keyCode = event.keyCode ? event.keyCode
: event.which ? event.which : event.charCode;
if(keyCode==8){
//判断是否为退格键
event.KeyCode=0;
event.returnValue=false;
alert("当前不允许使用退格键!");
}
if(KeyCode==13){
//判断是否为回车键
event.KeyCode=0;
event.returnValue=false;
alert("当前不允许使用回车键!");
}
if(KeyCode==116){
//判断是否为F5键
alert("it's F5");
event.KeyCode=0;
event.returnValue=false;
alert("当前不允许使用F5刷新键!");
}
if((event.altKey)&&(KeyCode==37)||(KeyCode==39)){
//判断是否为Alt+方向键←或方向键→
event.returnValue=false;
alert("当前设置不允许使用Alt+方向键←或方向键→");
}
if((event.ctrlKey)&&(KeyCode==78)){
//判断是否为ctrl+N
event.returnValue=false;
alert("当前设置不允许使用Ctrl+N新建IE窗口");
}
if((event.shiftKey)&&(KeyCode==121)){
//判断是不是shift+F10
event.returnValue=false;
alert("当前设置不允许使用shift+F10");
}
}
|
import React from 'react';
import styled from 'styled-components';
import { HEADER_ONE_FONT_SIZE, HEADER_TWO_FONT_SIZE, COLOR_ZOLAR_BLUE, HEADER_CUSTOM_FONT_SIZE } from "./Theme";
const CustomHeader = styled.span`
font-size: ${HEADER_CUSTOM_FONT_SIZE};
font-weight: ${props => props.fontWeight ? props.fontWeight : 400};
color: ${props => props.color ? props.color : COLOR_ZOLAR_BLUE};
padding: ${props => props.padding ? props.padding : 0};
margin: ${props => props.margin ? props.margin : 0};
width: ${props => props.fullwidth && "100%"};
`;
const HeaderOne = styled.h1`
font-size: ${HEADER_ONE_FONT_SIZE};
font-weight: ${props => props.fontWeight ? props.fontWeight : 400};
color: ${props => props.color ? props.color : COLOR_ZOLAR_BLUE};
padding: ${props => props.padding ? props.padding : 0};
margin: ${props => props.margin ? props.margin : 0};
`;
const HeaderTwo = styled.h2`
font-size: ${HEADER_TWO_FONT_SIZE};
font-weight: ${props => props.fontWeight ? props.fontWeight : 400};
color: ${props => props.color ? props.color : COLOR_ZOLAR_BLUE};
padding: ${props => props.padding ? props.padding : 0};
margin: ${props => props.margin ? props.margin : 0};
`;
export const Header = ({custom, h1, h2, children, ...props}) => {
// other props: color, padding, margin, fontWeight
if (custom) {return (<CustomHeader {...props}>{children}</CustomHeader>)}
if (h1) {return (<HeaderOne {...props}>{children}</HeaderOne>)}
if (h2) {return (<HeaderTwo {...props}>{children}</HeaderTwo>)}
};
|
/*global ODSA */
// Inseh1234 slideshow
$(document).ready(function() {
"use strict";
var av_name = "ProofOfStake";
var av = new JSAV(av_name);
var topMargin = 50;
var leftMargin = 390;
let leftAdding = 54;
var blocktop = 17;
var graph = av.ds.graph({visible: true, left: -10, top: blocktop, height: 300, width: 300});
av.umsg("The white nodes on perimeter of the graph represent 'thin nodes', essentially just users of the Ethereum network. The blue interior nodes represent the set of validator nodes that were selected to be part of the validation committee. A singular validator for the current block has not yet been selected. You will notice the validator nodes vary in size, this is done in proportion to how much each validator is staking. The bigger nodes represent a validator who has staked more tokens.");
// Thin Nodes
graph.css({"font-size": "12px"});
const a = graph.addNode('1', { "left": "200px", "bottom":"700px"});
const b = graph.addNode('2', {"left": "100px", "top":"150px"});
const c = graph.addNode('3', {"left": "200px", "top":"300px"});
const d = graph.addNode('4', {"left": "300px", "top":"150px"});
// Validator Nodes
const val1 = graph.addNode('V1', {"left": "150px", "top":"100px"});
const val2 = graph.addNode('V2', {"left": "250px", "top":"100px"});
const val3 = graph.addNode('V3', {"left": "200px", "top":"150px"});
val1.addClass('bluenode');
val2.addClass('bluenode');
val3.addClass('bluenode');
// Blockchain Current State
var blockchain = av.ds.list({top: blocktop + 0, left: "550px", nodegap: 10});
blockchain.addFirst("Blk 2").addFirst("Blk 1");
blockchain.layout({updateTop: false});
// BUG: THIS IS NOT WORKING FOR RESIZING NODES
val1.addClass('smallNode');
val2.addClass('mediumNode');
val3.addClass('largeNode');
av.displayInit();
// Slide 2
av.umsg("The validator for the current block has now been selected as shown in yellow. This validator is responsible for generating and proposing the next block.");
val3.addClass('yellownode');
av.step();
// Slide 3
av.umsg("The selected validator node will now assemble transactions into a block. These transactions are publicly visible to all nodes on the network.")
const av3Edge = graph.addEdge(a, val3).addClass("orangeedge");
const bv3Edge = graph.addEdge(b, val3).addClass("orangeedge");
const cv3Edge = graph.addEdge(c, val3).addClass("orangeedge");
const dv3Edge = graph.addEdge(d, val3).addClass("orangeedge");
av.step();
// Slide 4
av.umsg("The selected validator node has now assembled enough transactions to propose a new block.");
av3Edge.hide();
bv3Edge.hide();
cv3Edge.hide();
dv3Edge.hide();
var v3Block = av.ds.list({"left": "165px", "top":"185px", nodegap: 10}).addFirst("V3 Block");
av.step();
// Slide 5
av.umsg("The selected validator node will now begin to broadcast the new block to the network so that the validation committee can begin voting.");
a.hide();
b.hide();
c.hide();
d.hide();
val1.addClass('topLeftSpot')
val2.addClass('topRightSpot')
val3.addClass('proposalSpot')
v3Block.addClass('deadCenterBlock');
av.step();
// Slide 6
av.umsg("All other committee members nodes will now vote with their staked currency on whether or not to approve the block proposed by V3. It is important to note that the committee members have voting power in proportion to their amount of staked currency.");
var rect1 = av.g.set();
rect1.push(av.g.rect(400, 100 + 50, 50, 200));
rect1.css({fill: "gray"});
av.label("Block Voting", {before: rect1, left: 325, top: -7}); //TODO: Fix label so that it displays correctly next to the rectangle
av.step();
// Slide 7
av.umsg("A majority of staked currency from non-validator nodes has voted in-favor of this block and thus, the block will be appended to the chain.");
var rect2 = av.g.set();
rect2.push(av.g.rect(400, 100 + 50, 50, 50));
rect2.css({fill: "gray"});
rect1.css({fill: "blue"});
av.step();
v3Block.hide();
blockchain.hide();
var blockchainUpdated = av.ds.list({top: blocktop + 0, left: "550px", nodegap: 10});
blockchainUpdated.addFirst("V3 Block").addFirst("Blk 2").addFirst("Blk 1");
blockchainUpdated.layout({updateTop: false});
av.recorded();
});
|
$(document).ready(function() {
$('#cssmenu ul li a').each( function() {
if( $(this).attr('href') == window.location.pathname ) {
$(this).addClass('active')
}
});
$('#cssmenu ul li a').mouseenter( function() {
$(this).addClass('hover');
});
$('#cssmenu ul li a').mouseleave( function() {
$(this).removeClass('hover');
});
$('#cssmenu ul li a').click( function() {
$('#cssmenu ul li a').each( function() {
/*if( $(this).attr('href') == window.location.pathname ) {
$(this).removeClass('active') */
});
});
});
|
import React, { useEffect, useCallback } from 'react';
import qs from 'query-string';
import styled from 'styled-components';
import Selection from './components/Selection';
import { scrollTo } from '../utils';
import ScreenshotProvider from './context/ScreenshotContext';
import { WIDGET_HIDE } from '../constants';
const Container = styled.div`
*, *:before, *:after {
box-sizing: border-box;
}
`;
const ButtonContainer = styled.div`
position: fixed;
left: 24px;
bottom: 24px;
z-index: 5001;
`;
const App = () => {
useEffect(() => {
const { feedbackstreet_boys_scroll } = qs.parse(window.location.search);
if (feedbackstreet_boys_scroll) {
scrollTo(feedbackstreet_boys_scroll);
}
}, []);
const onCancel = useCallback(() => {
chrome.runtime.sendMessage({ type: WIDGET_HIDE });
}, []);
const onSave = useCallback(() => {}, []);
return (
<ScreenshotProvider>
<Container>
<ButtonContainer>
<button type="button" onClick={onCancel}>
Cancel
</button>
</ButtonContainer>
<Selection
onSave={onSave}
onClose={onCancel}
/>
</Container>
</ScreenshotProvider>
);
};
export default App;
|
/********************************************************************
* Handler for image/label (element) requests.
*
* Note: cwd is '..' for this '../lib/script'...
*/
// console.log(`\nmodule = %o`, module)
// console.log(`module.exports = %o`, module.exports)
// console.log(`exports = %o`, exports)
// console.log(`module.exports === exports = ${module.exports === exports}`)
const fs = require('fs')
const IDX = require('./idx')
const { collate, bySize } = require('./streamutils')
'use strict'
const charset = 'utf-8' // TODO: Institutionalize this...
let database = 'training'
const inputs = {
'training': {
'images': {
fileName: 'MNIST/train-images-idx3-ubyte',
idx: null,
},
'labels': {
fileName: 'MNIST/train-labels-idx1-ubyte',
idx: null,
},
},
'testing': {
'images': {
fileName: 'MNIST/t10k-images-idx3-ubyte',
idx: null,
},
'labels': {
fileName: 'MNIST/t10k-labels-idx1-ubyte',
idx: null,
},
},
}
function loadIndex(forThis, begin, count) {
return forThis.idx = new IDX(forThis.fileName, begin, count)
}
function logImageA(width, height, data) {
let text = '\n' + '-'.repeat(width)
for (let y = 0; y < height; ++y) {
text += '\n'
for (let x = 0; x < width; ++x) {
const byte = data[y * width + x]
text += byte ? 'X' : ' '
}
}
text += '\n' + '-'.repeat(28)
console.log(text)
}
const xhr = {
async getElements(request, response, begin, count) {
const { headers, method, url } = request
// const cwd = process.cwd()
const imgX = loadIndex(inputs[database].images, begin, count)
const lblX = loadIndex(inputs[database].labels, begin, count)
const streams = [
bySize(imgX.reader, imgX.size),
bySize(lblX.reader, lblX.size)
]
const reader = collate(streams) // A multiplexer.
// TODO: Just start writing into response stream as data
// arrives. Don't forget to prefix with header.
let data = null
try {
let firstTime = true
for await (data of reader) {
if (typeof data[0] === 'undefined')
break // normal termination
if (firstTime) {
firstTime = false
response.statusCode = 200;
response.setHeader('Content-Type', 'application/octet-stream');
}
let header = new Uint8Array(4)
header[0] = data[1][0] // label
header[1] = imgX.dims[1] // height, #rows
header[2] = imgX.dims[2] // width, #columns
header[3] = 0
let totalLength = 4 + imgX.size
let buffer = Buffer.concat([header, data[0]], totalLength)
// console.log(`xhr: sending ${totalLength} bytes`
// + `, index ${begin++}`)
// logImageA(header[2], header[1], data[0])
response.write(buffer)
}
}
catch (reject) {
throw reject
}
finally {
response.end();
}
},
async setDatabase(request, response, dbName = 'training') {
if (dbName) dbName = dbName.toLowerCase()
const abort = function (status, message) {
console.error(message)
response.statusCode = status
response.setHeader('Content-Type', `text/plain; ${charset}`)
response.end(message)
}
switch (dbName) {
case 'training':
case 'testing':
database = dbName
break
default:
return abort(404, `Unknown database (${dbName}), ignoring`)
}
const imgX = loadIndex(inputs[database].images, 0, 1)
const message = `Set database to "${dbName}," ${imgX.dimString}`
console.log(message)
response.statusCode = 200
response.setHeader('Content-Type', `text/plain; ${charset}`)
const [count, height, width] = imgX.dims
response.end(`count=${count}\nheight=${height}\nwidth=${width}\n`)
},
}
exports.getElements = xhr.getElements
exports.setDatabase = xhr.setDatabase
// console.log(`\nmodule = %o`, module)
// console.log(`module.exports = %o`, module.exports)
// console.log(`exports = %o`, exports)
// console.log(`module.exports === exports = ${module.exports === exports}`)
|
/**
* Created by krinjadl on 2016-07-01.
*/
import { INCREMENT,DECREMENT,SET_DIFF,ADDMESSAGE,UPDATEMESSAGESTATE,DELETEMSG,ITEMSELECTED} from '../actions';
import { combineReducers } from 'redux';
import { routerReducer} from 'react-router-redux';
const initialState = {
messageList: [],
newMessage:"",
selectedItemIndex:null,
value : 0,
diff : 1
};
const msgReducer = (state = initialState , action ) => { //set default state
switch (action.type){
case ADDMESSAGE:
return Object.assign({}, state, {
messageList:state.messageList.slice().concat(state.newMessage)
});
case UPDATEMESSAGESTATE:{
return Object.assign({}, state, {
newMessage: action.newMessage
});
}
case DELETEMSG:
let tmpArr = state.messageList.slice();
tmpArr.splice(state.selectedItemIndex,1);
return Object.assign({}, state, {
messageList:tmpArr
});
case ITEMSELECTED:
return Object.assign({}, state, {
selectedItemIndex: action.selectedItemIndex
});
default:
return state;
}
};
const countReducer = (state = initialState , action ) => { //set default state
switch (action.type){
case INCREMENT:
return Object.assign({}, state, {
value:state.value + state.diff
});
case DECREMENT:
return Object.assign({}, state, {
value:state.value - state.diff
});
case SET_DIFF:
return Object.assign({}, state, {
diff : action.diff
});
default:
return state;
}
};
// const extra = (state = {value : 'this_is_extra_reducer'}, action ) => {
// switch (action.type){
// default:
// return state;
// }
// };
const reduxTutorialApp = combineReducers({
msgReducer,
//countReducer,
routing:routerReducer
});
export default reduxTutorialApp;
//export default msgReducer;
|
//Импортировали данные
import React, { Component } from 'react';
//AppRegistry импортируем всегда, а виджет Image ипортируем по надобности
import { AppRegistry, Image } from 'react-native';
//Создали компонент, это кирпичик из которого строим программу.
export default class Bananas extends Component {
// Функция render - рисует виджеты на экране, нужна любому компоненту
render() {
let pic = {
uri: 'https://images-na.ssl-images-amazon.com/images/I/71gI-IUNUkL._SY355_.jpg'
};
// чтобы что-то нарисовать, надо поставить в return
return (
// если пишем виджет, то ставим угловые скобки
<Image
source={pic}
style={
{
width: 593,
height: 110
}
}
/>
);
}
}
|
document.onkeyup = (event) => {
let key = event.key;
if ([1, 2, 3].indexOf(Number(key)) > -1) {
const audio = document.querySelector(`#audio${key}`);
if (audio.paused) {
audio.play();
} else {
var fadeInterval = setInterval(function(){fadeOut(audio) },300);
fadeOut(audio);
}
}
};
function fadeOut(audio) {
// TODO: loop for 2 seconds dropping the volume as you go
if(audio.volume >= 0.0){
audio.volume -= 0.1;
}else{
//audio.pause();
clearInterval(fadeInterval)
audio.pause();
}
}
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "c4d928206c7dc01ada44b60ee488307f",
"url": "/index.html"
},
{
"revision": "a1f5f04a2ff09f4822a6",
"url": "/static/js/2.0fd1f235.chunk.js"
},
{
"revision": "dcceb77afec6303e7501",
"url": "/static/js/main.ef2ee6c1.chunk.js"
},
{
"revision": "42ac5946195a7306e2a5",
"url": "/static/js/runtime~main.a8a9905a.js"
}
]);
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = _default;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _ajv = _interopRequireDefault(require("ajv"));
var _amqplib = _interopRequireDefault(require("amqplib"));
var _v = _interopRequireDefault(require("uuid/v1"));
var _httpRequest = _interopRequireDefault(require("./validator/httpRequest"));
var _httpResponse = _interopRequireDefault(require("./validator/httpResponse"));
var ajv = new _ajv["default"]();
var validateHttpRequest = ajv.compile(_httpRequest["default"]);
var validateHttpResponse = ajv.compile(_httpResponse["default"]);
function _default(_x) {
return _ref.apply(this, arguments);
}
function _ref() {
_ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(clientConfig) {
var connection, channel, queue, callbackCorrMap, RPCImpl, _RPCImpl;
return _regenerator["default"].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_RPCImpl = function _RPCImpl3() {
_RPCImpl = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(method, url, cookies, query, headers, body) {
var requestObj, corr, publishOptions;
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
requestObj = {
method: method,
url: url,
cookies: cookies,
query: query,
headers: headers,
body: body
};
if (validateHttpRequest(requestObj)) {
_context.next = 3;
break;
}
return _context.abrupt("return", new Promise(function (resolve, reject) {
reject(new Error('[ERROR] Chapar: Invalid http request is not allowed to be sent to the queue'));
}));
case 3:
corr = (0, _v["default"])();
publishOptions = clientConfig.publish.options;
publishOptions.correlationId = corr;
publishOptions.replyTo = queue.queue;
channel.publish(clientConfig.exchange.name, clientConfig.publish.routingKey || 'HTTP_OVER_AMQP_ROUTING_KEY', Buffer.from(JSON.stringify(requestObj)), publishOptions);
return _context.abrupt("return", new Promise(function (resolve) {
callbackCorrMap.push({
corr: corr,
resolve: resolve
});
}));
case 9:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _RPCImpl.apply(this, arguments);
};
RPCImpl = function _RPCImpl2(_x2, _x3, _x4, _x5, _x6, _x7) {
return _RPCImpl.apply(this, arguments);
};
if (clientConfig != null && clientConfig.rabbitMQ != null && clientConfig.rabbitMQ.host != null && clientConfig.rabbitMQ.port != null && clientConfig.exchange != null && clientConfig.exchange.name != null) {
_context2.next = 4;
break;
}
throw new Error('[Error] Chapar: Invalid Chapar config. Please specify required options as expected in docs.');
case 4:
clientConfig.exchange.type = clientConfig.exchange.type || 'direct';
clientConfig.exchange.options = clientConfig.exchange.options || {
durable: true
};
clientConfig.queueing = clientConfig.queueing || {};
clientConfig.replyQueue = clientConfig.replyQueue || {};
clientConfig.replyQueue.name = clientConfig.replyQueue.name || '';
clientConfig.replyQueue.options = clientConfig.replyQueue.options || {
exclusive: true
};
clientConfig.replyQueue.prefetch = clientConfig.replyQueue.prefetch || 0;
clientConfig.publish = clientConfig.publish || {};
clientConfig.publish.routingKey = clientConfig.publish.routingKey || 'HTTP_OVER_AMQP_ROUTING_KEY';
clientConfig.publish.options = clientConfig.publish.options || {
persistent: true
};
_context2.next = 16;
return _amqplib["default"].connect(clientConfig.rabbitMQ.username == null ? "amqp://".concat(clientConfig.rabbitMQ.host, ":").concat(clientConfig.rabbitMQ.port) : "amqp://".concat(clientConfig.rabbitMQ.username, ":").concat(clientConfig.rabbitMQ.password, "@").concat(clientConfig.rabbitMQ.host, ":").concat(clientConfig.rabbitMQ.port));
case 16:
connection = _context2.sent;
_context2.next = 19;
return connection.createChannel();
case 19:
channel = _context2.sent;
channel.assertExchange(clientConfig.exchange.name, clientConfig.exchange.type, clientConfig.exchange.options);
_context2.next = 23;
return channel.assertQueue(clientConfig.replyQueue.name, clientConfig.replyQueue.options);
case 23:
queue = _context2.sent;
channel.prefetch(clientConfig.replyQueue.prefetch);
callbackCorrMap = [];
channel.consume(queue.queue, function (msg) {
var responseObj = JSON.parse(msg.content.toString());
if (!validateHttpResponse(responseObj)) {
console.log('[WARNING] Chapar: Invalid http response was fetched in the queue. The message is ignored due to preventing unhandled exceptions.');
}
var status = responseObj.status,
body = responseObj.body,
headers = responseObj.headers;
var callbackObject = callbackCorrMap.find(function (x) {
return x.corr === msg.properties.correlationId;
});
if (callbackObject && callbackObject.resolve && typeof callbackObject.resolve === 'function') {
callbackObject.resolve({
status: status,
body: body,
headers: headers
});
callbackCorrMap.splice(callbackCorrMap.indexOf(callbackObject), 1);
} else {
console.log('[WARNING] Chapar: A message received in the queue witch correlated callback was not found in the client.');
}
}, {
noAck: false
});
return _context2.abrupt("return", RPCImpl);
case 28:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return _ref.apply(this, arguments);
}
|
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
}
const uuidv4 = require('uuid/v4');
const bcrypt = require('bcrypt');
class Users {
constructor(db) {
this.db = db;
this._users = db.use('_users');
this._session = db.use('_session');
}
async auth(username, password) {
return await this.db.auth(username, password);
}
async get(user_id) {
return await this._users.get(user_id);
}
async create(username, password) {
var _id = 'org.couchdb.user:' + username;
return await this._users.insert({
'name': username,
'password': password,
'roles': [],
'type': 'user',
}, _id);
}
}
module.exports = function(db) {
return new Users(db);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.