text
stringlengths
7
3.69M
/* eslint-disable no-restricted-syntax */ ("use strict"); // System dependencies (Built in modules) const { Readable, Writable } = require("stream"); // Third party dependencies (Typically found in public NPM packages) const handlebars = require("handlebars"); const Vinyl = require("vinyl"); /** * Implements the core functionality that allows WebProducer to combine data and templates to produce pages. * Note that this class depends upon Handlebars which implies that WebProducer requires Handlebars syntax in templates. Testing and * benchmarking of several templating engines was performed before deciding to align with Handlebars. * * @class PageBuilder */ class PageBuilder { /** * Creates an instance of PageBuilder * * @memberof PageBuilder */ constructor() { // Track the handlebars engine this.handlebars = {}; } /** * Precompiles the .hbs files found in sourceStream into an instance property * * @param {stream} sourceStream: A Readable stream of vinyl files * @returns: A Promise of completion * @memberof PageBuilder */ async precompile(sourceStream) { return new Promise((resolve, reject) => { handlebars.templates = {}; const writable = new Writable({ objectMode: true, highWaterMark: 64, }); writable._write = function (file, _, done) { handlebars.templates[file.basename] = handlebars.compile(file.contents.toString()); done(); }; writable.on("error", (err) => { console.error("precompile():", err); reject(err); }); writable.on("finish", () => { this.handlebars = handlebars; this.handlebars.partials = handlebars.templates; // Resolve our completion return resolve(); }); // Start piping sourceStream.pipe(writable); }); } /** * Merges precompiled .hbs templates with data to generate a Readable stream of generated .html * * @param {object} data: Data, likely from a transformed GraphQL query, to be merged with precompiled .hbs templates * @returns: An object containing the Readable stream of generated pages, and the number of pages and redirects processed * @memberof PageBuilder */ async build(data) { const templates = this.handlebars.templates; // Use htmlStream for strictly HTML Vinyl objects. The htmlStream will be routed through the HTML minifier later. const htmlStream = new Readable({ objectMode: true, read: function (vinylFile) { this.push(vinylFile); }, }); // Use fileStream for all non-HTML types including but not limited to sitemap.xml, robots.txt, feed.xml, etc. const fileStream = new Readable({ objectMode: true, read: function (vinylFile) { this.push(vinylFile); }, }); // Set some counters let pages = 0; let redirects = 0; let files = 0; // Iterate all available data elements (note: one per "page") for (const key in data) { const pageData = data[key]; if (pageData && pageData.modelName) { if (templates[`${pageData.modelName}.hbs`]) { // Generate content by merging the pageData into the named Handlebars template const generatedContents = templates[`${pageData.modelName}.hbs`](pageData); // Create a new Vinyl object from the generated data const vinyl = new Vinyl({ path: key.trim().slice(1), contents: Buffer.from(generatedContents), }); // Check whether the resulting Vinyl file is HTML, and push to the appropriate stream, and increase the counter. if (vinyl.extname === "" || vinyl.extname === ".html") { htmlStream.push(vinyl); pages++; } else { fileStream.push(vinyl); files++; } } else if (pageData.modelName === "redirect") { // Redirects are basically text files and don't go through the HTML minifier but we like to count them separate from files const vinyl = new Vinyl({ path: key.trim().slice(1), contents: Buffer.from(key.trim().slice(1)), redirect: 301, targetAddress: pageData.targetAddress, }); // Note that while we push to fileStream, we increment the redirects counter. redirects++; fileStream.push(vinyl); } else { console.error(`${new Date().toISOString()}> modelName not found for ${key}`); } } } // End the readable streams htmlStream.push(null); fileStream.push(null); // Return a Promise (because we are async) of the streams and counters return { htmlStream, fileStream, pages, redirects, files }; } } module.exports = PageBuilder;
import React, { useEffect, useState } from 'react' import PropTypes from 'prop-types' import { disableBodyScroll, restoreBodyScroll } from '../../utils/bodyScroll' function MobileMenu(props) { const { children, toggle } = props const [isOpen, setIsOpen] = useState(props.isOpen) /** * Listen to isOpen to enable * or disable body scroll */ useEffect(() => { setIsOpen(props.isOpen) props.isOpen ? disableBodyScroll() : restoreBodyScroll() return () => { restoreBodyScroll() } }, [props.isOpen]) const openClassName = isOpen ? 'open' : '' return ( <div className={`NavBar-mobileMenu ${openClassName}`}> <div className="NavBar-mobileMenuToggle"> <button onClick={toggle} aria-label="Close menu"> <i className="fas fa-times" /> </button> </div> {children} </div> ) } MobileMenu.propTypes = { isOpen: PropTypes.bool, toggle: PropTypes.func, children: PropTypes.node, } MobileMenu.defaultProps = { toggle: () => {}, } export default MobileMenu
var annotated_dup = [ [ "Hurriyet", "class_hurriyet.html", "class_hurriyet" ] ];
import styled from 'styled-components/native'; export const Container = styled.View` height: 150px; flex-direction: row; justify-content: space-between; align-items: center; padding: 15px; `; export const Image = styled.Image` width: 180px; height: 24px; `; export const Cart = styled.TouchableOpacity` flex: 1; align-items: flex-end; justify-content: flex-end; `; export const Itens = styled.Text` position: absolute; text-align: center; top: -8px; right: -8px; min-width: 18px; min-height: 18px; background: #7159c1; color: #fff; font-size: 12px; padding: 2px; border-radius: 9px; overflow: hidden; `;
require('dotenv').config(); var request = require('request'); var sql = require("mssql"); var format = require('pg-format'); //Insert scheduling data into database async function insertData(req,res){ try { var reqData = req.body var a3sId = req.headers.id var userId = req.headers.userid var scope = req.headers.scope new Promise((resolve,reject)=>{ var request = new sql.Request(); var query = `INSERT INTO dbo.schedules VALUES ('${a3sId}','${userId}','${scope}','${reqData.scheduleName}','${reqData.scheduleDescription}','${reqData.startDate}','${reqData.endDate}','${reqData.Recurrence}','${reqData.startTime}','start'),('${a3sId}','${userId}','${scope}','${reqData.scheduleName}','${reqData.scheduleDescription}','${reqData.startDate}','${reqData.endDate}','${reqData.Recurrence}','${reqData.stopTime}','stop')` request.query(query, async function (err, recordset) { if(err) { reject(err) }else{ resolve(recordset.recordset) } }) }).then(result=>{ res.send("Data successfully inserted in Database..!!!") }).catch(error=>{ console.log("Error occurred: ",error) res.status(400).send({"Error":error}) }) }catch(error) { console.log(error) res.status(404).send({"status": "Error occurred..!!! Please try again."}) } } //Get scheduling data from database based on a3sID async function fetchData(req,res){ try { var a3sId = req.headers.id new Promise((resolve,reject)=>{ var request = new sql.Request(); var query = `SELECT * FROM dbo.schedules where a3sId='${a3sId}'` request.query(query, async function (err, recordset) { if(err) { reject(err) }else{ resolve(recordset.recordset) } }) }).then(result=>{ res.send(result) }).catch(error=>{ console.log("Error occurred: ",error) res.status(400).send({"Error":error}) }) }catch(error) { console.log(error) res.status(404).send({"status": "Error occurred..!!! Please try again."}) } } //Update scope value of given key in database async function updateData(req,res){ try { var key = req.params["key"] var scope = req.query["scope"] new Promise((resolve,reject)=>{ var request = new sql.Request(); var query = `UPDATE dbo.schedules SET scope='${scope}' WHERE uKey='${key}'` request.query(query, async function (err, recordset) { if(err) { reject(err) }else{ resolve(recordset.recordset) } }) }).then(result=>{ res.send("Data updated successfully..!!!") }).catch(error=>{ console.log("Error occurred: ",error) res.status(400).send({"Error":error}) }) }catch(error) { console.log(error) res.status(404).send({"status": "Error occurred..!!! Please try again."}) } } //Delete row with given key from database async function deleteData(req,res){ try { var key = req.params.key new Promise((resolve,reject)=>{ var request = new sql.Request(); var query = `DELETE FROM dbo.schedules WHERE uKey='${key}'` request.query(query, async function (err, recordset) { if(err) { reject(err) }else{ resolve(recordset.recordset) } }) }).then(result=>{ res.send("Data deleted successfully..!!!") }).catch(error=>{ console.log("Error occurred: ",error) res.status(400).send({"Error":error}) }) }catch(error) { console.log(error) res.status(404).send({"status": "Error occurred..!!! Please try again."}) } } module.exports = {insertData, fetchData, updateData ,deleteData}
import axios from 'axios'; const logout = () => { return axios.get("/logout"); }; export default logout;
(function () { 'use strict'; angular.module('veegam-trials').config(configBlock); /** @ngInject */ function configBlock($locationProvider, $logProvider, lockProvider, AUTH0_CLIENT_ID, AUTH0_DOMAIN, $httpProvider, $compileProvider, toastrConfig, $logentriesProvider, LogEntries_Token, stripeProvider) { $locationProvider.html5Mode(true); $logProvider.debugEnabled(true); //Enable cross domain calls $httpProvider.defaults.useXDomain = true; //Initialize lock for auth0 lockProvider.init({ clientID: AUTH0_CLIENT_ID, domain: AUTH0_DOMAIN, }); $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|blob):/); angular.extend(toastrConfig, { positionClass: 'toast-top-full-width', toastClass: 'toast toast-custom-main', }); // setDebug(true) outputs to console //$logentriesProvider.setDebug(true); //if no token is given no logs will be sent to logentries $logentriesProvider.init({ token: LogEntries_Token, catchall: true, page_info: 'per-page', trace: true }); //Stripe.setPublishableKey('pk_test_yUswBCTjf4OZIVDKclxZcszi'); //demo key stripeProvider.setPublishableKey('pk_test_yUswBCTjf4OZIVDKclxZcszi'); //Stripe.setPublishableKey('pk_test_yUswBCTjf4OZIVDKclxZcszi'); } })();
export const ACTIONS = { SIGNUP: 'signup', EDIT: 'edit' }
const hat = require('hat'); const Role = require('../../models').Role; exports.all = (req, res, next) => { res.render('admin/role/all', { roles: req.roles }); } exports.new = (req, res, next) => { res.render('admin/role/new'); } exports.edit = (req, res, next) => { res.render('admin/role/edit', { role: req.role }); } /** * @TODO validation in middleware */ exports.create = (req, res, next) => { const { name} = req.body; new Role({ name }) .save() .then((response) => { req.flash('success', { msg: 'Succesfully created '}); res.redirect('/admin/roles' || '/'); }) .catch((err) => { next(err); }); } exports.update = (req, res) => { const { name } = req.body; req.roleModel.set('name', name); req.roleModel .save() .then((response) => { req.flash('success', { msg: 'Updated role!'}); res.redirect('/admin/role/' + response.get('id') || '/'); }) .catch((err) => { next(err); }) }
var setActiveNavItem = function(event) { $('ul.nav.navbar-nav li').removeClass('active'); $('a[href="' + location.hash + '"]').parent('li').addClass('active'); $('a.list-group-item').removeClass('active'); $('a[href="' + location.hash + '"]').addClass('active'); }; $(window).on('hashchange', setActiveNavItem); /* People list configuration */ $("div#people_menu").navigation({ label: false, type: 'overlay', gravity: 'left', maxWidth: '767px' }); $('#menu_toggle').click(function() { $('#real_menu_toggle').click(); }); $("div#people_menu").on('click', 'a', function() { $("div#people_menu").navigation("close"); }); $('#actions_toggle').click(function(){ $("div#people_menu").navigation("close"); }); /* Close the nav menu after user choose an action */ $('#navbar-collapse-1').on('click', 'a:not(.dropdown-toggle)', function() { $('#navbar-collapse-1').collapse('hide'); }); /* Toastr component configuration */ var toastrOptions = { bottomCenter: { closeButton: true, timeOut: 3000, positionClass: 'toast-bottom-center' }, topCenter: { closeButton: true, timeOut: 1000, positionClass: 'toast-top-center' } }; toastr.options = toastrOptions.bottomCenter; /* Main Application */ var socket = io(); var esnApp = angular.module('EmergencySocialNetwork', ['ngRoute', 'ngAnimate']); esnApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { $routeProvider .when('/directory', { templateUrl: 'views/directory', controller: 'DirectoryCtrl', }) .when('/user/:username', { templateUrl: 'views/user', controller: 'UserCtrl', }) .when('/profile', { templateUrl: 'views/profile', controller: 'ProfileCtrl', }) .when('/chat/:target', { templateUrl: 'views/chat', controller: 'ChatCtrl', }) .when('/monitor/performance', { templateUrl: 'views/monitor-measure-performance', controller: 'MeasurePerformanceCtrl' }) .otherwise({ templateUrl: 'views/welcome', controller: 'AnnouncementCtrl', }); $locationProvider.hashPrefix(); } ]); esnApp.animation('.view-animate', function() { return { enter: function(element, done) { element.css('display', 'none'); element.fadeIn(500, done); return function() { element.stop(); }; }, leave: function(element, done) { element.css('width', $('.view-animate').width()); element.addClass('ng-leave'); element.fadeOut(500, done); return function() { element.stop(); }; } }; }); /* Factory for Status */ esnApp.factory('statusType', function() { var statusTypeFactory = {}; statusTypeFactory.list = [{ title: 'OK', desc: 'I am OK, I do not need help.', color: 'success', icon: 'glyphicon-heart' }, { title: 'Help', desc: 'I need help, but this is not a life threatening emergency.', color: 'warning', icon: 'glyphicon-bell' }, { title: 'Emergency', desc: 'I need help now, as this is a life threatening emergency!', color: 'danger', icon: 'glyphicon-alert' }]; return statusTypeFactory; }); /* Factory for People */ esnApp.factory('people', function($rootScope, $http, $timeout, statusType) { var getDistance = function(lat1, lon1, lat2, lon2){ var R = 3958.75587; // miles var dLat = (lat1 - lat2) * Math.PI / 180; var dLon = (lon1 - lon2) * Math.PI / 180; lat1 = lat1 * Math.PI / 180; lat2 = lat2 * Math.PI / 180; var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; var peopleFactory = {}; peopleFactory.list = {}; peopleFactory.parse = function(user, idx, arr) { if (!user.username) throw "No username"; user.createdAt_local = new Date(user.createdAt).toLocaleString(); user.lastLoginAt_local = new Date(user.lastLoginAt).toLocaleString(); if (user.lastStatusCode) { for (var i in statusType.list) { var st = statusType.list[i]; if (st.title.toUpperCase() === user.lastStatusCode.toUpperCase()) { user.statusIcon = st.icon; user.color = st.color; break; } } } if (!user.statusIcon) { user.color = 'info'; user.statusIcon = 'glyphicon-question-sign'; } if (!user.image) { user.image = '/default-user.png'; } if (!('login' in user)) { user.login = false; if (!user.lastLogoutAt || Date.parse(user.lastLogoutAt) < Date.parse(user.lastLoginAt)) { user.login = true; } } if (user.coordinate) { var crd = user.coordinate.split(', '); user.latitude = parseFloat(crd[0]).toFixed(4); user.longitude = parseFloat(crd[1]).toFixed(4); } if (user.peopleiknow) { user.peopleiknow_arr = user.peopleiknow.split(', '); } return user; }; peopleFactory.refresh = function(callback) { $http.get('/users').then(function successCallback(res){ var users = res.data; users.forEach(peopleFactory.parse); users.forEach(function(item){ peopleFactory.list[item.username] = item; }); if (!$rootScope.loginEventSent) { var meObj = users.filter(function(item){ return item.username === $rootScope.my_username; })[0]; socket.emit('login', meObj); $rootScope.loginEventSent = true; } if ($rootScope.me && $rootScope.me.latitude){ users.forEach(function calculateDist(item){ if (!item.latitude) return; item.distance = getDistance($rootScope.me.latitude, $rootScope.me.longitude, item.latitude, item.longitude); item.distance = item.distance.toFixed(2); console.log(item.distance); }); } callback(); }, function errorCallback(res) { console.error(res); }); }; peopleFactory.refreshMe = function(done) { $http({ method: 'GET', url: '/user/' + $rootScope.my_username }).then(function successCallback(res) { var data = res.data; peopleFactory.parse(data); $rootScope.me = data; done(); }, function errorCallback(res){ console.error(res); }); }; peopleFactory.updateUser = function(person) { var exist = false; for (var i in peopleFactory.list){ var u = peopleFactory.list[i]; if (u.username !== person.username) { continue; } exist = true; if ('statusType' in person) { u.lastStatusCode = person.statusType; peopleFactory.parse(u); } if ('login' in person) { u.login = person.login; } angular.element('#people_menu').scope().$apply(); angular.element('#content .view-animate').scope().$apply(); break; } if (!exist) { console.log('user not found!'); peopleFactory.refresh(function(){ angular.element('#people_menu').scope().users = peopleFactory.list; angular.element('#content .view-animate').scope().users = peopleFactory.list; }); } }; socket.on('login', function(person) { person.login = true; peopleFactory.updateUser(person); }); socket.on('logout', function(person) { console.log('on logout'); person.login = false; peopleFactory.updateUser(person); }); socket.on('shareStatus', function(person) { console.log('on shareStatus'); peopleFactory.updateUser(person); }); return peopleFactory; }); /* Factory for Messages */ esnApp.factory('messages', function($rootScope, $http, statusType) { var msgFactory = {}; msgFactory.publicMsgs = []; msgFactory.privateMsgs = {}; msgFactory.parse = function(msgItem, idx, arr) { msgItem.postedAt = Date.parse(msgItem.postedAt); msgItem.postedAt_s = new Date(msgItem.postedAt).toLocaleString(); return msgItem; }; msgFactory.add = function(msgItem) { msgFactory.parse(msgItem); var target = "public"; if (msgItem.target) { if (msgItem.author === $rootScope.my_username) { // msg from me if (!msgFactory.privateMsgs[msgItem.target]) msgFactory.privateMsgs[msgItem.target] = []; msgFactory.privateMsgs[msgItem.target].push(msgItem); target = msgItem.target; } else { // msg to me if (!msgFactory.privateMsgs[msgItem.author]) msgFactory.privateMsgs[msgItem.author] = []; msgFactory.privateMsgs[msgItem.author].push(msgItem); target = msgItem.author; } } else { msgFactory.publicMsgs.push(msgItem); } var current_a = $('a[href="#/chat/' + target + '"]'); if (!current_a.hasClass('active')) { var badge = current_a.children('.badge'); var unread_count = badge.text(); if (unread_count === "") unread_count = 0; unread_count = parseInt(unread_count) + 1; badge.text(unread_count); if (msgItem.author !== $rootScope.my_username) { var div = $("<div>"); var notification = msgItem.author + " sent a message to "; notification += (msgItem.target)? "you": "public chat"; notification += ": "; if (msgItem.content.length > 20) { notification += msgItem.content.substr(0, 20) + " ..."; } else { notification += msgItem.content; } div.html(notification).attr('data-hash', "#/chat/" + target); toastr.options = toastrOptions.topCenter; toastr.info(div); toastr.options = toastrOptions.bottomCenter; } } else { angular.element('#content .view-animate').scope().$apply(); $('html, body').scrollTop($('#messages').height()); } }; msgFactory.send = function(event) { event.preventDefault(); var msgText = $('#m').val(); var username = $rootScope.my_username; if (msgText === '') return false; var msgItem = { content: msgText, author: username, postedAt: new Date().toISOString() }; var target = $('#msg_target').val(); if (target === 'public') { socket.emit('public chat', msgItem); } else { msgItem.target = target; socket.emit('private chat', msgItem); } if (!target || target !== username) msgFactory.add(msgItem); $('#m').val(''); }; msgFactory.refresh = function(target, callback){ var url = '/messages/wall'; if (target) { url = '/messages/' + target; } $http({ method: 'GET', url: url }).then(function successCallback(response) { var data = response.data; data.forEach(msgFactory.parse); if (target) msgFactory.privateMsgs[target] = data; else msgFactory.publicMsgs = data; callback(data); }, function errorCallback(response) { console.error(response); }); }; socket.on('public chat', function(msgItem) { msgFactory.add(msgItem); }); socket.on('private chat', function(msgItem) { msgFactory.add(msgItem); }); return msgFactory; }); /* Factory for announcement */ esnApp.factory('announcement',function($rootScope, $http, $sce, statusType){ var announcementFactory = {}; announcementFactory.list = []; announcementFactory.parse = function(item, idx, arr) { item.postedAt = Date.parse(item.postedAt); item.postedAt_s = new Date(item.postedAt).toLocaleString(); item.content = item.content.replace(/\\n/g, '<br>'); item.content = item.content.replace(/\n/g, '<br>'); item.content = $sce.trustAsHtml(item.content); console.log(item); }; announcementFactory.add = function(item) { announcementFactory.parse(item); announcementFactory.list.push(item); angular.element('#content .view-animate').scope().$apply(); }; announcementFactory.send = function(event) { event.preventDefault(); var msgTextElem = $(event.target).find('textarea'); var msgText = msgTextElem.val(); var username = $rootScope.my_username; if (msgText === '') return false; var item = { author: username, messageType: 'Announcement', content: msgText, postedAt: new Date().toISOString() }; console.log(item); socket.emit('announcement', item); announcementFactory.add(item); msgTextElem.val(''); }; announcementFactory.refresh = function(callback){ $http({ method: 'GET', url: '/announcements/' }).then(function successCallback(response) { var data = response.data; data.forEach(announcementFactory.parse); announcementFactory.list = data; callback(data); }, function errorCallback(response) { console.error(response); }); }; socket.on('announcement', function(item) { announcementFactory.add(item); }); return announcementFactory; }); /* Main Controller */ esnApp.controller('MainCtrl', function($rootScope, $scope, $http, statusType, people) { $rootScope.my_username = $('#name').val(); // Get user profile people.refreshMe(function(){ people.refresh(function() { $scope.users = people.list; setTimeout(setActiveNavItem, 500); }); }); $scope.statusTypes = statusType.list; socket.on('force logout', function(person) { console.log('got force logout'); console.log(person); if (person.username === $rootScope.my_username) { toastr.warning("Account changed by Admin. You'll be logged out in 5 seconds."); setTimeout(function(){ $('a.logout').click(); }, 5000); } }); }); esnApp.directive('onStatusItemRender', function($rootScope, $http) { return function(scope, element, attrs) { angular.element(element).children('a').click(function(event) { event.preventDefault(); var username = $('#name').val(); var lnk = $(event.target); if (lnk.prop("tagName") !== 'A') lnk = lnk.parents('a'); var args = { statusType: lnk.attr('data-title'), updatedAt: new Date().toISOString() }; $rootScope.me.lastStatusCode = lnk.attr('data-title'); $http({ method: 'POST', url: '/status/' + username, data: args }).then(function successCallback(res) { toastr.success('Status Update succeeded'); $('#status').text(' (' + args.statusType + ')').removeClass('ng-hide'); }, function errorCallback(res) { toastr.warning('Status Update failed'); }); args.username = username; socket.emit('shareStatus', args); }); }; }); /* Search Controller */ esnApp.controller('SearchCtrl', function($scope, $http, people, messages) { var searchTypes = ['users_username', 'users_statusType', 'announcements', 'publicMessages', 'privateMessages']; angular.element('#search_types li').on('click', function(event){ $scope.result = {}; searchTypes.forEach(function(target, idx, arr){ if (target.indexOf('users') >= 0) { target = target.substr(0, 5); } $('div.search_result div.' + target).hide(); }); var searchTarget = $(event.target).attr('data-search'); if (searchTarget === '') return; var searchTargets = [searchTarget]; if (searchTarget === 'all') { searchTargets = searchTypes; } var searchPattern = $('#search_pattern').val(); searchTargets.forEach(function(target, idx, arr){ if (target.indexOf('users') >= 0) { $scope.result.users = {}; var criteria = target.substr(6); var args = {}; args[criteria] = searchPattern; $http({ method: 'GET', url: '/search/users/', params: args }).then(function successCallback(res) { res.data.forEach(function(item){ $scope.result.users[item.username] = people.parse(item); }); console.log($scope.result.users); }, function errorCallback(res){ console.error(res); }); $('div.search_result div.users').slideDown(); } else { // announcements, public/private msgs $scope.result[target] = []; $http({ method: 'GET', url: '/search/' + target + '/', params: { content: searchPattern } }).then(function successCallback(res) { res.data.forEach(function(item){ $scope.result[target].push(messages.parse(item)); }); console.log($scope.result[target]); }, function errorCallback(res){ console.error(res); }); $('div.search_result div.' + target).slideDown(); } }); $('div.search_result').show(); }); angular.element('div.search_result').on('click', 'a', function(event){ $('#search_modal').modal('hide'); }); }); /* Announcement Controller */ esnApp.controller("AnnouncementCtrl",function($rootScope, $scope, $http, $routeParams, announcement){ announcement.refresh(function(list){ $scope.announcements = list; }); $('form.announcement_input').submit(announcement.send); }); /* Directory Controller */ esnApp.controller('DirectoryCtrl', function ($scope, $http, people) { people.refresh(function() { $scope.users = people.list; }); angular.element('.view-animate').on('click', '.profile_modal_toggle', function(event) { event.preventDefault(); var lnk = $(event.target); if (lnk.prop("tagName") !== 'A') lnk = lnk.parents('a'); var username = lnk.attr('data-user'); var theUser = people.list[username]; $scope.targetUser = theUser; $('#username_to_edit').text(username); $('#newUsername').val(username); $('label[for=radio' + theUser.accountStatus + ']').click(); $('select[name=privilege]').val(theUser.privilege); }); angular.element('form[name="profile"]').submit(function(event) { event.preventDefault(); var updateInfo = {}; var newUsername = $('#newUsername').val(); if (newUsername !== $scope.targetUser.username) updateInfo.username = newUsername; var newPassword = $('#newPassword').val(); if (newPassword !== "") updateInfo.password = newPassword; var newPrivilege = $('select[name=privilege]').val(); if (newPrivilege !== $scope.targetUser.privilege) updateInfo.privilege = newPrivilege; var newAccountStatus = $('input:radio[name=accountStatus]:checked').val(); if (newAccountStatus !== $scope.targetUser.accountStatus) updateInfo.accountStatus = newAccountStatus; if ($.isEmptyObject(updateInfo)) { toastr.success('All changes are up to date.'); return; } $http({ method: 'PUT', url: '/user/' + $scope.targetUser.username, data: updateInfo }).then(function successCallback(res) { toastr.success('Update success'); if (updateInfo.username) { delete people.list[$scope.targetUser.username]; people.list[updateInfo.username] = $scope.targetUser; $scope.targetUser.username = updateInfo.username; } if (updateInfo.privilege) $scope.targetUser.privilege = updateInfo.privilege; if (updateInfo.accountStatus) $scope.targetUser.accountStatus = updateInfo.accountStatus; }, function errorCallback(res) { toastr.error('Update failed'); }); $('#profile_modal').modal('hide'); }); }); /* User Controller */ esnApp.controller('UserCtrl', function ($rootScope, $scope, $routeParams, $http, people) { if ($routeParams.username === $rootScope.my_username) { people.refreshMe(function(){ $scope.user = $rootScope.me; }); } else { $http({ method: 'GET', url: '/user/' + $routeParams.username }).then(function successCallback(res) { var data = res.data; people.parse(data); $scope.user = data; people.list[$routeParams.username] = data; }, function errorCallback(res){ console.error(res); }); } }); /* Profile Controller */ esnApp.controller('ProfileCtrl', function ($rootScope, $scope, $routeParams, $http, people) { var places = [{ name: 'CMU-SV B23', latitude: 37.410439, longitude: -122.059762 }, { name: 'CMU-SV B19', latitude: 37.412353, longitude: -122.058460 }, { name: 'Village Lake Apartments', latitude: 37.4028, longitude: -122.0753 }]; // Initialization people.refresh(function() { $scope.users = people.list; }); var updateLocation = function(latitude, longitude) { var crdStr = latitude + ", " + longitude; $('#coordinate').text(crdStr); var match = places.filter(function(place){ if (Math.abs(place.latitude - latitude) > 0.005) return false; if (Math.abs(place.longitude - longitude) > 0.005) return false; return true; }); if (match.length > 0) { var min_idx = 0; var min_diff = Math.abs(match[0].latitude - latitude) + Math.abs(match[0].longitude - longitude); for (var i = 1; i < match.length; i++) { var diff = Math.abs(match[i].latitude - latitude) + Math.abs(match[i].longitude - longitude); if (diff < min_diff) min_idx = i; } $('#location').val(match[min_idx].name); } }; // click handler angular.element('form[name="profile"]').on('click', function(event) { var target = $(event.target); if (target.attr('id') === 'getCoordinate') { if (!navigator.geolocation) { console.log("Geolocation is not supported by this browser."); } else { $('#getCoordinate').button('loading'); // change the button's looking navigator.geolocation.getCurrentPosition(function(position) { updateLocation(position.coords.latitude, position.coords.longitude); $('#getCoordinate').button('reset'); }, function showError(error) { switch (error.code) { case error.PERMISSION_DENIED: toastr.error("You denied the request for getting location."); break; case error.POSITION_UNAVAILABLE: toastr.error("Location information is unavailable."); break; case error.TIMEOUT: toastr.error("The request to get location timed out."); break; case error.UNKNOWN_ERROR: toastr.error("An unknown error occurred."); break; } $('#getCoordinate').button('reset'); }); } } else if (target.attr('id') === 'inputCoordinate') { latitude = window.prompt('Latitude?'); if (latitude === null || latitude === '') return; longitude = window.prompt('Longitude?'); if (longitude === null || longitude === '') return; updateLocation(latitude, longitude); } }); // submit handler angular.element('form[name="profile"]').on('submit', function(event) { event.preventDefault(); var toUpdate = {}; var val = $('#firstname').val(); if (val !== $rootScope.me.firstname) toUpdate.firstname = val; val = $('#lastname').val(); if (val !== $rootScope.me.lastname) toUpdate.lastname = val; val = $('#location').val(); if (val !== $rootScope.me.location) toUpdate.location = val; val = $('#coordinate').text(); if (val !== $rootScope.me.coordinate) toUpdate.coordinate = val; val = $('#peopleiknow').val(); val = (val === null)? '': val.join(', '); if (val !== $rootScope.me.peopleiknow) toUpdate.peopleiknow = val; toUpdate.updatedAt = new Date().toISOString(); console.log(toUpdate); $http.put('/user/' + $rootScope.my_username, toUpdate).then(function successCallback(res){ for (var i in toUpdate) { $rootScope.me[i] = toUpdate[i]; } toastr.success("Changes Saved"); }, function errorCallback(res){ console.error(res); toastr.error("failed to update"); }); }); }); /* Chat Controller */ esnApp.controller('ChatCtrl', function ($rootScope, $scope, $http, $routeParams, messages) { $scope.target = $routeParams.target; $('a[href="#/chat/'+ $routeParams.target + '"]').children('.badge').text(''); if ($scope.target === 'public') { $scope.msgs = messages.publicMsgs; if ($scope.msgs.length === 0) { // Get previous messages messages.refresh(null, function(publicMsgs) { $scope.msgs = publicMsgs; }); } } else { $scope.msgs = messages.privateMsgs[$scope.target]; if (!$scope.msgs) { messages.refresh($scope.target, function(privateMsgs) { $scope.msgs = messages.privateMsgs[$scope.target]; }); } } $('form.msg_input').submit(messages.send); }); $('a.logout').click(function(event) { event.preventDefault(); var usrObj = { username: $('#name').val() }; socket.emit('logout', usrObj); var logoutForm = $('<form method="post">').attr('action', '/user/logout/'); logoutForm.append($('<input type="hidden" name="logoutTime">').val(new Date().toISOString())); logoutForm.appendTo('body').submit(); });
import React, {useContext} from 'react' import AuthContext from '../../context/auth/authContext' import {Route, Redirect} from 'react-router-dom' const AdminRoute = ({component: Component, ...rest}) => { const authContext = useContext(AuthContext) const {isAuth, user} = authContext return ( <Route {...rest} render={props => user && user.role === 0 || !isAuth ? (<Redirect to="/error-page" />) : (<Component {...props} />)} /> ) } export default AdminRoute
// ********* PARSE REQUIREMENTS *********** function string_parser(course) { if (!course) { return []; } const words_array = course.match(/\b(\w|')+\b/gim); const class_and_number = []; words_array.forEach((word, i) => { if (word === `EECS`) { class_and_number.push(word); class_and_number.push(words_array[i+1]); class_and_number.push(words_array[i+2]) } }); const classes = []; let i = 0; class_and_number.forEach(() => { if (i + 2 <= class_and_number.length) { const s = `${class_and_number[i]} ${class_and_number[i+1]}-${class_and_number[i+2]}`; classes.push(s); i += 3; } }); return classes; } module.exports = string_parser;
import EventHandler from "../EventHandler.js"; import BreweryStore from "./BreweryStore.js"; import clickHandlers from "./clickHandlers/index.js"; import handleSearchSubmit from "./submitHandlers/handleSearchSubmit/handleSearchSubmit.js"; import * as actionCreators from "../AC/index.js"; import { scrollToFirstItem } from "../../utils/scroll.js"; import CONSTANT from "../../src/constants.js"; import { scrollTopArrow, modalFavorites, modalBeerItem, } from "./BreweryPageMarkupComponents.js"; const { handleAddToFavorites, handleSearchQuery, handleLoadMoreBeers, } = clickHandlers; export class BreweryEventHandler extends EventHandler { constructor(store) { super(store); } handleClick = async ({ target }) => { const dataForClickHandlers = { target, store: this.store, actionCreators }; if (!!target.dataset.searchQuery) { handleSearchQuery(dataForClickHandlers); } if (target.id === CONSTANT.LOAD_MORE) { handleLoadMoreBeers(dataForClickHandlers); } if (scrollTopArrow.isMyChild(target)) { return scrollToFirstItem(); } if (!!target.dataset.favorite) { handleAddToFavorites(dataForClickHandlers); } if (target.id === CONSTANT.FAVORITE_BTN) { modalFavorites.toggleModal(true); } if (target.dataset.role === CONSTANT.BEER_PICKER) { this.store.dispatch(actionCreators.pickBeerItem(target.id)); modalBeerItem.toggleModal(true); } if (target.dataset.role === CONSTANT.TOGGLE_MODAL) { target.id === CONSTANT.CLOSE_BEER_MODAL ? modalBeerItem.toggleModal(false) : modalFavorites.toggleModal(false); } }; handleSubmit = async (e) => { e.preventDefault(); if (e.target.name === CONSTANT.SEARCH_FORM) { handleSearchSubmit({ target: e.target, store: this.store, actionCreators, }); } }; handleKeydown = (e) => { if (e.code !== CONSTANT.ESCAPE_KEY) return; modalFavorites.toggleModal(false); modalBeerItem.toggleModal(false); }; } export default new BreweryEventHandler(BreweryStore);
module.exports = function () { var tlConfig = require('../../../handlers/lib/tl_config.js')({ server: {}, request: {} }); tlConfig.setTargetSeries([1000, 2000, 3000, 4000]); };
const fs = require('fs-extra'); const arguments = process.argv.splice(2); const dirArr = ['assets', 'components', 'views']; const configArr = ['apis', 'routes']; let content = ''; fs.mkdirSync(`src/modules/${arguments}`); dirArr.forEach(item => fs.mkdirSync(`src/modules/${arguments}/${item}`)); configArr.forEach((item, idx) => { switch (idx) { case 0: content = 'export default {}'; break; case 1: content = 'export default []'; break; } fs.writeFileSync(`src/modules/${arguments}/${item}.js`, content); }); // fs.writeFileSync(`mock/${arguments}.js`, 'module.exports = {}');
import Orientation from 'react-native-orientation'; import React, { Component } from 'react'; import Video from 'react-native-video'; import { Image,StyleSheet,TouchableOpacity,Linking } from 'react-native'; import { Container,Button,Title, Header, View, DeckSwiper, Card, CardItem, Thumbnail, Text, Left,Right, Body, Icon } from 'native-base'; const cards = [ { text: 'موزه', name: 'این مجسمه ی ۱ است', image: {uri : 'file:///Users/bobvv/AwesomeNativeBase/src/Home/image7.jpg'}, } ]; export default class Second2Page extends Component { constructor(props) { super(props) this.state = { buttonname : 0, paused: false, currentTime: '', duration: '' }} componentWillMount() { Orientation.unlockAllOrientations(); // this locks the view to Landscape Mode Orientation.lockToPortrait(); // this unlocks any previous locks to all Orientations // Orientation.addOrientationListener(this._orientationDidChange); } onLoad(data) { this.setState({ duration: data.duration }) } onProgress(data) { this.setState({ currentTime: data.currentTime }) } render() { return ( <Container> <View style={{flex : 1}}> <Image style={{width: '100%', height: '100%',opacity:0.8,position:'absolute'}} source={require('./second.png')} /> <Button rounded primary transparent onPress={() => { this.props.navigation.navigate('conIndex')} } > <Text>بازگشت</Text> </Button> <Button rounded primary transparent style = {{position:"absolute" , right:0}} onPress={() => { this.setState({paused : !this.state.paused}); }} > <Text>قطع صدا</Text> </Button> <Button primary transparent style={{width : '80%',height:'50%',position:'absolute',opacity:0.1,backgroundColor:'black' }} onPress={() => { this.props.navigation.navigate('test2')} } > </Button> <Video source={{uri: 'h2.mp3'}} // Can be a URL or a local file. ref={(ref) => { this.player = ref }} style={{position: "absolute",width:0,height:0}} // Store reference rate={1.0} // 0 is paused, 1 is normal. volume={1.0} // 0 is muted, 1 is normal. muted={false} // Mutes the audio entirely. paused={this.state.paused} // Pauses playback entirely. resizeMode="cover" // Fill the whole screen at aspect ratio.* repeat={false} // Repeat forever. playInBackground={false} // Audio continues to play when app entering background. playWhenInactive={false} // [iOS] Video continues to play when control or notification center are shown. ignoreSilentSwitch={"ignore"} // [iOS] ignore | obey - When 'ignore', audio will still play with the iOS hard silent switch set to silent. When 'obey', audio will toggle with the switch. When not specified, will inherit audio settings as usual. progressUpdateInterval={250.0} // [iOS] Interval to fire onProgress (default to ~250ms) onLoadStart={this.loadStart} // Callback when video starts to load onLoad={this.onLoad.bind(this)} onProgress={this.onProgress.bind(this)} // Callback every ~250ms with currentTime onEnd={this.onEnd} // Callback when playback finishes onError={this.videoError} // Callback when video cannot be loaded onBuffer={this.onBuffer} // Callback when remote video is buffering onTimedMetadata={this.onTimedMetadata} // Callback when the stream receive some metadata /> </View> </Container> ); } }
class Functor { static of (value) { return new Functor(value) } constructor (value) { this._value = value } map (f) { return new Functor(f(this._value)) } value (f) { return f(this._value) } }
import apiUrl from './api.js' import * as types from './type.js'; import {sendRequest} from '@/request/axios.js' const state={ [types.POST_LOGIN]:{}, [types.POST_LONG_OUT]:"", [types.GET_USER_MENU]:{}, } const getters={ } const actions ={//异步 async [types.POST_LOGIN](cxt,postData){ cxt.commit(types.POST_LOGIN,await sendRequest(apiUrl.login,postData,'post')) }, async [types.POST_LONG_OUT](cxt,postData){ cxt.commit(types.POST_LONG_OUT,await sendRequest(apiUrl.loginOut,postData,'post')) }, async [types.GET_USER_MENU](cxt,postData){ cxt.commit(types.GET_USER_MENU,await sendRequest(apiUrl.loginWeight,postData,'get')) }, } const mutations ={//同步 [types.POST_LOGIN](state,data){ state[types.POST_LOGIN]= data.data }, [types.POST_LONG_OUT](state,data){ state[types.POST_LONG_OUT]= data.data }, [types.GET_USER_MENU](state,data){ state[types.GET_USER_MENU]= data.data }, } export default { namespaced: true,//解决不同模块命名冲突的问题,需要加上所属的模块名 state, getters, actions, mutations }
/* /client/factories/item.js The "Client Side DB" / connection between the client and the server (where the client can request additional data) */ app.factory("pollFactory", function ($http, $location) { console.log("Created pollFactory Factory"); var factory = {}; var polls = []; var username = ""; factory.getPolls = function(callback){ $http({method: 'GET', url: '/polls'}) .then(function(response){ callback(response.data) polls = response.data }) }, factory.addnew = function(addpoll, username){ //console.log("factory username = ", username) addpoll.username = username $http({method: 'POST', url: '/addpoll', data: addpoll}) .then(function(response){polls.push(response.data)}) $location.url('/all') console.log('factory addnew --> ', addpoll) }, factory.delete = function(index, id){ $http({method: 'PUT', url:'/delete/'+id}) polls.splice(index, 1) }, factory.login = function(loginname){ console.log("factory received login name: ", loginname) username = loginname }, factory.getuser = function(callback){ callback(username) return username }, factory.updatepoll = function(data){ $http({method: 'POST', url: '/polls', data: data}) console.log("update poll route hit factory outgoing....") } return factory; });
import React from "react"; import styled from "styled-components"; import { useMutation } from "react-apollo-hooks"; import confirmUser from "../../graphql/user/mutations/confirmUser"; const StyledButton = styled.button` background-color: #3897f0; border: none; outline: none; width: 100%; color: #fff; cursor: pointer; padding: 9px 0; border-radius: 4px; margin-top: 10px; font-size: 14px; &:focus, &:active { opacity: 0.7; } `; const Wrapper = styled.div` margin: auto; padding: 40px; width: 100%; max-width: 350px; border: 1px solid #e6e6e6; border-radius: 1px; background-color: #fff; `; const ConfirmUser = props => { const confirm = useMutation(confirmUser, { variables: { token: props.match.params.token } }); return ( <Wrapper> <StyledButton onClick={async () => { await confirm(); props.history.push("/"); }} > Confirm </StyledButton> </Wrapper> ); }; export default ConfirmUser;
const { addSerializers, minimalRnw } = require("@times-components/jest-serializer"); addSerializers(expect, minimalRnw());
var windowWidth = window.innerWidth, windowHeight = window.innerHeight, scrollPosition = $(window).scrollTop(); $(document).ready(function() { $('#slide-next').click(function(){ $('#logo').addClass('white'); }); $('#slide-one').css({ 'width': windowWidth, 'min-height': windowHeight }); $('.list-case-studies li').click(function(){ $(this).parent().css({ 'position': 'static', 'box-shadow': '0px 0px 0px 0px #000000' }); $('.list-case-studies li').hide(); $(this).show(); $(this).addClass('active'); $('.close').fadeIn(); }); $('a.close').click(function(){ $('.list-case-studies').css({ 'position': 'relative', 'box-shadow': '0px 0px 5px 5px rgba(0,0,0,0.25)' }); $('.list-case-studies li').removeClass('active'); $('.list-case-studies li').show(); $('.close').hide(); $('.slimScroll').slimScroll({ destroy: true }); }); $(".footer-nav > ul > li").click(function() { $(".footer-nav > ul > li").find("ul").fadeOut(); $(this).find("ul").fadeIn(); $(".footer-nav > ul > li").removeClass("active"); $(this).addClass("active"); }); // Window Load $(window).resize(function(){ windowWidth = window.innerWidth; windowHeight = window.innerHeight; $('#slide-one').css({ 'width': windowWidth, 'min-height': windowHeight }); }); });
var intervalID; var counter = 10; var laDiv; function init(){ laDiv=document.getElementById('div'); laDiv.setAttribute('id','div'); count(laDiv); } function count(){ intervalID = setInterval(decremente,1000); // attention dans le setInterval passer une callback et pas une éxécution de fonction, donc ne dois pas avoir d'argument } function decremente(){ laDiv.innerHTML = counter; counter -=1; if(counter ===0){ clearInterval(intervalID); } }
const fs = require('fs') const config = require('../config.json') const sqlCmds = require('../rss/sql/commands.js') const fileOps = require('../util/fileOps.js') const channelTracker = require('../util/channelTracker.js') const currentGuilds = require('../util/storage.js').currentGuilds module.exports = function (bot, guild) { console.log(`Guild "${guild.name}" (Users: ${guild.members.size}) has been removed.`) guild.channels.forEach(function (channel, channelId) { if (channelTracker.hasActiveMenus(channel.id)) channelTracker.remove(channel.id) }) if (!fs.existsSync(`./sources/${guild.id}.json`)) return const rssList = currentGuilds.get(guild.id).sources for (var rssName in rssList) { sqlCmds.dropTable(config.feedManagement.databaseName, rssName) } fileOps.deleteGuild(guild.id, null, function () { console.log(`RSS Info: Guild profile ${guild.id}.json (${guild.name}) deleted from sources folder.`) }) if (!config.logging.discordChannelLog) return const logChannelId = config.logging.discordChannelLog const logChannel = bot.channels.get(config.logging.discordChannelLog) if (typeof logChannelId !== 'string' || !logChannel) { if (bot.shard) { bot.shard.broadcastEval(` const channel = this.channels.get('${logChannelId}'); if (channel) { channel.send('Guild Info: "${guild.name}" has been removed.\\nUsers: ${guild.members.size}').catch(err => console.log('Could not log guild removal to Discord, ', err.message || err)); true; } `).then(results => { for (var x in results) if (results[x]) return console.log(`Error: Could not log guild addition to Discord, invalid channel ID.`) }).catch(err => console.log(`Guild Info: Error: Could not broadcast eval log channel send for guildDelete. `, err.message || err)) } else console.log(`Error: Could not log guild removal to Discord, invalid channel ID.`) } else logChannel.send(`Guild Info: "${guild.name}" has been removed.\nUsers: ${guild.members.size}`).catch(err => console.log(`Could not log guild removal to Discord. (${err}) `)) }
import ContentEditable from './ContentEditable' module.exports = ContentEditable
var dir__97aefd0d527b934f1d99a682da8fe6a9_8js = [ [ "dir_97aefd0d527b934f1d99a682da8fe6a9", "dir__97aefd0d527b934f1d99a682da8fe6a9_8js.html#a7cef41ea1d1f578ec7d566de7f46f63d", null ] ];
const fs = require('fs') function init(){ let details = fs.readFileSync(`${__dirname}/input.txt`,'utf8') console.log(`Welcome to CodeWars, ${details}!`) } init()
import Vue from 'vue' import Router from 'vue-router' import Home from './views/Home.vue' Vue.use(Router) export default new Router({ mode: 'history', base: process.env.BASE_URL, linkActiveClass: 'is-active', routes: [ { path: '/', name: 'Home', component: Home }, { path: '/characters', name: 'Characters', component: () => import(/* webpackChunkName: "characters" */ './views/CharacterIndex') }, { path: '/characters/:id', name: 'Character', component: () => import(/* webpackChunkName: "character" */ './views/CharacterPage') }, { path: '/locations', name: 'Locations', component: () => import(/* webpackChunkName: "locations" */ './views/LocationIndex') }, { path: '/locations/:location', name: 'Location', component: () => import(/* webpackChunkName: "location" */ './views/LocationPage.vue') }, { path: '/shops/:id', name: 'Shop', component: () => import(/* webpackChunkName: "shop" */ './views/ShopPage.vue') }, { path: '/items', name: 'Items', component: () => import(/* webpackChunkName: "items" */ './views/ItemIndex.vue') }, { path: '/items/:category', name: 'ItemCategory', component: () => import(/* webpackChunkName: "item" */ './views/ItemCategory.vue') } ] })
import { UI } from "./ui.js"; class Widget { /** * Widget (abstract) constrcutor * @param {UI} ui parent UI */ constructor(ui) { /** * Parent ui element * @type {UI} */ this.ui = ui; /** * The element where the widget lives * @type {HTMLDivElement} */ this.elm = document.createElement("div"); this.elm.classList.add("widget"); this.ui.widgets.push(this); } /** * Appends to parent element * @param {HTMLElement} elm element to append to */ appendTo(elm) { elm.appendChild(this.elm); } /** * appends widget * @param {Widget} widget widget to append */ append(widget) { widget.appendTo(this.elm); } /** * Called when structure of circuit changes */ updateStruct() { } /** * Called when any part of circuit changes */ update() { } } export { Widget };
exports.up = function(knex, Promise) { return knex.schema.createTable("author", function(author){ author.increments(); author.string("name"); }); }; exports.down = function(knex, Promise) { return knex.schema.dropTableIfExists("author"); };
import React from 'react'; import { Route, Switch, Link } from 'react-router-dom'; import Button from '@material-ui/core/Button'; import Task from '../../components/TaskInfo'; import TaskNotFound from '../../components/TaskNotFound'; export default ({ match }) => { return ( <div> <Button component={Link} to="/" color="secondary"> Homepage </Button> <Switch> <Route exact path={`${match.url}/:taskId`} component={Task} /> <Route component={TaskNotFound} /> </Switch> </div> ); };
import axios from 'axios'; export const getProcess = () => async dispatch => { const ID = await localStorage.getItem('user'); const response = await axios.get('http://econseil.dd:8083/jsonapi/node/processus_metier?include=field_img_proc_met,field_proc_met_proc_met_parent,field_proc_met_sous_proc_met,field_proc_metier_docs,field_proc_metier_proc_orgs'); console.log(response) var Procsorg = []; response.data.data.map(order => { order['documents'] = []; order['procedures'] = []; order['childs'] = []; order['parent'] = {}; order['image'] = {}; var docIndex = order.relationships.field_proc_metier_docs.data.length; var proceduresIndex = order.relationships.field_proc_metier_proc_orgs.data.length var childsIndex = order.relationships.field_proc_met_sous_proc_met.data.length response.data.included.map(file => { if (order.relationships.field_organisme.data.id == ID) { for (let i = 0; i < docIndex; i++) { if ((file.id === order.relationships.field_proc_metier_docs.data[i].id) || file.id === undefined) { order.documents.push(file); Procsorg = [...Procsorg, order]; } } for (let i = 0; i < proceduresIndex; i++) { if ((file.id === order.relationships.field_proc_metier_proc_orgs.data[i].id) || file.id === undefined) { order.procedures.push(file); Procsorg = [...Procsorg, order]; } } for (let i = 0; i < childsIndex; i++) { if ((file.id === order.relationships.field_proc_met_sous_proc_met.data[i].id) || file.id === undefined) { order.childs.push(file); Procsorg = [...Procsorg, order]; } } // if ((order.relationships.field_proc_met_proc_met_parent.data.id != null) && (file.id === order.relationships.field_proc_met_proc_met_parent.data.id || file.id === undefined)) { // order.parent = file // Procsorg = [...Procsorg, order]; // } if (file.id === order.relationships.field_img_proc_met.data.id || file.id === undefined) { order.image = file Procsorg = [...Procsorg, order]; } } } ) console.log(order) } ); console.log(Procsorg) dispatch( { type: 'GET_PROCMET', payload: Procsorg } ); } export const getOneProcess = (identifier) => async dispatch => { const response = await axios.get('http://econseil.dd:8083/jsonapi/node/processus_metier/'+identifier+'?include=field_img_proc_met,field_proc_met_proc_met_parent,field_proc_met_sous_proc_met,field_proc_metier_docs,field_proc_metier_proc_orgs'); console.log(response) var order = response.data.data; var procmet = {}; procmet['nom'] = ""; procmet['code'] = order.attributes.field_code_proc_metier; procmet['documents'] = []; procmet['procedures'] = []; procmet['childs'] = []; procmet['parent'] = {}; procmet['image'] = {}; var docIndex = order.relationships.field_proc_metier_docs.data.length; var proceduresIndex = order.relationships.field_proc_metier_proc_orgs.data.length var childsIndex = order.relationships.field_proc_met_sous_proc_met.data.length response.data.included.map(file => { for (let i = 0; i < docIndex; i++) { if ((file.id === order.relationships.field_proc_metier_docs.data[i].id) || file.id === undefined) { procmet.documents.push(file); } } for (let i = 0; i < proceduresIndex; i++) { if ((file.id === order.relationships.field_proc_metier_proc_orgs.data[i].id) || file.id === undefined) { procmet.procedures.push(file); } } for (let i = 0; i < childsIndex; i++) { if ((file.id === order.relationships.field_proc_met_sous_proc_met.data[i].id) || file.id === undefined) { procmet.childs.push(file); } } // if ((order.relationships.field_proc_met_proc_met_parent.data.id != null) && (file.id === order.relationships.field_proc_met_proc_met_parent.data.id || file.id === undefined)) { // order.parent = file // Procsorg = [...Procsorg, order]; // } if (file.id === order.relationships.field_img_proc_met.data.id || file.id === undefined) { procmet.image = 'http://econseil.dd:8083'+ file.attributes.uri.url; } } ); // var Procmet = Procsorg.reduce((unique, o) => { // if(!unique.some(obj => obj.id === o.id)) { // unique.push(o); // } // return unique; // },[]); // console.log(Procmet) dispatch( { type: 'GET_ONE_PROCMET', payload: procmet } ); }
// Rock-paper-Scissors variables let userChoice; let rock = document.querySelector("button[name='rock']"); let paper = document.querySelector("button[name='paper']"); let scissors = document.querySelector("button[name='scissors']"); let computerChoice; let randomNumber = Math.random(); let img; // Score keeper variables let p1 = 0; let p2 = 0; let p1button = document.querySelector("#player1button"); let p2button = document.querySelector("#player2button"); let winningScoreDisplay = document.querySelector("#limit"); let numInput = document.querySelector("input"); let winningScore = 5; let span1 = document.querySelector("#score1"); let span2 = document.querySelector("#score2"); let gameOver = false; let reset = document.querySelector("#reset"); let play = document.querySelector("button[name='playAgain']"); // Score keeper functions // 1) add score on button click and change color when limit is reached function p1change(){ if(!gameOver){ p1++; console.log(p1, winningScore) if (p1 === winningScore) { span1.classList.add("winner"); span2.classList.add("looser") gameOver = true; } }; console.log("p1 score= " + p1) span1.textContent = p1; }; // 2) add score on button click and change color when limit is reached function p2change(){ if(!gameOver){ p2++; if(p2 === winningScore){ span2.classList.add("winner"); span1.classList.add("looser") gameOver = true; } console.log("p2 score= "+ p2); span2.textContent = p2; } }; //Relate chosen limit and displayed limit function limitScore(){ winningScoreDisplay.textContent = numInput.value; winningScore = Number(numInput.value); }; // RPS functions function computerChose(){ let randomNumber = Math.random(); if(randomNumber< 0.34) { computerChoice = "scissors" } if(randomNumber>= 0.34 && randomNumber<0.67) { computerChoice= "rock" } if(randomNumber>=0.67){ computerChoice= "paper" } console.log(`computer chose ${computerChoice}`); }; function youWin(){ console.log("user wins"); p1change(); document.querySelector("#userChoice").innerHTML = `You chose ${imgU}`; document.querySelector("#computerChoice").innerHTML = `Computer chose ${imgC}`; document.querySelector("#winner").innerHTML = "You win!!"; }; function youLoose(){ console.log("computer wins"); p2change(); document.querySelector("#userChoice").innerHTML = `You chose ${imgU}`; document.querySelector("#computerChoice").innerHTML = `Computer chose ${imgC} `; document.querySelector("#winner").innerHTML = "Computer wins"; }; function itsaDraw() { console.log("it's a draw"); document.querySelector("#userChoice").innerHTML = `You chose ${imgU} `; document.querySelector("#computerChoice").innerHTML = `Computer chose ${imgC}`; document.querySelector("#winner").innerHTML = "It's a draw"; }; function displayImgU(){ if(userChoice==="paper"){ imgU = "<img class='imgSize' src='/home/torof/Desktop/coderscJs.js/pictures/paper.jpg' alt='paper'>"; } if(userChoice==="rock"){ imgU = "<img class='imgSize' src='/home/torof/Desktop/coderscJs.js/pictures/rock.jpg' alt='rock'>"; } if(userChoice==="scissors"){ imgU = "<img class='imgSize' src='/home/torof/Desktop/coderscJs.js/pictures/scissors.jpg' alt='scissors'>"; } } function displayImgC(){ if(computerChoice==="paper"){ imgC = "<img class='imgSize' src='/home/torof/Desktop/coderscJs.js/pictures/paper.jpg' alt='paper'>"; } if(computerChoice==="rock"){ imgC = "<img class='imgSize' src='/home/torof/Desktop/coderscJs.js/pictures/rock.jpg' alt='rock'>"; } if(computerChoice==="scissors"){ imgC = "<img class='imgSize' src='/home/torof/Desktop/coderscJs.js/pictures/scissors.jpg' alt='scissors'>"; } } function stopPlaying() { document.querySelector("#winner").innerHTML = "Game is over!"; } function winnerIs() { if(p1 === winningScore){ document.querySelector("#displayWinner").innerHTML = "The Winner is : USER" } if(p2 === winningScore){ document.querySelector("#displayWinner").innerHTML = "The Winner is : COMPUTER" } } //User chose Rock rock.addEventListener("click", function(){ // Computer choice computerChose(); // User choice userChoice="rock"; console.log(`You chose ${userChoice}`); displayImgU(); displayImgC(); // result if(userChoice === "rock" && computerChoice === "scissors"){ youWin(); } if(userChoice === "rock" && computerChoice === "paper"){ youLoose(); } if(userChoice === computerChoice){ itsaDraw(); } if(p2 === winningScore){ stopPlaying(); winnerIs(); } if(p1 === winningScore){ stopPlaying(); winnerIs(); } }); //User chose Paper paper.addEventListener("click", function(){ // Computer choice computerChose(); // user choice userChoice="paper" console.log(`You chose ${userChoice}`); displayImgU(); displayImgC(); // result if(userChoice==="paper" && computerChoice==="rock"){ youWin(); } if (userChoice === "paper" && computerChoice === "scissors"){ youLoose(); } if(userChoice === computerChoice){ itsaDraw(); } if(p2 === winningScore){ stopPlaying(); winnerIs(); } if(p1 === winningScore){ stopPlaying(); winnerIs(); } }); //User chose Scissors scissors.addEventListener("click", function(){ // Computer choice computerChose(); // user choice userChoice="scissors"; console.log(`You chose ${userChoice}`); displayImgU(); displayImgC(); // result if(userChoice === "scissors" && computerChoice === "rock"){ youLoose(); } if(userChoice === "scissors" && computerChoice === "paper"){ youWin(); } if(userChoice === computerChoice){ itsaDraw(); } if(p2 === winningScore){ stopPlaying(); winnerIs(); } if(p1 === winningScore){ stopPlaying(); winnerIs(); } }); //resets everything function resetbtn (){ p1 = 0; p2 = 0; winningScoreDisplay.innerHTML = "0"; winningScore = 0; span1.textContent = 0; span2.textContent = 0; span1.classList.remove("winner"); span1.classList.remove("looser"); span2.classList.remove("winner"); span2.classList.remove("looser"); gameOver = false; numInput.value = 0; document.querySelector("#userChoice").innerHTML = ""; document.querySelector("#computerChoice").innerHTML = ""; document.querySelector("#winner").innerHTML = ""; document.querySelector("#displayWinner").innerHTML = ""; }; // Play again, resets score but no reset score limit function playAgain (){ p1 = 0; p2 = 0; winningScoreDisplay.innerHTML = winningScore; span1.textContent = 0; span2.textContent = 0; span1.classList.remove("winner"); span1.classList.remove("looser"); span2.classList.remove("winner"); span2.classList.remove("looser"); gameOver = false; document.querySelector("#userChoice").innerHTML = ""; document.querySelector("#computerChoice").innerHTML = ""; document.querySelector("#winner").innerHTML = ""; document.querySelector("#displayWinner").innerHTML = ""; } //Actions numInput.addEventListener("change", limitScore); reset.addEventListener("click", resetbtn); play.addEventListener("click", playAgain);
const express = require('express'); const bcrypt = require('bcrypt'); const router = express.Router(); const Teacher = require('../model/teacher'); router.post('/registerteacher', async(req, res) => { const { username, password, name, lastname, id } = req.body // simple validation if (!id || !name || !lastname || !username || !password) { return res.render('registerteacher', { message: 'Please try again' }) } //const passwordHash = bcrypt.hashSync(password, 10) const teacher = new Teacher({ id, name, lastname, username, password: passwordHash }); await teacher.save() req.session.teacher = teacher; res.render('index', { teacher }) }); router.post('/loginteacher', async(req, res) => { const { username, password } = req.body; // simple validation const teacher = await Teacher.findOne({ username }); if (teacher) { const isCorrect = password if (isCorrect) { req.session.teacher = teacher; return res.redirect('/indexteacher'); } else { return res.render('loginteacher', { message: 'Username or Password incorrect' }) } } else { return res.render('loginteacher', { message: 'Username does not exist.' }) } }) module.exports = router
import React from "react"; import "./HomeHeader.css"; const HomeHeader = () => { return ( <main className="homeHeader"> <div className="container"> <div className="row "> <div className="col-md-10 homeHeaderColumn"> <h2 className="text-white homeHeaderTitle"> We Give Life To Your <br /> <span className="homeHeaderTitleColor"> Electronic</span> Devices </h2> <p className="text-white homeHeaderSummary"> We are providing the Electronic Device Repair services from last 23 years. We believe in giving the best services to our clients. We use all the modern technologies to make fast repair services. Just send your valuable{" "} <strong className="homeHeaderTitleColor"> Laptop, PC, Mobile, Gaming Device or Smartphone </strong>{" "} and we will take care of it. We will happy to server our best to you at affordable price, just keep faith on us. We are happy to give an awesome repair experience to your devices. </p> <div> <button type="button" class="btn btn-light fw-bold homeButtonOne" > Get Start Now </button> <button type="button" class="btn fw-bold homeButtonTwo"> Learn More </button> </div> </div> </div> </div> </main> ); }; export default HomeHeader;
export { default as Image } from './Image'; export { default as document } from './Document'; export { default as lcalStorage } from './LocalStorage'; export { innerWidth, innerHeight } from './WindowProperties' export { setTimeout } export { setInterval } export { clearTimeout } export { clearInterval } export { requestAnimationFrame } export { cancelAnimationFrame }
/** * @date-of-doc: 2015-07-06 * @project-version: v0.2 * @called-by: * ../index.php * @calls: php/check_username_exists.php * @description: * This file takes in data from index.php and provides client-side validation to the data * The file ensures that the fields give correct data before returning 'true' to the calling html form. */ var fieldIsValid = [false, false]; function validateForm() { validateUsername(); validatePassword(); console.log(fieldIsValid); } function validateUsername() { var usernameInput = document.forms["viewer_login_form"]["username"].value.trim(); if(usernameInput.trim() === "") { document.getElementById("username_feedback").innerHTML = ""; fieldIsValid[0] = false; } else if(usernameInput.length < 4) { document.getElementById("username_feedback").innerHTML = "Username below 4 characters"; fieldIsValid[0] = false; } else { var container = document.getElementById("username_feedback"); checkUsernameExists(usernameInput, container); } console.log(fieldIsValid); } function validatePassword() { var userPasswordInput = document.forms["viewer_login_form"]["password"].value; if(userPasswordInput === "") { document.getElementById("password_feedback").innerHTML = ""; fieldIsValid[1] = false; } else if (userPasswordInput.length < 8) { document.getElementById("password_feedback").innerHTML = "Password too short"; fieldIsValid[1] = false; } else { document.getElementById("password_feedback").innerHTML = ""; fieldIsValid[1] = true; } console.log(fieldIsValid); } function checkUsernameExists(usernameInput, container) { var xmlhttp; if(window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var response = parseInt(xmlhttp.responseText); if(response == 1) { container.innerHTML = "We recognise you!"; fieldIsValid[0] = true; } else { container.innerHTML = "We don't seem to know you"; fieldIsValid[0] = false; } } /*else { container.innerHTML = ""; fieldIsValid[4] = true; }*/ } xmlhttp.open("GET", "php/check_username_exists.php?username=" + usernameInput, true); xmlhttp.send(); } function isFormValid() { validateForm(); var formIsValid = true; for(i = 0; i < fieldIsValid.length; i++) { console.log(fieldIsValid[i]); if(!fieldIsValid[i]) { formIsValid = false; } } if(!formIsValid) { alert("Log in information is incomplete/contain invalid fields"); return false; } else { return true; } }
var express = require('express'); var router = express.Router(); var check = require('../public/js/check.js'); /* GET users listing. */ router.get('/', check.notLogin, function(req, res, next) { //清除用户信息 req.session.user = null; req.flash('success', '登出成功!'); res.redirect('/');//登出成功后跳转到主页 }); module.exports = router;
function getObjectURL(file) { var url = null ; if (window.createObjectURL!=undefined) { // basic url = window.createObjectURL(file) ; } else if (window.URL!=undefined) { // mozilla(firefox) url = window.URL.createObjectURL(file) ; } else if (window.webkitURL!=undefined) { // webkit or chrome url = window.webkitURL.createObjectURL(file) ; } return url ; } function check_img0() { $("#upImg").change(function () { var objUrl = getObjectURL(this.files[0]); if (objUrl) { $("#perImg").attr("src", objUrl); } $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); var formData = new FormData(); formData.append('file', $('#upImg')[0].files[0]); $.ajax({ url: '/resume/image', type: 'post', cache: false, data: formData, processData: false, contentType: false }).done(function (res) { console.info(res); $('#Picture').val(res.file); }).fail(function (res) { }); }) } // 基本信息 function upInfo() { $("#infBox").css("display",'none'); $("#upName").val($("#name").html()); if($('#sex').html()=="男"){ $("input:radio[name='Sex']:first").attr("checked","true"); } else { $("input:radio[name='Sex']:last").attr("checked","true"); } $("#selEdu").val($("#edu").html()); $("#selExp").val($("#exp").html()); $("#upTel").val($("#tel").html()); $("#upEmail").val($("#email").html()); $("#selStatus").val($("#status").html()); $("#infoForm").css("display",'block'); } function quitInfo() { $("#infBox").css("display",'block'); $("#infoForm").css("display",'none'); } function saveInfo() { var a,b,c,d,e,f,g; a=$("#upName").val();//名字 b=$("input[name='Sex']:checked").val();//性别 c=$("#selEdu").val();//学历 d=$("#selExp").val();//经验 e=$("#upTel").val();//电话 f=$("#upEmail").val();//邮箱 g=$("#selStatus").val();//目前状态 $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ type: "POST", data: { name:a, sex:b, education:c, workYear:d, phone:e, email:f, state:g }, url:"/resume/basic" }).done(function (data) {//记得要在html里写东西 console.info(data) if(data.flag==true) { $("#name").html(a);//名字 $('#sex').html(b);//性别 $("#edu").html(c);//学历 $("#exp").html(d);//经验 $("#tel").html(e);//电话 $("#email").html(f);//邮箱 $("#status").html(g);//目前状态 $("#infBox").css("display", 'block'); $("#infoForm").css("display", 'none'); } else { alert("保存不成功"); } }) } // 基本信息 end // 期望工作 function upHope() { $("#hopeBox").css("display",'none'); $("#upcity").val($("#city").html()); $("input:radio[name='type'][value='"+$("#type").html()+"']").attr("checked","true"); $("#upposition").val($("#position").html()); $("#uppay").val($("#pay").html()); $("#hopeForm").css("display",'block'); } function quitHope() { $("#hopeBox").css("display",'block'); $("#hopeForm").css("display",'none'); } function saveHope() { var a,b,c,d; a=$("#upcity").val();//期望城市 b=$("input:radio[name='type']:checked").val();//工作类型 c=$("#upposition").val();//期望职位 d=$("#uppay").val();//期望月薪 $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ type: "POST", data: { city:a, nature:b, profession:c, salary:d }, url:"/resume/hopeProfession" }).done(function (data) { console.info(data); if(data.flag==true) { $("#city").html(a);//期望城市 $('#type').html(b);//工作类型 $("#position").html(c);//期望职位 $("#pay").html(d);//期望月薪 $("#hopeBox").css("display", 'block'); $("#hopeForm").css("display", 'none'); } else { alert("保存不成功"); } }) } // 期望工作end // 工作经历 function upWork() { $("#workBox").css("display",'none'); $("#upcompany").val($("#company").html()); $("#upjob").val($("#job").html()); $("#upWorkStaYear").val($("#workStaYear").html()); $("#upWorkStaMon").val($("#workStaMon").html()); $("#upWorkEndYear").val($("#workEndYear").html()); $("#upWorkEndMon").val($("#workEndMon").html()); $("#workForm").css("display",'block'); } function quitWork() { $("#workBox").css("display",'block'); $("#workForm").css("display",'none'); } function saveWork() { var a,b,c,d,e,f; a=$("#upcompany").val();//公司名称 b=$("#upjob").val();//职位名称 c=$("#upWorkStaYear").val();//开始年份 d=$("#upWorkStaMon").val();//开始月份 e=$("#upWorkEndYear").val();//结束年份 f=$("#upWorkEndMon").val();//结束月份 $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ type: "POST", data: { company:a, profession:b, beginYearTime:c, beginMonthTime:d, endYearTime:e, endMonthTime:f }, url:"/resume/workExperience" }).done(function (data) { console.info(data); if(data.flag==true) { $("#company").html(a);//公司名称 $("#job").html(b);//职位名称 $("#workStaYear").html(c);//开始年份 $("#workStaMon").html(d);//开始月份 $("#workEndYear").html(e);//结束年份 $("#workEndMon").html(f);//开始月份 $("#workBox").css("display", 'block'); $("#workForm").css("display", 'none'); } else { alert("保存不成功"); } }) } // 教育经历 function upEdu() { $("#eduBox").css("display",'none'); $("#upschool").val($("#school").html()); $("#updegree").val($("#degree").html()); $("#upmajor").val($("#major").html()); $("#upeduStaYear").val($("#eduStaYear").html()); $("#upeduEndYear").val($("#eduEndYear").html()); $("#eduForm").css("display",'block'); } function quitEdu() { $("#eduBox").css("display",'block'); $("#eduForm").css("display",'none'); } function saveEdu() { var a,b,c,d,e; a=$("#upschool").val();//学校 b=$("#updegree").val();//学位 c=$("#upmajor").val();//专业 d=$("#upeduStaYear").val();//开始年份 e=$("#upeduEndYear").val();//结束年份 $.ajax({ type: "POST", data: { 1:a, 2:b, 3:c, 4:d, 5:e }, url:"" }).done(function (data) { if(data.flag==true) { $("#school").html(a); $("#degree").html(b); $("#major").html(c); $("#eduStaYear").html(d); $("#eduEndYear").html(e); $("#eduBox").css("display", 'block'); $("#eduForm").css("display", 'none'); } else { alert("保存不成功"); } }) } // 教育经历end function showupload() { $('#upload_resume').show(); } function uploadQuit() { $('#upload_resume').hide(); } function uploadResume(){ $("#uploadResume").attr("disabled","true").css("background","silver").attr("value","上传中..."); $("#uploadQuit").attr("disabled","true").css("background","silver"); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); var formData = new FormData(); formData.append('file', $('#uploadFile')[0].files[0]); $.ajax({ url: '/upload/file', type: 'post', cache: false, data: formData, processData: false, contentType: false }).done(function (res) { console.info(res.flag); if(res.flag==true){ $("#uploadResume").attr("disabled","false").css("background","#0d9572").attr("value","上传"); $("#uploadQuit").attr("disabled","false").css("background","#0d9572"); alert("上传成功"); $('#upload_resume').hide(); } }).fail(function (res) { alert("上传不成功"); }); }
const path = require('path') console.log('获取后缀名',path.extname('a.md'))
/** * 列表JS */ /* * ========================= Query初始化 ========================= */ $(document).ready(function() { initTable(); }); /* * 列表操作 */ function initTable(){ var table=$('#commTable').bootstrapTable({ method : 'get', cache:false, url : BASE+'friends', pagination : true, showPaginationSwitch :false, pageSize : 5, pageList : [ 5, 10, 15,20], search : false, showExport : false, sidePagination : 'server', queryParams : function(params) { params.fName = $('#fName').val(); params.email = $('#email').val(); return params; }, responseHandler:responseHandler, onPostBody : function() { $('#commTable').bootstrapTable("resetView"); $(".btn").popover({ trigger : 'hover' }); } }); //分页操作 $('#togglePagBtn').click(function() { $('#commTable').bootstrapTable('togglePagination'); }); //查询操作 $('#queryBtn').click(function() { $('#commTable').bootstrapTable('selectPage',1); }); $(window).resize(function() { $('#commTable').bootstrapTable('resetView'); }); //操作事件 window.operateEvents = { //更新 'click .update': function (e, value, row, index) { location.href=BASE + '/friends/'+row.fId; }, //删除 'click .delete': function (e, value, row, index) { fId=row.fId; delOperate(); } }; } //获得服务器端数据 function responseHandler(res) { if("error"==res.RET_CODE){ showAlert(res.RET_MSG); return res; } return res; } /*添加表格【操作】的内容*/ function operateFormatter(value, row, index) { var content='<a ' +' class="update btn btn-xs btn-primary" ' +' role=button ' +' href="javascript:void(0)"> ' +' 更新 ' +' </a> ' +'<a ' +' class="delete btn btn-xs btn-danger" ' +' role=button ' +' href="javascript:void(0)"> ' +' 删除 ' +' </a> ' ; return content; } /*添加表格【性别】的内容*/ function operateSexFormatter(value, row, index) { var sex=row.sex; var content; if(sex==1){ content="男"; }else{ content="女"; } return content; } /*删除操作*/ var fId;//组ID function delOperate(){ if(confirm("是否删除组?")){ deleteTask(); } } //删除信息 var deleteTask=function(){ $.ajax({ url : BASE + "/friends/"+fId, dataType : "json", async : true, data : { }, type : "DELETE", beforeSend : function() { }, error : function() { }, success : function(data) { if(data.code=='success'){ alert(data.msg); $('#commTable').bootstrapTable('refresh'); } else{ alert(data.RET_MSG); } } }); }
// BUTTERCAKE CORE (function ($, window) { 'use strict'; var ButterCake = function () { // DEAFULTS var settings = { plugins: {} }; var enabled = {}; var BcSettings = { breakPoints: { 'sm': 580, 'md': 780, 'lg': 1150, 'xl': 1250 }, body: $('body , html'), } function plugin(pluginName, pluginFuntion, initPlugin) { var initPlugin = '' ? false : initPlugin; settings.plugins[pluginName] = { enabled: initPlugin, run: pluginFuntion }; enabled[pluginName] = initPlugin; this[pluginName] = pluginFuntion; if (initPlugin) { if (enabled[pluginName]) { settings.plugins[pluginName].run() } } } function InitPlugin(pluginName) { if (settings.plugins[pluginName]) { settings.plugins[pluginName].run(); } } function init() { var timer = setTimeout(function () { $.each(enabled, function (pluginName) { if (this) { settings.plugins[pluginName].run(); } }); clearTimeout(timer); }, 100); } return { plugin: plugin, plugins: settings.plugins, init: init, initPlugin: InitPlugin, settings: BcSettings, }; }; Window.prototype.ButterCake = Window.prototype.$BC = ButterCake(); })(jQuery, window); // NAVBAR ButterCake.plugin('navbar', function () { var $toggler = $('.navbar .toggler'); $('.navbar').each(function () { if ($(this).hasClass('expand-sm')) { $(this).attr('data-toggle', ButterCake.settings.breakPoints.sm); } else if ($(this).hasClass('expand-md')) { $(this).attr('data-toggle', ButterCake.settings.breakPoints.md); } else if ($(this).hasClass('expand-lg')) { $(this).attr('data-toggle', ButterCake.settings.breakPoints.lg); } else if ($(this).hasClass('expand-xl')) { $(this).attr('data-toggle', ButterCake.settings.breakPoints.xl); } else if ($(this).hasClass('expanded')) { $(this).attr('data-toggle', 'null'); } else { $(this).attr('data-toggle', 'none'); } sideBar(); $(this).find('.container').append('<div class="shadow-fixed"></div>'); $(this).find('.container-fluid').append('<div class="shadow-fixed"></div>'); }); // SIDEBAR function sideBar() { var $width = $(window).width() + 15; $('.navbar').each(function () { var $toggleWidth = $(this).attr('data-toggle'); if ($toggleWidth !== undefined) { if ($toggleWidth !== 'null' || $toggleWidth === 'none') { if ($width >= $toggleWidth) { $(this).find('.menu-box').removeClass('sideNavbar toggled'); } else { $(this).find('.menu-box').addClass('sideNavbar'); } } } }); } // ON RESIZE $(window).on('resize', function () { sideBar(); }); // TOGGLER CLICK $toggler.on('click', function () { var $id = $(this).attr('data-nav'); ButterCake.settings.body.toggleClass('noScroll'); $($id).toggleClass('toggled'); }); // MENU CLOSE $('.menu-close').on('click', function () { ButterCake.settings.body.removeClass('noScroll'); $('.navbar .menu-box').removeClass('toggled'); }); // SHADOW CLICK $('.navbar .shadow-fixed').click(function (e) { $(this).parents('.navbar').find('.toggled').removeClass('toggled'); ButterCake.settings.body.removeClass('noScroll'); }); }, true); // SLIDEDOWN NAVBAR ButterCake.plugin('slideNavbar', function () { var $elem = $('.navbar .menu-box'); var $toggler = $('.navbar .toggler'); // NAVBAR RESPONSIVE BREAKING POINTS $('.navbar').each(function () { if ($(this).hasClass('expand-sm')) { $(this).attr('data-toggle', ButterCake.settings.breakPoints.sm); } else if ($(this).hasClass('expand-md')) { $(this).attr('data-toggle', ButterCake.settings.breakPoints.md); } else if ($(this).hasClass('expand-lg')) { $(this).attr('data-toggle', ButterCake.settings.breakPoints.lg); } else if ($(this).hasClass('expand-xl')) { $(this).attr('data-toggle', ButterCake.settings.breakPoints.xl); } else if ($(this).hasClass('expanded')) { $(this).attr('data-toggle', 'null'); } else { $(this).attr('data-toggle', 'none'); } menu(); }); // SLIDEDOWN function menu() { var $width = $(window).width(); $('.navbar').each(function () { var $toggleWidth = $(this).attr('data-toggle'); if ($toggleWidth !== undefined) { if ($toggleWidth !== 'null' || $toggleWidth === 'none') { if ($width > $toggleWidth) { $('.menu-box').css('max-height', ''); $(this).find('.menu-box').removeClass('slidedown toggled'); } else { $('.menu-box').css('max-height', 0); $(this).find('.menu-box').addClass('slidedown'); $elem.each(function (e) { var $elemHeight = $($elem)[e].scrollHeight; $(this).attr('data-height', $elemHeight); }); } } } }); } // ON RESIZE $(window).on('resize', function () { menu(); }); // TOGGLER CLICK $toggler.on('click', function () { var $elemId = $(this).attr('data-nav'); $($elemId).toggleClass('toggled'); var $elemHeight = parseFloat($($elemId).attr('data-height')); $($elemId).css('max-height', $elemHeight + "px"); if (parseFloat($($elemId).css('max-height'))) { $($elemId).css('max-height', 0); } else { $($elemId).css('max-height', $elemHeight + "px"); } }); }); // DROPDOWN ButterCake.plugin('dropdown', function () { var $dropdown = $('.dropdown'); $('.dropdown > a').on('click', function (e) { e.preventDefault(); }) $dropdown.on('click', function (event) { event.stopPropagation(); $(this).siblings('.dropdown').removeClass('menu-showing'); $(this).toggleClass('menu-showing'); }); $dropdown.on('mouseleave', function (event) { event.stopPropagation(); $(this).removeClass('menu-showing'); }); ButterCake.settings.body.on('click', function (e) { if (!$(e.target).is('.dropdown')) { $('.dropdown').removeClass('menu-showing'); } }); }, true); // MODAL ButterCake.plugin('modal', function () { // MODAL ANIMATIONS function animateModal($modal) { var animate = $modal.find('.modal-container').attr('data-modal-animate'); if (typeof animate !== typeof undefined && animate !== false) { animate = animate.split(','); return animate; } else { $modal.find('.modal-container').addClass('animation-added'); return ['', '']; } } // MODAL OPEN function modalOpen($modal) { $modal.removeClass('modal-exit').addClass('modal-show'); $modal.find('.modal-container').addClass('animated ' + animateModal($modal)[0]); ButterCake.settings.body.addClass('noScroll'); setTimeout(function () { $modal.find('.modal-container').removeClass('animated ' + animateModal($modal)[0]); }, 1000); } // MODAL CLOSE function modalClose($modal) { $modal.find('.modal-container').addClass('animated ' + animateModal($modal)[1]); if (animateModal($modal)[1] === '') { $modal.find('.modal-container').removeClass('animated ' + animateModal($modal)[1]); $modal.removeClass('modal-show').addClass('modal-exit'); ButterCake.settings.body.removeClass('noScroll'); } else { setTimeout(function () { $modal.find('.modal-container').removeClass('animated ' + animateModal($modal)[1]); $modal.removeClass('modal-show').addClass('modal-exit'); if ($('.modal-show').length === 0) { ButterCake.settings.body.removeClass('noScroll'); } }, 1000); } } // MODAL OPEN ON CLICK $('.modal-open').on('click', function (e) { e.preventDefault(); var target = $(this).attr('data-modal'); var $modal = $('#' + target); modalOpen($modal); }); // MODAL CLOSE ON CLICK $('.modal-close').on('click', function (e) { e.preventDefault(); var target = $(this).attr('data-modal'); var $modal = $('#' + target); modalClose($modal); }); // MODAL PLUGIN $.fn.BCModal = function () { var $target = $(this); function open() { modalOpen($target); } function close() { modalClose($target); } return { open: open, close: close } }; // CLICK EVENT OUTSIDE MODAL $('.modal').on('click', function (e) { if ($(e.target).is('.modal')) { var $modal = $('.modal.modal-show'); modalClose($modal); } }); }, true); // TABS ButterCake.plugin('tabs', function () { $('.tab-link').on('click', function () { var $target = $(this).attr('data-tab'); var $mainParent = $(this).closest('.tabs'); $mainParent.find('.tab-nav .tab-link').removeClass('active'); $("[data-tab='" + $target + "']").addClass('active'); $mainParent.find('.tab-content').removeClass('active'); $('#' + $target).addClass('active'); }); // TAB CLOSE $('.tab-close').on('click', function () { $(this).closest('.tab-content').removeClass('active'); }); }, true); // ACCORDIONS ButterCake.plugin('accordion', function () { $('.accordion').each(function () { if ($(this).hasClass('active')) { var panel = $(this).next('.panel'); $(this).next('.panel').css('max-height', panel[0].scrollHeight + "px"); } $('.accordion').on('click', function () { $('.accordion').next('.panel').css('max-height', 0); $('.accordion').removeClass('active'); panel = $(this).next('.panel'); $(this).addClass('active'); if (parseFloat($(this).next('.panel').css('max-height'))) { $(this).next('.panel').css('max-height', 0); $(this).removeClass('active'); } else { $(this).next('.panel').css('max-height', panel[0].scrollHeight + "px"); } }); }); }, true); // ALERTS ButterCake.plugin('alert', function () { $('.alert .alert-close').on('click', function () { var $this = $(this); $this.parent('.dismissable').fadeOut('fast', function () { $this.parent('.dismissable').remove(); }) }); }, true); // CHIPS ButterCake.plugin('chip', function () { $('.chip .btn-clear-chip').on('click', function () { var $this = $(this); $this.closest('.chip').fadeOut('fast', function () { $this.closest('.chip').remove(); }) }) }, true); // SCROLL SPY ButterCake.plugin('scrollSpy', function (options) { // SETTINGS var scrollSpySetting = { el: '.scrollSpy', spyEl: '.scrollSpy-item', menu: '.scrollSpyMenu', menuLi: '.scrollSpyMenu li', offset: 150, speed: 100, activeClass: 'active' }; $.extend(scrollSpySetting, options); // Add smooth scrolling to all links $(scrollSpySetting.el).on('click', function (event) { event.preventDefault(); var hash = this.hash; $('html, body').animate({ scrollTop: $(hash).offset().top }, scrollSpySetting.speed, function () { window.location.hash = hash; }); }); $(window).on('scroll', function () { $(scrollSpySetting.spyEl).each(function () { if ($(window).scrollTop() >= $(this).offset().top - scrollSpySetting.offset) { var id = $(this).attr('id'); $(scrollSpySetting.menuLi).removeClass(scrollSpySetting.active); $(scrollSpySetting.menu + ' a[href=#' + id + ']').parents('li').addClass(scrollSpySetting.active); } }); }); });
/** * @param {string[]} words * @return {number[][]} */ let Trie = function() { this.node = {}; this.arrayIndex = -1; this.word = ""; }; let buildTrie = function(words) { let trie = new Trie(); for (let i = 0; i < words.length; i++) { let word = words[i]; let chars = word.split("").reverse(); if (word == "") { chars = [""]; } let node = trie.node; for (let j = 0; j < chars.length; j++) { if (node[chars[j]] === undefined) { node[chars[j]] = new Trie(); } node = node[chars[j]]; } node.arrayIndex = i; node.word = word; } return trie; }; var findMatchings2 = function(node, word, results) { if (node.arrayIndex > -1) { if (results.indexOf(node.arrayIndex) == -1) { results.push(node.arrayIndex); } } if (word == "") { for (let key in node) { if (node[key].arrayIndex !== undefined) { findMatchings(node[key], word, results); } } } let chars = word.split(""); for (let i = 0; i < chars.length; i++) { let char = chars[i]; if (node[char] === undefined) { return results; } findMatchings(node[char], word.slice(i + 1), results); } return results; }; var isPalindrome = function(word) { let chars = word.split(""); let left = 0; let right = chars.length - 1; while (left < right) { if (chars[left] != chars[right]) { return false; } left++; right--; } return true; }; var palindromePairs = function(words) { let trie = buildTrie(words); let results = []; for (let i = 0; i < words.length; i++) { let word = words[i]; let matchings = findMatchings(trie.node, word, []); if (trie.node[""]) { matchings.push(trie.node[""].arrayIndex); } for (let j = 0; j < matchings.length; j++) { let arrayIndex = matchings[j]; let merged = word + words[arrayIndex]; if (isPalindrome(merged)) { if (i != arrayIndex) { results.push([i, arrayIndex]); } } } } return results; }; let input2 = ["abcd", "dcba", "lls", "s", "sssll"]; let input = ["a", "b", "c", "ab", "ac", "aa"]; let input3 = ["a", ""]; console.log(JSON.stringify(palindromePairs(input)));
'use strict'; const express = require('express'); const route = express.Router(); const heroController = require('./hero.controller'); route.get('/heroes/', heroController.getHeroes); route.get('/heroes/:id', heroController.getHeroById); route.post('/heroes/', heroController.newHero); route.put('/heroes/:id', heroController.updateHero); route.delete('/heroes/:id', heroController.deleteHero); module.exports = route;
const Person=require('./Person') const _department=Symbol('department') const _account=Symbol("account") class UniPerson extends Person{ constructor(id,name){ super(id,name) this[_account]=null; this[_department]=null; } get account(){ return this[_account] } get department(){ return this[_department] } set account(value){ this[_account]=value; } set department(value){ this[_department]=(value) } toString(){ return `${super.toString()},department : ${this[_department]} account:${this[_account]}` } } module.exports=UniPerson
angular.module('weatherApp') .directive('logOutModal', [function () { return { restrict: 'E', templateUrl:'components/modal.logout/modal.logout.html', controller : 'ModalLoginController', controllerAs: 'modal' }; }])
import { Q, ajax, importHtml, importOnCall } from "/msa/utils/msa-utils.js" const makeSuggestions = importOnCall("/msa/utils/msa-utils-suggest.js", "makeSuggestions") // style importHtml(`<style> msa-user-selector .row { display: flex; flex-direction: row; } msa-user-selector .col { display: flex; flex-direction: column; } msa-user-selector .center { align-items:center } msa-user-selector input.value { width: 200px; } msa-user-selector img.icon { width: 1em; height: 1em; } </style>`) // template const template = ` <div class="row center" style="margin-bottom:.5em"> <div style="margin-right:.5em">Search for</div> <div class="col"> <div class="row center"> <input type="checkbox" class="users" checked /> <img class="icon" src="/user/img/user" /> <div>Users</div> </div> <div class="row center"> <input type="checkbox" class="groups" checked /> <img class="icon" src="/user/img/group" /> <div>Groups</div> </div> </div> </div><div> <input type="text" class="value" placeholder="Search..."></input></br> </div>` const suggestionTemplate = ` <div style="display:flex; flex-direction:row; align-items:center"> <img class="icon" style="width:1em; height:1em; padding:0; margin-right:.2em"/> <div class="text"></div> </div>` // msa-user-selector export class HTMLMsaUserSelectorElement extends HTMLElement { connectedCallback(){ this.Q = Q this.innerHTML = this.getTemplate() // this.syncContent() this.initActions() } /* setValue(val){ for(let key in val){ this.setTypeValue(val[key]) this.setType(key) } this.syncType() this.syncTypeValue() } */ getTemplate(){ return template } initActions(){ this.listenForSuggestions() } search(text){ const types = [] if(this.Q("input.users").checked) types.push("user") if(this.Q("input.groups").checked) types.push("group") return ajax("GET", "/msa/user/search", { query: { text, types } }) } listenForSuggestions(){ makeSuggestions(this.Q("input.value"), async el => { const res = await this.search(el.value) return res.results }, { formatSuggestion: suggest => { let imgSrc if(suggest.type === "user") imgSrc = "/msa/user/img/user" else if(suggest.type === "group") imgSrc = "/msa/user/img/group" const tmpl = document.createElement("template") tmpl.innerHTML = suggestionTemplate const res = tmpl.content.children[0] res.querySelector(".icon").src = imgSrc res.querySelector(".text").textContent = suggest.name return res }, fillTarget: (el, suggest) => { el.value = suggest.name const expr = {} if(suggest.type === "user") expr.user = suggest.name if(suggest.type === "group") expr.group = suggest.name this.value = expr } }) } /* syncContent(){ this.syncType() this.syncTypeValue() } */ /* setType(t){ if(t === this.type) return this.type = t this.value = (t == "all") ? true : "" this.syncType() this.syncTypeValue() } syncType(){ upd(this.querySelector("select.type"), "value", this.type) } setTypeValue(val){ this.value = val this.syncTypeValue() } syncTypeValue(){ const valEl = this.querySelector("input.value") upd(valEl, "value", this.value) valEl.style.display = (this.type==="all") ? "none" : "" } */ /* validate(){ const detail = {} detail[this.type] = this.value const evt = new CustomEvent('validate', { 'detail': detail }) this.dispatchEvent(evt) } */ focus(){ this.Q("input.value").focus() } } customElements.define("msa-user-selector", HTMLMsaUserSelectorElement) // utils function upd(obj, key, val){ if(obj[key]!==val) obj[key] = val }
$(document).ready(function() { $('.like-btn').on("click", function(event) { let post = $(this).attr("post-data"); $.get(window.location.url, {"post-data": post}, function(data, status) { $(this).hide(); console.log(window.location.url); }); }); });
let number = 12; function hi() { console.log("Mod new"); } module.exports = { var: number, sayHi: hi };
import React, { Component } from 'react'; import { View, StyleSheet, Dimensions } from 'react-native'; import MapViewDirections from 'react-native-maps-directions'; import MapView from 'react-native-maps'; const { width, height } = Dimensions.get('window'); const busStation = require('../../../Items/bus-station-icon.png'); const busStop = require('../../../Items/busStop.png'); class MapDirections extends Component { constructor(props) { super(props); this.state = { position: { latitude: 42.020857, longitude: 23.094338, latitudeDelta: 0.0092, longitudeDelta: 0.0421 }, waypoints: [] }; this.GOOGLE_DIRECTIONS_KEY = 'AIzaSyCPeQW1KzdUhnPrQNYWOpmpdg10AHNom64'; } componentWillMount() { const { bus } = this.props; this.getWayPoints(bus); this.setState(prevState => ({ position: { ...prevState.position, latitude: bus.start.latLong.latitude, longitude: bus.start.latLong.longitude } })); } getWayPoints(nextProps) { const { middle } = nextProps; const arr = []; // push start bus station arr.push(nextProps.start.latLong); // push every middle town bus station for (const town of middle) { if (!town.latLong) continue; arr.push(town.latLong); } // push last bus station arr.push(nextProps.end.latLong); this.setState({ waypoints: arr }); } render() { const waypoints = this.state.waypoints.length > 0 ? this.state.waypoints.slice(1, -1) : []; return ( <View style={{ flex: 1 }}> <View /> <MapView style={styles.map} initialRegion={this.state.position} region={this.state.position} ref={c => { this.mapView = c; }} > {this.state.waypoints.map((latLong, index) => ( <MapView.Marker key={`coordinate_${latLong.place}${index}`} coordinate={{ latitude: latLong.latitude, longitude: latLong.longitude }} description={latLong.place} title={latLong.place} image={(index === 0) ? busStation : busStop} style={{ width: 30, height: 30 }} />)) } {this.state.waypoints.length > 0 ? <MapViewDirections origin={this.state.waypoints[0]} destination={this.state.waypoints[this.state.waypoints.length - 1]} waypoints={waypoints} apikey={this.GOOGLE_DIRECTIONS_KEY} strokeWidth={3} strokeColor="hotpink" onReady={result => { this.mapView.fitToCoordinates(result.coordinates, { edgePadding: { right: parseInt(width / 20, 10), bottom: parseInt(height / 20, 10), left: parseInt(width / 20, 10), top: parseInt(height / 20, 10) } }); }} /> : null } </MapView> </View> ); } } const styles = StyleSheet.create({ map: { flex: 1, ...StyleSheet.absoluteFillObject }, hr: { width, height: StyleSheet.hairlineWidth, backgroundColor: '#ccc' } }); export default MapDirections;
const fs = require("fs"); const path = require("path"); const fetch = require("node-fetch"); const content = async () => { const res = await fetch( "https://ghost-dogefiles.herokuapp.com/ghost/api/v3/content/posts/?key=284a7bfa595c1137a327109d5d&limit=all" ); const { posts } = await res.json(); const slugs = posts.map(post => post.slug); return JSON.stringify(slugs); }; content().then(result => { fs.writeFile( path.join(__dirname, "../public", "posts-slug.json"), result, err => { if (err) { console.error(err); return; } //file written successfully } ); });
// This is main process of Electron, started as first thing when your // app starts. This script is running through entire life of your application. // It doesn't have any windows which you can see on screen, but we can open // window from here. import { app, BrowserWindow } from 'electron' import path from 'path' let mainWindow app.on('ready', () => { mainWindow = new BrowserWindow({ // width: //1024, // height: //768, frame: false }) mainWindow.maximize() // 窗口最大化 // mainWindow.setMenu(null);//设置菜单栏的 menu ,设置它为 null 则表示不设置菜单栏. // Load the HTML file directly from the webpack dev server if // hot reload is enabled, otherwise load the local file. const mainURL = process.env.HOT ? `http://localhost:${process.env.PORT}/main.html` : 'file://' + path.join(__dirname, 'main.html') mainWindow.loadURL(mainURL) if (process.env.NODE_ENV !== 'production') { mainWindow.openDevTools() } mainWindow.on('closed', () => { mainWindow = null }) }) app.on('window-all-closed', () => { app.quit() })
import React, { PropTypes } from 'react'; import Helmet from 'react-helmet'; const App = ({ children }) => ( <div> <Helmet title="MyApp" titleTemplate="%s - MyApp" meta={[ { 'char-set': 'utf-8' }, { name: 'description', content: 'React universal boilerplate by WellyShen' }, ]} /> <div> <h1>Diary</h1> </div> <hr /> {children} </div> ); App.propTypes = { children: PropTypes.object }; export default App;
import './style.scss' import * as hp from 'helper-js' export default function () { const myLocationBtn = document.createElement('div') hp.addClass(myLocationBtn, 'gmap-my-location-btn') myLocationBtn.innerHTML = `<i class="material-icons">my_location</i>` return myLocationBtn }
import React from 'react'; import { useEffect, useState } from 'react'; import { useParams,Link } from 'react-router-dom'; import { getOneBook } from '../services/books'; import ReactStars from "react-rating-stars-component"; const BookInfo = (props) => { const [book, setBook] = useState(null); const { id } = useParams(); const { handleDelete } = props; useEffect(() => { const fetchBook = async () => { const bookData = await getOneBook(id); setBook(bookData); } fetchBook(); }, [id]) return ( <div className='book-info'> <div className='upper-container'> <div className='info-left-container'> <div className='book-div'> <img src={book?.image_url} alt='' className='book-info-image' /> <Link to={`/books/${book?.id}/edit`}><span className='customize'>Customize</span></Link> <span className='delete' onClick={()=>handleDelete(book.id)}>Delete</span> </div> </div> <div className='info-middle-container'> <div className='upper-inner-container'><p>{book?.title}</p></div> <div className='lower-inner-container'> <div className='left-lower-inner-container'> <p><span>Condition:</span> {book?.condition}</p> <p><span>ISBN: </span>{book?.isbn}</p> <p><span>Rental Price: </span> {book?.price}$</p> <p><span>Author: </span>{book?.author_name}</p> </div> <div className='right-lower-inner-container'> <div className='instock'><p>In stock</p></div> </div> </div> </div> <div className='info-right-container'> <div className='ad overall-rating'> <h3> Book Overall Rating: {book?.rating}</h3> <ReactStars className="due" value={1} edit={false} count={1} size={24} activeColor="#ffd700" /> </div> <div className='ad'> <p>Free 2 Day Shipping</p> <p>Arrive 01.05.2021</p> </div> <div className='btn-rent'> <Link to={`/books/${id}/rents`}><p>RENT</p></Link> </div> </div> </div> <div className='lower-container'> <div className='reviews'> <input type='textarea' /> <img src='https://i.imgur.com/opaqxyG.png' alt=''/> </div> <div className='photo'> <img src='https://i.imgur.com/t0UsMu4.png' alt=''/> </div> </div> </div> ); }; export default BookInfo;
import React from "react"; import PropTypes from "prop-types"; import CircleIcon from "../Svg/CircleIcon"; import styles from "./userStatus.css"; const STATUS = { offline: "#ff3232", online: "#00CC00" }; function OnlineStatus({ width, height, status }) { return ( <div className={styles.status}> <CircleIcon fill={STATUS[status.toLowerCase()] || STATUS.online} width={width} height={height} /> </div> ); } OnlineStatus.defaultProps = { status: "online" }; OnlineStatus.propTypes = { status: PropTypes.string, width: PropTypes.number, height: PropTypes.number }; export default OnlineStatus;
function submitconfirm(){ let submit=document.getElementsByClassName('contactform') confirmation=confirm('Do you really want to submit?') if(confirmation){ submit.innerHTML = "<h1>SUBMITTED</h1><style>h1{text-align: center;}" } else{ console.log('cancle'); } }
function solve(params) { var s = +params[0], c1 = +params[1], c2 = +params[2], c3 = +params[3], i, j, k, all, answer = 0; for(i = 0; i <= s/c1; i+=1){ for(j = 0; j<= s/c2; j++){ for(k = 0; k<=s/c3; k++){ all = i*c1 + j*c2+k*c3; if(all>answer && all<=s){ answer = all; } } } } return answer; } var tests = [['110'],['13'],['15'], ['17']]; console.log(solve(tests));
var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Vehicle = /** @class */ (function () { function Vehicle() { //initialize with an initial value this.color = 'red'; } //no return so void is the return type // public drive():void{ // console.log('what') // } //private modifier prevents child class from accessing it. //protected modifier allows child class to access it but it can't be accessed outside of the child class Vehicle.prototype.honk = function () { console.log('honk'); }; return Vehicle; }()); var vehicles = new Vehicle(); console.log(vehicles.color); //Car is the child class of the super class and inherits Vehicle methods by using extends var Cars = /** @class */ (function (_super) { __extends(Cars, _super); function Cars() { return _super !== null && _super.apply(this, arguments) || this; } //override a method in the parent class //private modifier means only methods within the class can call drive //cannot change modifier in child class if parent class has one //private prevents application breaking due to a method being called. Cars.prototype.drive = function () { console.log('override'); }; //this method can call drive Cars.prototype.startDrivingProcess = function () { this.drive(); //cannot call honk if it is private in the parent class this.honk(); }; return Cars; }(Vehicle)); //vehicle is instance of Vehicle var coche = new Cars(); coche.startDrivingProcess(); // coche.drive(); // coche.honk()
import GroupBox from './GroupBox'; export default GroupBox;
var socket = io(); function scrollToBottom(){ //Selectors var messages = jQuery('#messages1'); var newMessage = messages.children('li:last-child');//El ultimo hijo (mensaje) que se agrega a "li" //Heights var clientHeight = messages.prop('clientHeight'); var scrollTop = messages.prop('scrollTop'); var scrollHeight = messages.prop('scrollHeight'); var newMessageHeight = newMessage.innerHeight(); var lastMessageHeight = newMessage.prev().innerHeight(); if(clientHeight + scrollTop + newMessageHeight + lastMessageHeight >= scrollHeight){ messages.scrollTop(scrollHeight); } } //-- socket.on('connect', function () { //Un usuario se conecta--------- //console.log('Connected to server'); var params = jQuery.deparam(window.location.search); socket.emit('join', params, function (err) {//para los parametros de join if(err){ alert(err); window.location.href = '/'; }else{ console.log('No error'); } }); }); //-- socket.on('disconnect', function () {//Un usuario se desconecta--------------- console.log('Disconnected from server'); }); //-- socket.on('updateUserList', function (users) {//Se actualiza la lista de usuarios en linea--------------- console.log('Lista de usuarios', users); var ol = jQuery('<ol></ol>'); users.forEach(function(user) { ol.append(jQuery('<li></li>').text(user)); }); jQuery('#users').html(ol); }); //-- socket.on('newMessage', function (mensaje) { var formattedTime = moment(mensaje.createdAt).format('h:mm a'); var template = jQuery('#message-template').html(); var html = Mustache.render(template, { texto: mensaje.text, from: mensaje.from, createdAt: formattedTime }); jQuery('#messages1').append(html); scrollToBottom(); }); //-- socket.on('newLocationMessage', function (mensaje) { var formattedTime = moment(mensaje.createdAt).format('h:mm a'); var template = jQuery('#location-message-template').html(); var html = Mustache.render(template, { from: mensaje.from, url: mensaje.url, createdAt: formattedTime }); jQuery('#messages1').append(html); scrollToBottom(); }); //Atrapar informacion del html jQuery('#message-form').on('submit', function(e) { e.preventDefault();//Previene que aparezca el mensaje en el buscador = http://localhost:3000/?message=hola var messageTextbox = jQuery('[name=message1]'); socket.emit('createMessage', { text: messageTextbox.val() }, function (){ messageTextbox.val(''); }); }); //-- var BotonUbicacion = jQuery('#send-location'); //-- BotonUbicacion.on('click', function (){//Cuando se haga click en el boton de ubicacion if(!navigator.geolocation){ return alert('Geolocalizacion no soportada por tu Navegador'); } BotonUbicacion.attr('disabled', 'disabled').text('Enviando ubicación...');//desactivo el boton mientras se manda la ubicacion navigator.geolocation.getCurrentPosition(function (position) { //console.log(position); BotonUbicacion.removeAttr('disabled').text('Enviar Ubicación');//activo el boton una vez se mando socket.emit('createLocationMessage', { latitud: position.coords.latitude, longitud: position.coords.longitude }); }, function () { BotonUbicacion.removeAttr('disabled').text('Enviar Ubicación');//activo el boton si fallo el envio alert('No se pudo obtener la ubicacion'); }) });//--
const ADD_TABLE = document.querySelector('.add_table'); const OVERLAY_ADD_TABLE = document.querySelector('.overlay'); const ADD_BUTTON = document.querySelector('.add_button'); const ESC_BUTTON = document.querySelector('.esc_button'); ADD_BUTTON.addEventListener('click', () => { // обработчик делает видимым секцию с формой для отзыва ADD_TABLE.classList.add('add_table-active'); }) OVERLAY_ADD_TABLE.addEventListener('click', () => { ADD_TABLE.classList.remove('add_table-active'); }) ESC_BUTTON.addEventListener('click', () => { // обработчик скрывает секцию с формой для отзыва ADD_TABLE.classList.remove('add_table-active'); })
var MongoClient = require('mongodb').MongoClient; var mongodb = require('mongodb') var serverMongo = new mongodb.Server('127.0.0.1', 27017, {auto_reconnect: true}); var db = new mongodb.Db('multichat', serverMongo); db.open(function(){}); verifyBan = function(req, res) { var collection = db.collection("room"); var doc = collection.findOne({_id:req.params.name}, {_id:0, passPrivate:1, bannedIP:1},function(err, item) { console.log("IP : " + req.connection.remoteAddress); if (item != null) { var bannedIP = JSON.stringify(item.bannedIP); if (bannedIP != undefined && bannedIP.indexOf(req.connection.remoteAddress) == 1) { res.send("You are banned"); } else { res.sendfile(__dirname + '/index.html'); } } else { res.sendfile(__dirname + '/index.html'); } }); } module.exports.setOnMethods = function(socket, io) { getLog = function (room) { var collection = db.collection("log"); var result = collection.find({room_id:room}, {_id:0, room_id:0}).sort({date:1}); result.toArray(function (err, results) { if (err) { throw err; } if (results.length === 0) { console.log('Error 404: No log found'); } var history = JSON.stringify(results); socket.emit('fullHistory', history); }); }, insertLog = function(room, date, text) { var newLog = { date : date, text : text, room_id : room }; insert('log', newLog); }, insertMessage = function (user, room, date, text) { var newMsg = { date : date, sender : user, text : text, room_id : room }; insert('message', newMsg); }, insertRoom = function (room, passAdmin, passPrivate) { var newRoom = { _id : room, name : room, passAdmin : passAdmin, passPrivate : passPrivate, bannedIP : [], }; insert('room', newRoom); }, insertPrivateRoom = function (room, pass) { var newRoom = { _id : room, pass : pass, name : room, bannedIP : [], }; insert('room', newRoom); }, insertUser = function (user, ip, room) { var newUser = { name : user, ip : ip, room_id : room }; insert('user', newUser); }, insert = function (collection, document) { var collection = db.collection(collection); collection.insert(document); }, setPass = function (room, pass) { var collection = db.collection("room"); collection.update({name:room},{$set:{pass:pass}}) get("room"); }, addBannedIP = function(room, ip) { var collection = db.collection("room"); //console.log("addBannedIP"); collection.update({_id:room}, {$push:{bannedIP:ip}}) } banIP = function(room, usernameToBan, passAdmin) { console.log('on banIP ' + room + ' ' + usernameToBan + ' ' + passAdmin); var collection = db.collection("room"); var doc = collection.findOne({_id:room}, function(err, item) { console.log('passAdmin ' + item.passAdmin + '=?=' + passAdmin); if (item.passAdmin == passAdmin) { var collectionUser = db.collection("user"); var docUser = collectionUser.findOne({name:usernameToBan, room_id:room}, function(err, item) { console.log('find user to ban ' + item.ip); addBannedIP(socket.room, item.ip); //Ask who is the user with item.ip io.sockets.in(room).emit('amITheUser', item.ip); }); } }); } isUnique = function(username, room, balise) { console.log('user ' + username + ' room ' + room); var collection = db.collection("user"); var doc = collection.find({room_id:room}); doc.toArray(function(err, item) { var returnValue = true; for(i=0; i<item.length; i++) { if(item[i].name == username){ returnValue = false; } } socket.emit('isUnique', returnValue, balise); }); } joinOrReject = function(room, passPrivate) { var collection = db.collection("room"); var doc = collection.findOne({_id:room}, {_id:0, passPrivate:1}, function(err, item) { console.log(item.passPrivate + " =?= " + passPrivate); if (item.passPrivate == passPrivate) { io.sockets.in(room).emit('join', room); socket.join(room); socket.room = room; socket.emit('joined', room); } else { socket.emit('wrongPass', room); } }); } insertFile = function (room, fileName, originName, owner, date) { var newFile = { filename : fileName, room_id : room, originName : originName, owner : owner, date : date, }; insert('file', newFile); } getFiles = function (room) { var collection = db.collection("file"); var result = collection.find({room_id:room}, {_id:0, room_id:0}); result.toArray(function (err, results) { if (err) { throw err; } if (results.length === 0) { console.log('Error 404: No log found'); } socket.emit('fullFiles', JSON.stringify(results)); }); } download = function(foldername, filename, res){ if (socket.room == foldername) { res.download(__dirname + '/files/'+foldername+'/'+filename); } else { res.send("You are not in the room"); } }, typePage = function(room) { var collection = db.collection("room"); var doc = collection.findOne({_id:room}, {_id:0, passPrivate:1, bannedIP:1},function(err, item) { if (item != null) { if (item.passPrivate == "") { socket.emit('typePage', "containerLogRoom"); } else { socket.emit('typePage', "containerLogPrivateRoom"); } } else { socket.emit('typePage', "containerNewRoom"); } }); } deleteUser = function (username, room) { var collection = db.collection('user'); collection.remove({name : username, room_id:room}); }, deleteAll = function (collection) { var collection = db.collection(collection); collection.remove({}); }, get = function (collection) { var collection = db.collection(collection); var result = collection.find(); result.toArray(function (err, results) { if (err) { throw err; } if (results.length === 0) { //res.statusCode = 404; //return res.send('Error 404: No users found'); console.log('Error 404: No users found'); } var users = JSON.stringify(results); console.log('plop ' + users); }); } }
import {GET_STUDENTS_REQUEST, GET_STUDENTS_SUCCESS, GET_STUDENTS_FAILURE, DELETE_STUDENTS_REQUEST, DELETE_STUDENTS_SUCCESS, DELETE_STUDENTS_FAILURE, ADD_STUDENTS_REQUEST, ADD_STUDENTS_SUCCESS, ADD_STUDENTS_FAILURE, UPDATE_STUDENTS_REQUEST, UPDATE_STUDENTS_SUCCESS, UPDATE_STUDENTS_FAILURE } from './actionTypes' import axios from 'axios' export const getStudentsRequest = () => { return { type : "GET_STUDENTS_REQUEST" } } export const getStudentsSuccess = (payload) => { return { type : "GET_STUDENTS_SUCCESS", payload } } export const getStudentsFailure = () => { return { type : "GET_STUDENTS_FAILURE" } } //GET STUDENTS REQUEST thunk export const getStudents = () => (dispatch) => { dispatch(getStudentsRequest()) return axios.get("http://localhost:5000/api/students") .then((res) => dispatch(getStudentsSuccess(res.data))) .catch((err) => dispatch(getStudentsFailure(err))) } //DELETE STUDENTS DATA export const deleteStudentsRequest = () => { return { type : "GET_STUDENTS_REQUEST" } } export const deleteStudentsSuccess = (payload) => { return { type : "GET_STUDENTS_SUCCESS", payload } } export const deleteStudentsFailure = () => { return { type : "GET_STUDENTS_FAILURE" } } //DELETE STUDENTS REQUEST thunk export const deleteStudents = (id) => (dispatch) => { dispatch(deleteStudentsRequest()) return axios({ method : "DELETE", url : `http://localhost:5000/api/students/delete/${id}` }) .then((res) => dispatch(getStudents())) .catch((err) => dispatch(getStudentsFailure(err))) } //ADD STUDENT export const addStudentsRequest = () => { return { type : "ADD_STUDENTS_REQUEST" } } export const addStudentsSuccess = (payload) => { return { type : "ADD_STUDENTS_SUCCESS", payload } } export const addStudentsFailure = () => { return { type : "ADD_STUDENTS_FAILURE" } } //ADD STUDENTS REQUEST thunk export const addStudents = ({fname,lname, age, city, phone, email}) => (dispatch) => { dispatch(addStudentsRequest()) return axios({ method : "post", url : "http://localhost:5000/api/students", data : { fname, lname, age, city, phone, email } }) .then((res) => dispatch(getStudents())) .catch((err) => dispatch(addStudentsFailure(err))) } //UPDATE STUDENT export const updateStudentsRequest = () => { return { type : "UPDATE_STUDENTS_REQUEST" } } export const updateStudentsSuccess = (payload) => { return { type : "UPDATE_STUDENTS_SUCCESS", payload } } export const updateStudentsFailure = () => { return { type : "UPDATE_STUDENTS_FAILURE" } } //UPDATE STUDENTS REQUEST thunk export const updateStudents = (id, {fname, lname, age, city, phone, email}) => (dispatch) => { dispatch(updateStudentsRequest()) return axios({ method : "PUT", url : `http://localhost:5000/api/students/update/${id}`, data : { fname, lname, age, city, phone, email } }) .then((res) => dispatch(getStudents())) // .then((res) => dispatch(updateStudentsSuccess)) .catch((err) => dispatch(updateStudentsFailure(err))) }
var slide = function () { /** * o----表示对象; * m----表示图片原宽 * n----表示图片均宽 * a----li对象集合 * mw----最小宽度 * d----持续时间 * g----像素间隔 */ var o,m,n,a,mw,d,g,offsetWid; return { destruct: function () { if (o) { clearInterval(o.timer); clearInterval(o.htimer); } }, build: function (sm, w, t, s, x) { o = document.getElementById(sm); m = w; d = t; g = s; a = $(o).find("li"); offsetWid = o.offsetWidth; n = offsetWid / a.length; mw = Math.floor((offsetWid - m) / (a.length - 1)); for (var i = 0; i < a.length; i++) { a[i].style.width = n + "px"; this.timer(a[i]); } if (x != null) { o.timer = setInterval(function () { slide.slide(a[x]); }, d); $(a[x]).find(".cover").hide(); } }, timer: function (obj) { obj.onmouseover = function () { clearInterval(o.timer); clearInterval(o.htimer); o.timer = setInterval(function () { slide.slide(obj); }, d); $(obj).find(".cover").hide(); }; obj.onmouseout = function () { clearInterval(o.timer); clearInterval(o.htimer); o.htimer = setInterval(function () { slide.slide(obj, true); }, d); $(".cover").show(); $(obj).find(".cover").hide(); } }, slide:function (obj,state) { var currWid = parseInt(obj.style.width); if(currWid < m && !state || currWid > n && state) { var widValue = 0; var otherWid; for(var i = 0; i < a.length; i++) { if(a[i] != obj) { var oi = 0; //注意:oi变量必须要放在for循环里;每一次检查obj是否符合条件时,都将该值进行清零; // 在开始的时候,放在外面,然后出现不符合下面if条件的情况时,oi仍然有值,进行了多余的加或减操作。 otherWid = parseInt(a[i].style.width); //对目标对象外的其它对象进行操作 //这里的if判断是针对目标对象以外的其他对象,决定的一个宽度条件 if(otherWid > mw && !state) { //目标对象展开操作,其他对象收缩操作 oi = Math.floor((otherWid - mw) / g); oi = oi > 0 ? oi : 1; a[i].style.width = otherWid - oi + "px"; } else if(otherWid < n && state) { //目标对象收缩操作,即其他对象扩宽操作,当前宽度小于平均宽度,就进行操作 oi = Math.floor((n - otherWid) / g); oi = oi > 0 ? oi : 1; a[i].style.width = otherWid + oi + "px"; } if(state) { widValue += (otherWid + oi); } else { widValue += (otherWid - oi); } } } obj.style.width = offsetWid - widValue + "px"; } else { if(o.timer) { clearInterval(o.timer); } if(o.htimer) { clearInterval(o.htimer); } } } } }(); slide.build("sm",450,10,10,1);
import Wallet from './wallet' import Account from './account' import TransactionPool from './transaction-pool' import Blockchain from './index' // import config from '../config' // // const fs = require('fs-extra') // const path = require('path') describe('TransactionPool', () => { // afterAll(() => { // fs.removeSync(path.resolve(config.STORE.WALLET, '..')) // }) let transactionPool, transaction, senderWallet, recipient, amount, fee, account beforeEach(async () => { transactionPool = new TransactionPool() senderWallet = new Wallet() // create account associated with wallet (sender's account) account = new Account({ publicKey: senderWallet.publicKey }) account.balance = '5000' await account.store() recipient = new Wallet().publicKey new Account({ publicKey: recipient }).store() amount = '49' fee = '1' transaction = senderWallet.createTransaction({ recipient, amount, fee }) }) describe('setTransaction()', () => { it('adds a transaction', () => { transactionPool.setTransaction(transaction) expect(transactionPool.transactionMap[transaction.uuid]) .toBe(transaction) }) }) describe('existingTransaction()', () => { it('returns an existing transaction given an input address', () => { transactionPool.setTransaction(transaction) expect( transactionPool.existingTransaction({ sender: senderWallet.publicKey }) ).toBe(transaction) }) }) describe('validTransactions()', () => { let validTransactions, errorMock beforeEach(async () => { validTransactions = [] errorMock = jest.fn() global.console.error = errorMock for (let i = 0; i < 10; i += 1) { senderWallet = new Wallet() recipient = new Wallet().publicKey // create account associated with wallet (sender's account) account = new Account({ publicKey: senderWallet.publicKey }) account.balance = '50' await account.store() // eslint-disable-line no-await-in-loop amount = '29' fee = '1' const transaction = senderWallet.createTransaction({ recipient, amount, fee }) if (i % 3 === 0) { transaction.amount = 999999 } else if (i % 3 === 1) { transaction.signature = `.${transaction.signature}`// alter signature } else { validTransactions.push(transaction) } transactionPool.setTransaction(transaction) } }) it('returns valid transaction', async () => { expect(await transactionPool.validTransactions()).toEqual(validTransactions) }) // it('logs errors for the invalid transactions', () => { // transactionPool.validTransactions() // expect(errorMock).toHaveBeenCalled() // }) }) describe('clear()', () => { it('clears the transactions', () => { transactionPool.clear() expect(transactionPool.transactionMap).toEqual({}) }) }) describe('clearBlockchainTransactions()', () => { it('clears the pool of any existing blockchain transactions', async () => { const blockchain = new Blockchain() senderWallet = new Wallet() const account = new Account({ publicKey: senderWallet.publicKey }) account.balance = '5000' await account.store() // first 3 reward bootstrap blocks await blockchain.addBlock({ data: [], wallet: senderWallet }) await blockchain.addBlock({ data: [], wallet: senderWallet }) await blockchain.addBlock({ data: [], wallet: senderWallet }) amount = '29' fee = '1' const transaction = senderWallet.createTransaction({ recipient, amount, fee }) transactionPool.setTransaction(transaction) expect(Object.values(transactionPool.transactionMap)).toHaveLength(1) const block = await blockchain.addBlock({ data: [ transaction, ], wallet: senderWallet, }) if (block) { transactionPool.clearBlockchainTransactions({ block }) } expect(Object.values(transactionPool.transactionMap)).toHaveLength(0) }) }) })
/** * @file * Contains the Formatter class. */ const { languages, Position, ProgressLocation, Range, TextEdit, window, workspace } = require('vscode'); const { processSnippet } = require('./strings'); const { createRunner } = require('./runner'); const { getExtraFileSelectors } = require('./files'); /** * Gets a full range of a document. * * @param {import('vscode').TextDocument} document * The document to get the full range of. * * @return {import('vscode').Range} * The range that covers the whole document. */ const documentFullRange = (document) => new Range( new Position(0, 0), document.lineAt(document.lineCount - 1).range.end, ); /** * Tests whether a range is for the full document. * * @param {import('vscode').Range} range * The range to test. * @param {import('vscode').TextDocument} document * The document to test with. * * @return {boolean} * `true` if the given `range` is the full `document`. */ const isFullDocumentRange = (range, document) => range.isEqual(documentFullRange(document)); /** * Formatter provider for PHP files. * * @type {import('vscode').DocumentRangeFormattingEditProvider} */ module.exports.Formatter = { /** * {@inheritDoc} */ async provideDocumentRangeFormattingEdits(document, range, formatOptions, token) { const isFullDocument = isFullDocumentRange(range, document); const text = document.getText(range); const formatter = createRunner(token, document.uri, isFullDocument).phpcbf; const replacement = await window.withProgress( { location: ProgressLocation.Window, title: 'PHP Sniffer: formatting…' }, () => (isFullDocument ? formatter(text) : processSnippet(text, formatOptions, formatter)), ); return replacement ? [new TextEdit(range, replacement)] : []; }, }; /** * Formatter provider for non-PHP files. * * @type {import('vscode').DocumentFormattingEditProvider} */ const GenericFormatter = { /** * {@inheritDoc} */ provideDocumentFormattingEdits(document, formatOptions, token) { return module.exports.Formatter.provideDocumentRangeFormattingEdits( document, documentFullRange(document), formatOptions, token, ); }, }; /** * Registers the generic formatter. * * @return {import('vscode').Disposable} * Disposable for the formatter. */ const registerGenericFormatter = () => languages.registerDocumentFormattingEditProvider( getExtraFileSelectors(), GenericFormatter, ); /** * Formatter provider for any file type. * * @return {import('vscode').Disposable} */ module.exports.activateGenericFormatter = () => { let formatter = registerGenericFormatter(); const onConfigChange = workspace.onDidChangeConfiguration((event) => { if (event.affectsConfiguration('phpSniffer.extraFiles')) { formatter.dispose(); formatter = registerGenericFormatter(); } }); return { dispose() { onConfigChange.dispose(); formatter.dispose(); }, }; };
const express = require('express'); const fs = require('fs'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.urlencoded({ extended:false })); app.use((req,res,next) => { res.append('Access-Control-Allow-Origin', '*'); next(); }) app.post('/login',(req,res) => { console.log(req.body); let { username, password } = req.body; if(username === 'cai' && password === '1128'){ res.send('登陆成功'); }else { res.send('登陆失败'); } }) app.listen(1999); console.log('启动服务器');
const userSchema = require('../../models/user.model'); module.exports = async function usernameValid(req, res, next) { const {name} = req.body; const user = await userSchema.findOne({"name": name}) .then(r => r) .catch(e => e); res.rawResponse = !user; next(); }; // hash password with bcrypt // bcrypt.hash("passwordPlain", 10, function(err, hash) { // console.log(hash) // });
import { connect } from 'react-redux' import { readEvents } from '../actions/readEvents.js' import EventsIndex from '../components/events_index.js' //import {Actions} from '../actions/index.js' //import {bindActionCreators} from 'redux' const mapStateToProps = state => ({events: state.modul.events}) const mapDispatchToProps = dispatch => ({ readEvents: async() => { console.log(readEvents()) dispatch( await readEvents()) } }) //const mapDispatchToProps = {readEvents} //const mapDidPatchToProps = { toshi: readEvents} とかでもいける //toshihikosato ishito //hkosato //oooiia //tsshhkt //sha sho shi //ko to ho si //shishi //tktoooa //toshikoshiato //toshikoshitao export default connect(mapStateToProps, mapDispatchToProps)(EventsIndex);
const Operation = require('@pascalcoin-sbx/json-rpc').Types.Operation; module.exports = { OPTYPE: function (value) { if (value === 'ALL') { return -1; } return Operation[value]; }, SUBTYPE: function (value) { if (value === 'ALL') { return -1; } return Operation['SUBTYPE_' + value]; } };
let HOURS_IN_DAY = 24; function calculateHoursOnMoon(days) { HOURS_IN_DAY = 29.5; return days * HOURS_IN_DAY; } function calculateHoursOnEarth(days) { HOURS_IN_DAY = 24; return days * HOURS_IN_DAY; }
module.exports = { index:function(req,res){ return res.redirect('/'); }, listProgram: function(req, res){ console.log("Consultando programas"); Program.find().exec(function(err,programs){ if(err){ return res.json(err); } return res.json(programs); }); }, listUsers: function(req, res){ User.find().exec(function(err,user){ if(err){ return res.json(err); } return res.json(user); }); }, listTypeUsers: function(req, res){ TypeUser.find().exec(function(err,typeUser){ if(err){ return res.json(err); } return res.json(typeUser); }); } };
const router = require('express').Router(); const refreshTokenMiddle = require('../middle/refresh-function.js'); const parseDataFormat = require('../middle/calendarFormat.js'); const lineMessageFormat = require('../middle/replyToLine.js'); const authCheck = (req,res,next) => { if(req.user){ res.redirect('/auth/login'); }else{ next(); } }; router.get('/', refreshTokenMiddle.calendarEventList, (req, res, next) => { //res.render('calendar', {data: req}); res.render('testview'); }); router.get('/askEvent', refreshTokenMiddle.calendarAskEventList, parseDataFormat.dataFormat,(req, res, next) => { //console.log('Event get data = ' + JSON.stringify(req.calendarList)); console.log("success Event server "); res.json({calendarList : req.calendarList , calendarNewList : req.newFormat}); //sucess in change the format to right size }); router.post('/quickAdd', refreshTokenMiddle.calendarEventInsert, (req, res) => { //console.log('backend get data = ' + req.body.event); console.log("success click server "); // insert eventdata to google server !!!! res.sendStatus(200); //sucess in }); router.post('/delete', refreshTokenMiddle.calendarEventDelete, (req, res) => { //console.log('backend get data = ' + req.body.event); console.log("success click server "); // insert eventdata to google server !!!! res.sendStatus(200); //sucess in }); router.post('/update', refreshTokenMiddle.calendarEventUpdate, (req, res) => { //console.log('backend get data = ' + req.body.event); console.log("success update server "); // insert eventdata to google server !!!! res.sendStatus(200); //sucess in }); router.post('/lineMessage', lineMessageFormat.reply, (req, res) => { console.log('in routerrrrrrrrrrrrrrrrrrrrrr'); res.sendStatus(200); }) module.exports = router;
import InternationalProvider from './provider'; import WithTranslation from './translate'; import YandexTranslator from './translators/yandex'; import translatable from './translatable'; export { InternationalProvider, WithTranslation, YandexTranslator, translatable };
$(document).ready(function() { $('a[href^="#"]').bind('click.smoothscroll', function(e) { e.preventDefault(); var target = this.hash, $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top }, 850, 'swing', function() { window.location.hash = target; }); }); }); function hasCookies() { if (!navigator.cookieEnabled) { document.getElementById("cookies").innerHTML = "Cannot remember you without cookies..."; } } $(document).ready(function() { $(".side-nav").css("width", "0"); $("#register-alert").hide(); $("#register-success").hide(); $("#login-alert").hide(); $("#login-success").hide(); }); function changeLogin() { $("#login").addClass("hidden"); $("#register").removeClass("hidden"); } function changeRegister() { $("#register").addClass("hidden"); $("#login").removeClass("hidden"); } function OpenNav() { $(".side-nav").css("width", "300px").css("border-right", "2px solid rgba(0,0,0,0.08)"); } function CloseNav() { $(".side-nav").css("width", "0").css("border", ""); } $(document).ready(function() { $("#reg").on("submit", function(e) { e.preventDefault(); let firstname = $('#firstname').val(); let lastname = $('#lastname').val(); let username = $('#username').val(); let email = $('#email').val(); let password = $('#password').val(); let passwordagain = $('#passwordagain').val(); if (firstname == '' || lastname == '' || username == '' || email == '' || password == '' || password != passwordagain) { notification("You forgot to fill something...",5000); } else { notification("Creating account", 2000); $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: { 'firstname': firstname, 'lastname': lastname, 'username': username, 'email': email, 'password': password }, dataType: 'json', cache: false, complete: function(answer) { let ans = JSON.parse(answer.responseText); if (ans === "success") { console.log(ans); notification("Your account was created", 2000); } else if (ans === "fail") { console.log(ans); notification("Could not create your account",2000); } else { console.log(ans); notification("Error",2000); } } }); } }); }); $(document).ready(function() { $('#log').on('submit', function(e) { e.preventDefault(); let email = $('#email2').val(); let password = $('#password2').val(); if (email == '' || password == '') { notification("You forgot to fill something",5000); } else { notification("Connecting", 2000); $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: { 'email': email, 'password': password }, dataType: 'text', cache: false, complete: function(answer) { let ans = JSON.parse(answer.responseText); if (ans === "success") { console.log(ans); notification("Connected", 2000); } else if (ans === "fail") { console.log(ans); notification("Wrong password", 2000); } else { console.log(ans); notification("Error", 2000); } } }); } }); }); function disconnect() { $.ajax({ url: "php/logout.php", dataType: 'text', cache: false, complete: function () { console.log("Disconnected"); location.reload(false); } }); } function notification(text, duration) { $('.notif-text').html(text); $('.notif') .clearQueue() .animate({ bottom: '40px'}, 500) .delay(duration) .animate({bottom: '-60px'}, 500); return true; }
import React from "react"; import LayOut from "./LayOut"; import BackHeadWithUsername from "../middleComponents/BackHeadWithUsername"; import MakeSettingPanel from "./MakeSettingPanel"; const data = { title: "安全", list: [ { key: 1, list: [ { key: 1, type: "link", title: "登录认证", to: "/settings/account/login_verification" }, { key: 2, type: "checkbox", title: "密码重设保护", subTitle: "如果勾选此复选框,你将需要验证附加信息,之后方可只使用你的 @用户名 申请密码重置。如果你的账号设置了手机号,将要求你验证该手机号,之后方可只使用你的邮件地址申请密码重置。" } ] } ] }; function Security() { return ( <LayOut narrowHead={<BackHeadWithUsername title="安全" />} rightAside={<MakeSettingPanel data={data} />} /> ); } export default Security;
window.onload = function(){ window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || (function () { return function (callback, element) { window.setTimeout(callback,1000/60) }; })(); var w = window.innerWidth var h = window.innerHeight var canvas = document.querySelector('.canvas') canvas.width = w canvas.height = h var ctx = canvas.getContext('2d') // 生成随机数 function Random(x, y){ return Math.random()*(y-x) + x } // 生成随机颜色 function getColor(r, g, b){ return 'rgb(' + r + ',' + g + ',' + b + ')' } var aPoint = [] // 画点的构造函数 function Point(){} Point.prototype = { init:function(){ this.x = Random(0, w) this.y = Random(0, h) this.color = getColor( Math.floor(Random(0,256)), Math.floor(Random(0,256)), Math.floor(Random(0,256))) this.r = Random(0.4, 0.6) this.vX = Random(-0.5, 0.5) this.vY = Random(-0.5, 0.5) }, draw:function(){ ctx.beginPath() ctx.fillStyle = this.color ctx.arc(this.x, this.y, this.r, 0, Math.PI*2) ctx.fill() }, move:function(){ this.x += this.vX this.y += this.vY if(this.x < 0 || this.x > w){ this.vX = -this.vX } if(this.y < 0 || this.y > h){ this.vY = -this.vY } this.draw() } } for( var i = 0; i < 200; i++ ){ var point = new Point() point.init() point.draw() aPoint.push(point) } // 鼠标移动事件 var mouseX, mouseY window.onmousemove = function(e){ mouseX = e.clientX mouseY = e.clientY } // 定时器方法 ~~function delay(){ ctx.clearRect(0, 0, w, h) for(var i = 0; i < aPoint.length; i++){ aPoint[i].move() } drawLine() window.requestAnimationFrame(delay) }() // 画线 function drawLine(){ for(var i = 0; i < aPoint.length; i++){ for(var j = i+1; j < aPoint.length; j++){ if( Math.pow( (aPoint[i].x - aPoint[j].x),2 ) + Math.pow( (aPoint[i].y - aPoint[j].y),2 ) < 2500 ){ ctx.beginPath() ctx.strokeStyle = 'rgba(32, 128, 247, 0.1)' ctx.moveTo( aPoint[i].x, aPoint[i].y ) ctx.lineTo( aPoint[j].x, aPoint[j].y ) ctx.stroke() ctx.closePath() } } // 鼠标移动特效 if(mouseX){ if( Math.pow( (aPoint[i].x - mouseX),2 ) + Math.pow( (aPoint[i].y - mouseY),2 ) < 12000 ){ ctx.beginPath() ctx.strokeStyle = 'rgba(32, 128, 247, 0.1)' ctx.moveTo( aPoint[i].x, aPoint[i].y ) ctx.lineTo( mouseX, mouseY ) ctx.stroke() ctx.closePath() } } } } }
const env = process.env.NODE_ENV || 'development'; if (env === 'development' || 'test') { // Uses try catch block for use in heroku, will crash otherwise try { const config = require('./config.json'); //eslint-disable-line const envConfig = config[env]; Object.keys(envConfig).forEach(key => { process.env[key] = envConfig[key]; }); } catch (e) { console.log(e); } }
function show(op){ document.getElementById('display').innerHTML = op; } function save(){ sum1 = document.getElementById('display').innerHTML; document.getElementById('display').innerHTML = ""; } function adder(){ sum2 = document.getElementById('display').innerHTML; resultado = parseInt(sum1)||parseInt(sum2); document.getElementById('display').innerHTML = resultado; }
const mongoose = require("mongoose"); const Schema = mongoose.Schema; const UserInfoSchema = new Schema( { company_email: { type: String, required: true, }, company_name: { type: String, required: true, }, company_address: { type: String, required: true, }, company_phone: { type: String, required: true, }, company_website: { type: String, required: true, }, vat_number: { type: String, required: true, }, address_proof: { type: String, required: true, }, legal_status: { type: String, required: true, }, typeof_company: { type: String, required: true, }, nameof_director: { type: String, required: true, }, proofof_director: { type: String, required: true, }, contact_name: { type: String, required: true, }, contact_designation: { type: String, required: true, }, contact_email: { type: String, required: true, }, contact_phone: { type: String, required: true, }, }, { autoCreate: true } ); const UserInfo = mongoose.model("userInfoRegister", UserInfoSchema); module.exports = UserInfo;
import React from 'react' import { handleLogin } from '../actions/google' import {connect} from 'react-redux' import GoogleLogin from 'react-google-login' // import { useGoogleLogin } from 'react-google-login' const Login = ({handleLogin}) => { const googleOnClick = () => { debugger; fetch("http://localhost:3001/auth/google_oauth2", { method: "POST", headers: { "content-type": "application/json" } }) .then(response => response.json()) .then(response => console.log("response from googleonclick", response)) } const onSuccess = (response) => { console.log("successful =>", response) handleLogin(response) } return( <GoogleLogin clientId="341724363289-il3rg7m66mgk3k3qegisntgs0ujv9b37.apps.googleusercontent.com" buttonText="Login" onSuccess={onSuccess} onFailure={googleOnClick} cookiePolicy={'single_host_origin'} /> ) } export default connect(null, {handleLogin})(Login)
var dbm = require('db-migrate'); var type = dbm.dataType; exports.up = function(db, callback) { db.createTable('tournaments', { id: {type: 'int', primaryKey: true, autoIncrement: true}, name: {type: 'string', notNull: true}, game: {type: 'string', notNull: true}, office: {type: 'string', notNull: true} }, callback) }; exports.down = function(db, callback) { db.dropTable('tournaments', callback) };
let wpUrl = 'http://cameron.local:8888/wp-json'; const Config = { apiUrl: wpUrl, AUTH_TOKEN: 'auth-token', USERNAME: 'username', }; export default Config;
import { connect } from 'react-redux'; import OrderPage from '../../../components/OrderPage'; import {fetchJson, showError, initTableCols} from '../../../common/common'; import {fetchDictionary, setDictionary} from '../../../common/dictionary'; import {Action} from '../../../action-reducer/action'; import {getPathValue} from '../../../action-reducer/helper'; import {search,search2} from '../../../common/search'; import {buildOrderPageState} from "../../../common/orderAdapter"; import {buildEditState} from "./EditDialogContainer"; const STATE_PATH = ['message', 'sendMessageByEmail']; const URL_CONFIG = '/api/message/sendMessageByEmail/config'; const URL_LIST = '/api/message/sendMessageByEmail/list'; const URL_DETAIL = '/api/message/sendMessageByEmail/detail'; const action = new Action(STATE_PATH); export const buildSendMessageByShortMesState = async () =>{ let res,data,config; data = await fetchJson(URL_CONFIG); if(data.returnCode !== 0) { showError('Get Config Failed'); return; } config = data.result; config.index.tableCols = initTableCols('sendMessageByEmail', config.index.tableCols); const {tableCols, filters} = config.index; const {controls} = config.edit; data = await fetchDictionary(config.dicNames); if(data.returnCode !=0){ showError(data.returnMsg); return; } setDictionary(tableCols, data.result); setDictionary(filters, data.result); setDictionary(controls, data.result); res = await search(URL_LIST, 0, config.index.pageSize, {}); if(res.returnCode !=0){ showError(res.returnMsg); return; } data = res.result; return buildOrderPageState(data, config.index, {editConfig: config.edit}); }; const getSelfState = (rootState) => { return getPathValue(rootState, STATE_PATH); }; const changeActionCreator = (key, value) => { return action.assign({[key]: value}, 'searchData'); }; //搜索 const searchActionCreator = async (dispatch, getState) =>{ const {pageSize, searchData} = getSelfState(getState()); const newState = {searchDataBak: searchData, currentPage: 1}; console.log(URL_LIST); return search2(dispatch, action, URL_LIST, 1, pageSize, searchData, newState); }; // 清空搜索框 const resetActionCreator = async(dispatch) => { return dispatch(action.assign({searchData: {}})); }; //双击进入编辑界面 const doubleClickActionCreator = (index) => async (dispatch, getState) => { const {tableItems, editConfig} = getSelfState(getState()); let id = tableItems[index].id; let res = await fetchJson(`${URL_DETAIL}/${id}`); if(res.returnCode !=0){ showError(res.returnMsg); return; } const payload = buildEditState(editConfig, res.result, true); dispatch(action.assign(payload, 'edit')); }; const toolbarActions = { reset: resetActionCreator, search: searchActionCreator }; const clickActionCreator = (key) =>async(dispatch, getState) => { if (toolbarActions.hasOwnProperty(key)) { return toolbarActions[key](dispatch, getState); } else { return {type: 'unknown'}; } }; const pageNumberActionCreator = (currentPage) => (dispatch, getState) => { const {pageSize, searchDataBak={}} = getSelfState(getState()); const newState = {currentPage}; return search2(dispatch, action, URL_LIST, currentPage, pageSize, searchDataBak, newState); }; const pageSizeActionCreator = (pageSize, currentPage) => async (dispatch, getState) => { const {searchDataBak={}} = getSelfState(getState()); const newState = {pageSize, currentPage}; return search2(dispatch, action, URL_LIST, currentPage, pageSize, searchDataBak, newState); }; const mapStateToProps = (state) => { return getSelfState(state); }; const actionCreators = { onClick: clickActionCreator, onChange: changeActionCreator, onDoubleClick: doubleClickActionCreator, onPageNumberChange: pageNumberActionCreator, onPageSizeChange: pageSizeActionCreator }; const Container = connect(mapStateToProps, actionCreators)(OrderPage); export default Container;
var filters = { urls: ["<all_urls>"], types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest"] }; var hostname_regexp = /^https?:\/\/([^\/]*)/; var getHostname = function (url) { var result = url.match(hostname_regexp); return result ? result[1] : ""; }; var whiteList = []; var getConfig = function () { var newWhiteList = []; window.localStorage.getItem('config').split('\n').forEach(function (line) { line = line.trim(); if (line.length > 0) { try { newWhiteList.push(new RegExp('^' + line + '$', 'i')); } catch (e) {} } }); whiteList = newWhiteList; }; getConfig(); chrome.webRequest.onCompleted.addListener(function (details) { var requestHostname = getHostname(details.url); var i,l,match; for (i = 0, l = whiteList.length; i < l; i++) { if (match = requestHostname.match(whiteList[i])) { setTimeout(function () { chrome.tabs.sendMessage(details.tabId, {"hostname" : requestHostname, "ip" : details.fromCache ? 'fromCache' : details.ip}) }, 2000); } } }, filters)
$(document).ready(function(){ var $window = $(window); //You forgot this line in the above example $('section[data-type="background"]').each(function(){ var $bgobj = $(this); // assigning the object $(window).scroll(function() { var yPos = -($window.scrollTop() / $bgobj.data('speed')); // Put together our final background position var coords = '50% '+ yPos + 'px'; // Move the background $bgobj.css({ backgroundPosition: coords }); }); }); }); // ScrollUp $(document).ready(function(){ $.scrollUp(); }); // smooth scroll $(document).ready(function(){ var nav = $('.custom-navbar'); $(window).scroll(function () { if ($(this).scrollTop() > 136) { nav.addClass("navbar-fixed-top"); } else { nav.removeClass("navbar-fixed-top"); // $('#status').css("margin","100 !importnt"); } }); }); // preloader $(document).ready(function(){ $(window).load(function() { // makes sure the whole site is loaded $('#status').fadeOut(); // will first fade out the loading animation $('#preloader').delay(350).fadeOut('slow'); // will fade out the white DIV that covers the website. $('body').delay(350).css({'overflow':'visible'}); }); }); // wow jquary $(document).ready(function(){ new WOW().init(); }); // smooth scroll $ (document).ready(function(){ smoothScroll.init(); });
var tokki = angular.module("tokkiApp"); tokki.config(["$stateProvider", "$urlRouterProvider", function($stateProvider, $urlRouterProvider){ $stateProvider .state('system.sii.libroguias', { url: '/libroguias', templateUrl: 'pages/sii/libroguias/libroguias.html', controller: 'LibroGuias', resolve: { tokkiData: ["$q", "tokkiApi", function($q, tokkiApi){ var deferred = $q.defer(); var fecha = moment().format('YYYY-MM-DD 00:00:00'); var libro = tokkiApi.query({action: 'libroguia', control: 'datos', fecha: fecha}) $q.all([fecha, libro.$promise]). then(function(response) { deferred.resolve(response); }); return deferred.promise; } ] }, }) } ]); tokki.controller('LibroGuias', ['$scope', '$filter', '$rootScope', 'tokkiData', 'tokkiApi', function($scope, $filter, $rootScope, tokkiData, tokkiApi){ $scope.fecha = tokkiData[0]; $scope.dtes = tokkiData[1]; $scope.obtenerDatos = function(){ var fecha = moment($scope.fecha).format('YYYY-MM-DD 00:00:00'); libro = tokkiApi.query({action: 'libroguia', control: 'datos', fecha: fecha}) .$promise.then(function(response){ $scope.dtes = response; var length = $scope.dtes.length; calculate(); }) } $scope.generarLibro = function(){ var fecha = moment($scope.fecha).format('YYYY-MM-DD 00:00:00'); libroVenta = tokkiApi.save({action: 'libroguia', control: 'create', resumen: $scope.guias, dtes: $scope.dtes, fecha: fecha}) .$promise.then(function(response){ var pom = document.createElement('a'); pom.setAttribute('href', 'data:text/plain;charset=iso-8859-1;base64,' + response.xml); pom.setAttribute('download', 'testing.xml'); pom.style.display = 'none'; document.body.appendChild(pom); pom.click(); document.body.removeChild(pom); }, function(response){ swal("Error", response.data, "error"); }) } $scope.borrar = function(i) { $scope.dtes.splice(i, 1); calculate(); } var calculate = function(){ var length = $scope.dtes.length; $scope.guias = {dte: 52, folios: 0, exento: 0, neto: 0, iva: 0, total: 0, guiaventa: 0, guiaventatot: 0, anuladas: 0, traslados: {}}; for(i=0;i<length;i++){ $scope.guias.folios++; $scope.guias.exento += $scope.dtes[i].exento; $scope.guias.neto += $scope.dtes[i].neto; $scope.guias.iva += $scope.dtes[i].iva; $scope.guias.total += $scope.dtes[i].total; if($scope.dtes[i].anulado){ $scope.guias.anuladas++; } else{ if($scope.dtes[i].traslado > 1){ if($scope.guias.traslados[$scope.dtes[i].traslado]){ $scope.guias.traslados[$scope.dtes[i].traslado].folios++; $scope.guias.traslados[$scope.dtes[i].traslado].monto += $scope.dtes[i].total; } else{ $scope.guias.traslados[$scope.dtes[i].traslado] = {folios: 1, monto: $scope.dtes[i].total}; } } else{ $scope.guias.guiaventa++; $scope.guias.guiaventatot += $scope.dtes[i].total; } } } } calculate(); }] );
/** * @author:Jacob Cohen * @description: command call for gifs, sends a random gif from array * @returns: gif output (no @) * Date last edited: 4/2/2018 */ const CONFIG = require('../../config.json'); const COMMANDO = require('discord.js-commando'); var LINQ = require('node-linq').LINQ; //Gifs to select from var gifToUse = [ './gifs/gif0.gif', './gifs/gif1.gif', './gifs/gif2.gif', './gifs/gif3.gif', './gifs/gif4.gif', './gifs/gif5.gif', './gifs/gif6.gif', './gifs/gif7.gif', './gifs/gif8.gif', './gifs/gif9.gif', './gifs/gif10.gif', './gifs/gif11.gif', './gifs/gif12.gif', './gifs/gif13.gif', './gifs/gif14.gif', './gifs/gif15.gif', './gifs/gif16.gif', './gifs/gif17.gif', './gifs/gif18.gif', './gifs/gif19.gif', './gifs/gif20.gif', './gifs/gif21.gif', './gifs/gif22.gif', './gifs/gif23.gif', './gifs/gif24.gif', './gifs/gif25.gif' ]; //gif strings var gifString = [ 'clapping', 'steal', 'hacking', 'dos', 'obama', 'played', 'haters', 'winning', 'stop', 'fall', 'jason', 'abandon', 'jack', 'spooky', 'triggered', 'cat', 'bus', 'trump', 'another', 'hammer', 'gun', 'flamethrower', 'doit', 'justdoit', 'nothing', 'hackerman', ]; var length = gifToUse.length; class CommandGif extends COMMANDO.Command { constructor(BOT_COMMANDO) { super(BOT_COMMANDO, //command initializing { name: 'gif', group: 'multiple', memberName: 'gif', description: 'sends a gif. User can choose from a current amount of ' + length + ' gifs; or can input invalid data for a random gif to be choosen.', examples: [CONFIG.prefix + 'gif bus', CONFIG.prefix + '/gif 8', CONFIG.prefix + 'jif haters'], aliases: ['jif'], args: [ //enter index { key: 'input', prompt: 'Choose a number from 1 to ' + length + ' to select a certian gif. Or put in the string title of the gif. Put in invalid data to have a random gif chosen', type: 'string', default: '' }, ] }); } //run async run(message, { input }) { //prevents message from being deleted in dms if (message.guild !== null) { message.delete(); } //checks array to see if current channel is in it if (new LINQ(CONFIG.multipleNotAllowed).Any(row => row.includes(message.channel.id))) { return message.reply("Multiple commands are not allowed in this channel.") } //varaibles var post; var text; //number input if (!isNaN(input)) { //gets actual index input--; //user selected if (input <= length && input >= 0) { text = gifString[input] post = gifToUse[input]; } //random else { var rand = Math.floor(Math.random() * gifToUse.length) text = gifString[rand]; post = gifToUse[rand];; } } //name input else { switch (input.toLowerCase()) { //gif 0 case 'clapping': text = gifString[0]; post = gifToUse[0]; break; //gif 1 case 'steal': text = gifString[1]; post = gifToUse[1]; break; //gif 2 case 'hacking': text = gifString[2]; post = gifToUse[2]; break; //gif 3 case 'dos': text = gifString[3]; post = gifToUse[3]; break; //gif 4 case 'obama': text = gifString[4]; post = gifToUse[4]; break; //gif 5 case 'played': text = gifString[5]; post = gifToUse[5]; break; //gif 6 case 'haters': text = gifString[6]; post = gifToUse[6]; break; //gif 7 case 'winning': text = gifString[7]; post = gifToUse[7]; break; //gif 8 case 'stop': text = gifString[8]; post = gifToUse[8]; break; //gif 9 case 'fall': text = gifString[9]; post = gifToUse[9]; break; //gif 10 case 'jason': text = gifString[10]; post = gifToUse[10]; break; //gif 11 case 'abandon': text = gifString[11]; post = gifToUse[11]; break; //gif 12 case 'jack': text = gifString[12]; post = gifToUse[12]; break; //gif 13 case 'spooky': text = gifString[13]; post = gifToUse[13]; break; //gif 14 case 'triggered': post = gifToUse[14]; break; //gif 15 case 'cat': text = gifString[15]; post = gifToUse[15]; break; //gif 16 case 'bus': text = gifString[16]; post = gifToUse[16]; break; //gif 17 case 'trump': text = gifString[17]; post = gifToUse[17]; break; //gif 18 case 'another': text = gifString[18]; post = gifToUse[18]; break; //gif 16 case 'hammer': text = gifString[19]; post = gifToUse[19]; break; //gif 20 case 'gun': text = gifString[20]; post = gifToUse[20]; break; //gif 21 case 'flamethrower': text = gifString[21]; post = gifToUse[21]; break; //gif 22 case 'doit': text = gifString[22]; post = gifToUse[22]; break; //gif 23 case 'justdoit': text = gifString[23]; post = gifToUse[23]; break; //gif 24 case 'nothing': text = gifString[24]; post = gifToUse[24]; break; //gif 25 case 'hackerman': text = gifString[25]; post = gifToUse[25]; break; //random gif default: var rand = Math.floor(Math.random() * gifToUse.length) text = gifString[rand]; post = gifToUse[rand]; break; } } //text to send message.channel.send(text); //gif to send message.channel.send({files: [post]}); } } //return module.exports = CommandGif;
//App import React from 'react'; import Csj from './src' import reducer from './src/reducers' import {createStore,applyMiddleware} from 'redux' import { Provider } from 'react-redux' import thunk from 'redux-thunk' import logger from 'redux-logger' import promise from 'redux-promise-middleware' import { AsyncStorage } from 'react-native' import {login} from './src/actions/login' const middleware = [ thunk, promise() ] const store = createStore( reducer, applyMiddleware(...middleware) ) AsyncStorage.getItem('account',(err,value)=>{ if(value){ store.dispatch(login({account:value})) } }) export default class App extends React.Component { render() { return ( <Provider store={store}> <Csj /> </Provider> ); } }
/* Components */ import Home from "./components/Home"; import ProductList from "./components/ProductList"; import ToggleBtn from "./components/ToggleBtn"; import ProductDetail from "./components/ProductDetail"; /* Styled-components */ import { ThemeProvider } from "styled-components"; import { GlobalStyle } from "../src/styles"; /* Global useState */ import { useState } from "react"; /* Gloves Data */ import gloves from "./gloves"; /* Theme Coloring */ const theme = { light: { mainColor: "#000", backgroundColor: "#fff", borderColor: "#fff", red: "red", }, dark: { mainColor: "#fff", backgroundColor: "#000", borderColor: "#fff", red: "red", }, }; function App() { /* useState to change theme Color */ const [currentMode, setCurrentMode] = useState("dark"); /* function to toggle the page color and text Mode */ const toggleSwitch = () => { return currentMode === "dark" ? setCurrentMode("light") : setCurrentMode("dark"); }; /* useState to Delete the product by passing the id */ const [_gloves, setGloves] = useState(gloves); const deletGloves = (gloveID) => { const updateGloves = _gloves.filter((glove) => glove.id !== gloveID); setGloves(updateGloves); }; /* Here where will show the details and function will check the status of user clicked or not */ const [glove, setGlove] = useState(false); const setView = () => { return glove ? ( <ProductDetail glove={glove} setGlove={setGlove} /> ) : ( <ProductList setGlove={setGlove} gloves={_gloves} deletGloves={deletGloves} /> ); }; return ( <ThemeProvider theme={theme[currentMode]}> <ToggleBtn onClick={toggleSwitch} /> <GlobalStyle /> {/* Call Home File Contain (title, description, shop image)*/} <Home /> {/* Call function of product details or show all product */} {setView()} </ThemeProvider> ); } export default App;
function StringBuilder() { this._buffer = []; } StringBuilder.prototype = { constructor: StringBuilder, add: function (str) { this._buffer.push(str); }, toString: function () { return this._buffer.join(''); } };
var $ = require('../lib/jquery'); Carousel = function() { function Carousel($ct) { this.$ct = $ct; this.init(); this.bind(); this.autoPlay(); } Carousel.prototype.init = function() { this.$img = this.$ct.find('.img'); this.$imgCt = this.$ct.find('.img-ct'); this.$btnPre = this.$ct.find('.btn-pre'); this.$btnNxt = this.$ct.find('.btn-nxt'); this.$bullet = this.$ct.find('.bullet'); this.imgCount = this.$img.length; this.imgWidth = this.$img.width(); this.pageIndex = 0; this.isAnimate = false; this.$img.width(this.imgWidth); this.$img.find('img').width(this.imgWidth); this.$imgCt.prepend(this.$img.eq(this.imgCount - 1).clone()); this.$imgCt.append(this.$img.eq(0).clone()); this.$imgCt.width(this.imgWidth * (this.imgCount + 2)); this.$imgCt.css({ left: -(this.imgWidth) }) }; Carousel.prototype.bind = function() { var _this = this; this.$btnPre.on('click', function(e) { e.preventDefault(); _this.playPre(); }) this.$btnNxt.on('click', function(e) { e.preventDefault(); _this.playNxt(); }) this.$bullet.find('li').on('click', function() { _this.playTo($(this).index()); }) }; Carousel.prototype.stopAuto = function(e) { e.clearInterval(clock); } Carousel.prototype.autoPlay = function() { var _this = this; this.clock = setInterval(function() { _this.playNxt(); }, 3000); } Carousel.prototype.playTo = function(n) { var _this = this; if (this.isAnimate === true) return; this.isAnimate = true; this.$imgCt.animate({ left: '+=' + (_this.pageIndex - n) * _this.imgWidth }, function() { _this.pageIndex = n; _this.isAnimate = false; _this.setBullet(); }) } Carousel.prototype.playNxt = function() { var _this = this; if (this.isAnimate === true) return; this.isAnimate = true; this.$imgCt.animate({ left: '-=' + this.imgWidth }, function() { _this.pageIndex++; if (_this.pageIndex === _this.imgCount) { _this.$imgCt.css('left', -_this.imgWidth); _this.pageIndex = 0; } _this.isAnimate = false; _this.setBullet(); }) } Carousel.prototype.playPre = function() { var _this = this; if (this.isAnimate === true) return; this.isAnimate = true; this.$imgCt.animate({ left: '+=' + this.imgWidth }, function() { _this.pageIndex--; if (_this.pageIndex < 0) { _this.$imgCt.css('left', -(_this.imgCount * _this.imgWidth)); _this.pageIndex = _this.imgCount - 1; } _this.isAnimate = false; _this.setBullet(); }) } Carousel.prototype.setBullet = function() { this.$bullet.children().removeClass('active').eq(this.pageIndex).addClass('active') } return { init: function($ct) { $ct.each(function(index, node) { new Carousel($(node)) }) } } }() module.exports = Carousel;
/* Written by beeven on 3/17/2015 */ var animations = (function() { var that = this; var slides = $(".slide"); var currentSlide = -1; function ShowNextSlide() { currentSlide++; if(currentSlide >= slides.length) { currentSlide = -1; } slides.removeClass("current"); if(currentSlide!=-1) { $(slides[currentSlide]).addClass("current"); var fn = $(slides[currentSlide]).attr('data-animation') if(fn == null || typeof(fn) === 'undefined') { fn = function(){} } return Q.fcall(that[fn]); } else { return Q(null); } } this.ShowTitle = function() { // return Q.all([ // Q.Promise(function(resolve,reject,notify){ // $("#slide1").animate({backgroundColor: "#333"},500,null,function(){resolve()}); // }), // Q.Promise(function(resolve,reject,notify){ // $(".title").show('slow',function(){resolve()}); // }) // ]); return Q("hello1"); } this.ShowSlide2 = function() { return Q.Promise(function(resolve,reject,notify){ $("#slide2 .typed").typed({ strings: ["Hello, Maeva", "I have something to share with you."], typeSpeed: 0, callback: function(){resolve()} }); }); } this.ShowSlide3 = function() { return Q.Promise(function(){ mapslides.ShowNextPoi().then(function(){ mapslides.ShowNextPoi(); }); }) } return { ShowNextSlide: ShowNextSlide } })();
const value = document.querySelectorAll('span') const show = [] let hide = [] for (let i = 0; i < value.length; i++) { if (value[i].innerHTML.includes("*") === false) { hide.push("*******") show.push(value[i].innerHTML) value[i].innerHTML = hide[i] } value[i].addEventListener("click", () => { value[i].innerHTML = show[i] }) }
import React, {useCallback, useEffect} from 'react'; import {AppBar, Button, Toolbar} from "@material-ui/core"; import Logo from "../../assets/Logo.svg"; import {useStyles} from "./styled"; import {v4} from 'uuid'; import {useHistory} from "react-router-dom"; import {setAuth} from "../../store/auth/actions"; import {useDispatch, useSelector} from "react-redux"; import {googleSignOut, onLoad} from "../../utils/googleAuth"; const Header = () => { const dispatch = useDispatch() const history = useHistory() const classes = useStyles(); const isAuth = useSelector(state => state.authReducer.isAuth) const auth = isAuth ? 'sign out' : 'sign in' const links = isAuth ? ['tickets', 'users', 'booking'] : [] useEffect(() => { onLoad() }, []); const signOut = useCallback(() => { if (googleSignOut()) { dispatch(setAuth()) history.push('/') } }, []) const clickHandler = (e) => { const target = '/' + e.target.innerText.toLowerCase() if (target === history.location.pathname) { return null } else if (target === '/login') { signOut() } else { history.push(target) } } const authHandler = () => { if (isAuth) { signOut() } else history.push('/') } return ( <AppBar position="static" className={classes.appBar}> <Toolbar className={classes.header}> <div className={classes.linksblock}> <div className={classes.logoWrapper}> <img src={Logo} height='60' width='60' alt="logo"/> </div> {links.map(item => <Button color="inherit" key={v4()} onClick={clickHandler}>{item}</Button>)} </div> <Button color="inherit" onClick={authHandler}>{auth}</Button> </Toolbar> </AppBar> ); }; export default Header;
const Koa = require('koa') const serve = require('koa-static') const server = new Koa() let port = process.env.PORT || 80 server.use(serve('./build')) server.use(serve('./files')) server.listen(port)
var assert = require('chai').assert; var Zombie = require('zombie'); /** * Not working * describe('basic web tests', function(){ var browser = new Zombie(); before(function(done){ browser.visit("http://localhost:8080/", function(){ done(); }); }); it("should load the page", function(){ browser.assert.text("title", "InSite"); }); it("map should hide if list is active", function(done){ browser.visit("location.href=http://localhost:8080/#List", function(){ browser.assert.evaluate("$('map').html().trim()===''"); }); }); }); **/
import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import { compose } from 'redux'; import { Button } from 'antd'; import buttonStyle from '../../antdTheme/button/style/index.less'; import { connect } from '../../store/redux'; import { commonReducer } from '../../store/common.reducer'; import { commonAction } from '../../store/common.action'; import s from './TableDemo.css'; import Query from '../../components/Query'; import Xtable from '../../components/XTable'; const StateName = 'tableDemo'; const defaultState = { test: 'default', table: { current: 1, pageSize: 10, }, }; const tableColumns = [ { title: '企业名称', dataIndex: 'buName', key: 'buName', width: 100, fixed: 'left', sorter: (a, b) => a > b, }, { title: '法人电话', dataIndex: 'ownerMobile', key: 'ownerMobile', width: 100, }, { title: '认证状态', dataIndex: 'authSatusStr', key: 'authSatusStr', }, { title: '认证状态', dataIndex: 'authSatusStr1', key: 'authSatusStr1', width: 500, }, { title: '操作', dataIndex: 'aa', key: 'aa', render: () => <a href="">编辑</a>, width: 200, fixed: 'right', }, ]; class Home extends React.Component { render() { const { table = {}, height = '70%' } = this.props; return ( <div style={{ height: '100%' }}> <h2>例子:</h2> <Button onClick={() => { this.props.commonAction({ height: height === '70%' ? '50%' : '70%', }); this.props.commonAction({ table: { resizeKey: Math.random(), }, }); }} > 改变高度 </Button> <Query method="get" url="{apiUrl}/op/v1/supplier/queryApplyList" statePath={`${StateName}.table`} data={{ pageSize: table.pageSize || 10, pageNum: table.current || 1, }} /> <Xtable resizeKey={table.resizeKey} style={{ height }} statePath={`${StateName}.table`} columns={tableColumns} rowKey="id" /> <h2>参数说明:</h2> <ul style={{ fontSize: 20, lineHeight: 1.7 }}> <li>statePath: 字符串:store中存储列表数据的位置(必填)</li> <li> columns: 数组:列属性,同antdesign,可选择添加sort,fixed等属性(必填) </li> <li>rowKey: 字符串:行键值(必填)</li> <li>resizeKey: 任意值:通过修改可以触发列表重新计算高度</li> <li>style: 容器样式</li> <li>className: 容器类名</li> <li>needRowSelection: 是否显示check框 默认true</li> <li>rowSelectionCallback: 点击check框触发回调函数</li> <li>其他参数 同antdesign</li> </ul> <h2>待解决问题:</h2> <ul style={{ fontSize: 20, lineHeight: 1.7 }}> <li>浏览器频繁resize后页面卡死(已解决)</li> <li>加入到模板页面(进行中)</li> </ul> <h2>注意:</h2> <ul style={{ fontSize: 20, lineHeight: 1.7 }}> <li>columns中设置fixed固定的列必须给定width</li> <li>columns中的width 不要小于100</li> </ul> </div> ); } } const mapState = state => ({ layout: state.layout, ...state[StateName], }); const mapDispatch = { commonAction: commonAction(StateName), }; export default compose( withStyles(s, buttonStyle), connect( StateName, commonReducer(StateName, defaultState), mapState, mapDispatch, ), )(Home);
define([ 'jquery', 'underscore', 'backbone' ], function($, _, Backbone){ SlideCollection = Backbone.Collection.extend({ initialize:function () { this.currentSlideIndex = -1; }, next : function(){ var prevSlideIndex = this.currentSlideIndex; this.currentSlideIndex += 1; console.log("next! "+this.currentSlideIndex); if (this.currentSlideIndex >= this.length){ this.currentSlideIndex = this.length-1; } this.trigger('slideChange',this.currentSlideIndex,prevSlideIndex); }, prev : function(){ var prevSlideIndex = this.currentSlideIndex; this.currentSlideIndex -= 1; console.log("prev! "+this.currentSlideIndex); if (this.currentSlideIndex < 0){ this.currentSlideIndex = 0; } this.trigger('slideChange',this.currentSlideIndex,prevSlideIndex); }, jumpTo : function(index){ var prevSlideIndex = this.currentSlideIndex; if (index >= 0 && index < this.length && index != this.currentSlideIndex){ console.log("Jump to "+index); this.currentSlideIndex = parseInt(index); this.trigger('slideChange',this.currentSlideIndex,prevSlideIndex); } return this.at(index); }, // jumpToByURL : function(url){ // var slide = this.findWhere({dataURL:url}); // if (slide != null){ // var index = this.indexOf(slide); // if (this.currentSlideIndex != index) // this.trigger('all'); // } // }, urlExists : function (url){ var slide = this.findWhere({dataURL:url}); console.log("url exists? "+url); if (slide != null) return true; else return false; }, getCurrentSlide : function(){ console.log("Current slide index? "+this.currentSlideIndex); var slideIndex = this.length-1; if (this.currentSlideIndex >= 0 && this.currentSlideIndex < this.length){ slideIndex = this.currentSlideIndex; console.log("within range"); } else{ this.currentSlideIndex = slideIndex; console.log("Outside range"); } console.log("Get current slide! "+slideIndex); return this.at(slideIndex); }, isCurrent : function(slide){ var slideIndex = this.indexOf(slide); if (this.currentSlideIndex == slideIndex){ return true; } else{ return false; } } }); return SlideCollection; });