text
stringlengths 7
3.69M
|
|---|
const Express = require("express");
const router = Express.Router();
const mongoUser = require("../../controller/mongoUser");
const isLoggedIn = require("../../middlewares/isLoggedIn");
const { newSong } = require("../../controller/mongoSong");
router.post("/", isLoggedIn, async (req, res) => {
const data = { message: "", code: "", navbar: true };
try {
const { spotify_id, name, album } = req.body;
const newSongID = await newSong(spotify_id, name, album);
const addSong = await mongoUser.addFavoriteSong(
req.session.currentUser,
newSongID
);
res.status(200).json({ message: addSong });
} catch (error) {
data.code = 422;
data.message = error;
res.render("error", data);
}
});
module.exports = router;
|
var nFib = function(n) {
var first = 0;
var second = 1;
for (var i = 2; i <= n; i++) {
var temp = second;
second += first;
first = temp;
}
return second;
}
|
import { createStore } from 'redux';
const ADD_TODO = 'ADD_TODO';
const TOGGLE_TODO = 'TOGGLE_TODO';
const CHANGE_VISIBILITY_FILTER = 'CHANGE_VISIBILITY_FILTER';
function addTodo(text) {
return { type: ADD_TODO, text };
}
function toggleTodo(todo) {
return { type: TOGGLE_TODO, todo };
}
function todoReducer(state = { id: 0, todos: [] }, action) {
switch (action.type) {
case ADD_TODO:
return [...state, { id: ++state.id, text: action.text, done: false }];
case TOGGLE_TODO:
return state.map(x => {
if (x === action.todo) {
return { ...x, done: !x.done };
}
return x;
});
default:
return state;
}
}
function visibilityReducer(state = 'all', action) {
switch (action.type) {
case CHANGE_VISIBILITY_FILTER:
return action.payload;
default:
return state;
}
}
function combineReducer(input) {
return function(state = {}, action) {
const newState = {};
Object.keys(input).map(x => {
newState[x] = input[x](state[x], action);
});
return newState;
};
}
const reducer = combineReducer({
todo: todoReducer,
visibilityFilter: visibilityReducer
});
const store = createStore(reducer);
store.subscribe(() => {
console.log(store.getState());
});
store.dispatch(addTodo('Get Milk'));
store.dispatch(addTodo('Get Kooft'));
store.dispatch(addTodo('Get Maraz'));
// store.dispatch(toggleTodo(store.getState()[0]))
|
var breakDancer = function(top, left, timeBetweenSteps) {
makeDancer.call(this, top, left, timeBetweenSteps);
// this.$node.removeClass('dancer');
this.$node.addClass('breakdancer');
// we plan to overwrite the step function below, but we still want the superclass step behavior to work,
// so we must keep a copy of the old version of this function
};
breakDancer.prototype = Object.create(makeDancer.prototype);
breakDancer.prototype.constructor = breakDancer;
breakDancer.prototype.step = function () {
makeDancer.prototype.step.call(this);
};
|
'use strict';
/*
* DATABASE: Mongo
*/
const mongoose = require(`mongoose`);
const MongooseSchema = mongoose.Schema;
const extender = require(`object-extender`);
const DatabaseBase = require(`./databaseBase`);
const Property = require(`../../modules/schema/property`);
const Reference = require(`../../modules/schema/reference`);
const Schema = require(`../../modules/schema/schema`);
module.exports = class DatabaseMongo extends DatabaseBase {
/*
* Instantiates the handler.
*/
constructor (_options) {
// Configure the handler.
super(`database`, `mongo`);
// Default config for this handler.
this.options = extender.defaults({
connectionString: null,
mock: false,
}, _options);
// Define the required dependencies.
this.requirements = [ `sharedLogger` ];
// Force Mongoose to use native promises.
mongoose.Promise = global.Promise;
}
/*
* Converts the given schema into a model this database can understand.
*/
addModel (Model, extraOptions = {}) {
const schema = new Model(Schema, Property, Reference);
const modelName = schema.modelName;
if (this.hasModel(modelName)) {
throw this.__error(`EXISTING_MODEL`, { modelName });
}
// Setup the Mongoose schema.
const mongooseSchema = this.__convertToMongooseSchema(schema);
// add methods and static methods
if (schema.options.statics || extraOptions.statics) {
Object.assign(mongooseSchema.statics, {
...schema.options.statics,
...extraOptions.statics,
getDB: () => this,
});
}
if (schema.options.methods || extraOptions.methods) {
Object.assign(mongooseSchema.methods, {
...schema.options.methods,
...extraOptions.methods,
getDB: () => this,
});
}
// Setup schema indices.
if (schema.options.indices) {
schema.options.indices.forEach(indexDefinition => mongooseSchema.index(indexDefinition));
}
// Convert to Mongoose model.
this.models[modelName] = mongoose.model(modelName, mongooseSchema, modelName.toLowerCase());
}
/*
* Converts the given hash of schema fields into a Mongoose schema recursively.
*/
__convertToMongooseSchema (input, isNested = false) {
const fields = (input.constructor.name === `Schema` ? input.fields : input);
const convertedProperties = {};
for (const key in fields) {
if (!fields.hasOwnProperty(key)) { continue; }
const field = fields[key];
switch (field.constructor.name) {
// Nested in an array (i.e. a subdocument).
case `Schema`:
convertedProperties[key] = new MongooseSchema(this.__convertToMongooseSchema(field, true), { _id: false });
break;
// Nested properties.
case `Object`:
convertedProperties[key] = this.__convertToMongooseSchema(field, true);
break;
// A primitive.
case `Property`:
convertedProperties[key] = { type: this.__getPropertyDataType(field), default: field.defaultValue };
break;
// A subdocument.
case `Array`:
convertedProperties[key] = Object.values(this.__convertToMongooseSchema(field, true));
break;
// A reference to another model.
case `Reference`:
convertedProperties[key] = { type: MongooseSchema.Types.ObjectId, ref: field.referencedModel };
break;
default: throw new Error(`Invalid schema property type at "${key}".`);
}
}
// We only need to turn the top level properties into a Mongoose schema.
return (isNested ? convertedProperties : new MongooseSchema(convertedProperties));
}
/*
* Returns the appropriate JavaScript type for the given property's data type.
*/
__getPropertyDataType (field) {
switch (field.dataType) {
case `boolean`: return Boolean;
case `date`: return Date;
case `float`: return Number;
case `integer`: return Number;
case `string`: return String;
case `flexible`: return MongooseSchema.Types.Mixed;
default: throw new Error(`Invalid data type "${field.dataType}".`);
}
}
/*
* Connect to the database.
*/
async connect () {
// Are we mocking the database for testing?
try {
if (this.options.mock) { await this.__mockDatabase(); }
}
catch (err) {
throw this.__error(`MOCK_FAILED`, { err });
}
// Connect to the database.
try {
await this.__connectToDatabase(this.options.connectionString);
}
catch (err) {
throw this.__error(`CONNECT_FAILED`, { err });
}
}
async disconnect () {
// Connect to the database.
try {
await mongoose.disconnect();
}
catch (err) {
throw this.__error(`DISCONNECT_FAILED`, { err });
}
}
/*
* Sets up Mockgoose for testing.
*/
async __mockDatabase () {
/* eslint global-require: 0 */
/* eslint node/no-unpublished-require: 0 */
const sharedLogger = this.__dep(`sharedLogger`);
sharedLogger.info(`Preparing Mockgoose for testing...`);
const { Mockgoose } = require(`mockgoose`);
const mockedDatabase = new Mockgoose(mongoose);
await mockedDatabase.prepareStorage();
sharedLogger.info(`Mockgoose ready!`);
}
/*
* Connect to MongoDB.
*/
async __connectToDatabase (connectionString) {
const sharedLogger = this.__dep(`sharedLogger`);
sharedLogger.info(`Connecting to database...`);
await mongoose.connect(connectionString);
sharedLogger.info(`Database ready!`);
}
/*
* Finds a single document that matches the given conditions.
*/
async get (modelName, conditions, options) {
super.get(modelName, conditions, options);
const Model = this.getModel(modelName);
const query = Model.findOne(conditions).lean();
this.__applyQueryOptions(query, options);
return await query.exec() || null;
}
/*
* Finds an array of documents that match the given conditions.
*/
async find (modelName, conditions, options) {
super.find(modelName, conditions, options);
const Model = this.getModel(modelName);
const query = Model.find(conditions).lean();
this.__applyQueryOptions(query, options);
return await query.exec() || [];
}
/*
* Inserts a new document or array of documents into the database. Return value is either a single record or an array
* of records based on what was inserted successfully.
*/
async insert (modelName, properties) {
super.insert(modelName, properties);
const propertiesList = (Array.isArray(properties) ? properties : [ properties ]);
const Model = this.getModel(modelName);
const documents = await Model.insertMany(propertiesList);
const records = documents.map(document => document.toObject());
return (propertiesList.length > 1 ? records : records[0]); // Returned objects must be lean!
}
/*
* Updates an existing document with the given changes. Input can be a document or a document ID.
*/
async update (modelName, input, changes, _options) {
super.update(modelName, input, changes, _options);
const options = extender.defaults({
upsert: false,
useConditions: false,
}, _options);
const Model = this.getModel(modelName);
const documentId = this.__getDocumentId(input);
const conditions = (options.useConditions ? input : { _id: documentId });
// Perform the update operation.
const newDocument = await Model.findOneAndUpdate(conditions, changes, {
new: true,
upsert: options.upsert,
setDefaultsOnInsert: true,
});
if (!newDocument) { throw this.__error(`UPDATE_MISSING_DOCUMENT`, { modelName, documentId }); }
return newDocument.toObject(); // Returned object must be lean!
}
/*
* Deletes an existing document. Input can be a document or a document ID.
*/
async delete (modelName, input) {
super.delete(modelName, input);
const Model = this.getModel(modelName);
const documentId = this.__getDocumentId(input);
// Perform the delete operation.
await Model.findByIdAndRemove(documentId);
}
/*
* Deletes multiple existing documents that match the conditions.
*/
async deleteWhere (modelName, conditions) {
super.deleteWhere(modelName, conditions);
const Model = this.getModel(modelName);
// Perform the delete operation.
await Model.remove(conditions);
}
/*
* Apply options to the query to modify its behaviour.
*/
__applyQueryOptions (query, options = {}) {
if (options.limit) { query.limit(options.limit); }
if (options.skip) { query.skip(options.skip); }
if (options.sort) { query.sort(options.sort); }
if (options.populate) { query.populate(options.populate); }
if (options.fields && options.fields.length) { query.select(options.fields.join(` `)); }
}
/*
* Returns the ID of the document.
*/
__getDocumentId (input) {
switch (typeof input) {
case `string`: return input;
case `object`:
if (input === null) { return null; }
if (mongoose.Types.ObjectId.isValid(input)) { return input; }
if (input._id) { return input._id; }
return null;
default: return null;
}
}
};
|
// eslint-disable-next-line no-unused-vars
class HttpClient{
constructor(){
}
}
|
/**
* Created by chrismorgan on 5/18/15.
*/
var mongoose = require('mongoose');
var locationTypes = "commercial residential".split(" ");
var schema = mongoose.Schema({
companyId: {type: String, required: true },
driverId: {type: String, required: true },
pickUpDate: {type: Date, required: true },
createdTimeStamp: { type: Date, default: Date.now },
editedTimeStamp: { type: Date, required: false},
location: {
latitude: {type: Number, required: true},
longitude: {type: Number, required: true},
address: {type: String, required: true}
},
type: {type: String, required: true},
locationType: { type: String, required: true, enum: locationTypes },
truckId: {type: String, required: true },
spreadSiteId: {type: String },
volume: {type: Number, required: true},
dischargeLocation: {
latitude: {type: Number, required: false},
longitude: {type: Number, required: false}
},
dischargeTimeStamp: { type: Date, required: false }
});
module.exports = mongoose.model('Collection', schema);
|
import React from 'react';
import I18n from '@aaua/i18n';
import {useSelector} from 'react-redux';
import {MainCard, Header} from '@aaua/components/common';
import AutocompleteScreen from '@aaua/components/common/AutocompleteScreen';
import styles from './styles';
const Cities = ({onSelectCity}) => {
const {
citiesBrands: {cities},
} = useSelector(state => state);
const defaultCities = cities.slice(0,4);
return (
<MainCard>
<Header>{I18n.t('insurance_screen.osago.city')}</Header>
<AutocompleteScreen
defaultList={defaultCities}
data={cities}
onSelect={onSelectCity}
textInputPlaceholder={I18n.t(
'insurance_screen.osago.car_city.placeholder',
)}
/>
</MainCard>
);
};
export default Cities;
|
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import Navbar from './Component/Navbar'
import Home from './Component/Home'
import Footer from './Component/Footer'
import Copyright from './Component/Copyright'
function App() {
return (
<div>
<Navbar/>
<Home/>
<Footer/>
<Copyright/>
</div>
);
}
export default App;
|
var reactVueTemplateParser = require('./compiler');
const traverse = require('babel-traverse');
const { SourceMapConsumer } = require('source-map');
function sourceMapAstInPlace(tsMap, babelAst) {
const tsConsumer = new SourceMapConsumer(tsMap);
traverse.default.cheap(babelAst, node => {
if (node.loc) {
const originalStart = tsConsumer.originalPositionFor(node.loc.start);
if (originalStart.line) {
node.loc.start.line = originalStart.line;
node.loc.start.column = originalStart.column;
}
const originalEnd = tsConsumer.originalPositionFor(node.loc.end);
if (originalEnd.line) {
node.loc.end.line = originalEnd.line;
node.loc.end.column = originalEnd.column;
}
}
});
}
function transform({ src, filename, options, upstreamTransformer }) {
if (typeof src === 'object') {
// handle RN >= 0.46
({ src, filename, options } = src);
}
const outputFile = reactVueTemplateParser(src, filename, options);
if (!outputFile.output) {
return upstreamTransformer.transform({
src: outputFile,
filename,
options
});
} else {
// Source Map support
const babelCompileResult = upstreamTransformer.transform({
src: outputFile.output,
filename,
options
});
if (outputFile.mappings) {
sourceMapAstInPlace(outputFile.mappings, babelCompileResult.ast);
}
return babelCompileResult;
}
}
module.exports = transform;
|
/**
* Copyright IBM Corp. 2016, 2021
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import { act } from 'react-dom/test-utils';
import LocaleButton from '../LocaleButton';
import React from 'react';
import ReactDOM from 'react-dom';
jest.mock('@carbon/ibmdotcom-services/lib/services/Locale/Locale', () => ({
getLocale: jest.fn(() => Promise.resolve({ cc: 'us', lc: 'en' })),
getList: jest.fn(() => Promise.resolve({})),
getLangDisplay: jest.fn(() => Promise.resolve()),
setLangDisplay: jest.fn(() => Promise.resolve()),
}));
describe('<LocaleButton />', () => {
let container;
beforeEach(() => {
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
it('renders button and locale modal', () => {
act(() => {
ReactDOM.render(<LocaleButton />, container);
});
const btnContainer = container.querySelector('.bx--locale-btn__container');
expect(btnContainer.querySelectorAll('button.bx--locale-btn')).toHaveLength(
1
);
expect(
btnContainer.querySelectorAll('.bx--locale-modal-container')
).toHaveLength(1);
});
it('opens and closes properly', () => {
act(() => {
ReactDOM.render(<LocaleButton />, container);
});
const btn = container.querySelector('button.bx--locale-btn');
const modal = container.querySelector('.bx--locale-modal-container');
const modalCloseBtn = modal.querySelector('button.bx--modal-close');
// Closed on load
expect(modal.classList.contains('is-visible')).toBe(false);
expect(modal.hasAttribute('open')).toBe(false);
// Open when button is clicked
act(() => {
btn.click();
});
expect(modal.classList.contains('is-visible')).toBe(true);
expect(modal.hasAttribute('open')).toBe(true);
// And closed again
act(() => {
modalCloseBtn.click();
});
expect(modal.classList.contains('is-visible')).toBe(false);
expect(modal.hasAttribute('open')).toBe(false);
});
});
|
'use strict';
module.exports = function(sequelize, DataTypes) {
var Unit = sequelize.define('Unit', {
rkap: DataTypes.FLOAT,
ra: DataTypes.FLOAT,
ri: DataTypes.FLOAT,
prognosa: DataTypes.FLOAT,
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
}
}
});
Unit.associate = function (models) {
Unit.belongsTo(models.Category, { onDelete: 'restrict' });
Unit.belongsTo(models.Revenue, { onDelete: 'restrict' });
};
return Unit;
};
|
// import required dependencies
// const bcrypt = require('bcrypt');
// const jwt = require('jsonwebtoken');
// import required files
const conn = require('../configs/db');
console.log('model'); // where I am
module.exports = {
loginUser: function(data_login) {
return new Promise( function(resolve, reject) {
conn.query('SELECT * FROM user WHERE username = ?',
data_login.username, function(err, result) {
if (!err) {
if (result.length == 0) {
resolve({
status: 400,
error: true,
message: 'Username was not registered',
result: {},
});
} else {
const hash = result[0].password;
const username = result[0].username;
const data = {
'username': username,
'hash': hash,
};
resolve(data);
}
} else {
reject(err);
}
});
});
},
};
|
/*
Peripheral example
runs Bluetooth radio as a Bluetooth 4.0 peripheral with one service.
Service has a single characteristic, which has a single-byte value.
created 16 Apr 2015
by Tom Igoe
*/
var bleno = require('bleno');
var PrimaryService = bleno.PrimaryService; // instantiate PrimaryService
var Characteristic = bleno.Characteristic; // instantiate PrimaryCharacteristic
var name = 'myService'; // peripheral's localName
var data = new Buffer(1); // Buffer for characteristic value
data[0] = 22; // actual value of the characteristic
// define the service's characteristic:
var myCharacteristic = new Characteristic({
uuid: 'A495FF25-C5B1-4B44-B512-1370F02D74DE', // characteristic UUID; chosen randomly
properties: [ 'notify','read' ], // characteristic properties
value: data // characteristic value
});
// define the service:
var myService = new PrimaryService({
uuid: 'A495FF20-C5B1-4B44-B512-1370F02D74DE', // service UUID; chosen randomly
characteristics: [ myCharacteristic] // service characteristic
});
// event handler for Bluetooth state change:
bleno.on('stateChange', function(state) {
console.log('on -> stateChange: ' + state);
if (state === 'poweredOn') {
bleno.startAdvertising(name, [myService.uuid]);
console.log('advertising ' + name);
} else {
bleno.stopAdvertising();
}
});
// event handler for advertising start:
bleno.on('advertisingStart', function(error) {
console.log('Bluetooth on. advertisingStart: ')
if (error) {
console.log('error ' + error);
} else {
// if advertising start succeeded, start the services
console.log('success');
bleno.setServices([myService], function(serviceError){
console.log('Starting services: ')
if (serviceError) {
console.log('error ' + serviceError);
} else {
console.log('service set.');
}
});
}
});
|
'use strict';
describe('Thermostat', () => {
let thermostat;
beforeEach(() => {
thermostat = new Thermostat();
});
it('starts at 20 degrees', () => {
expect(thermostat.getCurrentTemperature()).toEqual(20);
});
it('increases temperature', () => {
thermostat.up();
expect(thermostat.getCurrentTemperature()).toEqual(21)
});
it('decreases temperature', () => {
thermostat.down();
expect(thermostat.getCurrentTemperature()).toEqual(19)
});
it('has a minimum temperature of 10 degrees', () => {
for(let i = 0; i < 11; i++) {
thermostat.down();
}
expect(thermostat.getCurrentTemperature()).toEqual(10);
});
it('has Power Saving Mode set to default', () => {
expect(thermostat.isPowerSavingModeOn()).toBe(true);
});
it('can turn PSM off', () => {
thermostat.turnPowerSavingModeOff();
expect(thermostat.isPowerSavingModeOn()).toBe(false);
});
it('can turn PSM back on', () => {
thermostat.turnPowerSavingModeOff();
expect(thermostat.isPowerSavingModeOn()).toBe(false);
thermostat.turnPowerSavingModeOn();
expect(thermostat.isPowerSavingModeOn()).toBe(true);
});
describe('when power saving mode is on', () => {
it('has a maximum temperature of 25 degrees', () => {
for (let i = 0; i < 6; i++) {
thermostat.up();
}
expect(thermostat.getCurrentTemperature()).toEqual(25);
});
});
describe('when power saving mode is off', () => {
it('has a maximum temperature of 32 degress', () => {
thermostat.turnPowerSavingModeOff();
for (let i = 0; i < 13; i++) {
thermostat.up();
}
expect(thermostat.getCurrentTemperature()).toEqual(32);
})
});
it('can be reset to default temperature', () => {
for (let i = 0; i < 6; i++) {
thermostat.up();
}
thermostat.resetTemperature();
expect(thermostat.getCurrentTemperature()).toEqual(20);
});
describe('displaying energy usage', () => {
describe('when the temperature is below 18 degrees', () => {
it('returns low-usage', () => {
for (let i = 0; i < 3; i++) {
thermostat.down();
}
expect(thermostat.energyUsage()).toEqual('low-usage');
});
});
describe('when the temperature is between 18 and 25', () => {
it('returns medium-usage', () => {
expect(thermostat.energyUsage()).toEqual('medium-usage');
});
});
describe('when the temperature is anything else', () => {
it('returns high-usage', () => {
thermostat.powerSavingMode = false;
for (let i = 0; i < 6; i++) {
thermostat.up();
}
expect(thermostat.energyUsage()).toEqual('high-usage');
});
});
});
});
|
const mysql = require("mysql");
module.exports = function(app, connection) {
app.get("/", function(req, res) {
connection.query("SELECT * FROM about", function(err, results) {
err ? res.send(err) : res.send(JSON.stringify(results));
});
});
};
|
const express = require("express");
const router = express.Router();
const passport = require("passport");
require("./google-setup.js");
router.get(
"/login",
passport.authenticate("google", { scope: ["profile", "email"] })
);
router.get("/fail", async (req, res) => {
res.send("Auth Fail.");
});
router.get("/success", async (req, res) => {
res.send("Auth Success.");
});
router.get(
"/",
passport.authenticate("google", (err, prof) => {
// User-Data in prof.
})
);
module.exports = router;
|
(function(){
var scrollLink = document.querySelector('.home-top__scroll-link'),
block = document.querySelector('#portfolio');
if(scrollLink) {
var href = scrollLink.getAttribute('href');
scrollLink.addEventListener('click', function (e) {
e.preventDefault();
history.pushState(null, null, href);
animateScroll(block, 500, 'linear');
});
window.addEventListener("scroll", function(){
window.requestAnimationFrame(function(){
if(window.pageYOffset < block.getBoundingClientRect().top && APPLICA.scrollTop < window.pageYOffset) {
animateScroll(block, 500, 'linear');
}
APPLICA.scrollTop = window.pageYOffset;
});
});
}
})();
|
const balancePoint = (array) => {
const leftSum = [];
const rightSum = [];
const difference = [];
let i, j;
let l = 0; let r = 0;
for(i = 0; i < array.length; i++) {
j = array.length - i - 1;
l += array[i];
r += array[j];
leftSum[i] = l;
rightSum[j] = r;
};
for(i = 1; i < array.length; i++) {
difference.push(Math.abs(leftSum[i - 1] - rightSum[i]));
}
console.log(leftSum, rightSum, difference);
return Math.min(...difference);
};
module.exports = balancePoint;
|
import { SET_USERNAME } from '../actions/profile'
function login (state = {}, action) {
switch (action.type) {
case SET_USERNAME:
return {...state, username: action.username};
default:
return {...state};
}
}
export default login;
|
export const ProjectData =
[
{
name: "Macroman",
description: "An easy way for users to track calorie consumption by the use of macronutirents.",
link: "https://github.com/Cliffcoding/MacroMan",
style: "project--1 ",
techUsed: "jQuery, JavaScript, Firebase, Materialize, Git, GitHub, HTML5, CSS3"
},
{
name: "Jello",
description: "Trello clone, very clever name. A visulaization on the organization of a project.",
link: "https://github.com/JAMMS-g51",
style: "project--2 ",
techUsed: "PostgreSQL, Knex.js, Express, JWT, Firebase, Git, Github, Node.js, jQuery, JavaScript, HTML5, CSS3"
},
{
name: "Taparoo",
description: "A beer inventory management system for the building administrators. The Admin can add and remove beers from the inventory depending on orders. A portable display is set next to the keg to allow the users to see what is currently on tap.",
link: "https://github.com/taparoo",
style: "project--3 ",
techUsed: "AngularJS, Socket.io, Express, PostgreSQL, Knex.js, Express, Node.js, Bcrypt, JWT, Git, Github"
},
{
name: "MirrorMirror",
description: "A mirror with a built in display that renders a page that gives the illusion that the mirror has the time and weather.",
link: "https://github.com/Cliffcoding/Capstone-Display",
style: "project--4 ",
techUsed: "React, Resin.io, Express, Passport, MongoDB, Mongoose, Git, Github, Node.js, Raspberry Pi, Electron"
}
]
|
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope, $ionicModal, $timeout, $location) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//$scope.$on('$ionicView.enter', function(e) {
//});
// Form data for the login modal
$scope.loginData = {};
$scope.categoria_elegida={};
$scope.sub_categorias=['Cámaras','Aires Acondicionados', 'Todos'];
$scope.rubro="";
$scope.buscar=function(){
$location.path("/app/search");
};
$scope.filtrar=function(){
$location.path("/app/playlists/Búsqueda");
};
$scope.goToLogin= function (){
};
// Create the login modal that we will use later
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
// Triggered in the login modal to close it
$scope.closeLogin = function() {
$scope.modal.hide();
};
// Open the login modal
$scope.login = function() {
$scope.modal.show();
};
$scope.categorias = [
{ title: 'Instalaciones (Cámaras, AA, etc)', id: 1, sub_categorias: ['Cámaras','Aires Acondicionados', 'Todos']},
{ title: 'Electrónica', id: 2 , sub_categorias:['TV','Radio','Todos']},
{ title: 'Albañilería', id: 3 ,sub_categorias: ['Todos']},
{ title: 'Plomería', id: 4 ,sub_categorias: ['Todos']},
{ title: 'Informática', id: 5 ,sub_categorias: ['Todos']},
{ title: 'Enseñanza particular', id: 6 ,sub_categorias: ['Todos']},
{ title: 'Electricidad', id: 7,sub_categorias: ['Todos']}
];
// Perform the login action when the user submits the login form
$scope.doLogin = function() {
console.log('Doing login', $scope.loginData);
// Simulate a login delay. Remove this and replace with your login
// code if using a login system
$timeout(function() {
$scope.closeLogin();
}, 1000);
};
})
.controller('PlaylistsCtrl', function($scope) {
$scope.playlists = [
{ title: 'Instalaciones (Cámaras, AA, etc)', id: 1 },
{ title: 'Electrónica', id: 2 },
{ title: 'Albañilería', id: 3 },
{ title: 'Plomería', id: 4 },
{ title: 'Informática', id: 5 },
{ title: 'Enseñanza particular', id: 6 },
{ title: 'Electrónica', id: 7}
];
})
.controller('PlaylistCtrl', function($scope, $stateParams) {
$scope.rubro=$stateParams.playlistId;
if($scope.rubro==='Instalaciones (Cámaras, AA, etc)'){
$scope.destacados=[
{
nombre: 'Christian Flecher',
id: 1,
rubro: "Aires Acondicionados",
contacto: 123456,
zona: "San Lorenzo",
calificacion: 5
},
{nombre: 'Edgar Alvarenga', id: 2, rubro: "Aires Acondicionados",contacto: 123456, zona: "Asunción", calificacion: 5},
{nombre: 'Edgar Santacruz', id: 3, rubro: "Cámaras - CCTV", contacto: 123456, zona: "Central", calificacion: 4},
{
nombre: 'Agustín Rivarola',
id: 4,
rubro: "Cámaras - CCTV",
contacto: 123456,
zona: "Lambaré",
calificacion: 4.5
},
{
nombre: 'Manzur Tecnologías',
id: 5,
rubro:"Cámaras - CCTV",
contacto: 123456,
zona: "Asunción",
calificacion: 1
}];
$scope.trabajadores = [
{
nombre: 'Juan Gonzalez',
id: 1,
rubro: "Aires Acondicionados",
contacto: 123456,
zona: "San Lorenzo",
calificacion: 5
},
{nombre: 'Pedro Fernandez', id: 2, rubro: "Cámaras", contacto: 123456, zona: "San Lorenzo", calificacion: 5},
{nombre: 'Pedro Fernandez', id: 3, rubro: "Cámaras", contacto: 123456, zona: "San Lorenzo", calificacion: 4},
{
nombre: 'Pedro Fernandez',
id: 4,
rubro: "Aires Acondicionados",
contacto: 123456,
zona: "San Lorenzo",
calificacion: 4.5
},
{
nombre: 'Pedro Fernandez',
id: 5,
rubro: "Aires Acondicionados",
contacto: 123456,
zona: "San Lorenzo",
calificacion: 1
},
{
nombre: 'Pedro Fernandez',
id: 6,
rubro: "Aires Acondicionados",
contacto: 123456,
zona: "San Lorenzo",
calificacion: 3
}
];
}else if($scope.rubro==='Búsqueda'){
$scope.destacados=[
{
nombre: 'Christian Flecher',
id: 1,
rubro: "Aires Acondicionados",
contacto: 123456,
zona: "San Lorenzo",
calificacion: 5
},
{nombre: 'Edgar Alvarenga', id: 2, rubro: "Aires Acondicionados",contacto: 123456, zona: "Asunción", calificacion: 5}];
$scope.trabajadores=[{
nombre: 'Pedro Fernandez',
id: 4,
rubro: "Aires Acondicionados",
contacto: 123456,
zona: "San Lorenzo",
calificacion: 4.5
},
{
nombre: 'Pedro Fernandez',
id: 5,
rubro: "Aires Acondicionados",
contacto: 123456,
zona: "San Lorenzo",
calificacion: 1
},
{
nombre: 'Pedro Fernandez',
id: 6,
rubro: "Aires Acondicionados",
contacto: 123456,
zona: "San Lorenzo",
calificacion: 3
}]
}
else {
$scope.trabajadores = [
{
nombre: 'Juan Gonzalez',
id: 1,
rubro: "N/A",
contacto: 123456,
zona: "San Lorenzo",
calificacion: 5
},
{nombre: 'Pedro Fernandez', id: 2, rubro: "N/A",contacto: 123456, zona: "San Lorenzo", calificacion: 5},
{nombre: 'Pedro Fernandez', id: 3, rubro: "N/A", contacto: 123456, zona: "San Lorenzo", calificacion: 4},
{
nombre: 'Pedro Fernandez',
id: 4,
rubro: "N/A",
contacto: 123456,
zona: "San Lorenzo",
calificacion: 4.5
},
{
nombre: 'Pedro Fernandez',
id: 5,
rubro:"N/A",
contacto: 123456,
zona: "San Lorenzo",
calificacion: 1
},
{
nombre: 'Pedro Fernandez',
id: 6,
rubro: "N/A",
contacto: 123456,
zona: "San Lorenzo",
calificacion: 3
}
];
}
})
.controller('PerfilCtrl', function($scope, $stateParams, $ionicPopup) {
$scope.estrellas=["ion-android-star-outline", "ion-android-star-outline","ion-android-star-outline",
"ion-android-star-outline","ion-android-star-outline"];
$scope.favorito='ion-ios-heart-outline';
$scope.fav = function (){
if($scope.favorito=='ion-ios-heart-outline'){
$scope.favorito='ion-ios-heart';
}else{
$scope.favorito='ion-ios-heart-outline';
}
};
$scope.calificar=function (i){
angular.forEach($scope.estrellas, function(value, key) {
if (key<=i){
$scope.estrellas[key]="ion-android-star";
}else {
$scope.estrellas[key]= "ion-android-star-outline";
}
});
};
if($stateParams.rubro==='Instalaciones (Cámaras, AA, etc)'){
$scope.trabajadores= [
{ nombre: 'Christian Flecher',
id: 1,
contacto: "0982204947",
zona: "San Lorenzo",
descripcion:"Servicio Técnico de Aires Acondicionados split de 9000, 12000, 18000BTU",
tarifas:[
{nombre: "Instalacion",
tarifa: 180000},
{nombre: "Mantenimiento",
tarifa: 100000},
{nombre: "Carga de gas",
tarifa: 150000}],
comentarios:[
{id:1,nombre:"Anónimo",
contenido: "Muy buen servicio."}, {id:2,
nombre:"Anónimo", contenido:
"Puntualidad excelente."}] },
{ nombre: 'Edgar Alvarenga', id: 2, contacto: "0982201338" , zona: "Asunción", descripcion:"Instalación, mantenimiento y " +
"reparación con garantía de Aires Acondicionados. Trabajos los feriados y domingos.", tarifas:[
{nombre: "Instalación", tarifa: 150000},
{nombre: "Instalación con soporte", tarifa: 200000},
{nombre: "Mantenimiento", tarifa: 150000}],
comentarios:[]},
{ nombre: 'Edgar Santacruz', id: 3, contacto: "https://www.facebook.com/inkservice", zona: "Central",
descripcion:"Cámaras de seguridad en HD al mejor precio, solo calidad, instalación garantizada. Soporte tecnico de inmediato." +
"EQUIPO 1 instalado: 1 DVR de 4 canales Power pack, 4 CÁMARAS Visión Nocturnas 650 TVL, 1 HDD 500 GB, " +
"1 FUENTE 12VOL 5 amp., 16 MTS. DE CABLES por cámaras." +
"EQUIPO 2 instalado: DVR Network kadimay para 4 salidas, 4 cámaras dia/noche 1200 tvl, HDD 1 TB," +
"fuente eléctrica 12v/10A, cables externos e internos ", tarifas:[
{nombre: "Equipo 1", tarifa: "A consultar"},
{nombre: "Equipo 2", tarifa: "A consultar"}] ,
comentarios:[] },
{ nombre: 'Agustín Rivarola', id: 4, contacto: '0991188772', zona: "Lambaré", descripcion:"Instalación de cámaras de seguridad." +
"Incluye: Cámaras con Visión Nocturna (Interior/Exterior), DVR 4 Canales, Disco Duro de 500GB, " +
"Fuente de alimentación Centralizada para las cámaras, Cableado hasta 100mts, Configuración para ver desde la Web a través cualquier smartphone",
tarifas:[{nombre: "4 Cámaras",tarifa:2600000},
{nombre:"3 Cámaras", tarifa:2200000},
{nombre: "2 Cámaras", tarifa:1900000},
{nombre: "1 Cámaras", tarifa:1600000}],
comentarios:[] },
{ nombre: 'Manzur Tecnologías', id: 5, contacto: "0981966450", zona: "Asunción" , descripcion:"Venta e instalación de 4 cámaras" +
"HD con grabador de 4 canales, HDD de 1TB", tarifas:[{nombre: "Instalacion de 4 cámaras", tarifa: 2800000}],
comentarios:[] }
]
}else{
$scope.trabajadores= [
{ nombre: 'Juan Gonzalez', id: 1, contacto: 123456, zona: "San Lorenzo", descripcion:"Profesional con titulo del SNPP" +
"y 15 años de trabajo con instalaciones domeesticas", tarifas:[{nombre: "Instalacion de fluorescentes", tarifa: 500000}],
comentarios:[{id:1,nombre:"Anónimo", contenido: "Muy buen servicio."}, {id:2,nombre:"Anónimo", contenido: "Puntualidad excelente."}] },
{ nombre: 'Pedro Fernandez', id: 2, contacto: 123456, zona: "San Lorenzo", descripcion:"Profesional con titulo del SNPP" +
"y 15 años de trabajo con instalaciones domeesticas", tarifas:[{nombre: "Instalacion de fluorescentes", tarifa: 500000}],
comentarios:[]},
{ nombre: 'Pedro Fernandez', id: 3, contacto: 123456, zona: "San Lorenzo", descripcion:"Profesional con titulo del SNPP" +
"y 15 años de trabajo con instalaciones domeesticas", tarifas:[{nombre: "Instalacion de fluorescentes", tarifa: 500000}] ,
comentarios:[] },
{ nombre: 'Pedro Fernandez', id: 4, contacto: 123456, zona: "San Lorenzo", descripcion:"Profesional con titulo del SNPP" +
"y 15 años de trabajo con instalaciones domeesticas", tarifas:[{nombre: "Instalacion de fluorescentes", tarifa: 500000}],
comentarios:[] },
{ nombre: 'Pedro Fernandez', id: 5, contacto: 123456, zona: "San Lorenzo" , descripcion:"Profesional con titulo del SNPP" +
"y 15 años de trabajo con instalaciones domeesticas", tarifas:[{nombre: "Instalacion de fluorescentes", tarifa: 500000}],
comentarios:[] },
{ nombre: 'Pedro Fernandez', id: 6, contacto: 123456, zona: "San Lorenzo", descripcion:"Profesional con titulo del SNPP" +
"y 15 años de trabajo con instalaciones domesticas", tarifas:[{nombre: "Instalacion de fluorescentes", tarifa: 500000}],
comentarios:[] }
];}
$scope.trabajador_actual=$scope.trabajadores[$stateParams.trabajadorId-1];
console.log($scope.trabajador_actual);
$scope.abrirModal=function () {
$scope.data = {};
// An elaborate, custom popup
var myPopup = $ionicPopup.show({
template: '<div class="list">'+
'<label class="item item-input">'+
'<input type="text" placeholder="Nombre" style="font-size: smaller;" ng-model="data.nombre">'+
'</label>'+
'<label class="item item-input">'+
'<textarea placeholder="Por favor, comente su experiencia" style="font-size: smaller;" ng-model="data.contenido"></textarea>'+
'</label>'+
'</div>',
title: 'Comentario',
scope: $scope,
buttons: [
{ text: 'Cancelar' },
{
text: '<b>Comentar</b>',
type: 'button-positive',
onTap: function(e) {
if (!$scope.data.nombre) {
$scope.data.nombre='Anónimo';
}
if(!$scope.data.contenido){
alert("Introduzca un comentario");
e.preventDefault();
}
$scope.data.id=$scope.trabajador_actual.comentarios.length+1;
$scope.trabajador_actual.comentarios.unshift($scope.data);
return $scope.data;
}
}
]
});
myPopup.then(function(res) {
console.log('Tapped!', res);
});
};
});
|
import axios from "axios";
import React from "react";
import PropTypes from "prop-types";
import { FaBed, FaStar } from "react-icons/fa";
import Spinner from "./Spinner";
import ErrorMessage from "./ErrorMessage";
class HotelPage extends React.Component {
constructor(props) {
super(props);
this.state = { hotel: null };
}
componentDidMount() {
this.fetchHostel();
}
async fetchHostel() {
const { match } = this.props;
const { id } = match.params;
try {
const response = await axios.get(`/api/hotels/${id}/`);
const { data } = response;
this.setState({ hotel: data });
} catch (error) {
this.setState({ error });
}
}
renderStars() {
const { hotel } = this.state;
const { stars } = hotel;
return [...new Array(5).keys()].map(star => (
<FaStar key={star} color={star < stars ? "#FBC02D" : undefined} />
));
}
render() {
const { error, hotel } = this.state;
if (!hotel) return <Spinner />;
if (error) return <ErrorMessage />;
const { name, pricePerNight, availableBeds } = hotel;
return (
<div className="jumbotron">
<h1 className="display-4 mb-4">{name}</h1>
<h3 className="card-text text-info">
{pricePerNight} BGN
<small className="text-muted">/ night</small>
</h3>
<hr />
<div className="d-flex justify-content-between">
<h3>
{availableBeds} <FaBed />
</h3>
<h3>{this.renderStars()}</h3>
</div>
</div>
);
}
}
HotelPage.propTypes = {
match: PropTypes.objectOf(PropTypes.any).isRequired,
};
export default HotelPage;
|
import React from 'react'
import './scoreList.css'
import { withRouter } from 'react-router-dom'
import myTest from 'api/test/test'
import myTopic from 'api/topic/topic'
import myTime from 'utils/time'
import { PullToRefresh, ListView } from 'antd-mobile';
import { connect } from 'react-redux'
import MyTime from 'utils/time'
import NavBar from 'components/navBar/navBar'
import ReactPlaceholder from 'react-placeholder'
import "react-placeholder/lib/reactPlaceholder.css"
import RightContent from './rightContent/rightContent'
const awesomePlaceholder = (
<div></div>
);
class ScoreList extends React.Component {
constructor(props) {
super(props);
const dataSource = new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
});
this.state = {
data: [],
dataSource,
refreshing: true,
isLoading: true,
myScore: {
scSc: "无",
scTime: "无",
no: "无"
},
totalScore: 0,
ready: false
};
}
componentDidMount() {
this.init()
}
componentWillUnmount() {
this.setState = (state, callback) => {
return;
};
}
// 下拉刷新
onRefresh = () => {
this.setState({ refreshing: true, isLoading: true });
this.init()
};
// 到达底部
onEndReached = () => {
}
init() {
this.getData(this.props.testInfo.tsId)
// 计算总分
myTopic.getTopicList(this.props.testInfo.qbId).then(res => {
let count = 0;
for (let sc in res.data.items) {
count += res.data.items[sc].tpScore
}
this.setState({
totalScore: count,
ready: true
})
})
}
// 获取成绩列表数据
getData(id) {
myTest.getTestScoreList(id).then(res => {
// 如果没有数据
if (res.data.items.length === 0) {
return this.setState({
refreshing: false,
isLoading: false,
})
}
// 设置数据
this.setState({
data: [
res.data.items,
],
dataSource: this.state.dataSource.cloneWithRows(res.data.items),
refreshing: false,
isLoading: false,
})
// 设置个人数据
let no = res.data.items.findIndex((v) => v.stId + "" === this.props.userInfo.stId) + 1 // 排名
let myAskData = res.data.items.filter((v) => v.stId + "" === this.props.userInfo.stId) // 个人答题数据
// 如果没有个人数据
if (myAskData.length <= 0) return
// 如果有个人数据
this.setState({
myScore: {
...myAskData[0],
no
},
})
})
}
// 跳转个人分析页面
goto_Analyse() {
this.props.history.push("analyse")
}
render() {
// 渲染内容
const row = (rowData, sectionID, rowID) => {
let No = 1 + parseInt(rowID)
let time = myTime(rowData.scTime)
let sort = null
if (No === 1) {
sort = <img width="20px" alt="" src={"https://pengguodon-guli-file.oss-cn-guangzhou.aliyuncs.com/schoolMobile/%E9%87%91%E7%89%8C.png"} />
} else
if (No === 2) {
sort = <img width="20px" alt="" src={"https://pengguodon-guli-file.oss-cn-guangzhou.aliyuncs.com/schoolMobile/%E9%93%B6%E7%89%8C.png"} />
} else
if (No === 3) {
sort = <img width="20px" alt="" src={"https://pengguodon-guli-file.oss-cn-guangzhou.aliyuncs.com/schoolMobile/%E9%93%9C%E7%89%8C.png"} />
} else {
sort = No
}
return (
<div key={rowID}
style={{
padding: '15px 15px',
backgroundColor: 'white',
fontSize: '.8rem'
}}
>
<div className="ranking">
<span>
{
sort
}
</span><span>{rowData.stName}</span><span>{rowData.scSc}</span><span>{time}</span>
</div>
</div>
);
};
return (
<div className='scoreList'>
<NavBar title="成绩页面" back={true} url="/course/index/activity" rightContent={RightContent} />
<ReactPlaceholder customPlaceholder={awesomePlaceholder} ready={this.state.ready}>
<div className="topInfo">
<div className="content_top"><div className="top_center">"{this.props.testInfo.tsName}"</div></div>
<div className="message">
<span className="ranking">排名</span>
<span className="score">{this.state.myScore.no}</span>
</div>
<div className="student_score">
<span>总分:{this.state.totalScore} | 得分: {this.state.myScore.scSc} | 用时: {MyTime(this.state.myScore.scTime)}</span>
</div>
{
this.state.myScore.scSc === "无" ? null : <div className="result" onClick={() => { this.goto_Analyse() }}>查看个人结果解析</div>
}
</div>
<div className="title clearfix">
<span>排名</span><span>个人信息</span><span>得分</span><span>用时</span>
</div>
<div className="list">
<ListView
// renderHeader={() => {
// return (
// <div className="ranking">
// <span>排名</span><span>个人信息</span><span>得分</span><span>用时</span>
// </div>
// )
// }
// }
key={'1'}
ref={el => this.lv = el}
dataSource={this.state.dataSource}
renderRow={row}
style={{
height: "100%",
}}
// 下拉刷新
pullToRefresh={<PullToRefresh
refreshing={this.state.refreshing}
onRefresh={this.onRefresh}
/>}
// 当所有的数据都已经渲染过,并且列表被滚动到距离最底部不足onEndReachedThreshold个像素的距离时调用
// onEndReachedThreshold:调用onEndReached之前的临界值,单位是像素
onEndReached={this.onEndReached}
pageSize={5}
/>
</div>
</ReactPlaceholder>
</div >
)
}
}
const mapStateToProps = state => {
return {
userInfo: state.userInfo,
testInfo: state.testInfo
}
}
export default withRouter(connect(mapStateToProps)(ScoreList))
|
'use strict';
const Playlists = function() {
const root = document.querySelector('.playlist');
const playlistRoot = root.querySelector('ul');
const render = function(data) {
playlistRoot.innerHTML = "";
data.forEach(function(element) {
let li = document.createElement('li')
li.textContent = element;
playlistRoot.appendChild(li);
});
addEvents();
}
const showCreateDialog = function(data) {
ajax('POST', '/playlists', data, create);
ajax('GET', '/playlists', null, render);
};
let buttonToAddName = document.querySelector('button');
buttonToAddName.addEventListener('click', function() {
create()
});
const create = function() {
let addTitleName = document.querySelector('input');
let newPost = {name: addTitleName.value}
if (addTitleName.value !== '') {
ajax('POST', '/playlists', newPost, render);
};
};
// const deleted = function() {
// response.forEach(function(element) {
// if (element.system === 0) {
// let li = root.getElementsByTagName('li');
// li.forEach(function(e){
// if ()
// e.removeChild(li);
// })
// };
// console.log(response);
// });
// };
const highlight = function(index) {
let playList = root.querySelectorAll('li');
playList.forEach(function(element, i) {
if (index === i) {
element.style.backgroundColor = 'lightblue';
} else if (i % 2 === 0) {
element.style.backgroundColor = 'white';
} else {
element.style.backgroundColor = 'lightgray';
};
});
};
const addEvents = function() {
let playList = root.querySelectorAll('li');
playList.forEach(function(element, index) {
element.addEventListener('click', function(i) {
highlight(index);
});
});
};
const clickHandler = function() {}
const load = function() {
ajax('GET', '/playlists', null, render);
}
return {
render: render,
highlight: highlight,
create: create,
load: load,
showCreateDialog: showCreateDialog,
}
}
let playlistModule = Playlists();
// playlistModule.deleted();
playlistModule.highlight();
ajax('GET', '/playlists', null, playlistModule.render)
playlistModule.create()
playlistModule.showCreateDialog()
|
var mongoose = require( 'mongoose' );
var Main = require('../models/main');
var config = require('../config');
exports.savemain = function(req, res, next){
const uid = req.params.id;
const ticketid = req.body.ticketid;
const dt = req.body.mdate;
const tool = req.body.mtool;
const desc = req.body.mdesc;
const tech = req.body.mtech;
const rsdate = req.body.rsdate;
const rcom = req.body.rcom;
const fixdate = req.body.fixdate;
const rtech = req.body.rtech;
const mainid = req.body.mainid;
if (mainid) {
//Edit maintenance
Main.findById(mainid).exec(function(err, main){
if(err){ res.status(400).json({ success: false, message: 'Error processing request '+ err }); }
if(main) {
main.ticketid = ticketid;
main.maindate = dt;
main.maintool = tool;
main.maindesc = desc;
main.maintech = tech;
main.rsdate = rsdate;
main.rcom = rcom;
main.fixdate = fixdate;
main.rtech = rtech;
}
main.save(function(err) {
if(err){ res.status(400).json({ success: false, message: 'Error processing request '+ err }); }
res.status(201).json({
success: true,
message: 'Maintenance updated successfully'
});
});
});
}else{
Main.findOne({ ticketid: ticketid }, function(err, existingMain) {
if(err){ res.status(400).json({ success: false, message:'Error processing request '+ err}); }
// If user is not unique, return error
if (existingMain) {
return res.status(201).json({
success: false,
message: 'Ticket id already exists.'
});
}
// If no error, create account
let oMain = new Main({
userid: uid,
ticketid: ticketid,
maindate : dt,
maintool : tool,
maindesc : desc,
maintech : tech,
rsdate : rsdate,
rcom : rcom,
fixdate : fixdate,
rtech : rtech,
});
oMain.save(function(err, oMain) {
if(err){ res.status(400).json({ success: false, message:'Error processing request '+ err}); }
res.status(201).json({
success: true,
message: 'Maintenance saved successfully'
});
});
});
}
}
exports.delmain = function(req, res, next) {
Main.remove({_id: req.params.id}, function(err){
if(err){ res.status(400).json({ success: false, message: 'Error processing request '+ err }); }
res.status(201).json({
success: true,
message: 'Maintenance removed successfully'
});
});
}
exports.getmain = function(req, res, next){
Main.find({_id:req.params.id}).exec(function(err, main){
if(err){ res.status(400).json({ success: false, message:'Error processing request '+ err });
}
res.status(201).json({
success: true,
data: main
});
});
}
exports.maintotal = function(req, res, next){
const uid = req.params.id || req.param('uname');
const rptype = req.body.report || req.param('report');
const from_dt = req.body.startdt || req.param('startdt');
const to_dt = req.body.enddt || req.param('enddt');
const fromdt = new Date(from_dt);
const todt = new Date(to_dt);
let match = {};
if(rptype === 'opt1'){
let oDt = new Date();
let month = oDt.getUTCMonth() + 1; //months from 1-12
let year = oDt.getUTCFullYear();
let fdt = new Date(year + "/" + month + "/1");
let tdt = new Date(year + "/" + month + "/31");
match = { "$match": {userid:uid, maindate:{$gte: fdt, $lte: tdt}} };
} else if (rptype === 'opt2'){
match = { "$match": { userid:uid, maindate:{$gte: fromdt, $lte: todt}} };
} else {
match = { "$match": { userid:uid } };
}
}
exports.mainreport = function(req, res, next){
const uid = req.params.id || req.query.uname;
const rptype = req.body.report || req.query.report;
const from_dt = req.body.startdt || req.query.startdt;
const to_dt = req.body.enddt || req.query.enddt;
const fromdt = new Date(from_dt);
const todt = new Date(to_dt);
let limit = parseInt(req.query.limit);
let page = parseInt(req.body.page || req.query.page);
let sortby = req.body.sortby || req.query.sortby;
let query = {};
if(!limit || limit < 1) {
limit = 10;
}
if(!page || page < 1) {
page = 1;
}
if(!sortby) {
sortby = 'maindate';
}
var offset = (page - 1) * limit;
if (!uid || !rptype) {
return res.status(422).send({ error: 'Posted data is not correct or incompleted.'});
}else if(rptype === 'opt2' && !fromdt && !todt){
return res.status(422).send({ error: 'From or To date missing.'});
}else if(fromdt > todt){
return res.status(422).send({ error: 'From date cannot be greater than To date.'});
}else{
if(rptype === 'opt1'){
// returns records for the current month
let oDt = new Date();
let month = oDt.getUTCMonth() + 1; //months from 1-12
let year = oDt.getUTCFullYear();
let fdt = new Date(year + "/" + month + "/1");
let tdt = new Date(year + "/" + month + "/31");
query = { userid:uid, maindate:{$gte: fdt, $lte: tdt} };
Main.count(query, function(err, count){
if(count > offset){
offset = 0;
}
});
} else if (rptype === 'opt2'){
// return records within given date range
query = { userid:uid, maindate:{$gte: fromdt, $lte: todt} };
Main.count(query, function(err, count){
if(count > offset){
offset = 0;
}
});
} else {
// returns all maintenance records for the user
query = { userid:uid };
Main.count(query, function(err, count){
if(count > offset){
offset = 0;
}
});
}
var options = {
select: 'maindate maintool ticketid maindesc maintech',
sort: sortby,
offset: offset,
limit: limit
}
Main.paginate(query, options).then(function(result) {
res.status(201).json({
success: true,
data: result
});
});
}
}
/*exports.waitingtime = function(req, res, next){
var start = maindate(),
end = rsdate(),
diff = 0,
days = 100 * 60 * 60 * 24;
}
*/
|
import React from 'react';
import PropTypes from 'prop-types';
import { TextInput, StyleSheet, TouchableOpacity } from 'react-native';
import Block from '../Block';
import Typography from '../Typography';
import { colors, fontFamily, sizes } from '../../../constants/theme';
const Input = (props) => {
const { label, rightLabel, style, ...inputProps } = props;
const inputStyles = [styles.baseInput, style];
return (
<Block relative w100>
<Block row justify='space-between' align='center'>
<Typography color={colors.gray} size={15}>
{label}
</Typography>
{rightLabel ? (
<TouchableOpacity>
<Typography size={15} color={colors.mediumBlack}>
{rightLabel}
</Typography>
</TouchableOpacity>
) : (
<></>
)}
</Block>
<TextInput autoCapitalize='none' style={inputStyles} {...inputProps} />
</Block>
);
};
const styles = StyleSheet.create({
baseInput: {
fontFamily: fontFamily.regular,
color: colors.black,
fontSize: 18,
paddingBottom: 5,
borderBottomWidth: 1,
borderBottomColor: colors.gray,
marginBottom: 20,
},
});
Input.defaultProps = {
label: 'Label',
rightLabel: '',
};
Input.propTypes = {
label: PropTypes.string,
rightLabel: PropTypes.string,
};
export default Input;
|
import React from 'react';
import styles from './Canvas.module.css';
import {connect} from "react-redux";
import {changeHeight, changeWidth} from '../redux/bannerSize/banner.actions'
class Canvas extends React.Component {
constructor(props) {
super(props);
this.canvas = React.createRef();
this.isMoved = false;
this.x = 0;
this.y = 0;
}
state = {
sizeValue: 'px',
scale: 1,
x: 0,
y: 0
};
transformScale = () => {
return {
transform: 'scale(' + this.state.scale + ')'
}
};
transformPosition = () => {
return {
transform: 'translateX(' + this.state.x * (1 / this.state.scale) + 'px) translateY(' + this.state.y * (1 / this.state.scale) + 'px)'
}
};
getBannerSizes = () => {
const width = this.props.bannerSize.width;
const height = this.props.bannerSize.height;
return {
width: width + this.state.sizeValue,
height: height + this.state.sizeValue
}
};
handleWheel = (e) => {
const delta = e.deltaY || e.detail;
if (delta > 0) {
if (this.state.scale >= 2) {
this.setState({
scale: 2
})
} else {
this.setState({
scale: this.state.scale + 0.05
});
}
} else {
if (this.state.scale <= 1) {
this.setState({
scale: 1
})
} else {
this.setState({
scale: this.state.scale - 0.05
});
}
}
};
handleMouseDown = (e) => {
e.persist();
this.isMoved = true;
this.x = e.clientX - this.x;
this.y = e.clientY - this.y;
console.log('START', this.x, this.y)
};
handleMouseMove = (e) => {
e.persist();
console.log('this', this.x, this.y);
console.log('client',e.clientX,e.clientY);
const width = this.canvas.current.offsetWidth;
const height = this.canvas.current.offsetHeight;
if (this.isMoved && (e.clientX > 100 && e.clientX < width - 100 && e.clientY > 100 && e.clientY < height - 100)) {
this.setState({
x: e.clientX - this.x,
y: e.clientY - this.y
});
}
};
handleMouseUp = (e) => {
e.persist();
this.isMoved = false;
this.x = e.clientX - this.x;
this.y = e.clientY - this.y;
console.log('END', this.x, this.y);
};
addBackground = (obj) => {
if (obj.type === 'fill') {
return {
background: obj.resource,
width: '100%',
height: '100%',
}
}
if (obj.type === 'image') {
return {
background: obj.resource,
backgroundSize: 'contain',
width: '100%',
height: '100%',
}
}
};
render() {
return (
<>
<div className={styles.canvas}
onWheel={(e) => this.handleWheel(e)}
style={this.transformScale()}
>
<div id='getBanner' className={styles.transparentCanvas}
// onMouseUp={(e) => this.handleMouseUp(e)}
// onMouseDown={(e) => this.handleMouseDown(e)}
// onMouseMove={(e) => this.handleMouseMove(e)}
// style={this.transformPosition()}
ref={this.canvas}
>
<div className={styles.bannerWrapper + ' bannerWrapper'}
style={{...this.getBannerSizes(), position: 'relative', overflow: 'hidden'}}
>
<div className={styles.background} style={this.addBackground(this.props.bannerBackground.background)}>
{
this.props.layers.layers && this.props.layers.layers.map((el, i) => {
if (el.type === 'image') {
return (
<img key={i} style={{
position: 'absolute',
top: `${el.top}px`,
left: `${el.left}px`,
}}
src={el.image}
className={el.className}
/>
)
}
if (el.type === 'text') {
return (
<div key={i} style={{
position: 'absolute',
fontSize: `${el.size}px`,
top: `${el.top}px`,
left: `${el.left}px`,
fontFamily: `${el.family}`,
color: el.color
}}
className={el.className}
>
{el.name}
</div>
)}
})
}
</div>
</div>
</div>
</div>
</>
)
}
}
const mapStateToProps = (state) => {
return {
bannerSize: state.bannerSize,
bannerBackground: state.bannerBackground,
layers: state.layers
};
};
const mapDispatchToProps = (dispatch) => ({
changeHeight: (height) => dispatch(changeHeight(height)),
changeWidth: (width) => dispatch(changeWidth(width))
});
export default connect(mapStateToProps, mapDispatchToProps)(Canvas);
|
import React from 'react'
import { Navagation } from '../index.js'
import './error404.scss'
class Error404 extends React.Component {
render () {
return (
<h1>Error 404</h1>
);
}
}
export default Error404;
|
import React from 'react';
import PropTypes from 'prop-types';
export default class Button extends React.Component {
constructor() {
super();
}
render() {
return (
<button onClick={this.props.changeName}>{this.props.firstName}</button>
)
}
}
Button.propTypes = {
firstName: PropTypes.string,
changeName: PropTypes.func
}
|
'use strict';
const urlParse = require('url-parse');
const dbHandle = require('./Database/connect');
const UrlNode = dbHandle.model('UrlNode', require('./Schemas/UrlNode'));
const Request = dbHandle.model('Request', require('./Schemas/Request'));
/**
* Creates a new request if UrlNode does not exist
* or updates request's Priority if UrlNode exists
* or returns UrlNode if UrlNode is visited
* @param {String} rawUrl
*
*/
const updateRequest = (rawUrl) => {
const Url = urlParse(rawUrl);
const protocol = Url.protocol;
const hostname = Url.hostname;
const path = Url.path || '/';
console.log(protocol, hostname, path);
urlNodeExists({protocol,hostname,path})
.then(([exists,visited, urlObj]) => {
//console.log(`exist, visited, urlObj - ${exists} ${visited} ${urlObj}`);
if(exists) {
//Update Priority if !visited
if(!visited){
const nodeId = urlObj.id;
Request.updateOne({
nodeId : nodeId
}, {
$inc : {
priority : 1
}
}).then(res => {
console.log(`Priority Updated ${res.ok}`);
return true;
})
.catch(e => {
console.error(e);
return null;
})
}
else{
//Delete Request
Request.deleteOne({
nodeId : urlObj.id,
}).then(res => {
console.log(`Request Crawled, hence deleted`);
return true;
})
.catch(e => {
console.error(e);
return null;
})
}
}
else{
//Create URL Node and Create Request
createUrlNode({protocol,hostname,path})
.then(urlId => {
createNewRequest(urlId)
.then(reqId => {
return reqId;
})
})
.catch(e => {
console.error(e);
});
}
})
.catch(e => {
console.error(e);
return null;
});
}
const createNewRequest = async (nodeId) => {
const req = new Request({
nodeId: nodeId,
});
try {
const newRequest = await req.save();
console.log(`newRequest Id : ${newRequest.id}`);
return newRequest.id;
} catch (e) {
console.error(e);
return null;
}
}
const createUrlNode = async ({protocol, hostname, path}) => {
const node = new UrlNode({
protocol: protocol,
hostname: hostname,
path: path,
});
try{
const newNode = await node.save();
console.log(`New UrlNode ID : ${newNode.id}`);
return newNode.id;
} catch (e) {
console.error(e);
return null;
}
}
const urlNodeExists = async ({protocol, hostname, path}) =>{
/**
* returns [exists, isVisted]
*/
try{
//Find UrlNode matching {protocol, hostname, path}
const urlnode = await UrlNode.findOne({
'protocol':protocol,
'hostname':hostname,
'path':path
}).exec();
//console.log(urlnode);
if(urlnode === null){
return [false,false];
}
else{
return [true,urlnode.isVisited, urlnode];
}
} catch (e) {
console.error(e);
//error occured
return [false,true];
}
}
module.exports = updateRequest;
|
var express = require('express');
var router = express.Router();
var dblite = require('dblite').withSQLite('3.8.6+');
var fs = require('fs');
var crypto = require('crypto');
var format = require('string-format');
var events = require('events');
var auth_model = require('./model/auth_model');
var utlity= require('./sms_util');
/* GET users listing. */
router.post('/auth', function (req, res, next) {
console.log("auth");
var phone = req.body.phone;
var password = req.body.password;
if (phone != undefined && password != undefined) {
init();
var db = global.db;
db.query('.databases');
db.query("select * from user where phone = '" + phone + "'", function (err, rows) {
if (rows.length == 1) {
var pass_from_db = rows[0][1];
if (pass_from_db == password) {
console.log('login success.');
var new_auth = new auth_model();
new_auth.create_auth(phone);
global.authList.push(new_auth);
res.send(new_auth.uuid);
}
}else{
console.log("login fail");
res.send('');
}
});
}
});
var init = function () {
if (global.db == undefined) {
if (fs.existsSync('/db/sms.db')) {
global.db = dblite('/db/sms.db');
console.log("Production DB: /db/sms.db");
}
else {
if (fs.existsSync('./db/sms.db')) {
console.log("Debug DB: ./db/sms.db");
}
global.db = dblite('./db/sms.db');
}
}
if(global.authList==undefined) {
global.authList = new Array();
}
if(global.emitter==undefined) {
global.emitter = new events.EventEmitter();
}
};
router.post('/sms', function (req, res, next) {
var uuid = req.body.uuid;
var content = req.body.content;
var contact = req.body.contact;
var time = req.body.time;
var util = new utlity();
var phone = util.get_phone_by_uuid(uuid);
if (phone != undefined && content != undefined && contact != undefined && time != undefined) {
init();
var id = util.get_md5(phone + contact + content + time);
util.get_sms_by_phone(phone, 'post_sms');
global.emitter.on("post_sms" + phone, function (smsList) {
if (!util.sms_exist(id, smsList)) {
var sql = "insert into sms (id, phone, content, contact_phone, flag, time) values ('" + id + "'," + phone + ",'" + content + "'," + contact + ",'Received','" + time + "')";
var db = global.db;
db.query(sql, function (err, rows) {
if (err == undefined) {
console.log("inserted " + sql);
res.send("posted");
}
});
}
});
}
});
router.get('/sms', function (req, res, next) {
if(req.query!=undefined && req.query.uuid!=undefined) {
init();
var uuid = req.query.uuid;
var util = new utlity();
var phone = util.get_phone_by_uuid(uuid);
if(phone!=undefined) {
util.get_sms_by_phone(phone, "get_sms");
global.emitter.on("get_sms" + phone, function (smsList) {
res.send(smsList);
});
}
}
});
module.exports = router;
|
#!/usr/bin/env node
require ('proof')(4, prove)
function prove (assert) {
var rects = require('../../area.js')
var a = new rects.Area(-10, 5, -5, 0)
var b = new rects.Area(0, 7, 0, 7)
assert(a.containsPoint(-2, -2), true, "Square(-10, 5, -5, 0) contains point(-2, -2)")
assert(b.containsPoint(2,2), true , "Square(0,7,0,7) contains point(2,2)")
assert(b.containsPoint(0,0), true , "Square(0,7,0,7) contains point(0,0)")
assert(b.containsPoint(8,8), false , "Square(0,7,0,7) doesn't contain point(8,8)")
}
|
const express = require('express')
const createUser = require('../controllers/user').createUser
const router = express.Router
router.post('/', (req, res) => {
const user = req.body
createUser(user)
})
router.get('/', (req, res) => {
})
module.exports = router
|
/**
* 服务器端统计在线人数
*/
// 1. 加载net核心模块
var net = require('net');
// 2. 创建一个服务应用程序,得到一个服务器实例对象
var server = net.createServer();
var count = 0;
// 3. 监听客户端的连接事件,连接成功就会执行回调处理函数
server.on('connection', function (socket) {
count++;
console.log('welcome, 当前在线人数:' + count);
socket.write('remoteAddress' + socket.remoteAddress + '\n');
socket.write('remotePort' + socket.remotePort);
});
server.listen(3000, '127.0.0.1', function () {
console.log('server listening at port 3000');
});
|
'use strict'
/* Global Imports */
import Debug from 'debug'
import { Ticket, User } from '../models'
import { Sequelize } from 'sequelize'
/* Config vars */
const debug = new Debug('nodejs-hcPartnersTest-backend:db-api:ticket')
export default {
findAll: () => {
debug('findAll Ticket')
const tickets = Ticket.findAll({
attributes: ['id', 'requested_ticket', 'userId'],
include: [
{
model: User,
where: { id: Sequelize.col('ticket.userId') },
attributes: ['id', 'name', 'email']
}
]
})
return tickets
},
findById: (id) => {
debug('findByID Ticket')
const ticket = Ticket.findOne({
where: {
id
},
attributes: ['id', 'requested_ticket', 'userId']
})
return ticket
},
create: (objectTicket) => {
debug('Create Ticket')
const ticket = new Ticket(objectTicket)
return ticket.save()
},
update: async (id, ticket) => {
debug('Update Ticket')
let ticketToUpdate = await Ticket.findOne({
where: {
id
},
attributes: ['id', 'requested_ticket', 'userId']
})
if (ticketToUpdate) {
return ticketToUpdate.update(ticket)
}
return false
},
delete: async (id) => {
debug('Delete Ticket')
const ticketToDelete = await Ticket.findByPk(id)
if (ticketToDelete) {
return ticketToDelete.destroy()
}
return false
},
findTicketsByUser: (userId) => {
debug('findTicketUser')
const ticket = Ticket.findAll({
where: {
userId
},
attributes: ['id', 'requested_ticket'],
include: [
{
model: User,
where: { id: Sequelize.col('ticket.userId') },
attributes: ['id', 'name', 'email']
}
]
})
return ticket
}
}
|
'use strict';
module.exports = (sequelize, DataTypes) => {
const Coin = sequelize.define('Coin', {
name: DataTypes.STRING,
symbol: DataTypes.STRING,
address: DataTypes.STRING,
amount: DataTypes.DOUBLE(18,6),
decimal: DataTypes.INTEGER,
abi: DataTypes.TEXT
}, {
tableName: 'coin',
comment: "代币信息",
sequelize
});
Coin.associate = function(models) {
// associations can be defined here
};
return Coin;
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var VertexArrayObject = /** @class */ (function () {
function VertexArrayObject(buffer, options) {
if (options === void 0) { options = {}; }
this._buffer = buffer;
this._glContext = null;
this._glVertexArrayObject = null;
this._enabledAttributes = ('attributes' in options) ? options.attributes : null;
this._mustWriteData = 'dataOrLength' in options;
if (this._mustWriteData) {
this._dataOrLength = options.dataOrLength;
}
this._isInitialized = false;
}
/**
* Initializes the vertex array object.
* Do not call this method manually.
* @param {WebGL2RenderingContext} context
* @param {WebGLProgram} program
* @private
*/
VertexArrayObject.prototype._init = function (context, program) {
if (this._mustWriteData) {
this._buffer.bufferData(this._dataOrLength);
}
this._buffer._initOnce(context, program, this._enabledAttributes);
var vao = this._buffer._createWebGLVertexArrayObject(context, program, this._enabledAttributes);
this._glContext = context;
this._glVertexArrayObject = vao;
this._isInitialized = true;
};
Object.defineProperty(VertexArrayObject.prototype, "buffer", {
/**
* Returns buffer bound to the vertex array object.
* @returns {Buffer}
*/
get: function () {
return this._buffer;
},
enumerable: true,
configurable: true
});
Object.defineProperty(VertexArrayObject.prototype, "glVertexArrayObject", {
/**
* Returns `WebGLVertexArrayObject` if the vertex array object is initialized.
* Otherwise, throws an error.
* @returns {WebGLVertexArrayObject}
*/
get: function () {
if (this._isInitialized) {
return this._glVertexArrayObject;
}
else {
throw new Error('This vertex array object is not added to any program yet.');
}
},
enumerable: true,
configurable: true
});
return VertexArrayObject;
}());
exports.VertexArrayObject = VertexArrayObject;
|
import { createLocalVue, shallowMount } from "@vue/test-utils";
import VueRouter from "vue-router";
import AppHeader from "@/components/AppHeader";
const localVue = createLocalVue();
localVue.use(VueRouter);
describe("AppHeader component", () => {
it("Should render correctly", () => {
const wrapper = shallowMount(AppHeader, { localVue });
expect(wrapper.html()).toMatchSnapshot();
});
});
|
import Vue from 'vue'
import App from './App.vue'
import Header from './Components/Header_footer/Header'
import Footer from './Components/Header_footer/Footer'
Vue.component('app-header', Header)
Vue.component('app-footer', Footer)
Vue.directive('awesome', {
bind(el, binding, vnode){
el.innerHTML = binding.value;
el.style.color = binding.modifiers.red ? 'red' : 'blue';
el.style.fontSize = binding.modifiers.big ? '30px' : '20px';
},
inserted(el, binding, vnode){
el.parentNode
}
})
new Vue({
el: '#app',
render: h => h(App)
})
|
import React, { Component } from 'react';
import './App.css';
import KakaoLoginMaking from './component/KakaoLoginMaking';
import BibleFinder from './component/BibleFinder';
import BibleRemember from './component/BibleRemember';
import Signup from './component/Signup';
import SeparateSit from './component/SeparateSit';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import KakaoTokenGetter from './component/KakaoTokenGetter';
import {Button} from 'react-bootstrap';
import ReadBook from './component/ReadBook';
class Nav extends Component {
constructor(props) {
super(props)
this.state = { isOpen: false }
}
handleOpen = () => {
this.setState({ isOpen: true })
}
handleClose = () => {
this.setState({ isOpen: false })
}
render(){
console.log("hostname:e", this.props.hostName);
return(
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/token">KakaoTokenGetter</Link></li>
<li><Link to="/login/">KakaoLogin</Link></li>
{this.props.hostName !== "hanbitco-qa.firebaseapp.com"?<li><Link to="/finder/">Finder</Link></li>:""}
{this.props.hostName !== "hanbitco-qa.firebaseapp.com"?<li><Link to="/remember/">Remember</Link></li>:""}
<li><Link to="/signup/">회원가입(signup)</Link></li>
{this.props.hostName !== "hanbitco-qa.firebaseapp.com"?<li><Link to="/separate_sit/">자리배치</Link></li>:""}
{this.props.hostName !== "hanbitco-qa.firebaseapp.com"?<li><Link to="/read_book/">readBook</Link></li>:""}
</ul>
</nav>
)
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
showNav: false,
};
}
handleClickMenu() {
if(this.state.showNav){
this.setState({showNav: false});
}else{
this.setState({showNav: true});
}
}
success(response){
console.log(response);
};
render(){
const hostname = window && window.location && window.location.hostname;
return (
<Router>
<Button size={"sm"} onMouseEnter={()=>this.handleClickMenu()} onClick={()=>this.handleClickMenu()}>menu</Button>
{this.state.showNav ?<Nav hostName={hostname}/>:""}
<Route path="/" exact component={Signup}/>
<Route path="/login/" component={KakaoLoginMaking}/>
<Route path="/token/" component={KakaoTokenGetter}/>
<Route path="/finder/" component={BibleFinder}/>
<Route path="/remember/" component={BibleRemember}/>
<Route path="/signup/" component={Signup}/>
<Route path="/separate_sit/" component={SeparateSit}/>
<Route path="/oauth/" component={KakaoTokenGetter}/>
<Route path="/read_book/" component={ReadBook}/>
</Router>
);
}
}
export default App;
|
const mix = require('laravel-mix');
mix
.js('resources/js/~Plugins/plugins.js', 'public/js/plugins.bundle.js')
.js('resources/js/App/app.js', 'public/js/app.bundle.js')
.js('resources/js/Login/app.js', 'public/js/login.bundle.js')
.sass('resources/sass/vendors.scss', 'public/css/okr.bundle.css').options({
processCssUrls: false,
});
;
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import utils from 'common/utils';
import './TextExt.scss';
const PREFIX = 'text-ext';
const cx = utils.classnames(PREFIX);
let index = 0;
class TextExt extends Component {
componentDidMount() {
this._text.style.position = 'absolute';
this.textWidth = this._text.offsetWidth;
this._text.style.position = 'relative';
this.onWindowResize();
window.addEventListener('mouseup', this.onMouseUp, false);
window.addEventListener('mousemove', this.onMouseMove, false);
window.addEventListener('resize', this.onWindowResize, false);
this.bind = index++;
}
componentWillUnmount() {
window.removeEventListener('mouseup', this.onMouseUp, false);
window.removeEventListener('mousemove', this.onMouseMove, false);
window.removeEventListener('resize', this.onWindowResize, false);
}
onWindowResize = e => {
this.boxWidth = this._textContain.offsetWidth;
if (this.textWidth <= this.boxWidth) {
this._text.style.overflow = 'visible';
} else {
this._text.style.overflow = 'hidden';
}
this.collapseText();
};
onMouseEnter = e => {
this._mouseon = true;
this.boxWidth = this._textContain.offsetWidth;
this._text.style.width = this.textWidth + 'px';
this._boxX = this._textContain.getBoundingClientRect().left;
if (this.textWidth > this.boxWidth) {
this._text.style.overflow = 'visible';
}
};
onMouseMove = e => {
if ((this._mouseon || this._mousedown) && this.boxWidth < this.textWidth) {
const mouseX = e.pageX - this._boxX;
let left =
mouseX / this.boxWidth * (this.boxWidth - 100 - this.textWidth) + 40;
left = Math.min(40, Math.max(-40 - this.textWidth + this.boxWidth, left));
this._text.style.left = left + 'px';
}
};
onMouseLeave = e => {
this._mouseon = false;
this.collapseText();
};
onMouseDown = e => {
this._mousedown = true;
};
onMouseUp = e => {
this._mousedown = false;
this.collapseText();
};
collapseText = () => {
if (!this._mousedown && !this._mouseon) {
this._text.style.width = this.boxWidth + 'px';
this._text.style.left = '';
if (this.textWidth > this.boxWidth) {
this._text.style.overflow = '';
}
}
};
render() {
return (
<div
onMouseDown={this.onMouseDown}
onMouseEnter={this.onMouseEnter}
onMouseMove={this.onMouseMove}
onMouseLeave={this.onMouseLeave}
ref={dom => {
this._textContain = dom;
}}
className={PREFIX + ' ' + (this.props.className || '')}
style={this.props.style}
>
<div
className={cx('text')}
ref={dom => {
this._text = dom;
}}
>
{this.props.text}
</div>
</div>
);
}
}
TextExt.propTypes = {};
TextExt.defaultProps = {};
export default TextExt;
|
import { Data } from '../../CharacterDataStructure'
import * as SkillFunctions from '../../SkillFunctions'
Data.functions.skill.ATBModifierTarget = (G, caster, target, params) => {
target.current.progress += params.value;
if (target.current.progress < 0) target.current.progress = 0;
}
Data.functions.skill.DamageTarget = (G, caster, target, params) => {
SkillFunctions.dealDefaultDamage(G, caster, target, params);
}
Data.functions.skill.HealTarget = (G, caster, target, params) => {
SkillFunctions.receiveHealing(G, target, SkillFunctions.skillValue(caster, params));
}
Data.functions.skill.ExecuteTarget = (G, caster, target, params) => {
const threshold = SkillFunctions.skillValue(caster, params);
if (target.current.health < threshold) {
SkillFunctions.death(G, target);
}
}
Data.functions.skill.DamageTargetWithLifeSteal = (G, caster, target, params) => {
const damageDealt = SkillFunctions.dealDefaultDamage(G, caster, target, params);
SkillFunctions.receiveHealing(G, caster, damageDealt * params.lifesteal);
}
Data.functions.skill.GainPower = (G, caster, target, params) => {
SkillFunctions.team(G, caster).power += params.value;
}
|
import express from 'express';
import cors from 'cors';
import uuid from 'uuid';
const fakeCars = {
_id: "60e5403569523a475aff3fbb",
id: 97045,
title: "Ferrari 246 dino GT 1973",
makeId: 4400,
price: 566,
makeKey: "Ferrari",
images: [
{
uri: "https://particleforward.com/api/challenge/assets/image1",
set: "fe4cfedffdffffffff",
},
{
uri: "https://particleforward.com/api/challenge/assets/image1",
set: "fe4cfedffdffffffff",
},
{
uri: "https://particleforward.com/api/challenge/assets/image2",
set: "fe4cfedffdffffffff",
},
{
uri: "https://particleforward.com/api/challenge/assets/image3",
set: "fe4cfedffdffffffff",
},
{
uri: "https://particleforward.com/api/challenge/assets/image4",
set: "fe4cfedffdffffffff",
},
],
};
const app = express();
app.use(express.urlencoded({extended: true}))
app.use(express.json());
app.use(cors());
// The route for getting a list of all cars
app.get('/cars', (req, res) => {
res.status(200).json(fakeCars);
});
// The route for getting a list of all cars, but with a delay
// (to display the loading component better)
app.get('/cars-delay', (req, res) => {
setTimeout(() => res.status(200).json(fakeCars), 2000);
});
// The route for creating new car
app.post('/cars', (req, res) => {
const { car } = req.body;
if (text) {
const insertedCar = {
id: uuid(),
createdAt: Date.now(),
car,
}
fakeCars.push(insertedCar);
res.status(200).json(insertedCar);
} else {
res.status(400).json({ message: 'Wrong request body' });
}
});
// The route for deleting a car item
app.delete('/cars/:id', (req, res) => {
const { id } = req.params;
const removedCar = fakeCars.find(car => car.id === id);
fakeCars = fakeCars.filter(car => car.id !== id);
res.status(200).json(removedCar);
});
app.listen(8090, () => console.log("Server listening on port 8090"));
|
const React = require('react');
module.exports = () => (
<div>
<h3>ChannelList</h3>
<ul>
<li>#test</li>
<li>#fun</li>
</ul>
</div>
);
|
/**
* Implement Gatsby's Node APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/node-apis/
*/
// You can delete this file if you're not using it
/* eslint-disable @typescript-eslint/no-var-requires */
// @ts-check
// const { fetchTeamsFromTBA } = require("./lib/apiFetches")
// const { uniq } = require("ramda")
// const path = require("path")
// const { teams } = require("./lib/randomData")
// exports.createPages = async ({ actions: { createPage } }) => {
// try {
// // const sfrTeams = await fetchTeamsFromTBA("2019casf", "sfr")
// // const svrTeams = await fetchTeamsFromTBA("2019casj", "svr")
// // const teams = sfrTeams.concat(svrTeams)
// const AllTeamsTemplate = path.resolve(
// "src/templates/all-teams-template.tsx"
// )
// const TeamTemplate = path.resolve("src/templates/team-template.tsx")
// createPage({
// path: `/teams`,
// component: AllTeamsTemplate,
// context: { teams: uniq(teams) },
// })
// uniq(teams).forEach(team => {
// createPage({
// path: `/teams/${team.team_number}`,
// component: TeamTemplate,
// context: { team },
// })
// })
// // uniq(sfrTeams.concat(svrTeams)).forEach(team => {
// // createPage({
// // path: `/teams/${team.team_number}`,
// // component: TeamTemplate,
// // context: { team },
// // })
// // })
// } catch (error) {
// console.error(error)
// }
// }
|
var mongoose = require('mongoose'),
Bid = mongoose.model('Bid');
function bidsController() {
var _this = this;
this.logout = function(req, res) {
res.json({
future: 'logout'
});
}
this.bid = function(req, res) {
console.log("bid--------",req.body)
var bid = new Bid(req.body);
bid.save(function(err, bid) {
if (err){
res.json(err);
}
else{
res.json(bid);
}
});
}
this.end = function(req,res){
res.json({
future: 'end bid'
})
};
this.get_bid = function(req, res){
console.log("-----get_bid------",req.body);
Bid.find({}, function(err, bid) {
if(err){
console.log("something went wrong");
console.log(err);
} else {
console.log('result:', bid);
res.json(bid);
}
})
};
this.result = function(req,res){
Bid.find({})
// .sort({'product_id':1, 'bid':-1}) // give me the max
.exec(function (err, bids) {
console.log(bids)
var arr = []
for (var i = 0; i < bids.length; i++) {
// console.log(arr)
// console.log("===========================================================")
if(bids[i].product_id == 1){
if(arr.length == 0){
arr.push(bids[i])
}else{
for (var j = 0; j < arr.length; j++) {
if(arr[j].product_id == 1 && arr[j].bid < bids[i].bid){
arr[j]= bids[i];
}
}
}
}
if(bids[i].product_id == 2){
if(arr.length == 1){
arr.push(bids[i])
}else{
for (var j = 1; j < arr.length; j++) {
if(arr[j].product_id == 2 && arr[j].bid < bids[i].bid){
arr[j]= bids[i];
}
}
}
}
if(bids[i].product_id == 3){
if(arr.length == 2){
arr.push(bids[i])
}else{
for (var j = 0; j < arr.length; j++) {
if(arr[j].product_id == 3 && arr[j].bid < bids[i].bid){
arr[j]= bids[i];
}
}
}
}
}
console.log("=====ARR====", arr);
// Bid.find({}, function(err, bid) {
if(err){
console.log("something went wrong");
} else {
// console.log('===result:', bids);
res.json(arr);
}
})
};
}
module.exports = new bidsController();
|
'use strict';
const scriptInfo = {
name: 'Guess Sex',
desc: 'Guess the sex of a user based on their chat history',
createdBy: 'IronY'
};
// Original concept credited to http://www.hackerfactor.com/GenderGuesser.php
const _ = require('lodash');
const Models = require('bookshelf-model-loader');
const sampleSize = 1000;
const logger = require('../../lib/logger');
module.exports = app => {
if (!app.Database || !Models.Logging) return scriptInfo;
const getSexGuess = require('../generators/_guessSexInfo');
const type = require('../lib/_ircTypography');
const getResults = nick => Models.Logging.query(qb =>
qb
.select(['text'])
.where('from', 'like', nick)
.orderBy('id', 'desc')
.limit(sampleSize)
)
.fetchAll()
.then(results => getSexGuess(results.pluck('text').join(' ')));
const displaySexGuess = (to, from, text, message) => {
let [nick] = text.split(' ');
nick = nick || from;
// We are gendering the bot
if (nick === app.nick) {
app.say(to, `I am clearly {a male|a female|an Apache attack helicopter|what ever you want me to be} ${from}`);
return;
}
getResults(nick)
.then(r => {
let t = r.results.Combined;
let buffer = `Gender Guesser ${type.icons.sideArrow} ${nick} ${type.icons.sideArrow} ${r.sampleSize} words sampled ${type.icons.sideArrow} ` +
`${type.title('Female:')} ${t.female} ${type.icons.sideArrow} ${type.title('Male')} : ${t.male} ` +
`${type.icons.sideArrow} ${type.title('Diff:')} ${t.diff} ${type.icons.sideArrow} ${type.colorNumber(t.percentage)}% ${type.icons.sideArrow} ` +
`${t.sex} ${t.weak ? ` ${type.icons.sideArrow} (EU?)` : ''}`;
app.say(to, buffer);
})
.catch(err => {
logger.error('Guess Sex Error', {
err
})
app.say(to, err);
});
};
// Provide a OnConnected provider, this will fire when the bot connects to the network
app.Commands.set('gender', {
call: displaySexGuess,
desc: '[Nick?] Guess the sex of the user',
access: app.Config.accessLevels.admin
});
return scriptInfo;
};
|
export { FloatingButton } from './FloatingButton'
|
const mongoose = require('mongoose');
const schema = mongoose.Schema;
const codedefSchema = new schema({
code: Number,
code_type: Number,
definition: String,
picture_url: String,
});
mongoose.model('code_definition', codedefSchema);
|
"use strict";
const express = require('express');
const router = express.Router();
const comment = "Thanks for visiting my website!";
// GET home page
router.get('/', (req, res) => { res.render('index'); });
// GET resume page
router.get('/resume', (req, res) => { res.render('resume'); });
module.exports = router;
|
import *as ActionTypes from '../Action/types';
const intialState = {
numa:1
};
export default(stateA=intialState,action)=>{
switch(action.type){
case ActionTypes.UPDATE_A:{
return{...stateA,numa:stateA.numa+action.payloadA}
}
default:
return stateA;
}
}
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsEscalatorWarning = {
name: 'escalator_warning',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M6.5 2c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 7.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5S17.83 8 17 8s-1.5.67-1.5 1.5zm3 2.5h-2.84c-.58.01-1.14.32-1.45.86l-.92 1.32L9.72 8a2.02 2.02 0 00-1.71-1H5c-1.1 0-2 .9-2 2v6h1.5v7h5V11.61L12.03 16h2.2l.77-1.1V22h4v-5h1v-3.5c0-.82-.67-1.5-1.5-1.5z"/></svg>`
};
|
import { Map } from 'immutable';
import {
LOAD_CALENDAR_EVENTS,
LOAD_EVENTS_SUCCESS,
LOAD_EVENTS_FAILURE
} from '../actions/activities';
import { getToken } from '../../services/utility';
const initState = new Map({
isLoading: false,
events: null,
error: false
})
/**
*
* @function
* Cette fonction est un 'Reducer' pour stocker le 'State' à chaque 'action' pour des activités.
*/
function activitiesReducer(state = initState.merge(getToken()), action) {
switch (action.type) {
case LOAD_CALENDAR_EVENTS:
return state
.set('isLoading', true)
.set('events', null)
.set('error', false)
case LOAD_EVENTS_SUCCESS:
return state
.set('isLoading', false)
.set('events', action.result)
.set('error', false)
case LOAD_EVENTS_FAILURE:
return state
.set('isLoading', false)
.set('error', true)
default:
return state;
}
}
export default activitiesReducer;
|
/*****
Todo:
-place byte with certain endian
-can have a breakpoint return byte, and any input into the 'return' function will write to that byte
-string and bytes
Why does gameboy 'catch up' after breakpoint?
For holding down keys, only the last key is repeated
-use timeout loop instead?
-doesnt work properly when focus switches to input
Work for gameboy color?
-banks different?
-ram has banks?
HTML elements got into a div with ID 'interaction'
*****/
function Breakpoint( data, gb ){
var char_map, inverse_char_map, each, break_byte,
breaks = {},
global_breaks = {},
sym = data.sym,
callbacks = data.callbacks,
FLAGS = {
USING_EMULATOR : 0,
RETURN : 1,
CONNECTED_TO_SERVER : 2,
LOGGED_IN : 3,
CARRY : 4,
HALF_CARRY : 5,
OPERATION : 6,
ZERO : 7,
},
helpers = {
placeString : placeString,
placeBytes : placeBytes,
return : breakpointReturn,
getBytes : getBytes,
getString : getString,
setBit : setBit,
getBit : getBit,
setCarry : setCarry,
setHalfCarry : setHalfCarry,
setOperation : setOperation,
setZero : setZero,
resetFlags : resetFlags,
cleanString : cleanString,
preventInput : preventInput
};
//if there is no breakpoint data, then return false
if( !('BreakpointByte' in sym) || !('BreakpointReturn' in sym) ) return false;
//Store the char_map if one was provided
if( data.char_map ){
char_map = data.char_map;
inverse_char_map = {};
for( each in char_map ){
inverse_char_map[ char_map[each] ] = each;
}
}
/*****
Helpers
*****/
function setCarry( val ){
setBit(break_byte, FLAGS.CARRY, val);
};
function setHalfCarry( val ){
setBit(break_byte, FLAGS.HALF_CARRY, val);
};
function setOperation( val ){
setBit(break_byte, FLAGS.OPERATION, val);
};
function setZero( val ){
setBit(break_byte, FLAGS.ZERO, val);
};
//to place chars at a certain location in memory
function placeString(){
var str, len, f, i,
args = Array.prototype.slice.call(arguments),
byte_location = args.splice(0,1)[0];
if( char_map ){
f = function( arr, j ){
arr[j] = char_map[str[i]];
}
}
else{
f = function( arr, j ){
arr[j] = str[i];
}
}
while( args.length > 0 ){
str = args.splice(0,1)[0];
if( str.constructor === String || str.constructor === Array ){
len = str.length;
for(i=0;i<len;i++){
setByte( byte_location, f );
byte_location[ byte_location.length-1 ]++;
}
}
}
}
//to place bytes at a certain location in memory
function placeBytes(){
var i, j, len, f, num,
args = Array.prototype.slice.call(arguments),
byte_location = args.splice(0,1)[0];
f = function( arr, k ){
arr[k] = num;
}
while( args.length > 0 ){
i = args.splice(0,1)[0];
if( i.constructor === Number ){
num = i;
setByte( byte_location, f );
}
else if( i.constructor === Array ){
len = i.length;
for(j=0;j<len;j++){
num = i[j];
setByte( byte_location, f );
byte_location[ byte_location.length-1 ]++;
}
}
}
}
//To return from the breakpoint and resume game function
function breakpointReturn(){
var f = function( arr, i ){
arr[i] |= 1 << FLAGS.RETURN;
}
setByte( break_byte, f );
}
//to read bytes
function getBytes( byte_data, length ){
var ret = [],
count = byte_data[ byte_data.length -1 ],
bank;
if( byte_data.length > 1 ) bank = byte_data[0];
if( bank ) count += bank*0x4000;
//if a length was given, then return an array
if( length ) while( length-- > 0 ) ret.push( gb.memory[count++] );
else return gb.memory[count];
return ret;
}
//to read a string
function getString(){
var c, getNext,
args = Array.prototype.slice.call(arguments),
byte_location = args.splice(0,1)[0],
next = args.splice(0,1)[0],
ret = '';
if( inverse_char_map ){
getNext = function( i ){
return inverse_char_map[ getBytes( byte_location ) ];
}
}
else{
getNext = function( i ){
var s = i > 0x10 ? '' : '0';
return s+i.toString(0x10);
}
}
if( next.constructor === String ){
c = getNext(byte_location );
while( next !== c ){
ret += c;
byte_location[ byte_location.length-1 ]++;
c = getNext(byte_location );
}
}
else if(next.constructor === Number ){
while( next-- > 0 ){
ret += getNext(byte_location );
byte_location[ byte_location.length-1 ]++;
}
}
return ret;
}
//to modify a byte
function setByte( byte_data, f ){
var count = byte_data[ byte_data.length -1 ],
bank;
if( byte_data.length > 1 ) bank = byte_data[0];
if( bank ){
f( gb.ROM, count + bank*0x4000 );
//if we are in the current bank, then apply to the memory
if( gb.ROMBank1offs === bank ) f( gb.memory, count );
}
else{
f( gb.memory, count );
//if it is in the home bank, then also apply to the ROM
if( count < 0x4000 ) f( gb.ROM, count );
}
}
//to reset the flags
function resetFlags(){
var f = function( arr, i ){
arr[i] &= 0x0F;
}
setByte( break_byte, f );
}
//to set a bit
function setBit(byte_data, bit, val){
var f;
if(val === undefined){
val = true;
}
if( val ){
f = function( arr, i ){
arr[i] |= (1 << bit );
}
}
else{
f = function( arr, i ){
arr[i] &= ~( 1 << bit );
}
}
setByte( byte_data, f );
}
//to get a bit
function getBit( byte_data, bit ){
return getBytes( byte_data ) & 1 << bit;
}
//to remove unacceptable chars from the given string
function cleanString( str ){
var i, c,
ret_str = '',
l = str.length;
for(i=0;i<l;i++){
c = str[i];
if( c in char_map ) ret_str += c;
}
return ret_str;
}
//to prevent the input of the given element(s) from controlling the emulator
function preventInput(){
var args = Array.prototype.slice.call(arguments);
function stopProp(e){
e.stopPropagation();
}
args.forEach(
function( el ){
el.addEventListener("keydown",stopProp);
el.addEventListener("keyup",stopProp);
}
);
}
/*****
Functions called from the GameBoyCore
*****/
//To check to see if we reached a breakpoint, and execute if so
this.checkBreakpoint = function(){
var index,
bank = gb.ROMBank1offs,
count = gb.programCounter;
if( count in global_breaks ) setTimeout(global_breaks[count],1);
else if( bank in breaks ){
index = breaks[bank].counts.indexOf(count);
if( index > -1 ) setTimeout(breaks[bank].callbacks[index],1);
}
}
//initialize the breakpoint byte
this.initBreakpointByte = function(){
setBit( break_byte, FLAGS.USING_EMULATOR );
}
/*****
To init the breakpoint data
*****/
function init(){
var each, count, bank, callback;
function getResetFlagCallback( f ){
return function(){
resetFlags();
f( helpers );
}
}
function getCallback( f ){
return function(){
f( helpers );
}
}
//To set up the breakpoints for quick references
for( each in sym ){
count = sym[each][sym[each].length-1];
bank = null;
callback = null;
//To get the bank from the sym if it exists
//Won't exists for home bank or RAM
if( sym[each].length > 1 ) bank = sym[each][0];
if( each === 'BreakpointByte' ) break_byte = sym[ each ];
else if( each === 'BreakpointReturn' ){
callback = getCallback( function(){
setBit(break_byte, FLAGS.RETURN, false);
} );
}
else if( each in callbacks ){
callback = getResetFlagCallback( callbacks[each] );
}
if( callback ){
if( bank ){
if( bank in breaks ){
breaks[bank].counts.push(count);
breaks[bank].callbacks.push( callback );
}
else{
breaks[bank] = {
counts : [count],
callbacks : [callback]
};
}
}
else{
global_breaks[count] = callback;
}
}
}
//initialize if necessary
if( data.init ) data.init( helpers );
}
//Init the data
init();
}
|
"use strict";
require.config({
baseUrl: "../static/js",
paths: {
layui: "libraries/layui/layui",
jquery: "libraries/jquery"
}
});
require(["jquery", "layui"], function ($) {
const formatNum = n => {
n = n.toString();
return n[1] ? n : '0' + n;
};
const formatTime = date => {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
return [year, month, day].map(formatNum).join('-') + ' ' + [hour, minute, second].map(formatNum).join(':');
};
layui.use('element', function () {
var element = layui.element;
});
layui.use('laydate', () => {
var laydate = layui.laydate;
laydate.render({
elem: '#start',
type: 'datetime',
value: formatTime(new Date()),
format: 'yyyy-MM-dd',
theme: '#409EFF',
done: (value, date) => {
console.log(value);
}
});
});
});
|
import { mapState, mapActions } from 'vuex';
import _ from 'lodash';
import editTable from '@/components/edit-table';
export default {
data() {
return {
keyword: '',
isValid: false,
loading: false,
pageSize: 10,
pageSizes: [10, 20, 30, 50, 100],
dataToUpdate: null,
editIndex: -1,
keys: [
{
name: 'category',
},
{
name: 'name',
},
{
name: 'en',
type: 'textarea',
},
{
name: 'zh',
type: 'textarea',
},
{
name: 'creator',
readonly: true,
},
],
dataToAdd: null,
};
},
methods: {
...mapActions([
'langListAll',
'langUpdate',
'langAdd',
]),
getItems: async function getItems() {
if (this.loading) {
return;
}
const {
keyword,
} = this;
this.loading = true;
try {
const query = {};
if (keyword) {
query.category = keyword;
}
await this.langListAll(query);
} catch (err) {
this.$alert(err);
} finally {
this.loading = false;
}
},
handleEdit: function handleEdit(index) {
const item = this.items[index];
const data = {};
_.forEach(this.keys, (v) => {
const name = v.name;
data[name] = item[name];
});
this.dataToUpdate = data;
this.editIndex = index;
},
update: function update(id, data) {
return this.langUpdate(id, data);
},
handleUpdate: function handleUpdate(index) {
editTable.handleUpdate.bind(this)(index, 'name');
},
save: function save(data) {
return this.langAdd(data);
},
handleAdd: editTable.handleAdd,
handleSave: editTable.handleSave,
handleChangePage: editTable.handleChangePage,
handleSizeChange: editTable.handleSizeChange,
handleSortChange: editTable.handleSortChange,
handleSearch: editTable.handleSearch,
},
computed: {
...mapState({
userInfo: state => state.user.info,
items: (state) => {
const items = state.lang.items;
if (!items) {
return null;
}
return items.concat({});
},
total: state => state.lang.total,
}),
type: editTable.type,
},
};
|
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import { compose } from 'redux';
// import get from 'lodash.get';
import { Button, Form, Input, Select, Col, Row } from 'antd';
import buttonStyle from '../../antdTheme/button/style/index.less';
import formStyle from '../../antdTheme/form/style/index.less';
import gridStyle from '../../antdTheme/grid/style/index.less';
import inputStyle from '../../antdTheme/input/style/index.less';
import iconStyle from '../../antdTheme/icon/style/index.less';
import selectStyle from '../../antdTheme/select/style/index.less';
import { connect } from '../../store/redux';
import { commonReducer } from '../../store/common.reducer';
import { commonAction } from '../../store/common.action';
import s from './QueryForm.css';
import XQuery from '../../components/XQuery';
const StateName = 'accountManagement';
const { Option } = Select;
const FormItem = Form.Item;
const colWidth = 8; // 两列
const formItemLayout = {
wrapperCol: {
span: 18,
},
labelCol: {
span: 6,
},
style: {
width: '100%',
},
};
const formItemLayou2 = {
wrapperCol: {
span: 16,
},
labelCol: {
span: 8,
},
style: {
width: '100%',
},
};
// 审核状态
const Status = [
{
name: '全部',
key: -1,
},
{
name: '待审核',
key: 0,
},
{
name: '通过',
key: 1,
},
{
name: '未通过',
key: 2,
},
];
// 查询表单
class QueryForm extends React.Component {
render() {
const { getFieldDecorator } = this.props.form;
const { list } = this.props;
return (
<Form layout="inline" style={{ padding: '0 10px' }}>
<XQuery>
<FormItem label="名称" {...formItemLayout}>
{getFieldDecorator('buName')(
<Input autoFocus style={{ width: '100%' }} />,
)}
</FormItem>
<FormItem label="社会信用代码" {...formItemLayou2}>
{getFieldDecorator('bulicenseCode')(
<Input style={{ width: '100%' }} />,
)}
</FormItem>
<FormItem label="联系人" {...formItemLayout}>
{getFieldDecorator('ownerName')(
<Input style={{ width: '100%' }} />,
)}
</FormItem>
<FormItem label="联系方式" {...formItemLayout}>
{getFieldDecorator('ownerMobile')(
<Input style={{ width: '100%' }} />,
)}
</FormItem>
<FormItem label="审核状态" {...formItemLayou2}>
{getFieldDecorator('auditStatus')(
<Select
style={{ width: '100%' }}
getPopupContainer={() => document.querySelector(`.root`)}
>
{Status.map(b => (
<Option key={b.key} value={b.key}>
{b.name}
</Option>
))}
</Select>,
)}
</FormItem>
<FormItem label="注册平台" {...formItemLayout}>
{getFieldDecorator('applayfrom', {
initialValue: list[0] ? list[0].code : '',
})(
<Select
style={{ width: '100%' }}
getPopupContainer={() => document.querySelector(`.root`)}
>
{list.map(b => (
<Option key={b.memo} value={b.code}>
{b.cnname}
</Option>
))}
</Select>,
)}
</FormItem>
<FormItem>
<Button onClick={this.query} type="primary">
查询
</Button>
<a
href="javascript:void 0"
className="query-reset-btn"
onClick={this.resetForm}
>
重置
</a>
</FormItem>
</XQuery>
</Form>
/* <Form layout="inline" style={this.props.style}>
<table className="query-table">
<tbody>
<tr>
<td className="label" style={{ width: 73 }}>
名称:
</td>
<td colSpan={3}>
{getFieldDecorator('buName')(<Input style={{ width: 460 }} />)}
</td>
<td className="label" style={{ width: 143 }}>
统一社会信用代码:
</td>
<td colSpan={3}>
{getFieldDecorator('bulicenseCode')(
<Input style={{ width: 460 }} />,
)}
</td>
</tr>
<tr>
<td className="label" style={{ width: 73 }}>
联系人:
</td>
<td>
{getFieldDecorator('ownerName')(
<Input style={{ width: 180 }} />,
)}
</td>
<td className="label" style={{ width: 86 }}>
联系方式:
</td>
<td>
{getFieldDecorator('ownerMobile')(
<Input style={{ width: 180 }} />,
)}
</td>
<td className="label" style={{ width: 86 }}>
审核状态:
</td>
<td>
{getFieldDecorator('auditStatus')(
<Select style={{ width: 180 }}>
{Status.map(b => (
<Option key={b.key} value={b.key}>
{b.name}
</Option>
))}
</Select>,
)}
</td>
<td className="label" style={{ width: 86 }}>
注册平台:
</td>
<td>
{getFieldDecorator('applayfrom', {
initialValue: list[0] ? list[0].code : '',
})(
<Select style={{ width: 180 }}>
{list.map(b => (
<Option key={b.memo} value={b.code}>
{b.cnname}
</Option>
))}
</Select>,
)}
</td>
</tr>
<tr>
<td style={{ textAlign: 'right' }} colSpan={8}>
<Button onClick={this.query} type="primary">
查询
</Button>
<Button onClick={this.resetForm}>重置</Button>
</td>
</tr>
</tbody>
</table>
</Form> */
);
}
resetForm = () => {
this.props.form.resetFields();
};
query = () => {
const values = this.props.form.getFieldsValue();
const data = {};
for (const key in values) {
if (values[key] !== undefined) {
data[key] = values[key];
} else {
data[key] = '';
}
}
this.props.commonAction({ table: { current: 1, conditions: data } });
};
}
const mapState = state => ({
...state[StateName],
});
const mapDispatch = {
commonAction: commonAction(StateName),
};
export default compose(
withStyles(
s,
buttonStyle,
formStyle,
gridStyle,
inputStyle,
iconStyle,
selectStyle,
),
connect(StateName, commonReducer(StateName), mapState, mapDispatch),
Form.create(),
)(QueryForm);
|
import { queryObjToString } from "github-query-validator";
import {
SEARCH_RESULTS,
UPDATE_LICENSE,
UPDATE_FORK_SELECTION,
UPDATE_SEARCH_STATUS
} from "./types";
function parseResponse(repos) {
return repos.map(
({
fork,
stargazers_count,
html_url,
name,
license,
owner,
id,
description
}) => {
return {
isForked: fork,
stars: stargazers_count,
url: html_url,
id,
name,
license,
owner,
description
};
}
);
}
export const handleFormSubmit = (
formValues,
license,
fork,
history
) => dispatch => {
let queryObject = {
// cant add fork here because lib does not validate fork in the object
stars: formValues.stars,
addl: formValues.query
};
// create query string
let queryString =
queryObjToString(queryObject)
.split(" ")
.join("+") +
(license ? `+license:${license}` : "") +
`+fork:${fork ? "only" : "true"}`;
// update query string
history.push({
pathName: "/",
search: `q=${queryString}`
});
dispatch({
type: UPDATE_SEARCH_STATUS,
payload: {
loading: true,
error: false,
searchTiggeredAtLeastOnce: true
}
});
// service call
fetch(`https://api.github.com/search/repositories?q=${queryString}`)
.then(response => {
// dispatch action to hide loader
dispatch({
type: UPDATE_SEARCH_STATUS,
payload: {
loading: false
}
});
return response.json();
})
.then(responseData => {
// dispatch action with parsed search results
dispatch({
type: SEARCH_RESULTS,
payload: parseResponse(responseData.items)
});
})
.catch(() => {
// dispatch service error action
dispatch({
type: UPDATE_SEARCH_STATUS,
payload: {
error: true
}
});
});
};
export const handleDropdownSelect = value => {
return {
type: UPDATE_LICENSE,
payload: value
};
};
export const handleForkCheckboxChange = value => {
return {
type: UPDATE_FORK_SELECTION,
payload: value
};
};
|
'use strict';
/**
* Module Dependencies.
*/
var _ = require('lodash');
var options = ["limit", "skip"],
idRegExp = /^[0-9a-fA-F]{24}$/g,
helper;
module.exports = exports = helper = {};
helper.merge = function(body, query) {
_.merge(body, query, function(a, b) {
if (_.isArray(a)) {
return a.concat(b);
}
});
return body;
};
helper.validateId = function(ObjectID) {
return idRegExp.test(ObjectID);
};
helper.getQueryOptions = function(query) {
var _options = {},
_query = _.clone(query, true);
_query = helper.merge(_query, _query.query);
//removing the merged query
delete _query['query'];
for(var key in _query) {
if(options.indexOf(key) > -1) {
_options[key] = _query[key];
delete _query[key];
}
}
return {query: _query, options: _options};
};
|
const express = require('express');
const router = express.Router();
const Repository = require('../models/repository.js');
router.get('/get', async (req, res) => {
try {
const repositories = await Repository.find({});
return res.status(200).json({ success: true, repositories });
} catch (error) {
return res.status(400).json({ success: false, error });
}
});
module.exports = router;
|
module.exports = function(grunt) {
grunt.initConfig({
pkg : grunt.file.readJSON('package.json'),
cssmin: {
options: {
banner: '/* <%= grunt.template.today("yyyy-mm-dd HH:MM") %> */'
},
combine: {
files: {
'assets/css/publish-min.css':[
'assets/css/reset.css',
'assets/css/style.css',
'assets/css/button/button.css',
'assets/css/leftnav/leftnav.css',
'assets/css/header/header.css',
'assets/css/plug/plug.css',
'assets/css/title/title.css',
'assets/css/table/table.css',
'assets/css/right/right.css',
'assets/css/itemcode/itemcode.css'
]
}
}
},
concat: {
basic_and_extras: {
files: {
'assets/css/publish.css':[
'assets/css/reset.css',
'assets/css/style.css',
'assets/css/button/button.css',
'assets/css/leftnav/leftnav.css',
'assets/css/header/header.css',
'assets/css/plug/plug.css',
'assets/css/title/title.css',
'assets/css/table/table.css',
'assets/css/right/right.css',
'assets/css/itemcode/itemcode.css'
]
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.registerTask('default', ['cssmin', 'concat']);
};
|
exports.questions = [
{
full: 'Twas the night before Christmas',
cloze: 'Christmas'
},
{
full: 'The standard way to create an object prototype is to use an object constructor function',
cloze: 'constructor'
},
{
full: 'With a constructor function, you can use the new keyword to create new objects from the same prototype',
cloze: 'new'
},
{
full: 'The JavaScript prototype property allows you to add new properties to an existing prototype',
cloze: 'prototype'
},
{
full: 'Use an inline function with a regular expression to avoid for loops',
cloze: 'inline'
},
{
full: 'JavaScript is a programming language that adds interactivity to your website',
cloze: 'interactivity'
},
{
full: 'The JavaScript prototype property also allows you to add new methods to an existing prototype',
cloze: 'existing'
},
{
full: 'You should always wear sunscreen when you are outside',
cloze: 'sunscreen'
},
{
full: 'In JavaScript, most things are objects',
cloze: 'objects'
},
{
full: 'Ryan Dahl is a software engineer and the inventor of Node.js',
cloze: 'Ryan Dahl'
}
]
|
import React from 'react';
import { Navbar } from 'react-bootstrap';
import { Link } from 'react-router-dom';
//component to create the home button which links to the app's homepage. visible on all app screens
const HomeButton= () => (
<Navbar>
<Navbar.Header>
<Navbar.Brand>
<Link className="homeButton" to="/">
Home
</Link>
</Navbar.Brand>
</Navbar.Header>
</Navbar>
);
export default HomeButton;
|
import React, {Component} from 'react';
import './NERTagging.css';
class NERTagging extends Component {
state = {
visible: false,
};
componentDidMount() {
document.addEventListener('contextmenu', this._handleContextMenu);
document.addEventListener('click', this._handleClick);
document.addEventListener('scroll', this._handleScroll);
};
componentWillUnmount() {
document.removeEventListener('contextmenu', this._handleContextMenu);
document.removeEventListener('click', this._handleClick);
document.removeEventListener('scroll', this._handleScroll);
}
_handleContextMenu = (event) => {
event.preventDefault();
this.setState({ visible: true });
const clickX = event.clientX;
const clickY = event.clientY;
// const screenW = window.innerWidth;
// const screenH = window.innerHeight;
const parent = this.ner.parentElement;
const parent2 = parent.parentElement;
const parent3 = parent2.parentElement;
const OL = parent3.offsetLeft;
const OT = parent3.offsetTop;
const nerW = this.ner.offsetWidth;
const nerH = this.ner.offsetHeight;
// const wrapW = this.props.wrap.offsetWidth;
// const wrapH = this.props.wrap.offsetHeight;
// const right = (screenW - clickX) > nerW;
// const right = (screenW - clickX) > 900;
// const left = !right;
// const top = (screenH - clickY) > nerH;
// const top = (screenH - clickY) > 857.4
// const bottom = !top;
// if (right) {
// this.ner.style.left = `${clickX - screenW/2 + 450}px`;
// }
// if (left) {
// this.ner.style.left = `${clickX - screenW/2 + 450}px`;
// }
// if (top) {
// this.ner.style.top = `${clickY - screenH/2 + 428.2}px`;
// }
// if (bottom) {
// this.ner.style.top = 0
// }
// if ( clickX > OL ){
// this.ner.style.left = `${clickX - OL}px`
// }else{
// this.ner.style.left = `${-OL + clickX}px`
// }
if(this.props.selectedText === ''){
this.ner.style.left = `${clickX - OL}px`
this.ner.style.top = `${clickY - OT}px`
}else{
this.ner.style.left = `${clickX - OL -nerW*1.5}px`
this.ner.style.top = `${clickY - OT -nerH*2}px`
}
// this.ner.style.left = `${clickX - OL}px`
// this.ner.style.top = `${clickY - OT}px`
};
_handleClick = (event) => {
const { visible } = this.state;
const wasOutside = !(event.target.contains === this.ner);
if (wasOutside && visible) this.setState({ visible: false, });
};
_handleScroll = () => {
const { visible } = this.state;
if (visible) this.setState({ visible: false, });
};
render() {
const { visible } = this.state;
var nerList = this.props.nerList;
return(visible || null) &&
<div ref={ref => {this.ner = ref}} className="contextMenu">
<div className="contextMenu--option contextMenu--option__disabled">select NER</div>
<div className="contextMenu--separator" />
{nerList !== null && nerList !== undefined &&
nerList.map((data, i)=>{
return(
<div className="contextMenu--option" key={i} onClick={this.props.nerMatch.bind(this, data.parameter)}>{data.parameter}</div>
)
})
}
<div className="contextMenu--separator" />
<div className="contextMenu--option" onClick={this.props.nerMatch.bind(this, '')}>Remove NER Tag</div>
</div>
};
};
export default NERTagging;
|
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound',
waitOn: function() {
return [Meteor.subscribe('notifications')]
}
});
BookmarksListController = RouteController.extend({
template: 'bookmarksList',
increment: 50,
bookmarksLimit: function() {
return parseInt(this.params.bookmarksLimit) || this.increment;
},
findOptions: function() {
return {sort: this.sort, limit: this.bookmarksLimit()};
},
subscriptions: function() {
this.bookmarksSub = Meteor.subscribe('bookmarks', this.findOptions());
},
bookmarks: function() {
return Bookmarks.find({}, this.findOptions());
},
data: function() {
var self = this;
return {
bookmarks: self.bookmarks(),
ready: self.bookmarksSub.ready,
nextPath: function() {
if (self.bookmarks().count() === self.bookmarksLimit())
return self.nextPath();
}
};
}
});
BookmarksController = BookmarksListController.extend({
sort: {submitted: -1, _id: -1},
nextPath: function() {
return Router.routes.newPosts.path({postsLimit: this.postsLimit() + this.increment})
}
});
/*BestPostsController = PostsListController.extend({
sort: {votes: -1, submitted: -1, _id: -1},
nextPath: function() {
return Router.routes.bestPosts.path({postsLimit: this.postsLimit() + this.increment})
}
}); */
Router.route('/', {
name: 'home',
controller: BookmarksController
});
Router.route('/new/:postsLimit?', {name: 'newPosts'});
Router.route('/best/:postsLimit?', {name: 'bestPosts'});
Router.route('/posts/:_id', {
name: 'postPage',
waitOn: function() {
return [
Meteor.subscribe('singlePost', this.params._id),
Meteor.subscribe('comments', this.params._id)
];
},
data: function() { return Posts.findOne(this.params._id); }
});
Router.route('/posts/:_id/edit', {
name: 'postEdit',
waitOn: function() {
return Meteor.subscribe('singlePost', this.params._id);
},
data: function() { return Posts.findOne(this.params._id); }
});
Router.route('/submit', {name: 'addBookmark'});
var requireLogin = function() {
if (! Meteor.user()) {
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
this.render('accessDenied');
}
} else {
this.next();
}
}
Router.onBeforeAction('dataNotFound', {only: 'postPage'});
Router.onBeforeAction(requireLogin, {only: 'addBookmark'});
|
import { createStore, applyMiddleware, compose } from 'redux';
import persistState from 'redux-localstorage';
import rootReducer from './reducers';
const initialState = {};
const middleware = [];
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const composedEnhancers = composeEnhancers(
applyMiddleware(...middleware),
persistState(['cart', 'sorting'], { key: 'flowCart' })
);
const store = createStore(rootReducer, initialState, composedEnhancers);
export default store;
|
import createQueue from 'shared/bull/create-queue';
export const addQueue = (name, data, opts) => {
const worker = createQueue(name);
return worker.add({ ...data }, { ...opts });
};
export const createJob = (
name, // name of the job
) => {
try {
console.log(`New job initiated: ${name}`);
return addQueue(name, {
removeOnComplete: true,
removeOnFail: true,
attempts: 1
});
} catch (err) {
console.log(`🚨 Error initiating new job: \n${err}`);
}
};
|
const API_DOMAIN = "https://tny.ie/api"
export const APIReq = async (path, method, body) => {
const apiKey = localStorage.getItem("token")
let request
if (apiKey === null) {
request = await fetch(API_DOMAIN + path, {
method: method,
mode: 'cors',
headers: {
'Content-Type': (body != {}) ? 'application/json':'text/plain',
},
body: (method === 'GET') ? null:(!body) ? null:JSON.stringify(body)
})
} else {
request = await fetch(API_DOMAIN + path, {
method: method,
mode: 'cors',
headers: {
'Content-Type': (body != {}) ? 'application/json':'text/plain',
'Authorization': apiKey
},
body: (method === 'GET') ? null:(!body) ? null:JSON.stringify(body)
})
}
return request.json()
}
export * from './login'
export * from './links'
|
import React, { Component } from 'react';
import {
Form, Card, Row, Col,
} from 'react-bootstrap';
class RadioCheckInPanel extends Component {
constructor(props, context) {
super(props, context);
this.state = {
disabledComboBox: false,
};
}
onChangeTeste = (e, setFieldValue) => {
setFieldValue(e.target.name, e.target.value);
this.setState({ disabledComboBox: e.target.value });
};
render() {
const {
field,
config,
form: { setFieldValue },
} = this.props;
const { disabledComboBox } = this.state;
field.value = undefined;
return (
<Form.Group>
<Card className={config.center ? 'text-center' : ''}>
<Card.Header>{config.title}</Card.Header>
<Card.Body>
{config.radioCheckFields
&& config.radioCheckFields.map(fi => (
<Row key={`key-${fi.name}`} className="mb-3">
<Col xs={3}>
<Form.Check
{...field}
inline
type={fi.type}
id={fi.name}
name={config.name}
value={fi.value}
label={fi.description}
disabled={fi.disabled || false}
onChange={e => this.onChangeTeste(e, setFieldValue)}
/>
</Col>
{fi.combobox && (
<Col xs={6}>
<Form.Control
as="select"
name={fi.combobox.name}
disabled={disabledComboBox !== fi.value.toString()}
>
{fi.combobox.comboxField.map(cb => (
<option key={`key-${cb.value}`} value={cb.value}>
{cb.description}
</option>
))}
</Form.Control>
</Col>
)}
</Row>
))}
</Card.Body>
</Card>
</Form.Group>
);
}
}
export default RadioCheckInPanel;
|
function getCookie(key)
{
key += '=';
let decoded_cookie = decodeURIComponent(document.cookie);
let cookie_array = decoded_cookie.split(';');
for (let iii = 0; iii < cookie_array.length; ++iii) {
let each_entry = cookie_array[iii];
while (each_entry.charAt(0) == ' ') each_entry = each_entry.substring(1);
if (each_entry.indexOf(key) == 0)
return each_entry.substring(key.length, each_entry.length);
}
return '';
}
|
import { RestService } from '../../services/rest';
import { serviceOptions } from '../../services/serviceOptions';
export function pyrest(options) {
var inst = new RestService();
serviceOptions(inst, 'pyrest', options);
inst.getCurrentBlockHeight = getCurrentBlockHeight;
return inst;
}
function getCurrentBlockHeight () {
return this.$get('status', null, { transformResponse: transformResponse });
function transformResponse (response) {
return {
height: response.data && response.data.current_height,
version: response.data && response.data.version
};
}
}
|
import styled from 'styled-components';
export const StyledSection = styled.section``;
export const StyledFirstSection = styled.section`
background-image: url('https://woojoo.s3-us-west-1.amazonaws.com/bg4.webp');
height: 80vh;
background-repeat: no-repeat;
background-size: cover;
display: flex;
flex-direction: column;
align-items: end;
padding-left: 2rem;
width: 80%;
margin: auto;
margin-top: 2%;
`;
export const StyledGrayLayer = styled.section`
// background: rgba(0.1, 0.1, 0.1, 0.4);
height: 80vh;
width: 100%;
background-repeat: no-repeat;
background-size: cover;
display: flex;
align-items: flex-start;
`;
export const StyledText = styled.div`
margin: 0;
padding: 0;
font-size: 2.5rem;
color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
margin-top: 8%;
`;
export const StyledButton = styled.button`
background: transparent;
border: ${({ att }) =>
att ? '2px solid rgba(0,0,0,0.8)' : '2px solid white'};
font-size: 1.5rem;
margin: 1rem 0;
padding: 1rem;
cursor: pointer;
color: ${({ att }) => (att ? 'rgba(0,0,0,0.8)' : 'white')};
&:hover {
background: rgba(0, 0, 0, 0.2);
}
a {
text-decoration: none;
}
`;
export const StyledSubSection = styled.section`
margin-top: 5rem;
display: flex;
justify-content: center;
align-items: center;
`;
export const StyledText2 = styled.div`
color: ${({ att2, att3 }) => (att2 || att3 ? 'white' : 'rgba(0,0,0,0.8)')};
font-weight: bold;
font-size: ${({ att3 }) => (att3 ? '2rem' : '4rem')};
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
section {
font-size: 2rem;
}
`;
export const StyledImage = styled.img`
margin: 5rem;
`;
|
const modes = { bus: "bus", tube: "tube" };
const maxFare = 3.2;
class Trip {
constructor(card) {
this.zonesTravelled = [];
this.fare = 3.2;
this.card = card;
this.mode = "";
}
enterFrom(station, mode) {
if (this.card.balance > this.fare) {
this.zonesTravelled.push(...findZone(station));
this.mode = mode;
console.log(
`--------------\nStarting ${this.mode.toUpperCase()} from ${station.toUpperCase()}`
);
return 1;
} else return 0;
}
exitAt(station) {
console.log(
`Exiting ${this.mode.toUpperCase()} at ${station.toUpperCase()}`
);
if (this.mode === "bus") {
this.fare = 1.8;
this.zonesTravelled = [];
this.card.debitAmount(this.fare);
return;
} else {
this.zonesTravelled.push(...findZone(station));
this.fare = this.calculateFare();
this.zonesTravelled = [];
this.card.debitAmount(this.fare);
}
}
calculateFare() {
let uniqueZones = [...new Set(this.zonesTravelled)];
// console.log("uniqueZones: ", uniqueZones);
if (uniqueZones.length === 3) {
// All three zones
return maxFare;
}
if (uniqueZones.includes(1) && !uniqueZones.includes(2)) {
// Anywhere in Zone 1
return 2.5;
}
if (
uniqueZones.includes(2) &&
uniqueZones.includes(2) &&
uniqueZones.length === 2
) {
// Any one zone outside zone 1
// can happen only within zone 2
return 2;
}
if (uniqueZones.includes(1) && uniqueZones.length >= 2) {
// Any two zones including zone 1
return 3;
}
if (!uniqueZones.includes(1) && uniqueZones.length >= 2) {
// Any two zones excluding zone 1
return 2.25;
} else {
return maxFare;
}
}
}
const findZone = station => {
switch (station) {
case "Holborn":
return [1];
case "Earl’s Court":
return [1, 2];
case "Hammersmith":
return [2];
case "Wimbledon":
return [3];
default:
return [19];
}
};
module.exports = Trip;
|
/* global describe, it, expect */
/* jshint expr: true */
var WindowsLiveStrategy = require('../lib/strategy')
, chai = require('chai');
describe('Strategy', function() {
describe('constructed', function() {
var strategy = new WindowsLiveStrategy({
clientID: 'ABC123',
clientSecret: 'secret'
},
function() {});
it('should be named windowslive', function() {
expect(strategy.name).to.equal('windowslive');
});
})
describe('constructed with undefined options', function() {
it('should throw', function() {
expect(function() {
var strategy = new WindowsLiveStrategy(undefined, function(){});
}).to.throw(Error);
});
})
describe('authorization request with parameters', function() {
var strategy = new WindowsLiveStrategy({
clientID: 'ABC123',
clientSecret: 'secret',
response_type: 'code',
callbackURL: 'http://mockuri.com'
}, function() {});
var url;
before(function(done) {
chai.passport.use(strategy)
.redirect(function(u) {
url = u;
done();
})
.req(function(req) {
req.session = {};
})
.authenticate({ prompt: 'select_account', login_hint: 'abc@mockdomain.com', locale: 'fr-CA', display: 'popup', ignore: 'this' });
});
it('should be redirected', function() {
expect(url).to.equal('https://login.live.com/oauth20_authorize.srf?locale=fr-CA&display=popup&prompt=select_account&login_hint=abc%40mockdomain.com&response_type=code&redirect_uri=http%3A%2F%2Fmockuri.com&client_id=ABC123');
});
});
});
|
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
class Test extends Component{
constructor(props){
super(props);
this.onDellEvent = this.onDellEvent.bind(this);
}
onDellEvent(event){
this.props.onDell(event);
}
render(){
return(
<div>{this.props.value}
<button onClick={this.onDellEvent}>btn</button>
</div>
)
}
}
export default Test;
|
import React,{useState} from 'react';
import '../index.css';
import axios from 'axios';
import { Card, Form, Button, Alert,Nav, Navbar,NavLink} from 'react-bootstrap';
import {
Redirect
} from "react-router-dom";
import logo from "./images/freelancerlogo.png";
function Login(props){
const[state,setState]=useState({username:"",
password:"",
error:false});
return (
<>
<Navbar collapseOnSelect expand="lg">
<Navbar.Brand href="./">
<img
alt=""
src={logo}
width="140"
height="40"
className="d-inline-block align-top"
/>
</Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="mr-auto">
<NavLink to="/hire" exact>
{" "}
How it Works
</NavLink>
<NavLink to="/browse"> Browse Jobs </NavLink>
</Nav>
<Nav>
<NavLink to="/signup" exact>
{" "}
Sign up{" "}
</NavLink>
<Button variant="outline-primary" className="button11" href="/Postaproject">
{" "}
Post a Project{" "}
</Button>
</Nav>
</Navbar.Collapse>
</Navbar>
<Card className="Card">
<Card.Body>
<Card.Title>
<Alert variant="primary"> Login Here </Alert>
</Card.Title>
{
state.error ? (<Alert variant="danger"> Username/Password incorrect </Alert>) : null
}
{
props.loggedin ? (<Redirect to="/dashboard"></Redirect> ) : null
}
<Form className="signupform" onSubmit={(e)=>{
e.preventDefault();
setState({...state,error:false})
axios.post("http://FreelancerLaravel.test/api/login",{
username: state.username,
password: state.password
}).then((response)=>{
localStorage.setItem("token", response.data.token);
props.loginattempt();
setState({...state, loggedin:true})
}).catch(()=>{
setState({...state, error:true})
});
}}>
<Form.Label>Username</Form.Label>
<Form.Control type="text" placeholder="Enter your Username" value={state.username} onChange={(e)=>{
setState({...state, username:e.target.value})
}}/> <br/>
<Form.Label>Password</Form.Label>
<Form.Control type="password" placeholder="Enter your Password" value={state.password} onChange={(e)=>{
setState({...state, password:e.target.value})
}}/> <br/>
<Button disabled={!state.username || !state.password} variant="primary" type="submit" block>
Login
</Button>
</Form>
</Card.Body>
</Card>
</>
)
}
export default Login;
|
// import React from 'react'
import ProjectItem from "./ProjectItem";
import projects from "../data.js";
function ProjectList() {
// const projectItems = projects.map(project => {
// return (
// <ProjectItem
// name={project.name}
// about={project.about}
// image={project.image}
// phase={project.phase}
// link={project.link}
// />
// )
// })
// const projectItems = projects.map(project => {
// return (
// <ProjectItem project={project} />
// )
// })
const projectItems = projects.map(project => {
return (
<ProjectItem key={project.id} {...project} />
)
})
console.log(projects)
return (
<div>
{projectItems}
</div>
)
}
export default ProjectList
|
addLoadEvent(exercise);
function exercise() {
var btn1 = document.getElementById('btn1');
var bt2 = document.getElementById('btn2');
var label = document.getElementById('label').getElementsByTagName('h1')[0];
if(btn1) {
btn1.addEventListener('click', function() {
moveEle('picwall', {'desX': -773, 'desY': 0});
moveEle('shoppingMall', {'desX': 0, 'desY': 0});
label.textContent = '购物网';
btn1.style.display = 'none';
btn2.style.display = 'inline-block';
})
}
if(btn2 && btn2.style.display != 'none') {
btn2.addEventListener('click', function() {
moveEle('picwall', {'desX': 0, 'desY': 0});
moveEle('shoppingMall', {'desX': 773, 'desY': 0});
label.textContent = '照片墙';
btn2.style.display = 'none';
btn1.style.display = 'inline-block';
});
}
}
function addLoadEvent(func) {
var old_load = window.onload;//window.onload属性用一个old_onload指向;
if(typeof old_load !== "function") {//判断old_load是否指向一个函数;
window.onload = func;//不指向任何函数,则将新函数(即参数)绑定到加载事件上;
}
else { //指向某函数,则添加新函数到加载事件中;
window.onload = function() {
old_load();
func();
}
}
}
|
import { Notify } from 'quasar'
// import { firestoreAction } from 'vuexfire'
// import User from '../../models/User.js'
// import { createPusherUser } from '../../services/pusher'
// export const addUserToUsersCollection = async (state, userRef) => {
// const user = new User({
// email: state.email
// })
// try {
// await userRef.set(user)
// return user
// } catch (err) {
// return `[addUserToUsersCollection] Error: ${err}`
// }
// }
// export const createNewUser = async function ({ dispatch, commit }, data) {
// const $fb = this.$fb
// const { email, password } = data
// commit('common/setLoading', true, { root: true })
// try {
// const fbAuthResponse = await $fb.createUserWithEmail(email, password)
// const id = fbAuthResponse.user.uid
// const userRef = $fb.userRef('users', id)
// const newUserTransaction = await Promise.all([
// addUserToUsersCollection({ email }, userRef),
// createPusherUser(id, email)
// ])
// await dispatch('common/initUserChatServices', id, { root: true })
// const user = newUserTransaction[0]
// commit('user/setCurrentUserData', user, { root: true })
// commit('common/setLoading', false, { root: true })
// return user
// } catch (err) {
// Notify.create({
// message: `An error as occured: ${err}`,
// color: 'negative'
// })
// commit('common/setLoading', false, { root: true })
// }
// }
export const signInWithGoogle = async function ({ commit }) {
const $fb = this.$fb
try {
const user = await $fb.loginWithGoogle()
return user
} catch (err) {
Notify.create({
message: `An error as occured: ${err}`,
color: 'negative'
})
}
}
export const forgotPassword = async function ({ commit }, email) {
const $fb = this.$fb
commit('common/setLoading', true, { root: true })
try {
await $fb.resetPassword(email)
commit('common/setLoading', false, { root: true })
Notify.create({
message: 'An email was sent to the email you registered with to reset your password',
color: 'positive'
})
} catch (err) {
Notify.create({
message: `An error as occured: ${err}`,
color: 'negative'
})
commit('common/setLoading', false, { root: true })
}
}
export const loginUser = async function ({ commit, dispatch }, payload) {
const $fb = this.$fb
const { email, password } = payload
commit('common/setLoading', true, { root: true })
try {
const res = await $fb.loginWithEmail(email, password)
commit('common/setLoading', false, { root: true })
return res.user
} catch (err) {
Notify.create({
message: `An error as occured: ${err}`,
color: 'negative'
})
commit('common/setLoading', false, { root: true })
}
}
export const logoutUser = async function ({ commit }, id) {
// await firestoreAction(({ unbindFirestoreRef }) => { unbindFirestoreRef('users', id) })
// await firestoreAction(({ unbindFirestoreRef }) => { unbindFirestoreRef('users') })
// await firestoreAction(({ unbindFirestoreRef }) => { unbindFirestoreRef('contacts') })
await this.$fb.logoutUser()
// commit('common/setLeftDrawerOpen', false, { root: true })
}
export const sendEmailVerification = async function ({ commit }) {
const $fb = this.$fb
try {
await $fb.sendEmailVerification()
return true
} catch (err) {
Notify.create({
message: `An error as occured: ${err}`,
color: 'negative'
})
return (false)
}
}
|
var tnt_theme_track_buttons = function() {
var factor = 0.2;
var gBrowser;
var path = tnt.utils.script_path("buttons.js");
var theme = function(gB, div) {
gBrowser = gB;
var control_panel = d3.select(div)
.append("div")
.attr("id", "tnt_buttons_controlPanel")
.style("margin-left", "auto")
.style("margin-right", "auto")
.style("width", "70%");
var left_button = control_panel
.append("button")
.attr("title", "go left")
.on("click", theme.left);
left_button
.append("img")
.attr("src", path + "../../pics/glyphicons_216_circle_arrow_left.png");
var zoomIn_button = control_panel
.append("button")
.attr("title", "zoom in")
.on("click", theme.zoomIn)
zoomIn_button
.append("img")
.attr("src", path + "../../pics/glyphicons_191_circle_minus.png");
var zoomOut_button = control_panel
.append("button")
.attr("title", "zoom out")
.on("click", theme.zoomOut);
zoomOut_button
.append("img")
.attr("src", path + "../../pics/glyphicons_190_circle_plus.png");
var right_button = control_panel
.append("button")
.attr("title", "go right")
.on("click", theme.right);
right_button
.append("img")
.attr("src", path + "../../pics/glyphicons_217_circle_arrow_right.png");
var draggability_button = control_panel
.append("button")
.attr("title", "Disable dragging")
.on("click",theme.toggle_draggability);
draggability_button
.append("img")
.attr("id", "tnt_buttons_draggability") // WARNING: This doesn't support independent multiple instances of the control panel
.attr("src", path + "../../pics/noHand-cursor-icon.png")
.attr("width", "20px")
.attr("height", "20px");
var buttons_sensibility = control_panel
.append("span")
.style("font-size" , "12px")
.text("Buttons sensibility: 0");
buttons_sensibility
.append("input")
.attr("type", "range")
.attr("min", "0")
.attr("max", "1.0")
.attr("step", "0.1")
.attr("value", "0.2")
.on("change", function(d){theme.set_factor(this.value)});
buttons_sensibility
.append("text")
.text("1");
var gene_track = tnt.track()
.height(200)
.display(tnt.track.feature.gene()
.foreground_color("#586471")
)
.data(tnt.track.data.gene());
gB(div);
gB.add_track(gene_track)
gB.start();
};
theme.set_factor = function(val) {
factor = parseFloat(val);
};
theme.toggle_draggability = function() {
var div_id = "tnt_buttons_draggability";
if (gBrowser.allow_drag()) {
d3.select("#" + div_id)
.attr("src", path + "../../pics/noHand-cursor-icon.png")
.attr("title", "Enable dragging");
gBrowser.allow_drag(false);
} else {
d3.select("#" + div_id)
.attr("src", path + "../../pics/Hand-cursor-icon.png")
.attr("title", "Disable dragging");
gBrowser.allow_drag(true);
}
};
theme.left = function() {
gBrowser.move_left(1+factor);
};
theme.right = function() {
gBrowser.move_right(1+factor);
};
theme.zoomIn = function() {
gBrowser.zoom(1+factor);
};
theme.zoomOut = function() {
gBrowser.zoom(1/(1+factor));
};
theme.start = function() {
gBrowser.start();
};
return theme;
};
|
/* eslint-disable */
const { spawn } = require('child_process');
const { Buffer } = require('buffer');
const ls = spawn(/^win/.test(process.platform) ? 'npx.cmd' : 'npx', [
'craco',
'start',
]);
ls.stdout.on('data', data => {
console.log(`${data}`);
if (data.toString().includes('To ignore, add') || data.toString().includes('successfully')) {
console.log(Buffer.from('VGltZTJjb2RlIQ==', 'base64').toString('binary'));
}
});
ls.stderr.on('ERROR', data => {
console.log(`stderr: ${data}`);
});
ls.on('error', error => {
console.log(`error: ${error.message}`);
});
|
//index.js
//获取应用实例
const app = getApp()
Page({
data: {
scrollTop: 100,
array: [{
msg:'你好',
time:'yesterday',
text:'Anna',
icon:'../../image/1.jpg'
},{
msg: '在吗',
time: 'today',
text: 'Bill',
icon: '../../image/2.jpg'
}, {
msg: '请问你',
time: 'Sun',
text: 'Klia',
icon: '../../image/3.jpg'
}, {
msg: '你好',
time: '11/17/12',
text: 'Home',
icon: '../../image/4.jpg'
}, {
msg: '吃饭了吗',
time: 'yesterday',
text: 'Koli',
icon: '../../image/5.jpg'
},
{
msg: '好久不见',
time: '8:45AM',
text: 'Jkil',
icon: '../../image/6.jpg'
},
{
msg: '你好',
time: 'yesterday',
text: 'Fiki',
icon: '../../image/1.jpg'
},
{
msg:' 哈哈哈',
time: '9:00PM',
text: 'Sili',
icon: '../../image/2.jpg'
},
{
msg: '见到你真高兴',
time: 'yesterday',
text: 'Dava',
icon: '../../image/3.jpg'
},
],
},
imageError: function (e) {
console.log('image3发生error事件,携带值为', e.detail.errMsg)
},
onLoad: function () {
},
onShow: function () {
},
onHide: function(){
},
onUnload:function(){
},
onReachBottom:function(){
},
loadMore:function () {
var that=this;
wx.showLoading({
title:"正在加载..."
})
that.setData({
array: that.data.array.concat
([{
msg: '你好',
time: 'yesterday',
text: 'Anna',
icon: '../../image/1.jpg'
}, {
msg: '在吗',
time: 'today',
text: 'Bill',
icon: '../../image/2.jpg'
}, {
msg: '请问你',
time: 'Sun',
text: 'Klia',
icon: '../../image/3.jpg'
}, {
msg: '你好',
time: '11/17/12',
text: 'Home',
icon: '../../image/4.jpg'
}, {
msg: '吃饭了吗',
time: 'yesterday',
text: 'Koli',
icon: '../../image/5.jpg'
},
{
msg: '好久不见',
time: '8:45AM',
text: 'Jkil',
icon: '../../image/6.jpg'
},
{
msg: '你好',
time: 'yesterday',
text: 'Fiki',
icon: '../../image/1.jpg'
},
{
msg:'哈哈哈',
time: '9:00PM',
text: 'Sili',
icon: '../../image/2.jpg'
},
{
msg: '见到你真高兴',
time: 'yesterday',
text: 'Dava',
icon: '../../image/3.jpg'
},
])
})
setTimeout(function(){
wx.hideLoading()
},1000)
}
})
|
/**
*
* @author Anass Ferrak aka " TheLordA " <ferrak.anass@gmail.com>
* GitHub repo: https://github.com/TheLordA/Instagram-Clone
*
*/
import React, { useState, useContext } from "react";
import { Link, useHistory } from "react-router-dom";
import AuthenticationContext from "../contexts/auth/Auth.context";
import { FETCH_USER_DATA } from "../contexts/types.js";
import { LOGIN_URL } from "../config/constants";
import Copyright from "../components/Copyight";
import { EmailRegex } from "../utils/regex";
import axios from "axios";
// Material-UI Components
import Button from "@material-ui/core/Button";
import CssBaseline from "@material-ui/core/CssBaseline";
import TextField from "@material-ui/core/TextField";
import Grid from "@material-ui/core/Grid";
import Box from "@material-ui/core/Box";
import Typography from "@material-ui/core/Typography";
import { makeStyles } from "@material-ui/core/styles";
import Container from "@material-ui/core/Container";
import Alert from "@material-ui/lab/Alert";
// General Styles
const useStyles = makeStyles((theme) => ({
Logo: {
fontFamily: "Grand Hotel, cursive",
margin: "0px 0px 20px 0px",
},
paper: {
marginTop: "50px",
display: "flex",
flexDirection: "column",
alignItems: "center",
},
image: {
backgroundSize: "cover",
backgroundColor: "#fafafa",
backgroundImage: "url(https://source.unsplash.com/random)",
backgroundRepeat: "no-repeat",
backgroundPosition: "center",
height: "100vh",
},
form: {
width: "100%", // Fix IE 11 issue.
marginTop: theme.spacing(1),
},
submit: {
margin: theme.spacing(2, 0, 2),
},
}));
const Login = () => {
const { dispatch } = useContext(AuthenticationContext);
const history = useHistory();
const classes = useStyles();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [formatValidation, setFormatValidation] = useState(false);
const [authValidation, setAuthValidation] = useState(false);
const handleInputChanges = (e) => {
switch (e.target.name) {
case "email":
setEmail(e.target.value);
break;
case "password":
setPassword(e.target.value);
break;
default:
break;
}
};
const handlePostData = () => {
// the Regex email validation was token from : https://emailregex.com/
if (EmailRegex.test(email)) {
axios.post(LOGIN_URL, { password, email })
.then((res) => {
const data = res.data;
if (data.error) {
setFormatValidation(false);
setAuthValidation(true);
} else {
// we store our generated token in order to use it to access protected endpoints
localStorage.setItem("jwt", data.token);
// we also store the user details
localStorage.setItem("user", JSON.stringify(data.user));
dispatch({ type: FETCH_USER_DATA, payload: data.user });
// we redirect the user to home page
history.push("/");
}
})
.catch((err) => {
// that should be changed in Production
// TODO : Make an error handler
console.log(err);
});
} else {
setAuthValidation(false);
setFormatValidation(true);
}
};
return (
<Grid container>
<Grid className={classes.image} item sm={4} md={6} />
<Grid item xs={12} sm={8} md={6}>
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Typography className={classes.Logo} variant="h2" gutterBottom>
Instagram Clone
</Typography>
{formatValidation ? (
<Alert variant="outlined" severity="error">
Invalid Email format — check it out!
</Alert>
) : null}
{authValidation ? (
<Alert variant="outlined" severity="error">
Invalid given Email/Password — check it out!
</Alert>
) : null}
<form className={classes.form} noValidate>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
// autoComplete="email"
autoFocus
value={email}
onChange={handleInputChanges}
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
autoComplete="current-password"
value={password}
onChange={handleInputChanges}
/>
<Button
fullWidth
variant="outlined"
color="primary"
className={classes.submit}
disabled={email !== "" && password !== "" ? false : true}
onClick={handlePostData}
>
Sign In
</Button>
<Grid container>
<Grid item xs>
<Link to="/reset" style={{ textDecoration: "none" }}>
Forgot password?
</Link>
</Grid>
<Grid item>
<Link to="/signup" style={{ textDecoration: "none" }}>
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</form>
</div>
<Box mt={8}>
<Copyright />
</Box>
</Container>
</Grid>
</Grid>
);
};
export default Login;
|
angular.module('iCanHelp')
.directive('emailUnique', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attr, ctrl) {
ctrl.$parsers.push(function (viewValue) {
// set it to true here, otherwise it will not
// clear out when previous validators fail.
ctrl.$setValidity('uniqueEmail', true);
if (ctrl.$valid) {
// set it to false here, because if we need to check
// the validity of the email, it's invalid until the
// AJAX responds.
ctrl.$setValidity('checkingEmail', false);
// now do your thing, chicken wing.
if (viewValue !== "" && typeof viewValue !== "undefined") {
$http.get('/api/account/emailUnique/' + viewValue).success(function () {
ctrl.$setValidity('uniqueEmail', true);
ctrl.$setValidity('checkingEmail', true);
}).error(function () {
ctrl.$setValidity('uniqueEmail', false);
ctrl.$setValidity('checkingEmail', true);
});
} else {
ctrl.$setValidity('uniqueEmail', false);
ctrl.$setValidity('checkingEmail', true);
}
}
return viewValue;
});
}
}
});
|
/*
* Controller
*************/
// Import module
// const dateformat = require('datformat')
// Import de model
const User = require('../DB/models/User')
const bcrypt = require('bcrypt')
module.exports = {
// Method put
editOne: (req, res) => {
let boolAdmin = false
let boolVerified = false
let boolBan = false
if (req.body.isAdmin === 'on') boolAdmin = true;
if (req.body.isBan === 'on') boolBan = true;
if (req.body.isVerified === 'on') boolVerified = true;
// console.log(req.body);
User
.findByIdAndUpdate(req.params.id, {
isAdmin: boolAdmin,
isVerified: boolVerified,
isBan: boolBan
}, (err, data) => {
if (err) console.log(err)
// res.json(data)
res.redirect('/admin')
})
},
// Method delete one
deleteOne: (req, res) => {
console.log("Delete User: ", req.params.id)
User
.deleteOne({
// On va venir chercher parmis tout les _id celui égale à notre req.params (id recupéré dans l'URL)
_id: req.params.id
}, (err) => {
// Si nous avons pas d'erreur alors on redirige
if (err) console.log(err)
// Sinon on renvoit l'err
// res.json({
// succes: req.params.id + '// à bien été supprimer'
// })
res.redirect('/admin')
})
},
// logout: (req, res) => {
// req.session.destroy(() => {
// res.clearCookie('cookie-sess')
// console.log(req.session)
// res.redirect('/')
// })
// }
}
|
// Code generated by coz. DO NOT EDIT.
/**
* Done page of the-components
* @module the-done
*/
'use strict'
import TheDone from './TheDone'
import TheDoneStyle from './TheDoneStyle'
export {
TheDone,
TheDoneStyle,
}
|
import { convertPercentHrToTime } from "../helpers/convertPercentHrToTime";
test("Convert the hours work to a workable time input", () => {
expect(convertPercentHrToTime(8)).toBe("08:00");
expect(convertPercentHrToTime(8.5)).toBe("08:27");
expect(convertPercentHrToTime(10.6)).toBe("10:33");
expect(convertPercentHrToTime(14.1)).toBe("14:03");
});
|
import Config from './config.js';
export default class Report {
constructor(instance) {
this.JSON = {};
this.instance = instance;
this.canvas = window.canvas || document.querySelector('#canvas');
}
create() {
this.JSON = {
filename: Config.appname,
data: {}
};
this.canvas.querySelectorAll('.node').forEach(el => {
this.JSON.data[el.dataset.id] = {
id: el.dataset.id,
//data: el.firstChild.innerText,
//data: el.dataset.data ? JSON.parse(el.dataset.data) : el.querySelector('.node_label').innerText,
data: JSON.parse(el.dataset.data),
nodeName: el.dataset.nodeName || null,
type: el.dataset.type,
suggestions: [],
x: parseInt(el.style.left, 10),
y: parseInt(el.style.top, 10),
};
if (typeof this.JSON.data[el.dataset.id].data.params == 'string') {
this.JSON.data[el.dataset.id].data.params = JSON.parse(this.JSON.data[el.dataset.id].data.params);
}
});
this.instance.getConnections().forEach((i, c) => {
this.JSON.data[i.sourceId].suggestions.push({
text: i.getLabel(),
target: i.targetId
});
});
this.JSON.filename = Config.toolbar.filename.innerText || Config.appname;
//Config.panel.output.innerHTML = this._syntaxHighlight(this.JSON);
this.save();
}
get data() {
return this.JSON
}
set data(newData) {
this.JSON = newData;
this.save();
this.instance.repaintEverything();
}
view() {
Config.panel.output.innerHTML = this._syntaxHighlight(this.JSON);
}
save() {
//console.log(this.JSON.filename);
localStorage.setItem(Config.storageScenarionName, JSON.stringify(this.JSON));
}
_syntaxHighlight(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
download() {
const element = document.createElement('a');
element.setAttribute('href', 'data:application/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(this.data)));
const filename = prompt('File name', this.JSON.filename);
if (!filename) return;
element.setAttribute('download', filename + '.json');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
}
|
import React from "react"
import { FaSearch } from "react-icons/fa"
import livLogo from "../assets/images/Liv-Logo-New.png"
import giantLogo from "../assets/images/Giant-Logo-New copy.png"
import navLinks from "../constants/navlinks"
import { Link } from "gatsby"
const Navbar = ({ isOpen, toggleSidebar }) => {
return (
<div className="header">
<section className="container-top">
<div className="logo-liv">
<Link href="/">
<img src={livLogo} alt="liv brand logo" />
</Link>
</div>
<nav className="navbar-top">
<ul>
<li>
<Link to="/">my account</Link>
</li>
<li>
<a href="#cart"></a>
</li>
<li>
<Link to="/">united kingdom</Link>
</li>
</ul>
</nav>
</section>
<section className="container-bottom">
<div className="logo-giant">
<Link to="/">
<img src={giantLogo} alt="giant brand logo" />
</Link>
</div>
<input
type="checkbox"
id="nav-toggle"
className="nav-toggle"
onChange={toggleSidebar}
/>
<label
for="nav-toggle"
className="nav-toggle-label"
onChange={toggleSidebar}
>
<span></span>
</label>
<nav
className={isOpen ? "navbar-bottom visible" : "navbar-bottom hidden"}
>
<ul>
{navLinks.map(link => {
return (
<li className={link.size}>
<Link to={link.pathTo} className={link.btn}>
{link.text}
</Link>
</li>
)
})}
</ul>
<div className="brand-liv">
shop our brands:
<br />
<Link to="/">
<img src={livLogo} alt="liv brand logo" />
</Link>
</div>
<div className="search-btn">
<FaSearch />
</div>
</nav>
</section>
</div>
)
}
export default Navbar
|
const Hotel = require("../../models/emodels/Hotel");
const errorWrapper = require("../../helpers/error/errorWrapper");
const CustomError = require("../../helpers/error/customError");
const getAllHotels = errorWrapper(async (req, res, next) => {
return res.status(200).json(res.advanceQueryResults);
});
const getHotelsByCountry = errorWrapper(async (req, res, next) => {
const { countryId } = req.params;
const hotels = await Hotel.find({ country: countryId }).populate({
path: "country",
});
res.status(200).json({
success: true,
data: hotels,
});
});
const addNewHotel = errorWrapper(async (req, res, next) => {
const {countryId} = req.params;
const information = req.body;
const hotel = await Hotel.create({
...information,
country: countryId,
user: req.user.id,
});
res.status(200).json({
success: true,
message: hotel,
});
});
const getSingleHotel = errorWrapper(async (req, res, next) => {
const hotelId = req.params.id || req.params.restaurantId;
const hotel = await Hotel.findById(hotelId).populate([{
path: "user",
select: "name",
},{
path:"country",
}]);
res.status(200).json({
success: true,
data: hotel,
});
});
module.exports = {
addNewHotel,
getAllHotels,
getHotelsByCountry,
getSingleHotel,
};
|
var path;
var hitOptions = {
segments: true,
stroke: true,
fill: true,
tolerance: 5
};
var textItem = new PointText({
content: 'Click and drag to draw a line.',
point: new Point(20, 30),
fillColor: 'black',
});
//The dot
var path = new Path.Circle(new Point(5, 5), 2);
path.fillColor = 'black';
var dot = new Symbol(path);
//the 2D primitves
var triangle = new Path.RegularPolygon(new Point(80, 70), 3, 50);
var tri = new Symbol(triangle);
var circle = new Path.Circle(new Point(100, 70), 50);
circle.fillColor = 'black';
var circ = new Symbol(circle);
/*var segment, path;
var movePath = false;
*/
function onMouseDown(event) {
// If we produced a path before, deselect it:
//if (path) {
// path.selected = false;
// }
// Create a new path and set its stroke color to black:
path = new Path({
segments: [event.point],
strokeColor: 'black',
strokeWidth: 3
// Select the path, so we can see its segment points:
//path.fullySelected: true;
});
segment = path = null;
var hitResult = project.hitTest(event.point, hitOptions);
if (!hitResult)
return;
if (event.modifiers.shift) {
if (hitResult.type == 'segment') {
hitResult.segment.remove();
};
return;
}
if (hitResult) {
path = hitResult.item;
if (hitResult.type == 'segment') {
segment = hitResult.segment;
} else if (hitResult.type == 'stroke') {
var location = hitResult.location;
segment = path.insert(location.index + 1, event.point);
path.smooth();
}
}
movePath = hitResult.type == 'fill';
if (movePath)
project.activeLayer.addChild(hitResult.item);
}
//highlight path
function onMouseMove(event) {
project.activeLayer.selected = false;
if (event.item)
event.item.selected = true;
}
// While the user drags the mouse, points are added to the path
// at the position of the mouse:
function onMouseDrag(event) {
path.add(event.point);
/*if (segment) {
segment.point += event.delta;
path.smooth();
} else if (path) {
path.position += event.delta;
}
*/
// Update the content of the text item to show how many
// segments it has
textItem.content = 'Segment count: ' + path.segments.length + "\n" + 'Segment contents' + path.segments;
}
// When the mouse is released, we simplify the path:
function onMouseUp(event) {
var segmentCount = path.segments.length;
if (path.segments.length > 5) {path.toShape([true]);
}else if (path.segments.length < 5) {
dot.place(new Point(event.point));}
/*
if (path.segments.length > 5) {path.simplify([10]);
}else if (path.segments.length < 5) {
dot.place(new Point(event.point));}
*/
var newSegmentCount = path.segments.length;
var difference = segmentCount - newSegmentCount;
var percentage = 100 - Math.round(newSegmentCount / segmentCount * 100);
textItem.content = difference + ' of the ' + segmentCount + ' segments were removed. Saving ' + percentage + '%'+ "\n" + 'Segment contents' + path.segments;
// When the mouse is released, simplify it:
//path.simplify(15);
console.log(path.segments);
// Select the path, so we can see its segments:
//path.fullySelected = true;
}
|
(function() {
'use strict';
angular.module('veegam-trials')
.service('projectsSvc', projects);
projects.$inject = ['httpservice', 'apiUrl', 'utilsService'];
function projects(httpservice, apiUrl, utilsService) {
var self = this;
apiUrl = apiUrl + "/project-service";
self.orgID = utilsService.getOrganization();
//get all Projects.
self.getProject = function() {
var url = apiUrl + '/project';
return httpservice.get(url, true);
}
//get project by organization
self.getProjectByOrgID = function() {
var url = apiUrl + '/org/' + self.orgID + "/project";
return httpservice.get(url, true);
}
//get project by id inside organization.
self.getProjectForOrgByProjectID = function(orgID, projectID) {
var url = apiUrl + '/org/' + self.orgID + '/project/' + projectID;
return httpservice.get(url, true);
}
//get project by name inside organization
self.getProjectForOrgByProjectName = function(orgID, projectName) {
var url = apiUrl + '/org/' + self.orgID + '/project/' + projectName;
return httpservice.get(url, true);
}
//Create new project for organization
self.createProjectByOrg = function(projectDetails) {
var url = apiUrl + '/org/' + self.orgID + "/project";
return httpservice.post(url, projectDetails, true);
}
//Update existing project for organization
self.updateProjectByOrg = function(orgID, projectUpdates) {
var url = apiUrl + '/org/' + self.orgID + '/project';
return httpservice.put(url, projectUpdates, true);
}
//delete project for organization
self.deleteProjectByOrg = function(orgID, projectID) {
var url = apiUrl + '/org/' + self.orgID + '/project/' + projectID;
return httpservice.delete(url, true);
}
return self;
}
})();
|
//META { "name": "SelectionDefinition" } *//
var SelectionDefinition = (function() {
class SelectionDefinition {
constructor() {
this.stylesheet_name = "sd-stylesheet";
this.stylesheet = `
.sd-popup {position: absolute; white-space: pre-line; color: white; background: rgba(50, 50, 50, 0.7); padding: 6px; border-radius: 8px; display: none}
.sd-word {font-weight: bold}
.sd-pro {margin-left: 8px; font-size: 13px; color: rgba(255, 255, 255, 0.8) font-family: 'Roboto', arial, sans-serif}
.sd-def {display: block; font-size: 12px; color: rgba(255, 255, 255, 0.7)}
.sd-item {color: rgba(255, 255, 255, 0.6); margin: 2px 0px; padding: 6px 9px; line-height: 16px; font-size: 13px; font-weight: 500;}
.sd-item:hover {color: #fff; background: rgba(0, 0, 0, 0.2);}
.sd-backdrop {background-color: rgba(0, 0, 0, 0.5); border: 1px solid rgba(28, 36, 43, 0.6); box-shadow: 0 2px 10px 0 rgba(0, 0, 0, 0.2); border-radius: 8px; display: flex; contain: layout; position: absolute; z-index: 3000; height: 100%; width: 100%}
.sd-modal {background-color: #2f3136; border-radius: 8px; height: 540px; width: 640px; position: relative; top: 50%; left: 50%; transform: translate(-50%,-50%);}
.sd-modal-word {color: #fff; background-color: #35393e; height: 60px; border-radius: 8px 8px 0px 0px;}
.sd-modal-pro {color: rgba(255, 255, 255, 0.7); position: absolute; top: 40px}
.sd-modal-group {width: 500px; height: 150px; position: absolute; left: 70px; background-color: rgba(50, 50, 50, 1.0); border-radius: 8px;}
.sd-modal-group:first-of-type {top: 80px;}
.sd-modal-group:last-of-type {top: 290px;}
.sd-modal-type {color: #43b581; position: absolute;}
.sd-modal-def {color: #99aab5; position: absolute; top: 40px;}
.sd-modal-example {color: rgba(255, 255, 255, 0.7); position: absolute; top: 120px;}
.sd-modal-entym {color: rgba(255, 255, 255, 0.7); background-color: rgba(40, 43, 48, 0.6);}
`;
this.contextEntryMarkup =
`<div class="item-group">
<div class="sd-item">
<span>Get Definition</span>
<div class="hint"></div>
</div>
</div>`;
this.modalHTML =
`<div class="sd-backdrop">
<div class="sd-modal">
<div class="sd-modal-word" />
<span class="sd-modal-pro" />
<div class="sd-modal-group">
<span class="sd-modal-type" />
<span class="sd-modal-def" />
<span class="sd-modal-example" />
</div>
<div class="sd-modal-group">
<span class="sd-modal-type" />
<span class="sd-modal-def" />
<span class="sd-modal-example" />
</div>
<div class="sd-modal-entym" />
</div>
</div>`;
}
getName() { return "SelectionDefinition"; }
getDescription() { return "Plugin that provides a definition for selected words upon hover."; }
getAuthor() { return "Mashiro-chan"; }
getVersion() { return "1.0.0"; }
load() {
this.checkForUpdate();
}
start() {
this.showModal();
this.clientRect = [];
this.oldSelectionText;
this.wordData = {};
this.timer = null;
this.seconds = 2;
$('#app-mount').append('<div class="sd-popup">');
$('.sd-popup').append('<span class="sd-word">').append('<span class="sd-pro">').append('<span class="sd-def">');
$('.sd-word').text('example');
$('.sd-pro').text('/iɡˈzampəl/');
$('.sd-def').html('noun · <i>"a thing characteristic of its kind or illustrating a general rule."</i>');
$('.sd-popup').hide();
this.serverContextObserver = new MutationObserver((changes, _) => {
changes.forEach(
(change, i) => {
if (change.addedNodes) {
change.addedNodes.forEach((node) => {
if (node.nodeType == 1 && node.className.includes("context-menu")) {
this.onContextMenu(node);
}
});
}
}
);
});
if (document.querySelector(".app")) this.serverContextObserver.observe(document.querySelector(".app"), {childList: true});
$('#app-mount').on('mouseup.SelectionDefinition', '.markup', (e) => {
console.log('mouseup: ' + e.which);
$('.sd-popup').hide();
let message = e.target;
if (window.getSelection().anchorNode == null || e.which == 2) return;
if (e.which == 3) {
clearTimeout(this.timer);
this.timer = null;
return;
}
let selectRegion = window.getSelection().getRangeAt(0).getClientRects()[0];
$('.sd-highlight').remove();
if (selectRegion && selectRegion.width > 0) {
$(message).append('<span class="sd-highlight">');
$('.sd-highlight').css({height: selectRegion.height, width: selectRegion.width, left: selectRegion.left - 310, right: selectRegion.right, top: selectRegion.top - 55, bottom: selectRegion.bottom, position: "absolute", "background-color": "rgba(255, 98, 98, 0.3)"});
}
if (!this.timer)
this.timer = setTimeout(() => {
if ($('.sd-highlight').length) $('.sd-popup').show().css({"left": $('.sd-highlight').offset().left, "top": $('.sd-highlight').offset().top - 40});
this.timer = null;
}, 1 * 1000);
});
$('#app-mount').on('mouseenter.SelectionDefinition', '.sd-highlight', e => {
console.log('mouseenter');
if (!this.timer)
this.timer = setTimeout(() => {
$('.sd-popup').show().css({"left": $(e.target).offset().left, "top": $(e.target).offset().top - 40});
this.timer = null;
}, 1 * 1000);
});
$('#app-mount').on('mouseleave.SelectionDefinition', '.sd-highlight', () => {
console.log('mouseleave');
clearTimeout(this.timer);
this.timer = null;
$('.sd-popup').hide();
});
$('#app-mount').on('click.SelectionDefinition', '.sd-item', () => this.showModal());
$('#app-mount').on('click.SelectionDefinition', '.sd-backdrop', () => {
$('.sd-backdrop').remove();
});
BdApi.clearCSS(this.stylesheet_name);
BdApi.injectCSS(this.stylesheet_name, this.stylesheet);
console.log(this.getName() + ' loaded. Current version: ' + this.getVersion());
this.checkForUpdate();
}
stop() {
$('*').off(".SelectionDefinition");
$('[class^="sd-"]').remove();
$('.item-group > .sd-item').remove();
BdApi.clearCSS(this.stylesheet_name);
}
onContextMenu (context) {
if ($('.sd-highlight').length) {
$('.item-group > .sd-item').remove();
$(context).append(this.contextEntryMarkup);
}
}
showPopup() {
$('.sd-popup').hide();
let selectionText = this.getSelectionText();
if (selectionText == '' || /([^a-z ])+/ig.test(selectionText)) $('sd-popup').hide();
else {
if (selectionText != this.oldSelectionText) this.wordData = this.getWordData(selectionText);
this.oldSelectionText = selectionText;
$('.sd-popup').show();
this.setWordData('popup');
let newTop = this.clientRect.top - $('.sd-popup').outerHeight();
let newLeft = this.clientRect.left;
$('.sd-popup').css({"top": newTop, "left": newLeft});
}
}
showModal() {
$('.sd-backdrop').remove();
$('.app').append(this.modalHTML);
this.setWordData('modal');
}
getWordData(word) {
let url = 'od-api.oxforddictionaries.com:443/api/v1/entries/en/'+ word.trim().replace(/ /g, '_') + '/regions=us';
let returnData = {
word: '',
type1: '',
type2: '',
definition1: '',
definition2: '',
pronunciation: '',
example1: '',
example2: '',
entymologies: '',
error: false
};
$.ajax({
url: 'https://cors-anywhere.herokuapp.com/' + url,
type: 'GET',
async: false,
beforeSend: xhr => {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("app_id", "4af625b3");
xhr.setRequestHeader("app_key", "7d494264980005442c4ce94953da8105");
},
success: (data) => {
try {
returnData.word = data.results[0].word;
returnData.type1 = data.results[0].lexicalEntries[0].lexicalCategory;
returnData.type2 = data.results[0].lexicalEntries[1].lexicalCategory;
returnData.definition1 = data.results[0].lexicalEntries[0].entries[0].senses[0].definitions[0];
returnData.definition2 = data.results[0].lexicalEntries[1].entries[0].senses[0].definitions[0];
returnData.pronunciation = data.results[0].lexicalEntries[0].pronunciations[0].phoneticSpelling;
returnData.example1 = data.results[0].lexicalEntries[0].entries[0].senses[0].examples[0].text;
returnData.example2 = data.results[0].lexicalEntries[1].entries[0].senses[0].examples[0].text;
returnData.entymologies = data.results[0].lexicalEntries[0].entries[0].etymologies[0];
} catch (e) {
console.error('SelectionDefinition: one or more data parameters could not be returned!');
}
},
error: err => {
returnData.error = true;
console.error('SelectionDefinition: error retrieving data on that word or phrase!');
}
});
return returnData;
}
setWordData(type) {
let wordData = {
word: "example",
type1: "Noun",
type2: "Verb",
definition1: "a thing characteristic of its kind or illustrating a general rule",
definition2: "be illustrated or exemplified",
pronunciation: "ɪɡˈzæmpəl",
example1: "some of these carpets are among the finest examples of the period",
example2: "the extent of Allied naval support is exampled by the navigational specialists provided",
entymologies: "late Middle English: from Old French, from Latin exemplum, from eximere ‘take out’, from ex- ‘out’ + emere ‘take’. Compare with sample",
error: false
};
if (type === 'popup') {
$('.sd-word').text(wordData.word);
$('.sd-pro').text('/' + wordData.pronunciation + '/');
$('.sd-def').html(wordData.type1 + ' · <i>"' + wordData.definition1 + '."</i>');
} else if (type === 'modal') {
$('.sd-modal-word').text(wordData.word);
$('.sd-modal-pro').text('/' + wordData.pronunciation + '/');
$('.sd-modal-type').eq(0).text(wordData.type1);
$('.sd-modal-def').eq(0).text(wordData.definition1);
$('.sd-modal-example').eq(0).text(wordData.example1);
$('.sd-modal-type').eq(1).text(wordData.type2);
$('.sd-modal-def').eq(1).text(wordData.definition2);
$('.sd-modal-example').eq(1).text(wordData.example2);
$('.sd-modal-entym').text(wordData.entymologies);
}
}
getSelectionText() {
var text = '';
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}
checkForUpdate() {
const githubRaw = "https://raw.githubusercontent.com/mashirochan/Mashiro-chan/master/Plugins/" + this.getName() + "/" + this.getName() + ".plugin.js";
$.get(githubRaw, (result) => {
let ver = result.match(/['"][0-9]+\.[0-9]+\.[0-9]+['"]/i);
if (!ver) return;
ver = ver.toString().replace(/"/g, "");
ver = ver.split(".");
let lver = this.getVersion().split(".");
let hasUpdate = false;
if (ver[0] > lver[0]) hasUpdate = true;
else if (ver[0] == lver[0] && ver[1] > lver[1]) hasUpdate = true;
else if (ver[0] == lver[0] && ver[1] == lver[1] && ver[2] > lver[2]) hasUpdate = true;
if (hasUpdate) this.showUpdateNotice(this.getName());
else this.removeUpdateNotice(this.getName());
});
}
showUpdateNotice() {
const updateLink = "https://betterdiscord.net/ghdl?url=https://github.com/mashirochan/Mashiro-chan/blob/master/Plugins/" + this.getName() + "/" + this.getName() + ".plugin.js";
BdApi.clearCSS("pluginNoticeCSS");
BdApi.injectCSS("pluginNoticeCSS", "#pluginNotice span, #pluginNotice span a {-webkit-app-region: no-drag;color:#fff;} #pluginNotice span a:hover {text-decoration:underline;}");
let noticeElement = '<div class="notice notice-info" id="pluginNotice"><div class="notice-dismiss" id="pluginNoticeDismiss"></div>The following plugins have updates: <strong id="outdatedPlugins"></strong></div>';
if (!$('#pluginNotice').length) {
$('.app.flex-vertical').children().first().before(noticeElement);
$('.win-buttons').addClass("win-buttons-notice");
$('#pluginNoticeDismiss').on('click', () => {
$('.win-buttons').animate({ top: 0 }, 400, "swing", () => { $('.win-buttons').css("top", "").removeClass("win-buttons-notice"); });
$('#pluginNotice').slideUp({ complete: () => { $('#pluginNotice').remove(); }});
});
}
let pluginNoticeID = this.getName() + '-notice';
if (!$('#' + pluginNoticeID).length) {
let pluginNoticeElement = $('<span id="' + pluginNoticeID + '">');
pluginNoticeElement.html('<a href="' + updateLink + '" target="_blank">' + this.getName() + '</a>');
if ($('#outdatedPlugins').children('span').length) $('#outdatedPlugins').append("<span class='separator'>, </span>");
$('#outdatedPlugins').append(pluginNoticeElement);
}
}
removeUpdateNotice() {
let notice = $('#' + this.getName() + '-notice');
if (notice.length) {
if (notice.next('.separator').length) notice.next().remove();
else if (notice.prev('.separator').length) notice.prev().remove();
notice.remove();
}
if (!$('#outdatedPlugins').children('span').length) $('#pluginNoticeDismiss').click();
}
}
return SelectionDefinition;
})();
|
import styled from '@emotion/styled';
export const Input = styled.input`
padding: 5px 10px;
margin-right: 20px;
border: 1px solid black;
border-radius: 4px;
`;
export const Btn = styled.button`
padding: 5px 10px;
border: 1px solid black;
border-radius: 4px;
`;
|
/* Returns the the radian value of the specified degrees in the range of (-PI, PI] */
export function degToRad(degrees) {
var res = (degrees / 180) * Math.PI;
return res;
}
/* Returns the radian value of the specified radians in the range of [0,360), to a precision of four decimal places.*/
export function radToDeg(radians) {
var res = (radians * 180) / Math.PI;
return res;
}
export function computeAngleFromPoints(start, end) {
var dX = end[0] - start[0];
var dY = end[1] - start[1];
return computeAngle(dX, dY);
}
export function computeAngle(dX, dY) {
return radToDeg(Math.atan2(dY, dX));
}
export function computeDistanceBetweenPoints(start, end) {
return computeDistance(end[0] - start[0], end[1] - start[1]);
}
export function computeDistance(dX, dY) {
return Math.sqrt(Math.pow(dX, 2) + Math.pow(dY, 2));
}
export function computeEndPoint(start, angle, length) {
length = parseFloat(length);
var rad = degToRad(angle);
var dX = length * Math.cos(rad);
var dY = length * Math.sin(rad);
return [start[0] + dX, start[1] + dY];
}
|
const ShopActionTypes = {
FETCH_COLLECTIONS_START : 'FETCH_COLLECTIONS_START',
FETCH_COLLETIONS_SUCCESS : 'FETCH_COLLETIONS_SUCCESS',
FETCH_COLLETIONS_FAILURE : 'FETCH_COLLETIONS_FAILURE'
};
export default ShopActionTypes;
|
import * as dynamoDbLib from "./libs/dynamodb-lib";
import { success, failure } from "./libs/response-lib";
export async function main(event, context, callback) {
const params = {
TableName: "DynamoDBNotifications",
KeyConditionExpression: "RecipientId = :RecipientId",
ExpressionAttributeValues: {
":RecipientId": event.pathParameters.id
},
};
try {
const result = await dynamoDbLib.call("query", params);
callback(null, success(result.Items));
} catch(e) {
callback(null, failure(e));
}
}
|
const ROT = require('rot-js');
const Game = function(options = {}) {
this.options = options;
this.display = null;
this.currentScreen = null;
this.screenMap = {};
this._init(options);
};
Game.prototype._init = function _init(options) {
this.display = new ROT.Display(options);
this._bindEventToScreen('keydown');
this._bindEventToScreen('keyup');
this._bindEventToScreen('keypress');
};
Game.prototype._bindEventToScreen = function _bindEventToScreen(eventType) {
window.addEventListener(eventType, event => {
if (!this.currentScreen) {
return;
}
this.currentScreen.handleInput(this, eventType, event);
this.display.clear();
this.currentScreen.render(this);
});
};
Game.prototype.render = function render(dom) {
dom.appendChild(this.display.getContainer());
};
Game.prototype.registerScreens = function registerScreens(screenTuple = []) {
screenTuple.forEach(([screnName, screen]) => {
this.screenMap[screnName] = screen;
});
};
Game.prototype.switchScreen = function switchScreen(screenName) {
const screen = this.screenMap[screenName];
if (!screen) {
return null;
}
if (this.currentScreen !== null) {
this.currentScreen.exit();
}
this.display.clear();
this.currentScreen = screen;
this.currentScreen.enter(this);
this.currentScreen.render(this);
};
module.exports = {
Game,
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.