hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
611eacdc1f3b06d3de5803b71f53533fb66ff554 | 194 | js | JavaScript | webapp/javascript/util/history.js | ScriptBox99/pyroscope | fbf5bd297caf6a987f9fb6ffd0240ed804eaf9b4 | [
"Apache-2.0"
] | 2 | 2022-01-03T01:01:13.000Z | 2022-01-03T21:30:01.000Z | webapp/javascript/util/history.js | ScriptBox99/pyroscope | fbf5bd297caf6a987f9fb6ffd0240ed804eaf9b4 | [
"Apache-2.0"
] | 15 | 2021-10-02T11:57:36.000Z | 2021-12-15T16:44:58.000Z | webapp/javascript/util/history.js | admariner/pyroscope | e13afb40348914ae29b813881bfad0ca3b89f250 | [
"Apache-2.0"
] | null | null | null | // src/myHistory.js
import { createBrowserHistory } from 'history';
import basename from './baseurl';
const history = createBrowserHistory({
basename: basename(),
});
export default history;
| 21.555556 | 47 | 0.742268 |
611f83c212caf4f686b77cbfc1769cef04621780 | 8,349 | js | JavaScript | src/containers/Table/OrderTable.index.js | mugheerasadiq/KhareedLoAdminPanel | 2b885488879ac1a4f612d2d982410ddd73e82aff | [
"MIT"
] | 1 | 2021-02-02T15:57:50.000Z | 2021-02-02T15:57:50.000Z | src/containers/Table/OrderTable.index.js | basitimam/Khareedlo-adminPanel | be348e9c1ea1903e32eb547c01f5466f911a92e8 | [
"MIT"
] | null | null | null | src/containers/Table/OrderTable.index.js | basitimam/Khareedlo-adminPanel | be348e9c1ea1903e32eb547c01f5466f911a92e8 | [
"MIT"
] | null | null | null | import React, { Component } from "react";
import { connect } from "react-redux";
import { Table, Row, Col, Icon, Popconfirm, Input } from "antd";
import PropTypes from "prop-types";
import memoize from "memoize-one";
import { getAllOrders, deleteOrder } from "../../services/order.services";
import { Button, SearchInput } from "components/Shared";
import { setOrderLoader } from "../../actions/order.action";
import { openModal } from "../../actions/modal.action";
import { Modal, ModalHeader, ModalBody } from "reactstrap";
class OrderTableContainer extends Component {
// PropTypes
static propTypes = {
getAllUsers: PropTypes.func,
openModal: PropTypes.func,
setUserLoader: PropTypes.func,
loading: PropTypes.bool,
allUsers: PropTypes.array,
};
constructor(props) {
super(props);
// Initial State
this.state = {
dataSource: [],
loading: this.props.loading,
tableHeight: 500,
searchValue: "",
isModalOpen: false,
modalDataSource: [],
filterTable: null,
};
this.toggleModal = this.toggleModal.bind(this);
}
orderDetails = async (record) => {
let orders = [];
for (let i = 0; i < record.items.length; i++) {
orders.push(record.items[i]);
}
await this.setState({
modalDataSource: orders,
});
console.log(orders);
this.toggleModal();
};
static getDerivedStateFromProps(props, state) {
if (props.loading !== state.loading) {
return {
loading: props.loading,
};
}
return null;
}
toggleModal() {
this.setState({
isModalOpen: !this.state.isModalOpen,
});
}
componentDidMount() {
this.getTableData();
this.handleResize();
window.addEventListener("resize", this.handleResize);
}
// Handles the resize.
handleResize = () => {
this.setState({
tableHeight: window.innerHeight - 300,
});
};
getTableData = () => {
if (!this.props.allOrders) {
this.props.setOrderLoader(true);
return new Promise((resolve, reject) => {
this.props.getAllOrders(resolve, reject);
})
.then(() => {
this.props.setOrderLoader(false);
this.setState({
dataSource: [...this.props.allOrders],
});
})
.catch(() => {
this.props.setOrderLoader(false);
});
} else {
this.setState({
dataSource: [...this.props.allOrders],
});
}
};
handleChange = (pagination, filters, sorter) => {
this.setState({
filteredInfo: filters,
sortedInfo: sorter,
});
};
// Deletes a record.
onRecordDelete = (record) => {
this.props.setOrderLoader(true);
try {
return new Promise((resolve, reject) => {
this.props.deleteOrder(record, resolve, reject);
})
.then(() => {
this.setState(() => {
this.props.setOrderLoader(false);
});
alert("The Order has been deleted!");
})
.catch((err) => {
this.props.setOrderLoader(false);
console.log("cannot delete");
});
} catch (error) {
console.log(error);
this.props.setOrderLoader(false);
}
};
filterIt = memoize((arr, searchKey) => {
const list = arr.filter((obj) =>
Object.keys(obj).some((key) =>
key + "" !== "key" && key + "" !== "id"
? (obj[key] + "").toLowerCase().includes(searchKey.toLowerCase())
: null
)
);
if (list !== this.state.dataSource) {
this.setState({
dataSource: list,
});
}
});
onSearch = (text) => {
this.setState({
searchValue: text,
});
};
orderTable() {
const columns = [
{
title: "Product Name",
dataIndex: ["product", "name"],
width: 250,
},
{
title: "Category",
dataIndex: "product.category.name",
},
{
title: "Product Price",
dataIndex: "product.price",
},
{
title: "Quantity",
dataIndex: "quantity",
},
];
return (
<Table
columns={columns}
dataSource={this.state.modalDataSource}
pagination={false}
/>
);
}
search = (value) => {
const { dataSource } = this.state;
// console.log("PASS", { value });
// console.log(dataSource);
const filterTable = dataSource.filter((o) =>
Object.keys(o.user).some((k) =>
String(o.user[k])
.toLowerCase()
.includes(value.toLowerCase())
)
);
this.setState({ filterTable });
};
render() {
if (this.props.allOrders && this.props.allOrders.length > 0) {
this.filterIt(this.props.allOrders, this.state.searchValue);
}
// Columns
const columns = [
{
title: "Customer Name",
dataIndex: ["user", "name"],
width: 250,
},
{
title: "Email",
dataIndex: "user.email",
},
{
title: "Total amount",
dataIndex: "price",
},
{
title: "Total Orders",
dataIndex: "items.length",
},
{
title: "Show Orders",
key: "operation",
width: 100,
// fixed: 'right',
render: (text, record) => {
return (
<>
<Popconfirm
title="Are you sure you want to update this product?"
onConfirm={() => this.orderDetails(record)}
>
<div style={{ width: "100%", textAlign: "center" }}>
<Icon
style={{
alignSelf: "center",
cursor: "pointer",
fontSize: "1.7em",
color: "rgb(255,143,143)",
padding: 4,
background: "#efeded",
borderRadius: 25,
boxShadow: "1px 1px 1px rgba(0,0,0,0.3)",
}}
type="user-delete"
/>
</div>
</Popconfirm>
</>
);
},
},
{
title: "Delete",
key: "operation",
width: 100,
// fixed: 'right',
render: (text, record) => {
return (
<>
<Popconfirm
title="Are you sure you want to delete?"
onConfirm={() => this.onRecordDelete(record)}
>
<div style={{ width: "100%", textAlign: "center" }}>
<Icon
style={{
alignSelf: "center",
cursor: "pointer",
fontSize: "1.7em",
color: "rgb(255,143,143)",
padding: 4,
background: "#efeded",
borderRadius: 25,
boxShadow: "1px 1px 1px rgba(0,0,0,0.3)",
}}
type="user-delete"
/>
</div>
</Popconfirm>
</>
);
},
},
];
return (
<div>
<Modal isOpen={this.state.isModalOpen} toggle={this.toggleModal}>
<ModalHeader toggle={this.toggleModal}>Order Details</ModalHeader>
<ModalBody>{this.orderTable()}</ModalBody>
</Modal>
<Input.Search
style={{ border: "3px solid white", margin: "0 0 10px 0" }}
placeholder="Search by..."
enterButton
onSearch={this.search}
/>
<Table
columns={columns}
dataSource={
this.state.filterTable == null
? this.state.dataSource
: this.state.filterTable
}
bordered
size="middle"
loading={this.state.loading}
scroll={{ y: this.state.tableHeight }}
pagination={false}
// onChange={this.handleChange}
rowKey={(record) => record.id}
/>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
allOrders: state.order.allorders,
loading: state.order.loading,
};
};
export default connect(mapStateToProps, {
getAllOrders,
setOrderLoader,
openModal,
deleteOrder,
})(OrderTableContainer);
| 24.848214 | 76 | 0.492993 |
611fef3a2362559c3ba1f1b3cae7cc455abc82fe | 179 | js | JavaScript | client/src/components/Join/actions.js | patteri/slave-cardgame | cc2d537401f8b4d8b22819b7a0c94a5be018573a | [
"MIT"
] | 1 | 2020-07-31T17:49:11.000Z | 2020-07-31T17:49:11.000Z | client/src/components/Join/actions.js | patteri/slave-cardgame | cc2d537401f8b4d8b22819b7a0c94a5be018573a | [
"MIT"
] | 27 | 2017-07-10T06:31:06.000Z | 2022-03-08T22:35:05.000Z | client/src/components/Join/actions.js | patteri/slave-cardgame | cc2d537401f8b4d8b22819b7a0c94a5be018573a | [
"MIT"
] | 1 | 2017-06-16T16:04:33.000Z | 2017-06-16T16:04:33.000Z | import { createAction } from 'redux-actions';
export const gameIdChanged = createAction('GAME_ID_CHANGED');
export const usernameChanged = createAction('JOIN_USERNAME_CHANGED');
| 35.8 | 69 | 0.804469 |
61201a3ce3b1881cf67c1ddd8c20888a1cf07fc6 | 40 | js | JavaScript | packages/miniapp-render/src/builtInComponents/rich-text.js | dickeylth/miniapp | 01f06db32de3727d5f03e1eab110b9b677d9b175 | [
"BSD-3-Clause"
] | 58 | 2020-10-12T09:30:33.000Z | 2022-03-28T07:26:43.000Z | packages/miniapp-render/src/builtInComponents/rich-text.js | dickeylth/miniapp | 01f06db32de3727d5f03e1eab110b9b677d9b175 | [
"BSD-3-Clause"
] | 41 | 2020-09-28T09:31:17.000Z | 2022-02-14T09:17:24.000Z | packages/miniapp-render/src/builtInComponents/rich-text.js | dickeylth/miniapp | 01f06db32de3727d5f03e1eab110b9b677d9b175 | [
"BSD-3-Clause"
] | 27 | 2020-09-25T07:40:56.000Z | 2022-02-16T07:50:46.000Z | export default {
name: 'rich-text'
};
| 10 | 19 | 0.625 |
612040e4e46d8072fc2cfecb71cea1f421a23858 | 652 | js | JavaScript | src/utils.js | corsicanec82/frontend-project-lvl4 | bea61590f9361d40d3cfecdf1e3c6c8ee8a56690 | [
"MIT"
] | null | null | null | src/utils.js | corsicanec82/frontend-project-lvl4 | bea61590f9361d40d3cfecdf1e3c6c8ee8a56690 | [
"MIT"
] | 8 | 2020-09-06T20:48:27.000Z | 2022-03-08T22:59:15.000Z | src/utils.js | corsicanec82/frontend-project-lvl4 | bea61590f9361d40d3cfecdf1e3c6c8ee8a56690 | [
"MIT"
] | 1 | 2021-10-05T21:04:42.000Z | 2021-10-05T21:04:42.000Z | import faker from 'faker/locale/en';
import Cookies from 'js-cookie';
import _keyBy from 'lodash/keyBy';
export const getFakeUserData = () => ({
userName: faker.internet.userName(),
avatarUrl: faker.internet.avatar(),
});
export const getUserData = () => {
const userDataJSON = Cookies.get('userData') || JSON.stringify(getFakeUserData());
return JSON.parse(userDataJSON);
};
export const setUserData = (userData) => {
Cookies.set('userData', userData, { expires: 1 });
};
export const getStateFromData = (data) => {
const iteratee = item => item.id;
return {
byId: _keyBy(data, iteratee),
allIds: data.map(iteratee),
};
};
| 25.076923 | 84 | 0.677914 |
61210f15fb893bcfb14ffc8733afd709a7c7366a | 2,244 | js | JavaScript | server/handleMessageMethod/joinUserToAllChannels.js | samirsayyad/ep_rocketchat | b503f2007a7dc206b030c80f8e7a7bc6f34d4df8 | [
"MIT"
] | null | null | null | server/handleMessageMethod/joinUserToAllChannels.js | samirsayyad/ep_rocketchat | b503f2007a7dc206b030c80f8e7a7bc6f34d4df8 | [
"MIT"
] | 1 | 2021-12-16T18:08:19.000Z | 2022-03-01T07:34:27.000Z | server/handleMessageMethod/joinUserToAllChannels.js | samirsayyad/ep_rocketchat | b503f2007a7dc206b030c80f8e7a7bc6f34d4df8 | [
"MIT"
] | null | null | null | const db = require('ep_etherpad-lite/node/db/DB');
const config = require("../helpers/configs");
const joinChannels = require("../../rocketChat/api/separated").joinChannels
const rocketchatAuthenticator = require("../helpers/rocketchatAuthenticator");
const sharedTransmitter = require("../helpers/sharedTransmitter")
/**
*
* @param {padId} message
*/
exports.joinUserToAllChannels = async (message,socketClient)=>{
try{
const padId = message.padId;
const userId = message.userId;
const data = message.data;
var channelsMessageCount=[]
const rocketchatUserAuth = await rocketchatAuthenticator.runValidator(userId);
const channelsResults = await joinChannels(config, data.headerIds,rocketchatUserAuth.rocketchatAuthToken,rocketchatUserAuth.rocketchatUserId );
await db.set(`${config.dbRocketchatKey}:ep_rocketchat_canJoin_${padId}_${userId}`,"Y");
/**
* When this action fired, means user passed profile form and we can join him to channels
*/
const userGotHistoryStatus = await db.get(`${config.dbRocketchatKey}:ep_rocketchat_gotHistory_${padId}_${userId}`);
if(!channelsResults || !channelsResults.channels.length || userGotHistoryStatus =="Y") return ;
channelsResults.channels.forEach(element => {
channelsMessageCount.push({
name : element.name,
fname : element.fname,
count : element.msgs,
})
});
//it's a flag in db that represent user got history once
await db.set(`${config.dbRocketchatKey}:ep_rocketchat_gotHistory_${padId}_${userId}`,"Y");
const msg = {
type: 'COLLABROOM',
data: {
type: 'CUSTOM',
payload: {
padId: padId,
userId: userId,
action: 'updateChannelsMessageCount',
data: {
channelsMessageCount : channelsMessageCount
},
},
},
};
sharedTransmitter.sendToUser(msg,socketClient);
}catch(e){
console.error(e)
}
} | 35.0625 | 151 | 0.591355 |
e3553ff86922ee1757e38a00e81fbad06cc3439a | 1,569 | js | JavaScript | socket.io/index.js | remarkablemark/express-template | c425591619b0202d03d84d9254d8b16df4690414 | [
"MIT"
] | 9 | 2017-01-27T20:24:39.000Z | 2021-03-26T15:19:45.000Z | socket.io/index.js | remarkablemark/express-template | c425591619b0202d03d84d9254d8b16df4690414 | [
"MIT"
] | null | null | null | socket.io/index.js | remarkablemark/express-template | c425591619b0202d03d84d9254d8b16df4690414 | [
"MIT"
] | 1 | 2019-01-21T06:18:50.000Z | 2019-01-21T06:18:50.000Z | 'use strict';
/**
* Module dependencies.
*/
const { debug } = require('./helpers');
const socket = require('socket.io');
const session = require('../middleware/session');
// socket events
const { USER } = require('./events');
const connect = require('./connect');
const disconnect = require('./disconnect');
const messages = require('./messages');
const rooms = require('./rooms');
const user = require('./user');
/**
* Socket.IO server middleware.
*
* @param {Object} server - The server.
*/
function io(server) {
const io = socket(server);
// use session middleware
io.use((socket, next) => {
session(socket.request, socket.request.res, next);
});
// client connected
io.on('connection', (socket) => {
const { request } = socket;
debug('client connected', request.session);
// force client to disconnect if unauthenticated
if (!request.session.isAuthenticated) {
return socket.emit(USER, {
isAuthenticated: false
});
}
// save user id on socket
socket.userId = request.session._id;
socket.username = request.session.username;
// perform initial actions on connect
connect(io, socket);
// set up event listeners for user
user(io, socket);
// set up event listeners for messages
messages(io, socket);
// set up event listeners for rooms
rooms(io, socket);
// handle disconnect event
disconnect(socket);
});
}
module.exports = io;
| 24.138462 | 58 | 0.597196 |
e35548d31d8ef76dc346587580d5fe6961215c88 | 554 | js | JavaScript | src/config.js | danisabin/testcase | c889effb88ce6283e0d84ec6b22fa9874b539671 | [
"MIT"
] | null | null | null | src/config.js | danisabin/testcase | c889effb88ce6283e0d84ec6b22fa9874b539671 | [
"MIT"
] | null | null | null | src/config.js | danisabin/testcase | c889effb88ce6283e0d84ec6b22fa9874b539671 | [
"MIT"
] | null | null | null | 'use strict';
require('dotenv').config();
module.exports = {
port: process.env.PORT || 3000,
host: process.env.HOST || '0.0.0.0',
protocol: process.env.PROTOCOL || 'http',
logLevel: process.env.LOG_LEVEL || 'debug',
postgreSQL: {
host: process.env.PGHOST,
password: process.env.PGPASSWORD,
user: process.env.PGUSER,
database: process.env.PGDATABASE,
port: process.env.PGPORT,
},
swagger:{
options: {
info: {
title: 'Test Service API Documentation',
version: 'latest',
},
},
},
};
| 21.307692 | 48 | 0.606498 |
e35559d39bc811e6c5abd49d1f2ca9df574f3534 | 3,915 | js | JavaScript | src/routes/layout/components/footer/index.js | Arc152020/C-STEMP | 8c4d478da6a8879db126b32152ed71992459adb6 | [
"MIT"
] | 1 | 2021-01-25T11:18:57.000Z | 2021-01-25T11:18:57.000Z | src/routes/layout/components/footer/index.js | Arc152020/C-STEMP | 8c4d478da6a8879db126b32152ed71992459adb6 | [
"MIT"
] | null | null | null | src/routes/layout/components/footer/index.js | Arc152020/C-STEMP | 8c4d478da6a8879db126b32152ed71992459adb6 | [
"MIT"
] | null | null | null | import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import firebase from '../../../enrol/firebase';
import {GiHouse } from 'react-icons/gi';
import { HiOutlineMail } from "react-icons/hi";
import { FiPhone } from "react-icons/fi";
function footer(){
const [email, setEmail ] = useState('');
function handleEmail(event){
setEmail(prevEmail => { return event.target.value } );
}
function subscribe(e){
e.preventDefault();
try{
var result = firebase.firestore().collection("Newsletter").doc(email).set({email:email});
result.then(docRef =>{
document.querySelector(".status").innerHTML = `<p id="success">Thanks for Subscribing</p>`
})}
catch(err){
result.catch(error => {
document.querySelector(".status").innerHTML = `<p id="failure">Please Try again</p>`
})}
finally{
setEmail(prevEmail => {return ""});
}
}
return(
<div className="footer-container">
<footer className="top">
<div className="top-content">
<address>
<p> <GiHouse /> Plot 5 Citrus Estate New Abuja, Plateau State, Nigeria</p>
<p><HiOutlineMail /> nenji.emmanuel@cstemp.org</p>
<p> <FiPhone /> +234 901 1093 828</p>
</address>
<div className="useful-links">
<h4>Useful Links</h4>
<a href="https://www.cstemp.org"> C-STEMP Organisation</a> <br />
<a href="https://www.cstempedutech.com">C-STEMP EduTech</a> <br />
<a href="https://www.siteworx.ng.com">C-STEMP Siteworx</a> <br />
<a href="https://innovate.cstemp.org/otukpo/">C-STEMP Otukpo Innovation Hub</a> <br />
</div>
<div className="courses">
<h4>Our Trainings</h4>
<Link to="/enrol">Frontend Web Development</Link> <br />
<Link to="/enrol">Backend Web Development</Link> <br />
<Link to="/enrol">Graphic and UI/UX Design</Link> <br />
<Link to="/enrol">Python Programming</Link> <br />
<Link to="/enrol">Mobile Apps Development</Link> <br />
<Link to="/enrol">Digital Marketing</Link> <br />
<Link to="/enrol">AR/VR and Drones Technology </Link> <br />
</div>
<form onSubmit={subscribe} >
<label>Join our Newsletter </label><br />
<input type="text" placeholder="evelynsimon@gmail.com" value={email} onChange={handleEmail}/>
<button>Subscribe</button>
<div className="status"></div>
</form>
</div>
</footer>
<footer className="bottom">
<div className="bottom-content">
<p className="copyright">© 2021 C-STEMP Ltd/Gtee</p>
<p className="social-media-icons">
<a href="https://www.facebook.com/C-Stemp-Innovation-Centre-106411324587971"> <img src='/src/assets/img/fb.png' className="fb" /></a>
<a href="#"> <img src='/src/assets/img/twitter.png' className="tw" /></a>
<a href="https://www.instagram.com/_cstempinnovationcentre/"> <img src='/src/assets/img/instagram.png' className="ig" /></a>
<a href="#"> <img src='/src/assets/img/link.png' className="li" /></a>
</p>
</div>
</footer>
</div>
)
}
export default footer; | 41.648936 | 161 | 0.487356 |
e35615266da20d30d673b95b5994c283eb718a77 | 4,250 | js | JavaScript | benchmarks/index.js | weicrypto/weicore-node | 0101e637d2e9add952d71cfa41ef9fd9c26648d5 | [
"MIT"
] | null | null | null | benchmarks/index.js | weicrypto/weicore-node | 0101e637d2e9add952d71cfa41ef9fd9c26648d5 | [
"MIT"
] | null | null | null | benchmarks/index.js | weicrypto/weicore-node | 0101e637d2e9add952d71cfa41ef9fd9c26648d5 | [
"MIT"
] | null | null | null | 'use strict';
var benchmark = require('benchmark');
var weidRPC = require('@weicrypto/weid-rpc');
var async = require('async');
var maxTime = 20;
console.log('Wei Service native interface vs. Wei JSON RPC interface');
console.log('----------------------------------------------------------------------');
// To run the benchmarks a fully synced Wei Core directory is needed. The RPC comands
// can be modified to match the settings in wei.conf.
var fixtureData = {
blockHashes: [
'00000000fa7a4acea40e5d0591d64faf48fd862fa3561d111d967fc3a6a94177',
'000000000017e9e0afc4bc55339f60ffffb9cbe883f7348a9fbc198a486d5488',
'000000000019ddb889b534c5d85fca2c91a73feef6fd775cd228dea45353bae1',
'0000000000977ac3d9f5261efc88a3c2d25af92a91350750d00ad67744fa8d03'
],
txHashes: [
'5523b432c1bd6c101bee704ad6c560fd09aefc483f8a4998df6741feaa74e6eb',
'ff48393e7731507c789cfa9cbfae045b10e023ce34ace699a63cdad88c8b43f8',
'5d35c5eebf704877badd0a131b0a86588041997d40dbee8ccff21ca5b7e5e333',
'88842f2cf9d8659c3434f6bc0c515e22d87f33e864e504d2d7117163a572a3aa',
]
};
var weid = require('../').services.Wei({
node: {
datadir: process.env.HOME + '/.wei',
network: {
name: 'testnet'
}
}
});
weid.on('error', function(err) {
console.error(err.message);
});
weid.start(function(err) {
if (err) {
throw err;
}
console.log('Wei Core started');
});
weid.on('ready', function() {
console.log('Wei Core ready');
var client = new weidRPC({
host: 'localhost',
port: 18332,
user: 'wei',
pass: 'local321'
});
async.series([
function(next) {
var c = 0;
var hashesLength = fixtureData.blockHashes.length;
var txLength = fixtureData.txHashes.length;
function weidGetBlockNative(deffered) {
if (c >= hashesLength) {
c = 0;
}
var hash = fixtureData.blockHashes[c];
weid.getBlock(hash, function(err, block) {
if (err) {
throw err;
}
deffered.resolve();
});
c++;
}
function weidGetBlockJsonRpc(deffered) {
if (c >= hashesLength) {
c = 0;
}
var hash = fixtureData.blockHashes[c];
client.getBlock(hash, false, function(err, block) {
if (err) {
throw err;
}
deffered.resolve();
});
c++;
}
function weiGetTransactionNative(deffered) {
if (c >= txLength) {
c = 0;
}
var hash = fixtureData.txHashes[c];
weid.getTransaction(hash, true, function(err, tx) {
if (err) {
throw err;
}
deffered.resolve();
});
c++;
}
function weiGetTransactionJsonRpc(deffered) {
if (c >= txLength) {
c = 0;
}
var hash = fixtureData.txHashes[c];
client.getRawTransaction(hash, function(err, tx) {
if (err) {
throw err;
}
deffered.resolve();
});
c++;
}
var suite = new benchmark.Suite();
suite.add('weid getblock (native)', weidGetBlockNative, {
defer: true,
maxTime: maxTime
});
suite.add('weid getblock (json rpc)', weidGetBlockJsonRpc, {
defer: true,
maxTime: maxTime
});
suite.add('weid gettransaction (native)', weiGetTransactionNative, {
defer: true,
maxTime: maxTime
});
suite.add('weid gettransaction (json rpc)', weiGetTransactionJsonRpc, {
defer: true,
maxTime: maxTime
});
suite
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
console.log('----------------------------------------------------------------------');
next();
})
.run();
}
], function(err) {
if (err) {
throw err;
}
console.log('Finished');
weid.stop(function(err) {
if (err) {
console.error('Fail to stop services: ' + err);
process.exit(1);
}
process.exit(0);
});
});
});
| 25 | 96 | 0.555765 |
e356a7b7d314e80eb243c1e3fe2243a4caec988f | 1,552 | js | JavaScript | spec/calculatorPart2Spec.js | MasixoleMax/SimpleCalculator_Part_2 | 2f58f8c1c2f6fa536b8c5f5ca9ae88cf7e664c03 | [
"MIT"
] | null | null | null | spec/calculatorPart2Spec.js | MasixoleMax/SimpleCalculator_Part_2 | 2f58f8c1c2f6fa536b8c5f5ca9ae88cf7e664c03 | [
"MIT"
] | null | null | null | spec/calculatorPart2Spec.js | MasixoleMax/SimpleCalculator_Part_2 | 2f58f8c1c2f6fa536b8c5f5ca9ae88cf7e664c03 | [
"MIT"
] | null | null | null | describe("A simple calculator that can add muyltiple numbers", function(){
it ("should add two or more", function() {
expect(calculator.add(1, 3, 2)).toBe(6);
});
});
describe("Checking simple calculator that multiply multiple numbers", function() {
it ("should be able to multiply two or more numbers", function() {
expect(calculator.multiply(3,2,4)).toEqual(24);
});
});
describe("simple calculator that can return the last result", function() {
it ("should be able to remember and return the last result", function() {
calculator.multiply(1,2);
expect(calculator.Last()).toBe(2);
});
});
describe("simple calculator that can use the last result as a parameter", function() {
it ("should be able to use the last result as a parameter", function() {
calculator.add(1,2)
expect(calculator.multiply("LAST", 3)).toEqual(9); // the value of "LAST" is now 9
expect(calculator.add("LAST", 5)).toEqual(14)
});
});
describe("simple calculator that can use the slot function result as a parameter", function() {
it ("should be able to use the last result as a parameter", function() {
calculator.add(1,2);
calculator.set_slot(1);
calculator.multiply(1,3);
calculator.set_slot(2);
expect(calculator.multiply("SLOT_1", 1)).toEqual(3); // the value of "LAST" is now 9
expect(calculator.add("SLOT_2", 7)).toEqual(10);
});
});
| 23.164179 | 97 | 0.60567 |
e35726945aaed11bff25e74cc20614b8c19c2abf | 13,548 | js | JavaScript | src/index.js | zyn-frontcoder/promise-polyfill | 9ddbc59b4151d7338cd61995102217a7d3619377 | [
"MIT"
] | null | null | null | src/index.js | zyn-frontcoder/promise-polyfill | 9ddbc59b4151d7338cd61995102217a7d3619377 | [
"MIT"
] | null | null | null | src/index.js | zyn-frontcoder/promise-polyfill | 9ddbc59b4151d7338cd61995102217a7d3619377 | [
"MIT"
] | null | null | null | const promiseFinally = require('./finally');
const allSettled = require('./allSettled');
var setTimeoutFunc = setTimeout;
var setImmediateFunc = typeof setImmediate !== 'undefined' ? setImmediate : null;
function isArray(x) {
return Boolean(x && typeof x.length !== 'undefined');
}
function noop() { }
function bind(fn, thisArg) {
return function () {
fn.apply(thisArg, arguments);
};
}
/**
* Promise对象的核心三要素
* status: Pending->FullFilled->Rejected->Override
* value: resolveValue/rejectValue
* handled: handleBy then/catch
*
* Promise处理流程分为两类
* 1. 对于Promise对象自身的处理
* 根据resolve/reject的调用,调通用的handleResolve和handleReject处理,得到{value: resolvedValue,status: handleResolve(resolvedValue)/handleRejected(rejetedValue) }
* 2. 调用then时,直接创建一个空promise对象,作为返回值
* 调用then的promise对象为pending,将then注册到该promise上 => 返回的新promise {value: returnValueOfThen, status: handleResolve(returnValueOfThen)}
* 调用then的promise对象为确定状态 => 返回的新promise {value: returnValueOfThen, status: handleResolve(returnValueOfThen)}
*/
function Promise(fn) {
if (!(this instanceof Promise))
throw new TypeError('Promises must be constructed via new');
if (typeof fn !== 'function') throw new TypeError('not a function');
/**
* 当前promise状态
* 0 => Pending<待定>
* 1 => Fullfilled<满足>
* 2 => Rejected<拒绝>
* 3 => Override<被重写>
*/
this._state = 0;
/**
* 当前对象是否被自己的then/catch处理过
*/
this._handled = false;
/**
* resolve/reject的值,会作为调用对应回调时的入参
*/
this._value = undefined;
/**
* 在当前promise上注册的cbs
*/
this._deferreds = [];
doResolve(fn, this);
}
/**
* 1. 执行函数
* 2. 为resolve和reject定义实参 => 定义状态改变后的处理逻辑
*
* 直接执行fn说明Promise不在意,传入的fn是否是异步,因为回调是在调用resolve/reject才真正触发的
*
new Promise(async (resolve) => {
await new Promise(resolve => setTimeout(() => resolve(1), 1000));
await new Promise(resolve => setTimeout(() => resolve(2), 1000));
resolve(2000);
}).then(res => console.error('res->', res));
*/
function doResolve(fn, self) {
var done = false; // 标记只允许改变一次状态
try {
fn(
function (value) {
if (done) return;
done = true;
resolve(self, value);
},
function (reason) {
if (done) return;
done = true;
reject(self, reason);
}
);
} catch (ex) {
// 执行错误,也会被分发给onRejectedCb
if (done) return;
done = true;
reject(self, ex);
}
}
/**
* 将一个promise状态 Pending => FullFilled & 执行回调
*/
function resolve(self, newValue) {
try {
// 这里主要为了防止返回当前promise给不法者改变promise状态的机会
if (newValue === self){
throw new TypeError('A promise cannot be resolved with itself.');
}
// resolve的值是promiseObj或者具有then属性的对象时,需要改变指针
if (
newValue &&
(typeof newValue === 'object' || typeof newValue === 'function')
) {
var then = newValue.then;
if (newValue instanceof Promise) {
self._state = 3;
self._value = newValue;
finale(self);
return;
} else if (typeof then === 'function') {
doResolve(bind(then, newValue), self);
return;
}
}
// 正常resolve的流程
self._state = 1;
self._value = newValue;
finale(self);
} catch (e) {
/**
* onRejected进入的条件:运行错误/状态变为Rejected
* @test
* new Promise(resolve => a.toString()).then(null, err => console.error('err=>', err))
*/
reject(self, e);
}
}
/**
* 将Promise: pending => rejected & 执行回调
* 这里没有类似resolve对值的区分,因此一个reject状态的promise对象状态是无法再次改变的
* @test
* new Promise((resolve, reject) => reject(Promise.resolve(1))).then(res => console.error('res->', res)).catch(reason => console.error('reason->', reason))
*/
function reject(self, newValue) {
self._state = 2;
self._value = newValue;
finale(self);
}
/**
* 处理promise的单次回调
* 这说明同一Promise的回调,执行也是分批次的,不能保证连续执行
* 在Promise状态确定前注册的then(一个or多个),在promise对象的状态变化后在下一个微任务队列中批量执行
* 在Promise状态确定后注册的then(一个or多个),在在下一个微任务队列中批量执行
*/
function handle(self, deferred) {
/**
* 这段逻辑是为resolve(PromiseObj)的场景写的,这是唯一可以更改当前Promise状态的方法
* Promise实例返回一个resolve一个新的Promise时,使用该Promise替代当前的Promise对象
* 即resolve一个新的Promise时,回调是绑在返回的新Promise上的
*/
while (self._state === 3) {
self = self._value;
}
/**
* For: 这段逻辑是为then方法写的
* 如果then调用时,调用then的promise对象状态仍为pending,那么将cb注册到该对象上
*/
if (self._state === 0) {
self._deferreds.push(deferred);
return; // 使用return防止cb立即执行了
}
/**
* 进入后面说明Promise的状态已经确定了 FullFilled/Rejected
* 此时可以将实例的状态标记为handled,因为后续其回调肯定会被调用
*/
self._handled = true;
/**
* 这里是在执行promise对象的then方法,可能的触发常见有两种
* 1. promise对象的状态从pending->FullFilled/Rejected
* 2. 注册then时,Promise对象已确定,此时直接去除之前缓存的status和value,直接执行cb
*/
Promise._immediateFn(function () {
// deferred.onFulfilled || deferred.onRejected 指向了当前promise注册的cbs
var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
/**
* onFullFilled/onRejected为null时,将当前Promise的值赋值给返回的新Promise
* 这段逻辑是为catch设计的,如果then中未注册onRejectedCb,那么最终会被下个注册onRejected的then处理,被catch处理
* @test=>
* new Promise(resolve => resolve(1)).then(null).then(null).then(res => console.error(res))
*
* @test
* Promise.reject(1).then(null, reason => console.error('reason->', reason)).catch(err => console.error('err->', err));
*
* @test
* Promise.reject(1).then(null, reason => console.error('reason->', reason)).then(null, reason => console.error('reason->', reason));
*/
if (cb === null) {
(self._state === 1 ? resolve : reject)(deferred.promise, self._value);
return;
}
// 执行cb
var ret;
try {
ret = cb(self._value);
} catch (e) {
reject(deferred.promise, e);
return; // 说明then能执行
}
/**
* then特点总结
* 1. 入参是之前promise的resolve/reject的值 | resolve/reject的新Promise的reject值
* @test1 =>
* new Promise(resolve => resolve()).then(res => console.error(res))
* @test2 =>
* new Promise(resolve => {new Promise(innerResolve => innerResolve(1)); resolve(100)}).then(res => console.error(res));
* @test3 =>
* new Promise(resolve => {resolve(new Promise(innerResolve => innerResolve(1)))}).then(res => console.error(res));
*
* 2. then总是返回一个新的Promise,value为then函数的返回值
* 将then创建的新promise状态置为FullFilled,值设置为thencb的返回值
* 常说的Promise.prototype.then会默认包装返回值,其实不是默认包装,而是每次新建了一个空Promise,最后将promise的value设置为其返回值
* @test1 =>
* new Promise(resolve => resolve(1)).then(() => 10).then(res => console.error(res));
* @test2 =>
* new Promise(resolve => resolve(1)).then(() => Promise.reject(2)).then(null, reason => console.error(reason));
* @test3 =>
* new Promise(resolve => resolve(1)).then(() => new Promise(resolve => setTimeout(() => resolve(2), 3000))).then(res => console.error(res));
*
*/
resolve(deferred.promise, ret);
});
}
/**
* 执行绑在promise实例上的回调
*/
function finale(self) {
if (self._state === 2 && self._deferreds.length === 0) {
Promise._immediateFn(function () {
if (!self._handled) {
Promise._unhandledRejectionFn(self._value);
}
});
}
/**
* 这里是将指针传递了,往异步队列里添加了一个待执行的cb;
* 这意味着then回调肯定是按顺序异步执行的,但是是否在同一微任务队列得看注册的时间节点
* @test
```
const p = new Promise(resolve => resolve(1));
p.then(res1 => console.error('res1->', res1));
requestAnimationFrame(() => {
console.error('requestAnimationFrame called');
})
p.then(res2 => console.error('res2->', res2));
setTimeout(() => {
console.error('timeout01 called');
}, 10)
setTimeout(() => {
console.error('timeout02 called');
}, 10)
setTimeout(() => {
console.error('timeout03 called');
}, 100)
p.then(res3 => console.error('res3->', res3));
setTimeout(() => {
p.then(res4 => console.error('res4->', res4));
}, 50)
```
*
*/
for (var i = 0, len = self._deferreds.length; i < len; i++) {
handle(self, self._deferreds[i]); //
}
// 清空待执行的回调,防止内存泄漏
self._deferreds = null;
}
// 处理回调区分onFulfilled|onRejected和promise实例指向
function Handler(onFulfilled, onRejected, promise) {
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
this.onRejected = typeof onRejected === 'function' ? onRejected : null;
this.promise = promise; // 链表设计,指向下一个要处理的promise
}
/**
* 参考handle中对catch的特殊设计
* 这里默认调用一次then,只处理onRejected,这样就保证了@运行错误/@rejected未处理,会被捕获
* 也意味着,如果在then中处理了无法被catch处理
* @test
new Promise(resolve => a.toString()).then(null, err => console.error('err=>', err)).catch(err => console.error('catch->', err));
* @test
new Promise(resolve => a.toString()).then(null, err => Promise.reject(1)).catch(err => console.error('catch->', err));
*/
Promise.prototype['catch'] = function (onRejected) {
return this.then(null, onRejected);
};
/**
* @Promise.prototype.then
* 每次调用立即创建一个Pending状态的空Promise
*/
Promise.prototype.then = function (onFulfilled, onRejected) {
var prom = new this.constructor(noop); // 每次返回一个空的promise
handle(this, new Handler(onFulfilled, onRejected, prom));
return prom; // 【链式调用核心1】
};
Promise.prototype['finally'] = promiseFinally;
/**
* Promise.all为每个成员注册then
* 在所有成员变为FullFilled进入then,值为每一项resolve的值
*
*/
Promise.all = function (arr) {
// 包装成一个大的promise
return new Promise(function (resolve, reject) {
if (!isArray(arr)) {
return reject(new TypeError('Promise.all accepts an array'));
}
// resolve(args)
var args = Array.prototype.slice.call(arr);
/**
* 部分成员不是Promise也是可以的
* Promise.all([1, 2, 3, new Promise(resolve => setTimeout(() => resolve(1), 1000))]).then(result => console.error('result', result));
*/
if (args.length === 0) return resolve([]);
var remaining = args.length;
function res(i, val) {
try {
// 成员是promise
if (val && (typeof val === 'object' || typeof val === 'function')) {
var then = val.then;
if (typeof then === 'function') {
// 成员为promise时,为每个Promise成员注册then,在每个成员状态改变后调用
then.call(
val,
function (val) {
res(i, val);
},
/**
* 在最先出现的成员状态不是FullFilled后,totalPromise立即Rejected
* @test
const p1 = Promise.reject(1);
const p2 = Promise.resolve(2);
const p3 = Promise.resolve(3);
Promise.all([p1, p2, p3]).then(res => console.error(res)).catch(err => console.error(err));
*/
reject
);
return;
}
}
// 成员不是promise,就为当前值
args[i] = val;
/**
* 在最后一项的状态改变后,totalPromise才能把状态确定为FullFilled,
* 这意味着如果单个成员状态一直不确定,会导致Promoise.all创建的新Promise无法确定状态
* 所以在API请求时,Promise.all时不合理,最终耗时取决于最慢的那个接口
* @test
* const p1 = Promise.resolve(1);
const p2 = new Promise(resolve => setTimeout(() => resolve(2), 5000));
Promise.all([p1, p2]).then(res => console.error(res));
*
* @test
* const p1 = Promise.resolve(1);
const p2 = new Promise(() => {});
const p3 = Promise.resolve(3);
Promise.all([p1, p2, p3]).then(res => console.error(res)).catch(err => console.error(err));
*/
if (--remaining === 0) {
resolve(args);
}
} catch (ex) {
reject(ex);
}
}
/**
* Promise.all中的所有成员都会被执行
* @test
const p1 = Promise.reject(1);
const p2 = new Promise(resolve => setTimeout(() => {
console.error('p2');
resolve();
}, 1000));
const p3 = new Promise(resolve => setTimeout(() => {
console.error('p3');
}, 1000))
Promise.all([p1, p2]).then(res => console.error(res));
*/
for (var i = 0; i < args.length; i++) {
res(i, args[i]);
}
});
};
Promise.allSettled = allSettled;
/**
* 立即创建一个新的promise对象,区分value类型
* 类属性
* @test
* Promise.resolve(1).then(res => console.error('res->', res));
*
* @test
* Promise.resolve(Promise.reject(2)).catch(err => console.error('err->', err));
*/
Promise.resolve = function (value) {
if (value && typeof value === 'object' && value.constructor === Promise) {
return value;
}
return new Promise(function (resolve) {
resolve(value);
});
};
/**
* 立即创建一个rejected的promise对象
*
* @test
* Promise.reject(Promise.resolve(2)).catch(err => console.error('err->', err));
*/
Promise.reject = function (value) {
return new Promise(function (resolve, reject) {
reject(value);
});
};
/**
* 由第一个确定Promise状态的Promise决定最终的状态
* 每个promise都会执行
*
* @test
const p1 = Promise.resolve(1);
const p2 = Promise.reject(2);
const p3 = Promise.resolve(3);
Promise.race([p1, p2, p3]).then(res => console.error(res));
*
*/
Promise.race = function (arr) {
return new Promise(function (resolve, reject) {
if (!isArray(arr)) {
return reject(new TypeError('Promise.race accepts an array'));
}
for (var i = 0, len = arr.length; i < len; i++) {
Promise.resolve(arr[i]).then(resolve, reject);
}
});
};
// 模拟浏览器promise微任务的特点
Promise._immediateFn =
(typeof setImmediateFunc === 'function' &&
function (fn) {
setImmediateFunc(fn);
}) ||
function (fn) {
setTimeoutFunc(fn, 0);
};
Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
if (typeof console !== 'undefined' && console) {
console.warn('Possible Unhandled Promise Rejection:', err);
}
};
module.exports = Promise;
| 27.934021 | 155 | 0.611308 |
e357e00f3c50a04c80cb517a29782c4301e284b5 | 699 | js | JavaScript | shells/chrome/injector.js | wcjordan/devtool-boilerplate | df1e6a16c4d86e1171f9d90ef46a7a638aeb8599 | [
"MIT"
] | null | null | null | shells/chrome/injector.js | wcjordan/devtool-boilerplate | df1e6a16c4d86e1171f9d90ef46a7a638aeb8599 | [
"MIT"
] | null | null | null | shells/chrome/injector.js | wcjordan/devtool-boilerplate | df1e6a16c4d86e1171f9d90ef46a7a638aeb8599 | [
"MIT"
] | null | null | null | /* global chrome */
import RuntimeConnection from './RuntimeConnection';
import WindowConnection from '../../src/WindowConnection';
import wireConnections from './wireConnections';
// Inject script to run on page
const script = document.createElement('script');
script.src = chrome.runtime.getURL('injected_script.js');
document.documentElement.appendChild(script);
script.parentNode.removeChild(script);
// Setup devtools messaging connection
const connectionToDevtool = new RuntimeConnection(chrome.runtime.connect({
name: 'injector',
}));
const connectionToWebpage = new WindowConnection(WindowConnection.side.BOILERPLATE_INJECTOR);
wireConnections(connectionToDevtool, connectionToWebpage);
| 38.833333 | 93 | 0.806867 |
e357f1447b8ab47204595b8783fe3a0733b24a9d | 1,432 | js | JavaScript | web/ui-app-v2/src/redux/app/reducer.js | savitaepi/frontend | 1c4086b504b1fffc7388952c100e72b5a98fae75 | [
"MIT"
] | 1 | 2020-07-15T13:18:02.000Z | 2020-07-15T13:18:02.000Z | web/ui-app-v2/src/redux/app/reducer.js | savitaepi/frontend | 1c4086b504b1fffc7388952c100e72b5a98fae75 | [
"MIT"
] | 29 | 2020-07-16T09:39:12.000Z | 2021-02-04T08:53:48.000Z | web/ui-app-v2/src/redux/app/reducer.js | savitaepi/frontend | 1c4086b504b1fffc7388952c100e72b5a98fae75 | [
"MIT"
] | 3 | 2020-10-12T06:48:35.000Z | 2021-02-18T08:21:58.000Z | import * as actionTypes from "./actionTypes";
import { initLocalizationLabels } from "./utils";
const locale = window.localStorage.getItem("locale") || "en_IN";
const localizationLabels = initLocalizationLabels(locale);
const initialState = {
name: "Mseva",
showMenu: false,
showActionMenu:true,
showDailog: false,
route: "",
locale,
bottomNavigationIndex: 0,
previousRoute: "",
toast: {
message: "",
open: false,
error: true,
},
localizationLabels,
};
const appReducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.ADD_LOCALIZATION:
return {
...state,
locale: action.locale,
localizationLabels: action.localizationLabels,
};
case actionTypes.CHANGE_BOTTOM_NAVIGATION_INDEX:
return {
...state,
bottomNavigationIndex: action.bottomNavigationIndex,
};
case actionTypes.SET_ROUTE:
return { ...state, previousRoute: action.route ? window.location.pathname : state.previousRoute, route: action.route };
case actionTypes.SHOW_TOAST:
return {
...state,
toast: {
message: action.message,
open: action.open,
error: action.error,
},
};
case actionTypes.SET_USER_CURRENT_LOCATION:
return { ...state, currentLocation: action.currentLocation };
default:
return state;
}
};
export default appReducer;
| 26.036364 | 125 | 0.648743 |
e35a6a9c5f9f4e1e415221e7fce5862d901bafcc | 412 | js | JavaScript | index.js | Joontae-Kim/node_js__api_basic_class | 03bdf8dcedae57f4766c9c42b90dc2c001052496 | [
"MIT"
] | null | null | null | index.js | Joontae-Kim/node_js__api_basic_class | 03bdf8dcedae57f4766c9c42b90dc2c001052496 | [
"MIT"
] | null | null | null | index.js | Joontae-Kim/node_js__api_basic_class | 03bdf8dcedae57f4766c9c42b90dc2c001052496 | [
"MIT"
] | null | null | null | const express = require('express');
// const sys = require('util');
const logger = require('morgan');
const bodyParser = require('body-parser');
const app = express();
const users = require('./api/users/users');
app.use(logger('dev'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))
app.use('/users', users)
app.listen(3000, () => console.log('running'))
module.exports = app;
| 24.235294 | 50 | 0.682039 |
e35b189944982ef793c5c8a8dcf88dfdc853e26d | 7,851 | js | JavaScript | lib/route-helpers.js | flyvictor/fortune | ce7a77308ef3e14c06f1fe49bb3a1aa33a0965cc | [
"MIT"
] | 2 | 2015-01-07T19:18:21.000Z | 2015-08-13T07:37:34.000Z | lib/route-helpers.js | flyvictor/fortune | ce7a77308ef3e14c06f1fe49bb3a1aa33a0965cc | [
"MIT"
] | 29 | 2015-01-13T11:05:02.000Z | 2018-03-19T18:35:54.000Z | lib/route-helpers.js | flyvictor/fortune | ce7a77308ef3e14c06f1fe49bb3a1aa33a0965cc | [
"MIT"
] | 22 | 2015-01-04T18:14:42.000Z | 2018-02-28T09:51:58.000Z | 'use strict';
var _ = require('lodash');
exports.squash = function(type, target, source){
return _.reduce(Object.keys(source), function(memo, sourceKey){
var sourceValue = source[sourceKey];
var targetValue = target[sourceKey];
var resultValue;
switch(type){
case '$push':
if (sourceValue.$each) {
resultValue = {
$each: targetValue ? (targetValue.$each || targetValue).concat(sourceValue.$each) : sourceValue.$each
};
} else {
resultValue = sourceValue;
}
break;
case '$pullAll':
resultValue = targetValue ? targetValue.concat(sourceValue) : sourceValue;
break;
case '$set':
case '$pull':
case '$inc':
resultValue = sourceValue;
break;
default:
throw new Error('Unknown operation ' + type);
}
memo[sourceKey] = resultValue;
return memo;
}, target);
};
exports.needsPositionalUpdate = function(parts, model){
var fieldName = parts[0];
var fieldSchema = model.schema.tree[ fieldName ];
return _.isArray( fieldSchema ) &&
_.isObject( fieldSchema[ 0 ] ) &&
!_.has( fieldSchema[ 0 ], 'ref' );
};
exports.processReplaceOp = function(op, model){
var field = op.path.split('/').slice(3);
var value = _.cloneDeep(op.value);
var result = {
match: {},
separate: false,
key: '$set',
update: {}
};
var ret = [result];
if (field.length > 1 && field[0] !== "links") {
var needsPositionalUpdate = exports.needsPositionalUpdate(field, model);
if (needsPositionalUpdate && /[0-9a-f]{24}/.test(field[1])){
//happy to assume it's working one-level only for now
var subdocid = field[1];
var embeddedPath = field[0];
result.match[embeddedPath + '._id'] = subdocid;
result.separate = true;
var updatePath = [embeddedPath, '$'].concat(field.slice(2)).join('.');
result.update[updatePath] = value;
//And add an op updating the possible deleted bit
var forDeleted = {match: {}, separate: true, key: '$set', update: {}};
forDeleted.match['_internal.deleted.'+embeddedPath + '._id'] = subdocid;
forDeleted.update['_internal.deleted.'+ updatePath] = value;
ret.push(forDeleted);
}else{
//regular update to deep path
result.update[field.join(".")] = value;
}
} else {
result.update[field[field.length-1]] = value;
}
return ret;
};
exports.processAddOp = function(op, model){
var result = {
match: {},
separate: false,
key: '$push',
update: {}
};
var field = op.path.split('/').splice(3);
var tabFactor = field[field.length - 1] === "-" ? 2 : 1;
if (field.length > 1 && field[0] !== "links") {
var needsPositionalUpdate = exports.needsPositionalUpdate(field, model);
if (needsPositionalUpdate && (field.length - tabFactor) > 1){
var subdocid = field[1];
var embeddedPath = field[0];
result.match[embeddedPath + '._id'] = subdocid;
result.separate = true;
var updatePath = [embeddedPath, '$'].concat(
tabFactor === 2 ? _.initial(field, field.length - 1).slice(2) : field.slice(2)
).join('.');
result.update[updatePath] = result.update[updatePath] || {$each: []};
result.update[updatePath].$each.push(op.value);
}else{
var normalisedPath = (tabFactor === 2 ? _.initial(field, field.length - 1) : field).join('.');
result.update[normalisedPath] = result.update[normalisedPath] || {$each: []};
result.update[normalisedPath].$each.push(op.value);
}
} else{
result.update[field[field.length - tabFactor]] = result.update[field[field.length - tabFactor]] || {$each: []};
result.update[field[field.length - tabFactor]].$each.push(op.value);
}
return [result];
};
exports.processRemoveOp = function(op, model, returnedDocument){
var field = op.path.split('/').slice(3);
var value = field.pop()
, fieldName, pullKey, fieldSchema, nestedObjects;
if( field.length === 1 ){
fieldName = field[ field.length - 1 ];
}
fieldSchema = model.schema.tree[ fieldName ];
nestedObjects = _.isArray( fieldSchema ) &&
_.isObject( fieldSchema[ 0 ] ) &&
!_.has( fieldSchema[ 0 ], 'ref' );
if( nestedObjects ){
pullKey = '$pull';
}
else{
pullKey = '$pullAll';
}
var result = {
match: {},
separate: true,
key: pullKey,
update: {}
};
var ret = [result];
if (field.length > 1 && field[0] !== "links") {
result.update[field.join(".")] = result.update[field.join(".")] || [];
result.update[field.join(".")].push(value);
}
else{
if( !nestedObjects ){
result.update[field[field.length - 1]] = result.update[field[field.length - 1]] || [];
result.update[field[field.length - 1]].push(value);
}
else{
// create a $push and $pull queries for non-destructive deletes
var pullOp = result;
var pushOp = {
match: {},
separate: true,
key: '$push',
update: {}
};
ret.push(pushOp);
pullOp.update[fieldName] = pullOp.update[fieldName] || { _id: { $in: [] } };
pushOp.update[ "_internal.deleted." + fieldName ] = pushOp.update[ "_internal.deleted." + fieldName ] || {$each: []};
var pullObj = pullOp.update[ fieldName ]._id;
var pushObj = pushOp.update[ "_internal.deleted." + fieldName ];
var idsToRemove, subdocsToRemove;
subdocsToRemove = returnedDocument[ fieldName ]
.filter( function( subdoc ){
return subdoc._id.toString() === value;
})
.map( function( subdoc ){
subdoc.deletedAt = new Date();
return subdoc;
});
if( subdocsToRemove.length > 0 ){
idsToRemove = subdocsToRemove
.map( function( arg ){
if( arg._id ){
return arg._id;
}
}
);
pullObj.$in = pullObj.$in.concat( idsToRemove );
pushObj.$each = pushObj.$each.concat( subdocsToRemove );
}
}
}
return ret;
};
exports.processIncOp = function(op, model){
var field = op.path.split('/').slice(3);
var value = isNaN(parseInt(op.value)) ? 1 : parseInt(op.value);
var result = {
match: {},
separate: false,
key: '$inc',
update: {}
};
var needsPositionalUpdate = exports.needsPositionalUpdate(field, model);
if (needsPositionalUpdate){
result.separate = true;
var embeddedPath = field[0];
result.match[embeddedPath + '._id'] = field[1];
var updatePath = [embeddedPath, '$'].concat(field.slice(2)).join('.');
result.update[updatePath] = result.update[updatePath] || {};
result.update[updatePath] = value;
}else{
result.update[field.join('.')] = value;
}
return [result];
};
exports.buildPatchOperations = function(model, returnedDocument, ops){
var updates = [{
match: {},
update: {}
}];
ops.forEach(function (operation) {
var preprocessed;
switch(operation.op){
case 'replace':
preprocessed = exports.processReplaceOp(operation, model);
break;
case 'add':
preprocessed = exports.processAddOp(operation, model);
break;
case 'remove':
preprocessed = exports.processRemoveOp(operation, model, returnedDocument);
break;
case 'inc':
preprocessed = exports.processIncOp(operation, model);
}
preprocessed.forEach(function(meta){
var first = _.first(updates);
if (meta.separate) {
//split into two different update operations
first = {match: {}, update: {}};
updates.push(first);
}
_.extend(first.match, meta.match);
first.update[meta.key] = first.update[meta.key] || {};
exports.squash(meta.key, first.update[meta.key], meta.update);
});
});
return updates;
}; | 29.738636 | 123 | 0.595466 |
e35ba08c32f49e7f2ed343963c43fd3014218c77 | 27,324 | js | JavaScript | processapi/lib/process.js | its4land-new/publish-and-share | 8e344b5b78044a7ddc2a2bd0b6aa12915b88838a | [
"MIT"
] | null | null | null | processapi/lib/process.js | its4land-new/publish-and-share | 8e344b5b78044a7ddc2a2bd0b6aa12915b88838a | [
"MIT"
] | 4 | 2019-11-19T01:52:00.000Z | 2021-05-10T21:43:29.000Z | processapi/lib/process.js | its4land-new/publish-and-share | 8e344b5b78044a7ddc2a2bd0b6aa12915b88838a | [
"MIT"
] | null | null | null | 'use strict';
const dockerlib = require('../lib/docker')
const winston = require('winston');
const _ = require('lodash');
const EventEmitter = require('events');
const config = require('../settings/config');
const redis = require('redis');
const Redlock = require('redlock');
const crypto = require('crypto');
const http = require('http');
const JSONStream = require('JSONStream');
const util = require('util');
// Data structure names in redis
const procMap = "PROCESSMAP"; // Hashtable:ProcessID -> Process Object (as JSON string)
const cntnrMap = "CONTAINERMAP"; // Hashtable: ContainerID -> Process ID, for fast lookup
const waitQueue = "WAITING"; // Queue: ProcessIDs waiting to run
const runningMap = "RUNNING"; // Hashtable: ProcessIDs of running processes (Queue is not needed here)
const finishedMap = "FINISHED"; // Hashtable: ProcessIDs of finished processes
// Publish-Subscribe
const statusChannel = "STATUS_CHAN"
const publishClient = redis.createClient();
const msgFormat = winston.format.printf (log => {
let message = log.message;
if (typeof message === "object") {
message = JSON.stringify(message);
}
return `${log.timestamp} ${log.level}: ${message}`
})
const logger = winston.createLogger({
transports: [
new winston.transports.Console(),
new winston.transports.File({filename: 'logs/process_manager.log'})
],
level: 'debug',
format: winston.format.combine(winston.format.timestamp(), msgFormat)
});
/**
* Log errors and map Docker-API response error code/message to the one specified
* in the its4land processAPI
*
* TODO:
* 1. Format JSON messsages properly
*
* @method errorHandler
* @param caller {String} Name of calling function
* @return {Object}
*
*/
async function errorHandler(caller, err) {
let code = err.statusCode;
if ('errno' in err && err.errno === 'ECONNREFUSED') code = 503;
let message = "";
switch(code) {
case 304:
if ('reason' in err)
message = err.reason
else
message = "Not modified"
break;
case 400:
message = "Bad or incorrect HTTP request"
break;
case 404:
message = "No Docker image(s) found"
break;
case 409:
if (caller === 'killContainer') {
message = "Container not running"
} else {
if ('json' in err && 'message' in err.json)
message = err.json.message;
else
message = "Unknown error due to bad request"
}
break;
case 503:
message = "Docker internal error"
break;
default:
code = 500;
message = "Internal server error"
}
let newErr = {
statusCode: code,
msg: message,
origError: err
}
return newErr;
}
let redisClient = redis.createClient(config.redisCfg);
// Redis locking for simultaneous writes to shared resource
let redlock = new Redlock( [redisClient], {
driftFactor : 0.01,
retryCount: 10,
retryDelay: 200,
retryJitter: 200
});
// Respond to Redis connection events
redisClient.on('error', (err) => {
logger.error("Connection to Redis instance failed", err);
});
redisClient.on('ready', (val) => {
/* Create promisified versions of functions in the redis client library.
* By default the library uses old the callback style.
*
* To promisify a function just add it to the array candidateFunctions.
* Promisified functions are given the 'async' prefix and camelCased
*
* e.g. 'asyncHget' is the promisified version of 'hget'
*/
const candidateFunctions = ['hdel', 'hget', 'hgetall', 'hlen', 'hset', 'llen', 'lpush', 'lrem', 'rpop'];
candidateFunctions.forEach((fname) => {
let client = 'redisClient'; // variable used to reference client
let asyncFuncName = `${client}.async${fname.charAt(0).toUpperCase()}${fname.slice(1)}`
let cmd = `${asyncFuncName} = util.promisify(${client}.${fname}).bind(${client})`;
eval(cmd);
})
});
// Should be gotten rid of once database is in place
// 'tool name' : {'version' : 'docker image id', ...}
/*
let toolToImageMap = {
'WP3.1' : {
'1.0': '2f13a37dd5e6'
},
'WP3.2': {
'1.0': 'a8e0cd29a968',
'1.1': '216a1b7aadc7',
'1.2': '6e011835c7ee'
},
'WP5.1': {
'1.0': 'f0840c22031c'
}
};
*/
/**
* Create a process
*
* The process request requires the id of the tool to run and optionally its version,
* userId, comment and arguments passed to the tool. This method creates the corresponding
* container and assigns a unique SHA-1 hashvalue as the processId. The return object
* consists of the request + generated properties.
*
* NOTE: This method does not enqueue the process into the waiting queue yet
*
* @method createProcess
* @param {Object}
* @return {Object}
*/
module.exports.createProcess = async function(body){
try {
let toolImageId = body.toolImageId;
let version = body.version;
let userId = body.userId
//let imageId = body. toolImageId; //toolToImageMap[toolName][version];
let containerRequest = {
"id": toolImageId
};
let optionalArgs = ["args", "env", "dockerParams"];
for (let arg of optionalArgs) {
if (Object.keys(body).includes(arg)) {
containerRequest[arg] = body[arg];
}
}
let containerId = await dockerlib.createContainer(containerRequest);
containerId = containerId.id;
let processId;
if ('processId' in body) {
processId = body.processId;
} else {
let uniqStr = `${toolImageId}/${version}/${userId}/${Date.now()}`;
let salt = 'platform.its4land.com'
processId = crypto.createHmac('sha1', salt).update(uniqStr).digest('hex');
}
let processObj = body;
processObj.id = processId
processObj.containerId = containerId;
processObj.status = 'CREATED';
processObj.timestampCreated = Date.now();
processEvent.emit('process-created', processObj)
return processObj;
} catch (error) {
let handledErr = await errorHandler('createProcess', error);
throw(handledErr);
}
}
/**
* Add process to a waiting queue in Redis
*
* @method enqueueProcess
* @param {String} pid Process Id
* @return {Object}
*/
module.exports.enqueueProcess = async function(pid) {
try {
setProcessProperty(pid, 'status', 'WAITING');
let retVal = await redisClient.asyncLpush(waitQueue, pid);
let length = -1;
if (retVal) {
length = await redisClient.asyncLlen(waitQueue);
}
processEvent.emit('process-enqueued', pid, retVal);
let result = {
position: length - 1,
waitQueueLength: length
}
return result;
} catch (err) {
throw(err);
}
}
/**
* Remove process from waiting queue in Redis in a FIFO order
*
* @method enqueueProcess
* @param {Boolean} throwQueueingErr Throw error if queue is full. If false, return err as response
* @return {Object}
*/
module.exports.dequeueProcess = async function (throwQueueingErr=true) {
try {
let len = await redisClient.asyncHlen(runningMap);
let err = {};
let errQueueEmpty = {
statusCode: 500,
message: `Could not Dequeue. Possibly empty wait queue`
};
let errQueueFull = {
statusCode: 503,
message: `Run queue full `
}
// Dequeue only if no. of running processes is below limit
if (len < config.executionPolicy.maxConcurrentTasks) {
let waitQLen = await redisClient.asyncLlen(waitQueue);
// Queue exists and has waiting processes
if (waitQLen && waitQLen > 0) {
// Remove processes from wait queue and execute them
//let pid = await redisClient.asyncRpop(waitQueue);
let pid = await getPidOfWaitingProcess();
processEvent.emit('process-dequeued', pid);
let result = await executeProcess(pid);
processEvent.emit('process-started', pid);
result.statusCode = 200;
return result;
} else {
err = errQueueEmpty;
}
} else {
let waitQLen = await redisClient.asyncLlen(waitQueue);
if (waitQLen) {
err = errQueueFull;
err.message = `Run queue full (Number of waiting tasks = ${waitQLen}; Max concurrent tasks = ${config.executionPolicy.maxConcurrentTasks}) `;
} else {
err = errQueueEmpty;
}
}
// Throw error or return it as response depending on flasg
if (throwQueueingErr) {
throw(err);
} else {
return err;
}
} catch (err) {
if ( _(err).get('origError.reason') === "no such container") {
// Docker daemon could not find dequeued container. Possibly removed externally
// In this case continue with dequeueing
exports.dequeueProcess();
} else {
throw (err);
}
}
}
/**
* Stop a running/waiting process
*
* If the process is waiting, remove it from the waiting queue.
* If the process is running, stop the container. Set state to ABORTED in
* both these cases
*
* @method stopProcess
* @param {String} pid Process Id
* @return {Object}
*/
module.exports.stopProcess = async function(pid) {
try {
let info = await exports.getProcessInfo(pid);
switch (info.status) {
case 'FINISHED':
case 'ABORTED':
// If process already finished running, there's nothing to do
logger.debug(`Process '${pid}' already stopped`);
break;
case 'WAITING':
// If process is waiting, remove it from the wait queue
let numRemovedInstances = await redisClient.asyncLrem(waitQueue, 0, pid);
if (numRemovedInstances > 0) {
logger.debug(`Removed process from wait queue - ${pid}`)
// Also remove it from container map and change its status
redisClient.asyncHdel(cntnrMap, info.containerId);
setProcessProperty(pid, 'status', 'ABORTED');
}
break;
case 'RUNNING':
// If process is currently running, stop the container
logger.info(`Stopping running process - ${pid}`);
let containerInfo = await dockerlib.stopContainer(info.containerId);
logger.debug(`Attempting to stop container - ${info.containerId}`);
// Reread info. The state is changed in the 'container-killed' event handler
if (containerInfo)
info = await exports.getProcessInfo(pid);
break;
}
return info;
} catch(err) {
throw(err);
}
}
/**
* Return information about a process
*
* Comma separated fields can be passed as a string to choose what information
* to return. E.g. "containerId,status,timeStarted"
*
* @method getProcessInfo
* @param {String} pid Process Id
* @param {String} fields comma separated fields to include in return value
* @return {Object}
*/
module.exports.getProcessInfo = async function(pid, fields) {
try {
let pStr = await redisClient.asyncHget(procMap, pid);
if (pStr === null) {
let err = {
statusCode: 400,
message: `No such process with id - ${pid}`
}
throw (err);
}
let pObj = JSON.parse(pStr);
let output = {};
// Filter which fields to add to response
if (fields) {
let fArr = fields.split(",");
fArr.forEach(element => {
let elem = element.trim();
if (pObj[element]) {
output[element] = pObj[element];
}
});
} else {
output = pObj;
}
return output;
} catch (err) {
throw(err);
}
}
/**
* Get information about all processes currently tracked in Redis Hashmap
*
* NOTE: Implementation uses Lodash functionality for filtering/sorting
*
* @method getAllProcessInfo
* @param {String} status Process state filter - RUNNING/WAITING/FINISHED/ABORTED
* @param {String} fields comma separated fields to include in return value
* @param {String} sortBy sort results according to given field
* @param {String} sortOrder sorting order for above field - asc(default)/desc
*/
module.exports.getAllProcessInfo = async function(status, fields, sortBy, sortOrder) {
try {
let allProcesses = await redisClient.asyncHgetall(procMap);
let pObj = allProcesses;
// Convert JSON Object to Array of Process Objects
let result = _.values(pObj).map((elem) => {return JSON.parse(elem)});
// Filter by status
if (status) {
result = _.filter(result, (proc) => {return status === proc.status});
}
// If result is empty at this point, there's no need to process further
if (result.length == 0) {
return result;
}
// First sort by given field
if (sortBy) {
// Determine sort order
if (sortOrder) {
if (sortOrder !== 'asc' && sortOrder !== 'desc') {
let err = {
statusCode: 400,
message: `Invalid sortOrder in request: '${sortOrder}'. Should be either 'asc' or 'desc'`
};
throw (err);
}
} else {
sortOrder = 'asc'; // default sort order
}
// Check if field exists in returned objects
if ( (sortBy in _.sample(result)) === false) {
let err = {
statusCode: 400,
message: `Invalid sortBy field in request: '${sortBy}'`
};
throw(err);
}
result = _.orderBy(result, (obj) => { return obj[sortBy] }, sortOrder);
}
// Select fields to return
if (fields) {
// Convert comma separated string to array of strings
let fieldsArr = _(fields.split(',')).map(e => {return e.trim()}).value();
// Pick fields to return
result = _.map(result, (e) => {return _.pick(e, fieldsArr)});
}
return result;
} catch (err) {
throw(err);
}
}
/**
* Create, Enqueue and Dequeue process, in one shot.
*
* @param {Object} procRequestBody New Process request body
*/
module.exports.runProcessPost = async function(procRequestBody) {
try {
let response = {};
response.statusCode = 500;
// 1. Create Process
let procObj = await exports.createProcess(procRequestBody);
let procId = procObj.id;
response.createResponse = procObj; // response for container creation
response.statusCode = 202;
// 2. Enqueue Process
let enqResult = await exports.enqueueProcess(procId);
response.enqueueResponse = enqResult;
if (enqResult) {
// 3. Dequeue process - set throwQueueingErr flag to false
let deqResult = await exports.dequeueProcess(false);
response.dequeueResponse = deqResult;
if (Object.keys(deqResult).includes('statusCode')) { //indicates error
switch (deqResult.statusCode) {
case 503: // queue is full, but process might eventually run
response.statusCode = 202;
}
} else {
response.statusCode = 201;
}
} else {
let err = {
statusCode: 500,
message: `Unable to enqueue process with ID - ${procId}`
}
throw(err);
}
return response;
} catch (err) {
throw(err);
}
};
/**
* Execute a process
*
* Extract and parse the process object encoded as a JSON string in Redis PROCESSMAP hashtable
* and start the container associated with the process
*
* @method executeProcess
* @param {string} pid Id of process to execute
* @return {Object} return id and containerId of started process
*
*/
async function executeProcess(pid) {
try {
let pStr = await redisClient.asyncHget(procMap, pid); // JSON string of process object
let pObj = JSON.parse(pStr);
// Start container
logger.debug(`Executing container with id: "${pObj.containerId}"`);
let containerInfo = await dockerlib.startContainer(pObj.containerId);
let result = {
'processId': pid,
'containerInfo': containerInfo
}
return result;
} catch (err) {
err.processId = pid;
throw(err);
}
}
/**
* Set the value of a process' property
*
* The Process object is stored in a Redis Hashmap as a JSON string. This method parses
* the JSON string as an object, sets/modifies the given property and writes it
* back as a JSON string.
*
* Since the process can be invoked concurrently by different methods, we need to use
* locks to avoid race conditions.
*
* @method setProcessProperty
* @param {String} pid Process Id
* @param {String} property Property to change
* @param {String} value Value of property
*/
async function setProcessProperty(pid, property, value) {
// A unique id for the resource we want to lock
let resource = `lock:process:${pid}`;
// the maximum amount of time you want the resource locked,
let ttl = 100;
try {
let lock = await redlock.lock(resource, ttl);
let pStr = await redisClient.asyncHget(procMap, pid);
let pObj = JSON.parse(pStr);
pObj[property] = value;
await redisClient.asyncHset(procMap, pid, JSON.stringify(pObj));
lock.unlock();
return pObj;
} catch (err) {
throw (err);
}
}
/**
* Get container events by monitoring Docker event stream using docker internal API
*/
let dockerAPIurl = `${config.dockerCfg.protocol}`
+ `://${config.dockerCfg.host}:${config.dockerCfg.port}`
+ `/${config.dockerCfg.version}`
+ '/events';
http.get(dockerAPIurl, function(res) {
// Events are streamed as concatenated JSON i.e. a response can
// contain more than one JSON object. Hence we use JSONStream
// to parse it
let stream = JSONStream.parse();
res.setEncoding('utf8');
res.pipe(stream);
// Monitor Docker events
stream.on('data', (event) => {
if (event.Type == "container") {
// logger.debug(`Docker Container Event - Type:${event.Type} Action:${event.Action}`);
let cid = event.id;
redisClient.hget(cntnrMap, cid, (err, pid) => {
if (err) throw err;
// Create container event only if the container is present in the map
if (pid) {
switch(event.status) {
case 'create': // Container created
logger.debug(`(event) container-created: ${event.id}`);
break;
case 'die': // Container finished running
processEvent.emit('container-died', event, pid);
break;
case 'start': // Container started running
processEvent.emit('container-started', event, pid);
break;
case 'kill': // Container forcibly killed
processEvent.emit('container-killed', event, pid);
break;
case 'destroy': // Container removed
processEvent.emit('container-destroyed', event, pid);
break;
}
}
});
}
});
});
/**
* Event handlers for process management
*/
class ProcEventHandler extends EventEmitter {}
const processEvent = new ProcEventHandler();
processEvent.on('process-created', handleProcessCreated);
processEvent.on('process-enqueued', handleProcessEnqueued);
processEvent.on('process-dequeued', handleProcessDequeued);
processEvent.on('process-started', handleProcessStarted);
processEvent.on('process-terminated', handleProcessTerminated);
processEvent.on('container-died', handleContainerDied);
processEvent.on('container-started', handleContainerStarted);
processEvent.on('container-killed', handleContainerKilled);
processEvent.on('container-destroyed', handleContainerDestroyed);
function handleProcessCreated(pObj){
let pid = pObj.id;
let state = 'CREATED';
// Add process to hash of processes maintained on Redis
redisClient.hset(procMap, pid, JSON.stringify(pObj));
// Add an inverse map from containerID to process Id
redisClient.hset(cntnrMap, pObj.containerId, pid);
publishState(pid, state);
}
function handleProcessEnqueued(pid, len){
publishState(pid, 'WAITING');
}
function handleProcessDequeued(pid){
publishState(pid, 'DEQUEUED');
}
function handleProcessStarted(pid){
setProcessProperty(pid, 'timestampStarted', Date.now());
publishState(pid, 'RUNNING');
}
/**
* Handle termination of a process. A process can either terminate normally (state=FINISHED) or
* may be terminated forcibly (state=ABORTED).
*
* @param {String} pid id of proces
* @param {String} state state of termination FINISHED|ABORTED
*/
function handleProcessTerminated(pid, state){
// Remove process id from Running Map
redisClient.hdel(runningMap, pid);
// Add process id to Hashmap of finished processes
redisClient.hset(finishedMap, pid, state);
// Set process state
setProcessProperty(pid, 'status', state);
setProcessProperty(pid, 'timestampFinished', Date.now());
// publish message
publishState(pid, state);
// Start next process in queue
exports.dequeueProcess(false)
.then((data) => {
let statusCode = _(data).get('statusCode');
switch (statusCode) {
case 200:
logger.debug(`Auto-dequeue successful. DQ'd process had id ${data.processId}`);
break;
case 500:
logger.debug(`Auto-dequeue: Queue is empty!`);
break;
}
})
.catch ((err) => {
logger.error("Error when auto-dequeueing on process terminated signal");
logger.error(err);
// Handle case when process terminates before container even starts
if ( _(err).get("origError.statusCode") == 500 && _(err).has('processId')) {
let errPid = err.processId;
logger.error(`Process ${errPid} terminated before container started`);
// Remove created (but not started) container
processEvent.emit('process-terminated', errPid, state);
}
});
}
function handleContainerStarted(event, pid) {
logger.debug(`(event) container-started: ${event.id}`);
// First set process status to RUNNING in process map
let state = 'RUNNING';
setProcessProperty(pid, 'status', state);
// Add process id to Running Map
redisClient.hset(runningMap, pid, true);
}
async function handleContainerDied(event, pid) {
let cid = event.id;
logger.debug(`(event) container-died: ${cid}`);
let state = 'FINISHED';
let wasAborted = await redisClient.asyncHget(finishedMap, pid);
if (!wasAborted) { // i.e. container was not killed before
cleanupAfterContainer(cid, pid, state);
}
// Remove container - can't always assume that container will be removed
//dockerlib.removeContainer(cid)
//.then((id) => { logger.debug(`Removed container: ${id}`)})
}
async function handleContainerKilled(event, pid) {
let cid = event.id;
logger.debug(`(event) container-killed: ${cid}`);
let state = 'ABORTED';
cleanupAfterContainer(cid, pid, state);
//processEvent.emit('process-terminated', pid, state);
// Remove container id from container map
// redisClient.hdel(cntnrMap, cid);
// Add process id to Hashmap of finished processes
//await redisClient.hset(finishedMap, pid, state);
// redisClient.hset(finishedMap, pid, true);
}
async function handleContainerDestroyed(event, pid) {
let cid = event.id;
logger.debug(`(event) container-destroyed: ${cid}`);
redisClient.hget(cntnrMap, cid, (err, pid) => {
// If a container is removed before it starts:
// 1. remove corresponding process from the wait queue
// 2. remove container from container map
// 3. set corresponding process state to ABORTED
if (err) throw(err);
redisClient.lrem(waitQueue, 0, pid);
// Remove container id from container map
redisClient.hdel(cntnrMap, cid);
processEvent.emit('process-terminated', pid, 'ABORTED');
});
}
function cleanupAfterContainer(cid, pid, state) {
let delay = 3000; // wait this long for Docker daemon to disconnect networks etc.
// Remove container id from container map
redisClient.hdel(cntnrMap, cid);
setTimeout(() => {
processEvent.emit('process-terminated', pid, state);
}, delay);
}
/**
* Publish process state onto redis channel
*
* @param {String} pid Process ID
* @param {String} state Process runtime status
*/
function publishState(pid, state) {
let message = `${pid}:${state}`;
logger.info(`(event) Process ${message}`);
publishClient.publish(statusChannel, message);
}
/**
* Examine Redis WAITING queue to get pid of waiting process
*/
async function getPidOfWaitingProcess() {
try {
let waitQLen = await redisClient.asyncLlen(waitQueue);
if (waitQLen > 0) {
let pid = await redisClient.asyncRpop(waitQueue);
let pStr = await redisClient.asyncHget(procMap, pid); // JSON string of process object
let pObj = JSON.parse(pStr);
let cid = pObj.containerId;
let info = await dockerlib.getContainerInfo(cid);
if (info) {
return pid;
}
}
return null; // should not happen
} catch(err) {
logger.error(`Error getting PID of waiting process`);
logger.error(err);
if (_(err).get('reason') === "no such container") {
setProcessProperty(pid, 'status', state);
// Container of dequeued process not available
getPidOfWaitingProcess();
}
}
} | 33.567568 | 157 | 0.589994 |
e35c0f803cb8a5cd81524c338a86fdef01d1c620 | 1,019 | js | JavaScript | webpack.mix.js | nandomoreirame/wp-docker | d4b6cdc9bf32bb6fcbbd84932409415dbf812cb9 | [
"MIT"
] | 14 | 2017-03-06T13:46:03.000Z | 2017-09-20T22:14:43.000Z | webpack.mix.js | nandomoreirame/docker-wordpress | d4b6cdc9bf32bb6fcbbd84932409415dbf812cb9 | [
"MIT"
] | 1 | 2017-10-15T16:41:00.000Z | 2017-10-15T16:41:00.000Z | webpack.mix.js | onedevstudio/dockering | d4b6cdc9bf32bb6fcbbd84932409415dbf812cb9 | [
"MIT"
] | null | null | null | const mix = require('laravel-mix')
const pkg = require('./package.json')
const { join } = require('path')
const path = {
resources: join(__dirname, 'src'),
assets: join(__dirname, 'src', 'assets'),
theme: join(__dirname, 'src', 'wordpress', 'wp-content', 'themes', pkg.name)
}
mix.setPublicPath('./')
.js([ join(path.assets, 'scripts/app.js') ], join(path.theme, 'assets', 'scripts/bundle.js'))
.extract(['vue', 'jquery', 'bootstrap'])
.sass(join(path.assets, 'sass/app.scss'), join(path.theme, 'assets', 'stylesheets/bundle.css'))
.options({
extractVueStyles: true,
processCssUrls: true,
uglify: {},
purifyCss: false,
postCss: [require('autoprefixer')],
clearConsole: false
})
.sourceMaps()
.disableNotifications()
.autoload({
'jquery': ['$', 'window.jQuery', 'jQuery'],
'vue': ['Vue', 'window.Vue']
})
.webpackConfig({
resolve: {
alias: {
'~': join(__dirname, 'node_modules'),
'@': join(path.assets, 'scripts'),
}
}
})
| 27.540541 | 97 | 0.600589 |
e35c1fa3dddfd02a7138e55fed738566ed2a886b | 4,523 | js | JavaScript | src/components/ShowMediaModal/index.js | RafaellaJunqueira/2021.2-Cartografia-social-front | 733a70261f8dba09993fcfd2698b93e875beabd6 | [
"MIT"
] | 2 | 2022-03-29T00:52:25.000Z | 2022-03-29T16:08:28.000Z | src/components/ShowMediaModal/index.js | RafaellaJunqueira/2021.2-Cartografia-social-front | 733a70261f8dba09993fcfd2698b93e875beabd6 | [
"MIT"
] | 77 | 2021-09-01T23:13:35.000Z | 2022-03-12T07:31:28.000Z | src/components/ShowMediaModal/index.js | fga-eps-mds/2021.1-Cartografia-social-front | b62cb61c17405e56cd9e5447d20fa7ef3d71cd9a | [
"MIT"
] | 1 | 2022-03-30T13:08:22.000Z | 2022-03-30T13:08:22.000Z | /* eslint-disable react/prop-types */
import React, {useState} from 'react';
import PropTypes from 'prop-types';
import theme from 'theme/theme';
import normalize from 'react-native-normalize';
import AudioRecorderPlayer from 'react-native-audio-recorder-player';
import Pdf from 'react-native-pdf';
import VideoPlayer from 'react-native-video-controls';
import {
Container,
Header,
OptionsButton,
Icon,
Text,
Media,
Audio,
AudioContainer,
Document,
} from './styles';
import Btn from '../UI/Btn';
let audioRecorderPlayer = new AudioRecorderPlayer();
const ShowMediaModal = ({media, closeModal}) => {
const [startPlay, setStartPlay] = useState(false);
const [recordPlayMinTime, setRecordPlayMinTime] = useState('00');
const [recordPlaySecTime, setRecordPlaySecTime] = useState('00');
const getTime = (time) => {
if (time) {
return new Date(time).toISOString().slice(11, -1);
}
return '';
};
const getTitle = () => {
if (media.type === 'audio/mpeg') {
return 'Áudio';
}
return 'Documento';
};
const onStartPlay = async (path) => {
// function to play an audio after recording it.
setStartPlay(true);
await audioRecorderPlayer.startPlayer(path);
audioRecorderPlayer.addPlayBackListener((e) => {
if (e.currentPosition === e.duration) {
audioRecorderPlayer.stopPlayer();
setStartPlay(false);
}
const time = audioRecorderPlayer
.mmssss(Math.floor(e.currentPosition))
.split(':');
setRecordPlayMinTime(time[0]);
setRecordPlaySecTime(time[1]);
});
};
const onPausePlay = async () => {
// function to pause an audio
await audioRecorderPlayer.pausePlayer();
setStartPlay(false);
};
const onStopPlay = async () => {
// function to pause an audio
await audioRecorderPlayer.stopPlayer();
setStartPlay(false);
};
const handleCloseModal = () => {
onStopPlay();
audioRecorderPlayer = new AudioRecorderPlayer();
closeModal();
};
const displayDocument = (uri) => {
return (
<Document>
<Pdf
source={{uri}}
page={0}
style={{
backgroundColor: '#000',
flex: 1,
height: '100%',
width: '100%',
}}
/>
</Document>
);
};
const displayAudio = (durationTime, uri) => {
return (
<Audio>
<AudioContainer>
<Icon size={25} name="clock" />
<Text
marginLeft={10}
fontWeight="bold"
fontSize={theme.font.sizes.SM}
mb={2}>
{`00:${recordPlayMinTime}:${recordPlaySecTime} / ${durationTime}`}
</Text>
</AudioContainer>
<Btn
title=""
icon={startPlay ? 'pause' : 'play-arrow'}
size={normalize(25)}
background="#FFF"
style={{width: '25%', alignItems: 'center', marginTop: normalize(20)}}
color={theme.colors.primary}
onPress={() => {
if (!startPlay) {
onStartPlay(uri);
} else {
onPausePlay();
}
}}
/>
</Audio>
);
};
const MediaContainer = (duration, path) => {
if (media.type === 'audio/mpeg') {
return displayAudio(duration, path);
}
return displayDocument(path);
};
return (
<Container>
{media.type === 'video/mp4' ||
(media.uri && media.uri.includes('.mp4')) ? (
<VideoPlayer
source={{uri: media.uri}}
showOnStart={false}
onBack={closeModal}
paused
/>
) : (
<>
<Header>
<Text fontSize={theme.font.sizes.ML}>{getTitle()}</Text>
</Header>
<Media>
{MediaContainer(getTime(media.duration).split('.')[0], media.uri)}
</Media>
<OptionsButton onPress={handleCloseModal}>
<Btn
title="Fechar"
background="#FFF"
style={{borderWidth: 0.5}}
color={theme.colors.primary}
onPress={handleCloseModal}
/>
</OptionsButton>
</>
)}
</Container>
);
};
ShowMediaModal.propTypes = {
media: PropTypes.shape({
type: PropTypes.string,
uri: PropTypes.string,
duration: PropTypes.number,
}),
closeModal: PropTypes.func,
};
ShowMediaModal.defaultProps = {
media: {},
closeModal: () => null,
};
export default ShowMediaModal;
| 24.715847 | 80 | 0.556268 |
e35c655e6388842ca8baa0aecf7782e709a1dfcf | 2,379 | js | JavaScript | server/routes/organization-providers.js | nadavtal/3dbia | 0db974febc8620952bc80ac01f8828121572fad0 | [
"MIT"
] | null | null | null | server/routes/organization-providers.js | nadavtal/3dbia | 0db974febc8620952bc80ac01f8828121572fad0 | [
"MIT"
] | 3 | 2020-04-06T10:16:16.000Z | 2020-05-26T12:01:25.000Z | server/routes/organization-providers.js | nadavtal/3dbia | 0db974febc8620952bc80ac01f8828121572fad0 | [
"MIT"
] | null | null | null |
var express = require('express');
var app = module.exports = express();
const connection = require('../db.js');
const jwt = require('jsonwebtoken');
const config = require('../config.js')
app.get("/organization-providers", function(req, res){
console.log('getting all organization-providers');
var q = `SELECT * FROM tbl_organization_providers`;
// console.log(q)
connection.query(q, function (error, results) {
if (error) res.send(error) ;
res.send(results);
});
});
app.post("/organization-providers", function(req, res){
console.log('creating organization-providers', req.body);
const orgProvider = req.body
var q = `INSERT INTO tbl_organization_providers ( organization_id, provider_id, remarks, date_created, status, provider_code)
VALUES (${orgProvider.organization_id}, ${orgProvider.provider_id}, '${orgProvider.remarks}', now() , '${orgProvider.status}', '${orgProvider.provider_code}')`;
// console.log(q)
connection.query(q, function (error, results) {
if (error) res.send(error) ;
res.send(results);
});
});
app.post("/organization-providers/confirmation", function(req, res){
console.log('confirming organization user', req.body)
const decoded = jwt.verify(req.body.token, config.secret)
console.log(decoded)
var q = `UPDATE tbl_organizations_users
SET confirmation_token = '',
status = 'confirmed'
WHERE confirmation_token = '${decoded.email}';`
// connection.query(q, function (error, results) {
// if (error) throw error;
// res.send(results);
// });
});
app.put("/organization-providers", function(req, res){
console.log('updating organization-providers', req.body);
const orgProv = req.body
const token = jwt.sign({
user_id: req.body.user_id,
organization_id: req.body.organization_id,
role_id: req.body.role_id
}, config.secret);
var q = `UPDATE tbl_organization_providers
SET organization_id = ${orgProv.organization_id},
provider_id = ${orgProv.provider_id},
remarks = '${orgProv.remarks}',
status = '${orgProv.new_status}',
confirmation_token = '${token}',
provider_code = '${orgProv.provider_code}'
where organization_id = ${orgProv.organization_id} and provider_id = ${orgProv.provider_id};`
console.log(q)
connection.query(q, function (error, results) {
if (error) res.send(error) ;
res.send({results, token});
});
});
| 31.302632 | 162 | 0.693569 |
e35ee3aed59d8f6c4c5e52989b1e1740523ad86a | 713 | js | JavaScript | db.js | dammybakare/bitpay | 2c07db0e20a67adf16aa0270c6d71385c4843923 | [
"MIT"
] | null | null | null | db.js | dammybakare/bitpay | 2c07db0e20a67adf16aa0270c6d71385c4843923 | [
"MIT"
] | null | null | null | db.js | dammybakare/bitpay | 2c07db0e20a67adf16aa0270c6d71385c4843923 | [
"MIT"
] | null | null | null | const mongoose = require('mongoose');
const conn = mongoose.createConnection('localhost', 'mydatabase');
conn.once('open', function() {
console.log('Connection Successful');
});
//conn.open('localhost', 'database')
var User;
const DB = {
initDb: function initDb() {
var userSchema = new mongoose.Schema({
name: String,
account: String
});
User = conn.model('User', userSchema);
},
search: function(str, callback) {
return User.find(str, callback);
},
save: function(params){
const user = new User({name: params.name, account: params.account});
user.save(function(err){
if(err) throw err;
});
}
}
module.exports.UserDb = DB;
| 25.464286 | 73 | 0.617111 |
e35f2802de4b41d9656c27d5ccfb448330d9d5b4 | 209 | js | JavaScript | test/hotCases/worker/move-between-runtime/workerB.js | fourstash/webpack | f07a3b82327f4f7894500595f6619c7880eb31a7 | [
"MIT"
] | 66,493 | 2015-01-01T02:28:31.000Z | 2022-03-31T23:46:51.000Z | test/hotCases/worker/move-between-runtime/workerB.js | fourstash/webpack | f07a3b82327f4f7894500595f6619c7880eb31a7 | [
"MIT"
] | 14,141 | 2015-01-01T21:00:12.000Z | 2022-03-31T23:59:55.000Z | test/hotCases/worker/move-between-runtime/workerB.js | fourstash/webpack | f07a3b82327f4f7894500595f6619c7880eb31a7 | [
"MIT"
] | 11,585 | 2015-01-01T02:28:31.000Z | 2022-03-31T19:47:10.000Z | import worker from "./worker";
import "./moduleB";
worker(() => import(/* webpackChunkName: "shared" */ "./moduleBs"));
import.meta.webpackHot.accept("./moduleB");
import.meta.webpackHot.accept("./moduleBs");
| 34.833333 | 68 | 0.688995 |
e35f4582d054436bbe1744e19b27a2d0301a5a01 | 4,809 | js | JavaScript | Web Development/Basic/Form Validation/formValidation.js | ayushi1210/Project-Guidance | 31d227ab70756a9afabce41ce577bd8cec1d264b | [
"MIT"
] | 1 | 2022-03-03T12:50:58.000Z | 2022-03-03T12:50:58.000Z | Web Development/Basic/Form Validation/formValidation.js | srinjoy-26/Project-Guidance | 504f37e8f7566db2d1bca873df7dd1fff5368497 | [
"MIT"
] | null | null | null | Web Development/Basic/Form Validation/formValidation.js | srinjoy-26/Project-Guidance | 504f37e8f7566db2d1bca873df7dd1fff5368497 | [
"MIT"
] | null | null | null | const firstN = document.getElementById("fname");
const lastN = document.getElementById("lname")
const phone = document.getElementById("contact");
const email = document.getElementById("email");
const userID = document.getElementById("username");
const password = document.getElementById("pswrd");
const confirm_password = document.getElementById("confirm_pswrd");
//VALIDATION WHILE TYPING IN THE INPUT FIELD
//phone number validation
function ValidPhoneNumber() {
var PhoneNo = /^\d{10}$/;
if (phone.value == "") {
document.getElementById("phone_message").style.color = "red";
document.getElementById("phone_message").innerHTML = "❌ Contact Number field cannot be blank.";
}
else if (phone.value.match(PhoneNo)) {
document.getElementById("phone_message").style.color = "green";
document.getElementById("phone_message").innerHTML = "✔ Valid Contact Number.";
}
else {
document.getElementById("phone_message").style.color = "red";
document.getElementById("phone_message").innerHTML = "❌ Contact Number should have 10 digits";
}
}
//email ID validation
function ValidEmail() {
var emailVal = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (email.value == ""){
document.getElementById("email_message").style.color = "red";
document.getElementById("email_message").innerHTML = "❌ Email Id field cannot be blank.";
}
else if (email.value.match(emailVal)) {
document.getElementById("email_message").style.color = "green";
document.getElementById("email_message").innerHTML = "✔ Valid Email Id";
}
else {
document.getElementById("email_message").style.color = "red";
document.getElementById("email_message").innerHTML = "❌ Email Id format is incorrect.";
}
}
//username validation
function ValidUsername() {
if (userID.value == "") {
document.getElementById("userid_message").style.color = "red";
document.getElementById("userid_message").innerHTML = "❌ Username field cannot be blank.";
}
else if (userID.value.length < 6){
document.getElementById("userid_message").style.color = "red";
document.getElementById("userid_message").innerHTML = "❌ Username must be aleast 6 characters long.";
}
else {
document.getElementById("userid_message").style.color = "green";
document.getElementById("userid_message").innerHTML = "✔ Valid Username";
}
}
//password validation against constraints
function ValidPassword() {
if (password.value == ""){
document.getElementById("pswrd_message").style.color = "red";
document.getElementById("pswrd_message").innerHTML = "❌ Password field cannot be blank.";
}
else if (password.value.match(/[a-z]/g) && password.value.match(/[A-Z]/g) && password.value.match(/[0-9]/g) && password.value.match(/[^a-zA-Z\d]/g) && password.value.length >= 8 && password.value.length <= 20) {
document.getElementById("pswrd_message").style.color = "green";
document.getElementById("pswrd_message").innerHTML = "✔ Password match the format."
}
else {
document.getElementById("pswrd_message").style.color = "red";
document.getElementById("pswrd_message").innerHTML = "❌ Password does not match the format."
}
}
//password and retype-password validation
function matchPassword() {
if (confirm_password.value == "") {
document.getElementById("retype_message").style.color = "red";
document.getElementById("retype_message").innerHTML = "❌ Re-type password field cannot be blank.";
}
else if (confirm_password.value != "" && password.value != confirm_password.value) {
document.getElementById("retype_message").style.color = "red";
document.getElementById("retype_message").innerHTML = "❌ Re-type passowrd does not matches the above password.";
}
else {
document.getElementById("retype_message").style.color = "green";
document.getElementById("retype_message").innerHTML = "✔ Passwords are matching.";
}
}
//VALIDATION AFTER CLICKING THE SUBMIT BUTTON (for fields empty)
//form submitted only after all the fields are filled.
function ValidateForm() {
if(firstN.value == "" || lastN.value == "" || email.value == "" || phone.value == "" || userID.value == "" || password.value =="" || confirm_password.value == "") {
alert("Registration form fields cannot be blank. \nKindly fill all the form fields!");
}
else {
document.getElementById("form_id").submit(); //form submission
alert("Registered Successfully...... \n\nCourses For ALL welcomes " + firstN.value + " " + lastN.value );
}
} | 47.147059 | 215 | 0.657933 |
e361f97a8e6055ce8e260b94bc3bfa2c8acf35ed | 61 | js | JavaScript | test/resources/composition/dsi/setups/index.js | atomservicesjs/atomservicessetup | d3d635022007e2967d63bfebe2dfaf8b21b9731e | [
"MIT"
] | 2 | 2018-01-24T05:02:34.000Z | 2018-01-29T21:39:12.000Z | test/resources/composition/dsi/setups/index.js | atomservicesjs/atomservicessetup | d3d635022007e2967d63bfebe2dfaf8b21b9731e | [
"MIT"
] | 24 | 2017-12-28T12:46:57.000Z | 2018-03-16T15:56:12.000Z | test/resources/composition/dsi/setups/index.js | atomservicesjs/atomservicessetup | d3d635022007e2967d63bfebe2dfaf8b21b9731e | [
"MIT"
] | null | null | null | module.exports = [
{ type: 'file', module: './setup' },
];
| 15.25 | 38 | 0.52459 |
e36227923a638345928d0f55ecea1f0a5a2828f3 | 57 | js | JavaScript | node_modules/@equilab/definitions/index.js | sbnair/PolkaJS | ee99d8a4611ba0217d3c4a7c738ca26b13add0ca | [
"Apache-2.0"
] | null | null | null | node_modules/@equilab/definitions/index.js | sbnair/PolkaJS | ee99d8a4611ba0217d3c4a7c738ca26b13add0ca | [
"Apache-2.0"
] | null | null | null | node_modules/@equilab/definitions/index.js | sbnair/PolkaJS | ee99d8a4611ba0217d3c4a7c738ca26b13add0ca | [
"Apache-2.0"
] | null | null | null | module.exports = {
latest: require("./latest.json")
};
| 14.25 | 34 | 0.631579 |
e3638a879e9bf4a5a36e8c6ef2bdc736d0973aae | 450 | js | JavaScript | client/src/components/layout/Layout.js | rober95/devscenter | e6bc37f69124b53daab685c0149412fa5ed08950 | [
"MIT"
] | null | null | null | client/src/components/layout/Layout.js | rober95/devscenter | e6bc37f69124b53daab685c0149412fa5ed08950 | [
"MIT"
] | null | null | null | client/src/components/layout/Layout.js | rober95/devscenter | e6bc37f69124b53daab685c0149412fa5ed08950 | [
"MIT"
] | null | null | null | import React from 'react';
import { withRouter } from 'react-router-dom';
import Navbar from './Navbar';
import Footer from './Footer';
const Layout = props => (
<>
<Navbar />
{props.location.pathname === '/' ? (
<main>{props.children}</main>
) : (
<main className="container d-flex flex-column main-container mb-5">
{props.children}
</main>
)}
<Footer />
</>
);
export default withRouter(Layout);
| 21.428571 | 73 | 0.593333 |
e364a717c21142f28535cbd899840ef64247bf53 | 1,120 | js | JavaScript | src/pages/about.js | iancarnation/iancarnation-website | 7ccda52030d76593574889c742bf761c2a0f9446 | [
"MIT"
] | null | null | null | src/pages/about.js | iancarnation/iancarnation-website | 7ccda52030d76593574889c742bf761c2a0f9446 | [
"MIT"
] | null | null | null | src/pages/about.js | iancarnation/iancarnation-website | 7ccda52030d76593574889c742bf761c2a0f9446 | [
"MIT"
] | null | null | null | import React from "react";
import resume from "../files/Ian_Rich-Resume.pdf"
export default ({data}) => (
<div>
<h1>
About {data.site.siteMetadata.title}
</h1>
<p style={{ 'font-size': `small` }}>
<em>Intrepid Technician . Insatiable Learner . Intriguing Artist . Infinite Smiles-Provider</em>
</p>
Hello, I'm an educator and technical artist excited to support your creative and computational needs!
{/*<embed src={resume} type="application/pdf" width="100%" height="900px" />*/}
<p>
<br></br>
<a href={resume}>View Resume</a>
</p>
<p>
<a href="https://www.linkedin.com/in/iancarlrich/">LinkedIn Profile</a>
</p>
<p>
View my codeses on <a href="https://gitlab.com/iancarnation">GitLab</a>(Recent) or <a href="https://github.com/iancarnation/">GitHub</a>(Everything)
</p>
</div>
);
export const query = graphql`
query AboutQuery {
site {
siteMetadata {
title
}
}
}
` | 30.27027 | 160 | 0.535714 |
e366612acbb63ad0e3d966485ae3b615dffbc9aa | 3,093 | js | JavaScript | tests/plugins/phantomjs_screenshot.js | DuCorey/bokeh | a88e24f34d40499a4608d01da8d706123350b4e6 | [
"BSD-3-Clause"
] | 1 | 2021-01-31T22:13:13.000Z | 2021-01-31T22:13:13.000Z | tests/plugins/phantomjs_screenshot.js | adsbxchange/bokeh | 47aa8f8420944c47e876c1c36be182d257c14b87 | [
"BSD-3-Clause"
] | 1 | 2017-01-12T00:37:38.000Z | 2017-01-12T00:37:38.000Z | tests/plugins/phantomjs_screenshot.js | adsbxchange/bokeh | 47aa8f8420944c47e876c1c36be182d257c14b87 | [
"BSD-3-Clause"
] | 1 | 2018-03-02T09:57:56.000Z | 2018-03-02T09:57:56.000Z | var page = require('webpage').create();
var system = require('system');
var fs = require('fs');
var url = system.args[1];
var png = system.args[2];
var local_wait = system.args[3];
var global_wait = system.args[4];
var width = system.args[5];
var height = system.args[6];
var errors = [];
var messages = [];
var resources = [];
function finalize(timeout, success) {
if (png != null) {
page.render(png);
}
console.log(JSON.stringify({
success: success,
timeout: timeout,
errors: errors,
messages: messages,
resources: resources,
}));
phantom.exit();
}
function waitFor(testFx, onReady, timeOutMillis) {
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : global_wait, //< default timeout is 'global_wait' period
start = new Date().getTime(),
condition = false,
interval = setInterval(function() {
if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
// If not time-out yet and condition not yet fulfilled
condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
} else {
if(!condition) {
// If condition still not fulfilled (timeout but condition is 'false')
// we return success=true here because some cases don't correctly return is_idle (i.e. TileRenderers)
finalize(true, true);
} else {
// Condition fulfilled (timeout and/or condition is 'true')
typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
clearInterval(interval); //< Stop this interval
}
}
}, local_wait); //< repeat check every 'local_wait' period
};
page.viewportSize = { width: width, height: height };
page.onError = function(msg, trace) {
errors.push({
msg: msg,
trace: trace.map(function(item) {
return { file: item.file, line: item.line };
}),
});
};
page.onResourceError = function(response) {
resources.push(response);
};
page.onConsoleMessage = function(msg, line, source) {
messages.push({msg: msg, line: line, source: source});
};
page.onCallback = function(data) {
if (data === 'done') {
finalize(false, true);
}
};
page.open(url, function(status) {
if (status === 'fail') {
finalize(false, false);
} else {
waitFor(function() {
return page.evaluate(function() {
// this will annoying be set repeatedly, but we need to make sure it happens
document.body.bgColor = 'white';
// wait for BokehJS to be loaded
if (window.Bokeh == undefined) {
return false
};
// check that document is done rendering
var docs = window.Bokeh.documents;
if (docs.length == 0) {
return false
};
return docs[0].is_idle
});
}, function() {
page.evaluate(function() {
window.callPhantom('done');
});
});
};
});
| 29.179245 | 141 | 0.582929 |
e366a3bf7f5dc2cf695c7d8c8ff3c6b4af01dbce | 1,163 | js | JavaScript | www/app/modules/administrative/site/addedit.js | marwahan/test-os | 8673696fa13c848c8dfe118d30ff0475f1e8bf77 | [
"BSD-3-Clause"
] | null | null | null | www/app/modules/administrative/site/addedit.js | marwahan/test-os | 8673696fa13c848c8dfe118d30ff0475f1e8bf77 | [
"BSD-3-Clause"
] | null | null | null | www/app/modules/administrative/site/addedit.js | marwahan/test-os | 8673696fa13c848c8dfe118d30ff0475f1e8bf77 | [
"BSD-3-Clause"
] | null | null | null | angular.module('os.administrative.site.addedit', ['os.administrative.models'])
.controller('SiteAddEditCtrl', function(
$scope, $state, site, extensionCtxt, Institute, PvManager, ExtensionsUtil) {
function init() {
$scope.site = site;
$scope.deFormCtrl = {};
$scope.extnOpts = ExtensionsUtil.getExtnOpts(site, extensionCtxt);
loadPvs();
}
function loadPvs() {
$scope.siteTypes = PvManager.getPvs('site-type');
$scope.institutes = [];
Institute.query().then(
function(instituteList) {
angular.forEach(instituteList, function(institute) {
$scope.institutes.push(institute.name);
});
}
);
}
$scope.save = function() {
var formCtrl = $scope.deFormCtrl.ctrl;
if (formCtrl && !formCtrl.validate()) {
return;
}
var site = angular.copy($scope.site);
if (formCtrl) {
site.extensionDetail = formCtrl.getFormData();
}
site.$saveOrUpdate().then(
function(savedSite) {
$state.go('site-detail.overview', {siteId: savedSite.id});
}
);
}
init();
});
| 25.844444 | 80 | 0.580396 |
e3674f409bb2eacc293a99d775f4a0e805666c62 | 2,687 | js | JavaScript | src/util/permissions.js | theLAZYmd/LAZYmail | f9e1db53df51ebbd0685c18d04c5cf724b79995e | [
"MIT"
] | null | null | null | src/util/permissions.js | theLAZYmd/LAZYmail | f9e1db53df51ebbd0685c18d04c5cf724b79995e | [
"MIT"
] | null | null | null | src/util/permissions.js | theLAZYmd/LAZYmail | f9e1db53df51ebbd0685c18d04c5cf724b79995e | [
"MIT"
] | null | null | null | const DataManager = require("./datamanager.js");
const config = require("../config.json");
class Permissions {
static user(requirement, argsInfo) {
let value = config.ids[requirement];
if (!value) return true;
if (typeof value === "string" && value === argsInfo.author.id) return true;
else if (Array.isArray(value)) {
for (let passable of value)
if (passable === argsInfo.author.id) return true; //if Array. No support for object.
}
return false;
}
static role(roleType, argsInfo) { //admin, {object}
if (roleType === "owner") return (argsInfo.guild.ownerID === argsInfo.member.id || config.ids.owner.includes(argsInfo.author.id));
let roleName = argsInfo.server.roles[roleType];
if (!argsInfo.guild.roles.some(role => role.name = roleName) || !roleName) return true;
return (argsInfo.member.roles.some(role => role.name.toLowerCase().startsWith(roleName)) || argsInfo.guild.ownerID === argsInfo.member.id);
}
static channels(channelResolvable, argsInfo) {
let channelName;
if (typeof channelResolvable === "string") channelName = channelResolvable;
else if (typeof channelResolvable === "object") {
if (channelResolvable.name) channelName = channelResolvable.name;
else if (channelResolvable.type) return channelResolvable.type === argsInfo.channel.type;
}
if (!argsInfo.guild.channels.some(channel => channel.name.toLowerCase() === argsInfo.server.channels[channelName].toLowerCase())) channelName = "general";
return argsInfo.channel.name.toLowerCase() === argsInfo.server.channels[channelName].toLowerCase();
}
static state(state, data) {
if (typeof state !== "string") return true;
return data.server.states._getDescendantProp(state.toLowerCase());
}
static bot(bot, data) {
return data.author.bot === bot;
}
static args(data, argsInfo) {
if (data.length || data.length === 0) {
if (typeof data.length === "number") {
if (argsInfo.args.length === data.length) return true;
} else {
for (let value of data.length) {
if (argsInfo.args.length === value) return true;
if (value === "++" && argsInfo.args.length > data.length[data.length.length - 2]) return true;
}
}
return false;
}
return true;
}
static output(key, argsInfo) {
switch (key) {
case "user":
return "That command is bot owner only.\nIf you are not an active developer on the bot, you cannot use this command.";
case "role":
return "Insufficient server permissions to use this command.";
case "channel":
return "Wrong channel to use this command.";
case "args":
return argsInfo.command === ".." ? "" : "Inapplicable number of parameters."
}
}
}
module.exports = Permissions; | 36.310811 | 156 | 0.687012 |
e367828b6c46e962838c93b3b19679d76c5bc946 | 3,157 | js | JavaScript | app.js | leidig54/stripe-no-website-example | 2614b1cb53435422a917d09bae82a70f4ef08b5b | [
"MIT"
] | 8 | 2020-10-02T19:37:30.000Z | 2021-11-21T23:10:51.000Z | app.js | leidig54/stripe-no-website-example | 2614b1cb53435422a917d09bae82a70f4ef08b5b | [
"MIT"
] | null | null | null | app.js | leidig54/stripe-no-website-example | 2614b1cb53435422a917d09bae82a70f4ef08b5b | [
"MIT"
] | 6 | 2021-06-28T19:08:16.000Z | 2022-03-04T12:31:20.000Z | // --- Set these values in your environment variables
const PORT = process.env.PORT;
const TEST_MODE = process.env.TEST_MODE == 'true';
const STRIPE_KEY = process.env.STRIPE_KEY;
const STRIPE_KEY_TEST = process.env.STRIPE_KEY_TEST;
const RC_API_KEY = process.env.RC_API_KEY;
const SUCCESS_URL = process.env.SUCCESS_URL;
const CANCEL_URL = process.env.CANCEL_URL;
// -------------------
// --- Imports
const express = require('express');
const createError = require('http-errors');
const path = require('path');
// -------------------
// --- Axios request library
const axios = require('axios').create({
baseURL: 'https://api.revenuecat.com/v1',
headers: { 'X-Platform': 'stripe', 'Authorization': `Bearer ${RC_API_KEY}` }
});
// -------------------
// --- Express app setup
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// -------------------
// --- Landing Page
app.get('/', function (req, res, next) {
res.render('landing', { test_mode: TEST_MODE });
});
// -------------------
// --- Endpoints
app.get('/purchase/:userId/:productId', async function (req, res, next) {
// - Render our redirection page with context
res.render('redirectToCheckout', {
user_id: req.params.userId,
key: (TEST_MODE == true ? STRIPE_KEY_TEST : STRIPE_KEY),
success_url: SUCCESS_URL,
cancel_url: CANCEL_URL,
product_id: req.params.productId
});
});
app.post('/webhooks/stripe', async function (req, res, next) {
// - Ensure there is a purchase object
let purchaseObject = req.body?.data?.object
if (purchaseObject) {
// - Get the associated app user ID and token
let userId = purchaseObject.client_reference_id;
let token = purchaseObject.subscription;
// - Print to log
console.log(userId);
console.log(token);
// - Post receipt data to RevenueCat
axios.post('/receipts', {
app_user_id: userId,
fetch_token: token,
attributes: { "stripe_customer_id": { value: purchaseObject.customer } }
})
.then(function (response) {
// TODO: ensure a successful response from RevenueCat, retry if necessary
})
.catch(function (error) {
// TODO: error- retry if necessary
});
// - Respond to Stripe to let them know we got the webhook
res.status(200).json();
} else {
// - No purchase object found
console.log("No purchase found in webhook body:")
console.log(req.body);
res.status(400).json();
}
});
// -------------------
// --- Catch generic errors
app.use(function (req, res, next) {
next(createError(404));
});
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = TEST_MODE ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
// -------------------
// --- Start listening
app.listen(PORT, function () {
console.log(`App is listening on port ${PORT} - Test Mode: ${TEST_MODE}`);
});
// -------------------
| 23.559701 | 81 | 0.621159 |
e3686ab3fe73173bf0c6a827582600c5e9211d38 | 2,325 | js | JavaScript | assets/js/fancybox.js | SlipBey/xidev-site-kodlar- | 17fbcc4108d3f805b33574b7ae3800099e42e7d9 | [
"MIT"
] | 1 | 2021-06-26T22:14:07.000Z | 2021-06-26T22:14:07.000Z | assets/js/fancybox.js | SlipBey/xidev-site-kodlari | 17fbcc4108d3f805b33574b7ae3800099e42e7d9 | [
"MIT"
] | null | null | null | assets/js/fancybox.js | SlipBey/xidev-site-kodlari | 17fbcc4108d3f805b33574b7ae3800099e42e7d9 | [
"MIT"
] | null | null | null | var MyBBFancyBox = (function($, m) {
"use strict";
var lang = {
clickToEnlarge: "Click to enlarge",
CLOSE: "Close",
NEXT: "Next",
PREV: "Previous",
ERROR:
"The requested content cannot be loaded.<br/>Please try again later.",
PLAY_START: "Start slideshow",
PLAY_STOP: "Pause slideshow",
FULL_SCREEN: "Full screen",
THUMBS: "Thumbnails",
DOWNLOAD: "Download",
SHARE: "Share",
ZOOM: "Zoom",
MINIMIZE: "Minimize"
},
options = {
slideClass: "",
closeExisting: true,
loop: true,
protect: false,
keyboard: true,
arrows: true,
infobar: true,
thumbs: { autoStart: false, hideOnClose: true },
buttons: [
"slideShow",
"fullScreen",
"thumbs",
"share",
"download",
"zoom",
"minimize",
"close"
]
};
function init() {
if (options.buttons && options.buttons.indexOf("minimize") !== -1) {
var yState = $("body").css("overflow-y");
$(document).on("click", "[data-fancybox-minimize]", function() {
var fb = $.fancybox.getInstance();
if (fb) {
fb.$refs.container.toggleClass("minimized");
$("body").css(
"overflow-y",
fb.$refs.container.hasClass("minimized") ? yState : "hidden"
);
}
});
}
$(".post_body img").each(function() {
var currentImage = $(this);
var pid = currentImage.parents(".post_body.scaleimages").attr("id");
if (
currentImage.hasClass("smilie") == false &&
currentImage.parent().is("a") == false
) {
currentImage.wrap(
"<a title='" +
lang.clickToEnlarge +
"' target='_blank' data-fancybox='" +
pid +
"' data-type='image' href='" +
currentImage.attr("src") +
"'>"
);
}
});
$.fancybox.defaults.lang = "en";
$.fancybox.defaults.i18n.en = lang;
$("[data-fancybox]").fancybox(options);
}
function setup(l, o) {
$.extend(lang, l || {});
$.extend(options, o || {});
}
m.setup = setup;
$(init);
return m;
})(jQuery, MyBBFancyBox || {});
| 28.012048 | 79 | 0.488172 |
e3688d8639fda4f71476d84fbaf6e2a99f8fe3b6 | 775 | js | JavaScript | js/welcome.js | game-for-fun/frontend | c0c2fc7d878dacb613b3015ca7405b49125a9d57 | [
"Apache-2.0"
] | null | null | null | js/welcome.js | game-for-fun/frontend | c0c2fc7d878dacb613b3015ca7405b49125a9d57 | [
"Apache-2.0"
] | null | null | null | js/welcome.js | game-for-fun/frontend | c0c2fc7d878dacb613b3015ca7405b49125a9d57 | [
"Apache-2.0"
] | null | null | null | function preloader(){
if (document.images){
var img1 = new Image();
img1.src = "../img/bg/bg_welcome.jpg";
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if(typeof window.onload != 'function'){
window.onload = func;
}else{
window.onload = function(){
if(oldonload){
oldonload();
}
func();
}
}
}
addLoadEvent(preloader);
function go(str){
switch (str) {
case "zhaohuan":
str = "../lottery/lottery.html";
break;
case "jinji":
str = "/lottery/myCard.html";
break;
case "huodong":
str = "/huodong/huodongPage.html";
break;
case "rank":
str = "/user/rankPage.html?orderParam='rmb'";
break;
}
window.location.href = str;
} | 19.871795 | 47 | 0.56129 |
e368de73a72d62cd265c005dbc1caf811353a1da | 2,173 | js | JavaScript | lib/adaptor.js | hybridgroup/cylon-joystick | 4944d7b02bebc01c7d47e54a23f35c919447b0ec | [
"Apache-2.0"
] | 7 | 2015-04-17T14:28:15.000Z | 2020-02-15T16:18:23.000Z | lib/adaptor.js | hybridgroup/cylon-joystick | 4944d7b02bebc01c7d47e54a23f35c919447b0ec | [
"Apache-2.0"
] | 7 | 2015-03-06T18:56:16.000Z | 2018-09-09T22:34:11.000Z | lib/adaptor.js | hybridgroup/cylon-joystick | 4944d7b02bebc01c7d47e54a23f35c919447b0ec | [
"Apache-2.0"
] | 6 | 2015-07-04T22:10:50.000Z | 2021-08-21T05:00:02.000Z | /*
* cylon-joystick adaptor
* http://cylonjs.com
*
* Copyright (c) 2013-2014 The Hybrid Group
* Licensed under the Apache 2.0 license.
*/
"use strict";
var Cylon = require("cylon");
var gamepad = require("gamepad");
var Adaptor = module.exports = function Adaptor(opts) {
Adaptor.__super__.constructor.apply(this, arguments);
opts = opts || {};
this.connector = this.joystick = null;
this.events = [
/**
* Emitted when a controller is connected
*
* @event attach
*/
"attach",
/**
* Emitted when a controller is disconnected
*
* @event remove
*/
"remove",
/**
* Emitted when any connected controller's analog sticks are moved
*
* @event move
*/
"move",
/**
* Emitted when any connected controller's button is released
*
* @event down
*/
"up",
/**
* Emitted when any connected controller's button is pressed
*
* @event down
*/
"down"
];
};
Cylon.Utils.subclass(Adaptor, Cylon.Adaptor);
/**
* Connects to the gamepads, attaches event handlers
*
* @param {Function} callback to be triggered when connected
* @return {void}
*/
Adaptor.prototype.connect = function(callback) {
gamepad.init();
if (gamepad.numDevices() === 0) {
throw new Error("No Joysticks available.");
}
// process events on a loop
every(5, gamepad.processEvents);
// check for new gamepads every half-second
every(500, gamepad.detectDevices);
["attach", "remove", "move", "up", "down"].forEach(function(event) {
gamepad.on(event, function() {
var args = [].slice.apply(arguments);
args.unshift(event);
this.emit.apply(this, args);
}.bind(this));
}.bind(this));
callback();
};
/**
* Disconnects from the adaptor
*
* @param {Function} callback to be triggered when disconnected
* @return {void}
*/
Adaptor.prototype.disconnect = function(callback) {
callback();
};
Adaptor.prototype.getDevices = function() {
var devices = [];
for (var i = 0, l = gamepad.numDevices(); i < l; i++) {
var d = gamepad.deviceAtIndex(i);
devices.push(d);
}
return devices;
};
| 19.230088 | 70 | 0.613438 |
e36950647fe12b7a9d9ac69c7ec579056d2c8cca | 798 | js | JavaScript | studio/node_modules/@sanity/ui/node_modules/@reach/utils/computed-styles/dist/reach-utils-computed-styles.esm.js | sajustsmile/twitter-blockchain | 3b79a54024ccb499fd128e693e2c3dd363a0572c | [
"Apache-2.0"
] | 1 | 2022-03-31T20:19:12.000Z | 2022-03-31T20:19:12.000Z | studio/node_modules/@sanity/ui/node_modules/@reach/utils/computed-styles/dist/reach-utils-computed-styles.esm.js | sajustsmile/twitter-blockchain | 3b79a54024ccb499fd128e693e2c3dd363a0572c | [
"Apache-2.0"
] | null | null | null | studio/node_modules/@sanity/ui/node_modules/@reach/utils/computed-styles/dist/reach-utils-computed-styles.esm.js | sajustsmile/twitter-blockchain | 3b79a54024ccb499fd128e693e2c3dd363a0572c | [
"Apache-2.0"
] | null | null | null | import { getOwnerWindow } from '../../owner-document/dist/reach-utils-owner-document.esm.js';
import '../../can-use-dom/dist/reach-utils-can-use-dom.esm.js';
/**
* Get computed style properties of a DOM element.
*
* @param element
* @param styleProp
*/
function getComputedStyles(element) {
var ownerWindow = getOwnerWindow(element);
if (ownerWindow) {
return ownerWindow.getComputedStyle(element, null);
}
return null;
}
/**
* Get a computed style value by property.
*
* @param element
* @param styleProp
*/
function getComputedStyle(element, styleProp) {
var _getComputedStyles;
return ((_getComputedStyles = getComputedStyles(element)) == null ? void 0 : _getComputedStyles.getPropertyValue(styleProp)) || null;
}
export { getComputedStyle, getComputedStyles };
| 23.470588 | 135 | 0.718045 |
e36a405668d0cf13a193631d5b63a744d74586f5 | 1,671 | js | JavaScript | services/leagues.service.js | Seyi-Baks/MockPremierLeague | 04d4de87956a0489ed37f05549254969f7980630 | [
"MIT"
] | null | null | null | services/leagues.service.js | Seyi-Baks/MockPremierLeague | 04d4de87956a0489ed37f05549254969f7980630 | [
"MIT"
] | 2 | 2021-05-11T19:19:38.000Z | 2021-09-02T13:28:42.000Z | services/leagues.service.js | Seyi-Baks/MockPremierLeague | 04d4de87956a0489ed37f05549254969f7980630 | [
"MIT"
] | null | null | null | const League = require('../models/league.model');
const Team = require('../models/teams.model');
exports.createLeague = async (league) => {
try {
const leagueDetails = await League.findOne({ name: league.name });
if (leagueDetails) {
throw new Error('League already exists');
}
const createdLeague = await League.create(league);
return createdLeague;
} catch (error) {
throw new Error(error);
}
};
exports.fetchLeagues = async () => {
try {
const leagues = await League.find().sort({ name: 1 });
return leagues;
} catch (error) {
throw new Error(error);
}
};
exports.fetchLeague = async (leagueId) => {
try {
const league = await League.findById(leagueId);
if (!league) {
throw new Error('League does not exist');
}
return league;
} catch (error) {
throw new Error(error);
}
};
exports.updateLeague = async (leagueId, league) => {
try {
const updatedLeague = League.findByIdAndUpdate({ _id: leagueId }, league, {
new: true,
runValidators: true,
});
if (!updatedLeague) {
throw new Error('League does not exist');
}
return updatedLeague;
} catch (error) {
throw new Error(error);
}
};
exports.deleteLeague = async (leagueID) => {
try {
const league = await League.findOneAndDelete(leagueID);
if (!league) {
throw new Error('League does not exist');
}
return league;
} catch (error) {
throw new Error(error);
}
};
exports.fetchTeams = async (leagueId) => {
try {
const teams = await Team.find({ league: leagueId });
return teams;
} catch (error) {
throw new Error(error);
}
};
| 21.151899 | 79 | 0.613405 |
e36aea0fda8ff77cfa93540a2eafa8842df5240b | 32,359 | js | JavaScript | server.js | salmanff/test-freezr | 41b4a3dc8d3b948acea245271a4678b1b5363236 | [
"MIT"
] | null | null | null | server.js | salmanff/test-freezr | 41b4a3dc8d3b948acea245271a4678b1b5363236 | [
"MIT"
] | null | null | null | server.js | salmanff/test-freezr | 41b4a3dc8d3b948acea245271a4678b1b5363236 | [
"MIT"
] | null | null | null | // freezr.info - nodejs system files - main file: server.js
const VERSION = "0.0.133";
// INITALISATION / APP / EXPRESS
console.log("========================= VERSION Jan 2020 =======================")
const LISTEN_TO_LOCALHOST_ON_LOCAL = true; // for local development - set to true to access local site at http://localhost:3000, and false to access it at your local ip address - eg http://192.168.192.1:3000 (currently not working)
var fs = require('fs'),
express = require('express'),
bodyParser = require('body-parser'),
multer = require('multer'),
upload = multer().single('file'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
cookieSession = require('cookie-session'),
session = require('express-session'),
app = express();
var db_handler = require('./freezr_system/db_handler.js'),
admin_handler = require('./freezr_system/admin_handler.js'),
account_handler = require('./freezr_system/account_handler.js'),
helpers = require('./freezr_system/helpers.js'),
environment_defaults = require('./freezr_system/environment/environment_defaults.js'),
file_handler = require('./freezr_system/file_handler.js'),
app_handler = require('./freezr_system/app_handler.js'),
async = require('async'),
visit_logger = require('./freezr_system/visit_logger.js'),
public_handler = require('./freezr_system/public_handler.js');
//console
//var tester = require('./freezr_system/environment/file_env_dropbox.js');
// var tester = require('./freezr_system/environment/db_env_nedb.js');
// stackoverflow.com/questions/26287968/meanjs-413-request-entity-too-large
app.use(bodyParser.json({limit:1024*1024*3, type:'application/json'}));
app.use(bodyParser.urlencoded( { extended:true,limit:1024*1024*3,type:'application/x-www-form-urlencoding' } ) );
app.use(cookieParser());
var freezr_prefs={};
const DEFAULT_PREFS={
log_visits:true,
log_details:{each_visit:true, daily_db:true, include_sys_files:false, log_app_files:false},
redirect_public:false,
public_landing_page: ""
};
var freezr_secrets = {params: {
session_cookie_secret:null
}};
var freezr_environment, custom_file_environment;
// ACCESS RIGHT FUNCTIONS
var serveAppFile = function(req, res, next) {
//onsole.log( (new Date())+" serveAppFile - "+req.originalUrl);
var fileUrl = req.originalUrl;
// clean up url
if (helpers.startsWith(fileUrl,'/app_files/')) { fileUrl = fileUrl.replace('/app_files/','app_files/')}
else if (helpers.startsWith(fileUrl,'/apps/')) { fileUrl = fileUrl.replace('/apps/','app_files/')}
if (fileUrl.indexOf('?')>1) { fileUrl = fileUrl.substr(0,fileUrl.indexOf('?'));} // solving slight problem when node.js adds a § param to some fetches
//onsole.log( (new Date())+" serveAppFile - "+fileUrl);
if (req.session && req.session.logged_in) {
visit_logger.record(req, freezr_environment, freezr_environment, freezr_prefs, {source:'serveAppFile'});
file_handler.sendAppFile(res, fileUrl, freezr_environment);
} else {
visit_logger.record(req, freezr_environment, freezr_prefs, {source:'serveAppFile',auth_error:true});
helpers.auth_warning("server.js", VERSION, "serveAppFile", "Unauthorized attempt to access file "+ fileUrl);
res.sendStatus(401);
}
}
var servePublicAppFile = function(req, res, next) {
var fileUrl = file_handler.normUrl(req.originalUrl.replace('/app_files/','app_files/') );
if (helpers.startsWith(fileUrl,'/apps/')) { fileUrl = fileUrl.replace('/apps/','app_files/')}
if (fileUrl.indexOf('?')>1) { fileUrl = fileUrl.substr(0,fileUrl.indexOf('?'));} // solving slight problem when node.js adds a query param to some fetches
visit_logger.record(req, freezr_environment, freezr_prefs, {source:'servePublicAppFile'});
if (fileUrl.slice(1)=="favicon.ico") {
res.sendFile(file_handler.systemPathTo("systemapps/info.freezr.public/static/" + fileUrl));
} else {
file_handler.sendAppFile(res, fileUrl, freezr_environment);
}
}
var appPageAccessRights = function(req, res, next) {
if ((freezr_environment.freezr_is_setup && req.session && req.session.logged_in) ){
visit_logger.record(req, freezr_environment, freezr_prefs, {source:'appPageAccessRights'});
if (req.params.page || helpers.endsWith(req.originalUrl,"/") ) {
req.freezr_server_version = VERSION;
req.freezrStatus = freezrStatus;
req.freezr_environment = freezr_environment;
next();
} else {
res.redirect(req.originalUrl+'/');
}
} else {
visit_logger.record(req, freezr_environment, freezr_prefs, {source:'appPageAccessRights', auth_error:true});
if (freezr_environment && freezr_environment.freezr_is_setup) helpers.auth_warning("server.js", VERSION, "appPageAccessRights", "Unauthorized attempt to access page"+req.url+" without login ");
res.redirect('/account/login')
}
}
function requireAdminRights(req, res, next) {
//onsole.log("require admin login "+req.session.logged_in_as_admin+" for "+req.session.logged_in_user_id);
if (req.session && req.session.logged_in_as_admin) {
req.freezr_server_version = VERSION;
req.freezrStatus = freezrStatus;
req.freezr_environment = freezr_environment;
visit_logger.record(req, freezr_environment, freezr_prefs, {source:'requireAdminRights', auth_error:false});
next();
} else {
visit_logger.record(req, freezr_environment, freezr_prefs, {source:'requireAdminRights', auth_error:true});
helpers.auth_warning("server.js", VERSION, "requireAdminRights", "Unauthorized attempt to access admin area "+req.url+" - ");
res.redirect("/account/login");
}
}
var userDataAccessRights = function(req, res, next) {
//onsole.log("userDataAccessRights sess "+(req.session?"Y":"N")+" loggin in? "+req.session.logged_in_user_id+" param id"+req.params.userid);
//if (freezr_environment.freezr_is_setup && req.session && req.session.logged_in && req.session.logged_in_user_id){
if (freezr_environment.freezr_is_setup && req.session && req.header('Authorization') ) {
req.freezr_environment = freezr_environment;
req.freezrStatus = freezrStatus;
visit_logger.record(req, freezr_environment, freezr_prefs, {source:'userDataAccessRights'});
next();
} else {
if (freezr_environment && freezr_environment.freezr_is_setup) helpers.auth_warning("server.js", VERSION, "userDataAccessRights", "Unauthorized attempt to access data "+req.url+" without login ");
visit_logger.record(req, freezr_environment, freezr_prefs, {source:'userDataAccessRights', auth_error:true});
res.sendStatus(401);
}
}
var userLoggedInRights = function(req, res, next) {
//onsole.log("userLoggedInRights sess "+(req.session?"Y":"N")+" loggin in? "+req.session.logged_in_user_id+" param id"+req.params.userid);
//if (freezr_environment.freezr_is_setup && req.session && req.session.logged_in && req.session.logged_in_user_id){
if (freezr_environment.freezr_is_setup && req.session && req.session.logged_in_user_id ) {
req.freezr_environment = freezr_environment;
req.freezrStatus = freezrStatus;
visit_logger.record(req, freezr_environment, freezr_prefs, {source:'userLoggedInRights'});
next();
} else {
if (freezr_environment && freezr_environment.freezr_is_setup) helpers.auth_warning("server.js", VERSION, "userLoggedInRights", "Unauthorized attempt to access data "+req.url+" without login ");
visit_logger.record(req, freezr_environment, freezr_prefs, {source:'userLoggedInRights', auth_error:true});
res.sendStatus(401);
}
}
function uploadFile(req,res) {
req.freezr_server_version = VERSION;
req.freezr_environment = freezr_environment;
// visit_logger already done via userdatarights
upload(req, res, function (err) {
if (err) {
helpers.send_failure(res, err, "server.js", VERSION, "uploadFile");
} else app_handler.create_file_record(req,res);
})
}
function installAppFromZipFile(req,res) {
req.freezr_server_version = VERSION;
req.freezr_environment = freezr_environment;
// visit_logger already done via
upload(req, res, function (err) {
if (err) {
helpers.send_failure(res, err, "server.js", VERSION, "installAppFromZipFile");
}
account_handler.install_app(req,res);
})
}
function addVersionNumber(req, res, next) {
req.freezr_server_version = VERSION;
req.freezr_environment = freezr_environment;
req.freezrStatus = freezrStatus;
req.freezr_is_setup = freezr_environment.freezr_is_setup;
visit_logger.record(req, freezr_environment, freezr_prefs, {source:'addVersionNumber', auth_error:false});
next();
}
// APP PAGES AND FILE
const add_app_uses = function(){
// headers and cookies
app.use(cookieSession(
// todo - move to a metof (if possible) to be able to reset coookie secret programmatically?
{
secret: freezr_secrets.params.session_cookie_secret,
maxAge: 15552000000,
store: new session.MemoryStore() // todolater:eview
}
));
app.use(function(req, res, next) {
//stackoverflow.com/questions/22535058/including-cookies-on-a-ajax-request-for-cross-domain-request-using-pure-javascri
res.header("Access-Control-Allow-Credentials","true");
res.header("Access-Control-Allow-Origin", null);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Origin, Accept");
res.header("Access-Control-Allow-Methods","PUT, POST, GET, OPTIONS");
next();
});
// app pages and files
app.use("/app_files/info.freezr.public", servePublicAppFile);
app.get('/app_files/:app_name/public/static/:file', servePublicAppFile);
app.get('/app_files/:app_name/public/:file', servePublicAppFile);
app.use("/app_files/:app_name/:file", serveAppFile);
app.get('/apps/:app_name', appPageAccessRights, app_handler.generatePage);
app.get('/apps/:app_name/static/:file', serveAppFile);
app.get('/apps/:app_name/:page', appPageAccessRights, app_handler.generatePage);
app.get('/favicon.ico', servePublicAppFile)
// publci todo console.log(review)
app.get('/pcard/:user_id/:requestor_app/:permission_name/:app_name/:collection_name/:data_object_id', addVersionNumber, public_handler.generatePublicPage);
app.get('/pcard/:user_id/:app_name/:collection_name/:data_object_id', addVersionNumber, public_handler.generatePublicPage);
// public
app.get('/papp/:app_name/:page', addVersionNumber, public_handler.generatePublicPage);
app.get('/papp/:app_name', addVersionNumber, public_handler.generatePublicPage);
app.get('/ppage/:user_id/:app_table/:data_object_id', addVersionNumber, public_handler.generatePublicObjectPage);
app.get('/ppage/:object_public_id', addVersionNumber, public_handler.generatePublicObjectPage);
app.get('/ppage', addVersionNumber, public_handler.generatePublicPage);
app.get('/rss.xml', addVersionNumber, public_handler.generatePublicPage);
app.get('/apps/:app_name/public/static/:file', servePublicAppFile);
app.get('/v1/pdbq', addVersionNumber, public_handler.dbp_query);
app.get('/v1/pdbq/:app_name', addVersionNumber, public_handler.dbp_query);
app.post('/v1/pdbq', addVersionNumber, public_handler.dbp_query);
app.get('/v1/publicfiles/:requestee_app/:user_id/*', addVersionNumber, public_handler.get_public_file);
app.get('/v1/pobject/:user_id/:requestee_app_table/:data_object_id', addVersionNumber, public_handler.generatePublicPage);
// developer utilities
app.get('/v1/developer/config/:app_name',userLoggedInRights, app_handler.getConfig);
app.get('/v1/developer/fileListUpdate/:app_name/:source_app_code', userLoggedInRights, app_handler.updateFileList);
app.get('/v1/developer/fileListUpdate/:app_name/:source_app_code/:folder_name', userLoggedInRights, app_handler.updateFileList);
// account pages
app.get ('/account/logout', addVersionNumber, account_handler.logout_page);
app.get ('/account/login', addVersionNumber, account_handler.generate_login_page);
app.get ('/login', addVersionNumber, account_handler.generate_login_page);
app.get('/account/appdata/:app_name/:action', appPageAccessRights, account_handler.generateSystemDataPage);
app.get ('/account/:page/:app_name', appPageAccessRights, account_handler.generateAccountPage); // for "perms"
app.get ('/account/:page', appPageAccessRights, account_handler.generateAccountPage);
app.post('/v1/account/login', addVersionNumber, account_handler.login);
app.post('/v1/account/applogout', addVersionNumber, account_handler.app_logout);
app.put ('/v1/account/changePassword.json', userLoggedInRights, account_handler.changePassword);
app.get('/v1/account/apppassword/generate', addVersionNumber, account_handler.app_password_generate_one_time_pass);
app.get('/v1/account/apppassword/updateparams', addVersionNumber, account_handler.app_password_update_params);
app.put ('/v1/account/app_install_from_zipfile.json', userLoggedInRights, installAppFromZipFile);
app.post ('/v1/account/app_install_from_url.json', userLoggedInRights, addVersionNumber, account_handler.get_file_from_url_to_install_app);
app.post ('/v1/account/app_install_blank', userLoggedInRights, addVersionNumber, account_handler.install_blank_app);
app.get('/v1/account/app_list.json', userDataAccessRights, account_handler.list_all_user_apps);
app.post('/v1/account/appMgmtActions.json', userLoggedInRights, account_handler.appMgmtActions);
// admin pages
app.put ('/v1/admin/oauth_perm', requireAdminRights, admin_handler.oauth_perm_make);
app.get('/v1/admin/oauth/public/:dowhat', addVersionNumber, admin_handler.oauth_do);
app.get('/admin/public/:sub_page', addVersionNumber, admin_handler.generateAdminPage);
app.get('/admin/:sub_page', requireAdminRights, admin_handler.generateAdminPage);
app.get('/admin', requireAdminRights, admin_handler.generateAdminPage);
app.put('/v1/admin/change_main_prefs', requireAdminRights, function (req, res) {
req.defaultPrefs = DEFAULT_PREFS;
admin_handler.change_main_prefs (req, function(err, returns) {
if (err) {
helpers.send_auth_failure(res, "admin_handler", exports.version,"change_main_prefs",err.message, err.errCode);
} else {
freezr_prefs = returns;
helpers.send_success(res, returns);
}
})
})
app.put('/v1/admin/user_register', requireAdminRights, admin_handler.user_register);
app.put('/v1/admin/first_registration', addVersionNumber, function (req, res) {
admin_handler.first_registration(req, function(err, results) {
if (err || !results || !results.freezr_environment) {
if (!err) err = {message:'unknown err', code:null}
helpers.send_auth_failure(res, "admin_handler", exports.version,"first_registration",err.message, err.errCode);
} else {
helpers.log (null,"End of process of 1st reg "+JSON.stringify(results))
freezr_environment = results.freezr_environment
file_handler.reset_freezr_environment(freezr_environment);
freezrStatus = results.fstatus;
freezrStatus.fundamentals_okay = get_all_okay_status(freezrStatus);
helpers.send_success(res, {user:results.user, freezrStatus:freezrStatus});
}
})
});
app.post('/v1/admin/dbquery/:collection_name', requireAdminRights, admin_handler.dbquery);
// CEPS
app.get('/ceps/ping', addVersionNumber, account_handler.ping);
app.post('/oauth/token', addVersionNumber, account_handler.login_for_app_token);
//app.post('/ceps/app_token', addVersionNumber, account_handler.login_for_app_token); old
app.post('/ceps/write/:app_table', userDataAccessRights, app_handler.write_record);
app.get('/ceps/read/:app_table/:data_object_id', userDataAccessRights, app_handler.read_record_by_id);
app.get('/ceps/query/:app_table', userDataAccessRights, app_handler.db_query);
app.put('/ceps/update/:app_table/:data_object_id', userDataAccessRights, app_handler.write_record)
app.delete('/ceps/delete/:app_table/:data_object_id', userDataAccessRights, app_handler.delete_record)
// app files and pages and user files
app.get('/feps/ping', addVersionNumber, account_handler.ping);
app.post('/feps/write/:app_table', userDataAccessRights, app_handler.write_record);
app.post('/feps/write/:app_table/:data_object_id', userDataAccessRights, app_handler.write_record);
app.get('/feps/read/:app_table/:data_object_id', userDataAccessRights, app_handler.read_record_by_id);
app.get('/feps/read/:app_table/:data_object_id/:requestee_user_id', userDataAccessRights, app_handler.read_record_by_id);
app.get('/feps/query/:app_table', userDataAccessRights, app_handler.db_query);
app.post('/feps/query/:app_table', userDataAccessRights, app_handler.db_query);
app.post('/feps/restore/:app_table', userDataAccessRights, app_handler.restore_record)
app.put('/feps/update/:app_table/:data_object_id', userDataAccessRights, app_handler.write_record)
app.put('/feps/update/:app_table', userDataAccessRights, app_handler.write_record)
app.post('/feps/upsert/:app_table', userDataAccessRights, app_handler.write_record);
// userfiles
app.get('/feps/getuserfiletoken/:permission_name/:requestee_app_name/:requestee_user_id/*', userDataAccessRights, app_handler.read_record_by_id); // collection_name is files
app.put('/feps/upload/:app_name',userDataAccessRights, uploadFile);
app.get('/feps/userfiles/:requestee_app/:user_id/*', addVersionNumber, app_handler.sendUserFile); // collection_name is files
// permissions
app.put('/v1/permissions/setobjectaccess/:requestor_app/:permission_name', userLoggedInRights, app_handler.setObjectAccess);
app.put('/v1/permissions/change/:requestee_app', userLoggedInRights, account_handler.changeNamedPermissions);
app.get('/v1/permissions/getall/:app_name', userDataAccessRights, account_handler.all_app_permissions);
app.get('/v1/permissions/groupall/:app_name', userDataAccessRights, account_handler.all_app_permissions);
app.get('/v1/permissions/gethtml/:app_name', userDataAccessRights, account_handler.generatePermissionHTML);
// todo & review / redo app.put('/v1/permissions/setfieldaccess/:requestor_app/:source_app_code/:permission_name', userDataAccessRights, app_handler.setFieldAccess);
// todo & review / redoapp.get('/v1/permissions/getfieldperms/:requested_type/:requestor_app/:source_app_code', userDataAccessRights, app_handler.getFieldPermissions)
// default redirects
function getPublicUrlFromPrefs () {
if (!freezr_prefs || !freezr_prefs.redirect_public) return "/account/login";
if (!freezr_prefs.public_landing_page) return "/ppage";
return "/papp/"+freezr_prefs.public_landing_page;
}
app.get('/feps*', function (req, res) {
helpers.log(req,"unknown feps api url "+req.url)
visit_logger.record(req, freezr_environment, freezr_prefs);
helpers.send_failure(res, helpers.error("invalid api url:",req.path), "server.js", VERSION, "server");
})
app.get('/ceps*', function (req, res) {
helpers.log(req,"unknown feps api url "+req.url)
visit_logger.record(req, freezr_environment, freezr_prefs);
helpers.send_failure(res, helpers.error("invalid api url:",req.path), "server.js", VERSION, "server");
})
app.get('/v1/*', function (req, res) {
helpers.log(req,"unknown api url "+req.url)
visit_logger.record(req, freezr_environment, freezr_prefs);
helpers.send_failure(res, helpers.error("invalid api url:",req.path), "server.js", VERSION, "server");
})
app.get("/", function (req, res) {
// to if allows public people coming in, then move to public page
//onsole.log("redirecting to account/home as default for "+req.originalUrl);
visit_logger.record(req, freezr_environment, freezr_prefs, {source:'home'});
var redirect_url = (req.session && req.session.logged_in)? "/account/home": getPublicUrlFromPrefs();
helpers.log(req,"home url redirect")
res.redirect( redirect_url);
res.end();
});
app.get('*', function (req, res) {
helpers.log(req,"unknown url redirect: "+req.url)
visit_logger.record(req, freezr_environment, freezr_prefs, {source:'redirect'});
//onsole.log("redirecting to account/login as default or for non logged in "+req.originalUrl);
res.redirect( (req.session && req.session.logged_in)? "/account/home":getPublicUrlFromPrefs());
res.end();
});
}
// SET UP AND RUN APP
var freezrStatus = {
fundamentals_okay: null,
environment_file_exists_no_faults : false,
can_write_to_user_folder : false,
can_read_write_to_db : false,
environments_match : true
}
const get_all_okay_status = function(aStatus) {
return (aStatus.can_write_to_user_folder && aStatus.can_read_write_to_db)
}
const try_reading_freezr_env_file = function(env, callback) {
file_handler.init_custom_env(env, (err) => { // uses env passed to it (generally autoconfig params) to find nev on file
if (err) {
console.warn("Error getting custom_env ", err)
callback(err)
} else {
file_handler.requireFile("userfiles","freezr_environment.js",env, callback )
}
})
}
function has_cookie_in_environment() {
return (process && process.env && process.env.COOKIE_SECRET);
}
// setting up freezr_environment
// Checks file on server - if so, use that but check against the version of the db and mark error if they are different
// But if file doesn't exist (it could be because of a restart in docker wiping it out) use the db. (Not an error - just warn)
async.waterfall([
// 1 Read freezr_environment from file and initiate environment or use defaults
function (cb) { // todo - make async with errr coming back from init_custome_env
try_reading_freezr_env_file (freezr_environment, (err, env_on_file) => {
if (!err) {
freezr_environment = env_on_file.params;
freezrStatus.environment_file_exists_no_faults = true;
console.log("1. Local copy of freezr_environment.js exists") //,JSON.stringify (freezr_environment))
cb(null)
} else {
// todo later: consider also case where file is corrupt - here we assume it doesnt exist and try other options
console.log("1. Note - no local copy of freezr_environment found")
environment_defaults.autoConfigs((err, autoconfigs) => {
if (err) {
console.warn("1 - Local environment file missing and ERROR getting Autoconfigured settings")
cb(null)
} else {
if (autoconfigs) freezr_environment = autoconfigs;
//onsole.log("Got autoconfigs, freezr_environment is "+JSON.stringify(freezr_environment))
try_reading_freezr_env_file (freezr_environment, (err, env_on_file) => {
if (!err) {
freezr_environment = env_on_file.params;
freezrStatus.environment_file_exists_no_faults = true;
console.log("1. Using autoconfig parameters, found freezr_environment.js file")
cb(null);
} else {
console.warn("1 - freezr_environment file does NOT exist or had errors(!) (DB to be queried for environment)");
freezr_environment.freezr_is_setup = false;
freezr_environment.first_user = null;
cb(null);
}
})
}
})
}
})
},
// 2. test check db and re-write or check freezr_environment
function (cb) {
db_handler.re_init_freezr_environment(freezr_environment, cb);
},
function (cb) {
db_handler.check_db(freezr_environment, function (err, env_on_db) {
if (err) {
freezrStatus.can_read_write_to_db = false;
console.warn("2 - DB Not Working ",err)
cb (err)
} else {
freezrStatus.can_read_write_to_db = true;
if (freezrStatus.environment_file_exists_no_faults) {
if (!helpers.variables_are_similar(freezr_environment,env_on_db)) {
helpers.warning("server.js", exports.version, "startup_waterfall", "STARTUP MISMATCH - freezr_environment on server different from one on db" )
freezrStatus.environments_match = false;
console.warn("2 - PROBLEM freezr_environment NOT consistent with db version")
} else {
console.log("2 - db working - freezr_environment consistent with db version")
}
cb(null)
} else {
if (freezr_environment.freezr_is_setup) helpers.warning("server.js", exports.version, "startup_waterfall", "freezr_environment on server not found" )
if (env_on_db && env_on_db.params) {
console.log("2 - Using db version of freezr_environment (as file doesnt exist)")
freezr_environment = env_on_db.params
freezr_environment.env_on_db_only = true;
cb(null)
} else {
console.log("2 - No freezr_environment on db or file - FIRST REGISTRATION WILL BE TRIGGERED")
cb(null)
}
}
}
})
},
// 3a. create user directories and file_handler
function (cb) {
file_handler.reset_freezr_environment(freezr_environment);
file_handler.init_custom_env(freezr_environment, (err)=>{
if(err) {
helpers.warning("server.js", exports.version,"startup_waterfall","failure to initialise custom environment - "+err);
}
cb(null);
});
},
// 3b - Check if can write to user folder (if 3a fails, 3b should fail too)
function (cb) {
file_handler.setup_file_sys(freezr_environment, (err) => {
if(err) {
helpers.warning("server.js", exports.version,"startup_waterfall","failure to create user directories - "+err);
}
cb(null);
})
},
// 3c - Check if can write to user folder (if 3b fails, 3c will fail too)
function (cb) {
file_handler.writeTextToUserFile ("userapps", "test_write.txt", "Testing write on server", {fileOverWrite:true}, null, null, freezr_environment, function (err) {
if(err) {
helpers.warning("server.js", exports.version,"startup_waterfall","failure to write to user folder - "+err);
} else {
console.log("3 - Can write to user folders")
}
freezrStatus.can_write_to_user_folder = err? false:true;
if (freezrStatus.can_write_to_user_folder && freezr_environment.env_on_db_only ){
// try re-writing freezr_environment.js on local environment if only existed on the db
fs.writeFile(file_handler.fullLocalPathToUserFiles("userfiles","freezr_environment.js"), "exports.params=" + JSON.stringify(freezr_environment), function(err) {
// only happens if using local file system and file has been corrupted. Other wise, if non local fs, then error is normal, so it is not caught
cb(null);
})
} else {
cb(null)
}
})
},
// 4 - Read and write freezr secrets if doesnt exist
function (cb) {
file_handler.requireFile("userfiles","freezr_secrets.js",freezr_environment, (err, secrets_onfile) => {
if (secrets_onfile) freezr_secrets=secrets_onfile;
if (has_cookie_in_environment()) { // override
freezr_secrets.params.session_cookie_secret = process.env.COOKIE_SECRET
}
if (!freezr_secrets.params.session_cookie_secret) {
freezr_secrets.params.session_cookie_secret = helpers.randomText(20)
}
add_app_uses();
if (!secrets_onfile && freezrStatus.can_write_to_user_folder) {
var file_text = has_cookie_in_environment()? "exports.params={}" : "exports.params=" + JSON.stringify(freezr_secrets.params);
file_handler.writeTextToUserFile ("userfiles", "freezr_secrets.js", file_text, {fileOverWrite:true}, null, null, freezr_environment, function (err) {
if(err) {
helpers.warning("server.js", exports.version, "startup_waterfall", "Stransge inconsistency writing files (freezr_secrets) onto server" )
}
cb(null)
});
} else {cb(null)}
})
},
// 5 - Get ip address for local network servers (currently not working - todo to review)
function (cb) {
freezrStatus.fundamentals_okay = get_all_okay_status(freezrStatus);
//onsole.log("require('os').hostname()"+require('os').hostname())
if (LISTEN_TO_LOCALHOST_ON_LOCAL) {
cb(null)
} else {
require('dns').lookup(require('os').hostname(), function (err, add, fam) {
// Priorities in choosing default address: 1. default ip from environment_defaults (if written) 2. localhost if relevant 3. address looked up.
freezr_environment.ipaddress = freezr_environment.ipaddress? freezr_environment.ipaddress: ((helpers.startsWith(add,"192.168") && LISTEN_TO_LOCALHOST_ON_LOCAL)? "localhost" :add);
console.warn("hostname currently not working - Once working: Would be running on local ip Address: "+freezr_environment.ipaddress);
cb(null);
})
}
},
// 6 Get freezr main preferences
function (cb) {
//onsole.log("get or set main prefs "+JSON.stringify(DEFAULT_PREFS))
if (freezrStatus.can_read_write_to_db){
db_handler.get_or_set_prefs(freezr_environment, "main_prefs", DEFAULT_PREFS, false ,function (err, main_prefs_on_db) {
freezr_prefs = main_prefs_on_db;
cb(err)
})
} else {cb (null)}
},
// reload visit_logger
function (cb) {
if (freezrStatus.can_read_write_to_db) {visit_logger.reloadDb(freezr_environment, cb)} else {cb(null)}
}],
function (err) {
if (err) console.log(" =================== Got err on start ups =================== ")
console.log("Startup checks complete.")
//onsole.log("freezr_prefs: ", freezr_prefs)
console.log("freezrStatus: ")
console.log(freezrStatus)
if (err) {
helpers.warning("server.js", exports.version, "startup_waterfall", "STARTUP ERR "+JSON.stringify(err) )
}
// st hack in case of change in port (eg heroku) - to do - make more elegant with env defaults
var theport = (process && process.env && process.env.PORT)? process.env.PORT : freezr_environment.port;
app.listen(theport) //, freezr_environment.ipaddress)
helpers.log (null,"Going to listen on port "+freezr_environment.port)
//onsole.log(freezr_environment)
console.log("Database : "+freezr_environment.dbParams.dbtype || "tbd")
console.log("File System: "+(freezr_environment.userDirParams.name || "local"))
}
)
| 54.20268 | 231 | 0.671529 |
e36cca19faf5e382ac5c285740f17eb35ecf8bae | 273 | js | JavaScript | docs/documentation/search/variables_15.js | akashkumarsingh612/pawpyseed | 6f5aa0b8ca8c28a0221e5256afeb939c3344560b | [
"BSD-3-Clause"
] | 26 | 2018-09-22T01:09:04.000Z | 2022-03-25T04:03:56.000Z | docs/documentation/search/variables_15.js | akashkumarsingh612/pawpyseed | 6f5aa0b8ca8c28a0221e5256afeb939c3344560b | [
"BSD-3-Clause"
] | 13 | 2020-01-17T18:19:43.000Z | 2020-12-22T22:23:40.000Z | docs/documentation/search/variables_15.js | akashkumarsingh612/pawpyseed | 6f5aa0b8ca8c28a0221e5256afeb939c3344560b | [
"BSD-3-Clause"
] | 7 | 2019-12-05T16:12:25.000Z | 2022-03-25T04:03:51.000Z | var searchData=
[
['x',['x',['../namespacepawpyseed_1_1core_1_1quadrature.html#ae4e7a512dfb8bbb88e9776e951e5c4c8',1,'pawpyseed.core.quadrature.x()'],['../namespacepawpyseed_1_1core_1_1rayleigh.html#a3e3052b17ec06a85da30ca178bc836b8',1,'pawpyseed.core.rayleigh.x()']]]
];
| 54.6 | 251 | 0.787546 |
e36d19b64fdf9868bf9ffcc8d301b8d31ca45956 | 15,347 | js | JavaScript | satellite-search-ui/js/ceda-eo-init.js | cedadev/ceda-map-uis | 2ac2d9c2aaa30fd72933e90584817beedca569cf | [
"BSD-3-Clause-Clear"
] | null | null | null | satellite-search-ui/js/ceda-eo-init.js | cedadev/ceda-map-uis | 2ac2d9c2aaa30fd72933e90584817beedca569cf | [
"BSD-3-Clause-Clear"
] | 5 | 2020-06-22T14:29:26.000Z | 2021-08-25T11:01:16.000Z | satellite-search-ui/js/ceda-eo-init.js | cedadev/ceda-map-uis | 2ac2d9c2aaa30fd72933e90584817beedca569cf | [
"BSD-3-Clause-Clear"
] | null | null | null | /*jslint browser: true, devel: true, sloppy: true*/
/*global google, $, GeoJSON*/
// Handles map drawing functions such as drawing the polygons on the map, listeners and handles the window.onload event.
function getParameterByName(name) {
// Function from: http://stackoverflow.com/a/901144
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'),
results = regex.exec(location.search);
if (!results) {
return null;
}
return decodeURIComponent(results[1].replace(/\+/g, ' '));
}
// Window constants
const ES_HOST = 'https://elasticsearch.ceda.ac.uk/'
var REQUEST_SIZE = 1000;
var INDEX = getParameterByName('index') || 'ceda-eo';
var ES_URL = ES_HOST + INDEX + '/_search';
var TRACK_COLOURS = [
'#B276B2', '#5DA5DA', '#FAA43A',
'#60BD68', '#F17CB0', '#B2912F',
'#4D4D4D', '#DECF3F', '#F15854'
];
var redraw_pause = false;
// based on the Track Colours
var COLOUR_MAP = {
"sentinel1": "#B276B2",
"sentinel2": "#5DA5DA",
"sentinel3": "#FAA43A",
"landsat": "#60BD68",
"other": "#F17CB0"
};
var export_modal_open = false;
// -----------------------------------String-----------------------------------
String.prototype.hashCode = function () {
// Please see: http://bit.ly/1dSyf18 for original
var i, c, hash;
hash = 0;
if (this.length === 0) {
return hash;
}
for (i = 0; i < this.length; i++) {
c = this.charCodeAt(i);
hash = ((hash << 5) - hash) + c;
}
return hash;
};
String.prototype.truncatePath = function (levels) {
// Removes 'levels' directories from a path, e.g.:
// '/usr/bin/path/to/something/useful'.truncatePath(3);
// => '/usr/bin/path
var parts, t_path;
parts = this.split('/');
t_path = parts.slice(0, parts.length - levels).join('/');
return t_path;
};
// Toggle text at top of the filters panel
function toggleText() {
var sliders = document.getElementsByClassName('slider')
for (var i = 0; i < sliders.length; i++) {
sliders[i].classList.toggle('closed')
}
var headerCollapse = document.getElementById('headCollapse');
var hCHTML = headerCollapse.innerHTML;
headerCollapse.innerHTML = hCHTML === 'Collapse Header' ? 'Expand Header' : 'Collapse Header'
}
// -----------------------------------Map--------------------------------------
var geometries = [];
var info_windows = [];
var quicklooks = [];
function centreMap(gmap, geocoder, loc) {
if (loc !== '') {
geocoder.geocode(
{
address: loc
},
function (results, status) {
if (status === 'OK') {
gmap.panTo(results[0].geometry.location);
} else {
alert('Could not find "' + loc + '"');
}
}
);
}
}
function colourSelect(mission) {
// Designates a colour to the polygons based on the satellite mission.
var colour;
switch (true) {
case /sentinel\W1.*/gi.test(mission):
colour = COLOUR_MAP['sentinel1'];
break;
case /sentinel\W2.*/gi.test(mission):
colour = COLOUR_MAP['sentinel2'];
break;
case /sentinel\W3.*/gi.test(mission):
colour = COLOUR_MAP['sentinel3'];
break;
case /landsat/gi.test(mission):
colour = COLOUR_MAP['landsat'];
break;
default:
colour = COLOUR_MAP['other'];
break;
}
return colour
}
function truncatePole(displayCoords) {
// Polygons drawn at the poles were wrapping round the globe as google maps mecator projection is limited to 85N/S.
// Function truncates coordinates to 85 N/S for drawing purposes.
var i, truncatedCoords = [];
var truncate = false;
displayCoords = displayCoords.coordinates[0];
for (i = 0; i < displayCoords.length; i++) {
var coords = displayCoords[i];
var last_coords;
if (coords[1] > 85) {
// If co-ordinate traverses >85 N, truncate to 85
coords[1] = 85.0;
// Only return the first co-ordinate to cross the threshold
if (!truncate) {
truncatedCoords.push(coords)
}
truncate = true;
// Store last coordinate to push when polygon re-enters threshold
if (truncate) {
last_coords = coords
}
} else if (coords[1] < -85) {
// If co-ordinate traverses < -85 S, truncate to -85
coords[1] = -85;
// Only return the first co-ordinate to cross the threshold
if (!truncate) {
truncatedCoords.push(coords)
}
truncate = true;
// Store last coordinate to push when polygon re-enters threshold
if (truncate) {
last_coords = coords
}
} else {
// On re-entry, push the last truncated co-ordinate as well as the current
// non-truncated coordinate
if (truncate) {
truncatedCoords.push(last_coords)
}
truncate = false;
truncatedCoords.push(coords)
}
}
truncatedCoords = [truncatedCoords];
return truncatedCoords
}
function drawFlightTracks(gmap, hits) {
// Add satellite scene polygons onto the map.
var colour_index, geom, hit, i, info_window, options, display;
// Clear old map drawings
cleanup();
// only need to pass to truncate filter if map is displaying region north/south of 70N/S
var mapBounds = gmap.getBounds();
var truncate;
if (mapBounds.getNorthEast().lat() > 70 || mapBounds.getSouthWest().lat() < -70) {
truncate = true
} else {
truncate = false
}
// Reverse the "hits" array because the ES response is ordered new - old and we want to draw the newest items on top.
hits.reverse();
for (i = 0; i < hits.length; i += 1) {
hit = hits[i];
hit = hits[i];
var mission = hit._source.misc.platform.Mission
options = {
strokeColor: colourSelect(mission),
strokeWeight: 5,
strokeOpacity: 0.6,
fillOpacity: 0.1,
zIndex: i
};
// Create GeoJSON object
display = hit._source.spatial.geometries.display;
// Truncate the polygon coordinates
if (truncate) {
display.coordinates = truncatePole(display)
}
// Create the polygon
geom = GeoJSON(display, options);
geom.setMap(gmap);
geometries.push(geom);
// Construct info window
info_window = createInfoWindow(hit);
info_windows.push(info_window);
}
for (i = 0; i < geometries.length; i += 1) {
google.maps.event.addListener(geometries[i], 'click',
(function (i, e, hits) {
return function (e, hits) {
var j;
google.maps.event.clearListeners(gmap, 'bounds_changed');
for (j = 0; j < info_windows.length; j += 1) {
info_windows[j].close();
}
info_windows[i].setPosition(e.latLng);
getQuickLook(info_windows[i], i);
info_windows[i].open(gmap, null);
window.setTimeout(function () {
addBoundsChangedListener(gmap);
}, 1000);
};
})(i));
}
}
function cleanup() {
// removes all map objects
var i;
for (i = 0; i < geometries.length; i += 1) {
geometries[i].setMap(null);
}
geometries = [];
for (i = 0; i < info_windows.length; i += 1) {
info_windows[i].close();
}
info_windows = [];
quicklooks = [];
}
function redrawMap(gmap, add_listener) {
var full_text, request;
// Draw flight tracks
// full_text = $('#ftext').val();
request = createElasticsearchRequest(gmap.getBounds(), full_text, REQUEST_SIZE);
sendElasticsearchRequest(request, updateMap, gmap);
if (add_listener === true) {
window.setTimeout(function () {
addBoundsChangedListener(gmap);
}, 1000);
}
}
function updateMap(response, gmap) {
if (response.hits) {
// Update "hits" and "response time" fields
$('#resptime').html(response.took);
let result_count_string = ''
// ES7 total response includes value and relation
if (response.hits.total.relation === 'gte'){
result_count_string = '>' + response.hits.total.value
} else {
result_count_string = response.hits.total.value
}
$('#numresults').html(result_count_string);
// Draw flight tracks on a map
drawFlightTracks(gmap, response.hits.hits);
// Toggle loading modal
if (!export_modal_open) {
displayLoadingModal()
}
}
if (response.aggregations) {
// Generate variable aggregation on map and display
updateTreeDisplay(response.aggregations, gmap);
}
}
function addBoundsChangedListener(gmap) {
google.maps.event.addListenerOnce(gmap, 'bounds_changed', function () {
if (window.rectangle === undefined)
redrawMap(gmap, true);
});
}
// ----------------------------- First Load --------------------------------
$('#applyfil').one('click', function(){
// When the user clicks apply filters for the first time. Make the map responsive.
addBoundsChangedListener(glomap)
});
// ------------------------------window.unload---------------------------------
// makes sure that the drawing tool is always off on page load.
window.unload = function() {
document.getElementById$('polygon_draw').checked = false
};
// ------------------------------window.onload---------------------------------
window.onload = function () {
var geocoder, lat, lon, map;
// Google Maps geocoder and map object
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(
document.getElementById('map-container').getElementsByClassName('map')[0],
{
mapTypeId: google.maps.MapTypeId.TERRAIN,
zoom: 3,
}
);
glomap = map
centreMap(map, geocoder, 'Lake Balaton, Hungary');
google.maps.event.addListener(map, 'mousemove', function (event) {
// Add listener to update mouse position
// see: http://bit.ly/1zAfter
lat = event.latLng.lat().toFixed(2);
lon = event.latLng.lng().toFixed(2);
$('#mouse').html('Lat: ' + lat + ', Lng: ' + lon);
});
// set map key colours
$('#sentinel1Key').css('border-color', COLOUR_MAP['sentinel1']);
$('#sentinel2Key').css('border-color', COLOUR_MAP['sentinel2']);
$('#sentinel3Key').css('border-color', COLOUR_MAP['sentinel3']);
$('#landsatKey').css('border-color', COLOUR_MAP['landsat']);
$('#otherKey').css('border-color', COLOUR_MAP['other']);
// Open welcome modal
var welcomeModal = $('#welcome_modal');
if (Storage !== undefined) {
// If HTML5 storage available
// If the modal has been closed this session do not display the modal
if (!sessionStorage.welcomeDismissed) {
welcomeModal.modal('show')
}
// When the welcome modal is closed, set the session welcomeDismissed to true to prevent showing the modal on
// page refresh during the same browser session.
welcomeModal.on('hidden.bs.modal', function () {
sessionStorage.welcomeDismissed = true
});
} else {
// HTML5 storage is not available, default to displaying the modal on every page load.
welcomeModal.modal('show')
}
//------------------------------- Buttons -------------------------------
$('#location_search').click(
function () {
centreMap(map, geocoder, $('#location').val());
}
);
$('#ftext').keypress(
function (e) {
var charcode = e.charCode || e.keyCode || e.which;
if (charcode === 13) {
if (window.rectangle !== undefined) {
queryRect(map);
} else {
redrawMap(map, false);
}
return false;
}
}
);
$('#location').keypress(
function (e) {
var charcode = e.charCode || e.keyCode || e.which;
if (charcode === 13) {
centreMap(map, geocoder, $('#location').val());
return false;
}
}
);
$('#applyfil').click(
function () {
if (window.rectangle !== undefined) {
queryRect(map);
} else {
redrawMap(map, false);
}
}
);
$('#clearfil').click(
function () {
var tree_menu = $('#tree_menu');
$('#start_time').val('');
$('#end_time').val('');
$('#ftext').val('');
if (window.rectangle !== undefined) {
clearRect();
}
// Clear the map of objects and initialise the tree to clear the badges.
cleanup()
sendElasticsearchRequest(treeRequest(), initTree, false);
// Check all the options in the tree and make sure they are selected.
// Checked state has to match selected state.
if (tree_menu.treeview('getUnselected').length > 0) {
tree_menu.treeview('checkAll', { silent: true})
var unselected = tree_menu.treeview('getUnselected'), i;
for (i = 0; i < unselected.length; i++){
tree_menu.treeview('selectNode', [ unselected[i].nodeId, {silent: true}])
}
}
// Make sure the rectangle drawing tool is deactivated.
$('#polygon_draw').prop('checked', false).change()
}
);
//----------------------------- UI Widgets -------------------------------
// initialise the treeview
$('#tree_menu').treeview({
data: {},
showBorder: false
});
// Kick off help text popovers
// http://stackoverflow.com/a/18537617
$('span[data-toggle="popover"]').popover({
'trigger': 'hover'
});
// Datepicker
var picker = $('#datepicker').datepicker({
autoclose: true,
format: 'yyyy-mm-dd',
startView: 2
});
// Draw histogram
sendHistogramRequest();
// Add rectangle toggle listener
$('#polygon_draw').change(rectToolToggle)
//---------------------------- Map main loop ------------------------------
google.maps.event.addListenerOnce(map, 'tilesloaded', function () {
// init Tree
var bounds, tmp_ne, tmp_sw, nw, se, request;
bounds = map.getBounds();
tmp_ne = bounds.getNorthEast();
tmp_sw = bounds.getSouthWest();
nw = [tmp_sw.lng(), tmp_ne.lat()];
se = [tmp_ne.lng(), tmp_sw.lat()];
sendElasticsearchRequest(treeRequest(), initTree, false);
});
};
| 29.570328 | 121 | 0.534502 |
e36d3aa4eb1704219dc2b3ce1ae0f5fdbf1a2fd1 | 211 | js | JavaScript | src/api/score.js | lsybrenda/vue-manage-system | 700ba9c9fd638291cdfe5debe0dabfc0ebf75569 | [
"MIT"
] | null | null | null | src/api/score.js | lsybrenda/vue-manage-system | 700ba9c9fd638291cdfe5debe0dabfc0ebf75569 | [
"MIT"
] | null | null | null | src/api/score.js | lsybrenda/vue-manage-system | 700ba9c9fd638291cdfe5debe0dabfc0ebf75569 | [
"MIT"
] | null | null | null | import request from '../utils/request';
import qs from 'qs';
export const fetchData = query => {
return request({
url: '/score/getCandidates/',
method: 'get',
params: query
});
} | 21.1 | 39 | 0.578199 |
e36d5749a846abb287f00877f7ec7d979fe610d8 | 2,620 | js | JavaScript | app/containers/FlightsPage/index.js | natanr123/blue-ribbon-assignment-flights | cc4a4b14cf31e1016bee8cf18f2f61ad8ef0c034 | [
"MIT"
] | null | null | null | app/containers/FlightsPage/index.js | natanr123/blue-ribbon-assignment-flights | cc4a4b14cf31e1016bee8cf18f2f61ad8ef0c034 | [
"MIT"
] | null | null | null | app/containers/FlightsPage/index.js | natanr123/blue-ribbon-assignment-flights | cc4a4b14cf31e1016bee8cf18f2f61ad8ef0c034 | [
"MIT"
] | null | null | null | /* eslint-disable react/prop-types */
import React from 'react';
import { Helmet } from 'react-helmet';
import { compose } from 'redux';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import injectReducer from 'utils/injectReducer';
import FlightsService from 'services/FlightsService';
import {
FilteringState,
IntegratedFiltering,
} from '@devexpress/dx-react-grid';
import {
Grid,
Table,
TableHeaderRow,
TableFilterRow,
} from '@devexpress/dx-react-grid-material-ui';
import reducer from './reducer';
import * as actions from './actions';
/* eslint-disable react/prefer-stateless-function */
export class FlightsPage extends React.PureComponent {
componentDidMount() {
this.loadFlights();
}
loadFlights() {
const flights = FlightsService.list();
this.props.flightsLoaded(flights);
}
clearFlights() {
FlightsService.clear();
const flights = FlightsService.list();
this.props.flightsLoaded(flights);
}
render() {
return (
<article>
<Helmet>
<title>FlightsPage</title>
<meta
name="description"
content="FlightsPage"
/>
</Helmet>
<div>
<h1>Flights</h1>
</div>
<button onClick={() => { this.clearFlights(); }}>Clear Flights</button>
<a href={'/new'}>Create New Flight</a>
{this.props.flights ?
<Grid
rows={this.props.flights}
columns={[
{ name: 'from', title: 'From' },
{ name: 'to', title: 'To' },
{ name: 'departureTime', title: 'Departure Time' },
{ name: 'landingTime', title: 'Landing Time' },
{ name: 'price', title: 'Price' },
]}
>
<FilteringState defaultFilters={[]} />
<IntegratedFiltering />
<Table />
<TableHeaderRow />
<TableFilterRow />
</Grid> : <p> No Flights Data </p>
}
</article>
);
}
}
export function mapDispatchToProps(dispatch) {
return {
flightsLoaded: (arr) => {
dispatch(actions.flightsLoaded(arr));
},
};
}
const mapStateToProps = (state) => {
const flightsState = state.get('flights');
return {
flights: flightsState.get('flights'),
};
};
FlightsPage.propTypes = {
flightsLoaded: PropTypes.func,
flights: PropTypes.any,
};
const withConnect = connect(
mapStateToProps,
mapDispatchToProps,
);
const withReducer = injectReducer({ key: 'flights', reducer });
export default compose(
withReducer,
withConnect,
)(FlightsPage);
| 24.485981 | 79 | 0.59542 |
e36e0354e1e6b441953a8ca72daaceb462fda4d6 | 1,008 | js | JavaScript | src/components/EmployeeCreate.js | Reyhanahmed/RN_EmployeeManager | 6762c3037cd2143b4fde7376caa07926122df3b1 | [
"MIT"
] | null | null | null | src/components/EmployeeCreate.js | Reyhanahmed/RN_EmployeeManager | 6762c3037cd2143b4fde7376caa07926122df3b1 | [
"MIT"
] | null | null | null | src/components/EmployeeCreate.js | Reyhanahmed/RN_EmployeeManager | 6762c3037cd2143b4fde7376caa07926122df3b1 | [
"MIT"
] | null | null | null | import React, { Component } from 'react';
import { Card, CardSection, Button} from './common';
import { connect } from 'react-redux';
import { employeeCreate } from '../actions';
import EmployeeForm from './EmployeeForm';
class EmployeeCreate extends Component{
constructor(props){
super(props);
}
onButtonPress(){
const { name, phone, shift } = this.props;
this.props.onPress({ name, phone, shift: shift || 'Monday' });
}
render(){
return(
<Card>
<EmployeeForm {...this.props} />
<CardSection>
<Button onPress={this.onButtonPress.bind(this)}>
Create
</Button>
</CardSection>
</Card>
);
}
}
function mapStateToProps(state) {
const { name, phone, shift } = state.employeeForm;
return { name, phone, shift};
}
function mapDispatchToProps(dispatch) {
return {
onPress: ({ name, phone, shift }) => {
dispatch(employeeCreate({ name, phone, shift }));
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(EmployeeCreate); | 20.16 | 76 | 0.656746 |
e36f479d4ee038a2d723f4948fdfd86f253394b2 | 3,991 | js | JavaScript | js/script.js | javierlona/to-do-list | 3a7ea98c56f65d709c1c84cc464e1773093d4223 | [
"MIT"
] | null | null | null | js/script.js | javierlona/to-do-list | 3a7ea98c56f65d709c1c84cc464e1773093d4223 | [
"MIT"
] | null | null | null | js/script.js | javierlona/to-do-list | 3a7ea98c56f65d709c1c84cc464e1773093d4223 | [
"MIT"
] | null | null | null | // Constant variables
const FORM = document.querySelector('#addForm');
const TASKLIST = document.querySelector('.list-group');
const FILTER = document.querySelector('#filter');
// Event listeners
FORM.addEventListener('submit', add_task, false);
TASKLIST.addEventListener('click', remove_task, false);
FILTER.addEventListener('keyup', filter_tasks, false);
function get_existing_tasks(){
let tasks;
// Check if tasks are already stored
if(localStorage.getItem('tasks') === null){
tasks = [];
}
else{
// Set tasks with what's already there
tasks = JSON.parse(localStorage.getItem('tasks'));
}
return tasks;
}
// domcontentloaded event not firing, hence an IIFE function
document.addEventListener('DOMContentLoaded', function () {
// Fires each time page is refreshed
tasks = get_existing_tasks();
// Loop to create the DOM elements to display
tasks.forEach(function(task) {
// Get input value
let newTask = document.createTextNode(task);
// Create new li element
let liElement = document.createElement('li');
// Create delete button element
let deleteBTN = document.createElement('button');
// Add classes
liElement.className = 'list-group-item';
deleteBTN.className = 'btn btn-danger btn-lg float-right delete';
deleteBTN.innerHTML = '<i class="fas fa-trash-alt"></i>';
// Add to DOM Tree from outside in
TASKLIST.append(liElement);
liElement.append(newTask);
liElement.append(deleteBTN);
})
}());
function add_task(event){
event.preventDefault();
// Get input value
let newTask = document.querySelector('#task').value;
// Create new li element
let liElement = document.createElement('li');
// Create delete button element
let deleteBTN = document.createElement('button');
// Add classes
liElement.className = 'list-group-item';
deleteBTN.className = 'btn btn-danger btn-lg float-right delete';
deleteBTN.innerHTML = '<i class="fas fa-trash-alt"></i>';
// Add to DOM Tree from outside in
TASKLIST.append(liElement);
liElement.append(newTask);
liElement.append(deleteBTN);
// Call function add task to local storage
store_in_local_storage(newTask);
// Clear input filed(s) on form submit
FORM.reset();
}
function store_in_local_storage(task){
tasks = get_existing_tasks();
// Add task to tasks array
tasks.push(task);
/* You can only store string values in localStorage.
You'll need to serialize the array object and
then store it in localStorage.
*/
localStorage.setItem('tasks', JSON.stringify(tasks))
}
function remove_task(event) {
if(event.target.classList.contains('delete')){
if(confirm("Are you sure?")){
let delLiTask = event.target.parentElement;
TASKLIST.removeChild(delLiTask);
// Remove from Local Storage
remove_task_from_local_storage(delLiTask);
}
}
}
function remove_task_from_local_storage(delLiTask){
tasks = get_existing_tasks();
// Go through each task in localStorage
tasks.forEach(function(task, index){
// Determine if selected task matches one in the array
if(delLiTask.textContent === task){
// Remove selected task from the tasks array
tasks.splice(index, 1);
}
});
// Add the remaining tasks to localStorage
localStorage.setItem('tasks', JSON.stringify(tasks));
}
function filter_tasks(event) {
// Grab and convert to lowercase the users search term
let text = event.target.value.toLowerCase();
// Select all the li tasks
let tasks = TASKLIST.querySelectorAll('li');
// Create an array of the tasks and traverse them
let tasksArray = Array.from(tasks);
for (let i = 0; i < tasksArray.length; i++) {
let taskName = tasksArray[i].firstChild.textContent;
// Check if it's a match
if(taskName.toLowerCase().indexOf(text) != -1){
// Display task
tasksArray[i].style.display = 'block';
}
else{
// Don't display task
tasksArray[i].style.display = 'none';
}
}
}
| 30.234848 | 69 | 0.695064 |
e3708c2fe9559ca3e36db4455a430cf3b7472204 | 3,377 | js | JavaScript | gulpfile.js | lvillasante/calendar-js | 953942ada1aff4719ed7909ec420dbc5a5ce5880 | [
"MIT"
] | null | null | null | gulpfile.js | lvillasante/calendar-js | 953942ada1aff4719ed7909ec420dbc5a5ce5880 | [
"MIT"
] | null | null | null | gulpfile.js | lvillasante/calendar-js | 953942ada1aff4719ed7909ec420dbc5a5ce5880 | [
"MIT"
] | null | null | null | var gulp = require("gulp"),
concat = require('gulp-concat'),
plumber = require("gulp-plumber"),
rename = require('gulp-rename'),
gulpsass = require('gulp-sass'),
autoprefixer = require('gulp-autoprefixer'),
cleanCss = require("gulp-clean-css"),
sourcemaps = require("gulp-sourcemaps"),
notify = require("gulp-notify"),
size = require('gulp-size'),
browserSync = require('browser-sync').create();
// Define paths variables
var DEST = 'dist/';
var SRC = 'src/';
var PROY = 'calendar-lvillasante.css';
var onError = function(err){
console.log("Se ha producido un error:", err.message);
this.emit("end");
}
// TODO: Maybe we can simplify how sass compile the minify and unminify version
gulp.task("sass", function(){
return gulp.src(SRC+"/sass/*.scss")
.pipe(plumber({errorHandler:onError}))
.pipe(sourcemaps.init())
.pipe(gulpsass())
.pipe(autoprefixer('last 2 versions', '> 5%'))
.pipe(concat(PROY))
.pipe(gulp.dest(DEST+'css'))
.pipe(sourcemaps.write("."))
.pipe(gulp.dest(DEST+'css'))
.pipe(notify({message:"Task SASS finalizado"}))
.pipe(browserSync.stream());
});
gulp.task("css-min", function(){
return gulp.src(DEST+"css/"+PROY)
.pipe(plumber({errorHandler:onError}))
.pipe(sourcemaps.init())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest(DEST+'css'))
.pipe(cleanCss())
.pipe(gulp.dest(DEST+'css'))
.pipe(sourcemaps.write("."))
.pipe(gulp.dest(DEST+'css'))
.pipe(size())
.pipe(notify({message:"Task CSS-MIN finalizado"}))
.pipe(browserSync.stream());
});
gulp.task('directories', function () {
return gulp.src('*.*', {read: false})
.pipe(gulp.dest(DEST+'./css'))
.pipe(gulp.dest(DEST+'./img'))
// .pipe(gulp.dest(DEST+'./fonts'))
.pipe(gulp.dest(DEST+'./js'));
});
// Copy CSS Styles
gulp.task('copy-css', function () {
gulp.src([
'./src/assets/css/css-reset.css',
])
.pipe(gulp.dest(DEST+'css/'));
});
// Copy Js
gulp.task('copy-js', function () {
gulp.src([
'./node_modules/moment/min/moment.min.js',
'./src/assets/js/es.js',
'./src/assets/js/calendar.js',
])
.pipe(gulp.dest(DEST+'js/'));
});
// Copy images
gulp.task('copy-img', function () {
// gulp.src(SRC+'img/**/*')
// .pipe(gulp.dest(DEST+'img/'));
return gulp.src(SRC+'assets/img/**/*')
.pipe(gulp.dest(DEST+'img'))
.pipe(size());
});
// FontAwesome
// gulp.task('copy-fonts', function() {
// return gulp.src(['./node_modules/font-awesome/fonts/fontawesome-webfont.*'])
// .pipe(gulp.dest(DEST+'fonts/'));
// });
gulp.task('browser-sync', function() {
browserSync.init({
server: {
baseDir: './'
},
// startPath: './production/index.html'
startPath: DEST+'index.html'
});
});
gulp.task('watch', function() {
// Watch .html files
gulp.watch(DEST + '*.html', browserSync.reload);
// Watch .js files
// gulp.watch('src/js/**/*.js', ['scripts']);
// Watch .scss files
gulp.watch(SRC+'sass/*.scss', ['sass', 'css-min']);
gulp.watch(DEST+'css/*.css', ['css-min']);
});
// Build
gulp.task('build', ['directories', 'copy-css', 'copy-js', 'copy-img', 'sass', 'css-min']);
// Default Task
gulp.task('default', ['browser-sync', 'watch']);
| 27.680328 | 90 | 0.579805 |
e3723aeae74a0d42cfb28d3ba3b4f5cdb7bd7805 | 1,214 | js | JavaScript | lib/manager/containers/ActiveProjectsList.js | 5Tsrl/TransitCafe | 5d49304fb42ce7278b819b40b5f16c58a4c7348b | [
"MIT"
] | null | null | null | lib/manager/containers/ActiveProjectsList.js | 5Tsrl/TransitCafe | 5d49304fb42ce7278b819b40b5f16c58a4c7348b | [
"MIT"
] | 6 | 2017-07-14T13:41:01.000Z | 2017-07-19T14:14:50.000Z | lib/manager/containers/ActiveProjectsList.js | 5Tsrl/TransitCafe | 5d49304fb42ce7278b819b40b5f16c58a4c7348b | [
"MIT"
] | null | null | null | import { connect } from 'react-redux'
import { fetchProjects, updateProject, createProject, saveProject } from '../actions/projects'
import { setVisibilitySearchText } from '../actions/visibilityFilter'
import ProjectsList from '../components/ProjectsList'
const mapStateToProps = (state, ownProps) => {
return {
projects: state.projects.all ? state.projects.all.filter(p => p.isCreating || state.user.permissions.isApplicationAdmin() || state.user.permissions.hasProject(p.id, p.organizationId)) : [],
visibilitySearchText: state.projects.filter.searchText,
user: state.user
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onComponentMount: (initialProps) => {
dispatch(setVisibilitySearchText(null))
dispatch(fetchProjects())
},
onNewProjectClick: (project) => dispatch(createProject(project)),
saveProject: (project) => dispatch(saveProject(project)),
projectNameChanged: (project, name) => dispatch(updateProject(project, {name})),
searchTextChanged: (text) => dispatch(setVisibilitySearchText(text))
}
}
const ActiveProjectsList = connect(
mapStateToProps,
mapDispatchToProps
)(ProjectsList)
export default ActiveProjectsList
| 35.705882 | 193 | 0.737232 |
e37259bdb80d4fcfbe3150eb554f572edb4c9399 | 3,645 | js | JavaScript | app/src/App/Plugins/Standard/EventLog/EventLogVirtualList.js | clangen/piggy | 1b630a8305fcbe48e993bb62510ccc12b1c7168a | [
"MIT"
] | null | null | null | app/src/App/Plugins/Standard/EventLog/EventLogVirtualList.js | clangen/piggy | 1b630a8305fcbe48e993bb62510ccc12b1c7168a | [
"MIT"
] | null | null | null | app/src/App/Plugins/Standard/EventLog/EventLogVirtualList.js | clangen/piggy | 1b630a8305fcbe48e993bb62510ccc12b1c7168a | [
"MIT"
] | null | null | null | import React from 'react';
import PropTypes from 'prop-types';
import AutoSizer from 'react-virtualized-auto-sizer';
import { css } from 'aphrodite/no-important';
import VirtualList, {
CURRENT_VIRTUAL_LIST_TYPE,
VIRTUAL_LIST_TYPE,
} from '@widgets/VirtualList';
import styles from './EventLogStyles';
const EventLogVirtualList = React.memo(
({
itemType: ItemType,
eventHandler,
events,
count,
selectedItemId,
markedItems,
highlightedItems,
disablePinToBottom,
pinToBottomChanged,
overscanCount,
innerWrapperStyle = {},
outerWrapperStyle = {},
}) => {
if (CURRENT_VIRTUAL_LIST_TYPE === VIRTUAL_LIST_TYPE.VIRTUOSO) {
const renderVirtuosoItem = (index) => (
<ItemType
rowClicked={eventHandler.rowClicked}
chipClicked={eventHandler.chipClicked}
markerClicked={eventHandler.markerClicked}
urlClicked={eventHandler.urlClicked}
markedItems={markedItems}
highlightedItems={highlightedItems}
selectedItemId={selectedItemId}
index={index}
data={events}
/>
);
return (
<div className={css(styles.mainContainer)} style={outerWrapperStyle}>
<div className={css(styles.list)} style={innerWrapperStyle}>
<AutoSizer>
{({ height, width }) => (
<VirtualList
ref={eventHandler.setVirtualListRef}
style={{ width, height }}
totalCount={count}
item={renderVirtuosoItem}
onPinChanged={pinToBottomChanged}
disablePinToBottom={disablePinToBottom}
overscanCount={overscanCount}
/>
)}
</AutoSizer>
</div>
</div>
);
}
return (
<div className={css(styles.mainContainer)} style={outerWrapperStyle}>
<div className={css(styles.list)} style={innerWrapperStyle}>
<AutoSizer>
{({ height, width }) => (
<VirtualList
ref={eventHandler.setVirtualListRef}
itemType={ItemType}
itemData={events}
itemCount={count}
itemProps={{
rowClicked: eventHandler.rowClicked,
chipClicked: eventHandler.chipClicked,
markerClicked: eventHandler.markerClicked,
urlClicked: eventHandler.urlClicked,
selectedItemId,
markedItems,
highlightedItems,
}}
width={width}
height={height}
overscanCount={overscanCount}
onPinChanged={pinToBottomChanged}
disablePinToBottom={disablePinToBottom}
/>
)}
</AutoSizer>
</div>
</div>
);
}
);
EventLogVirtualList.propTypes = {
itemType: PropTypes.object.isRequired,
eventHandler: PropTypes.object.isRequired,
events: PropTypes.array.isRequired,
count: PropTypes.number.isRequired,
selectedItemId: PropTypes.number.isRequired,
markedItems: PropTypes.object.isRequired,
highlightedItems: PropTypes.object.isRequired,
disablePinToBottom: PropTypes.bool.isRequired,
pinToBottomChanged: PropTypes.func,
overscanCount: PropTypes.number,
innerWrapperStyle: PropTypes.object,
outerWrapperStyle: PropTypes.object,
};
EventLogVirtualList.defaultProps = {
pinToBottomChanged: undefined,
overscanCount: 64,
innerWrapperStyle: {},
outerWrapperStyle: {},
};
export default EventLogVirtualList;
| 30.889831 | 77 | 0.603018 |
e373bf6be5ce323781120d3fc000e80221cd1c55 | 780 | js | JavaScript | chapter2/12-observer-pattern/emitter_example.js | Andrew4d3/njsdp-notes | 1c69d9b5e0d78fdb9d1c9ddf44b95dcb239d6e65 | [
"MIT"
] | null | null | null | chapter2/12-observer-pattern/emitter_example.js | Andrew4d3/njsdp-notes | 1c69d9b5e0d78fdb9d1c9ddf44b95dcb239d6e65 | [
"MIT"
] | null | null | null | chapter2/12-observer-pattern/emitter_example.js | Andrew4d3/njsdp-notes | 1c69d9b5e0d78fdb9d1c9ddf44b95dcb239d6e65 | [
"MIT"
] | null | null | null | // Page 50
// This does not follow the same aproach described by the book.
// Instead, it's using the ES6 class and extends keywords to get language level inheritance support
var EventEmitter = require('events');
class NumberProcessor extends EventEmitter {
constructor() {
super();
}
run() {
var self = this;
setInterval(function () {
var numb = parseInt(Math.random()*1000);
if (numb % 2 == 0) {
self.emit('even', numb);
}
else {
self.emit('odd', numb);
}
}, 2000);
}
}
var numberProcessor = new NumberProcessor();
numberProcessor.on('even', function (numb) {
console.log(numb + " is even");
});
numberProcessor.on('odd', function (numb) {
console.log(numb + " is odd");
});
numberProcessor.run();
| 21.666667 | 99 | 0.621795 |
e373feda6d05ca027e7a77db194763a3ae7c304a | 2,049 | js | JavaScript | packages/family-tree-app-client/src/containers/Login.js | MUAS-DTLab-WiSe19-20-Alexa-Demenz/WiSe19-20-Alexa-Demenz-WieHeisst | e18157603adcd347dee2e105c42c1cf1a5a8db31 | [
"Apache-2.0"
] | null | null | null | packages/family-tree-app-client/src/containers/Login.js | MUAS-DTLab-WiSe19-20-Alexa-Demenz/WiSe19-20-Alexa-Demenz-WieHeisst | e18157603adcd347dee2e105c42c1cf1a5a8db31 | [
"Apache-2.0"
] | null | null | null | packages/family-tree-app-client/src/containers/Login.js | MUAS-DTLab-WiSe19-20-Alexa-Demenz/WiSe19-20-Alexa-Demenz-WieHeisst | e18157603adcd347dee2e105c42c1cf1a5a8db31 | [
"Apache-2.0"
] | null | null | null | import React, { useState } from "react";
import { Button, Card, Form, Alert } from "react-bootstrap";
import { Auth } from "aws-amplify";
import "./Login.css";
export default function Login(props) {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [notYetConfirmed, setNotYetConfirmed] = useState(false);
function validateForm() {
return email.length > 0 && password.length > 0;
}
async function handleSubmit(event) {
event.preventDefault();
setIsLoading(true);
try {
const user = await Auth.signIn(email, password);
if (user.challengeName === 'NEW_PASSWORD_REQUIRED') {
props.history.push("/new-password");
} else {
props.userHasAuthenticated(true);
props.history.push("/persons");
}
} catch (e) {
if (e.code === 'UserNotConfirmedException') {
setNotYetConfirmed(true);
}
console.log(e.message);
setIsLoading(false);
}
}
return (
<div className="Login">
<Form onSubmit={handleSubmit}>
<Card><Card.Body>
<Form.Group controlId="email" bsSize="large">
<Form.Label>Email</Form.Label>
<Form.Control
autoFocus
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
/>
</Form.Group>
<Form.Group controlId="password" bsSize="large">
<Form.Label>Password</Form.Label>
<Form.Control
value={password}
onChange={e => setPassword(e.target.value)}
type="password"
/>
</Form.Group>
{notYetConfirmed ? <Alert variant={"danger"}>You are not yet confirmed!</Alert> : null}
<Button block bsSize="large" disabled={!validateForm() || isLoading} type="submit">
{isLoading ? 'Loading…' : 'Login'}
</Button></Card.Body>
</Card>
</Form>
</div>
);
} | 30.58209 | 97 | 0.569546 |
e3744109842cb5fb174bbc1e9622dd5bb3cf3e68 | 1,064 | js | JavaScript | act/helpers/mk-doc/index.js | imaginate/vitals | a54e7c70f3e958b61fb3fbcaffa2679ad2c1faf4 | [
"Apache-2.0"
] | 3 | 2015-12-06T20:56:58.000Z | 2016-04-14T22:43:29.000Z | act/helpers/mk-doc/index.js | imaginate/algorithmIV-javascript-shortcuts | a54e7c70f3e958b61fb3fbcaffa2679ad2c1faf4 | [
"Apache-2.0"
] | null | null | null | act/helpers/mk-doc/index.js | imaginate/algorithmIV-javascript-shortcuts | a54e7c70f3e958b61fb3fbcaffa2679ad2c1faf4 | [
"Apache-2.0"
] | 1 | 2017-12-04T15:08:51.000Z | 2017-12-04T15:08:51.000Z | /**
* -----------------------------------------------------------------------------
* ACT TASK HELPER: mkDoc
* -----------------------------------------------------------------------------
* @author Adam Smith <adam@imaginate.life> (https://github.com/imaginate)
* @copyright 2017 Adam A Smith <adam@imaginate.life> (https://github.com/imaginate)
*
* Annotations:
* @see [JSDoc3](http://usejsdoc.org)
* @see [Closure Compiler JSDoc Syntax](https://developers.google.com/closure/compiler/docs/js-for-compiler)
*/
'use strict';
var mkHeader = require('./mk-header');
var mkBody = require('./mk-body');
var mkFooter = require('./mk-footer');
/**
* @param {string} content
* @param {string=} fscontent
* @return {string}
*/
module.exports = function mkDoc(content, fscontent) {
/** @type {string} */
var header;
/** @type {string} */
var footer;
/** @type {string} */
var body;
header = mkHeader(content, fscontent);
body = mkBody(content, fscontent);
footer = mkFooter(content, fscontent);
return header + body + footer;
};
| 28 | 108 | 0.558271 |
e3749d6c38b57bab1b2b86a36c968689753489c8 | 2,408 | js | JavaScript | tm-aspect-div-css.js | tmcmaster/tm-aspect-div | f190471e88946d601747cf84fcfe799cead7b210 | [
"MIT"
] | null | null | null | tm-aspect-div-css.js | tmcmaster/tm-aspect-div | f190471e88946d601747cf84fcfe799cead7b210 | [
"MIT"
] | null | null | null | tm-aspect-div-css.js | tmcmaster/tm-aspect-div | f190471e88946d601747cf84fcfe799cead7b210 | [
"MIT"
] | null | null | null | import {html, PolymerElement} from '@polymer/polymer/polymer-element.js';
/**
* `tm-aspect-div`
* Polymer web component container that maintains an aspect ratio.
*
* @customElement
* @polymer
* @demo demo/index.html
*/
class TmAspectDivCSS extends PolymerElement {
static get template() {
return html`
<style>
:host {
width:100%;
height:100%;
display: flex;
justify-content: center;
align-items: center;
border: solid blue 2px;
}
.cell {
box-sizing: border-box;
border: solid green 2px;
width: 100%;
}
.wrapper-with-intrinsic-ratio {
position: relative;
padding-bottom: 20%;
height: 0;
border: solid red 2px;
box-sizing: border-box;
}
.element-to-stretch {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: teal;
}
.aspectRatioSizer {
display: grid;
}
.aspectRatioSizer > * {
grid-area: 1 / 1 / 2 / 2;
}
.content {
width: 200px;
height: 200px;
border: solid teal 2px;
}
</style>
<div class="aspectRatioSizer">
<!--<svg viewBox="0 0 7 2"></svg>-->
<div>
<div class="content">Content goes here</div>
</div>
</div>
<!--<div class="cell">-->
<!--<div class="wrapper-with-intrinsic-ratio">-->
<!--<div class="element-to-stretch">-->
<!--<slot></slot>-->
<!--</div>-->
<!--</div>-->
<!--</div>-->
`;
}
static get properties() {
return {};
}
ready() {
super.ready();
}
}
window.customElements.define('tm-aspect-div-css', TmAspectDivCSS);
| 28.329412 | 73 | 0.376246 |
e37599ac16ca3305264be37f2661ae2c951ec381 | 528 | js | JavaScript | js/editor/editor.js | Rrayor/m-editor | 832a4ad180342aa8ce2b71efc12161c3f8ed2d8a | [
"MIT"
] | null | null | null | js/editor/editor.js | Rrayor/m-editor | 832a4ad180342aa8ce2b71efc12161c3f8ed2d8a | [
"MIT"
] | null | null | null | js/editor/editor.js | Rrayor/m-editor | 832a4ad180342aa8ce2b71efc12161c3f8ed2d8a | [
"MIT"
] | null | null | null | const paper = document.getElementById('page')
const validCommands = [
'bold',
'italic',
'underline',
'fontSize'
]
const isValidCommand = command => {
return validCommands.contains(command)
}
export const execute = (command, value = null) => {
if (!isValidCommand) {
console.error(`${command} is not a valid command`)
return false
}
if (!value) {
document.execCommand(command)
return true
}
document.execCommand(command, false, value)
return true
} | 19.555556 | 58 | 0.621212 |
e375fa4ca080e21e1876468f0306e0a96bc5ea20 | 3,207 | js | JavaScript | lib/plugins/helper/tag.js | kuetemeier/hexo | c28ac17ba8ff88118b07aeb7b74b397dc2bb78e8 | [
"MIT"
] | 1 | 2015-01-16T07:31:09.000Z | 2015-01-16T07:31:09.000Z | lib/plugins/helper/tag.js | kuetemeier/hexo | c28ac17ba8ff88118b07aeb7b74b397dc2bb78e8 | [
"MIT"
] | null | null | null | lib/plugins/helper/tag.js | kuetemeier/hexo | c28ac17ba8ff88118b07aeb7b74b397dc2bb78e8 | [
"MIT"
] | null | null | null | var _ = require('lodash'),
pathFn = require('path'),
url = require('url'),
qs = require('querystring'),
util = require('../../util'),
htmlTag = util.html_tag;
var mergeAttrs = function(options, attrs){
if (options.class){
var classes = options.class;
if (Array.isArray(classes)){
attrs.class = classes.join(' ');
} else {
attrs.class = classes;
}
}
if (options.id) attrs.id = options.id;
};
exports.css = function(){
var args = _.flatten(_.toArray(arguments)),
config = this.config || hexo.config,
root = config.root,
str = '',
self = this;
args.forEach(function(path){
if (pathFn.extname(path) !== '.css') path += '.css';
str += htmlTag('link', {rel: 'stylesheet', href: self.url_for(path), type: 'text/css'}) + '\n';
});
return str;
};
exports.js = function(){
var args = _.flatten(_.toArray(arguments)),
config = this.config || hexo.config,
root = config.root,
str = '',
self = this;
args.forEach(function(path){
if (pathFn.extname(path) !== '.js') path += '.js';
str += htmlTag('script', {src: self.url_for(path), type: 'text/javascript'}, '') + '\n';
});
return str;
};
exports.link_to = function(path, text, options){
if (typeof options === 'boolean') options = {external: options};
options = _.extend({
external: false,
class: '',
id: ''
}, options);
if (!text) text = path.replace(/^https?:\/\//, '');
var attrs = {
href: this.url_for(path),
title: text
};
mergeAttrs(options, attrs);
if (options.external){
attrs.target = '_blank';
attrs.rel = 'external';
}
return htmlTag('a', attrs, text);
};
exports.mail_to = function(path, text, options){
options = _.extend({
class: '',
id: '',
subject: '',
cc: '',
bcc: '',
body: ''
}, options);
if (Array.isArray(path)) path = path.join(',');
if (!text) text = path;
var attrs = {
href: 'mailto:' + path,
title: text
};
mergeAttrs(options, attrs);
var data = {};
['subject', 'cc', 'bcc', 'body'].forEach(function(i){
var item = options[i];
if (options[i]){
data[i] = Array.isArray(item) ? item.join(',') : item;
}
});
var querystring = qs.stringify(data);
if (querystring) attrs.href += '?' + querystring;
return htmlTag('a', attrs, text);
};
exports.image_tag = function(path, options){
options = _.extend({
alt: '',
class: '',
id: '',
width: 0,
height: 0
}, options);
var attrs = {
src: this.url_for(path)
};
mergeAttrs(options, attrs);
['alt', 'width', 'height'].forEach(function(i){
if (options[i]) attrs[i] = options[i];
});
return htmlTag('img', attrs);
};
exports.favicon_tag = function(path){
return htmlTag('link', {
rel: 'shortcut icon',
href: this.url_for(path)
});
};
exports.feed_tag = function(path, options){
var config = this.config || hexo.config;
options = _.extend({
title: config.title,
type: 'atom'
}, options);
var attrs = {
rel: 'alternative',
href: this.url_for(path),
title: options.title,
type: 'application/' + options.type + '+xml'
};
return htmlTag('link', attrs);
}; | 19.919255 | 99 | 0.570939 |
e3762eb20c1f5db7b0d67820f36be2a4d1789462 | 2,333 | js | JavaScript | src/reducers/initialState.js | krisheinrich/opencourseware-explorer | 544a2f5157486b3f1df65ff87f885ece02f40b1e | [
"MIT"
] | null | null | null | src/reducers/initialState.js | krisheinrich/opencourseware-explorer | 544a2f5157486b3f1df65ff87f885ece02f40b1e | [
"MIT"
] | null | null | null | src/reducers/initialState.js | krisheinrich/opencourseware-explorer | 544a2f5157486b3f1df65ff87f885ece02f40b1e | [
"MIT"
] | null | null | null | export default {
categories: {
isFetching: false,
byId: {
"2175": {
children: [
"Art & Society", "Art History", "Design", "Pop Culture", "Media Studies",
"Film & Video", "Photography", "Music", "Dance", "Architecture", "Urban Planning",
]
},
"2202": {
children: [
"Economics", "Finance", "Data Modeling", "Marketing", "Management", "Information Systems",
"Game Theory", "Business Law"
]
},
"2267": {
children: [
"Academia", "Research", "Teaching", "Learning Disabilities", "Online Education", "Physical Education"
]
},
"2327": {
children: [
"History", "Culture & Civilization", "Philosophy", "Intellectual History", "Classics",
"Comparative Literature", "Religious Studies", "Gender Studies", "Human Rights"
]
},
"2513": {
children: [
"Algebra", "Number Theory", "Statistics & Probability", "Calculus", "Differential Equations",
"Linear Algebra", "Combinatorics", "Graph Theory", "Algorithms", "Applied Math", "Machine Learning"
]
},
"2605": {
children: [
"Chemistry", "Physics", "Biology", "Biotechnology", "Physiology", "Health", "Nutrition",
"Environment", "Engineering", "Material Science", "Computer Science", "IT"
]
},
"2787": {
children: [
"Anthropology", "Sociology", "Psychology", "Political Science", "International Relations", "Law & Policy",
"Globalization", "Race & Ethnic Identity", "Gender & Sexuality", "Justice"
]
},
"372822": {
children: [
"Teaching", "Online Education"
]
},
"516814": {
children: [
"Logistics", "Biomedical Engineering"
]
}
}
},
courses: {
isFetching: false,
byHash: {}
},
pagination: {
byCategory: { // 25 results/page
isFetching: false,
count: 0,
currentPage: 0,
totalPages: 0,
courseIds: []
},
bySearch: { // 10 results/page
isFetching: false,
count: 0,
currentPage: 0,
totalPages: 0,
courseIds: []
}
},
user: {
currentPage: 0,
totalPages: 0,
savedCourses: []
}
};
| 27.77381 | 116 | 0.519074 |
e37648997b9c6b41dbc77d90988c16b883ee1537 | 115 | js | JavaScript | docs/html/search/variables_9.js | asiarabbit/BINGER | f525a7445be1aa3ac3f8fb235f6097c999f25f2d | [
"MIT"
] | 1 | 2017-11-23T14:47:47.000Z | 2017-11-23T14:47:47.000Z | docs/html/search/variables_9.js | asiarabbit/BINGER | f525a7445be1aa3ac3f8fb235f6097c999f25f2d | [
"MIT"
] | null | null | null | docs/html/search/variables_9.js | asiarabbit/BINGER | f525a7445be1aa3ac3f8fb235f6097c999f25f2d | [
"MIT"
] | null | null | null | var searchData=
[
['j',['j',['../define__hist_8C.html#abf2bc2545a4a5f5683d9ef3ed0d977e0',1,'define_hist.C']]]
];
| 23 | 93 | 0.695652 |
e37735c25716ba9056538545233f7919055f2388 | 1,445 | js | JavaScript | src/router.js | afandilham/reveal-blog | 0736855b150f3aee402e4f3277d13031ddcbf155 | [
"MIT"
] | null | null | null | src/router.js | afandilham/reveal-blog | 0736855b150f3aee402e4f3277d13031ddcbf155 | [
"MIT"
] | null | null | null | src/router.js | afandilham/reveal-blog | 0736855b150f3aee402e4f3277d13031ddcbf155 | [
"MIT"
] | null | null | null | import { createRouter, createWebHistory } from "vue-router";
import RevealHome from "./pages/RevealHome.vue";
import RevealProjects from "./pages/RevealProjects.vue";
import RevealAbout from "./pages/RevealAbout.vue";
import HomeFooter from './pages/HomeFooter.vue';
import CopyrightFooter from './pages/CopyrightFooter.vue';
import ArticleView from './components/articles/ArticleView.vue';
// import ProjectDetail from './components/projects/ProjectDetail.vue';
import NotFound from "./pages/NotFound.vue";
const routes = [
{
path: "/",
components: {
default: RevealHome,
footer: HomeFooter
},
},
{
name: 'article',
path: '/article/:articleId',
component: ArticleView,
},
{
name: "projects",
path: "/projects",
components: {
default: RevealProjects,
footer: CopyrightFooter
},
},
{
name: "about",
path: "/about",
components: {
default: RevealAbout,
footer: CopyrightFooter
}
},
{
name: "NotFound",
path: "/:notFound(.*)*",
component: NotFound,
},
];
const router = createRouter({
history: createWebHistory(),
routes,
linkActiveClass: 'underline'
});
// router.afterEach((to, from) => {
// const prevHistory = to.path.split('/').length;
// const afterhistory = from.path.split('/').length;
// to.meta.transition = prevHistory < afterhistory ? 'slide-up' : 'slide-down';
// });
export default router;
| 23.688525 | 81 | 0.646367 |
e3778ca7c14d1f85e02156b6b5012e85ed0aab82 | 398 | js | JavaScript | jest.config.js | sirLisko/sirlisko.com | 397e6403cf852e6849afcce700505dc5f1d9101c | [
"MIT"
] | 2 | 2015-07-06T17:27:14.000Z | 2018-10-30T13:57:59.000Z | jest.config.js | sirLisko/sirlisko.com | 397e6403cf852e6849afcce700505dc5f1d9101c | [
"MIT"
] | 4 | 2017-12-31T14:19:26.000Z | 2020-04-22T09:59:08.000Z | jest.config.js | sirLisko/sirlisko.com | 397e6403cf852e6849afcce700505dc5f1d9101c | [
"MIT"
] | null | null | null | module.exports = {
preset: "ts-jest",
moduleNameMapper: {
".+\\.(css|styl|less|sass|scss)$": `identity-obj-proxy`,
".+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": `<rootDir>/__mocks__/file-mock.js`,
},
collectCoverageFrom: ["src/**/*.{js,jsx,ts,tsx}"],
testPathIgnorePatterns: [`node_modules`, `.cache`],
testURL: `http://localhost`,
};
| 36.181818 | 128 | 0.635678 |
e37813118df039826a2699d30712823c561e74b0 | 44,885 | js | JavaScript | src/assets/js/modules/mapclick_bkh3gp.js | tangcn01/Webpack5-Vue3 | 037ee5644fa91b99d38cc7e9ce68e0747b70c573 | [
"MIT"
] | null | null | null | src/assets/js/modules/mapclick_bkh3gp.js | tangcn01/Webpack5-Vue3 | 037ee5644fa91b99d38cc7e9ce68e0747b70c573 | [
"MIT"
] | null | null | null | src/assets/js/modules/mapclick_bkh3gp.js | tangcn01/Webpack5-Vue3 | 037ee5644fa91b99d38cc7e9ce68e0747b70c573 | [
"MIT"
] | null | null | null | /**/ _jsload2 &&
_jsload2(
"mapclick",
'var ui=0,vi=1,wi=2,lj,mj=s;Ya=function(a){this.map=a;this.SE=this.Qw=s;this.Oo={};this.jZ=8;this.lm=[];this.c0=4;this.CF="";this.al=this.ne=this.oe=this.Fe=this.Rm=s;this.lt=this.xp="";this.Qy=s;this.ri=0;this.pE=t;this.qN=s;this.pm=this.aL="";this.yj=new kd(J.ta+"spotmkrs.png",new M(18,18),{anchor:new M(9,9),imageOffset:new M(0,0),infoWindowOffset:new M(10,0)});this.CY()};mj=Ya.prototype; mj.CY=function(){var a=this;a.OU();a.bind();a.eb=q;setTimeout(function(){a.Ln()},1E3);setInterval(function(){a.pE=t},300)};mj.H6=fa(t);mj.bind=function(){this.cV();this.dV();this.eV();this.fV()};mj.fV=function(){var a=this,b=this.map;b.addEventListener("vectorchanged",function(c,e){e.isvector?a.close():b.M.um==q&&a.open()})}; mj.oZ=function(a){var b=this.map;if(this.eb)if(10>b.la())this.nm();else if(this.kC(),a&&a.point)if(this.ri&&(this.qN=a.point),this.pE=q,1!=this.ri&&(this.ne&&this.ne.aa(),this.oe&&this.oe.aa(),this.Sd&&this.Sd.aa()),a=b.ML(a.point,b.la()),a.bn&&a.ns&&a.Gg)this.pm=a.Gg+"_"+a.bn+"_"+a.ns,this.Oo[a.Gg+"_"+a.bn+"_"+a.ns]?this.CF!=this.pm&&this.NG(this.pm):this.v_({wE:a.Gg,x:a.bn,y:a.ns})}; mj.NG=function(a){var b=this.map;if(b.ya()!=Qa&&b.ya()!=Va)this.nm(),this.Nk();else if(b=a.split("_"),b=b[0]+"_"+b[1]+"_"+b[2],this.Oo[b]){this.nm();this.SE=this.OJ(this.Oo[b][a]?this.Oo[b][a]:[],"MAP_CLICK_POI");this.CF=a;for(var a=-1,c=0,e=this.lm.length;c<e;c++)if(b==this.lm[c]){a=c;break}0<=a&&(this.lm.splice(a,1),this.lm.push(b))}};mj.OJ=function(a,b){for(var c=0;c<a.length;c++){var e=a[c],f=e.o,g=e.C,i=new nb(f,{offsets:[g[3],g[2],g[3],g[2]]});i.C=g;i.o=f;i.B=e.B;i.Gh=e.Gh;this.map.SB(i,b)}return q}; mj.dV=function(){var a=this;this.map.addEventListener("mousemove",function(b){a.oZ(b)})};mj.EV=function(a){if(10>this.map.la())for(var b=0,c=a.spots.length;b<c;b++){if(a.spots[b].B){this.map.xd(a.spots[b].B);break}}else this.Qy&&this.oC(this.Qy)};mj.oC=function(a){var b=this.map;!(10>b.la())&&a&&(this.ri=0,this.al&&(b.ba.wb&&b.ba.wb.close(),this.Ai=a,b.M.um&&this.y_(this.al)))};mj.y_=function(a){if(a){var b=this;He.lb(function(c){b.aS(a,c)},{qt:"inf",uid:a,operate:"mapclick",clicktype:"tile"})}}; mj.aS=function(a,b){var c=this,e=this.map;if(b&&b.content){var f=b.content,g=f.pano||0;gb.Ge(f.geo,q);if(!i)var i={};i.isFromMPC=q;var k=f.addr,i=f.street_id||"";if(1==f.poiType||3==f.poiType)k=gb.unique(k.split(";")).join("; ");var m=f.tel;m&&(m=m.replace(/,/g,", "));c.VR(f.cla);var n=F("div",{style:"font-size:12px;padding:5px 0;overflow:hidden;*zoom:1;"}),o=t;if(g)if(360>c.map.height)o=q;else{g=[];g.push("<div class=\'panoInfoBox\' id=\'panoInfoBox\' title=\'"+f.name+"\\u5916\\u666f\' title=\'\\u67e5\\u770b\\u5168\\u666f\' >"); var p=A.url.proto+A.url.domain.pano[0]+"/?qt=poiprv&uid="+i+"&width=323&height=101&quality=80&fovx=200",v=Rb(p);v?(v=Nc(v.path,{Ap:t}),p+="&"+v):p=s;g.push("<img filter = \'pano_thumnail_img\' class=\'pano_thumnail_img\' width=323 height=101 border=\'0\' alt=\'"+f.name+"\\u5916\\u666f\' src=\'"+p+"\' id=\'pano_"+a+"\'/>");g.push("<div filter = \'panoInfoBoxTitleBg\' class=\'panoInfoBoxTitleBg\'></div><a href=\'javascript:void(0)\' filter=\'panoInfoBoxTitleContent\' class=\'panoInfoBoxTitleContent\' >\\u8fdb\\u5165\\u5168\\u666f>></a>"); g.push("</div>");n.innerHTML=g.join("")}k&&(g=F("p",{style:"padding:0;margin:0;line-height:18px;font-size:12px;color:#4d4d4d;"}),g.innerHTML="\\u5730\\u5740\\uff1a"+k,n.appendChild(g));m&&(k=F("p",{style:"padding:0;margin:0;line-height:18px;font-size:12px;color:#4d4d4d;"}),k.innerHTML="\\u7535\\u8bdd\\uff1a"+m,n.appendChild(k));f.tag&&(m=F("p",{style:"padding:0;margin:0;line-height:18px;font-size:12px;color:#4d4d4d;color:#7f7f7f;"}),m.innerHTML="\\u6807\\u7b7e\\uff1a"+f.tag,n.appendChild(m));var m="http://api.map.baidu.com/place/detail?uid="+ a+"&output=html&source=jsapi&operate=mapclick&clicktype=tile",k="<div style=\'height:26px;\' id=\'detailDiv\'><a filter=\'detailInfo\' href=\'"+m+"\' target=\'_blank\' style=\'font-size:14px;color:#4d4d4d;font-weight:bold;text-decoration:none;\' onmouseover=\'this.style.textDecoration=\\"underline\\";this.style.color=\\"#3d6dcc\\"\' onmouseout =\'this.style.textDecoration=\\"none\\";this.style.color=\\"#4d4d4d\\"\'>"+f.name+"</a>",w=new nd(n,{width:322,enableSearchTool:q,title:k+("<a filter=\'detailLink\' href=\'"+m+"\' target=\'_blank\' style=\'font-size:12px;color:#3d6dcc;margin-left:5px;text-decoration:none;\' onmouseover=\'this.style.textDecoration=\\"underline\\"\' onmouseout =\'this.style.textDecoration=\\"none\\"\'>\\u8be6\\u60c5»</a>")+ "</div>",enableParano:o});o&&(w.street_id=i);w.addEventListener("open",function(){var a=x.fa("panoInfoBox");if(a){var b=f.street_id||"";Vb(function(){Ua(6006);c.yQ(b)},a,"pano_thumnail_img|panoInfoBoxTitleBg|panoInfoBoxTitleContent")}a=x.fa("detailDiv");Vb(function(){Ua(6001)},a,"detailInfo")});w.addEventListener("close",function(){c.ne&&c.ne.aa();c.oe&&c.oe.aa();c.Sd&&c.Sd.aa();e.ba.wb.xb&&e.ba.wb.xb.aa();lj=c.Ai=s;w.removeEventListener("close",arguments.callee)});c.Ai?(c.Ai.Vc(w),lj||(lj=c.al+"|"+ (c.xp?c.xp:c.lt))):c.Fe||(i=gb.Ge(f.geo,q).point,c.xp&&(n=nj.blank,c.yj.bu(new M(n.x,n.y)),n=oj[n.ea],c.yj.He(new M(n.a,n.kb)),c.yj.wc(new M(n.a/2,n.kb/2))),c.Fe=new W(i,{icon:c.yj,zIndexFixed:q}),e.Ra(c.Fe),c.Fe.addEventListener("click",function(){lj=c.al+"|"+(c.xp?c.xp:c.lt);c.oC(c.Fe)}),c.Fe.addEventListener("mouseout",function(){c.WM(c.Fe)}),c.Fe.Vc(w));c.ne&&c.ne.aa();c.oe&&c.oe.aa();c.Sd&&c.Sd.aa()}}; mj.yQ=function(a){var b=A.rh("pano","")[0],c=this,e=(new Date).getTime(),f="Pano"+e;A[f]=function(a){var b=c.map.ct(),a=a.content[0];b.Gc(a.poiinfo.PID);b.show();b.Ad({heading:a.poiinfo.Dir,pitch:a.poiinfo.Pitch})};e=(new Date).getTime();b+="?qt=poi&udt=20131021&uid="+a+"&t="+e+"&fn=BMap."+f;if(a=Rb(b))a=Nc(a.path,{Ap:t}),sa(b+("&"+a),t)}; mj.rZ=function(a){var b=this.map;if(!(10>b.la())){var c=a.spots;if(c&&!(1>c.length||"MAP_CLICK_POI"!=c[0].tag)){var e=this,f=s,g=s,i=0;e.Ai&&e.Ai===e.Fe?(f=e.Rm,g=e.oe,i=2):(f=e.Fe,g=e.ne,i=1);if(!b.ba.wb||!(b.ba.wb.eb()==q&&lj&&c[0].Gh.uid==lj.split("|")[0])){var k=nj.blank;e.lt="blank";var m=oj[k.ea];e.yj.He(new M(m.a,m.kb));e.yj.wc(new M(m.a/2,m.kb/2));e.yj.bu(new M(k.x,k.y));m=c[0].Gh.dM?c[0].Gh.dM:c[0].o;f&&f.map?(f.aa(),f.va(m),f.Wb(e.yj),f.show(),e.al=c[0].Gh.uid):(f=new W(m,{icon:e.yj,zIndexFixed:q, baseZIndex:3E6}),e.al=c[0].Gh.uid,b.Ra(f),1==i?e.Fe=f:e.Rm=f,f.addEventListener("click",function(){e.xp=e.lt;lj=e.al+"|"+e.lt;e.oC(f)}),f.addEventListener("mouseout",function(){e.WM(f)}));f.Fi(q);k=[{backgroundColor:"#FFFFE1",borderColor:"#8C8C8C",color:"#4D4D4D"},{backgroundColor:"#F0F7FF",borderColor:"#7AA3CC",color:"#224B73"}];e.Qy=f;g&&g.map?(g.aa(),c[0].Gh.name?(e.ri=1,g.Pc(c[0].Gh.name),a=e.tx(m,1,{x:Math.abs(c[0].C[0])+6,y:-9}),g.va(a),g.Ud(k[1]),g.show()):(e.ri=2,g.Pc("\\u70b9\\u51fb\\u53ef\\u67e5\\u770b\\u8be6\\u60c5"), g.Ud(k[0]),e.zO(g))):c[0].Gh.name?(e.ri=1,a=e.tx(m,1,{x:Math.abs(c[0].C[0])+6,y:-9}),g=new od(c[0].Gh.name,{position:a}),b.Ra(g),1==i?e.ne=g:e.oe=g,g.Ud(k[1])):(e.ri=2,g=new od("\\u70b9\\u51fb\\u53ef\\u67e5\\u770b\\u8be6\\u60c5",{position:e.tx(a.point,0)}),b.Ra(g),g.aa(),1==i?e.ne=g:e.oe=g,g.Ud(k[0]),e.zO(g))}}}};mj.zO=function(a){var b=this;b.nn=setInterval(function(){b.pE||setTimeout(function(){if(2==b.ri){var c=b.tx(b.qN,0);a.va(c);a.show()}clearInterval(b.nn)},500)},200)}; mj.tx=function(a,b,c){var e=this.map,a=e.vc(a);if(c)var f=c;else 0==b?f={x:-1,y:24}:1==b&&(f={x:12,y:-9});try{if(0==b||1==b)return e.bc(new Q(a.x+f.x,a.y+f.y))}catch(g){}}; mj.qZ=function(){var a=this.map;if(!(10>a.la())){this.ri=0;this.ne&&this.ne.aa();this.oe&&this.oe.aa();this.Sd&&this.Sd.aa();this.nn&&clearInterval(this.nn);this.Qy=s;var b=this.Rm;if(b&&b.map&&(!a.ba.wb||a.ba.wb.eb()==t||a.ba.wb.xb!==b)){if(this.Ai&&this.Ai===b)return;b.aa()}(b=this.Fe)&&b.map&&((!a.ba.wb||a.ba.wb.eb()==t||a.ba.wb.xb!==b)&&!(this.Ai&&this.Ai===b))&&b.aa()}}; mj.WM=function(a){var b=this.map;!(10>b.la())&&a&&(this.ne&&this.ne.aa(),this.oe&&this.oe.aa(),this.Sd&&this.Sd.aa(),this.Ai!==a&&!(b.ba.wb&&b.ba.wb.eb()==q)&&(this.al=""))}; mj.cV=function(){var a=this,b=this.map;b.addEventListener("load",function(){a.Ln()});b.addEventListener("moveend",function(){a.Ln()});b.addEventListener("dragend",function(){a.Ln()});b.addEventListener("zoomend",function(){a.kC();a.nm();if(!b.ba.wb||b.ba.wb.eb()!=q)a.Fe&&a.Fe.aa(),a.Rm&&a.Rm.aa(),a.ne&&a.ne.aa(),a.oe&&a.oe.aa(),a.Sd&&a.Sd.aa(),a.ri=0,a.nn&&clearInterval(a.nn);a.Ln()});b.addEventListener("resize",function(){a.Ln()})}; mj.Ln=function(){var a=this.map;this.eb&&10>a.la()&&(this.nm(),this.Qw||(this.Qw=this.OJ(pj,"MAP_CLICK_CITY")))};mj.v_=function(a){var b=this.map,c=this.map.da;if(a&&this.aL!=a.wE+"_"+a.x+"_"+a.y){this.aL=a.wE+"_"+a.x+"_"+a.y;var e=[];e.push(A.url.proto+A.url.domain.TILE_ONLINE_URLS[Math.abs(a.x+a.y)%3]+"/js/?qt=vtileQuest&styles=pl");e.push("&x="+a.x+"&y="+a.y+"&z="+b.Za+"&v=056&fn=MPC_Mgr."+c+".getPoiData");sa(e.join(""))}}; mj.getPoiData=function(a){var b=a.content[0],c=this.map;if(!(0<b.error_no||1>b.uids.length)){for(var e={},a=t,f=[],g=0,i=b.uids.length;g<i;g++){var k=b.uids[g],m=(k.bound.xmax+k.bound.xmin)/2,n=(k.bound.ymax+k.bound.ymin)/2,o=c.vc(R.hc(new P(k.bound.xmin,k.bound.ymin))),p=c.vc(R.hc(new P(k.bound.xmax,k.bound.ymax))),o=[(o.x-p.x)/2,(p.y-o.y)/2,(p.x-o.x)/2,(o.y-p.y)/2];f.push({o:R.hc(new P(m,n)),C:o,Gh:{name:k.name?k.name:"",uid:k.uid,type:k.type,dM:k.icon?R.hc(new P(k.icon.x,k.icon.y)):""},m6:"MAP_SPOT_INFO"})}this.pm&& this.pm==b.tileid&&(a=q);e[b.tileid]=f;b=b.tileid.split("_");b=b[0]+"_"+b[1]+"_"+b[2];this.Oo[b]=e;this.lm.push(b);this.lm.length>this.jZ&&(e=this.lm.shift(),delete this.Oo[e],delete e);a&&this.NG(this.pm)}};mj.nm=function(){var a=this.map;this.SE&&(a.Rw("MAP_CLICK_POI"),this.SE=s,this.pm=this.CF="")};mj.kC=function(){var a=this.map;this.Qw&&(a.Rw("MAP_CLICK_CITY"),this.Qw=s)}; mj.Nk=function(){this.Fe&&this.Fe.aa();this.Rm&&this.Rm.aa();this.ne&&this.ne.aa();this.oe&&this.oe.aa();this.Sd&&this.Sd.aa();this.nn&&clearInterval(this.nn)};mj.VR=function(a){for(var b=[],c=0,e=a.length;c<e;c++)b.push(a[c][1]),c<e-1&&b.push(", ")};mj.OU=function(){this.Sd||(this.Sd=new od("shadow"),this.map.Ra(this.Sd),this.Sd.Ud({backgroundColor:"#BEBEBE",borderColor:"#BEBEBE",color:"#BEBEBE",zIndex:-2E4}));this.Sd.aa()};mj.k4=ca();mj.d5=function(a){return Math.floor(parseInt(a,10)/this.c0)}; mj.WB=function(){var a=this,b=this.map;this.TA||(this.TA=function(b){a.rZ(b)});this.SA||(this.SA=function(){a.qZ()});this.Hz||(this.Hz=function(b){a.EV(b)});b.addEventListener("hotspotover",this.TA);b.addEventListener("hotspotout",this.SA);b.addEventListener("hotspotclick",this.Hz)};mj.IN=function(){var a=this.map;a.removeEventListener("hotspotover",this.TA);a.removeEventListener("hotspotout",this.SA);a.removeEventListener("hotspotclick",this.Hz)}; mj.eV=function(){var a=this.map,b=this;b.WB();a.addEventListener("onmaptypechange",function(a){a=a.Ua;a!=Qa&&a!=Va?(b.nm(),b.Nk(),b.IN()):b.WB()})};mj.open=function(){this.eb!=q&&(this.eb=q,this.WB())};mj.close=function(){this.eb!=t&&(this.eb=t,this.nm(),this.kC(),this.Nk(),this.IN())}; for(var oj=[{a:18,kb:18},{a:20,kb:20},{a:26,kb:16},{a:15,kb:15},{a:18,kb:18},{a:24,kb:24},{a:16,kb:16},{a:20,kb:20},{a:24,kb:24},{a:5,kb:5},{a:24,kb:14},{a:34,kb:16},{a:17,kb:18},{a:21,kb:22},{a:21,kb:21},{a:23,kb:23},{a:30,kb:30}],nj={zhudijigou:{x:-195,y:0,ea:0},zhongyangjigou:{x:-178,y:-190,ea:0},zhongxiaoxue:{x:-196,y:-190,ea:0},zhongheyiyuan_1:{x:-214,y:-190,ea:0},zhongcan:{x:-232,y:-190,ea:0},zhongcan_a:{x:-232,y:-190,ea:0},zhongcan_b:{x:-232,y:-190,ea:0},zhongbiaoyanjing:{x:-250,y:-190,ea:0}, youzheng:{x:-160,y:-208,ea:0},xiyidian:{x:-178,y:-208,ea:0},xinwenchuban:{x:-196,y:-208,ea:0},xican:{x:-214,y:-208,ea:0},xiaoxue_loupan:{x:-232,y:-208,ea:0},wenhuabangong:{x:-285,y:-18,ea:0},yinyueting:{x:-160,y:-226,ea:0},tushuyinxiang:{x:-178,y:-226,ea:0},tiyuyongpin:{x:-196,y:-226,ea:0},tiyu:{x:-214,y:-226,ea:0},tingchecang:{x:-232,y:-226,ea:0},shoupiaochu:{x:-250,y:-226,ea:0},yinghang:{x:-160,y:-244,ea:0},sheyingshexiang:{x:-178,y:-244,ea:0},shangwudasha:{x:-196,y:-244,ea:0},shangchang:{x:-214, y:-244,ea:0},sewaijigou:{x:-267,y:-54,ea:0},qita:{x:-250,y:-244,ea:0},yaodian_yaofang:{x:-160,y:-262,ea:0},qiche:{x:-178,y:-262,ea:0},meirongmeifa:{x:-196,y:-262,ea:0},lingmu:{x:-214,y:-262,ea:0},lianshuokuaishujiudiann:{x:-232,y:-262,ea:0},keyangjigou:{x:-250,y:-262,ea:0},hill:{x:-160,y:-280,ea:0},jiaotang:{x:-178,y:-280,ea:0},jiayouzhan:{x:-196,y:-280,ea:0},jiguandanwei:{x:-249,y:-90,ea:0},jiuba:{x:-232,y:-280,ea:0},kafeiting:{x:-250,y:-280,ea:0},guji:{x:-160,y:-298,ea:0},gouwuzhongxin:{x:-178, y:-298,ea:0},gongyuan:{x:-196,y:-298,ea:0},gongjianfajigou:{x:-249,y:-108,ea:0},gongce:{x:-232,y:-298,ea:0},gewuting:{x:-250,y:-298,ea:0},gaodengjiaoyu:{x:-160,y:-316,ea:0},gangkou_matou:{x:-178,y:-316,ea:0},fengjing:{x:-196,y:-316,ea:0},fangwuzhongjie:{x:-214,y:-316,ea:0},dujiachun:{x:-232,y:-316,ea:0},dongwuyuan:{x:-250,y:-316,ea:0},dongnanyacai:{x:-160,y:-334,ea:0},dianyingyuan:{x:-178,y:-334,ea:0},dianxinyingyeting:{x:-196,y:-334,ea:0},dianxingongsi:{x:-214,y:-334,ea:0},dianshita:{x:-232,y:-334, ea:0},chongwudian:{x:-250,y:-334,ea:0},chazhuo:{x:-160,y:-352,ea:0},chaoshi:{x:-178,y:-352,ea:0},changtuqichezhan:{x:-196,y:-352,ea:0},bowuguan:{x:-214,y:-352,ea:0},binguan:{x:-232,y:-352,ea:0},atm:{x:-250,y:-352,ea:0},blank:{x:-166,y:0,ea:0},feijichang:{x:-167,y:-18,ea:1},huochezhan:{x:-167,y:-40,ea:1},tianam:{x:-164,y:-61,ea:2},busstop_2:{x:-82,y:-289,ea:12},busstop_3:{x:-124,y:-289,ea:13},ditie_beijing_00:{x:-175,y:-90,ea:9},ditie_beijing_0:{x:-8,y:0,ea:3},ditie_beijing_1:{x:-27,y:0,ea:4},ditie_beijing_2:{x:-51, y:0,ea:5},ditie_shanghai_0:{x:-8,y:-23,ea:3},ditie_shanghai_1:{x:-27,y:-23,ea:4},ditie_shanghai_2:{x:-51,y:-23,ea:5},ditie_guangzhou_0:{x:-8,y:-47,ea:3},ditie_guangzhou_1:{x:-27,y:-47,ea:4},ditie_guangzhou_2:{x:-51,y:-47,ea:5},ditie_tianjin_0:{x:-8,y:-71,ea:3},ditie_tianjin_1:{x:-27,y:-71,ea:4},ditie_tianjin_2:{x:-51,y:-71,ea:5},ditie_shenzhen_0:{x:-8,y:-95,ea:3},ditie_shenzhen_1:{x:-27,y:-95,ea:4},ditie_shenzhen_2:{x:-51,y:-95,ea:5},ditie_xianggang_0:{x:-8,y:-120,ea:3},ditie_xianggang_1:{x:-27,y:-120, ea:4},ditie_xianggang_2:{x:-51,y:-120,ea:5},ditie_nanjing_0:{x:-8,y:-142,ea:3},ditie_nanjing_1:{x:-27,y:-142,ea:4},ditie_nanjing_2:{x:-51,y:-142,ea:5},ditie_chongqing_0:{x:-8,y:-166,ea:3},ditie_chongqing_1:{x:-27,y:-166,ea:4},ditie_chongqing_2:{x:-51,y:-166,ea:5},ditie_wuhan_0:{x:-8,y:-191,ea:3},ditie_wuhan_1:{x:-27,y:-191,ea:4},ditie_wuhan_2:{x:-51,y:-191,ea:5},ditie_changchun_0:{x:-8,y:-214,ea:3},ditie_changchun_1:{x:-27,y:-214,ea:4},ditie_changchun_2:{x:-51,y:-214,ea:5},ditie_dalian_0:{x:-8,y:-238, ea:3},ditie_dalian_1:{x:-27,y:-238,ea:4},ditie_dalian_2:{x:-51,y:-238,ea:5},ditie_chengdu_0:{x:-6,y:-316,ea:14},ditie_chengdu_1:{x:-28,y:-316,ea:15},ditie_chengdu_2:{x:-52,y:-316,ea:16},ditie_shenyang_0:{x:-8,y:-289,ea:3},ditie_shenyang_1:{x:-27,y:-289,ea:4},ditie_shenyang_2:{x:-51,y:-289,ea:5},trans_beijing_0:{x:-83,y:-1,ea:6},trans_beijing_1:{x:-102,y:-1,ea:7},trans_beijing_2:{x:-127,y:-1,ea:8},trans_shanghai_0:{x:-83,y:-27,ea:6},trans_shanghai_1:{x:-102,y:-27,ea:7},trans_shanghai_2:{x:-127,y:-27, ea:8},trans_guangzhou_0:{x:-83,y:-53,ea:6},trans_guangzhou_1:{x:-102,y:-53,ea:7},trans_guangzhou_2:{x:-127,y:-53,ea:8},trans_tianjin_0:{x:-83,y:-79,ea:6},trans_tianjin_1:{x:-102,y:-79,ea:7},trans_tianjin_2:{x:-127,y:-79,ea:8},trans_shenzhen_0:{x:-83,y:-105,ea:6},trans_shenzhen_1:{x:-102,y:-105,ea:7},trans_shenzhen_2:{x:-127,y:-105,ea:8},trans_xianggang_0:{x:-83,y:-131,ea:6},trans_xianggang_2:{x:-102,y:-131,ea:7},trans_xianggang_3:{x:-127,y:-131,ea:8},trans_nanjing_0:{x:-83,y:-157,ea:6},trans_nanjing_1:{x:-102, y:-157,ea:7},trans_nanjing_2:{x:-127,y:-157,ea:8},trans_chongqing_0:{x:-83,y:-183,ea:6},trans_chongqing_1:{x:-102,y:-183,ea:7},trans_chongqing_2:{x:-127,y:-183,ea:8},trans_wuhan_0:{x:-83,y:-209,ea:6},trans_wuhan_1:{x:-102,y:-209,ea:7},trans_wuhan_2:{x:-127,y:-209,ea:8},trans_changchun_0:{x:-83,y:-235,ea:6},trans_changchun_1:{x:-102,y:-235,ea:7},trans_changchun_2:{x:-127,y:-235,ea:8},trans_dalian_0:{x:-83,y:-261,ea:6},trans_dalian_1:{x:-102,y:-261,ea:7},trans_dalian_2:{x:-127,y:-261,ea:8},gaosurukou:{x:-163, y:-131,ea:10},gaosuchukou:{x:-163,y:-107,ea:10},shoufeizhan:{x:-156,y:-153,ea:11}},Z=[-5,-4,4,4],pj=[{B:"\\u5168\\u56fd",o:new P(1.199957122E7,4112219.88),C:[-19,-9,15,9],D:[3,3]},{B:"\\u5317\\u4eac\\u5e02",o:new P(12990903,4825899),C:[-6,-4,5,6],D:[4,4]},{B:"\\u5317\\u4eac\\u5e02",o:new P(12960183,4824235),C:[-6,-6,6,6],D:[5,9]},{B:"\\u5929\\u6d25\\u5e02",o:new P(1.304829434E7,4712296.83),C:Z,D:[5,9]},{B:"\\u77f3\\u5bb6\\u5e84\\u5e02",o:new P(1.27478124E7,4559586.74),C:Z,D:[5,9]},{B:"\\u5510\\u5c71\\u5e02",o:new P(1.315665616E7, 4785778.65),C:Z,D:[7,9]},{B:"\\u79e6\\u7687\\u5c9b\\u5e02",o:new P(1.331489428E7,4829754.58),C:Z,D:[7,9]},{B:"\\u90af\\u90f8\\u5e02",o:new P(1.274620545E7,4360272.57),C:Z,D:[7,9]},{B:"\\u90a2\\u53f0\\u5e02",o:new P(1.274749344E7,4423803.15),C:Z,D:[8,9]},{B:"\\u4fdd\\u5b9a\\u5e02",o:new P(1.28543128E7,4677428.01),C:Z,D:[7,9]},{B:"\\u5f20\\u5bb6\\u53e3\\u5e02",o:new P(1.279008463E7,4959101.33),C:Z,D:[7,9]},{B:"\\u627f\\u5fb7\\u5e02",o:new P(1.313032691E7,4981742.46),C:Z,D:[7,9]},{B:"\\u6ca7\\u5dde\\u5e02",o:new P(1.30072937E7, 4596691.7),C:Z,D:[7,9]},{B:"\\u5eca\\u574a\\u5e02",o:new P(1.299258176E7,4769905.8),C:Z,D:[8,9]},{B:"\\u8861\\u6c34\\u5e02",o:new P(1.288017593E7,4516789.37),C:Z,D:[7,9]},{B:"\\u592a\\u539f\\u5e02",o:new P(1.252907701E7,4535262.32),C:Z,D:[5,9]},{B:"\\u5927\\u540c\\u5e02",o:new P(1.261336427E7,4850167.42),C:Z,D:[7,9]},{B:"\\u9633\\u6cc9\\u5e02",o:new P(1.264459126E7,4533525.33),C:Z,D:[8,9]},{B:"\\u957f\\u6cbb\\u5e02",o:new P(1.25931022E7,4302896.69),C:Z,D:[7,9]},{B:"\\u664b\\u57ce\\u5e02",o:new P(1.256346095E7,4206462.32), C:Z,D:[7,9]},{B:"\\u6714\\u5dde\\u5e02",o:new P(1.251682783E7,4742810.65),C:Z,D:[7,9]},{B:"\\u664b\\u4e2d\\u5e02",o:new P(1.255228326E7,4509774.55),C:Z,D:[7,9]},{B:"\\u8fd0\\u57ce\\u5e02",o:new P(1.235808371E7,4143552.84),C:Z,D:[7,9]},{B:"\\u5ffb\\u5dde\\u5e02",o:new P(1.255078132E7,4612328.73),C:Z,D:[7,9]},{B:"\\u4e34\\u6c7e\\u5e02",o:new P(1.241495146E7,4288092.81),C:Z,D:[7,9]},{B:"\\u5415\\u6881\\u5e02",o:new P(1.237335426E7,4486213.29),C:Z,D:[7,9]},{B:"\\u547c\\u548c\\u6d69\\u7279\\u5e02",o:new P(1.243971997E7,4961446.57), C:Z,D:[5,9]},{B:"\\u5305\\u5934\\u5e02",o:new P(1.222832364E7,4934673.82),C:Z,D:[7,9]},{B:"\\u4e4c\\u6d77\\u5e02",o:new P(1.189243044E7,4793517.95),C:Z,D:[7,9]},{B:"\\u8d64\\u5cf0\\u5e02",o:new P(1.323554733E7,5171648.96),C:Z,D:[7,9]},{B:"\\u901a\\u8fbd\\u5e02",o:new P(1.361147247E7,5377912.47),C:Z,D:[7,9]},{B:"\\u9102\\u5c14\\u591a\\u65af\\u5e02",o:new P(1.224841002E7,4812809.03),C:Z,D:[7,9]},{B:"\\u547c\\u4f26\\u8d1d\\u5c14\\u5e02",o:new P(1.333315354E7,6279368.64),C:Z,D:[7,9]},{B:"\\u5df4\\u5f66\\u6dd6\\u5c14\\u5e02",o:new P(1.195525708E7, 4947259.83),C:Z,D:[7,9]},{B:"\\u4e4c\\u5170\\u5bdf\\u5e03\\u5e02",o:new P(1.259485229E7,4984078.08),C:Z,D:[7,9]},{B:"\\u5174\\u5b89\\u76df",o:new P(1.358886567E7,5762892.65),C:Z,D:[7,9]},{B:"\\u9521\\u6797\\u90ed\\u52d2\\u76df",o:new P(1.291922601E7,5426155.97),C:Z,D:[7,9]},{B:"\\u963f\\u62c9\\u5584\\u76df",o:new P(1.177053341E7,4674264.08),C:Z,D:[7,9]},{B:"\\u6c88\\u9633\\u5e02",o:new P(1.374036603E7,5103661.8),C:Z,D:[5,9]},{B:"\\u5927\\u8fde\\u5e02",o:new P(1.353897373E7,4683025.5),C:Z,D:[7,9]},{B:"\\u978d\\u5c71\\u5e02", o:new P(1.369251369E7,5000950.08),C:Z,D:[7,9]},{B:"\\u629a\\u987a\\u5e02",o:new P(1.379938803E7,5114977.65),C:Z,D:[7,9]},{B:"\\u672c\\u6eaa\\u5e02",o:new P(1.377864321E7,5028229.05),C:Z,D:[7,9]},{B:"\\u4e39\\u4e1c\\u5e02",o:new P(1.384731338E7,4857753.87),C:Z,D:[7,9]},{B:"\\u9526\\u5dde\\u5e02",o:new P(13485599,4998700.1),C:Z,D:[7,9]},{B:"\\u8425\\u53e3\\u5e02",o:new P(1.360800602E7,4936051.67),C:Z,D:[7,9]},{B:"\\u961c\\u65b0\\u5e02",o:new P(1.354506745E7,5136335.54),C:Z,D:[7,9]},{B:"\\u8fbd\\u9633\\u5e02",o:new P(1.371241685E7, 5024584.95),C:Z,D:[8,9]},{B:"\\u76d8\\u9526\\u5e02",o:new P(1.358987645E7,5002667.8),C:Z,D:[7,9]},{B:"\\u94c1\\u5cad\\u5e02",o:new P(1.378727479E7,5175928.41),C:Z,D:[7,9]},{B:"\\u671d\\u9633\\u5e02",o:new P(1.340929734E7,5069601.1),C:Z,D:[7,9]},{B:"\\u846b\\u82a6\\u5c9b\\u5e02",o:new P(1.345225378E7,4942439.12),C:Z,D:[7,9]},{B:"\\u957f\\u6625\\u5e02",o:new P(1.395169647E7,5407899.41),C:Z,D:[5,9]},{B:"\\u5409\\u6797\\u5e02",o:new P(1.408831069E7,5411361.75),C:Z,D:[7,9]},{B:"\\u56db\\u5e73\\u5e02",o:new P(1.384344811E7, 5308670.02),C:Z,D:[7,9]},{B:"\\u8fbd\\u6e90\\u5e02",o:new P(1.393179056E7,5266534.49),C:Z,D:[7,9]},{B:"\\u901a\\u5316\\u5e02",o:new P(1.402045802E7,5092482.52),C:Z,D:[7,9]},{B:"\\u767d\\u5c71\\u5e02",o:new P(1.407431642E7,5124029.48),C:Z,D:[8,9]},{B:"\\u677e\\u539f\\u5e02",o:new P(1.389631929E7,5614174.46),C:Z,D:[7,9]},{B:"\\u767d\\u57ce\\u5e02",o:new P(1.367521901E7,5689684.01),C:Z,D:[7,9]},{B:"\\u5ef6\\u8fb9\\u671d\\u9c9c\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.441776373E7,5266998.98),C:Z,D:[7,9]},{B:"\\u54c8\\u5c14\\u6ee8\\u5e02", o:new P(1.408650136E7,5722186.15),C:Z,D:[5,9]},{B:"\\u9f50\\u9f50\\u54c8\\u5c14\\u5e02",o:new P(1.37952823E7,5969334.56),C:Z,D:[7,9]},{B:"\\u9e21\\u897f\\u5e02",o:new P(1.458080782E7,5638827.82),C:Z,D:[7,9]},{B:"\\u9e64\\u5c97\\u5e02",o:new P(1.450560155E7,5968656.02),C:Z,D:[7,9]},{B:"\\u53cc\\u9e2d\\u5c71\\u5e02",o:new P(1.460142765E7,5854241.34),C:Z,D:[7,9]},{B:"\\u5927\\u5e86\\u5e02",o:new P(1.392732491E7,5844873.47),C:Z,D:[7,9]},{B:"\\u4f0a\\u6625\\u5e02",o:new P(1.435040278E7,6030712.32),C:Z,D:[7,9]},{B:"\\u4f73\\u6728\\u65af\\u5e02", o:new P(1.450805986E7,5878973.81),C:Z,D:[7,9]},{B:"\\u4e03\\u53f0\\u6cb3\\u5e02",o:new P(1.458408167E7,5713695.85),C:Z,D:[7,9]},{B:"\\u7261\\u4e39\\u6c5f\\u5e02",o:new P(1.443006301E7,5527661.89),C:Z,D:[7,9]},{B:"\\u9ed1\\u6cb3\\u5e02",o:new P(1.419624334E7,6457183.7),C:Z,D:[7,9]},{B:"\\u7ee5\\u5316\\u5e02",o:new P(1.413493747E7,5855417.31),C:Z,D:[7,9]},{B:"\\u5927\\u5174\\u5b89\\u5cad\\u5730\\u533a",o:new P(1.383893581E7,6763930.17),C:Z,D:[7,9]},{B:"\\u4e0a\\u6d77\\u5e02",o:new P(1.35231485E7,3641129.98),C:Z,D:[5,9]}, {B:"\\u5357\\u4eac\\u5e02",o:new P(1.322439822E7,3749110.08),C:Z,D:[5,9]},{B:"\\u65e0\\u9521\\u5e02",o:new P(1.339293301E7,3684625.08),C:Z,D:[8,9]},{B:"\\u5f90\\u5dde\\u5e02",o:new P(1.304658292E7,4040227.55),C:Z,D:[7,9]},{B:"\\u5e38\\u5dde\\u5e02",o:new P(1.335631214E7,3716455.43),C:Z,D:[7,9]},{B:"\\u82cf\\u5dde\\u5e02",o:new P(1.342436752E7,3650025.6),C:Z,D:[7,9]},{B:"\\u5357\\u901a\\u5e02",o:new P(1.345867166E7,3738891.76),C:Z,D:[7,9]},{B:"\\u8fde\\u4e91\\u6e2f\\u5e02",o:new P(1.327258831E7,4085285.7),C:Z,D:[7,9]}, {B:"\\u6dee\\u5b89\\u5e02",o:new P(1.324961418E7,3953528.85),C:Z,D:[7,9]},{B:"\\u76d0\\u57ce\\u5e02",o:new P(1.337721562E7,3919501.88),C:Z,D:[7,9]},{B:"\\u626c\\u5dde\\u5e02",o:new P(1.329391759E7,3792837.54),C:Z,D:[7,9]},{B:"\\u9547\\u6c5f\\u5e02",o:new P(1.329874933E7,3767384.26),C:Z,D:[8,9]},{B:"\\u6cf0\\u5dde\\u5e02",o:new P(1.335064059E7,3800783.56),C:Z,D:[8,9]},{B:"\\u5bbf\\u8fc1\\u5e02",o:new P(1.316723796E7,4000367.15),C:Z,D:[7,9]},{B:"\\u676d\\u5dde\\u5e02",o:new P(1.33805214E7,3509725.46),C:Z,D:[5,9]},{B:"\\u5b81\\u6ce2\\u5e02", o:new P(1.353171719E7,3466700.47),C:Z,D:[7,9]},{B:"\\u6e29\\u5dde\\u5e02",o:new P(1.343705661E7,3228862.38),C:Z,D:[7,9]},{B:"\\u5609\\u5174\\u5e02",o:new P(1.344251601E7,3578433.26),C:Z,D:[7,9]},{B:"\\u6e56\\u5dde\\u5e02",o:new P(1.336888217E7,3597591.37),C:Z,D:[7,9]},{B:"\\u7ecd\\u5174\\u5e02",o:new P(1.342353439E7,3483350.89),C:Z,D:[7,9]},{B:"\\u91d1\\u534e\\u5e02",o:new P(1.331996271E7,3365440.15),C:Z,D:[7,9]},{B:"\\u8862\\u5dde\\u5e02",o:new P(1.323381451E7,3347380.57),C:Z,D:[7,9]},{B:"\\u821f\\u5c71\\u5e02",o:new P(1.360498413E7, 3480848.35),C:Z,D:[7,9]},{B:"\\u53f0\\u5dde\\u5e02",o:new P(1.351735559E7,3311823.54),C:Z,D:[7,9]},{B:"\\u4e3d\\u6c34\\u5e02",o:new P(1.335063445E7,3288178.9),C:Z,D:[7,9]},{B:"\\u5408\\u80a5\\u5e02",o:new P(1.305046054E7,3720544.86),C:Z,D:[5,9]},{B:"\\u829c\\u6e56\\u5e02",o:new P(1.317946498E7,3655185.37),C:Z,D:[7,9]},{B:"\\u868c\\u57e0\\u5e02",o:new P(1.306849369E7,3861457.33),C:Z,D:[7,9]},{B:"\\u6dee\\u5357\\u5e02",o:new P(1.302555953E7,3823189.84),C:Z,D:[7,9]},{B:"\\u9a6c\\u978d\\u5c71\\u5e02",o:new P(1.319275845E7, 3701721.87),C:Z,D:[7,9]},{B:"\\u6dee\\u5317\\u5e02",o:new P(1.300279748E7,3999425.85),C:Z,D:[8,9]},{B:"\\u94dc\\u9675\\u5e02",o:new P(1.311655618E7,3603277.27),C:Z,D:[8,9]},{B:"\\u5b89\\u5e86\\u5e02",o:new P(1.303162375E7,3550019.08),C:Z,D:[7,9]},{B:"\\u9ec4\\u5c71\\u5e02",o:new P(1.317427886E7,3446439.23),C:Z,D:[7,9]},{B:"\\u6ec1\\u5dde\\u5e02",o:new P(1.317183794E7,3780786.48),C:Z,D:[7,9]},{B:"\\u961c\\u9633\\u5e02",o:new P(1.289321516E7,3858085.78),C:Z,D:[7,9]},{B:"\\u5bbf\\u5dde\\u5e02",o:new P(1.30212317E7,3958276.71), C:Z,D:[7,9]},{B:"\\u5de2\\u6e56\\u5e02",o:new P(1.312385159E7,3691564.79),C:Z,D:[8,9]},{B:"\\u516d\\u5b89\\u5e02",o:new P(1.297019874E7,3707970.37),C:Z,D:[7,9]},{B:"\\u4eb3\\u5dde\\u5e02",o:new P(1.288949748E7,3985791.77),C:Z,D:[8,9]},{B:"\\u6c60\\u5dde\\u5e02",o:new P(1.30798748E7,3567450.98),C:Z,D:[8,9]},{B:"\\u5ba3\\u57ce\\u5e02",o:new P(1.322101886E7,3603632.56),C:Z,D:[7,9]},{B:"\\u798f\\u5dde\\u5e02",o:new P(1.328071393E7,2989935.97),C:Z,D:[5,9]},{B:"\\u53a6\\u95e8\\u5e02",o:new P(1.314651306E7,2794855.77),C:Z,D:[7, 9]},{B:"\\u8386\\u7530\\u5e02",o:new P(1.324873885E7,2913804.66),C:Z,D:[7,9]},{B:"\\u4e09\\u660e\\u5e02",o:new P(1.309639979E7,3013435.8),C:Z,D:[7,9]},{B:"\\u6cc9\\u5dde\\u5e02",o:new P(1.320191012E7,2846954.45),C:Z,D:[8,9]},{B:"\\u6f33\\u5dde\\u5e02",o:new P(1.30972994E7,2798905.67),C:Z,D:[7,9]},{B:"\\u5357\\u5e73\\u5e02",o:new P(1.31563519E7,3060177),C:Z,D:[7,9]},{B:"\\u9f99\\u5ca9\\u5e02",o:new P(1.302904754E7,2870546.66),C:Z,D:[7,9]},{B:"\\u5b81\\u5fb7\\u5e02",o:new P(1.330647299E7,3063294.93),C:Z,D:[7,9]},{B:"\\u5357\\u660c\\u5e02", o:new P(1.291001755E7,3308071.83),C:Z,D:[5,9]},{B:"\\u666f\\u5fb7\\u9547\\u5e02",o:new P(1.304548805E7,3394401.41),C:Z,D:[7,9]},{B:"\\u840d\\u4e61\\u5e02",o:new P(1.267515981E7,3182197.09),C:Z,D:[8,9]},{B:"\\u4e5d\\u6c5f\\u5e02",o:new P(1.291408497E7,3445118.73),C:Z,D:[7,9]},{B:"\\u65b0\\u4f59\\u5e02",o:new P(1.279332028E7,3206680.44),C:Z,D:[8,9]},{B:"\\u9e70\\u6f6d\\u5e02",o:new P(1.303295225E7,3262112.41),C:Z,D:[8,9]},{B:"\\u8d63\\u5dde\\u5e02",o:new P(1.279518535E7,2959890.57),C:Z,D:[7,9]},{B:"\\u5409\\u5b89\\u5e02", o:new P(1.280188497E7,3118790.33),C:Z,D:[7,9]},{B:"\\u5b9c\\u6625\\u5e02",o:new P(1.273693492E7,3206538.71),C:Z,D:[7,9]},{B:"\\u629a\\u5dde\\u5e02",o:new P(12953213,3222556.21),C:Z,D:[7,9]},{B:"\\u4e0a\\u9976\\u5e02",o:new P(1.313388004E7,3285299.92),C:Z,D:[7,9]},{B:"\\u6d4e\\u5357\\u5e02",o:new P(1.302458137E7,4367507.59),C:Z,D:[5,9]},{B:"\\u9752\\u5c9b\\u5e02",o:new P(1.340183129E7,4285182.82),C:Z,D:[7,9]},{B:"\\u6dc4\\u535a\\u5e02",o:new P(1.31426863E7,4388052.83),C:Z,D:[7,9]},{B:"\\u67a3\\u5e84\\u5e02",o:new P(1.306127478E7, 4114277.91),C:Z,D:[7,9]},{B:"\\u4e1c\\u8425\\u5e02",o:new P(1.321165635E7,4474393.79),C:Z,D:[7,9]},{B:"\\u70df\\u53f0\\u5e02",o:new P(1.352035299E7,4478575.49),C:Z,D:[7,9]},{B:"\\u6f4d\\u574a\\u5e02",o:new P(1.326587888E7,4373424.04),C:Z,D:[7,9]},{B:"\\u6d4e\\u5b81\\u5e02",o:new P(1.297932404E7,4196136.66),C:Z,D:[7,9]},{B:"\\u6cf0\\u5b89\\u5e02",o:new P(1.303498861E7,4303535.5),C:Z,D:[7,9]},{B:"\\u5a01\\u6d77\\u5e02",o:new P(1.359563129E7,4485000.06),C:Z,D:[7,9]},{B:"\\u65e5\\u7167\\u5e02",o:new P(1.330710951E7,4195766.38), C:Z,D:[7,9]},{B:"\\u83b1\\u829c\\u5e02",o:new P(1.310045667E7,4305551.29),C:Z,D:[8,9]},{B:"\\u4e34\\u6c82\\u5e02",o:new P(1.317546245E7,4147217.21),C:Z,D:[7,9]},{B:"\\u5fb7\\u5dde\\u5e02",o:new P(1.294762204E7,4476813.41),C:Z,D:[7,9]},{B:"\\u804a\\u57ce\\u5e02",o:new P(1.291231075E7,4338690.92),C:Z,D:[7,9]},{B:"\\u6ee8\\u5dde\\u5e02",o:new P(1.31345846E7,4466450.28),C:Z,D:[8,9]},{B:"\\u83cf\\u6cfd\\u5e02",o:new P(1.285603348E7,4171820.25),C:Z,D:[7,9]},{B:"\\u90d1\\u5dde\\u5e02",o:new P(1.264866361E7,4105852.45),C:Z,D:[5, 9]},{B:"\\u5f00\\u5c01\\u5e02",o:new P(1.272550083E7,4112517.32),C:Z,D:[7,9]},{B:"\\u6d1b\\u9633\\u5e02",o:new P(1.251908239E7,4088441.36),C:Z,D:[7,9]},{B:"\\u5e73\\u9876\\u5c71\\u5e02",o:new P(1.261439072E7,3969016.16),C:Z,D:[7,9]},{B:"\\u5b89\\u9633\\u5e02",o:new P(1.273504336E7,4289478.97),C:Z,D:[7,9]},{B:"\\u9e64\\u58c1\\u5e02",o:new P(1.27118028E7,4262428.36),C:Z,D:[8,9]},{B:"\\u65b0\\u4e61\\u5e02",o:new P(1.268305211E7,4179998.27),C:Z,D:[7,9]},{B:"\\u7126\\u4f5c\\u5e02",o:new P(1.260690819E7,4169148.29),C:Z,D:[8, 9]},{B:"\\u6fee\\u9633\\u5e02",o:new P(1.280622838E7,4243123.16),C:Z,D:[8,9]},{B:"\\u8bb8\\u660c\\u5e02",o:new P(1.267484133E7,4010264.96),C:Z,D:[8,9]},{B:"\\u6f2f\\u6cb3\\u5e02",o:new P(1.269314311E7,3949716.47),C:Z,D:[8,9]},{B:"\\u4e09\\u95e8\\u5ce1\\u5e02",o:new P(1.237984112E7,4110225.01),C:Z,D:[7,9]},{B:"\\u5357\\u9633\\u5e02",o:new P(1.252747532E7,3871404.82),C:Z,D:[7,9]},{B:"\\u5546\\u4e18\\u5e02",o:new P(1.287511484E7,4065382.71),C:Z,D:[7,9]},{B:"\\u4fe1\\u9633\\u5e02",o:new P(1.269893502E7,3757290.11),C:Z,D:[7, 9]},{B:"\\u5468\\u53e3\\u5e02",o:new P(1.27640208E7,3955188.99),C:Z,D:[7,9]},{B:"\\u9a7b\\u9a6c\\u5e97\\u5e02",o:new P(1.26952599E7,3870201.61),C:Z,D:[7,9]},{B:"\\u6b66\\u6c49\\u5e02",o:new P(1.272455882E7,3558883.15),C:Z,D:[5,9]},{B:"\\u9ec4\\u77f3\\u5e02",o:new P(1.280683116E7,3508246.06),C:Z,D:[8,9]},{B:"\\u5341\\u5830\\u5e02",o:new P(1.233381983E7,3826557.97),C:Z,D:[7,9]},{B:"\\u5b9c\\u660c\\u5e02",o:new P(1.238926478E7,3571550.15),C:Z,D:[7,9]},{B:"\\u8944\\u6a0a\\u5e02",o:new P(1.248580442E7,3744176.48),C:Z,D:[7, 9]},{B:"\\u8346\\u95e8\\u5e02",o:new P(1.24908312E7,3615936.83),C:Z,D:[7,9]},{B:"\\u5b5d\\u611f\\u5e02",o:new P(1.268197645E7,3601581.31),C:Z,D:[8,9]},{B:"\\u8346\\u5dde\\u5e02",o:new P(1.24953132E7,3525594.67),C:Z,D:[7,9]},{B:"\\u9ec4\\u5188\\u5e02",o:new P(1.278872731E7,3541014.86),C:Z,D:[7,9]},{B:"\\u54b8\\u5b81\\u5e02",o:new P(1.272713679E7,3462404.52),C:Z,D:[7,9]},{B:"\\u968f\\u5dde\\u5e02",o:new P(1.262253173E7,3700874.41),C:Z,D:[7,9]},{B:"\\u6069\\u65bd\\u571f\\u5bb6\\u65cf\\u82d7\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.218903267E7, 3517579.64),C:Z,D:[7,9]},{B:"\\u4ed9\\u6843\\u5e02",o:new P(1.263056786E7,3529164.83),C:Z,D:[9,9]},{B:"\\u6f5c\\u6c5f\\u5e02",o:new P(1.256873544E7,3534321.2),C:Z,D:[9,9]},{B:"\\u5929\\u95e8\\u5e02",o:new P(1.259844393E7,3567930.91),C:Z,D:[9,9]},{B:"\\u795e\\u519c\\u67b6\\u6797\\u533a",o:new P(1.23212052E7,3707164.42),C:Z,D:[9,9]},{B:"\\u957f\\u6c99\\u5e02",o:new P(1.257234748E7,3258455.64),C:Z,D:[5,9]},{B:"\\u682a\\u6d32\\u5e02",o:new P(1.259492763E7,3207920.8),C:Z,D:[7,9]},{B:"\\u6e58\\u6f6d\\u5e02",o:new P(1.257361587E7, 3208214.06),C:Z,D:[7,9]},{B:"\\u8861\\u9633\\u5e02",o:new P(1.25323004E7,3091412.15),C:Z,D:[7,9]},{B:"\\u90b5\\u9633\\u5e02",o:new P(1.240939043E7,3134535.06),C:Z,D:[7,9]},{B:"\\u5cb3\\u9633\\u5e02",o:new P(12594102,3400788.63),C:Z,D:[7,9]},{B:"\\u5e38\\u5fb7\\u5e02",o:new P(1.243507912E7,3359523.26),C:Z,D:[7,9]},{B:"\\u5f20\\u5bb6\\u754c\\u5e02",o:new P(1.229944266E7,3370126.24),C:Z,D:[7,9]},{B:"\\u76ca\\u9633\\u5e02",o:new P(1.250817766E7,3299123.14),C:Z,D:[7,9]},{B:"\\u90f4\\u5dde\\u5e02",o:new P(1.258158251E7,2952694.08), C:Z,D:[7,9]},{B:"\\u6c38\\u5dde\\u5e02",o:new P(1.242566251E7,3032983.5),C:Z,D:[7,9]},{B:"\\u6000\\u5316\\u5e02",o:new P(1.22457125E7,3174098.87),C:Z,D:[7,9]},{B:"\\u5a04\\u5e95\\u5e02",o:new P(1.246803765E7,3191557.89),C:Z,D:[8,9]},{B:"\\u6e58\\u897f\\u571f\\u5bb6\\u65cf\\u82d7\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.221698361E7,3268959.39),C:Z,D:[7,9]},{B:"\\u5e7f\\u5dde\\u5e02",o:new P(1.260930783E7,2631271.83),C:Z,D:[5,9]},{B:"\\u97f6\\u5173\\u5e02",o:new P(1.264644631E7,2835068.76),C:Z,D:[7,9]},{B:"\\u6df1\\u5733\\u5e02", o:new P(1.268919896E7,2569212.32),C:Z,D:[8,9]},{B:"\\u6c55\\u5934\\u5e02",o:new P(1.298983615E7,2658196.76),C:Z,D:[7,9]},{B:"\\u4f5b\\u5c71\\u5e02",o:new P(1.259351942E7,2618810.41),C:Z,D:[8,9]},{B:"\\u6c5f\\u95e8\\u5e02",o:new P(1.258907706E7,2565305.02),C:Z,D:[7,9]},{B:"\\u6e5b\\u6c5f\\u5e02",o:new P(1.228601939E7,2409244.55),C:Z,D:[7,9]},{B:"\\u8302\\u540d\\u5e02",o:new P(1.234899961E7,2455913.03),C:Z,D:[7,9]},{B:"\\u8087\\u5e86\\u5e02",o:new P(1.252044564E7,2621563.68),C:Z,D:[7,9]},{B:"\\u60e0\\u5dde\\u5e02",o:new P(1.273769287E7, 2629228.47),C:Z,D:[8,9]},{B:"\\u6885\\u5dde\\u5e02",o:new P(1.292755225E7,2771587.26),C:Z,D:[7,9]},{B:"\\u6c55\\u5c3e\\u5e02",o:new P(1.284440979E7,2590115.95),C:Z,D:[7,9]},{B:"\\u6cb3\\u6e90\\u5e02",o:new P(1.276927156E7,2705584.51),C:Z,D:[7,9]},{B:"\\u9633\\u6c5f\\u5e02",o:new P(1.246669444E7,2479195.46),C:Z,D:[7,9]},{B:"\\u6e05\\u8fdc\\u5e02",o:new P(1.258621367E7,2698112.83),C:Z,D:[7,9]},{B:"\\u4e1c\\u839e\\u5e02",o:new P(1.266361776E7,2618331.04),C:Z,D:[7,9]},{B:"\\u4e2d\\u5c71\\u5e02",o:new P(1.262365308E7,2557824.08), C:Z,D:[8,9]},{B:"\\u6f6e\\u5dde\\u5e02",o:new P(1.298326614E7,2695080.32),C:Z,D:[8,9]},{B:"\\u63ed\\u9633\\u5e02",o:new P(1.29554097E7,2682130.11),C:Z,D:[8,9]},{B:"\\u4e91\\u6d6e\\u5e02",o:new P(1.247360714E7,2605655.19),C:Z,D:[7,9]},{B:"\\u5357\\u5b81\\u5e02",o:new P(1.206357678E7,2594028.7),C:Z,D:[5,9]},{B:"\\u67f3\\u5dde\\u5e02",o:new P(1.218092228E7,2776089.56),C:Z,D:[7,9]},{B:"\\u6842\\u6797\\u5e02",o:new P(1.227827601E7,2891719.35),C:Z,D:[7,9]},{B:"\\u68a7\\u5dde\\u5e02",o:new P(1.238836717E7,2673421.13),C:Z,D:[7, 9]},{B:"\\u5317\\u6d77\\u5e02",o:new P(1.214803492E7,2434259.23),C:Z,D:[7,9]},{B:"\\u9632\\u57ce\\u6e2f\\u5e02",o:new P(1.206275824E7,2458819.91),C:Z,D:[7,9]},{B:"\\u94a6\\u5dde\\u5e02",o:new P(1.209618474E7,2493766.85),C:Z,D:[8,9]},{B:"\\u8d35\\u6e2f\\u5e02",o:new P(1.220111842E7,2628719.18),C:Z,D:[8,9]},{B:"\\u7389\\u6797\\u5e02",o:new P(1.226430972E7,2572247.58),C:Z,D:[7,9]},{B:"\\u767e\\u8272\\u5e02",o:new P(1.186950163E7,2724850.41),C:Z,D:[7,9]},{B:"\\u8d3a\\u5dde\\u5e02",o:new P(1.242050604E7,2785419.69),C:Z,D:[7, 9]},{B:"\\u6cb3\\u6c60\\u5e02",o:new P(1.203293245E7,2820780.9),C:Z,D:[7,9]},{B:"\\u6765\\u5bbe\\u5e02",o:new P(1.215949606E7,2706113.22),C:Z,D:[7,9]},{B:"\\u5d07\\u5de6\\u5e02",o:new P(1.195283116E7,2541092.75),C:Z,D:[7,9]},{B:"\\u6d77\\u53e3\\u5e02",o:new P(1.228340323E7,2262634.65),C:Z,D:[5,9]},{B:"\\u4e09\\u4e9a\\u5e02",o:new P(1.219159361E7,2054280.47),C:Z,D:[7,9]},{B:"\\u4e94\\u6307\\u5c71\\u5e02",o:new P(1.21922034E7,2115118.31),C:Z,D:[9,9]},{B:"\\u743c\\u6d77\\u5e02",o:new P(1.229883941E7,2171833.78),C:Z,D:[9, 9]},{B:"\\u510b\\u5dde\\u5e02",o:new P(1.219933474E7,2202719.22),C:Z,D:[9,9]},{B:"\\u6587\\u660c\\u5e02",o:new P(1.233475447E7,2205345.6),C:Z,D:[9,9]},{B:"\\u4e07\\u5b81\\u5e02",o:new P(1.228968886E7,2117494.22),C:Z,D:[9,9]},{B:"\\u4e1c\\u65b9\\u5e02",o:new P(1.209493819E7,2153087.07),C:Z,D:[9,9]},{B:"\\u5b9a\\u5b89\\u53bf",o:new P(1.228188148E7,2223659.92),C:Z,D:[9,9]},{B:"\\u5c6f\\u660c\\u53bf",o:new P(1.225750859E7,2183877.5),C:Z,D:[9,9]},{B:"\\u6f84\\u8fc8\\u53bf",o:new P(1.224679354E7,2228213.81),C:Z,D:[9,9]},{B:"\\u4e34\\u9ad8\\u53bf", o:new P(1.163568384E7,3284342.89),C:Z,D:[9,9]},{B:"\\u767d\\u6c99\\u9ece\\u65cf\\u81ea\\u6cbb\\u53bf",o:new P(1.427215715E7,5044605.41),C:Z,D:[9,9]},{B:"\\u660c\\u6c5f\\u9ece\\u65cf\\u81ea\\u6cbb\\u53bf",o:new P(1.427215715E7,5044605.41),C:Z,D:[9,9]},{B:"\\u4e50\\u4e1c\\u9ece\\u65cf\\u81ea\\u6cbb\\u53bf",o:new P(1.427215715E7,5044605.41),C:Z,D:[9,9]},{B:"\\u9675\\u6c34\\u9ece\\u65cf\\u81ea\\u6cbb\\u53bf",o:new P(1.427215715E7,5044605.41),C:Z,D:[9,9]},{B:"\\u4fdd\\u4ead\\u9ece\\u65cf\\u82d7\\u65cf\\u81ea\\u6cbb\\u53bf",o:new P(1.427215715E7, 5044605.41),C:Z,D:[9,9]},{B:"\\u743c\\u4e2d\\u9ece\\u65cf\\u82d7\\u65cf\\u81ea\\u6cbb\\u53bf",o:new P(1.427215715E7,5044605.41),C:Z,D:[9,9]},{B:"\\u91cd\\u5e86\\u5e02",o:new P(1.184984638E7,3437582.53),C:Z,D:[5,9]},{B:"\\u6210\\u90fd\\u5e02",o:new P(1.158524888E7,3567151.84),C:Z,D:[5,9]},{B:"\\u81ea\\u8d21\\u5e02",o:new P(1.166471081E7,3398518.18),C:Z,D:[8,9]},{B:"\\u6500\\u679d\\u82b1\\u5e02",o:new P(1.132399544E7,3052819.58),C:Z,D:[7,9]},{B:"\\u6cf8\\u5dde\\u5e02",o:new P(1.173866293E7,3339244.88),C:Z,D:[7,9]},{B:"\\u5fb7\\u9633\\u5e02", o:new P(1.162232681E7,3627742.01),C:Z,D:[7,9]},{B:"\\u7ef5\\u9633\\u5e02",o:new P(1.165370954E7,3671830.29),C:Z,D:[7,9]},{B:"\\u5e7f\\u5143\\u5e02",o:new P(1.178330189E7,3798266.61),C:Z,D:[7,9]},{B:"\\u9042\\u5b81\\u5e02",o:new P(1.175261568E7,3550145.61),C:Z,D:[7,9]},{B:"\\u5185\\u6c5f\\u5e02",o:new P(1.169593316E7,3429168.69),C:Z,D:[7,9]},{B:"\\u4e50\\u5c71\\u5e02",o:new P(1.155195965E7,3425604.02),C:Z,D:[7,9]},{B:"\\u5357\\u5145\\u5e02",o:new P(1.181303976E7,3590300.79),C:Z,D:[7,9]},{B:"\\u7709\\u5c71\\u5e02",o:new P(1.156121596E7, 3492381.09),C:Z,D:[8,9]},{B:"\\u5b9c\\u5bbe\\u5e02",o:new P(1.16496864E7,3324145.29),C:Z,D:[7,9]},{B:"\\u5e7f\\u5b89\\u5e02",o:new P(1.187120628E7,3541167.9),C:Z,D:[7,9]},{B:"\\u8fbe\\u5dde\\u5e02",o:new P(1.196462416E7,3639026.15),C:Z,D:[7,9]},{B:"\\u96c5\\u5b89\\u5e02",o:new P(1.146823433E7,3480224.33),C:Z,D:[7,9]},{B:"\\u5df4\\u4e2d\\u5e02",o:new P(1.188364069E7,3723597.18),C:Z,D:[7,9]},{B:"\\u8d44\\u9633\\u5e02",o:new P(1.164804568E7,3499522.66),C:Z,D:[8,9]},{B:"\\u963f\\u575d\\u85cf\\u65cf\\u7f8c\\u65cf\\u81ea\\u6cbb\\u5dde", o:new P(1.13805074E7,3728228.76),C:Z,D:[7,9]},{B:"\\u7518\\u5b5c\\u85cf\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.135132558E7,3489245.11),C:Z,D:[7,9]},{B:"\\u51c9\\u5c71\\u5f5d\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.138524665E7,3214579.77),C:Z,D:[7,9]},{B:"\\u8d35\\u9633\\u5e02",o:new P(1.187051966E7,3060500.8),C:Z,D:[5,9]},{B:"\\u516d\\u76d8\\u6c34\\u5e02",o:new P(1.167058944E7,3054081.9),C:Z,D:[7,9]},{B:"\\u9075\\u4e49\\u5e02",o:new P(1.190392155E7,3195127.87),C:Z,D:[7,9]},{B:"\\u5b89\\u987a\\u5e02",o:new P(1.179486899E7,3012140.6), C:Z,D:[7,9]},{B:"\\u94dc\\u4ec1\\u5730\\u533a",o:new P(1.215250778E7,3190837.66),C:Z,D:[7,9]},{B:"\\u9ed4\\u897f\\u5357\\u5e03\\u4f9d\\u65cf\\u82d7\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.167900108E7,2869017.96),C:Z,D:[7,9]},{B:"\\u6bd5\\u8282\\u5730\\u533a",o:new P(1.172103141E7,3142281.31),C:Z,D:[7,9]},{B:"\\u9ed4\\u4e1c\\u5357\\u82d7\\u65cf\\u4f97\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.202055046E7,3053190.16),C:Z,D:[7,9]},{B:"\\u9ed4\\u5357\\u5e03\\u4f9d\\u65cf\\u82d7\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.197016471E7,3012312.19),C:Z, D:[7,9]},{B:"\\u6606\\u660e\\u5e02",o:new P(1.14354367E7,2863224.69),C:Z,D:[5,9]},{B:"\\u66f2\\u9756\\u5e02",o:new P(1.155538253E7,2918266.01),C:Z,D:[7,9]},{B:"\\u7389\\u6eaa\\u5e02",o:new P(1.141628645E7,2779261.88),C:Z,D:[7,9]},{B:"\\u4fdd\\u5c71\\u5e02",o:new P(1.103962837E7,2872619.83),C:Z,D:[7,9]},{B:"\\u662d\\u901a\\u5e02",o:new P(1.154639116E7,3146685.98),C:Z,D:[7,9]},{B:"\\u4e3d\\u6c5f\\u5e02",o:new P(1.115836761E7,3089380.29),C:Z,D:[7,9]},{B:"\\u4e34\\u6ca7\\u5e02",o:new P(1.114163522E7,2721813.79),C:Z,D:[7, 9]},{B:"\\u695a\\u96c4\\u5f5d\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.130289047E7,2863837.49),C:Z,D:[7,9]},{B:"\\u7ea2\\u6cb3\\u54c8\\u5c3c\\u65cf\\u5f5d\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.13805074E7,3740772.75),C:Z,D:[7,9]},{B:"\\u6587\\u5c71\\u58ee\\u65cf\\u82d7\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.160607041E7,2660260.24),C:Z,D:[7,9]},{B:"\\u666e\\u6d31\\u5e02",o:new P(1.124081051E7,2589692.16),C:Z,D:[8,9]},{B:"\\u897f\\u53cc\\u7248\\u7eb3\\u50a3\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.122158475E7,2496986.94),C:Z,D:[7,9]},{B:"\\u5927\\u7406\\u767d\\u65cf\\u81ea\\u6cbb\\u5dde", o:new P(1.116259344E7,2932487.29),C:Z,D:[7,9]},{B:"\\u5fb7\\u5b8f\\u50a3\\u65cf\\u666f\\u9887\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.097526362E7,2789037.62),C:Z,D:[7,9]},{B:"\\u6012\\u6c5f\\u5088\\u50f3\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.100507724E7,2963098.98),C:Z,D:[7,9]},{B:"\\u8fea\\u5e86\\u85cf\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.109972407E7,3206846.47),C:Z,D:[7,9]},{B:"\\u62c9\\u8428\\u5e02",o:new P(10143520,3437204.04),C:Z,D:[5,9]},{B:"\\u660c\\u90fd\\u5730\\u533a",o:new P(1.08186096E7,3629569.73),C:Z,D:[7,9]},{B:"\\u5c71\\u5357\\u5730\\u533a", o:new P(1.021725503E7,3384053.82),C:Z,D:[7,9]},{B:"\\u65e5\\u5580\\u5219\\u5730\\u533a",o:new P(9895060.53,3389319.88),C:Z,D:[7,9]},{B:"\\u90a3\\u66f2\\u5730\\u533a",o:new P(1.024898914E7,3672743.64),C:Z,D:[7,9]},{B:"\\u963f\\u91cc\\u5730\\u533a",o:new P(9033914.88,3534099.27),C:Z,D:[7,9]},{B:"\\u6797\\u829d\\u5730\\u533a",o:new P(1.050495382E7,3440916.27),C:Z,D:[7,9]},{B:"\\u897f\\u5b89\\u5e02",o:new P(1.212685248E7,4041048.13),C:Z,D:[5,9]},{B:"\\u94dc\\u5ddd\\u5e02",o:new P(1.212856149E7,4126022.53),C:Z,D:[7,9]},{B:"\\u5b9d\\u9e21\\u5e02", o:new P(1.192768136E7,4054988.15),C:Z,D:[7,9]},{B:"\\u54b8\\u9633\\u5e02",o:new P(1.210235668E7,4049604.29),C:Z,D:[8,9]},{B:"\\u6e2d\\u5357\\u5e02",o:new P(1.219149518E7,4072416.28),C:Z,D:[7,9]},{B:"\\u5ef6\\u5b89\\u5e02",o:new P(1.218921144E7,4356570.08),C:Z,D:[7,9]},{B:"\\u6c49\\u4e2d\\u5e02",o:new P(1.191463981E7,3881566.87),C:Z,D:[7,9]},{B:"\\u6986\\u6797\\u5e02",o:new P(1.221646444E7,4593874.99),C:Z,D:[7,9]},{B:"\\u5b89\\u5eb7\\u5e02",o:new P(1.213775212E7,3831579.1),C:Z,D:[7,9]},{B:"\\u5546\\u6d1b\\u5e02",o:new P(1.223875885E7, 3988163.54),C:Z,D:[7,9]},{B:"\\u5170\\u5dde\\u5e02",o:new P(1.155916065E7,4284481.62),C:Z,D:[5,9]},{B:"\\u5609\\u5cea\\u5173\\u5e02",o:new P(1.094239153E7,4806166.82),C:Z,D:[8,9]},{B:"\\u91d1\\u660c\\u5e02",o:new P(1.137633355E7,4627477.91),C:Z,D:[7,9]},{B:"\\u767d\\u94f6\\u5e02",o:new P(11593403,4350996.94),C:Z,D:[7,9]},{B:"\\u5929\\u6c34\\u5e02",o:new P(1.177010649E7,4083646.7),C:Z,D:[7,9]},{B:"\\u6b66\\u5a01\\u5e02",o:new P(1.14264471E7,4544105.57),C:Z,D:[7,9]},{B:"\\u5f20\\u6396\\u5e02",o:new P(1.118285571E7,4684858.01), C:Z,D:[7,9]},{B:"\\u5e73\\u51c9\\u5e02",o:new P(1.187473404E7,4213583.82),C:Z,D:[7,9]},{B:"\\u9152\\u6cc9\\u5e02",o:new P(1.096513556E7,4801282.37),C:Z,D:[7,9]},{B:"\\u5e86\\u9633\\u5e02",o:new P(1.198249448E7,4240364.21),C:Z,D:[7,9]},{B:"\\u5b9a\\u897f\\u5e02",o:new P(1.164777893E7,4218809.12),C:Z,D:[7,9]},{B:"\\u9647\\u5357\\u5e02",o:new P(1.168075314E7,3925419.77),C:Z,D:[7,9]},{B:"\\u4e34\\u590f\\u56de\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.149023588E7,4221664.83),C:Z,D:[7,9]},{B:"\\u7518\\u5357\\u85cf\\u65cf\\u81ea\\u6cbb\\u5dde", o:new P(1.145697069E7,4137705.18),C:Z,D:[7,9]},{B:"\\u897f\\u5b81\\u5e02",o:new P(1.133042455E7,4360836.12),C:Z,D:[5,9]},{B:"\\u6d77\\u4e1c\\u5730\\u533a",o:new P(1.136772454E7,4345818.22),C:Z,D:[7,9]},{B:"\\u6d77\\u5317\\u85cf\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.123307971E7,4407698.25),C:Z,D:[7,9]},{B:"\\u9ec4\\u5357\\u85cf\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.136701869E7,4210804.21),C:Z,D:[7,9]},{B:"\\u6d77\\u5357\\u85cf\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.120187652E7,4315364.9),C:Z,D:[7,9]},{B:"\\u679c\\u6d1b\\u85cf\\u65cf\\u81ea\\u6cbb\\u5dde", o:new P(1.116006336E7,4068657.46),C:Z,D:[7,9]},{B:"\\u7389\\u6811\\u85cf\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.080074697E7,3875570.18),C:Z,D:[7,9]},{B:"\\u6d77\\u897f\\u8499\\u53e4\\u65cf\\u85cf\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(1.081693601E7,4468024.21),C:Z,D:[7,9]},{B:"\\u94f6\\u5ddd\\u5e02",o:new P(1.183289883E7,4616373.5),C:Z,D:[5,9]},{B:"\\u77f3\\u5634\\u5c71\\u5e02",o:new P(1.184171118E7,4698078.16),C:Z,D:[7,9]},{B:"\\u5434\\u5fe0\\u5e02",o:new P(1.182282987E7,4553415.21),C:Z,D:[7,9]},{B:"\\u56fa\\u539f\\u5e02",o:new P(1.182773154E7, 4278231.51),C:Z,D:[8,9]},{B:"\\u4e2d\\u536b\\u5e02",o:new P(1.17087377E7,4485946.9),C:Z,D:[7,9]},{B:"\\u4e4c\\u9c81\\u6728\\u9f50\\u5e02",o:new P(9753667.88,5409369.63),C:Z,D:[5,9]},{B:"\\u514b\\u62c9\\u739b\\u4f9d\\u5e02",o:new P(9450655.5,5683311.14),C:Z,D:[7,9]},{B:"\\u5410\\u9c81\\u756a\\u5730\\u533a",o:new P(9929119.54,5277242.75),C:Z,D:[7,9]},{B:"\\u54c8\\u5bc6\\u5730\\u533a",o:new P(1.041095095E7,5256019.72),C:Z,D:[7,9]},{B:"\\u660c\\u5409\\u56de\\u65cf\\u81ea\\u6cbb\\u5dde",o:new P(9719944.71,5438088.99),C:Z,D:[7,9]}, {B:"\\u535a\\u5c14\\u5854\\u62c9\\u8499\\u53e4\\u81ea\\u6cbb\\u5dde",o:new P(9137172.41,5576651.41),C:Z,D:[7,9]},{B:"\\u5df4\\u97f3\\u90ed\\u695e\\u8499\\u53e4\\u81ea\\u6cbb\\u5dde",o:new P(9590451.71,5097890.07),C:Z,D:[7,9]},{B:"\\u963f\\u514b\\u82cf\\u5730\\u533a",o:new P(8935351.95,5009761.4),C:Z,D:[7,9]},{B:"\\u5580\\u4ec0\\u5730\\u533a",o:new P(8459954.24,4762722.83),C:Z,D:[7,9]},{B:"\\u548c\\u7530\\u5730\\u533a",o:new P(8898707.07,4429816.8),C:Z,D:[7,9]},{B:"\\u4f0a\\u7281\\u54c8\\u8428\\u514b\\u81ea\\u6cbb\\u5dde",o:new P(9054161.44, 5423973.33),C:Z,D:[7,9]},{B:"\\u5854\\u57ce\\u5730\\u533a",o:new P(9238596.44,5870707.55),C:Z,D:[7,9]},{B:"\\u963f\\u52d2\\u6cf0\\u5730\\u533a",o:new P(9812358.95,6050881.84),C:Z,D:[7,9]},{B:"\\u77f3\\u6cb3\\u5b50\\u5e02",o:new P(9583272.07,5483579.8),C:Z,D:[9,9]},{B:"\\u963f\\u62c9\\u5c14\\u5e02",o:new P(9049687.77,4918103.23),C:Z,D:[9,9]},{B:"\\u56fe\\u6728\\u8212\\u514b\\u5e02",o:new P(8802730.81,4819584.88),C:Z,D:[9,9]},{B:"\\u4e94\\u5bb6\\u6e20\\u5e02",o:new P(9746120.75,5462086.91),C:Z,D:[9,9]},{B:"\\u9999\\u6e2f\\u7279\\u522b\\u884c\\u653f\\u533a", o:new P(1.271433369E7,2538103.92),C:Z,D:[5,9]},{B:"\\u6fb3\\u95e8\\u7279\\u522b\\u884c\\u653f\\u533a",o:new P(1.264258348E7,2514883.38),C:Z,D:[5,9]}],Ch=0,qj=pj.length;Ch<qj;Ch++)pj[Ch].o=R.hc(pj[Ch].o); '
);
| 7,480.833333 | 44,834 | 0.640548 |
e3783c2f447157ad12e8b0bfb48950a2104bd1f1 | 1,456 | js | JavaScript | src/components/timeline-item/TimelineItem.js | yipster8888/blm-timeline | 68dba7bd53240b009b13b1cef08754e2a6ffaab7 | [
"MIT"
] | null | null | null | src/components/timeline-item/TimelineItem.js | yipster8888/blm-timeline | 68dba7bd53240b009b13b1cef08754e2a6ffaab7 | [
"MIT"
] | 1 | 2022-02-15T03:17:03.000Z | 2022-02-15T03:17:03.000Z | src/components/timeline-item/TimelineItem.js | yipster8888/blm-timeline | 68dba7bd53240b009b13b1cef08754e2a6ffaab7 | [
"MIT"
] | 1 | 2020-09-07T16:23:12.000Z | 2020-09-07T16:23:12.000Z | import React from "react";
import "./TimelineItem.css";
function TimelineItem(props) {
//Determine the colour for the tag
const date = new Date(props.data.date);
return (
<div className="timeline-item">
<div className="timeline-item-content">
{props.data.cityName && (
<span className="tag" style={{ background: props.data.colour }}>
{props.data.cityName}
</span>
)}
<time>
{getMonthName(date.getMonth()) +
" " +
date.getDate() +
", " +
date.getFullYear()}
</time>
<p className="timeline-item-title">{props.data.title}</p>
<p className="timeline-item-p">"{props.data.text}"</p>
{props.data.imageURL && (
<img src={props.data.imageURL} alt={props.data.title} />
)}
{props.data.newsURL && (
<a
href={props.data.newsURL}
target="_blank"
rel="noopener noreferrer"
>
{"read more"}
</a>
)}
<span className="circle"></span>
</div>
</div>
);
}
// Shortened months included to avoid date/location tag being squished
function getMonthName(index) {
const monthNames = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sept",
"Oct",
"Nov",
"Dec",
];
return monthNames[index];
}
export default TimelineItem;
| 23.111111 | 74 | 0.51511 |
e37858be3b868267cccca232bd8a023bed88f68a | 1,582 | js | JavaScript | src/lib/requestUtils.js | rhgrieve/drops-client-react | 08154d4abf11d32ebeab37e48173bb7d4ed57e9a | [
"MIT"
] | null | null | null | src/lib/requestUtils.js | rhgrieve/drops-client-react | 08154d4abf11d32ebeab37e48173bb7d4ed57e9a | [
"MIT"
] | 5 | 2021-05-11T07:50:09.000Z | 2022-02-27T01:39:24.000Z | src/lib/requestUtils.js | rhgrieve/drops-client-react | 08154d4abf11d32ebeab37e48173bb7d4ed57e9a | [
"MIT"
] | null | null | null | const types = {
NOTE: "NOTE",
LIST: "LIST"
};
const methods = {
PUT: "PUT",
DELETE: "DELETE",
POST: "POST",
GET: "GET"
};
function execute(url, method, params = null) {
let xhr = new XMLHttpRequest();
let data;
xhr.addEventListener("load", () => {
return xhr.responseText;
});
if (params) {
data = new URLSearchParams();
const paramList = Object.entries(params);
for (let param in paramList) {
const key = paramList[param][0];
const value = paramList[param][1];
data.append(key, value);
}
}
return new Promise((resolve, reject) => {
xhr.onreadystatechange = () => {
if (xhr.readyState !== 4) return;
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr);
} else {
reject({
status: xhr.status,
statusText: xhr.statusText
});
}
};
xhr.open(method || "GET", url, true);
if (data) {
xhr.send(data);
} else xhr.send();
});
}
async function put(url, type, params) {
if (type === types.NOTE) {
let xhr = new XMLHttpRequest();
xhr.addEventListener("load", () => {
return xhr.responseText;
});
let data = new URLSearchParams();
data.append("title", params.title);
data.append("message", params.message);
xhr.open("PUT", url);
xhr.send(data);
}
}
async function del(url) {
let xhr = new XMLHttpRequest();
xhr.addEventListener("load", () => {
return xhr.responseText;
});
xhr.open("DELETE", url);
xhr.send();
}
module.exports = { types, methods, execute };
| 19.292683 | 50 | 0.564475 |
e37867665acae541ce01f5c50336cb68003902e2 | 3,473 | js | JavaScript | src/components/adminPage.js | jayeshkr77/antDesign | 1f1bb61b754a1fa0f4b260932477883bf534f130 | [
"Unlicense"
] | null | null | null | src/components/adminPage.js | jayeshkr77/antDesign | 1f1bb61b754a1fa0f4b260932477883bf534f130 | [
"Unlicense"
] | null | null | null | src/components/adminPage.js | jayeshkr77/antDesign | 1f1bb61b754a1fa0f4b260932477883bf534f130 | [
"Unlicense"
] | null | null | null | import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
import { Form, Icon, Input, Button, Checkbox, message } from 'antd';
import './css/admin.css'
import axios from 'axios';
import Example from './blogform';
import AdminForm from './adminform';
const FormItem = Form.Item;
class AdminLoginForm extends Component {
constructor(props) {
super(props);
this.state = {
authUser: false
}
}
componentDidMount() {
if (localStorage.getItem('adminToken')) {
this.setState({
authUser: true
});
}
}
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
console.log(err);
if (!err) {
const msg = message.loading('Signing in', 0);
axios({
method: 'post',
url: 'https://56y1lomy27.execute-api.ap-south-1.amazonaws.com/v1/login1',
data: {
email: values.email,
password: values.password
}
}).then((res) => {
var userToken = res.data.Token;
localStorage.setItem('adminToken', userToken);
this.setState({
authUser: !this.authUser,
});
setTimeout(msg)
}).catch((error) => {
console.log(error)
setTimeout(msg);
message.error('Not Found');
})
}
});
}
render() {
const { getFieldDecorator } = this.props.form;
if (!this.state.authUser) {
return (
<div >
<div className="container admin-form" style={{ width: '300px', padding: '30px', margin: '200px auto', border: '1px solid black' }}>
<Form onSubmit={this.handleSubmit} className="login-form">
<FormItem>
{getFieldDecorator('email', {
rules: [{ required: true, message: 'Please input your username!' }],
})(
<Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0)' }} />} placeholder="Username" />
)}
</FormItem>
<FormItem>
{getFieldDecorator('password', {
rules: [{ required: true, message: 'Please input your Password!' }],
})(
<Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0)' }} />} type="password" placeholder="Password" />
)}
</FormItem>
<FormItem>
<Button type="primary" htmlType="submit" className="login-form-button">Log in</Button>
</FormItem>
</Form>
</div>
</div>
);
} else {
return <Redirect to='/admin/dashboard' />;
}
}
}
const WrappedNormalLoginForm = Form.create()(AdminLoginForm);
export default WrappedNormalLoginForm; | 35.080808 | 151 | 0.430176 |
e3796f8764b7f72d715fd31bcdbc281b30da06f8 | 39 | js | JavaScript | packages/1972/12/04/index.js | antonmedv/year | ae5d8524f58eaad481c2ba599389c7a9a38c0819 | [
"MIT"
] | 7 | 2017-07-03T19:53:01.000Z | 2021-04-05T18:15:55.000Z | packages/1972/12/04/index.js | antonmedv/year | ae5d8524f58eaad481c2ba599389c7a9a38c0819 | [
"MIT"
] | 1 | 2018-09-05T11:53:41.000Z | 2018-12-16T12:36:21.000Z | packages/1972/12/04/index.js | antonmedv/year | ae5d8524f58eaad481c2ba599389c7a9a38c0819 | [
"MIT"
] | 2 | 2019-01-27T16:57:34.000Z | 2020-10-11T09:30:25.000Z | module.exports = new Date(1972, 11, 4)
| 19.5 | 38 | 0.692308 |
e37a6b13d59cd6549e5dffb5b693e269afe50c81 | 1,124 | js | JavaScript | src/bed-finder/SubmitPhone.js | ocelotconsulting/global-hack-6 | 616c5968375963a91a58321fcead8d23ace892d7 | [
"MIT"
] | 1 | 2021-03-03T10:03:09.000Z | 2021-03-03T10:03:09.000Z | src/bed-finder/SubmitPhone.js | ocelotconsulting/global-hack-6 | 616c5968375963a91a58321fcead8d23ace892d7 | [
"MIT"
] | null | null | null | src/bed-finder/SubmitPhone.js | ocelotconsulting/global-hack-6 | 616c5968375963a91a58321fcead8d23ace892d7 | [
"MIT"
] | null | null | null | import React from "react";
import {render} from "react-dom";
export default class ProfileDetails extends React.Component {
submit(e) {
e.preventDefault()
const num = this.state.number.replace(/\D/g, '')
this.props.requestNotification(this.props.shelter.id, (num.length === 11) ? num : ('11111111111' + num).slice(-11))
}
handleChange(e) {
this.setState({number: e.target.value})
}
render () {
return (
<div className="submit-phone">
<div className="title">Enter Phone Number</div>
<form>
<div className="form-group">
<label>Number</label>
<input className="form-control" type="tel" placeholder="3145555555" onChange={(e) => this.handleChange(e)}/>
</div>
<button className="btn btn-primary" onClick={(e) => this.submit(e)}>Confirm</button>
<div className="alert alert-warning" role="alert">A single text message is sent when a bed is free.
Messaging fees may apply.
</div>
</form>
</div>
)
}
}
| 35.125 | 128 | 0.565836 |
e37ee237964fec36c7cac02b55e7eabfdb042f42 | 4,067 | js | JavaScript | src/pages/application/components/ApplicationList.js | factly/dega-identity | 6544564d97dbe88802a0c36981f81b00fbe060b2 | [
"MIT"
] | 2 | 2021-01-15T09:51:57.000Z | 2021-03-15T21:23:01.000Z | src/pages/application/components/ApplicationList.js | factly/dega-identity | 6544564d97dbe88802a0c36981f81b00fbe060b2 | [
"MIT"
] | 37 | 2020-06-27T13:35:32.000Z | 2021-04-30T16:01:56.000Z | src/pages/application/components/ApplicationList.js | factly/dega-identity | 6544564d97dbe88802a0c36981f81b00fbe060b2 | [
"MIT"
] | 1 | 2020-11-20T18:27:27.000Z | 2020-11-20T18:27:27.000Z | import React from 'react';
import { Popconfirm, Button, Table, Space, Avatar, Tooltip } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { getApplications, deleteApplication } from '../../../actions/application';
import { Link } from 'react-router-dom';
function ApplicationList() {
const dispatch = useDispatch();
const [filters, setFilters] = React.useState({
page: 1,
limit: 5,
});
const { applications, loading, total } = useSelector((state) => {
const node = state.application.req[0];
if (node)
return {
applications: node.data.map((element) => state.application.details[element]),
loading: state.application.loading,
total: node.total,
};
return { applications: [], loading: state.application.loading, total: 0 };
});
React.useEffect(() => {
fetchApplications();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dispatch]);
const fetchApplications = () => {
dispatch(getApplications());
};
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
width: '15%',
render: (_, record) => {
return <Link to={`/applications/${record.id}/detail`}>
{record.name}
</Link>
}
},
{
title: 'Slug',
dataIndex: 'slug',
key: 'slug',
width: '15%',
},
{
title: 'Description',
dataIndex: 'description',
key: 'description',
width: '40%',
ellipsis: true,
},
{
title: 'Users',
dataIndex: 'users',
key: 'users',
width: '30%',
render: (_, record) => {
return (
<Avatar.Group maxCount={4} maxStyle={{ color: '#f56a00', backgroundColor: '#fde3cf' }}>
<Tooltip title="Add user" placement="top">
<Link
className="ant-dropdown-link"
style={{
marginRight: 8,
}}
to={`/applications/${record.id}/users`}
>
<Avatar icon={<PlusOutlined />} />
</Link>
</Tooltip>
{record.users &&
record.users.length > 0 &&
record.users.map((each) => (
<Tooltip title={each.email} placement="top">
<Avatar
style={{
backgroundColor:
'#' + ((Math.random() * 0xffffff) << 0).toString(16).padStart(6, '0'),
}}
>
{each.email.charAt(0).toUpperCase()}
</Avatar>
</Tooltip>
))}
</Avatar.Group>
);
},
},
{
title: 'Action',
dataIndex: 'operation',
width: '20%',
render: (_, record) => {
return (
<span>
<Link
className="ant-dropdown-link"
style={{
marginRight: 8,
}}
to={`/applications/${record.id}/edit`}
>
<Button>Edit</Button>
</Link>
<Popconfirm
title="Sure to Delete?"
onConfirm={() =>
dispatch(deleteApplication(record.id)).then(() => fetchApplications())
}
>
<Link to="" className="ant-dropdown-link">
<Button>Delete</Button>
</Link>
</Popconfirm>
</span>
);
},
},
];
return (
<Space direction="vertical">
<Table
bordered
columns={columns}
dataSource={applications}
loading={loading}
rowKey={'id'}
pagination={{
total: total,
current: filters.page,
pageSize: filters.limit,
onChange: (pageNumber, pageSize) =>
setFilters({ ...filters, page: pageNumber, limit: pageSize }),
}}
/>
</Space>
);
}
export default ApplicationList;
| 26.756579 | 97 | 0.476764 |
e37f0a12d63cb433a56fa8d033381667e5681cbb | 971 | js | JavaScript | scripts/utils/cp.js | nia3y/dobux | 81b5eef14ecc59aaaa575599c75063c4f00835a7 | [
"MIT"
] | null | null | null | scripts/utils/cp.js | nia3y/dobux | 81b5eef14ecc59aaaa575599c75063c4f00835a7 | [
"MIT"
] | null | null | null | scripts/utils/cp.js | nia3y/dobux | 81b5eef14ecc59aaaa575599c75063c4f00835a7 | [
"MIT"
] | null | null | null | const cp = require('child_process')
exports.exec = (cmd, options = {}, output = {}) => {
if (!options.maxBuffer) {
options.maxBuffer = 2 * 1024 * 1024
}
return new Promise((resolve, reject) => {
cp.exec(cmd, options, (err, stdout, stderr) => {
if (err) {
reject(err)
} else {
output.stdout = stdout.toString()
output.stderr = stderr.toString()
resolve(stdout || stderr)
}
})
})
}
exports.spawn = (bin, args, options) => {
return new Promise((resolve, reject) => {
const child = cp.spawn(bin, args, options)
let hasError = false
// 子进程出现 error 事件时, exit 可能会触发, 也可能不会
child.once('error', err => {
hasError = true
reject(err)
})
child.once('exit', code => {
if (hasError) {
return
}
if (code) {
reject(new Error(`failed to exec command ${bin} the code is ${code}`))
} else {
resolve(code)
}
})
})
}
| 21.108696 | 78 | 0.531411 |
e37f56e4f2405d20c8b0430b8dc8b711c615b327 | 1,175 | js | JavaScript | www/js/controllers/charview.js | cthos/gw2-ionic | c8845ec753c993a0838685a7198c167e4fdfcb5d | [
"BSD-3-Clause"
] | 1 | 2019-06-07T08:11:33.000Z | 2019-06-07T08:11:33.000Z | www/js/controllers/charview.js | cthos/gw2-ionic | c8845ec753c993a0838685a7198c167e4fdfcb5d | [
"BSD-3-Clause"
] | null | null | null | www/js/controllers/charview.js | cthos/gw2-ionic | c8845ec753c993a0838685a7198c167e4fdfcb5d | [
"BSD-3-Clause"
] | null | null | null | (function () {
'use strict';
angular
.module('app.controllers')
.controller('CharacterViewCtrl', CharacterViewCtrl);
CharacterViewCtrl.$inject = ['$scope', '$ionicLoading', '$stateParams', 'GW2API'];
function CharacterViewCtrl($scope, $ionicLoading, $stateParams, GW2API) {
var vm = this;
vm.reload = reload;
activate();
////////////////
function activate() {
GW2API.tokenHasPermission('characters').then(function (hasPerm) {
if (hasPerm) {
$ionicLoading.show();
loadCharacters().then(function () {
$ionicLoading.hide();
});
}
vm.error = "Your API token needs the 'builds' permission to access this page.";
});
}
function loadCharacters() {
return GW2API.api.getCharacters($stateParams.charname).then(function (character) {
vm.character = character;
});
}
function reload() {
GW2API.api.setCache(false);
GW2API.api.setStoreInCache(true);
loadCharacters().then(function () {
GW2API.api.setCache(true);
$scope.$broadcast('scroll.refreshComplete');
});
}
}
})(); | 23.979592 | 88 | 0.58383 |
e380014399a6d1d2bd67cb25eb412b5b1b7bcbed | 386 | js | JavaScript | colors/colors.js | lozarcher/KingstonPound | d35fb260ba405ba44f6193f338a66a607ce38cad | [
"MIT"
] | 3 | 2018-03-04T21:15:56.000Z | 2021-01-05T01:23:57.000Z | colors/colors.js | lozarcher/KingstonPound | d35fb260ba405ba44f6193f338a66a607ce38cad | [
"MIT"
] | null | null | null | colors/colors.js | lozarcher/KingstonPound | d35fb260ba405ba44f6193f338a66a607ce38cad | [
"MIT"
] | null | null | null | const colors = {
darkBlue: '#204497',
primaryBlue: '#158ACB',
secondaryBlue: '#5CCAF2',
orange: '#F28F30',
offBlack: '#393939',
gray: '#6A6A6A',
gray2: '#8A8A8A',
gray3: '#B1B1B1',
gray4: '#D2D2D2',
gray5: '#E2E2E2',
offWhite: '#F4F4F4',
white: '#FFFFFF',
pink: '#DD1565',
lightGray: '#eee',
transparent: '#00000000',
red: 'red'
}
export default colors
| 18.380952 | 27 | 0.601036 |
e3804d217093517f97605c25e1d5c5ff7b6295f4 | 43 | js | JavaScript | lib/viewsHandler/index.js | vaquitalabs/receptionist | a275e6303aa6695d377aaa97c22903e3432d26d0 | [
"MIT"
] | 1 | 2017-02-26T00:31:23.000Z | 2017-02-26T00:31:23.000Z | lib/viewsHandler/index.js | vaquitalabs/receptionist | a275e6303aa6695d377aaa97c22903e3432d26d0 | [
"MIT"
] | 3 | 2017-06-29T02:49:45.000Z | 2018-02-15T07:27:33.000Z | lib/viewsHandler/index.js | vaquitalabs/receptionist | a275e6303aa6695d377aaa97c22903e3432d26d0 | [
"MIT"
] | null | null | null | module.exports = require('./viewsHandler')
| 21.5 | 42 | 0.744186 |
e38065a42194269e9f62b947726965e72775231a | 761 | js | JavaScript | server/totara/completionimport/amd/build/select_evidence_type.min.js | woon5118/totara_ub | a38f8e5433c93d295f6768fb24e5eecefa8294cd | [
"PostgreSQL"
] | null | null | null | server/totara/completionimport/amd/build/select_evidence_type.min.js | woon5118/totara_ub | a38f8e5433c93d295f6768fb24e5eecefa8294cd | [
"PostgreSQL"
] | null | null | null | server/totara/completionimport/amd/build/select_evidence_type.min.js | woon5118/totara_ub | a38f8e5433c93d295f6768fb24e5eecefa8294cd | [
"PostgreSQL"
] | null | null | null | define(["core/ajax"],function(a){function b(b){var c=document.querySelector(".completionimport_evidencetype_customfields");if(c){if(!b||0==b)return void c.classList.add("hidden");M.util.js_pending("totara_coursecompletion_evidence_type_fields_"+b),a.call([{methodname:"totara_evidence_type_import_fields",args:{type_id:b}}])[0].then(function(a){if(!a.length)return void c.classList.add("hidden");var d=a.join(","),e=c.querySelectorAll(".felement.fstatic");e.length<2||(e[1].innerHTML=d,c.classList.remove("hidden"),M.util.js_complete("totara_coursecompletion_evidence_type_fields_"+b))})}}function c(){var a=document.getElementById("id_evidencetype");if(a){a.addEventListener("change",function(a){b(a.currentTarget.value)});var c=a.value;b(c)}}return{init:c}}); | 761 | 761 | 0.768725 |
e381b893fd89e2baa832175736608d17e979b3cc | 11,085 | js | JavaScript | application/src/js/jquery.filterable.js | cmooreitrs/monitor-ninja | ca70126712f37fabbe7409509eeb3624c93bc96d | [
"BSD-3-Clause"
] | 21 | 2016-06-10T07:23:45.000Z | 2019-02-07T03:22:25.000Z | application/src/js/jquery.filterable.js | cmooreitrs/monitor-ninja | ca70126712f37fabbe7409509eeb3624c93bc96d | [
"BSD-3-Clause"
] | 57 | 2019-03-25T13:42:01.000Z | 2022-03-22T10:14:51.000Z | application/src/js/jquery.filterable.js | cmooreitrs/monitor-ninja | ca70126712f37fabbe7409509eeb3624c93bc96d | [
"BSD-3-Clause"
] | 13 | 2016-06-14T14:21:59.000Z | 2018-11-20T15:52:49.000Z |
( function ( jQuery, global ) {
var settings = {
"limit": 1000,
"selector": "select[data-filterable]",
"host": window.location.protocol + "//" + window.location.host,
"datasource": function ( select ) {
var type = select.attr( 'data-type' ),
root = settings.host + _site_domain + _index_page;
return root + '/listview/fetch_ajax?query=[' + type + 's] all&columns[]=key&limit=1000000';
},
"collector": function ( select, data ) {
var names = [];
for ( var i = 0; i < data.data.length; i++ ) {
names.push( data.data[ i ].key );
}
select.filterable( names );
},
"ajax": {
dataType: 'json',
error: function( xhr ) {
console.log( xhr.responseText );
}
}
};
var getBoxing = function ( filtered, multi ) {
if ( multi ) {
return $( '<div class="jq-filterable-box">' ).append(
$( '<div class="jq-filterable-left">' ).append(
$( '<div class="jq-filterable-searchbox" />' ).append(
$( '<input type="text" class="jq-filterable-filter" placeholder="Search...">' ),
$( '<input type="button" value="➤" class="jq-filterable-move" title="Use objects matching search">' )
),
filtered.clone()
.addClass( "jq-filterable-list" ),
"<br>",
$( '<div class="jq-filterable-stats">' )
),$( '<div class="jq-filterable-right">' ).append(
$( '<select multiple class="jq-filterable-results">' ),
"<br>",
$( '<div class="jq-filterable-result-stats">' ).append( "No items selected..." )
)
);
} else {
return $( '<div class="jq-filterable-box">' ).append(
$( '<div class="jq-filterable-left">' ).append(
$( '<input type="text" class="jq-filterable-filter" placeholder="Search...">' ),
filtered.clone()
.addClass( "jq-filterable-list" ),
"<br>",
$( '<div class="jq-filterable-stats jq-filterable-largest">' )
)
);
}
}
var Filterable = function Filterable ( filtered, data ) {
var defaults = [];
if ( filtered.find( 'option' ).length > 0 ) {
filtered.find( 'option' ).each( function ( i, e ) {
defaults.push( e.value );
} );
}
var self = this;
this.box = null;
this.matching = 0;
if ( filtered.attr( "multiple" ) ) {
this.box = getBoxing( filtered, true );
this.multiple = true;
} else {
this.box = getBoxing( filtered, false );
this.multiple = false;
}
if (!this.multiple && !filtered.attr('data-required')) {
data.unshift('');
}
this.results = new Set();
this.memory = new Set();
this.data = new Set( data );
this.filter = this.box.find( ".jq-filterable-filter" );
this.filtered = this.box.find( ".jq-filterable-list" );
this.statusbar = this.box.find( '.jq-filterable-stats' );
this.selected = this.box.find( '.jq-filterable-results' );
this.resultstats = this.box.find( '.jq-filterable-result-stats' );
this.mover = this.box.find( '.jq-filterable-move' );
this.form = filtered.closest("form");
this.form.on( "submit", function ( e ) {
self.selected.find( "option" ).attr( "selected", true );
} );
if ( this.multiple ) {
var scrollpos = 0;
this.after = function () {
var list = this.box.find('.jq-filterable-list');
list.scrollTop(scrollpos);
}
this.selected.attr( "id", this.filtered.attr( "id" ) );
this.selected.attr( "name", this.filtered.attr( "name" ) );
this.filtered.attr("id", this.selected.attr("id")+'_tmp');
this.filtered.removeAttr( "name" );
}
filtered.replaceWith( this.box );
var _default = filtered.find( ':selected' );
if ( _default.length > 0 ) {
this.search( this.filter.val(), _default.val() );
if ( this.multiple && defaults.length > 0 ) {
defaults = new Set( defaults );
this.add( defaults );
}
} else {
this.search( this.filter.val() );
if ( defaults.length > 0 ) {
defaults = new Set( defaults );
this.add( defaults );
}
}
// Add relevant events
var key_timeout = null;
this.box.on( "keyup", ".jq-filterable-filter", function ( e ) {
if ( $.inArray( e.which, [ 37, 38, 39, 40 ] ) >= 0 ) return;
else if ( e.which == 13 ) {
clearTimeout( key_timeout );
self.search( self.filter.val() );
} else {
clearTimeout( key_timeout );
key_timeout = setTimeout( function () {
self.search( self.filter.val() );
}, 250 );
}
} );
this.box.on('click', '.deselect_all', function( e ) {
e.preventDefault();
self.reset();
});
if ( this.multiple ) {
this.box.on( "change", ".jq-filterable-list, .jq-filterable-results", function ( e ) {
var parent = $( e.target ),
values = null;
if ( parent.is( "option" ) ) {
parent = parent.closest( 'select' );
}
scrollpos = parent.scrollTop();
values = parent.val();
values = new Set( values );
if ( parent[0] == self.selected[0] )
self.remove( values );
else self.add( values );
} );
this.mover.on( "click", function () {
var values = self.search( self.filter.val(), null, true );
self.add( values );
} );
}
};
Filterable.prototype.batcher = function batcher ( set ) {
var iterator = new SetIterator( set ),
self = this;
this.selected.empty();
return function () {
var fragment = document.createDocumentFragment(),
counter = 0,
index = null,
opt = null;
while ( index = iterator.next() ) {
opt = document.createElement( 'option' );
opt.innerHTML = index;
opt.title = index;
opt.value = index;
fragment.appendChild( opt );
counter++;
if ( counter > 1000 ) break;
}
self.selected.append( fragment );
return ( counter < 1000 );
}
};
Filterable.prototype.add = function add ( set ) {
var self = this;
this.memory.reset();
this.memory = set.union( this.memory );
this.filtered.attr( 'disabled', 'disabled' );
this.box.addClass( 'jq-filterable-working' );
this.form.find( 'input[type="submit"]' )
.attr( 'disabled', 'disabled' );
var batch = this.batcher( this.memory ),
completed = batch(),
interval = setInterval( function () {
completed = batch();
if ( completed ) {
clearInterval( interval );
self.filtered.attr( 'disabled', false );
self.form.find( 'input[type="submit"]' )
.attr( 'disabled', false );
self.box.removeClass( 'jq-filterable-working' );
self.search( self.filter.val() );
}
}, 10 );
};
Filterable.prototype.remove = function remove ( set ) {
var iterator = new SetIterator( set ),
index = null, i = null;
while ( index = iterator.next() ) {
i = this.memory.find( index );
if ( i >= 0 ) this.memory.remove( i );
this.selected.find( 'option[value="' + index + '"]' ).remove();
}
this.search( this.filter.val() );
};
Filterable.prototype.note = function note ( message, type ) {
this.statusbar.html( message );
if ( type && type == "error" )
this.statusbar.attr( "data-state", "error" );
else if ( type && type == "warning" )
this.statusbar.attr( "data-state", "warning" );
else this.statusbar.attr( "data-state", "info" );
};
Filterable.prototype.error = function error ( message ) {
this.filter.css( { "border-color": "#f40" } );
this.note( message, "error" );
};
Filterable.prototype.reset = function reset () {
this.memory.empty();
this.selected.empty();
this.search( this.filter.val() );
};
Filterable.prototype.update_labels = function update_labels ( ) {
if ( this.matching >= settings.limit ) {
this.note( "Not all items shown; " + this.matching + "/" + this.data.size() );
} else {
this.note( this.matching + " Items" );
}
// Fixes IE 9 error with dynamic options
this.selected.css( 'width', '0px' );
this.selected.css( 'width', '' );
if( this.memory.size() > 0 ) {
this.resultstats.html( this.memory.size() + " items selected. <a href='#' class='deselect_all'>Deselect all</a>" );
} else {
this.resultstats.text( "No items selected..." );
}
};
/** method search ( string term )
*
* Searches the data array for regexp matches
* against term, then runs method populate.
*
* @param string term
* @param boolean respond
* @return void
*/
Filterable.prototype.search = function search ( term, source, respond ) {
var memresult = [];
this.results = new Set();
try {
term = new RegExp( term, "i" );
} catch ( e ) {
this.error( "Invalid search ( " + e.message + " ) " );
return;
}
var iterator = new SetIterator( this.data ),
index = null;
while ( ( index = iterator.next() ) != null ) {
if ( index.match( term ) )
this.results.push( index );
}
this.memory.reset();
this.results.reset();
this.results = this.results.diff( this.memory );
this.matching = this.results.size();
if ( respond ) {
this.results.reset();
return this.results;
} else {
this.results.shrink( 0, settings.limit );
this.populate( source );
}
};
/** method populate ( string array data )
*
* Searches the data array for regexp matches
* against term, then runs method populate.
*
* @param string term
* @return void
*/
Filterable.prototype.populate = function populate ( source ) {
var fragment = document.createDocumentFragment(),
iterator = null,
opt = null,
index = 0;
iterator = new SetIterator( this.results );
while ( ( index = iterator.next() ) != null ) {
opt = document.createElement( 'option' );
opt.innerHTML = index;
opt.title = index;
opt.value = index;
fragment.appendChild( opt );
}
this.filtered.empty();
this.filtered.append( fragment );
this.update_labels();
if ( source ) {
this.filtered.val( source );
}
if ( this.multiple ) {
this.filtered.val([]);
this.after();
}
};
var Filterables = [];
var FilterableFactory = function FilterableFactory ( data ) {
var F = ( new Filterable( this, data ) );
Filterables.push( F );
return F;
};
jQuery.filterable_settings = function ( key, value ) {
if ( settings[ key ] ) {
settings[ key ] = value;
}
}
jQuery.fn.filterable = FilterableFactory;
jQuery.fn.filterable.find = function ( element ) {
for ( var i = 0; i < Filterables.length; i++ ) {
if ( Filterables[ i ].selected[ 0 ] == element[ 0 ] ) {
return Filterables[ i ];
}
}
return null;
};
function selectload ( index, element ) {
var select = $( element );
if ( select.attr( 'data-type' ) ) {
settings.ajax.success = function ( data ) {
settings.collector( select, data );
};
settings.ajax.url = settings.datasource( select );
$.ajax( settings.ajax );
} else if (select.length) {
var options = $.map( select.children(), function( option ) {
return option.text;
});
select.children().each( function() {
if (!$(this).attr('selected')) {
select.find('option[value="' + this.text + '"]').remove();
}
} );
select.filterable( options );
}
}
$( document ).ready( function () {
var selects = $( settings.selector );
selects.each( selectload );
} );
} ) ( jQuery, window );
| 22.484787 | 118 | 0.592963 |
e381b946d33da4d6340331fd55c63a1d9ed97361 | 4,892 | js | JavaScript | src/index.js | alextanhongpin/node-eth-api | dd866c45e66c02e0cd3f6ea8cc28b6886ecd6c42 | [
"MIT"
] | null | null | null | src/index.js | alextanhongpin/node-eth-api | dd866c45e66c02e0cd3f6ea8cc28b6886ecd6c42 | [
"MIT"
] | null | null | null | src/index.js | alextanhongpin/node-eth-api | dd866c45e66c02e0cd3f6ea8cc28b6886ecd6c42 | [
"MIT"
] | null | null | null | /*
* src/index.js
*
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
*
* Created by Alex Tan Hong Pin 17/10/2017
* Copyright (c) 2017 alextanhongpin. All rights reserved.
**/
import express from 'express'
import bodyParser from 'body-parser'
import path from 'path'
import helmet from 'helmet'
import morgan from 'morgan'
import Web3 from 'web3'
// Internal dependencies
import config from './config'
import DB from './database'
import Schema from './schema'
import EthService from './eth-service'
// Schemas
import getBlockRequestSchema from './schema/get-block-request.json'
import getBlockResponseSchema from './schema/get-block-response.json'
import getTransactionRequestSchema from './schema/get-transaction-request.json'
import getTransactionResponseSchema from './schema/get-transaction-response.json'
import getTransactionReceiptRequestSchema from './schema/get-transaction-receipt-request.json'
import getTransactionReceiptResponseSchema from './schema/get-transaction-receipt-response.json'
// main is where our application resides
async function main () {
// Create a new application
const app = express()
// Setup middlewares
middlewares(app)
// Setup database
const db = await DB.connect(config.get('db'))
console.log(await setupDatabaseTables(db))
// Setup schemas
const schema = Schema()
// Setup web3
const web3 = new Web3(new Web3.providers.HttpProvider(config.get('web3Provider')))
if (web3.isConnected()) {
console.log(`connected to web3 successfully`)
}
schema.add('getBlockRequest', getBlockRequestSchema)
schema.add('getBlockResponse', getBlockResponseSchema)
schema.add('getTransactionRequest', getTransactionRequestSchema)
schema.add('getTransactionResponse', getTransactionResponseSchema)
schema.add('getTransactionReceiptRequest', getTransactionReceiptRequestSchema)
schema.add('getTransactionReceiptResponse', getTransactionReceiptResponseSchema)
const services = [ EthService ].map(service => service({ db, schema, web3 }))
// Initialize service by looping through them
services.forEach((service) => {
app.use(service.basePath, service.route)
})
app.get('/', async (req, res) => {
res.status(200).json({
endpoints: services.map((service) => service.info),
routes: app.routes
})
})
app.get('/status', async(req, res) => {
res.status(200).json({
isConnected: web3.isConnected(),
syncing: web3.eth.syncing,
blockNumber: web3.eth.blockNumber,
pending: web3.eth.getBlock('pending')
})
})
// Host the schemas as static file
app.use('/schemas', express.static(path.join(__dirname, 'schema')))
app.listen(config.get('port'), () => {
console.log(`listening to port *:${config.get('port')}. press ctrl + c to cancel`)
})
return app
}
function middlewares (app) {
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(helmet())
app.use(morgan('dev', {
skip (req, res) {
return res.statusCode < 400
},
stream: process.stderr
}))
app.use(morgan('dev', {
skip (req, res) {
return res.statusCode >= 400
},
stream: process.stdout
}))
}
async function setupDatabaseTables (db) {
const blockTable = db.query(`
CREATE TABLE IF NOT EXISTS block (
difficulty BIGINT,
extraData VARCHAR(255),
gasLimit INT,
gasUsed INT,
hash VARCHAR(255),
logsBloom VARCHAR(255),
miner VARCHAR(255),
mixHash VARCHAR(255),
nonce VARCHAR(255),
number INT NOT NULL,
parentHash VARCHAR(255),
receiptsRoot VARCHAR(255),
sha3Uncles VARCHAR(255),
size INT,
stateRoot VARCHAR(255),
timestamp INT NOT NULL,
totalDifficulty BIGINT,
transactions JSON,
transactionsRoot VARCHAR(255),
uncles JSON,
PRIMARY KEY (number)
)
`)
const transactionTable = db.query(`
CREATE TABLE IF NOT EXISTS transaction (
hash VARCHAR(255),
description VARCHAR(255),
nonce INT,
blockHash VARCHAR(255),
blockNumber INT,
transactionIndex INT,
txFrom VARCHAR(255),
txTo VARCHAR(255),
value BIGINT,
gasPrice BIGINT,
gas INT,
input VARCHAR(255),
PRIMARY KEY (hash)
)
`)
const transactionReceiptTable = db.query(`
CREATE TABLE IF NOT EXISTS transactionReceipt (
blockHash VARCHAR(255),
blockNumber INT,
transactionHash VARCHAR(255),
transactionIndex INT,
txFrom VARCHAR(255),
txTo VARCHAR(255),
cumulativeGasUsed INT,
gasUsed INT,
contractAddress VARCHAR(255),
logs JSON,
status VARCHAR(255),
PRIMARY KEY (transactionHash)
)
`)
return Promise.all([blockTable, transactionTable, transactionReceiptTable])
}
main().catch(console.log)
| 27.483146 | 96 | 0.686631 |
e381c68a090513705dc363afe5f30662df3510fa | 492 | js | JavaScript | @xtcoder/uxt/utils/validator.js | xt1987/uxt | 5f45d497a251a19500dc57b6a8171a224fe94f4e | [
"Apache-2.0"
] | null | null | null | @xtcoder/uxt/utils/validator.js | xt1987/uxt | 5f45d497a251a19500dc57b6a8171a224fe94f4e | [
"Apache-2.0"
] | null | null | null | @xtcoder/uxt/utils/validator.js | xt1987/uxt | 5f45d497a251a19500dc57b6a8171a224fe94f4e | [
"Apache-2.0"
] | null | null | null | /**
* 判断是否为有效的大小值
*/
export const isSize = value => {
if (typeof value === 'number') {
if (value > 0) {
return true
}
}
if (typeof value === 'string') {
return /^\d+(\.\d+)?r?px$/.test(value)
}
return false
}
export const allTag = (vNodes, tag) => {
for (let vn of vNodes) {
if (!vn.tag) {
return false
}
if (!vn.tag.endsWith(tag)) {
return false
}
}
return true
}
| 18.222222 | 46 | 0.445122 |
e381d622bdfa702a766b34e2891c57626b8d20db | 3,613 | js | JavaScript | resources/assets/js/searchProducts.js | Alejandro-school/Gestion_Almacen | f166c0c1c77171b0e0af43be226a1a56e502dded | [
"MIT"
] | null | null | null | resources/assets/js/searchProducts.js | Alejandro-school/Gestion_Almacen | f166c0c1c77171b0e0af43be226a1a56e502dded | [
"MIT"
] | null | null | null | resources/assets/js/searchProducts.js | Alejandro-school/Gestion_Almacen | f166c0c1c77171b0e0af43be226a1a56e502dded | [
"MIT"
] | null | null | null | function searchProducts() {
document.querySelector("#form-search-products").addEventListener("keyup", function(e) {
e.preventDefault();
var internal_number = document.querySelector(".internal_number").value;
let token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
fetch("/searchDinamic", {
headers: {
"Content-Type": "application/json",
"Accept": "application/json, text-plain, */*",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-TOKEN": token
},
method: 'POST',
credentials: "same-origin",
body: JSON.stringify({
internal_number: internal_number
})
})
.then(function(response) {
if(response.ok) {
return response.json()
} else {
throw "Error en la llamada Ajax";
}
})
.then(function(respuesta) {
if(respuesta){
console.log(respuesta.product);
printSearchProduct(respuesta);
}
})
.catch(function(err) {
console.log(err);
});
});
}
function printSearchProduct(respuesta) {
var parentTable = document.querySelector(".parent-table");
var pagination = document.querySelector(".pagination");
var resultSearch = "";
while(parentTable.firstChild) {
parentTable.removeChild(parentTable.firstChild);
}
pagination.innerHTML="";
document.querySelector("#countProducts").innerHTML=`<p>Productos encontrados: ${respuesta.countProducts}</p>`;
resultSearch = ` <thead class="bg-orange">
<tr>
<th scope="col">#</th>
<th scope="col">Nombre</th>
<th scope="col">Codigo Producto</th>
<th scope="col">Codigo interno</th>
<th scope="col">Imagen</th>
<th scope="col">Acciones</th>
</tr>
</thead>`;
for(var i=0; i<respuesta.product.length;i++) {
resultSearch+=`
<tbody>
<tr>
<td>${respuesta.product[i].id}</td>
<td>${respuesta.product[i].name}</td>
<td>${respuesta.product[i].id_prodfab}</td>
<td>${respuesta.product[i].internal_number}</td>
<td><img src="http://gestion-almacen.com.devel/images/${respuesta.product[i].image}" alt=""></td>
<td>
<a href="http://gestion-almacen.com.devel/modifyProduct/${respuesta.product[i].id}"><img src="http://gestion-almacen.com.devel/images/pencil.svg" alt=""></a>
<form method="post" action="http://gestion-almacen.com.devel/deleteProduct" style="display:inline">
<input type="hidden" name="_token" value="2NpEQKO50dwlMVRFkTLDp0f8avQevsQWdse47Mnq">
<input type="hidden" name="id_product" value="${respuesta.product[i].id}">
<button class="btn btn-danger" type="submit">Borrar</button>
</form>
</td>
</tr>
</tbody>`
}
parentTable.innerHTML=resultSearch;
} | 29.859504 | 173 | 0.480764 |
e38256d7c7d8cef7a102687154aa2ed849d93dc7 | 1,807 | js | JavaScript | packages/experimental/micro-journeys/__tests__/microjourneys.js | vercel-support/bolt-test | 50ff0def16cf63589978a3f95f2e959b075eb295 | [
"MIT"
] | 137 | 2019-10-09T16:09:36.000Z | 2022-03-09T21:42:07.000Z | packages/experimental/micro-journeys/__tests__/microjourneys.js | vercel-support/bolt-test | 50ff0def16cf63589978a3f95f2e959b075eb295 | [
"MIT"
] | 610 | 2019-10-01T11:41:22.000Z | 2022-03-31T18:45:41.000Z | packages/experimental/micro-journeys/__tests__/microjourneys.js | vercel-support/bolt-test | 50ff0def16cf63589978a3f95f2e959b075eb295 | [
"MIT"
] | 26 | 2019-10-09T14:37:54.000Z | 2022-01-21T13:00:06.000Z | import { stopServer, html } from '../../../testing/testing-helpers';
const timeout = 120000;
describe('Micro journeys', () => {
let page;
beforeEach(async () => {
await page.evaluate(() => {
document.body.innerHTML = '';
});
}, timeout);
beforeAll(async () => {
page = await global.__BROWSER__.newPage();
await page.goto('http://127.0.0.1:4444/', {
timeout: 0,
});
}, timeout);
afterAll(async () => {
await stopServer();
await page.close();
}, timeout);
test('<bolt-interactive-pathway> ready event emits only when actually ready', async function() {
await page.evaluate(async () => {
const wrapper = document.createElement('div');
wrapper.innerHTML = `
<bolt-interactive-pathways>
<bolt-interactive-pathway pathway-title="My pathway title">
<bolt-interactive-step tab-title="My step title">Hello world</bolt-interactive-step>
</bolt-interactive-pathway>
</bolt-interactive-pathways>
`;
document.body.appendChild(wrapper);
const interactivePathway = document.querySelector(
'bolt-interactive-pathway',
);
return new Promise((resolve, reject) => {
interactivePathway.addEventListener('ready', e => {
// Make sure that this is the ready event on interactivePathway and not a child element.
if (interactivePathway === e.target) {
resolve();
}
});
interactivePathway.addEventListener('error', reject);
});
});
const interactivePathwayShadowRoot = await page.evaluate(async () => {
return document.querySelector('bolt-interactive-pathway').renderRoot
.innerHTML;
});
expect(interactivePathwayShadowRoot).toContain('My step title');
});
});
| 29.622951 | 98 | 0.615385 |
e382583a91d2f67f005dea253750672f23e3a9c0 | 411 | js | JavaScript | examples/hello-world/handler.js | ojongerius/epsagon-node | 5d3fe4a6c6a324ff69dda1f42ad263ca543b8365 | [
"MIT"
] | 52 | 2018-10-03T14:51:22.000Z | 2022-03-19T10:40:57.000Z | examples/hello-world/handler.js | ojongerius/epsagon-node | 5d3fe4a6c6a324ff69dda1f42ad263ca543b8365 | [
"MIT"
] | 507 | 2018-10-02T15:08:04.000Z | 2022-03-31T08:40:01.000Z | examples/hello-world/handler.js | rammatzkvosky/epsagon-node | 7bad2838d8ab86c5c41e847c8eee2086c7d69f83 | [
"MIT"
] | 19 | 2019-04-01T16:12:12.000Z | 2021-12-21T08:17:42.000Z | const epsagon = require('epsagon');
epsagon.init({
token: 'my-secret-token',
appName: 'my-app-name',
metadataOnly: false,
});
module.exports.hello = epsagon.lambdaWrapper((event, context, callback) => {
const response = {
statusCode: 200,
body: JSON.stringify({
message: 'It Worked!',
input: event,
}),
};
callback(null, response);
});
| 20.55 | 76 | 0.569343 |
e3833dbe32fbd645e346125c9d49585671a38ebb | 437 | js | JavaScript | src/binary/src/readUint8Array.js | jsFile/jsFile-wcbff | f50281874d3b648ca8f9541479691ca050a3b7d9 | [
"MIT"
] | 1 | 2015-08-19T13:58:46.000Z | 2015-08-19T13:58:46.000Z | src/binary/src/readUint8Array.js | jsFile/jsFile-wcbff | f50281874d3b648ca8f9541479691ca050a3b7d9 | [
"MIT"
] | null | null | null | src/binary/src/readUint8Array.js | jsFile/jsFile-wcbff | f50281874d3b648ca8f9541479691ca050a3b7d9 | [
"MIT"
] | null | null | null | /**
*
* @param options
*/
export default function readUint8Array (options = {}) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
const {index = 0, length = 0} = options;
reader.onload = (e) => {
resolve(new Uint8Array(e.target.result));
};
reader.onerror = reject;
reader.readAsArrayBuffer(this.blob.slice(index, index + length));
});
} | 25.705882 | 73 | 0.569794 |
e3838d31651c44fba7c0185b94b4c8c3887e20f6 | 9,144 | js | JavaScript | creditCalculator/calc.js | mylog00/mylog00.github.io | 3b163c4ec57775591ec6b6400b41c3f276826615 | [
"Unlicense"
] | null | null | null | creditCalculator/calc.js | mylog00/mylog00.github.io | 3b163c4ec57775591ec6b6400b41c3f276826615 | [
"Unlicense"
] | null | null | null | creditCalculator/calc.js | mylog00/mylog00.github.io | 3b163c4ec57775591ec6b6400b41c3f276826615 | [
"Unlicense"
] | null | null | null | "use strict";
//on load restore input data from local storage
window.onload = restore;
function calculate() {
//find elements by 'id'
var amount = document.getElementById('amount');
var apr = document.getElementById('apr');
var years = document.getElementById('years');
var zipcode = document.getElementById('zipcode');
var payment = document.getElementById('payment');
var total = document.getElementById('total');
var totalinterest = document.getElementById('totalinterest');
//Get input data
var principal = parseFloat(amount.value);
log('principal:' + principal);
var interest = parseFloat(apr.value) / 100 / 12;
log('interest:' + interest);
var payments = parseFloat(years.value) * 12;
log('payments:' + payments);
//Calculate monthly payment
var x = Math.pow(1 + interest, payments);
var monthly = (principal * x * interest) / (x - 1);
//Check 'monthly'
//If the argument is NaN, positive infinity, or negative infinity, this method returns false; otherwise, it returns true.
if (isFinite(monthly)) {//NOTE need check 'null'
//Set output data
payment.innerHTML = monthly.toFixed(2);
total.innerHTML = (monthly * payments).toFixed(2);
totalinterest.innerHTML = ((monthly * payments) - principal).toFixed(2);
//Save input data to local storage
save(amount.value, apr.value, years.value, zipcode.value);
//Draw graph
chart(principal, interest, monthly, payments);
} else {
//Clear output data
payment.innerHTML = '';
total.innerHTML = '';
totalinterest.innerHTML = '';
chart();
}
}
//Save data to local storage
function save(amount, apr, years, zipcode) {
if (window.localStorage) {
localStorage.loan_amount = amount;
localStorage.loan_apr = apr;
localStorage.loan_years = years;
localStorage.loan_zipcode = zipcode;
}
}
//Restore data to local storage
function restore() {
try {
getExchangeData();
} catch (e) {
log('Can not load foreign exchange data');
}
if (window.localStorage && localStorage.loan_amount) {
document.getElementById('amount').value = localStorage.loan_amount;
document.getElementById('apr').value = localStorage.loan_apr;
document.getElementById('years').value = localStorage.loan_years;
document.getElementById('zipcode').value = localStorage.loan_zipcode;
}
}
function getExchangeData() {
// http://www.cbr.ru/scripts/XML_dynamic.asp?date_req1=13/01/2016&date_req2=14/01/2016&VAL_NM_RQ=R01235
var url = getYqlUrl();
var newScriptElement = document.createElement("script");
newScriptElement.setAttribute("src", url);
newScriptElement.setAttribute("id", "jsonp");
var head = document.getElementsByTagName("head")[0];
var oldScriptElement = document.getElementById("jsonp");
if (oldScriptElement === null) {
head.appendChild(newScriptElement);
}
else {
head.replaceChild(newScriptElement, oldScriptElement);
}
}
//used as JSONP callback
function updateExchangeTable(object) {
var records = object.query.results.ValCurs.Record;
if (Array.isArray(records)) {
//fill table head
var tableHead = document.getElementsByTagName("thead")[0];
var row = createTableRow(['Value','Pair','Date'],true);
tableHead.appendChild(row);
//fill table body
records.reverse();
var tableBody = document.getElementsByTagName("tbody")[0];
for (var i = 0; i < records.length; i++) {
var rec = records[i];
var date = rec.Date;
var nominal = rec.Nominal;
var value = rec.Value.replace(',', '.');
value = parseFloat(value).toFixed(2);
log(date + ';' + nominal + ';' + rec.Value + ';' + value + ';');
row = createTableRow([value, 'USD/RUB', date], false);
tableBody.appendChild(row);
}
}
function createTableRow(valueList, isHeader) {
var row = document.createElement('tr');
if (Array.isArray(valueList)) {
for (var i = 0; i < valueList.length; i++) {
var col = createColumn(valueList[i], isHeader);
row.appendChild(col);
}
}
return row;
function createColumn(value, isHeader) {
var elem = isHeader ? 'th' : 'td';
var col = document.createElement(elem);
col.innerHTML = value;
return col;
}
}
}
function getYqlUrl() {
//Example:
//https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'www.cbr.ru%2Fscripts%2FXML_dynamic.asp%3Fdate_req1%3D02%2F03%2F2001%26date_req2%3D14%2F03%2F2001%26VAL_NM_RQ%3DR01235'&format=json&callback=callback
var yql_uri = 'https://query.yahooapis.com/v1/public/yql?q=';
yql_uri += getEncodedSelectQuery();
yql_uri += '&format=json&callback=updateExchangeTable';
log('url:' + yql_uri);
return yql_uri;
}
function getEncodedSelectQuery() {
var selectStr = 'select * from xml where url=\'' + getCbrUrl() + '\'';
return encodeURIComponent(selectStr);
function getCbrUrl() {
var usd_code = 'R01235';//USD
//var eur_code = 'R01239';//EUR
var date = new Date();//current date
var cur_date = formatDate(date);
date.setDate(date.getDate() - 7);//past date
var yestr_date = formatDate(date);
//Example:
//http://www.cbr.ru/scripts/XML_dynamic.asp?date_req1=13/01/2016&date_req2=14/01/2016&VAL_NM_RQ=R01235
var url = 'www.cbr.ru/scripts/XML_dynamic.asp?date_req1=' + yestr_date + '&date_req2=' + cur_date + '&VAL_NM_RQ=' + usd_code;
log('cbr url:' + url);
return url;
}
// format date to 'dd/mm/YYY'
function formatDate(date) {
function formatNum(num) {
if (num < 10) return '0' + num;
return String(num);
}
return formatNum(date.getDate()) + '/' + formatNum(date.getMonth() + 1) + '/' + date.getFullYear();
}
}
//Draw payment graph
function chart(principal, interest, monthly, payments) {
var graph = document.getElementById('graph');
graph.width = graph.width;//its magic
//if no parameters or no <canvas> then return
//NOTE getContext() method returns a drawing context on the canvas, or null if the context identifier is not supported.
if (arguments.length == 0 || !graph.getContext)
return;
var context = graph.getContext('2d');//CanvasRenderingContext2D
var width = graph.width;
var height = graph.height;
function paymentToX(n) {
return n * width / payments;
}
function amountToY(a) {
return height - (a * height / (monthly * payments * 1.05));
}
//First triangle
context.moveTo(paymentToX(0), amountToY(0));
context.lineTo(paymentToX(payments), amountToY(monthly * payments));
context.lineTo(paymentToX(payments), amountToY(0));
context.closePath();
//First triangle color
context.fillStyle = '#f88';
context.fill();
//First triangle text
context.font = 'bold 12px sans-serif';
context.fillText('Total interest payments', 20, 20);
//Second figure
var equity = 0;
context.beginPath();
context.moveTo(paymentToX(0), amountToY(0));
var thisMonthsInterest;
var i;
for (i = 1; i <= payments; i++) {
thisMonthsInterest = (principal - equity) * interest;
equity += (monthly - thisMonthsInterest);
context.lineTo(paymentToX(i), amountToY(equity));
}
context.lineTo(paymentToX(payments), amountToY(0));
context.closePath();
context.fillStyle = 'green';
context.fill();
context.fillText('Total equity', 20, 30);
//Third figure
var bal = principal;
context.beginPath();
context.moveTo(paymentToX(0), amountToY(bal));
for (i = 1; i <= payments; i++) {
thisMonthsInterest = bal * interest;
bal -= (monthly - thisMonthsInterest);
context.lineTo(paymentToX(i), amountToY(bal));
}
context.lineWidth = 3;
context.stroke();//draw curve
context.fillStyle = 'black';
context.fillText('Loan balance', 20, 50);
//X axis
context.textAlign = 'right';
var y = amountToY(0);
for (var year = 1; year * 12 <= payments; year++) {
var x = paymentToX(year * 12);
context.fillRect(x - 0.5, y - 3, 1, 3);
if (year == 1)
context.fillText('Year', x, y - 5);
if (year % 5 == 0 && year * 12 !== payments)
context.fillText(String(year), x, y - 5);
}
//Y axis
context.textAlign = 'right';
context.textBaseline = 'middle';
var ticks = [monthly * payments, principal];
var rightEdge = paymentToX(payments);
for (i = 0; i < ticks.length; i++) {
y = amountToY(ticks[i]);
context.fillRect(rightEdge - 3, y - 0.5, 3, 1);
context.fillText(String(ticks[i].toFixed(0)), rightEdge - 5, y);
}
}
function log(str) {
console.log(str);
}
| 34.768061 | 239 | 0.61986 |
e383af45261616d81b3409c9fd1b745c21e46f41 | 895 | js | JavaScript | plugins/firebase.js | NovicodeGithub/service-mobile | 88f365391c3ee9a58e7b7774e9453c16f75a1002 | [
"MIT"
] | null | null | null | plugins/firebase.js | NovicodeGithub/service-mobile | 88f365391c3ee9a58e7b7774e9453c16f75a1002 | [
"MIT"
] | 5 | 2021-03-09T00:41:41.000Z | 2022-02-10T16:29:36.000Z | plugins/firebase.js | novicode1/service-mobile | 88f365391c3ee9a58e7b7774e9453c16f75a1002 | [
"MIT"
] | null | null | null | import Vue from 'vue'
import { DB, storage, auth } from '@/plugins/firebase-init'
const firebasePlugin = {
install () {
if (Vue.__nuxt_firebase_installed__) {
return
}
Vue.__nuxt_firebase_installed__ = true
if (!Vue.prototype.$DB) {
Vue.prototype.$firestore = DB
Vue.prototype.$storage = storage
Vue.prototype.$auth = auth
}
}
}
Vue.use(firebasePlugin)
export default (ctx) => {
const { app, store } = ctx
app.$firestore = Vue.prototype.$firestore
ctx.$firestore = Vue.prototype.$firestore
app.$storage = Vue.prototype.$storage
ctx.$storage = Vue.prototype.$storage
app.$auth = Vue.prototype.$storage
ctx.$auth = Vue.prototype.$storage
if (store) {
store.$firestore = Vue.prototype.$firestore
store.$storage = Vue.prototype.$storage
store.$auth = Vue.prototype.$auth
}
}
| 22.948718 | 60 | 0.63352 |
e387d44dec2ed4eb7586b541ec51aa3a905d3b5f | 8,020 | js | JavaScript | lc3/math/fft-tfm-cooleytukey.js | TaikiAkita/lc3codec-nodejs | 41936a9306e96785d8c4fef5ac224ae7524911a6 | [
"BSD-3-Clause"
] | 5 | 2021-08-05T07:19:43.000Z | 2022-03-20T16:47:42.000Z | lc3/math/fft-tfm-cooleytukey.js | TaikiAkita/lc3codec-nodejs | 41936a9306e96785d8c4fef5ac224ae7524911a6 | [
"BSD-3-Clause"
] | null | null | null | lc3/math/fft-tfm-cooleytukey.js | TaikiAkita/lc3codec-nodejs | 41936a9306e96785d8c4fef5ac224ae7524911a6 | [
"BSD-3-Clause"
] | 3 | 2021-06-24T13:01:44.000Z | 2021-08-20T02:27:36.000Z | //
// Copyright 2021 XiaoJSoft Studio. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.md file.
//
//
// Imports.
//
// Imported modules.
const Lc3FftTfmCore =
require("./fft-tfm-core");
const Lc3Brp =
require("./brp");
const Lc3ObjUtil =
require("./../common/object_util");
const Lc3Error =
require("./../error");
// Imported classes.
const IFFTTransformer =
Lc3FftTfmCore.IFFTTransformer;
const LC3IllegalParameterError =
Lc3Error.LC3IllegalParameterError;
// Imported functions.
const NewBitReversalPermutate =
Lc3Brp.NewBitReversalPermutate;
const Inherits =
Lc3ObjUtil.Inherits;
//
// Constants.
//
// Twiddle factor WN[i] = e ^ (-1j * 2pi / (2 ^ i))
// (for 0 <= i < 32).
const WN_RE = [
1.0, -1.0, 6.123233995736766e-17, 0.7071067811865476, 0.9238795325112867, 0.9807852804032304, 0.9951847266721969, 0.9987954562051724, 0.9996988186962042, 0.9999247018391445, 0.9999811752826011, 0.9999952938095762, 0.9999988234517019, 0.9999997058628822, 0.9999999264657179, 0.9999999816164293, 0.9999999954041073, 0.9999999988510269, 0.9999999997127567, 0.9999999999281892, 0.9999999999820472, 0.9999999999955118, 0.999999999998878, 0.9999999999997194, 0.9999999999999298, 0.9999999999999825, 0.9999999999999957, 0.9999999999999989, 0.9999999999999998, 0.9999999999999999, 1.0, 1.0
];
const WN_IM = [
2.4492935982947064e-16, -1.2246467991473532e-16, -1.0, -0.7071067811865475, -0.3826834323650898, -0.19509032201612825, -0.0980171403295606, -0.049067674327418015, -0.024541228522912288, -0.012271538285719925, -0.006135884649154475, -0.003067956762965976, -0.0015339801862847655, -0.0007669903187427045, -0.00038349518757139556, -0.0001917475973107033, -9.587379909597734e-05, -4.793689960306688e-05, -2.396844980841822e-05, -1.1984224905069705e-05, -5.9921124526424275e-06, -2.996056226334661e-06, -1.4980281131690111e-06, -7.490140565847157e-07, -3.7450702829238413e-07, -1.8725351414619535e-07, -9.362675707309808e-08, -4.681337853654909e-08, -2.340668926827455e-08, -1.1703344634137277e-08, -5.8516723170686385e-09, -2.9258361585343192e-09
];
//
// Public classes.
//
/**
* FFT Cooley-Tukey transformer.
*
* @constructor
* @throws {LC3IllegalParameterError}
* - Incorrect stage count.
* @param {Number} stageCnt
* - The stage count (min: 1, max: 31).
*/
function FFTCooleyTukeyTransformer(stageCnt) {
// Let parent class initialize.
IFFTTransformer.call(this);
// Check the stage count.
if (!(Number.isInteger(stageCnt) && stageCnt > 0 && stageCnt < 32)) {
throw new LC3IllegalParameterError(
"Incorrect stage count."
);
}
//
// Members.
//
// Get the bit reversal permutation used by FFTArrayBitReversalSwap2().
let brvtable = NewBitReversalPermutate(stageCnt >>> 1);
// Get the block size.
let blksize = ((1 << stageCnt) >>> 0);
//
// Public methods.
//
/**
* Apply transform.
*
* @throws {LC3IllegalParameterError}
* - Incorrect block size.
* @param {Number[]} x_re
* - The real part of each point.
* @param {Number[]} x_im
* - The imaginary part of each point.
*/
this.transform = function(x_re, x_im) {
// Check the block size.
if (x_re.length != blksize || x_im.length != blksize) {
throw new LC3IllegalParameterError("Incorrect block size.");
}
// Do bit reversal shuffle.
FFTArrayBitReversalShuffle2(x_re, x_im, stageCnt, brvtable);
// Do FFT transform.
for (let s = 1; s <= stageCnt; ++s) {
let wNs_r = WN_RE[s], wNs_i = WN_IM[s];
let pow_2_s = ((1 << s) >>> 0);
let pow_2_ss1 = (pow_2_s >>> 1);
for (let off = 0; off < blksize; off += pow_2_s) {
let wNr_r = 1.0, wNr_i = 0.0;
for (
let p = off, pend = off + pow_2_ss1, q = pend;
p < pend;
++p, ++q
) {
// Do 2-points Cooley-Tukey transform.
let p_r = x_re[p], p_i = x_im[p];
let q_r = x_re[q], q_i = x_im[q];
let t_r = q_r * wNr_r - q_i * wNr_i,
t_i = q_r * wNr_i + q_i * wNr_r;
x_re[p] = p_r + t_r;
x_im[p] = p_i + t_i;
x_re[q] = p_r - t_r;
x_im[q] = p_i - t_i;
// Roll the subsup{w, N, r} coefficient.
let wNr_r_next = (wNr_r * wNs_r - wNr_i * wNs_i);
let wNr_i_next = (wNr_r * wNs_i + wNr_i * wNs_r);
wNr_r = wNr_r_next;
wNr_i = wNr_i_next;
}
}
}
};
}
//
// Private functions.
//
/**
* Swap two items at specific indexes on both arrays.
*
* @param {Number[]} arr1
* - The first array.
* @param {Number[]} arr2
* - The second array.
* @param {Number} i1
* - The first index.
* @param {Number} i2
* - The second index.
*/
function FFTArraySwap2(arr1, arr2, i1, i2) {
// Swap the 1st array.
let tmp = arr1[i1];
arr1[i1] = arr1[i2];
arr1[i2] = tmp;
// Swap the 2nd array.
tmp = arr2[i1];
arr2[i1] = arr2[i2];
arr2[i2] = tmp;
}
/**
* Do bit reversal shuffle on both arrays.
*
* Note(s):
* [1] The description algorithm used here can be downloaded from:
* https://drive.google.com/file/d/1ESvZy5U__Uir3hePc3CGgHdBmflf47jA/
*
* @param {Number[]} arr1
* - The first array.
* @param {Number[]} arr2
* - The second array.
* @param {Number} nbits
* - The bit count.
* @param {Number[]} brv_m
* - The bit reversal table (must contains 2 ^ (nbits >> 1) items).
*/
function FFTArrayBitReversalShuffle2(arr1, arr2, nbits, brv_m) {
if (nbits <= 1) {
return;
}
let m = (nbits >>> 1);
let mp1 = m + 1;
// let brv_m = NewBitReversalPermutate(m);
let inv = ((1 << nbits) >>> 0) - 1;
let pow_2_m = ((1 << m) >>> 0);
let pow_2_ms1 = (pow_2_m >>> 1);
if (((nbits & 1) >>> 0) == 0) {
for (let a = 1; a < pow_2_ms1; ++a) {
for (let b = 0; b < a; ++b) {
let i = ((b << m) >>> 0) + brv_m[a];
let ri = ((a << m) >>> 0) + brv_m[b];
FFTArraySwap2(arr1, arr2, i, ri);
FFTArraySwap2(arr1, arr2, ((inv ^ ri) >>> 0), ((inv ^ i) >>> 0));
}
}
for (let a = pow_2_ms1; a < pow_2_m; ++a) {
for (let b = 0; b < pow_2_ms1; ++b) {
let i = ((b << m) >>> 0) + brv_m[a];
let ri = ((a << m) >>> 0) + brv_m[b];
FFTArraySwap2(arr1, arr2, i, ri);
}
}
} else {
for (let a = 1; a < pow_2_ms1; ++a) {
for (let b = 0; b < a; ++b) {
let i = ((b << mp1) >>> 0) + brv_m[a];
let ri = ((a << mp1) >>> 0) + brv_m[b];
FFTArraySwap2(arr1, arr2, i, ri);
FFTArraySwap2(arr1, arr2, ((inv ^ ri) >>> 0), ((inv ^ i) >>> 0));
i += pow_2_m;
ri += pow_2_m;
FFTArraySwap2(arr1, arr2, i, ri);
FFTArraySwap2(arr1, arr2, ((inv ^ ri) >>> 0), ((inv ^ i) >>> 0));
}
}
for (let a = pow_2_ms1; a < pow_2_m; ++a) {
for (let b = 0; b < pow_2_ms1; ++b) {
let i = ((b << mp1) >>> 0) + brv_m[a];
let ri = ((a << mp1) >>> 0) + brv_m[b];
FFTArraySwap2(arr1, arr2, i, ri);
FFTArraySwap2(arr1, arr2, i + pow_2_m, ri + pow_2_m);
}
}
}
}
//
// Inheritances.
//
Inherits(FFTCooleyTukeyTransformer, IFFTTransformer);
// Export public APIs.
module.exports = {
"FFTCooleyTukeyTransformer": FFTCooleyTukeyTransformer
};
| 33.140496 | 746 | 0.54389 |
e388177824e9024efff4a89e48e4c59d8bac553a | 306 | js | JavaScript | App.js | katalla1/AirPnP | f2b347afa9b4ab228b936edfee327910ea50c01a | [
"MIT"
] | null | null | null | App.js | katalla1/AirPnP | f2b347afa9b4ab228b936edfee327910ea50c01a | [
"MIT"
] | null | null | null | App.js | katalla1/AirPnP | f2b347afa9b4ab228b936edfee327910ea50c01a | [
"MIT"
] | null | null | null | import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import LoginScreen from './app/assets/screens/LoginScreen';
import AppText from './app/components/AppText';
export default function App() {
return (
<LoginScreen />
);
}
| 25.5 | 59 | 0.70915 |
e388451c3ce7c500171fd6fee0234978d07f6473 | 11,286 | js | JavaScript | docs/7.4aa9e71ff1e08337e705.js | leoaraujocosta/ngx-sharebuttons | 364a2ecad1edf191fc16253e450339519985179a | [
"MIT"
] | null | null | null | docs/7.4aa9e71ff1e08337e705.js | leoaraujocosta/ngx-sharebuttons | 364a2ecad1edf191fc16253e450339519985179a | [
"MIT"
] | null | null | null | docs/7.4aa9e71ff1e08337e705.js | leoaraujocosta/ngx-sharebuttons | 364a2ecad1edf191fc16253e450339519985179a | [
"MIT"
] | 1 | 2019-10-09T18:13:07.000Z | 2019-10-09T18:13:07.000Z | (window.webpackJsonp=window.webpackJsonp||[]).push([[7],{n0El:function(l,n,u){"use strict";u.r(n);var a=u("LoAr"),e=function(){},t=u("C9Ky"),o=u("pLqg"),r=u("7tlY"),i=u("Ckq/"),s=u("//aV"),c=u("U+go"),d=u("WT9V"),b=u("QoAl"),p=u("320Y"),h=u("ChgE"),g=u("fxml"),m=u("YzpY"),f=u("TeY9"),Y=u("UelK"),y=u("SPdK"),w=u("fDe+"),Q=u("jQpT"),k=function(){function l(l){this.titleService=l,this.code={lazyImport:"// in root module\n@NgModule({\n imports: [\n ShareButtonsModule.forRoot()\n ]\n})\nexport class AppModule { }\n\n// in lazy module\n@NgModule({\n imports: [\n ShareButtonsModule\n ]\n})\nexport class MyLazyModule { }",includeOrder:"import { ShareButtonsOptions } from '@ngx-share/core';\nimport { ShareButtonsModule } from '@ngx-share/buttons';\n\noptions: ShareButtonsOptions = {\n include: ['facebook', 'twitter', 'pinterest']\n}\n\n@NgModule({\n imports: [\n ShareButtonsModule.forRoot(options)\n ]\n})",buttonsOrder:"<share-buttons [include]=\"['telegram', 'twitter', 'pinterest', 'whatsapp']\"></share-buttons>",metaTags:'<meta property="og:title" content="European Travel Destinations">\n<meta property="og:description" content="Offering tour packages for individuals or groups.">\n<meta property="og:image" content="http://euro-travel-example.com/thumbnail.jpg">\n<meta property="og:url" content="http://euro-travel-example.com/index.html">'}}return l.prototype.ngOnInit=function(){this.titleService.setTitle("Frequently Asked Questions")},l}(),v=u("SeAg"),x=a.Oa({encapsulation:0,styles:[["figure[_ngcontent-%COMP%]{max-width:400px;margin:.5em}img[_ngcontent-%COMP%]{max-width:100%;display:block;box-shadow:0 3px 10px rgba(0,0,0,.1);border-radius:4px;overflow:hidden}figcaption[_ngcontent-%COMP%]{margin-top:1em;text-align:center;font-family:Play,sans-serif;opacity:.5}"]],data:{}});function P(l){return a.kb(2,[(l()(),a.Qa(0,0,null,null,79,"ng-scrollbar",[["thumbClass","page-scrollbar-thumb"]],null,null,null,s.b,s.a)),a.Pa(1,4374528,null,0,c.a,[a.y,a.D,d.d],{autoHide:[0,"autoHide"],thumbClass:[1,"thumbClass"]},null),(l()(),a.Qa(2,0,null,0,3,"header",[],null,null,null,b.b,b.a)),a.Pa(3,49152,null,0,p.a,[],null,null),(l()(),a.Qa(4,0,null,0,1,"h1",[],null,null,null,null,null)),(l()(),a.ib(-1,null,["Frequently Asked Questions"])),(l()(),a.Qa(6,0,null,0,71,"div",[["class","page-content container"]],null,null,null,null,null)),(l()(),a.Qa(7,0,null,null,5,"section",[],null,null,null,null,null)),(l()(),a.Qa(8,0,null,null,2,"section-title",[],null,null,null,h.b,h.a)),a.Pa(9,49152,null,0,g.a,[],null,null),(l()(),a.ib(-1,0,["How to import share buttons module in a lazy module?"])),(l()(),a.Qa(11,0,null,null,1,"hl-code",[],null,null,null,m.b,m.a)),a.Pa(12,4243456,null,0,f.a,[a.h],{code:[0,"code"]},null),(l()(),a.Qa(13,0,null,null,5,"section",[],null,null,null,null,null)),(l()(),a.Qa(14,0,null,null,2,"section-title",[],null,null,null,h.b,h.a)),a.Pa(15,49152,null,0,g.a,[],null,null),(l()(),a.ib(-1,0,["Why Facebook share button not working?"])),(l()(),a.Qa(17,0,null,null,1,"p",[],null,null,null,null,null)),(l()(),a.ib(-1,null,["If the shared link is hosted on a local server, Facebook sharing window will not work. Make sure it is hosted on a public server."])),(l()(),a.Qa(19,0,null,null,32,"section",[],null,null,null,null,null)),(l()(),a.Qa(20,0,null,null,2,"section-title",[],null,null,null,h.b,h.a)),a.Pa(21,49152,null,0,g.a,[],null,null),(l()(),a.ib(-1,0,["No article preview when a link is shared?"])),(l()(),a.Qa(23,0,null,null,1,"p",[],null,null,null,null,null)),(l()(),a.ib(-1,null,[" When a link is shared, the social network scrapes the associated web page and reads its meta tags to display the appropriate information."])),(l()(),a.Qa(25,0,null,null,10,"div",[["fxLayout",""],["fxLayout.lt-sm","column"],["fxLayoutAlign","space-between center"]],null,null,null,null,null)),a.Pa(26,737280,null,0,Y.d,[y.i,a.k,y.m],{layout:[0,"layout"],layoutLtSm:[1,"layoutLtSm"]},null),a.Pa(27,737280,null,0,Y.c,[y.i,a.k,[6,Y.d],y.m],{align:[0,"align"]},null),(l()(),a.Qa(28,0,null,null,3,"figure",[],null,null,null,null,null)),(l()(),a.Qa(29,0,null,null,0,"img",[["src","https://res.cloudinary.com/css-tricks/image/fetch/q_auto,f_auto/https://cdn.css-tricks.com/wp-content/uploads/2016/06/facebook-card.jpg"]],null,null,null,null,null)),(l()(),a.Qa(30,0,null,null,1,"figcaption",[],null,null,null,null,null)),(l()(),a.ib(-1,null,["Facebook card"])),(l()(),a.Qa(32,0,null,null,3,"figure",[],null,null,null,null,null)),(l()(),a.Qa(33,0,null,null,0,"img",[["src","https://res.cloudinary.com/css-tricks/image/fetch/q_auto,f_auto/https://cdn.css-tricks.com/wp-content/uploads/2016/06/twitter-card.jpg"]],null,null,null,null,null)),(l()(),a.Qa(34,0,null,null,1,"figcaption",[],null,null,null,null,null)),(l()(),a.ib(-1,null,["Twitter card"])),(l()(),a.Qa(36,0,null,null,1,"p",[],null,null,null,null,null)),(l()(),a.ib(-1,null,["There are many other meta tags available that can be used to specify different types of content. But, in general, the following will suffice"])),(l()(),a.Qa(38,0,null,null,1,"hl-code",[],null,null,null,m.b,m.a)),a.Pa(39,4243456,null,0,f.a,[a.h],{code:[0,"code"]},null),(l()(),a.Qa(40,0,null,null,3,"p",[],null,null,null,null,null)),(l()(),a.ib(-1,null,["Check this cool "])),(l()(),a.Qa(42,0,null,null,1,"a",[["href","https://megatags.co/#generate-tags"]],null,null,null,null,null)),(l()(),a.ib(-1,null,["online meta tags generator"])),(l()(),a.Qa(44,0,null,null,7,"p",[],null,null,null,null,null)),(l()(),a.ib(-1,null,["If there are any doubts about the legitimacy of paring down to these tags, we can use the helpful "])),(l()(),a.Qa(46,0,null,null,1,"a",[["href","https://developers.facebook.com/tools/debug/sharing/"]],null,null,null,null,null)),(l()(),a.ib(-1,null,["Facebook Sharing Debugger"])),(l()(),a.ib(-1,null,[" and "])),(l()(),a.Qa(49,0,null,null,1,"a",[["href","https://cards-dev.twitter.com/validator"]],null,null,null,null,null)),(l()(),a.ib(-1,null,["Twitter Card Validator"])),(l()(),a.ib(-1,null,[". Both these tools will scrape any Web page hosted on a public server for relevant meta tags and display how it would look when shared. It will also list any errors and provide suggestions"])),(l()(),a.Qa(52,0,null,null,9,"section",[],null,null,null,null,null)),(l()(),a.Qa(53,0,null,null,2,"section-title",[],null,null,null,h.b,h.a)),a.Pa(54,49152,null,0,g.a,[],null,null),(l()(),a.ib(-1,0,["How to set the meta tags dynamically"])),(l()(),a.Qa(56,0,null,null,1,"p",[],null,null,null,null,null)),(l()(),a.ib(-1,null,["Using Angular Universal"])),(l()(),a.Qa(58,0,null,null,0,"iframe",[["allowfullscreen",""],["frameborder","0"],["height","488px"],["src","https://www.youtube.com/embed/lncsmB5yfzE?start=777"],["width","100%"]],null,null,null,null,null)),(l()(),a.Qa(59,0,null,null,1,"p",[],null,null,null,null,null)),(l()(),a.ib(-1,null,["Or using Rendertron"])),(l()(),a.Qa(61,0,null,null,0,"iframe",[["allowfullscreen",""],["frameborder","0"],["height","488px"],["src","https://www.youtube.com/embed/ANyOZIcGvB8"],["width","100%"]],null,null,null,null,null)),(l()(),a.Qa(62,0,null,null,15,"section",[],null,null,null,null,null)),(l()(),a.Qa(63,0,null,null,4,"section-title",[],null,null,null,h.b,h.a)),a.Pa(64,49152,null,0,g.a,[],null,null),(l()(),a.ib(-1,0,["How to change share buttons order in "])),(l()(),a.Qa(66,0,null,0,0,"code",[["class","hljs"]],[[8,"textContent",0]],null,null,null,null)),(l()(),a.ib(-1,0,[" component? "])),(l()(),a.Qa(68,0,null,null,1,"p",[],null,null,null,null,null)),(l()(),a.ib(-1,null,["You can change the order by including the share buttons in order you want, for example:"])),(l()(),a.Qa(70,0,null,null,1,"hl-code",[],null,null,null,m.b,m.a)),a.Pa(71,4243456,null,0,f.a,[a.h],{code:[0,"code"]},null),(l()(),a.ib(-1,null,[" Or directly using the "])),(l()(),a.Qa(73,0,null,null,1,"b",[],null,null,null,null,null)),(l()(),a.ib(-1,null,["include"])),(l()(),a.ib(-1,null,[" input in ShareButtons components "])),(l()(),a.Qa(76,0,null,null,1,"hl-code",[],null,null,null,m.b,m.a)),a.Pa(77,4243456,null,0,f.a,[a.h],{code:[0,"code"]},null),(l()(),a.Qa(78,0,null,0,1,"footer",[],null,null,null,w.b,w.a)),a.Pa(79,49152,null,0,Q.a,[],null,null)],function(l,n){var u=n.component;l(n,1,0,!0,"page-scrollbar-thumb"),l(n,12,0,u.code.lazyImport),l(n,26,0,"","column"),l(n,27,0,"space-between center"),l(n,39,0,u.code.metaTags),l(n,71,0,u.code.includeOrder),l(n,77,0,u.code.buttonsOrder)},function(l,n){l(n,66,0,"<share-buttons>")})}var C=a.Ma("faq",k,function(l){return a.kb(0,[(l()(),a.Qa(0,0,null,null,1,"faq",[],null,null,null,P,x)),a.Pa(1,114688,null,0,k,[v.i],null,null)],function(l,n){l(n,1,0)},null)},{},{},[]),M=u("LYzL"),S=u("y7gG"),O=u("eXL1"),A=u("C7Lb"),L=u("CRa1"),q=u("SECt"),B=u("s8WJ"),j=u("IfiR"),I=u("981U"),T=u("X7Hn"),F=u("EAoM"),z=u("a198"),E=u("WV+C"),N=u("IvSS"),V=u("V3Ng"),H=u("euho"),W=u("abkR"),X=u("Ho7M"),_=u("0xYh"),R=u("+3V+"),D=u("dgjn"),K=u("GcYS"),U=u("8xy9"),G=u("e8uv"),J=u("rXXt"),Z=u("Hfg7"),$=u("XIB+"),ll=u("z1EI"),nl=u("qXP9"),ul=u("5dmV"),al=u("WgBV"),el=u("LxDK"),tl=u("V7OE"),ol=u("AFqu"),rl=u("wEfT"),il=u("FOLC"),sl=u("vA/A"),cl=u("6yYy"),dl=u("PCNd"),bl=u("rh80");u.d(n,"FaqPageModuleNgFactory",function(){return pl});var pl=a.Na(e,[],function(l){return a.Xa([a.Ya(512,a.j,a.Ca,[[8,[t.a,o.a,r.a,i.a,C]],[3,a.j],a.w]),a.Ya(4608,d.n,d.m,[a.t,[2,d.y]]),a.Ya(4608,M.b,M.b,[]),a.Ya(4608,S.c,S.c,[]),a.Ya(4608,v.f,M.c,[[2,M.g],[2,M.l]]),a.Ya(4608,O.c,O.c,[O.i,O.e,a.j,O.h,O.f,a.q,a.y,d.d,A.b]),a.Ya(5120,O.j,O.k,[O.c]),a.Ya(5120,L.a,L.b,[O.c]),a.Ya(5120,q.b,q.c,[O.c]),a.Ya(5120,B.c,B.d,[O.c]),a.Ya(4608,B.e,B.e,[O.c,a.q,[2,d.h],[2,B.b],B.c,[3,B.e],O.e]),a.Ya(4608,y.k,y.j,[y.d,y.h]),a.Ya(5120,a.b,function(l,n){return[y.n(l,n)]},[d.d,a.A]),a.Ya(4608,j.p,j.p,[]),a.Ya(4608,j.d,j.d,[]),a.Ya(1073742336,d.c,d.c,[]),a.Ya(1073742336,I.r,I.r,[[2,I.x],[2,I.o]]),a.Ya(1073742336,T.p,T.p,[]),a.Ya(1073742336,A.a,A.a,[]),a.Ya(1073742336,M.l,M.l,[[2,M.d]]),a.Ya(1073742336,F.l,F.l,[]),a.Ya(1073742336,z.d,z.d,[]),a.Ya(1073742336,E.b,E.b,[]),a.Ya(1073742336,N.b,N.b,[]),a.Ya(1073742336,V.h,V.h,[]),a.Ya(1073742336,M.v,M.v,[]),a.Ya(1073742336,S.d,S.d,[]),a.Ya(1073742336,H.b,H.b,[]),a.Ya(1073742336,W.f,W.f,[]),a.Ya(1073742336,O.g,O.g,[]),a.Ya(1073742336,M.t,M.t,[]),a.Ya(1073742336,M.r,M.r,[]),a.Ya(1073742336,X.d,X.d,[]),a.Ya(1073742336,L.d,L.d,[]),a.Ya(1073742336,_.a,_.a,[]),a.Ya(1073742336,q.e,q.e,[]),a.Ya(1073742336,R.c,R.c,[]),a.Ya(1073742336,D.b,D.b,[]),a.Ya(1073742336,K.c,K.c,[]),a.Ya(1073742336,M.m,M.m,[]),a.Ya(1073742336,U.b,U.b,[]),a.Ya(1073742336,G.c,G.c,[]),a.Ya(1073742336,J.b,J.b,[]),a.Ya(1073742336,Z.a,Z.a,[]),a.Ya(1073742336,$.d,$.d,[]),a.Ya(1073742336,ll.a,ll.a,[]),a.Ya(1073742336,B.h,B.h,[]),a.Ya(1073742336,nl.b,nl.b,[]),a.Ya(1073742336,ul.a,ul.a,[]),a.Ya(1073742336,y.e,y.e,[]),a.Ya(1073742336,Y.b,Y.b,[]),a.Ya(1073742336,al.b,al.b,[]),a.Ya(1073742336,el.a,el.a,[]),a.Ya(1073742336,tl.a,tl.a,[[2,y.l],a.A]),a.Ya(1073742336,j.o,j.o,[]),a.Ya(1073742336,j.g,j.g,[]),a.Ya(1073742336,j.n,j.n,[]),a.Ya(1073742336,c.b,c.b,[]),a.Ya(1073742336,ol.c,ol.c,[]),a.Ya(1073742336,rl.e,rl.e,[]),a.Ya(1073742336,il.e,il.e,[]),a.Ya(1073742336,sl.b,sl.b,[]),a.Ya(1073742336,cl.c,cl.c,[]),a.Ya(1073742336,dl.a,dl.a,[]),a.Ya(1073742336,e,e,[]),a.Ya(256,z.a,{separatorKeyCodes:[bl.f]},[]),a.Ya(1024,I.m,function(){return[[{path:"",component:k}]]},[])])})}}]); | 11,286 | 11,286 | 0.627769 |
e38908d63f0a39f7aef288342965d0374a5e413d | 638 | js | JavaScript | api.js | nlrb/com.jilles.oregon | 8d092b8e20c65aa15b7d1fe4dfe1ac6bc2a2a5fd | [
"MIT"
] | 15 | 2016-10-10T13:10:48.000Z | 2021-03-29T20:02:30.000Z | api.js | nlrb/com.jilles.oregon | 8d092b8e20c65aa15b7d1fe4dfe1ac6bc2a2a5fd | [
"MIT"
] | 92 | 2017-05-06T07:09:34.000Z | 2022-02-06T15:44:30.000Z | api.js | nlrb/com.jilles.oregon | 8d092b8e20c65aa15b7d1fe4dfe1ac6bc2a2a5fd | [
"MIT"
] | 22 | 2016-11-20T14:23:49.000Z | 2022-02-05T20:24:15.000Z | 'use strict'
const Homey = require('homey')
module.exports = [
{
method: 'GET',
path: '/getSensors/',
public: true,
fn: function(args, callback) {
callback(null, Homey.app.getSensors());
}
},
{
method: 'GET',
path: '/getProtocols/',
public: true,
fn: function(args, callback) {
callback(null, Homey.app.getProtocols());
}
},
{
method: 'GET',
path: '/getStatistics/',
public: true,
fn: function(args, callback) {
callback(null, Homey.app.getStatistics());
}
}
];
| 20.580645 | 52 | 0.484326 |
e38ab3fea13d954e7ec7531ecfa185045c66d58f | 231 | js | JavaScript | es/utils/deepClone.js | ronn9419/create-redux-actions | 387cd33247b03b04744dfd62d2558728be7c232f | [
"MIT"
] | 2 | 2019-10-01T12:06:21.000Z | 2019-12-25T16:12:57.000Z | lib/utils/deepClone.js | ronn9419/create-redux-actions | 387cd33247b03b04744dfd62d2558728be7c232f | [
"MIT"
] | null | null | null | lib/utils/deepClone.js | ronn9419/create-redux-actions | 387cd33247b03b04744dfd62d2558728be7c232f | [
"MIT"
] | null | null | null | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
// Add support to clone function :TODO
var _default = function _default(obj) {
return obj;
};
exports.default = _default; | 17.769231 | 46 | 0.709957 |
e38bd2e31fdb69867d96305926ef37c82304d30a | 6,520 | js | JavaScript | frontend/src/pages/AdminEditUser.js | Narottam04/StoreBay | e6eadb0fd917d0320dbb14c61348569e94b7eedb | [
"Apache-2.0"
] | 2 | 2022-01-13T20:17:06.000Z | 2022-02-03T08:01:51.000Z | frontend/src/pages/AdminEditUser.js | Narottam04/StoreBay | e6eadb0fd917d0320dbb14c61348569e94b7eedb | [
"Apache-2.0"
] | 1 | 2022-01-08T14:44:27.000Z | 2022-01-08T17:17:54.000Z | frontend/src/pages/AdminEditUser.js | Narottam04/StoreBay | e6eadb0fd917d0320dbb14c61348569e94b7eedb | [
"Apache-2.0"
] | 1 | 2022-02-03T07:59:29.000Z | 2022-02-03T07:59:29.000Z | import React, { useEffect, useState } from "react";
import { MenuIcon, XIcon } from '@heroicons/react/outline'
import Sidebar from '../components/Sidebar'
import { useDispatch, useSelector } from 'react-redux'
import Loader from '../components/Loader'
import { getUserDetails, updateUser } from '../actions/userActions'
import { Link,useNavigate, useParams } from 'react-router-dom'
import { USER_UPDATE_RESET } from "../constants/userConstants";
const AdminEditUser = () => {
const [openSidebar,setOpenSidebar] = useState(false)
const [name,setName] = useState('')
const [email,setEmail] = useState('')
const [isAdmin,setisAdmin] = useState(false)
const navigate = useNavigate()
const {id} = useParams()
const dispatch = useDispatch()
const userDetails = useSelector(state => state.userDetails)
const {loading, error,user} = userDetails
const userUpdate = useSelector(state => state.userUpdate)
const {loading:loadingUpdate, error:errorUpdate,success:successUpdate} = userUpdate
const userLogin = useSelector(state => state.userLogin)
const {userInfo} = userLogin
useEffect(()=> {
if(successUpdate){
dispatch({type: USER_UPDATE_RESET})
navigate('/admin')
}
else{
if(!user.name || user._id !== id) {
dispatch(getUserDetails(id))
}
else{
setName(user.name)
setEmail(user.email)
setisAdmin(user.isAdmin)
}
}
},[user,dispatch,id,successUpdate])
const submitHandler = (e) => {
e.preventDefault()
dispatch(updateUser({_id:id,name,email,isAdmin}))
}
return (
<div className="flex flex-row min-h-screen bg-gray-100 text-gray-800 md:overflow-x-hidden">
<Sidebar openSidebar = {openSidebar} />
<main className="main flex flex-col flex-grow -ml-64 md:ml-0 transition-all duration-150 ease-in pl-64">
<header className="header bg-white shadow py-4 px-4">
<div className="header-content flex items-center flex-row">
<div >
<a href className="flex flex-row items-center">
<img
src={`https://avatars.dicebear.com/api/initials/${userInfo.name}.svg`}
alt
className="h-10 w-10 bg-gray-200 border rounded-full"
/>
<span className="flex flex-col ml-2">
<span className=" w-60 font-semibold tracking-wide leading-none">{userInfo.name}</span>
<span className=" w-30 text-gray-500 text-xs leading-none mt-1">{userInfo.email}</span>
</span>
</a>
</div>
<div className="flex ml-auto">
{!openSidebar?
<svg xmlns="http://www.w3.org/2000/svg" class="text-black w-8 h-8 md:hidden" fill="none" viewBox="0 0 24 24" stroke="currentColor" onClick={()=>setOpenSidebar(!openSidebar)}>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
</svg>
:
<svg xmlns="http://www.w3.org/2000/svg" class="text-black w-8 h-8 md:hidden" fill="none" viewBox="0 0 24 24" stroke="currentColor" onClick={()=>setOpenSidebar(!openSidebar)}>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
}
</div>
</div>
</header>
<div className="main-content flex flex-col flex-grow p-4">
<Link to={`/admin`} className="text-xl underline text-gray-700 mb-6"> Go Back</Link>
<h1 className="font-bold text-2xl text-gray-700 ">Edit User</h1>
{loadingUpdate && <p>Loading...</p>}
{errorUpdate && <p>{errorUpdate}</p>}
{loading ? <p>Loading...</p> : error ? <p>{error}</p>
:
<form onSubmit={submitHandler} className="mt-8 flex flex-col justify-start items-start w-full space-y-8 ">
<input className="px-2 focus:outline-none focus:ring-2 focus:ring-gray-500 border-b border-gray-200 leading-4 text-base placeholder-gray-600 py-4 w-full" type="text" placeholder="Name" value={name} onChange={(e)=> setName(e.target.value)} />
<input className="px-2 focus:outline-none focus:ring-2 focus:ring-gray-500 border-b border-gray-200 leading-4 text-base placeholder-gray-600 py-4 w-full" type="text" placeholder="Email" value={email} onChange={(e)=> setEmail(e.target.value)} />
<label className="inline-flex items-center">
<input type="radio" className="form-radio" name="admin" value="PayPal" onClick={(e)=> setisAdmin(true)}/>
<span className="ml-2 text-xl font-semibold">Admin</span>
</label>
<label className="inline-flex items-center mt-2 mb-5">
<input type="radio" className="form-radio" name="admin" value="Stripe" onClick={(e)=> setisAdmin(false)}/>
<span className="ml-2 text-xl font-semibold">Not Admin</span>
</label>
<button type="submit" className="focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 mt-8 text-base font-medium focus:ring-ocus:ring-gray-800 leading-4 hover:bg-black py-4 w-full md:w-4/12 lg:w-full text-white bg-gray-800">Update User</button>
</form>
}
</div>
<footer className="footer px-4 py-6">
<div className="footer-content">
<p className="text-sm text-gray-600 text-center">© Brandname 2020. All rights reserved. <a href="https://twitter.com/iaminos">by iAmine</a></p>
</div>
</footer>
</main>
</div>
)
}
export default AdminEditUser
| 53.884298 | 296 | 0.537117 |
e38c173c61c8331d32291afe9e6b4a187ce9822e | 12,155 | js | JavaScript | FMI_Parking_System/frontend/account/javascript/get_schedule.js | andy489/FMI_Parking_System | 92346552669dc58728fd36a34f526eb9461a7747 | [
"MIT"
] | 3 | 2021-07-29T21:03:39.000Z | 2022-01-02T17:19:47.000Z | FMI_Parking_System/frontend/account/javascript/get_schedule.js | andy489/FMI_Parking_System | 92346552669dc58728fd36a34f526eb9461a7747 | [
"MIT"
] | null | null | null | FMI_Parking_System/frontend/account/javascript/get_schedule.js | andy489/FMI_Parking_System | 92346552669dc58728fd36a34f526eb9461a7747 | [
"MIT"
] | null | null | null | (function() {
const uploadButton = document.getElementById("first-button"); // get the "Качване на график" button of tab "Моят график"
const scheduleButton = document.getElementById("second-button"); // get the "График" button of tab "Моят график"
const slotsButton = document.getElementById("third-button"); // get the "Запазени паркоместа" button of tab "Моят график"
const uploadSection = document.getElementById("upload-file-section"); // get the section which will be displayed when button "Качване на график" is pressed
const scheduleSection = document.getElementById("schedule-section"); // get the section which will be displayed when button "График" is pressed
const slotsSection = document.getElementById("slots-section"); // get the section which will be displayed when button "Запазени паркоместа" is pressed
let isStudent = false; // determine whether the user is a student; if he is - then block the access to the first two buttons of the "Моят график" tab
checkUserType()
.then((response) => {
if (response["user_type"] == "Студент") {
isStudent = true;
}
})
.then(() => {
if (isStudent == false) { // if user is not a student
getScheduleData()
.then((schedules) => {
if (schedules["status"] == "SUCCESS") {
const allSchedules = schedules["data"]; // get the upcoming schedule of the user
const container = document.getElementById("upcoming-schedule"); // get the container where the schedule will reside
container.innerHTML = null; // clear from previous search
for (let schedule of allSchedules) {
createSchedule(schedule, container); // attach each schedule to the container
}
}
else {
throw new Error(schedule["message"]);
}
})
.catch((error) => {
console.log(error); // for now, log the error; could add response pop-up
})
}
else { // if user is a student
uploadButton.classList.add("inactive"); // set "Качване на график" button to be inactive
scheduleButton.classList.add("inactive"); // set "График" button to be inactive
scheduleButton.classList.remove("active"); // remove default active button which is "График" button
slotsButton.classList.add("active"); // make the active button - "Запазени паркоместа" button
slotsSection.classList.remove("no-display"); // display the "Запазени паркоместа" section
scheduleSection.classList.add("no-display"); // hide the "График" section
// query the backend which slots has the student reserved
getTakenSlots()
.then((takenSlots) => {
if (takenSlots["status"] == "SUCCESS") {
const slots = takenSlots["data"]; // get the student's taken slots
const container = document.getElementById("taken-slots"); // get the div element where the taken slots will be attached
container.innerHTML = null; // clear the container from previous click
for (let slot of slots) {
createSlotSchedule(slot, container); // attach each taken slot to the container
}
}
else {
throw new Error(schedule["message"]);
}
})
.catch((error) => {
console.log(error); // log the error for now
})
}
addEventListeners(isStudent); // add event listneres to the buttons which are not inactive
})
function addEventListeners(isStudent) {
if (!isStudent) { // if user is not a student add event listeners for all buttons ("Качване на график", "График", "Запазени паркоместа")
/* all events that are going to be listened to are click events on the given button */
uploadButton.addEventListener("click", () => { // if "Качване на график" button is pressed, make that button active and display the respective section
uploadSection.classList.remove("no-display");
scheduleSection.classList.add("no-display");
slotsSection.classList.add("no-display");
uploadButton.classList.add("active");
scheduleButton.classList.remove("active");
slotsButton.classList.remove("active");
});
scheduleButton.addEventListener("click", () => { // if "График" button is pressed, make that button active, display the respective section and load the section content from a query to the backend
uploadSection.classList.add("no-display");
scheduleSection.classList.remove("no-display");
slotsSection.classList.add("no-display");
uploadButton.classList.remove("active");
scheduleButton.classList.add("active");
slotsButton.classList.remove("active");
// get the upcoming schedule of the user by querying the backend
getScheduleData()
.then((schedules) => {
if (schedules["status"] == "SUCCESS") {
const allSchedules = schedules["data"]; // get the returned schedules of the user
const container = document.getElementById("upcoming-schedule"); // get the div element where each schedule will be attacheds
container.innerHTML = null; // clear the container from the previous button click
for (let schedule of allSchedules) {
createSchedule(schedule, container); // attach each schedule to the div element (the container)
}
}
else {
throw new Error(schedule["message"]);
}
})
.catch((error) => {
console.log(error); // log the error for now
})
});
}
// if user is student execute only the below lines of code
slotsButton.addEventListener("click", () => { // if "Запазени паркоместа" button is pressed, then make that button active, display the respective section and load the section content from q query to the backend
uploadSection.classList.add("no-display");
scheduleSection.classList.add("no-display");
slotsSection.classList.remove("no-display");
uploadButton.classList.remove("active");
scheduleButton.classList.remove("active");
slotsButton.classList.add("active");
// get the taken slots from the user by querying the backend
getTakenSlots()
.then((takenSlots) => {
if (takenSlots["status"] == "SUCCESS") {
const slots = takenSlots["data"]; // get the returned reserved slots
const container = document.getElementById("taken-slots"); // get the div element where the slots will reside
container.innerHTML = null; // clear the div's content from previous button clicks
for (let slot of slots) {
createSlotSchedule(slot, container); // attach each reserved slot to the container (the div element)
}
}
else {
throw new Error(schedule["message"]);
}
})
.catch((error) => {
console.log(error); // log the error for now
})
});
}
/* create a rectangular box containing the given schedule information and attach it to the container div
here we use two spans as wrappers in order to use the css flexbox to center the texts vertically and horizontally*/
function createSchedule(schedule, container) {
const div = document.createElement("div"); // create the rectangular box
div.classList.add("schedule");
div.classList.add("schedule-item");
const firstSpanWrapper = document.createElement("span"); // first span contains the header (the type of the schedule)
const h4 = document.createElement("h4");
h4.textContent = schedule["discipline_type"] + ": " + schedule["discipline_name"]; // for example: "Лекция: WEB"
firstSpanWrapper.appendChild(h4);
const secondSpanWrapper = document.createElement("span"); // second span contains a paragraph (the info of the schedule)
const p = document.createElement("p");
p.textContent = schedule["date"] + ", " + schedule["start_time"] + "—" + schedule["end_time"] + ", " + schedule["faculty"]; // for example: "2021-06-24, 15:00-17:00, ФЗФ"
secondSpanWrapper.appendChild(p);
// append both spans to the div element (the rectangular box)
div.appendChild(firstSpanWrapper);
div.appendChild(secondSpanWrapper);
// append the rectangular box (which contains information about the given schedule) to the container element
container.appendChild(div);
}
/* create a rectangular box containing the given reserved slot information and attach it to the container div
here we use two spans as wrappers in order to use the css flexbox to center the texts vertically and horizontally */
function createSlotSchedule(slot, container) {
const div = document.createElement("div"); // create the rectangular box
div.classList.add("schedule");
div.classList.add("schedule-item");
const firstSpanWrapper = document.createElement("span"); // first span contains the header (which slot is taken)
const h4 = document.createElement("h4");
h4.textContent = "Паркомясто: " + slot["zone"] + slot["code"]; // for example: "Паркомясто: B7"
firstSpanWrapper.appendChild(h4);
const secondSpanWrapper = document.createElement("span"); // second span contains information about the taken slot (when and for what interval)
const p = document.createElement("p");
p.textContent = slot["date"] + ", " + slot["start_time"] + "—" + slot["end_time"]; // for example: "2021-06-24, 15:00-17:00"
secondSpanWrapper.appendChild(p);
// append both spans to the div element (the rectangular box)
div.appendChild(firstSpanWrapper);
div.appendChild(secondSpanWrapper);
// append the rectangular box (which contains information about the given reserved slot) to the container element
container.appendChild(div);
}
})()
// send a GET request to the backend in order to recieve the upcoming schedule of the user
function getScheduleData() {
return fetch("../../backend/api/load_user_schedule_data/load_user_schedule.php")
.then((response) => {
return response.json();
})
.then((data) => {
return data;
})
}
// send a GET request to the backend in order to recieve the reserved slots for the upcoming days by the user
function getTakenSlots() {
return fetch("../../backend/api/load_user_schedule_data/load_user_taken_slots.php")
.then((response) => {
return response.json();
})
.then((data) => {
return data;
})
}
// send a GET request to the backend in order to check whether the user is a student or not
function checkUserType() {
return fetch("../../backend/api/check_user_type/check_user_type.php")
.then((response) => {
return response.json();
})
.then((data) => {
return data;
})
} | 52.619048 | 219 | 0.588811 |
e38cb2c0767e592fbfc7c0d67f19a710a76121e2 | 185 | js | JavaScript | v15.4/app/modules/ImageUpload/index.js | kostovmichael/react-examples | 882e6702d23d9c836b54940ce93858b927849b17 | [
"MIT"
] | null | null | null | v15.4/app/modules/ImageUpload/index.js | kostovmichael/react-examples | 882e6702d23d9c836b54940ce93858b927849b17 | [
"MIT"
] | null | null | null | v15.4/app/modules/ImageUpload/index.js | kostovmichael/react-examples | 882e6702d23d9c836b54940ce93858b927849b17 | [
"MIT"
] | null | null | null | export default {
path: 'image-upload',
getComponents(nextState, cb) {
require.ensure([], require => {
cb(null, {content: require('./main')});
}, 'ImageUpload');
}
}
| 20.555556 | 45 | 0.578378 |
e38d1434e513ae90052b0115970fce716f8336b2 | 521 | js | JavaScript | src/components/NotFoundPage.js | cglorious/magic-mouse-frontend-v2 | 78794b8c8499f78dd8d4453a89687a8706c23271 | [
"MIT"
] | 2 | 2021-04-08T04:05:12.000Z | 2021-04-08T04:53:46.000Z | src/components/NotFoundPage.js | cglorious/magic-mouse-frontend | 78794b8c8499f78dd8d4453a89687a8706c23271 | [
"MIT"
] | null | null | null | src/components/NotFoundPage.js | cglorious/magic-mouse-frontend | 78794b8c8499f78dd8d4453a89687a8706c23271 | [
"MIT"
] | null | null | null | import React from "react";
import "../styles/style.css";
const NotFoundPage = () => {
return (
<div className="page-container">
<img className= "center-pixie" src="https://i.pinimg.com/originals/fd/f7/14/fdf714eb409e093eae14bde94e9f0648.jpg" alt="Pardon our Pixie Dust" />
<br/ >
<div className="header">
<h1>SORRY, we couldn't find that page.</h1>
<h5> Try going back to <a href='/'>Magic Mouse's home page.</a></h5>
</div>
</div>
);
};
export default NotFoundPage;
| 28.944444 | 150 | 0.621881 |
e39033e92db7fbd4d5a58c79e9e1a5ad50598fb1 | 1,504 | js | JavaScript | frontend/src/components/pages/EmailVerify.js | slmnt/dw | a63feb4c7a16aa72a1f7282b599bd65f46e03df9 | [
"MIT"
] | null | null | null | frontend/src/components/pages/EmailVerify.js | slmnt/dw | a63feb4c7a16aa72a1f7282b599bd65f46e03df9 | [
"MIT"
] | null | null | null | frontend/src/components/pages/EmailVerify.js | slmnt/dw | a63feb4c7a16aa72a1f7282b599bd65f46e03df9 | [
"MIT"
] | null | null | null | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import api from '../../modules/api';
import Footer from '../Footer';
import styles from './EmailVerify.module.css';
import { ReactComponent as CheckIcon } from '../../img/check.svg';
class EmailVerify extends Component {
constructor(props){
super(props);
this.state = {
flag: false
};
}
componentDidMount(){
api.post('/checkmail/', {
code: this.props.match.params['code']
}).then(response => {
console.log(response)
//this.props.history.push('/mypage')
//checked ok mail, goto mypage
}).catch(e => {
//Dont checked mail, print BLOCK page
this.setState({flag: true})
})
}
render() {
return (
<div className={styles.main}>
<div className={styles.header}>
<span>メールアドレスの確認</span>
<div className={styles.text}>
<CheckIcon className={styles.icon}/>
<span>確認完了</span>
</div>
{
this.state.flag &&
<div>エラー</div>
}
</div>
<div className={styles.content}>
</div>
<Footer />
</div>
);
}
}
EmailVerify.propTypes = {};
export default EmailVerify;
| 26.385965 | 66 | 0.466755 |
e390722fe8f3040e1a430d17efea4ecd279a6f1d | 246 | js | JavaScript | src/App.js | CristoferPortela/calculator | 533e59bbee229e799af523bfc24591ed6ed07f1d | [
"MIT"
] | null | null | null | src/App.js | CristoferPortela/calculator | 533e59bbee229e799af523bfc24591ed6ed07f1d | [
"MIT"
] | 7 | 2020-09-07T00:22:05.000Z | 2022-02-26T16:52:12.000Z | src/App.js | CristoferPortela/calculator | 533e59bbee229e799af523bfc24591ed6ed07f1d | [
"MIT"
] | null | null | null | import React from 'react';
import './App.css';
import { Main } from './templates/Main'
export default props =>
<React.Fragment>
<header>
<h1> Calcule it! </h1>
</header>
<main className="main">
<Main/>
</main>
</React.Fragment>
| 16.4 | 39 | 0.621951 |
e391116eddc987a4c3d56acde272987f5a9ab529 | 5,475 | js | JavaScript | assets/src/pages/test/http/effects.js | papa-hexuan/juno | 200e4861243070761ee063d99e093d809ff9b79a | [
"Apache-2.0"
] | 411 | 2020-06-01T04:42:53.000Z | 2022-03-30T23:59:07.000Z | assets/src/pages/test/http/effects.js | icewater2020/juno | d66b729612c8db72404d48c066216533afe9a5a5 | [
"Apache-2.0"
] | 52 | 2020-06-02T09:41:23.000Z | 2022-02-28T01:49:35.000Z | assets/src/pages/test/http/effects.js | icewater2020/juno | d66b729612c8db72404d48c066216533afe9a5a5 | [
"Apache-2.0"
] | 111 | 2020-06-01T02:09:05.000Z | 2022-02-25T03:33:17.000Z | import {
createCollection, fetchCollections,
getFolderTree,
fetchTestCase,
loadHistory,
sendRequest,
saveTestCase, createTestCase, fetchHttpAddrList, loadHistoryDetail
} from "@/services/httptest";
import {message} from "antd";
export default {
* loadTestCase({payload}, {call, put}) {
yield put({
type: '_apply',
payload: {
currentRequestLoading: true
}
})
const res = yield call(fetchTestCase, payload.id);
yield put({
type: '_apply',
payload: {
currentRequestLoading: false
}
})
if (res.code === 0) {
yield put({
type: '_setCurrentRequest',
payload: res.data
})
}
return res;
},
* updateCurrentRequest({payload}, {put}) {
yield put({
type: '_updateCurrentRequest',
payload: payload
})
},
* sendRequest({payload}, {call, put}) {
yield put({
type: '_setSendStatus',
payload: 'sending'
});
const res = yield call(sendRequest, payload);
if (res.code !== 0) {
message.error(res.msg);
yield put({
type: '_setResponse',
payload: {
response: null,
status: "fail",
error: res.msg
}
});
} else {
yield put({
type: '_setResponse',
payload: {
response: res.data,
status: "success",
error: ''
}
});
}
},
* saveTestCase({payload}, {call, put}) {
if (typeof payload.body !== 'string') {
try {
payload.body = JSON.stringify(payload.body)
} catch (e) {
payload.body = ''
}
}
const res = yield call(saveTestCase, payload);
if (res.code === 0) {
message.success("保存成功")
} else {
message.error(res.msg)
}
return res
},
* loadHistory({payload}, {call, put}) {
yield put({
type: '_apply',
payload: {
historyLoading: true
}
})
const res = yield call(loadHistory, payload);
if (res.code === 0) {
yield put({
type: '_setHistory',
payload: res.data
})
}
},
* loadHistoryDetail({payload}, {call, put}) {
yield put({
type: '_apply',
payload: {
currentRequestLoading: true
}
})
const res = yield call(loadHistoryDetail, payload)
if (res.code !== 0) {
message.error(res.msg)
return res;
}
yield put({
type: '_apply',
payload: {
currentRequestLoading: false,
currentRequest: {
...res.data,
id: undefined
}
}
})
return res
},
* createCollection({payload}, {call, put}) {
const {name, appName} = payload;
yield put({
type: '_apply',
payload: {
confirmNewCollectionLoading: true
}
})
const res = yield call(createCollection, appName, name);
yield put({
type: '_apply',
payload: {
confirmNewCollectionLoading: false,
visibleModalNewCollection: res.code !== 0
}
})
if (res.code !== 0) {
message.error(res.msg)
}
return res
},
* createTestCase({payload}, {call, put}) {
yield put({
type: '_apply',
payload: {
confirmNewTestCaseLoading: true,
currentRequestLoading: true
}
})
const res = yield call(createTestCase, payload)
if (res.code !== 0) {
message.error(res.msg)
} else {
message.success("创建成功")
}
let updatePayload = {
confirmNewTestCaseLoading: false,
visibleModalNewTestCase: res.code !== 0,
currentRequestLoading: false,
}
if (res.code === 0) {
updatePayload.currentRequest = res.data
}
yield put({
type: '_apply',
payload: updatePayload
})
return res
},
* showModalNewCollection({payload}, {call, put}) {
yield put({
type: '_apply',
payload: {
visibleModalNewCollection: payload
}
})
},
* showModalNewTestCase({payload}, {call, put}) {
yield put({
type: '_apply',
payload: {
visibleModalNewTestCase: payload.visible,
selectedCollection: payload.collectionID
}
})
},
* setCurrentApp({payload}, {call, put}) {
yield put({
type: '_apply',
payload: {
currentAppName: payload
}
})
},
* fetchCollections({payload}, {call, put}) {
const {appName, page = 0, pageSize = 1000} = payload
yield put({
type: '_apply',
payload: {
collectionsLoading: true
}
})
const res = yield call(fetchCollections, appName, page, pageSize)
if (res.code !== 0) {
message.error(res.msg);
return res;
}
yield put({
type: '_apply',
payload: {
collectionsLoading: false,
collections: res.data.list,
collectionsPagination: res.data.pagination
}
})
return res
},
* fetchAppHttpAddrList({payload}, {call, put}) {
const res = yield call(fetchHttpAddrList, payload);
if (res.code !== 0) {
message.error("获取应用地址列表失败:" + res.msg);
return res;
}
yield put({
type: '_apply',
payload: {
httpPort: res.data.port,
addrList: res.data.hosts
}
})
return res
},
* showModalScriptEditor({payload}, {call, put}) {
yield put({
type: '_apply',
payload: {
visibleModalScriptEditor: payload
}
})
}
}
| 19.836957 | 69 | 0.537169 |
e39159c6705224ee941fe98b9ab5a7a523f5928b | 435 | js | JavaScript | LeanKanban/main.js | Aspectize/Samples | 30a6f09d74df2c59e7940bcf00d65734ee9be906 | [
"MIT"
] | null | null | null | LeanKanban/main.js | Aspectize/Samples | 30a6f09d74df2c59e7940bcf00d65734ee9be906 | [
"MIT"
] | null | null | null | LeanKanban/main.js | Aspectize/Samples | 30a6f09d74df2c59e7940bcf00d65734ee9be906 | [
"MIT"
] | null | null | null | /// <reference path="S:\Delivery\Aspectize.core\AspectizeIntellisenseLibrary.js" />
function Main() {
Aspectize.App.Initialize(function () {
var currentUser = Aspectize.GetCurrentUser();
if (currentUser.IsAuthenticated) {
Aspectize.ExecuteCommand('UIService.ShowView', 'MyBoards');
}
else {
Aspectize.ExecuteCommand('UIService.ShowView', 'Welcome');
}
});
}
| 24.166667 | 83 | 0.622989 |
e3915a67f092cb15fdcfc0127bbce0a17512b290 | 289 | js | JavaScript | scripts/prepublish/browserify.js | horaguchi/Ponzu | c33ef600e098b9fd291e40615b666d3e0fdde768 | [
"Apache-2.0"
] | 2 | 2015-03-12T21:08:45.000Z | 2015-03-16T03:58:47.000Z | scripts/prepublish/browserify.js | horaguchi/Ponzu | c33ef600e098b9fd291e40615b666d3e0fdde768 | [
"Apache-2.0"
] | null | null | null | scripts/prepublish/browserify.js | horaguchi/Ponzu | c33ef600e098b9fd291e40615b666d3e0fdde768 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env node
var fs = require('fs');
var browserify = require('browserify');
var b = browserify({
standalone: "Ponzu"
});
b.add("./ponzu.js");
b.bundle(function (err, src) {
fs.writeFileSync("./ponzu.browserify.js", src);
console.info("ponzu.browserify.js is updated");
});
| 20.642857 | 49 | 0.657439 |
e39213440de0284fef0a97476467eabe2506e013 | 255 | js | JavaScript | src/tools/summary/file-size.js | davelab6/wakamai-fondue-engine | 50b68ac117a9aa5d907174db1920b4823ed4263e | [
"Apache-2.0"
] | 27 | 2020-08-26T00:40:26.000Z | 2022-03-19T05:13:38.000Z | src/tools/summary/file-size.js | davelab6/wakamai-fondue-engine | 50b68ac117a9aa5d907174db1920b4823ed4263e | [
"Apache-2.0"
] | 41 | 2020-08-26T06:26:08.000Z | 2022-03-19T05:38:34.000Z | src/tools/summary/file-size.js | davelab6/wakamai-fondue-engine | 50b68ac117a9aa5d907174db1920b4823ed4263e | [
"Apache-2.0"
] | 7 | 2020-08-26T00:40:39.000Z | 2022-03-21T10:53:40.000Z | export default function getFileSize(fondue) {
const bytes = fondue._font.fontData.byteLength;
return bytes > 1024 * 1024
? `${Math.floor(bytes / (1024 * 1024))} MB`
: bytes > 1024
? `${Math.floor(bytes / 1024)} KB`
: `${Math.floor(bytes)} B`;
}
| 28.333333 | 48 | 0.643137 |
e393075bb6a4b29f0754b7a8c22f165f8af05375 | 186 | js | JavaScript | docs/html docs/struct__NV__PIXEL__SRSO__2x2_1_1NV__PIXEL__SRSO__2x2__X2.js | kdschlosser/nvapi | f56c1b74e3066be1fa0bb21326403cd33fda16d1 | [
"MIT"
] | 5 | 2020-06-05T23:56:37.000Z | 2021-06-12T06:21:15.000Z | docs/html docs/struct__NV__PIXEL__SRSO__2x2_1_1NV__PIXEL__SRSO__2x2__X2.js | kdschlosser/nvapi | f56c1b74e3066be1fa0bb21326403cd33fda16d1 | [
"MIT"
] | 1 | 2020-12-03T18:25:45.000Z | 2020-12-05T14:55:07.000Z | docs/html docs/struct__NV__PIXEL__SRSO__2x2_1_1NV__PIXEL__SRSO__2x2__X2.js | kdschlosser/nvapi | f56c1b74e3066be1fa0bb21326403cd33fda16d1 | [
"MIT"
] | null | null | null | var struct__NV__PIXEL__SRSO__2x2_1_1NV__PIXEL__SRSO__2x2__X2 =
[
[ "YXS", "struct__NV__PIXEL__SRSO__2x2_1_1NV__PIXEL__SRSO__2x2__X2.html#a35209923f0ad7edededa7c461dc43acd", null ]
]; | 46.5 | 118 | 0.854839 |
e39333ddc8c920b760fa6564b1ffb287116929af | 1,038 | js | JavaScript | src/gl/HelloGL.js | gr4yscale/havit | 95bad4b1d0681b1adc3b9d5d91f03907eed2316e | [
"MIT"
] | 1 | 2016-01-03T01:03:57.000Z | 2016-01-03T01:03:57.000Z | src/gl/HelloGL.js | gr4yscale/havit | 95bad4b1d0681b1adc3b9d5d91f03907eed2316e | [
"MIT"
] | 1 | 2016-08-24T10:37:04.000Z | 2016-08-24T10:37:04.000Z | src/gl/HelloGL.js | gr4yscale/havit | 95bad4b1d0681b1adc3b9d5d91f03907eed2316e | [
"MIT"
] | null | null | null | const React = require('react-native');
const GL = require('gl-react');
const {Surface} = require('gl-react-native');
const shaders = GL.Shaders.create({
helloGL: {
frag: `
precision highp float;
varying vec2 uv; // This variable vary in all pixel position (normalized from vec2(0.0,0.0) to vec2(1.0,1.0))
void main () { // This function is called FOR EACH PIXEL
gl_FragColor = vec4(uv.x, uv.y, 0.5, 1.0); // red vary over X, green vary over Y, blue is 50%, alpha is 100%.
}
`,
},
});
module.exports = GL.createComponent(() =>
<GL.Node shader={shaders.helloGL} />,
{ displayName: 'HelloGL' }
);
class HelloGL extends React.Component {
render () {
const { width, height } = this.props;
return (
<Surface
width={width} height={height}
pixelRatio={2}
opaque={true}
ref="helloGL"
style={{position:'absolute', width, height, top:0, left: 0}}
>
<GL.Node
shader={shaders.helloGL}
/>
</Surface>
)
}
}
module.exports = HelloGL
| 23.066667 | 111 | 0.602119 |
e3956047cfb9471c4aece6fba4af12e7b3a73a88 | 1,021 | js | JavaScript | app/imports/api/tasks/publications.js | ajaybhatia/taskbuster-meteor | 62ad0781a26ca6eed24ab90098c23fe84e0742d3 | [
"MIT"
] | null | null | null | app/imports/api/tasks/publications.js | ajaybhatia/taskbuster-meteor | 62ad0781a26ca6eed24ab90098c23fe84e0742d3 | [
"MIT"
] | null | null | null | app/imports/api/tasks/publications.js | ajaybhatia/taskbuster-meteor | 62ad0781a26ca6eed24ab90098c23fe84e0742d3 | [
"MIT"
] | null | null | null | import { Meteor } from 'meteor/meteor';
import { Tasks } from './tasks.js';
/**
* Collection publications to the client. Publications must
* return a cursor object.
*
* *Disabled by default. Uncomment return for each publication to enable.*
*
* Example:
* ```
* Meteor.publish('tasks.public', function tasksPublic() {
* let cursor = Tasks.find({
* userId: { $exists: false },
* }, {
* fields: Tasks.publicFields
* });
* return cursor;
* });
* ```
* @memberof Server.Tasks
* @member Publications
*/
Meteor.publish('tasks.public', function tasksPublic() {
let cursor = Tasks.find({
userId: { $exists: false },
}, {
fields: Tasks.publicFields
});
return cursor;
});
Meteor.publish('tasks.private', function tasksPrivate() {
if (!this.userId) {
return this.ready();
}
let cursor = Tasks.find({
userId: this.userId,
}, {
fields: Tasks.privateFields,
});
return cursor;
});
| 21.723404 | 74 | 0.575906 |
e395fc6f81a53b262b0c9b040b9c7947f5aaf546 | 273 | js | JavaScript | test/std2525c-ground-equipment.test.js | agmt5989/milsymbol | 72ec7691d455e259356ddc73c76d5c45d4be2356 | [
"MIT"
] | 359 | 2015-07-20T15:34:56.000Z | 2022-03-31T18:47:37.000Z | test/std2525c-ground-equipment.test.js | agmt5989/milsymbol | 72ec7691d455e259356ddc73c76d5c45d4be2356 | [
"MIT"
] | 231 | 2015-06-19T08:20:34.000Z | 2022-02-22T09:11:21.000Z | test/std2525c-ground-equipment.test.js | agmt5989/milsymbol | 72ec7691d455e259356ddc73c76d5c45d4be2356 | [
"MIT"
] | 108 | 2015-07-24T17:57:08.000Z | 2022-03-19T14:59:50.000Z | import { ms } from "../src/milsymbol";
ms.reset();
import { ms2525c } from "milstd2525";
import verify from "./letter-sidc";
import { equipment } from "../src/lettersidc";
ms.addIcons(equipment);
export default verify(ms, "MIL-STD-2525C Ground", ms2525c.WAR.GRDTRK_EQT);
| 27.3 | 74 | 0.70696 |
e396492240a5f3e756ff82abc524dcb1d99d388b | 3,585 | js | JavaScript | src/components/ContactForm/ContactForm.js | LarsBehrenberg/portfolio | 7a3a4bbd4c7aedcc4db9567a2dbe15ebd6de5964 | [
"MIT"
] | null | null | null | src/components/ContactForm/ContactForm.js | LarsBehrenberg/portfolio | 7a3a4bbd4c7aedcc4db9567a2dbe15ebd6de5964 | [
"MIT"
] | null | null | null | src/components/ContactForm/ContactForm.js | LarsBehrenberg/portfolio | 7a3a4bbd4c7aedcc4db9567a2dbe15ebd6de5964 | [
"MIT"
] | null | null | null | import React from "react";
import { Form } from "react-bootstrap";
import { Input, TextArea, Button, Text } from "../Core";
import { FormattedMessage, useIntl } from "gatsby-plugin-intl";
const ContactForm = ({ theme = "dark", ...rest }) => {
const intl = useIntl();
const initialState = {
name: "",
subject: "",
email: "",
message: "",
};
const [state, setState] = React.useState(initialState);
const [successMessage, setSuccessMessage] = React.useState("");
function encode(data) {
return Object.keys(data)
.map(
(key) => encodeURIComponent(key) + "=" + encodeURIComponent(data[key])
)
.join("&");
}
const handleChange = (e) => {
if (successMessage !== "") {
setSuccessMessage("");
}
setState({ ...state, [e.target.name]: e.target.value });
console.log(state);
};
const handleSubmit = (e) => {
e.preventDefault();
const form = e.target;
fetch("/", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encode({
"form-name": form.getAttribute("name"),
...state,
}),
})
.then(() => setState(initialState))
.then(() =>
setSuccessMessage(intl.formatMessage({ id: "contact_form_success" }))
)
.catch(() =>
setSuccessMessage(intl.formatMessage({ id: "contact_form_error" }))
);
};
return (
<Form
name="contact"
method="POST"
data-netlify="true"
netlify-honeypot="bot-field"
action="/#"
onSubmit={handleSubmit}
{...rest}
>
{/* You still need to add the hidden input with the form name to your JSX form */}
<input type="hidden" name="bot-field" />
<input type="hidden" name="form-name" value="contact" />
<p hidden>
<label>
Don’t fill this out if you're human: <input name="bot-field" />
</label>
</p>
<div className="mt-4">
<Input
type="text"
placeholder={intl.formatMessage({ id: "contact_form_name" })}
required
name="name"
value={state.name}
onChange={handleChange}
/>
</div>
<div className="mt-4">
<Input
type="email"
placeholder={intl.formatMessage({ id: "contact_form_email" })}
required
name="email"
value={state.email}
onChange={handleChange}
/>
</div>
<div className="mt-4">
<Input
type="text"
placeholder={intl.formatMessage({ id: "contact_form_subject" })}
required
name="subject"
value={state.subject}
onChange={handleChange}
/>
</div>
<div className="mt-4 ">
<TextArea
rows={4}
placeholder={intl.formatMessage({ id: "contact_form_message" })}
required
value={state.message}
name="message"
onChange={handleChange}
/>
</div>
<div className="mt-4 mt-lg-5">
<Button arrowRight variant="primary" type="submit">
<FormattedMessage id="contact_form_submit" />
</Button>
</div>
<div className="mt-4 ">
<Text
color={`${successMessage.includes("successfully") ? "green" : "red"}`}
>
{successMessage}
</Text>
</div>
</Form>
);
};
export default ContactForm;
| 26.954887 | 89 | 0.514644 |
e3133637c4fbd25b17aee17c4b976ac6f56a4b68 | 1,333 | js | JavaScript | src/components/ItemList.js | Fahad-Shinwari/ecomerce | fb5bde98540f8dc8bfcd4bbdf0ff303d202f5d12 | [
"MIT"
] | null | null | null | src/components/ItemList.js | Fahad-Shinwari/ecomerce | fb5bde98540f8dc8bfcd4bbdf0ff303d202f5d12 | [
"MIT"
] | null | null | null | src/components/ItemList.js | Fahad-Shinwari/ecomerce | fb5bde98540f8dc8bfcd4bbdf0ff303d202f5d12 | [
"MIT"
] | null | null | null | import React, { Component } from 'react'
import { Item } from './Item'
export class ItemList extends Component {
state={
database:[
{id:1,name:'Google Pixel - Black',price:13,count:0,total:0,img:"img/product-1.png"},
{id:2,name:'Samsung S7',price:28,count:0,total:0,img:"img/product-2.png"},
{id:3,name:'HTC 10 - Black',price:38,count:0,total:0,img:"img/product-3.png"},
{id:4,name:'HTC 10 - White',price:132,count:0,total:0,img:"img/product-4.png"},
{id:5,name:'HTC Desire 626s',price:88,count:0,total:0,img:"img/product-5.png"},
{id:6,name:'Vintage Iphone',price:83,count:0,total:0,img:"img/product-6.png"},
{id:7,name:'Iphone 7',price:53,count:0,total:0,img:"img/product-7.png"},
{id:8,name:'Smashed Iphone',price:68,count:0,total:0,img:"img/product-8.png"}
]
}
render() {
const phone= this.state.database.map(item=>{
return(
<Item key={item.id} id={item.id} img={item.img} name={item.name} count={item.count} total={item.total} price={item.price} />
) })
return (
<div className="row">
{phone}
</div>
)
}
}
export default ItemList
| 39.205882 | 137 | 0.534134 |
e31341e7a16073f9b62bde92a1e8800a1f23900f | 6,430 | js | JavaScript | controllers/files.js | enki-com/TC-london-hack | 7c840c883a12305fae6ed2ce2932d3c160225ab1 | [
"MIT"
] | 8 | 2017-03-04T06:54:13.000Z | 2020-05-28T16:40:03.000Z | controllers/files.js | enkidevs/TC-london-hack | 7c840c883a12305fae6ed2ce2932d3c160225ab1 | [
"MIT"
] | 1 | 2018-01-10T19:47:32.000Z | 2018-01-10T19:47:32.000Z | controllers/files.js | enkidevs/TC-london-hack | 7c840c883a12305fae6ed2ce2932d3c160225ab1 | [
"MIT"
] | 3 | 2017-08-10T14:15:16.000Z | 2019-07-17T17:27:34.000Z | /**
* Split into declaration and initialization for better startup performance.
*/
const User = require('../models/User');
const _ = require('lodash');
const refresh = require('passport-oauth2-refresh');
const secrets = require('../config/secrets');
const google = require('googleapis');
const fs = require('fs');
const request = require('request');
const {downloadGoogleSpreadsheet} = require('../libs/downloadingFile');
const {genSchema} = require('../libs/genSchema');
/**
* GET /api/files
*/
function getGoogleFiles(req, res, next) {
const token = _.find(req.user.tokens, { kind: 'google' });
let retries = 2;
const OAuth2 = google.auth.OAuth2;
function makeRequest() {
retries--;
if (!retries) {
// Couldn't refresh the access token.
return res.status(401).end();
}
const oauth2Client = new OAuth2(
secrets.google.clientID,
secrets.google.clientSecret,
secrets.google.callbackURL
);
oauth2Client.setCredentials({
access_token: token.accessToken,
refresh_token: token.refreshToken,
});
const drive = google.drive({ version: 'v2', auth: oauth2Client });
drive.files.list({
q: 'mimeType = \'application/vnd.google-apps.spreadsheet\' and trashed = false',
}, (err, result) => {
if (err) {
if (err.code === 401) {
refresh.requestNewAccessToken('google', token.refreshToken, (err2, accessToken) => {
if (err2 || !accessToken) { return res.status(401).end(); }
token.accessToken = accessToken;
// Save the new accessToken for future use
User.findById(req.user, (_err, user) => {
user.tokens = user.tokens.map(t => {
if (t.kind === 'google') {
return { kind: 'google', accessToken, refreshToken: t.refreshToken };
}
return t;
});
user.save(makeRequest);
});
});
return;
}
next(err);
return;
}
User.findById(req.user.id, (err2, user) => {
if (err2) {
return next(err2);
}
user.googleFiles = result.items.map(f => {
if (f.exportLinks) {
f.exportLinks = {
officedocument: f.exportLinks['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
};
}
return f;
});
user.save((err3) => {
if (err3) {
return next(err3);
}
res.render('files/files', {
title: 'Files',
files: result.items.map(file => {
if (user.apiFiles.find(f => f.id === file.id)) {
file.synced = true;
}
file.cleanTitle =
file.title.replace(/ /g, '_')
.replace(/\./g, '_')
.replace(/\//g, '_');
return file;
}),
});
});
});
});
}
makeRequest();
}
exports.getGoogleFiles = getGoogleFiles;
exports.getSyncedFiles = function getSyncedFiles(req, res, next) {
User.findById(req.user.id, (err, user) => {
if (err) {
return next(err);
}
return res.render('files/synced', {
title: 'Synced',
apiFiles: user.apiFiles.map(f => {
f.cleanTitle =
f.title.replace(/ /g, '_')
.replace(/\./g, '_')
.replace(/\//g, '_');
return f;
})}
);
});
};
function deleteCachedFile(file, user) {
const cleanTitle = file.title.replace(/ /g, '_').replace(/\//g, '_').replace(/\./g, '_');
try {
fs.unlinkSync(
'.cached_files/' + cleanTitle + '.xlsx'
);
} catch (e) {
console.log(e);
}
const token = _.find(user.tokens, { kind: 'google' });
request('https://www.googleapis.com/drive/v2/channels/stop'
, {
method: 'POST',
'id': 'file--' + file.id + '__user--' + user.id,
'resourceId': file.resourceId,
'auth': {
'bearer': token.accessToken,
},
}, (err, res) => {
console.log('Unsubscribe: ', (err || {}).body, (res || {}).body);
});
}
exports.unsyncFile = function unsyncFile(req, res, next) {
User.findById(req.user.id, (err, user) => {
if (err) {
return next(err);
}
user.apiFiles = user.apiFiles.filter(
f => {
if (f.id === req.params.id) {
deleteCachedFile(f, user);
return false;
}
return true;
}
);
user.save();
return res.render('files/synced',
{apiFiles: user.apiFiles}
);
});
};
exports.unsyncFileFromFullList = function unsyncFileFromFullList(req, res, next) {
User.findById(req.user.id, (err, user) => {
if (err) {
return next(err);
}
user.apiFiles = user.apiFiles.filter(
f => {
if (f.id === req.params.id) {
deleteCachedFile(f, user);
return false;
}
return true;
}
);
user.save(() => {
return getGoogleFiles(req, res, next);
});
});
};
/**
* GET /api/file
*/
exports.getGoogleFile = function getGoogleFile(req, res, next) {
const fileId = req.params.file;
const file = req.user.googleFiles.find(f => f.id === fileId);
if (!file) { return next(new Error('no file with this id')); }
const OAuth2 = google.auth.OAuth2;
const token = _.find(req.user.tokens, { kind: 'google' });
downloadGoogleSpreadsheet(token, file, () => {
genSchema();
console.log('done');
});
const oauth2Client = new OAuth2(
secrets.google.clientID,
secrets.google.clientSecret,
secrets.google.callbackURL
);
oauth2Client.setCredentials({
access_token: token.accessToken,
refresh_token: token.refreshToken,
});
const drive = google.drive({ version: 'v2', auth: oauth2Client });
const resource = {
'id': 'file--' + file.id + '__user--' + req.user.id,
'type': 'web_hook',
'address': 'https://driveql.herokuapp.com/notification',
};
drive.files.watch({
'fileId': file.id,
resource,
}, (err, result) => {
if (err) {
console.log('error on watch:', err);
} else { console.log('watch result:', result); }
});
return User.findById(req.user.id, (err, user) => {
if (err) {
return next(err);
}
user.apiFiles.push(file);
user.save(() => {
return getGoogleFiles(req, res, next);
});
});
};
| 26.244898 | 113 | 0.54168 |
e313b73260f8aa5881863e6065d26410111db1b1 | 941 | js | JavaScript | client/src/EventNotifier.js | investingsnippets/simple-portfolio-management-on-ethereum | e28f6589bf031c13775f24a1ff113c06bee3907e | [
"MIT"
] | null | null | null | client/src/EventNotifier.js | investingsnippets/simple-portfolio-management-on-ethereum | e28f6589bf031c13775f24a1ff113c06bee3907e | [
"MIT"
] | null | null | null | client/src/EventNotifier.js | investingsnippets/simple-portfolio-management-on-ethereum | e28f6589bf031c13775f24a1ff113c06bee3907e | [
"MIT"
] | 1 | 2021-02-22T15:22:31.000Z | 2021-02-22T15:22:31.000Z | import {EventActions} from "@drizzle/store";
import { toast } from 'react-toastify'
// Due to an issue with metamask we get several fires for teh same event:
// https://github.com/MetaMask/metamask-extension/issues/6668
// To avoid that we just make sure that we do not retrigger
let processed_events = new Set();
const EventNotifier = store => next => action => {
if (action.type === EventActions.EVENT_FIRED && !processed_events.has(action.event.transactionHash)) {
console.log(action);
const contract = action.name
const contractEvent = action.event.event
const message = action.event.returnValues._message
const display = `${contract}(${contractEvent}): ${message}`
console.log(display);
toast.success(display, { position: toast.POSITION.TOP_RIGHT })
processed_events.add(action.event.transactionHash);
}
return next(action);
}
export default EventNotifier; | 39.208333 | 106 | 0.700319 |