text
stringlengths
7
3.69M
// Array.from(); // 类数组对象转为真正的数组 // 第一个参数类数组对象 // 第二个参数, map方法 // 第三个参数, map方法中的this指向 function foo() { var args = [...arguments]; console.log('arguments: ', arguments); console.log('args: ', args); console.log('Array.from: ', Array.from(arguments, x => x*x) ); } foo(2, 3, 4); // Array.of 将一组值转换为数组 // 数组实例的copyWithin()方法 var ss = [].copyWithin.call({length: 5, 3: 1}, 0, 3); // console.log('ss: ', ss); // 数组实例的find和findIndex方法 var r2 = [{name: 'heke'}, {name: 'yunkehe'}].find(x => x.name === 'heke'); var r3 = [{name: 'heke'}, {name: 'yunkehe'}].findIndex(x => x.name === 'heke'); console.log('r2: ', r2); console.log('r3: ', r3); console.log( [NaN].indexOf(NaN) ); // -1; console.log( [NaN].findIndex(x => Object.is(NaN, x)) ); // 0 // 数组实例的fill方法 填充空数组 // entries(), keys(), values() let letter = ['a', 'b', 'c']; let entries = letter.entries(); console.log(entries.next().value); console.log(entries.next().value); console.log(entries.next().value); console.log(entries.next().value); // includes是否包含某个值 // 数组的空位 0 in [4, 3] // 0 in [, 3] // 数组的空位 各个方法处理方式不太一样 // 数组推导 function caculate(times) { let i = 0; while (i < times) i++; } function log(fn) { return function(...args) { const start = Date.now(); fn(...args); const used = Date.now() - start; console.log(`call ${fn.name} {${args}} used ${used}ms`); } } caculate = log(caculate); caculate(1000); caculate(100000);
const path = require("path") const requireIndex = require("requireindex") module.exports = { get rules() { // eslint-disable-next-line prefer-destructuring const RULES_DIR = module.exports.RULES_DIR if (typeof module.exports.RULES_DIR !== "string") { throw new Error( "To use eslint-plugin-boyscout, you must load it beforehand and set the `RULES_DIR` property on the module to a string. See https://npmjs.com/eslint-plugin-boyscout for an example" ) } return requireIndex(path.resolve(RULES_DIR)) } }
const mongoose = require('mongoose'); const submissionSchema = require('./submission.schema.server'); const submissionModel = mongoose.model('SubmissionModel', submissionSchema); findAllSubmissions = () => submissionModel.find(); findSubmissionById = (submissionId) => submissionModel.findById(submissionId); findAllSubmissionsForQuizAndStudent = (quizId, studentId) => { return submissionModel.find({quiz: quizId, student: studentId}); } findAllSubmissionsForQuiz = quizId => submissionModel.find({quiz: quizId}); createSubmission = submission => { return submissionModel.create(submission); }; deleteSubmission = submission => submissionModel.delete(submission); updateSubmission = (submissionId, newSubmission) => submissionModel.update({_id: submissionId}, {$set: newSubmission}); module.exports = { findAllSubmissions, findSubmissionById, findAllSubmissionsForQuizAndStudent, findAllSubmissionsForQuiz, createSubmission, deleteSubmission, updateSubmission };
var url = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json"; var xl = []; var yl = []; Plotly.d3.json(url, function(figure) { var data = figure.data; for (var i = 0; i < data.length; i++) { xl.push(data[i][0]) yl.push(data[i][1]) } var trace = { x: xl, y: yl, marker: { color: 'rgb(55, 83, 109)' }, type:'bar', } var layout = { title: "USA GDP from January 1st 1947 to July 1st 2015", yaxis:{ title: "USA GDP" }, xaxis: { title: "Date" } , // autosize: true, width: 0, height: 0, margin: { l: 100, r: 50, b: 100, t: 100, pad: 4 }, } // var d3 = Plotly.d3; // var WIDTH_IN_PERCENT_OF_PARENT = 80; // var HEIGHT_IN_PERCENT_OF_PARENT = 0; // var gd3 = d3.select('body').append('div').style({ // width: WIDTH_IN_PERCENT_OF_PARENT + '%', // 'margin-left': (100 - WIDTH_IN_PERCENT_OF_PARENT) / 2 + '%', // height: HEIGHT_IN_PERCENT_OF_PARENT + '%', // 'margin-top': (100 - HEIGHT_IN_PERCENT_OF_PARENT) / 2 + '%' // }); // var gd = gd3.node(); Plotly.plot(document.getElementById('graph'), [trace], layout, {displayModeBar: false}); // Plotly.plot(document.getElementById('graph1'), [trace], layout, {displayModeBar: false}); window.onresize = function() { Plotly.Plots.resize(document.getElementById('graph')); // Plotly.Plots.resize(document.getElementById('graph1')); }; });
export { default as List } from './List/List'; export { default as InputWithLabel } from './InputWithLabel/InputWithLabel'; export { default as SearchForm } from './SearchForm/SearchForm';
const net = require('net'); const socks5 = require('../index'); const socks5Server = net.createServer((socket) => { // upgrade socket const conn = new socks5.ServerSocket(socket); socket.on('error', (err) => { console.error(err); }); conn.on('connect', ()=>{ let s = `${conn.remoteAddress}:${conn.remotePort}` + ` > ${conn.dstHost}:${conn.dstPort}`; if (conn.username !== undefined && conn.password !== undefined) { s += ` [ ${conn.username} : ${conn.password} ]`; } console.log(s); }); socks5.proxy(conn); }); socks5Server.listen(8888, () => { console.log('SOCKS5 Proxy listen on :8888'); });
module.exports = { collectCoverage: true, collectCoverageFrom: ['**/*.{ts,tsx}', '!**/node_modules/**'], moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'], setupTestFrameworkScriptFile: require.resolve('./jest.setup.js'), testMatch: ['**/*.test.ts?(x)'], transform: { '^.+\\.tsx?$': 'babel-jest', }, };
import axios from 'axios'; export const getTrendingGifs = () => { return async (dispatch) => { const gifList = await axios.get('http://api.giphy.com/v1/gifs/trending?api_key=ms344CewNH5NEbybHwQifMZImoQfEQ38&limit=21'); dispatch({ type: 'GET_TRENDING_LIST', payload: gifList.data.data }); } }; export const getArtistGifs = () => { return async (dispatch) => { const gifList = await axios.get('https://api.giphy.com/v1/gifs/search?q=artist&api_key=ms344CewNH5NEbybHwQifMZImoQfEQ38'); dispatch({ type: 'GET_ARTIST_LIST', payload: gifList.data.data }); } }; export const getReactionsGifs = () => { return async (dispatch) => { const gifList = await axios.get('https://api.giphy.com/v1/gifs/search?q=reactions&api_key=ms344CewNH5NEbybHwQifMZImoQfEQ38'); dispatch({ type: 'GET_REACTIONS_LIST', payload: gifList.data.data }); } }; export const getSearchedGifs = (searchTerm) => { return async (dispatch) => { const gifList = await axios.get(`https://api.giphy.com/v1/gifs/search?q=${searchTerm}&api_key=ms344CewNH5NEbybHwQifMZImoQfEQ38`); dispatch({ type: 'GET_SEARCHED_GIFS', payload: gifList.data.data }); } }; export const getGifList = (searchTerm) => { return async (dispatch) => { const gifList = await axios.get(`https://api.giphy.com/v1/gifs/search?q=${searchTerm}&api_key=ms344CewNH5NEbybHwQifMZImoQfEQ38`); dispatch({ type: 'GET_GIF_LIST', payload: gifList.data.data }); } }; export const getTrendingStickers = () => { return async (dispatch) => { const gifList = await axios.get(`http://api.giphy.com/v1/stickers/trending?api_key=ms344CewNH5NEbybHwQifMZImoQfEQ38&limit=21`); dispatch({ type: 'GET_TRENDING_STICKERS', payload: gifList.data.data }); } }; export const getStickersList = (searchTerm) => { return async (dispatch) => { const gifList = await axios.get(`https://api.giphy.com/v1/stickers/search?q=${searchTerm}&api_key=ms344CewNH5NEbybHwQifMZImoQfEQ38`); dispatch({ type: 'GET_STICKERS_LIST', payload: gifList.data.data }); } }; export const updateSearchTerm = (term) => { return { type: 'GET_SEARCH_TERM', payload: term } }; export const updateTagTitle = (title) => { return { type: 'UPDATE_TAG_TITLE', payload: title } }; export const getTitle = (title) => { return { type: 'GET_TITLE', payload: title } };
export function validateKorean_name(korean_name) { const korean_namereg = /^[가-힣]+$/; const isKorean_nameValid = korean_namereg.test(korean_name); return isKorean_nameValid; } export function validateEnglish_name(english_name) { const english_namereg = /^[a-zA-Z]*$/; const isEnglish_nameValid = english_namereg.test(english_name); return isEnglish_nameValid; } export function validateEmail(email) { const emailreg = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i; const isEmailValid = emailreg.test(email); return isEmailValid; } export function validatePhone(phone) { const phonereg = /^\d{3}\d{3,4}\d{4}$/; const isPhoneValid = phonereg.test(phone); return isPhoneValid; } export function validatePassport(passport) { const passportreg = /^[A-Z]+[0-9]{8}$/g; const isPassportValid = passportreg.test(passport); return isPassportValid; } export function validateBirth(birth) { const birthreg = /^(19[0-9][0-9]|20\d{2})-(0[0-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/; const isBirthValid = birthreg.test(birth); return isBirthValid; }
import React, { Component } from "react"; import { Doughnut } from "react-chartjs-2"; import PropTypes from "prop-types"; import { Card, CardBody, Table } from "reactstrap"; class DoughnutChart extends Component { render() { var data_labels = this.props.data.map(block => { return block.result; }); var data_items = this.props.data.map(item => { return item.count; }); return ( <div className="card"> <div class="card-header"> <h5 class="card-category">{this.props.title}</h5> </div> <div className="card-body"> <Doughnut data={canvas => { const ctx = canvas.getContext("2d"); var chartColor = "rgba(128, 182, 244, 0.1)"; var gradientStroke = ctx.createLinearGradient(500, 0, 100, 0); gradientStroke.addColorStop(0, "#80b6f4"); gradientStroke.addColorStop(1, chartColor); var gradientFill = ctx.createLinearGradient(0, 500, 0, 50); gradientFill.addColorStop(0, "rgba(128, 182, 244, 0)"); gradientFill.addColorStop(1, "rgba(255, 255, 255, 0.8)"); return { labels: data_labels, datasets: [ { label: this.props.label, borderColor: chartColor, pointBorderColor: chartColor, pointBackgroundColor: "rgba(128, 182, 244, 0.5)", pointHoverBackgroundColor: "#2c2c2c", pointHoverBorderColor: chartColor, pointBorderWidth: 1, pointHoverRadius: 7, pointHoverBorderWidth: 2, pointRadius: 5, fill: true, backgroundColor: gradientFill, borderWidth: 2, data: data_items } ] }; }} /> <Table responsive> <thead className=" text-primary"> <tr> <th>{this.props.tablelabel}</th> <th className="text-right">Count</th> </tr> </thead> <tbody> {this.props.data.map((data, key)=>{ return ( <tr key={key}> <td>{data.result==""?"Unknown":data.result}</td> <td className="text-right">{data.count}</td> </tr> ) })} </tbody> </Table> </div> </div> ); } } DoughnutChart.propTypes = { // Where the user to be redirected on clicking the avatar data: PropTypes.object, label: PropTypes.string, title: PropTypes.string, tablelabel: PropTypes.string }; export default DoughnutChart;
import logo from './logo.svg'; import React, { useState, useEffect } from 'react' import { BrowserRouter, BrowserRouter as Router, Route, Switch } from 'react-router-dom' import './App.css'; import TesPage from './pages/tesPage/TesPage'; import Header from './components/header/header'; import Footer from './components/footer/footer'; import AppContext from './components/AppContext/AppContext'; import OurListPage from './pages/OurListPage/OurListPage'; import AlbumPage from './pages/AlbumPage/AlbumPage'; import SearchPage from './pages/SearchPage/SearchPage'; import FavoritePage from './pages/FavoritePage/FavoritePage'; function App() { const [darkMode, setDarkMode] = useState(false) const [favorite, setFavorite] = useState([]) const toogleDark = () => { setDarkMode(!darkMode) } const addToFav = (fav) => { setFavorite([...favorite, fav]) } const removeFromFav = (fav) => { setFavorite(favorite.filter(item => item.name !== fav.name)) } const checkIsFoundFav = (fav) => { for(let f of favorite){ if(fav.id == f.id) return true } return false } const context = { darkMode: darkMode, favorite: favorite, setDarkMode, setFavorite, toogleDark, addToFav, removeFromFav, checkIsFoundFav } return ( <AppContext.Provider value={context}> <Router> {/* <Header/> */} <Switch> <Route path="/favorite"> <FavoritePage/> </Route> <Route path="/search"> <SearchPage/> </Route> <Route path="/album/:id"> <AlbumPage/> </Route> <Route path="/"> <OurListPage/> </Route> </Switch> </Router> {/* <Footer/> */} </AppContext.Provider> ); } export default App;
$( function () { // Imports let BFSForm = window.__BFS.exports.BFSForm BFSForm.validators = { name ( name ) { name = name.trim(); if ( name === "" ) throw new Error( "Please provide your name." ); if ( name.match( /\d/ ) ) throw new Error( "Please provide a valid name." ); return name; }, emailAddress ( emailAddress ) { emailAddress = emailAddress.trim(); emailAddress = emailAddress.replace( /\s/g, "" ) if ( emailAddress === "" ) throw new Error( "Please provide your email address." ); if ( ! /@/.test( emailAddress ) ) throw new Error( "Please provide a valid email address." ); return emailAddress; }, phoneNumber ( phoneCountryCode, phoneNumberLocal ) { phoneCountryCode = phoneCountryCode.replace( /[^\+\d+]/g, "" ) phoneNumberLocal = phoneNumberLocal.trim(); let phoneNumber = phoneCountryCode + phoneNumberLocal; if ( phoneNumberLocal.length <= 1 ) throw new Error( "Please provide a valid phone number." ); // For India if ( phoneCountryCode === "+91" && phoneNumberLocal.length !== 10 ) throw new Error( "Please provide a valid 10-digit number." ) if ( phoneNumberLocal.length > 1 ) if ( ! ( phoneNumber.match( /^\+\d[\d\-]+\d$/ ) // this is not a perfect regex, but it's close && phoneNumberLocal.replace( /\D/g, "" ).length > 3 ) ) throw new Error( "Please provide a valid phone number." ); return phoneNumber; } }; /* * * Wire in the phone country code UI * */ $( document ).on( "change", ".js_phone_country_code", function ( event ) { var $countryCode = $( event.target ); var countryCode = $countryCode.val().replace( /[^\+\d]/g, "" ); $countryCode .closest( "form" ) .find( ".js_phone_country_code_label" ) .val( countryCode ); } ); } );
'use strict' angular.module('main') .controller('ProjectsFilesListController', ['$scope', '$routeParams', 'ProjectFile', function ($scope, $routeParams, ProjectFile) { $scope.project_id = $routeParams.id; $scope.files = ProjectFile.query({id: $scope.project_id}); }]);
const { dcBot, tgBot, DCREVCHN, TGREVGRP } = require( '../util/bots' ); /** * @typedef {import('./command').reply} reply * @typedef {import('./command').command} command */ /** * @param {command} command */ function tgCommand( command ) { tgBot.telegram.setMyCommands( [ { command: command.name, description: command.description } ] ); tgBot.command( command.name, function ( ctx ) { let args = ctx.message.text.split( ' ' ); args.shift(); command.run( { dcBot, tgBot }, args, /** * @type {reply} */ async function ( { tMsg, dMsg }, iserror, eMsg ) { if ( iserror ) { ctx.reply( tMsg, { // eslint-disable-next-line camelcase parse_mode: 'Markdown', // eslint-disable-next-line camelcase reply_to_message_id: ctx.message } ).catch( function () { ctx.reply( tMsg ); } ); return; } let m = await ctx.reply( tMsg, { // eslint-disable-next-line camelcase parse_mode: 'Markdown', // eslint-disable-next-line camelcase disable_web_page_preview: true } ); if ( ctx.chat.id === TGREVGRP ) { dcBot.channels.cache.get( DCREVCHN ).send( dMsg ); } return m } ); } ); } /** * @param {command} command */ function dcCommand( command ) { dcBot.on( 'message', function ( message ) { if ( typeof message.content !== 'string' || !message.content.startsWith( `/${ command.name }` ) ) { return; } let args = message.content.split( ' ' ); args.shift(); command.run( { dcBot, tgBot }, args, /** * @type {reply} */ async function ( { tMsg, dMsg }, iserror, eMsg ) { if ( iserror ) { message.channel.send( dMsg ); return; } let m = await message.channel.send( dMsg ); if ( message.channel.id === DCREVCHN ) { tgBot.telegram.sendMessage( TGREVGRP, tMsg, { // eslint-disable-next-line camelcase parse_mode: 'Markdown', // eslint-disable-next-line camelcase disable_web_page_preview: true } ); } return m } ); } ); } /** * @param {command} command */ function bindCommand( command ) { console.log( `\x1b[33m[Command]\x1b[0m Load plugin ${ command.name }` ); dcCommand( command ); tgCommand( command ); } module.exports = { tgCommand, dcCommand, bindCommand };
let a = { aa : '123' }; console.log( `哈哈:${ a.aa }` );
import React from "react" import { withRouter } from "react-router"; import { connect } from "react-redux" import { Col, Row, Badge, Card, Space, Drawer, Button, } from "antd" import MainLayout from "../../layouts/MainLayout" import {setGoBack} from "../../stores/app/actions" // import FloorPlanPage from "../../assets/images/FloorPlanPage.jpg" import Circle from "../../components/FloorPlan/Circle"; import Rectangle from "../../components/FloorPlan/Rectangle"; const mapStateToProps = state => ({ }) const mapDispatchToProps = dispatch => { return { setGoBack: (val) => dispatch(setGoBack(val)) } } const connector = connect(mapStateToProps, mapDispatchToProps) class FloorPlan extends React.Component { componentDidMount() { this.props.setGoBack(true); } render() { return ( <MainLayout> <Row gutter={[16, 16]}> <Col> <svg viewBox="0 0 400 400" width="600" height="500" style={{border: "1px solid black"}}> <Circle /> <Rectangle /> </svg> </Col> </Row> </MainLayout> ) } } export default connector(withRouter(FloorPlan));
import editor from 'hyrax/editor' import GppSaveWorkControl from 'gpp/save_work/save_work_control' export default class extends editor { saveWorkControl() { new GppSaveWorkControl(this.element.find('#form-progress'), this.adminSetWidget) } }
/** * @author:Jacob Cohen * @description: command call for law, sends a random law from array * @returns: text output (no @) * Date last edited: 4/1/2018 */ //laws to select from var laws = [ "Murphy was a grunt.", "Recoilless rifles - aren't.", "Suppressive fires - won't.", "You are not Superman; Marines and fighter pilots take note.", "A sucking chest wound is Nature's way of telling you to slow down.", "If it's stupid but it works, it isn't stupid.", "Try to look unimportant; the enemy may be low on ammo and not want to waste a bullet on you.", "If at first you don't succeed, call in an air strike.", "If you are forward of your position, your artillery will fall short.", "Never share a foxhole with anyone braver than yourself.", "Never go to bed with anyone crazier than yourself", "Never forget that your weapon was made by the lowest bidder.", "If your attack is going really well, it's an ambush.", "The enemy diversion you're ignoring is their main attack.", "The enemy invariably attacks on two occasions: when they're ready. when you're not.", "No OPLAN ever survives initial contact.", "There is no such thing as a perfect plan.", "Five second fuses always burn three seconds", "There is no such thing as an atheist in a foxhole.", "A retreating enemy is probably just falling back and regrouping.The Ol' Ranger's addendum: Or else they're trying to suck you into a serious ambush!", "The important things are always simple; the simple are always hard.", "The easy way is always mined.", "Teamwork is essential; it gives the enemy other people to shoot at.", "Don't look conspicuous; it draws fire. For this reason, it is not at all uncommon for aircraft carriers to be known as bomb magnets.", "Never draw fire; it irritates everyone around you.", "If you are short of everything but the enemy, you are in the combat zone.", "When you have secured the area, make sure the enemy knows it too.", "Incoming fire has the right of way.", "No combat ready unit has ever passed inspection.", "No inspection ready unit has ever passed combat.", "If the enemy is within range, so are you.", "The only thing more accurate than incoming enemy fire is incoming friendly fire.", "Things which must be shipped together as a set, aren't.", "Things that must work together, can't be carried to the field that way.", "Radios will fail as soon as you need fire support.", "Radar tends to fail at night and in bad weather, and especially during both.", "Anything you do can get you killed, including nothing.", "Make it too tough for the enemy to get in, and you won't be able to get out.", "Tracers work both ways.", "If you take more than your fair share of objectives, you will get more than your fair share of objectives to take.", "When both sides are convinced they're about to lose, they're both right.", "Professional soldiers are predictable; the world is full of dangerous amateurs.", "Military Intelligence is a contradiction.", "Fortify your front; you'll get your rear shot up.", "Weather ain't neutral.", "If you can't remember, the Claymore is pointed toward you.", "Air defense motto: shoot 'em down; sort 'em out on the ground.", "Flies high, it dies; low and slow, it'll go.", "The Cavalry doesn't always come to the rescue.", "Napalm is an area support weapon.", "Mines are equal opportunity weapons.", "B - 52s are the ultimate close support weapon.", "Sniper's motto: reach out and touch someone.", "Killing for peace is like screwing for virginity.", "The one item you need is always in short supply.", "Interchangeable parts aren't.", "It's not the one with your name on it; it's the one addressed to whom it may concern you've got to think about.", "When in doubt, empty your magazine.", "The side with the simplest uniforms wins.", "Combat will occur on the ground between two adjoining maps.", "If the Platoon Sergeant can see you, so can the enemy.", "Never stand when you can sit, never sit when you can lie down, never stay awake when you can sleep.", "The most dangerous thing in the world is a Second Lieutenant with a map and a compass.", "Exceptions prove the rule, and destroy the battle plan.", "Everything always works in your HQ, everything always fails in the Colonel's HQ.", "The enemy never watches until you make a mistake.", "One enemy soldier is never enough, but two is entirely too many.", "A clean(and dry) set of BDU's is a magnet for mud and rain.", "The worse the weather, the more you are required to be out in it.", "Whenever you have plenty of ammo, you never miss.Whenever you are low on ammo, you can't hit the broad side of a barn.", "The more a weapon costs, the farther you will have to send it away to be repaired.", "The complexity of a weapon is inversely proportional to the IQ of the weapon's operator.", "Field experience is something you don't get until just after you need it.", "No matter which way you have to march, its always uphill.", "If enough data is collected, a board of inquiry can prove anything.", "For every action, there is an equal and opposite criticism. (in boot camp).", "Air strikes always overshoot the target, artillery always falls short.", "When reviewing the radio frequencies that you just wrote down, the most important ones are always illegible.", "Those who hesitate under fire usually do not end up KIA or WIA.", "The tough part about being an officer is that the troops don't know what they want, but they know for certain what they don't want.", "To steal information from a person is called plagiarism.To steal information from the enemy is called gathering intelligence.", "The weapon that usually jams when you need it the most is the M60.", "The perfect officer for the job will transfer in the day after that billet is filled by someone else.", "When you have sufficient supplies & ammo, the enemy takes 2 weeks to attack. When you are low on supplies & ammo the enemy decides to attack that night.", "The newest and least experienced soldier will usually win the Medal of Honor.", "A Purple Heart just proves that were you smart enough to think of a plan, stupid enough to try it, and lucky enough to survive.", "Murphy was a grunt.", "Beer Math: 2 beers times 37 men equals 49 cases.", "Body count Math: 3 guerrillas plus 1 probable plus 2 pigs equals 37 enemies killed in action.", "The bursting radius of a hand grenade is always one foot greater than your jumping range.", "All - weather close air support doesn't work in bad weather.", "The combat worth of a unit is inversely proportional to the smartness of its outfit and appearance.", "The crucial round is a dud.", "Every command which can be misunderstood, will be.", "There is no such place as a convenient foxhole.", "Don't ever be the first, don't ever be the last and don't ever volunteer to do anything.", "If your positions are firmly set and you are prepared to take the enemy assault on, he will bypass you.", "If your ambush is properly set, the enemy won't walk into it.", "If your flank march is going well, the enemy expects you to outflank him.", "Density of fire increases proportionally to the curiousness of the target.", "Odd objects attract fire -never lurk behind one.", "The more stupid the leader is, the more important missions he is ordered to carry out.", "The self-importance of a superior is inversely proportional to his position in the hierarchy (as is his deviousness and mischievousness).", "There is always a way, and it usually doesn't work.", "Success occurs when no one is looking, failure occurs when the General is watching.", "The enemy never monitors your radio frequency until you broadcast on an unsecured channel.", "Whenever you drop your equipment in a fire-fight, your ammo and grenades always fall the farthest away, and your canteen always lands at your feet.", "As soon as you are served hot chow in the field, it rains.", "Never tell the Platoon Sergeant you have nothing to do.", "The seriousness of a wound(in a fire - fight) is inversely proportional to the distance to any form of cover.", "Walking point = sniper bait.", "Your bivouac for the night is the spot where you got tired of marching that day.", "If only one solution can be found for a field problem, then it is usually a stupid solution.", "No battle plan ever survives contact with the enemy.", "The most dangerous thing in the combat zone is an officer with a map.", "The problem with taking the easy way out is that the enemy has already mined it.", "The buddy system is essential to your survival; it gives the enemy somebody else to shoot at.", "If your advance is going well, you are walking into an ambush.", "The quartermaster has only two sizes, too large and too small.", "If you really need an officer in a hurry, take a nap.", "The only time suppressive fire works is when it is used on abandoned positions.", "There is nothing more satisfying that having someone take a shot at you, and miss.", "Don't be conspicuous. In the combat zone, it draws fire. Out of the combat zone, it draws sergeants.", "If see you, so can the enemy.", "All or any of the above combined.", "Avoid loud noises, there are few silent killers in a combat zone.", "Never screw over a buddy; you'll never know when he could save your life.", "Never expect any rations; the only rations that will be on time and won't be short is because the ration is made of shit.", "Respect all religions in a combat zone, take no chances on where you may go if killed.", "A half filled canteens a beacon for a full loaded enemy weapon.", "When in a fire fight, kill as many as you can, the one you miss may not miss tomorrow.", "It is a physical impossibility to carry too much ammo.", "If you survive an ambush, something's wrong.", "Some General last words(as his aides tried to get him to get his head down):What! what! men, dodging this way for single bullets! What will you do when they open fire along the whole line? I am ashamed of you. They couldn't hit an elephant at this dist...", "If you can see the flashes from the enemies' guns in battle, he can see yours too.", "Flashlights, lighters and matches don't just illuminate the surrounding area; they illuminate you too.", "Just because you have nearly impenetrable body armor and a hard - ass Kevlar helmet, doesn't mean you don't have exposed areas.", "There are few times when the enemy can't hear you: When he's dead, you're dead, or both.", "Addendum: When he's not there, when you're not there, or both.", "Never cover a dead body with your own in hopes of looking like you're one of the casualties. Even using his cadaver is a stretch to avoid being shot just in case.", "You're only better than your enemy if you kill him first.", "Complain about the rations all you want, but just remember; they could very well be your last meal.", "Never underestimate the ability of the brass to fuck things up.", "You have two mortal enemies in combat; the opposing side and your own rear services.", "You think the enemy has better artillery support and the enemy thinks yours is better; you're both right.", "Three things you will never see in combat; hot chow, hot showers, and an uninterrupted night's sleep.", "Live and Hero are mutually exclusive terms.", "Don't be a hero", "Once you are in the fight it is way too late to wonder if this is a good idea.", "NEVER get into a fight without more ammunition that the other guy.", "Cover your Buddy, so he can be around to cover for you.", "Decisions made by someone over your head will seldom be in your best interest.", "Sometimes, being good and lucky still is not enough.", "If the rear echelon troops are really happy, the front line troops probably do not have what they need.", "If you are wearing body armor they will probably miss that part.", "Happiness is a belt fed weapon.", "Having all your body parts intact and functioning at the end of the day beats the alternative...", "If you are allergic to lead it is best to avoid a war zone.", "Hot garrison chow is better than hot C - rations which, in turn, are better than cold C - rations, which are better than no food at all. All of these, however, are preferable to cold rice balls even if they do have little pieces of fish in them.", "A free fire zone has nothing to do with economics.", "Medals are OK, but having your body and all your friends in one piece at the end of the day is better.", "Being shot hurts.", "Thousands of Veterans earned medals for bravery every day.A few were even awarded.", "There is only one rule in war: When you win, you get to make up the rules.", "C - 4 can make a dull day fun.", "There is no such thing as a fair fight-- only ones where you win or lose.", "If you win the battle you are entitled to the spoils.If you lose you don't care.", "Nobody cares what you did yesterday or what you are going to do tomorrow.What is important is what you are doing --NOW-- to solve our problem.", "Always make sure someone has a can opener.", "Prayer may not help . . . but it can't hurt.", "Flying is better than walking. Walking is better than running. Running is better than crawling. All of these, however, are better than extraction by a Med - Evac even if it is, technically, a form of flying.", "If everyone does not come home none of the rest of us can ever fully come home either.", "Carrying any weapon that you weren't issued (e.g, an AK) in combat is Not A Good Idea!", "A combat vet will know the sound of an unfamiliar weapon in an instant and will point and shoot.Not only that, AKs use green tracers which mean shoot 'em all and let God sort them out.", "As has been noted, Friendly fire isn't!", "When the going gets tough, the tough go cyclic.", "Military Intelligence is not a contradiction in terms, Light Infantry is!", "Proximity factor: The need for relief is directly related to the distance of the relief station.", "Always keep one bullet in the chamber when changing your magazine.", "In peacetime people say, War is Hell.In combat, under fire from artillery, airplanes, or whatever, a soldier thinks, War is really really really LOUD as Hell!!!.", "If you can think clearly, know exactly what's happening, and have total control of a situation in combat, then you're not in combat.", "When you get the coveted 1, 000 yard stare, don't forget about the enemy who is 30 yards away and about to pop your ass.", "Stay away from officers in combat, they're clever decoys for noncoms.", "If you think you don't need something for your combat load for an OP PLAN, you'll probably wish you had it after the shit hits the fan in combat.", "Hope for the best, but prepare for the worst.", "Failure of plan A will directly affect your ability to carry out plan B.", "If you drop a soldier in the middle of a desert with a rock, a hammer, and an anvil, tell him not to touch any of it, and come back two hours later, the anvil will be broken. Because soldiers gotta fuck with shit.", "War does not determine who is right, war determines who is left.", "Never be first.", "Never be last.", "Never volunteer for anythin", "An escaping soldier can be used again.", "If you think you'll die, don't worry you won't.", "Near death, but still a live ? There is nothing wrong with physics.God doesn't like you.", "It is better to be lucky than good in the battlefield.", "If it's worth fighting for...it's worth fighting dirty for.", "If god wanted boots to be comfortable he would have designed them like running shoes.", "If you survive the extraordinary things, it will often be the little things that will kill you.", "Give an order, then change the order, will get you disorder.", "You never have fire support in heavy firefight but you always have it on a silent recon mission.", "The only thing more dangerous to you than the enemy, is your allies.", "Night vision - isn't", "When you need CAS, they'll be on last weeks radio fill and you won't be able to reach them.", "When you need Apache's, they'll be busy escorting the generals bird around.", "Whatever you have, you won't need; whatever you need, you won't have.", "If it was risky, it worked and no one got hurt: you were brilliant", "If it was risky, it worked and someone got hurt; you were courageous", "If it was risky, it didn't work and no one got hurt; you were lucky", "If it was risky, it didn't work and someone got hurt; you were stupid (and probably dead)", "The best sniper position is always the hardest to reach", "Snakes aren't neutral", "When you need to use the bathroom - the enemy is watching your position", "Never trust a private that says don't worry I learned this is in basic.", "Bring extra rations when you hear the lieutenant is leading the recce patrol.", "Everything you packed for the field is everything you don't need, and everything you need is at your FOB.", "Be prepared to go defensive when your vehicle breaks down until support arrives.", "Your vehicle is a civilian car painted tan, with less security features.", "Helicopter tail rotors are naturally drawn toward trees, stumps, rocks, etc.", "While it may be possible to ward off this event some of the time, it cannot, despite the best efforts of the crew, always be prevented.", "The engine RPM and the rotor RPM must BOTH be kept in the GREEN.", "Failure to heed this commandment can adversely affect the morale of the crew.", "The terms Protective Armor and Helicopter are mutually exclusive.", "Chicken Plates are not something you order in a restaurant.", "The louder the sudden bang in the helicopter, the quicker your eyes will be drawn to the gauges.", "Corollary: The longer you stare at the gauges the less time it takes them to move from green to red.", "Loud, sudden noises in a helicopter WILL get your undivided attention.", "The further you fly into the mountains, the louder the strange engine noises become.", "It is a bad thing to run out of airspeed, altitude and ideas all at the same time.", "Pucker Factor is the formal name of the equation that states the more hairy the situation is, the more of the seat cushion will be sucked up your butt.", "It can be expressed in its mathematical formula of: S (suction) + H(height above ground) + I(interest in staying alive) + T(# of tracers coming your way).Thus the term 'SHIT!' can also be used to denote a situation where a high Pucker Factor is being encountered.", "Running out of pedal, fore or aft cyclic, or collective are all bad ideas.", "Helicopters have been described as nothing more than 50,000 parts flying in close formation.It is the mechanics responsibility to keep that formation as tight as possible.", "It is mathematically impossible for either hummingbirds, or helicopters to fly. Fortunately, neither are aware of this.", "LZ's are always hot.", "There are 'old' pilots and 'bold' pilots, but there are no 'old, bold' pilots.", "Any helicopter pilot story that starts There I was,.... will be either true or false.", "Any of these stories that end with No shit. was neither true nor false.", "The mark of a truly superior pilot is the use of his superior judgment to avoid situations requiring the use of his superior skill", "The last three laws were sent by Brad Lucas, CPT, AV USA Ret, and a 1st Gulf War Vet.", "Ch-53's are living proof, that if you strap enough engines to something it will fly.", "The same gun tube that would probably stay in alignment after lifting a car, will get you beaten after calibration if used to assist in climbing on the tank.", "Tanks draw fire.A lot of it. It does not behoove the infantryman to hide behind one.", "If you're close enough to actually hear an M1 series tank running, while in combat, and not part of the crew, you're too close.", "It never rains in the Marine Corp, it rains on the Marine Corp.", "The enemy is always has the advantage.", "Heat-seeking missiles don't know the difference between friend and foe.", "'Armor' is a fantasy invented by your C.O.to make you feel better.", "Afterburners aren't.", "Air Brakes don't.", "Your cannon will jam in combat, and then when you get back to base there will be nothing wrong with it.", "You may have the better plane, but the enemy is the better pilot. (or vise versa)", "When getting spare parts for your aircraft, you can get them CHEAP - FAST - IN GOOD CONDITION,pick two. (This applies to everything)", "Your radar will not pick up the enemy behind you or the one in the sun.", "If you have got into the sun and are about to ambush the enemy, it will either be a trap or you'll run out of fuel.", "Don't pick a fight with the baddest guys on the block!", "Any attempt to find cover will result in failure.", "Supply Shipments at night stick out like a sore thumb.", "Tanks should never leave the established roads, Established roads are always mined.", "Operations in daytime will cause the lesser equipped army to win.", "The effectiveness of a soldier in desert combat is inversely porportional to how heavy his equipment is.", "Have plenty of water on hand.", "If it makes sense, it is not the Army Way", "If you do, don't even try to run or hide. The pain will be worse.", "The Iraqis always know the area better than you, no matter how many dismounts or convoys you have been on.", "Iraqis always have the advantage of blending in with the crowd.You do not.", "Iraqis are used to the heat and will rarely, if ever, be out during the hottest part of the day.", "Drink more water than you think that you will need.", "Always keep your radio fill up to date.", "Don't piss off the IP's that run the check points, they sometimes allow insurgents to place IED's near their location just to fuck with you.", "Be nice to the Iraqi children, they will soon be either IP's, IA's, or insurgents!", "Always remember: Shoot first and then swear up and down that you saw them pull out a grenade. This always works!!!", "IED's will be placed frequently in the same spots over and over again.", "Always shoot the guy walking down the MSR in the middle of the night carrying a gas can and a shovel. If they can't place the IED's, they can't blow you up!", "Never attribute to an Officer that which is adequately explained by a Private.", "If at first you don't succeed, blame it on the new private!", "If at first you don't succeed, redefine success.", "If, throughout your entire life you have been ruled by Murphy's Law, then at least one thing, usually no more than that, will go so right as to make up for a lifetime of failures.", ]; var length = laws.length; const CONFIG = require('../../config.json'); const COMMANDO = require('discord.js-commando'); var LINQ = require('node-linq').LINQ; class CommandLaw extends COMMANDO.Command { constructor(BOT_COMMANDO) { super(BOT_COMMANDO, //command initializing { name: 'law', group: 'multiple', memberName: 'law', description: 'sends a law of war. User can choose from a current amount of ' + length + ' laws; or just call the command without a number for a random law.', examples: [CONFIG.prefix + 'law', CONFIG.prefix + 'law 8'], args: [ //enter index { key: 'index', prompt: 'Choose a number from 1 to ' + length + ' to select a certian law. or type just the call for a random law', type: 'integer', default: -1 }, ] }); } //run run(message, {index}) { //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.") } //get actuall index index--; //random if (index < 0 || index > length) { //rand var rand = Math.floor(Math.random() * laws.length); var count = rand + 1; //text to send return message.channel.send("The following is a Murphy law of war #" + count + ": " + laws[rand]); } //chosen var count = index + 1; //text to send return message.channel.send("The following is a Murphy law of war #" + count + ": " + laws[index]); } } //return module.exports = CommandLaw;
/* Import express, path, body-parser */ const express = require("express"); const app = express(); const path = require("path"); const bp = require("body-parser"); /* Router Module for handling routing */ const router = express.Router(); app.use("/", router); /* --- Your code goes here --- */ router.use(bp.json()); router.use(bp.urlencoded({ extended: true })); app.get("/", (req, res)=>{ res.type("text/html; charset=utf-8;"); res.status(200).sendFile(path.join(__dirname,'/contact_us.html')); }); app.post("/submit-form", (req, res) =>{ console.log("Accessed Contact Us"); console.log("Form submitted by "+req.body.name); const string = `<h1>Greeting <span style="background-color: #b188f7;"> ${req.body.name}</span></h1> <p>The following message has been received: <span style="background-color: #f5f57d;">${req.body.messages}</span> We will contact you via <span style="background-color: #88c1f7;">${req.body.email}</span></p> `; res.status(200).send(string); }); /* --- ------------------- --- */ /* Server listening */ app.listen(3030, function () { console.log("Server listening at Port 3030"); });
import React, { useCallback, useEffect, useState } from "react"; import { useSelector, useDispatch } from "react-redux"; import { useParams, Link } from "react-router-dom"; import Layout from "./Layout"; import { Grid, Card, Button, Image, Divider, Header, Segment, Popup, } from "semantic-ui-react"; import { ethSelector, ethActions } from "../features/ethSlice"; import ContributeForm from "./ContributeForm"; import UseFundingButton from "./UseFundingButton"; import firebaseFuntions from "../firebase"; import { userSelector } from "../features/userSlice"; function Campaign() { const { address } = useParams(); const dispatch = useDispatch(); const { initialized, web3 } = useSelector(ethSelector.all); const campaignContract = useSelector(ethSelector.campaignContract); const loginUserID = useSelector(userSelector.loginUserID); const [detailedInfos, setDetailedInfos] = useState({ minimumContribution: "", balance: "", requestCounts: "", approveCounts: "", owner: "", createdAt: "", description: "", managerNickname: "", name: "", pictureURL: "", managerID: "", }); useEffect(() => { if (initialized) { dispatch(ethActions.loadCampaignContractRequest({ web3, address })); } return () => { dispatch(ethActions.clearCampaignContract()); }; }, [initialized, address, web3]); useEffect(() => { if (campaignContract) { getSummary(campaignContract); } }, [campaignContract]); // 프로젝트 정보 가져오기 const getSummary = useCallback( async (campaignContract) => { const summary = await campaignContract.methods.getSummary().call(); const { createdAt, description, managerNickname, name, pictureURL, managerID, } = await firebaseFuntions.getProjectDetail(summary[6]); const time = createdAt.toDate(); setDetailedInfos((prev) => ({ ...prev, minimumContribution: web3.utils.fromWei(summary[0]), balance: web3.utils.fromWei(summary[1]), requestCounts: summary[2], approveCounts: summary[3], owner: summary[4], createdAt: time.getFullYear() + "-" + time.getMonth() + "-" + time.getDate(), description, managerNickname, name, pictureURL, managerID, })); }, [web3] ); // Contribute event useEffect(() => { if (campaignContract) { campaignContract.events .Contribute() .on("data", (event) => { setDetailedInfos((prev) => ({ ...prev, balance: web3.utils.fromWei(event.returnValues[0]), approveCounts: event.returnValues[1], })); }) .on("error", (error) => console.error(error)); } }, [campaignContract, address]); const renderCampaignDetails = useCallback( () => ( <Card.Group> <Card centered> <Image src={detailedInfos.pictureURL} wrapped /> </Card> <Card color="red" fluid style={{ overflowWrap: "break-word" }}> <Card.Content> <Card.Header as="h2">{detailedInfos.name}</Card.Header> <Card.Content>{detailedInfos.description}</Card.Content> <Card.Meta textAlign="right"> 생성일: {detailedInfos.createdAt} </Card.Meta> </Card.Content> </Card> <Card color="blue"> <Card.Content> <Popup hoverable content={detailedInfos.owner} trigger={ <Card.Header>{detailedInfos.managerNickname}</Card.Header> } /> <Card.Meta>프로젝트 메니저</Card.Meta> </Card.Content> </Card> <Card color="blue"> <Card.Content> <Card.Header>{detailedInfos.minimumContribution} Ether</Card.Header> <Card.Meta>최소 펀딩금액</Card.Meta> </Card.Content> </Card> <Card color="blue"> <Card.Content> <Link to={`/campaigns/${address}/total-funding`}> <Button color="instagram" size="tiny" floated="right" content="상세보기" /> </Link> <Card.Header>{detailedInfos.balance} Ether</Card.Header> <Card.Meta>모금액</Card.Meta> </Card.Content> </Card> <Card color="blue"> <Card.Content> <Link to={{ pathname: `/campaigns/${address}/usage`, state: { managerAccount: detailedInfos.owner }, }} > <Button size="tiny" color="instagram" floated="right" content="상세보기" /> </Link> <Card.Header>{detailedInfos.requestCounts}</Card.Header> <Card.Meta>펀딩 사용처</Card.Meta> </Card.Content> </Card> <Card color="blue"> <Card.Content> <Card.Header>{detailedInfos.approveCounts} 명</Card.Header> <Card.Meta>참여자</Card.Meta> </Card.Content> </Card> </Card.Group> ), [detailedInfos, address, campaignContract] ); const { Row, Column } = Grid; return ( <Layout> <Segment basic> <Header as="h2">프로젝트 세부사항</Header> </Segment> <Grid divided> <Row> <Column width={11}> {campaignContract ? renderCampaignDetails() : null} </Column> <Column width={5}> <ContributeForm web3={web3} address={address} minimumContribution={detailedInfos.minimumContribution} campaignContract={campaignContract} /> <Divider hidden /> {loginUserID === detailedInfos.managerID && ( <UseFundingButton address={address} managerAccount={detailedInfos.owner} /> )} </Column> </Row> </Grid> </Layout> ); } export default Campaign;
export const FETCH_NOTIFICATIONS_REQUEST = "FETCH_NOTIFICATIONS_REQUEST"; export const FETCH_NOTIFICATIONS_SUCCESS = "FETCH_NOTIFICATIONS_SUCCESS"; export const FETCH_NEW_NOTIFICATIONS_SUCCESS = "FETCH_NEW_NOTIFICATIONS_SUCCESS"; export const READ_ALL_NOTIFICATIONS = "READ_ALL_NOTIFICATIONS"; export const READ_ONE_NOTIFICATION = "READ_ONE_NOTIFICATION"; export const CHECK_NEW_NOTIFICATION = "CHECK_NEW_NOTIFICATION"; export const RESET_HAS_NEW = "RESET_HAS_NEW";
/** * Created by admin on 12/11/2020. */ function checkMod(){ var firstNumber=document.getElementById('firstnumber').value; var secondNumber=document.getElementById('secondnumber').value; var result = parseInt(firstNumber)%parseInt(secondNumber); if (result==0){ document.getElementById('result').innerHTML=('Key qua: '+firstNumber+'&nbsp;'+'chia het cho'+'&nbsp;'+ secondNumber); } else{ document.getElementById('result').innerHTML=('Key qua: '+firstNumber+'&nbsp;'+'KHONG chia het cho'+'&nbsp;'+ secondNumber); } }
$(function() { window.$Qmatic.components.modal.wrapUp = new window.$Qmatic.components.modal.WrapUpModalComponent('#wrap-up-modal') })
function Basket() { Container.call(this, 'basket'); this.countGoods = 0; this.amount = 0; this.basketItems = []; } Basket.prototype = Object.create(Container.prototype); Basket.prototype.constructor = Basket; //Восстановление товаров из cookies Basket.prototype.restoreCookies = function () { if($.cookie('items').length > 0){ this.basketItems = JSON.parse($.cookie('items')); } this.countGoods = parseInt($.cookie('count')); this.amount = parseInt($.cookie('amount')); }; //Обновление товаров в Cookies Basket.prototype.updateCookies = function () { $.removeCookie('items'); $.removeCookie('count'); $.removeCookie('amount'); $.cookie('items', JSON.stringify(this.basketItems)); $.cookie('count', this.countGoods); $.cookie('amount', this.amount); }; //Отрисовка корзины Basket.prototype.render = function (root) { var basketDiv = $('<div />', { id: this.id, text: 'Корзина' }); var basketItemsDiv = $('<div />', { id: this.id + '_items' }); basketItemsDiv.appendTo(basketDiv); basketDiv.appendTo(root); this.collectBasketItems(); }; //Загрузка уже существующих товаров Basket.prototype.collectBasketItems = function () { if ($.cookie('items')) { this.restoreCookies(); this.refresh(); return; } //var self = this; $.get({ url: './basket.json', success: function (data) { this.countGoods = data.basket.length; this.amount = data.amount; for (var index in data.basket) { this.basketItems.push(data.basket[index]); } this.refresh(); }, dataType: 'json', context: this }); }; //Добавление товара в корзину Basket.prototype.add = function (idProduct, quantity, price) { //TODO: Передаем на сервер var basketItem = { "id_product": idProduct, "price": price }; for (var i = 1; i <= quantity; i++) { this.countGoods++; } this.amount += parseInt(price) * parseInt(quantity); this.basketItems.push(basketItem); this.refresh(); }; //Перерисовка корзины Basket.prototype.refresh = function () { if(!$('#basket_data').length) { var appendId = '#' + this.id + '_items'; var basketData = $('<div />', { id: 'basket_data' }); basketData.appendTo(appendId); } var basketDataDiv = $('#basket_data'); basketDataDiv.empty(); basketDataDiv.append('<p>Всего товаров: ' + this.countGoods + '</p>'); basketDataDiv.append('<p>Сумма: ' + this.amount + '</p>'); this.updateCookies(); };
import { ADD_BATTLETAG_SUCCESS, ADD_BATTLETAG_FAILURE, RESET_BATTLETAG_STATE, FETCH_BATTLETAG_SUCCESS, FETCH_BATTLETAG_FAILURE, CREATE_SEASON_SUCCESS, CREATE_SEASON_FAILURE } from '../actions/battletagActions/battletagActionTypes'; const initialState = { success: false, error: null, selected: null, selectedError: null, }; export default function battletagReducer(state = initialState, action) { switch (action.type) { case ADD_BATTLETAG_SUCCESS: return { ...state, success: true }; case ADD_BATTLETAG_FAILURE: return { ...state, success: false }; case FETCH_BATTLETAG_SUCCESS: return { ...state, selected: action.data, } case FETCH_BATTLETAG_FAILURE: return { ...state, selectedError: action.data.error, } case CREATE_SEASON_SUCCESS: return { ...state, selected: action.data.data } case CREATE_SEASON_FAILURE: return { ...state, selectedError: action.data.data } case RESET_BATTLETAG_STATE: return initialState; default: return state; } };
// @flow export const mapsUrl = 'https://www.google.com/maps/';
import * as mixins from "codogo-utility-functions"; import styled from "styled-components"; // -------------------------------------------------- // -------------------------------------------------- const Grid = styled.div` align-items: flex-start; display: flex; flex-direction: column; padding: 3em; flex: 1; ${ mixins.bp.sm.max` flex-basis: 100%; padding: 1em; ` }; `; export { Grid, };
"use strict"; var models = require('../models'); exports.app = function (req, res) { models.Teacher.findOne({ where: { url: req.params.random } }).then(function (data) { if (!data.dataValues) { return res.sendStatus(404).end('<h1>404: NOT FOUND</h1>'); } else { return res.render(__dirname + '/../views/student', { teacher: data.dataValues }); } }); }
import React, { useContext } from 'react'; import Stepper from '@material-ui/core/Stepper'; import Step from '@material-ui/core/Step'; import StepLabel from '@material-ui/core/StepLabel'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; import { DEFAULT_STATE, FormContext } from '../Form/FormStateContext'; const STEPS = ['Personal', 'Address', 'Contactability']; export function HorizontalStepper() { const { formState, setFormState } = useContext(FormContext); const handleReset = () => { setFormState({ method: 'setActiveStep', activeStep: DEFAULT_STATE.activeStep, }); }; return ( <> <Stepper activeStep={formState.activeStep} alternativeLabel> {STEPS.map((label) => ( <Step key={label}> <StepLabel>{label}</StepLabel> </Step> ))} </Stepper> <div> {formState.activeStep === STEPS.length && ( <div> <Typography>All steps completed</Typography> <Button onClick={handleReset}>Reset</Button> </div> )} </div> </> ); }
// class AgePerson { // age = 40; // printAge() { // console.log(this.age); // } // } // class Person extends AgePerson { // name = "Max"; // constructor() { // super(); // this.age = 30; // } // greet() { // console.log(`Hi, I am ${this.name} and I am ${this.age} years old`); // } // } // function Person() { // this.name = "Max"; // this.age = "30"; // this.greet = function() { // console.log(`Hi, I am ${this.name} and I am ${this.age} years old`); // }; // } // Person.describe = function() { // console.log("Creating person"); // }; // Person.describe(); // Person.prototype = { // printAge() { // console.log(this.age); // } // }; // Person.prototype.printAge = function() { // console.log(this.age); // }; // const p = new Person(); // p.greet(); // p.printAge(); // console.dir(p); // console.dir(Person); // console.dir(p); // const p2 = new p.__proto__.constructor(); // console.log(p2); // console.dir(Object); // const p = new Person(); // console.dir(p); const course = { title: "Javascript - The Complete guide", rating: 5 }; Object.setPrototypeOf(course, { ...Object.getPrototypeOf(course), printRating: function() { console.log(`${this.rating}/5`); } }); course.printRating();
import caseGeo3HTML from "./caseGeo3.html"; export const caseGeo3 = { template: caseGeo3HTML };
const Certificates = artifacts.require("Certificates"); contract("Certificates", function (accounts) { //add a new certificate - get the details of the newly added certificate based on image hash //details of certicate should be the same it("add new certificate", async function () { let cert = await Certificates.deployed(); await cert.addCertificate(123, "John", "Blockchain", "7 May 2018", "30 days", "CET", "1 June 2018", "QmSCfVVZ8TCrWKoW5od9nhRC7DceGNM5THWUK6mmnWijj2"); let testCert = await cert.getCertificate("QmSCfVVZ8TCrWKoW5od9nhRC7DceGNM5THWUK6mmnWijj2"); assert.equal(testCert.toString(), "123,John,Blockchain,7 May 2018,30 days,CET,1 June 2018", "did not add cert correctly"); }); //count the number of certificates - count should be 1 it("count certificate", async function () { let cert = await Certificates.deployed(); let num = await cert.countCertificates(); assert.equal(num.toString(), "1", "did not count cert correctly"); }); //verify the certificate based on existing image hash - result should be true it("verify existing certificate", async function () { let cert = await Certificates.deployed(); let verify = await cert.verifyCertificate("QmSCfVVZ8TCrWKoW5od9nhRC7DceGNM5THWUK6mmnWijj2"); assert.equal(verify.toString(), "true", "did not verify cert correctly"); }); //verify the certificate based on non-existing image hash - result should be true it("verify non existing certificate", async function () { let cert = await Certificates.deployed(); let verify = await cert.verifyCertificate("nnSCfVVZ8TCrWKoW5od9nhRC7DceGNM5THWUK6mmnWijj2"); assert.equal(verify.toString(), "false", "did not verify cert correctly"); }); //add the second certificate - of another staff ID //details of certicate should be the same it("add second certificate", async function () { let cert = await Certificates.deployed(); await cert.addCertificate(789, "Lily", "Blockchain", "7 May 2018", "30 days", "CET", "1 June 2018", "QmSCfVVZ8TCrWKoW5od9nhRC7DceGNM5THWUK6mmnWijj4"); let testCert = await cert.getCertificate("QmSCfVVZ8TCrWKoW5od9nhRC7DceGNM5THWUK6mmnWijj4"); assert.equal(testCert.toString(), "789,Lily,Blockchain,7 May 2018,30 days,CET,1 June 2018", "did not add second cert correctly"); }); //count the number of certificates - count should be 2 it("count second certificate", async function () { let cert = await Certificates.deployed(); let num = await cert.countCertificates(); assert.equal(num.toString(), "2", "did not count cert correctly"); }); //count the number of certificates based on staff ID 123 - count should be 1 it("count certificate for staff ID 123", async function () { let cert = await Certificates.deployed(); let holderCount = await cert.countHolderCertificates(123); assert.equal(holderCount.toString(), "1", "did not count holder cert correctly"); }); //get the details of certificates based on staff ID 123 it("get certificate for staff ID 123", async function () { let cert = await Certificates.deployed(); let holderCert = await cert.certHolderToIndex(123, 0); //index 0 - first cert assert.equal(holderCert.toString(), "John,Blockchain,7 May 2018,30 days,1 June 2018,QmSCfVVZ8TCrWKoW5od9nhRC7DceGNM5THWUK6mmnWijj2", "did not get holder cert correctly"); }); //add the third certificate - for the first staff ID 123 //details of certicate should be the same it("add third certificate", async function () { let cert = await Certificates.deployed(); await cert.addCertificate(123, "John", "Java", "7 Sep 2018", "3 days", "CET", "1 Oct 2018", "QmSCfVVZ8TCrWKoW5od9nhRC7DceGNM5THWUK6mmnWijj6"); let testCert = await cert.getCertificate("QmSCfVVZ8TCrWKoW5od9nhRC7DceGNM5THWUK6mmnWijj6"); assert.equal(testCert.toString(), "123,John,Java,7 Sep 2018,3 days,CET,1 Oct 2018", "did not add second cert correctly"); }); //count the number of certificates - count should be 3 it("count third certificate", async function () { let cert = await Certificates.deployed(); let num = await cert.countCertificates(); assert.equal(num.toString(), "3", "did not count cert correctly"); }); //count the number of certificates based on staff ID 123 - count should be 2 it("count certificate for staff ID 123", async function () { let cert = await Certificates.deployed(); let holderCount = await cert.countHolderCertificates(123); assert.equal(holderCount.toString(), "2", "did not count holder cert correctly"); }); //get the details of all certificates based on staff ID 123 - should have 2 certificates it("get all certificates for staff ID 123", async function () { let cert = await Certificates.deployed(); let holderCount = await cert.countHolderCertificates(123); let i = 0; let holderCert = ""; for (i = 0; i < holderCount; i++) { holderCert += await cert.certHolderToIndex(123, i); //index i holderCert += "-"; } assert.equal(holderCert.toString(), "John,Blockchain,7 May 2018,30 days,1 June 2018,QmSCfVVZ8TCrWKoW5od9nhRC7DceGNM5THWUK6mmnWijj2-John,Java,7 Sep 2018,3 days,1 Oct 2018,QmSCfVVZ8TCrWKoW5od9nhRC7DceGNM5THWUK6mmnWijj6-", "did not get holder cert correctly"); }); });
// TJ bot example that uses listen to execute different actions. // This example also uses spotify's API to play a music preview for a given artist. // Since spotify requires a token, we need to generate one first. You will need a spotify account for this. // Access this link: https://developer.spotify.com/console/get-artist/ // Click on "GET TOKEN" and in the POP-UP, select "user-top-read" and click "REQUEST TOKEN". // Spotify will now request for you to login. // Copy the generated token and copy it in the "token" variable bellow. // example: // var token = "BQBJnLEjVzrXTE88upMWK2vRZvEFTgJqqvxHbeEUczu3tJnso2ghBxuvTa_RIG8ibV5iLNdm7K-8iWn1KKtJoR3bqS2hNEdP66C6Qjq0TEFrVM_u-MJ7mGyI4AQiKDZouwcW26NMAS0nNMf1swbnbG9ULJPe"; var token = ""; var tjName = "Johnny"; var tj = new TJBot(["servo", "led", "speaker", "microphone"], { robot: { gender: "male" }, speak: { language: "en-US" } }, { text_to_speech: { apikey: process.env.TEXT_TO_SPEECH_API_KEY }, speech_to_text: { apikey: process.env.SPEECH_TO_TEXT_API_KEY }, assistant: { apikey: process.env.ASSISTANT_API_KEY } }); tj.listen(function (msg) { // check to see if they are talking to TJBot if (msg.startsWith(tjName)) { // remove our name from the message var turn = msg.toLowerCase().replace(tjName.toLowerCase(), ""); if (turn.trim().startsWith("change light to")) { var color = turn.toLowerCase().replace("change light to", "").replace(".", ""); tj.shine(color.trim()) } else if (turn.trim().startsWith("put your arm up")) { tj.raiseArm(); } else if (turn.trim().startsWith("put your arm down")) { tj.lowerArm(); } else if (turn.trim().startsWith("move your arm")) { tj.wave(); } else if (turn.trim().startsWith("play")) { var toSearch = turn.toLowerCase().replace("play", "").replace(".", ""); spotifyPlay(toSearch); } else if (turn.trim().startsWith("stop")) { tj.stopListening(); } else { // send to the conversation service tj.converse(process.env.ASSISTANT_WORKSPACE_ID, turn, function (response) { console.log(response) // speak the result tj.speak(response.description); }); } } }); // spotifyPlay receives an artist name as a search term and plays the preview of the song with the highest popularity. function spotifyPlay(searchTerm) { if (token === "") { console.log("No spotify token was found!") return } $.ajax({ url: "https://api.spotify.com/v1/search", data: { q: searchTerm, type: "track", market: "us", limit: 10 }, beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "Bearer " + token) }, }) .done(function (data) { $.each(data, function (key, value) { var popularity = 0; var preview_url = ""; // get the preview with the highest popularity for (var i = 0; i < data.tracks.items.length; i++) { if (data.tracks.items[i].preview_url != null) { preview_url = data.tracks.items[i].popularity > popularity ? data.tracks.items[i].preview_url : preview_url; popularity = data.tracks.items[i].popularity > popularity ? data.tracks.items[i].popularity : popularity; } } var audio = new Audio(preview_url); audio.type = 'audio/wav'; var playPromise = audio.play(); if (playPromise !== undefined) { playPromise.then(function () { console.log('Playing....'); }).catch(function (error) { console.log('Failed to play....' + error); }); } }) }) .fail(function (jqXHR, textStatus) { console.log("Error searching in spotify"); }) }
import React from 'react'; import {StyleSheet, Text, View, TouchableNativeFeedback} from 'react-native'; import Ionicons from 'react-native-vector-icons/Ionicons'; import Timer from './Timer'; import CircularProgressBar from '../Circular ProgressBar'; const QuizDetails = ({ currentTime, shouldStart, useLife, correctAnswer, lifeUsed, lifeLeft, }) => { return ( <View style={styles.container}> <Ionicons name="md-flag" color="rgba(0,0,0,0.5)" size={28} /> <View style={styles.timer}> <CircularProgressBar shouldStart={shouldStart} duration={5800} color="red"> <Timer currentTime={currentTime} /> </CircularProgressBar> </View> <TouchableNativeFeedback onPress={() => { if (lifeUsed || lifeLeft <= 0) { alert('You have exhausted your chances!'); return; } if (shouldStart) { useLife(correctAnswer, true); } }}> <Ionicons style={styles.life} name="md-heart" color={lifeUsed || lifeLeft <= 0 ? 'rgba(0,0,0,0.5)' : '#ED3544'} size={28} /> </TouchableNativeFeedback> </View> ); }; const styles = StyleSheet.create({ container: { backgroundColor: '#ffffff', alignItems: 'center', justifyContent: 'flex-start', padding: 10, flexDirection: 'row', position: 'absolute', height: 60, bottom: 0, left: 0, right: 0, }, timer: { marginLeft: 'auto', width: 60, height: 60, }, life: { marginLeft: 'auto', }, }); export default QuizDetails;
const $ = jQuery = jquery = require ("jquery") const switchElement = require ("cloudflare/generic/switch") $(document).on ( "cloudflare.ssl_tls.ssl_tls_recommender.initialize", switchElement.initializeCustom ( "enabled", true ) ) $(document).on ( "cloudflare.ssl_tls.ssl_tls_recommender.toggle", switchElement.toggle )
import React from 'react'; import { AppRegistry, StyleSheet, Text, View, Image, Button, ScrollView, TextInput, KeyboardAvoidingView, Picker, TouchableOpacity, Dimensions, } from 'react-native'; import {connect} from 'react-redux'; import {bindActionCreators } from 'redux'; import navigateTo from '../../../actions/NavigationAction'; import { Container, Content, Form, Item, Input } from 'native-base'; import uStyles from '../../../styles'; import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; const {height,width}=Dimensions.get('window'); class SystemAdminPublisherMenu extends React.Component{ constructor(){ super(); } static navigationOptions = ({ navigation }) => ({ headerTitle:'Publisher Menu', drawerLabel: 'Publisher', headerStyle: { backgroundColor: '#0D47A1'}, drawerIcon:()=>( <Icon name="newspaper" size={25} color="#fff" /> ), headerRight:( <TouchableOpacity onPress={() => navigation.navigate('DrawerOpen')} style={uStyles.hambergerMenu}> <Icon name="menu" size={30} color="#fff" /> </TouchableOpacity> ) }); render(){ return( <ScrollView style={[uStyles.mainView,localStyles.mainView]} keyboardShouldPersistTaps="always"> <View style={[uStyles.container,localStyles.container]}> <View style={uStyles.row}> <View style={uStyles.buttonContainer}> <View style={uStyles.buttonSubContainer}> <TouchableOpacity style={uStyles.dashBoardbutton} onPress={()=>this.props.navigateTo('createPublisher')}> <Text style={uStyles.dashBoardButtonText}>Create Publisher</Text> </TouchableOpacity> </View> </View> <View style={uStyles.buttonContainer}> <View style={uStyles.buttonSubContainer}> <TouchableOpacity style={uStyles.dashBoardbutton} onPress={()=>this.props.navigateTo('viewPulisher')}> <Text style={uStyles.dashBoardButtonText}>View Publishers</Text> </TouchableOpacity> </View> </View> </View> </View> </ScrollView> ) } } const localStyles=StyleSheet.create({ mainView:{ backgroundColor:'#fff' }, container:{ }, logoContainer:{ }, textInput:{ } }); function mapStateToProps(state) { return { } } function mapDispatchToProps(dispatch) { return bindActionCreators( { navigateTo:navigateTo },dispatch) } export default connect(mapStateToProps,mapDispatchToProps)(SystemAdminPublisherMenu)
"use strict"; const Path = require("path"); const fs = require("fs"); const archetype = require("./config/archetype"); const gulpHelper = archetype.devRequire("electrode-gulp-helper"); const shell = gulpHelper.shell; const mkdirp = archetype.devRequire("mkdirp"); const config = archetype.config; function setupPath() { const nmBin = "node_modules/.bin"; gulpHelper.envPath.addToFront(Path.resolve(nmBin)); gulpHelper.envPath.addToFront(Path.join(archetype.devPath, nmBin)); gulpHelper.envPath.addToFront(Path.join(__dirname, nmBin)); } function setProductionEnv() { process.env.NODE_ENV = "production"; } function setStaticFilesEnv() { process.env.STATIC_FILES = "true"; } function setWebpackDev() { process.env.WEBPACK_DEV = "true"; } function setOptimizeStats() { process.env.OPTIMIZE_STATS = "true"; } const exec = gulpHelper.exec; function checkFrontendCov(minimum) { if (typeof minimum === "string") { minimum += "."; } else { minimum = ""; } return exec(`istanbul check-coverage 'coverage/client/*/coverage.json' --config=${config.istanbul}/.istanbul.${minimum}yml`); } function checkFileExists(path) { /** * fs.accessSync is a synchronous version of fs.access(). * fs.accessSync() throws if any accessibility checks fail, and does nothing otherwise. * * https://nodejs.org/api/fs.html#fs_fs_accesssync_path_mode */ try { fs.accessSync(path, fs.F_OK); return true; } catch (e) { return false; } } function createElectrodeTmpDir() { const eTmp = Path.resolve(".etmp"); const eTmpGitIgnore = Path.join(eTmp, ".gitignore"); if (!checkFileExists(eTmpGitIgnore)) { mkdirp.sync(eTmp); fs.writeFileSync(eTmpGitIgnore, "# Electrode tmp dir\n*\n"); } } /** * [generateServiceWorker gulp task to generate service worker code that will precache specific resources so they work offline.] * */ function generateServiceWorker() { const NODE_ENV = process.env.NODE_ENV; const serviceWorkerExists = checkFileExists("./service-worker.js"); const serviceWorkerConfigExists = checkFileExists("config/sw-precache-config.json"); /** * Determines whether the fetch event handler is included in the generated service worker code, * by default value is set to true for development builds set the value to false * * https://github.com/GoogleChrome/sw-precache#handlefetch-boolean * */ const cacheRequestFetch = (NODE_ENV !== "production" ? "--no-handle-fetch" : ""); if (serviceWorkerConfigExists) { // generate-service-worker return exec(`sw-precache --config=config/sw-precache-config.json --verbose ${cacheRequestFetch}`); } else if (serviceWorkerExists && !serviceWorkerConfigExists) { // this is the case when service-worker exists from the previous build but service-worker-config // does not exist/deleted on purpose for future builds return shell.rm("-rf", "./service-worker.js"); } else { // default case return false; } } /* * * For information on how to specify a task, see: * * https://www.npmjs.com/package/electrode-gulp-helper#taskdata * */ const tasks = { ".production-env": () => setProductionEnv(), ".static-files-env": () => setStaticFilesEnv(), ".webpack-dev": () => setWebpackDev(), ".optimize-stats": () => setOptimizeStats(), "build": { desc: "Build your app's client bundle for production", task: ["build-dist"] }, "build-analyze": { dep: [".optimize-stats"], desc: "Build your app's client bundle for production and run bundle analyzer", task: ["build-dist", "optimize-stats"] }, ".build-browser-coverage-1": () => { setProductionEnv(); return exec(`webpack --config ${config.webpack}/webpack.config.browsercoverage.js --colors`); }, "build-browser-coverage": { desc: "Build browser coverage", task: ["clean-dist", ".build-browser-coverage-1", "build-dist:flatten-l10n", "build-dist:clean-tmp"] }, "build-dev-static": { desc: "Build static copy of your app's client bundle for development", task: ["clean-dist", "build-dist-dev-static"] }, "build-dist": ["clean-dist", "build-dist-min", "build-dist:flatten-l10n", "generate-service-worker", "build-dist:clean-tmp"], "build-dist-dev-static": { desc: false, task: `webpack --config ${config.webpack}/webpack.config.dev.static.js --colors` }, "electrify": ["clean-dist", "build-webpack-stats-with-fullpath", "build-dist:clean-tmp", "run-electrify-cli"], "build-webpack-stats-with-fullpath": { desc: "Build static bundle with stats.json containing fullPaths to inspect the bundle on electrode-electrify", task: `webpack --config ${config.webpack}/webpack.config.stats.electrify.js --colors` }, "build-dist-min": { dep: [".production-env"], desc: false, task: `webpack --config ${config.webpack}/webpack.config.js --colors` }, "build-dist:clean-tmp": { desc: false, task: () => shell.rm("-rf", "./tmp") }, "build-dist:flatten-l10n": { desc: false, task: `node ${__dirname}/scripts/l10n/flatten-messages.js` }, "run-electrify-cli": { desc: false, task: `electrify dist/server/stats.json -O` }, "check": ["lint", "test-cov"], "check-ci": ["lint", "test-ci"], "check-cov": ["lint", "test-cov"], "check-dev": ["lint", "test-dev"], "clean": ["clean-dist"], "clean-dist": () => shell.rm("-rf", "dist"), "cov-frontend": () => checkFrontendCov(), "cov-frontend-50": () => checkFrontendCov("50"), "cov-frontend-70": () => checkFrontendCov("70"), "cov-frontend-85": () => checkFrontendCov("85"), "cov-frontend-95": () => checkFrontendCov("95"), "debug": ["build-dev-static", "server-debug"], "dev": { desc: "Start server with watch in development mode with webpack-dev-server", task: [".webpack-dev", ["server-dev", "server-watch", "generate-service-worker"]] }, "dev-static": { desc: "Start server in development mode with statically built files", task: ["build-dev-static", "server"] }, "hot": { desc: "Start server with watch in hot mode with webpack-dev-server", task: [".webpack-dev", ["server-hot", "server-watch", "generate-service-worker"]] }, "generate-service-worker": { desc: "Generate Service Worker using the options provided in the app/config/sw-precache-config.json file for prod/dev/hot mode", task: () => generateServiceWorker() }, "lint": [["lint-client", "lint-client-test", "lint-server", "lint-server-test"]], "lint-client": `eslint --ext .js,.jsx -c ${config.eslint}/.eslintrc-react client templates`, "lint-client-test": `eslint --ext .js,.jsx -c ${config.eslint}/.eslintrc-react-test test/client`, "lint-server": `eslint -c ${config.eslint}/.eslintrc-node server`, "lint-server-test": `eslint -c ${config.eslint}/.eslintrc-mocha-test test/server test/func`, "optimize-stats": { desc: "Generate a list of all files that went into production bundle JS (results in .etmp)", task: `analyze-bundle -b dist/js/bundle.*.js -s dist/server/stats.json` }, "npm:test": ["check"], "npm:release": `node ${__dirname}/scripts/map-isomorphic-cdn.js`, "server": { desc: "Start the app server only, Must have dist by running `gulp build` first.", task: `node server/index.js` }, "server-prod": { dep: [".production-env", ".static-files-env"], desc: "Start server in production mode with static files routes. Must have dist by running `gulp build`.", task: `node server/index.js` }, "server-debug": `node debug server/index.js`, ".init-bundle.valid.log": () => fs.writeFileSync(Path.resolve(".etmp/bundle.valid.log"), `${Date.now()}`), "server-watch": { dep: [".init-bundle.valid.log"], task: `nodemon -C --ext js,jsx,json,yaml --watch .etmp/bundle.valid.log --watch server --watch config server/index.js --exec node` }, "server-dev": { desc: "Start server in dev mode with webpack-dev-server", task: `webpack-dev-server --config ${config.webpack}/webpack.config.dev.js --progress --colors --port ${archetype.webpack.devPort}` }, "server-hot": { desc: "Start server in hot mode with webpack-dev-server", task: `webpack-dev-server --config ${config.webpack}/webpack.config.hot.js --hot --progress --colors --port ${archetype.webpack.devPort} --inline` }, "server-test": { desc: "Start server in test mode with webpack-dev-server", task: `webpack-dev-server --config ${config.webpack}/webpack.config.test.js --progress --colors --port ${archetype.webpack.testPort}` }, "test-ci": ["test-frontend-ci"], "test-cov": ["test-frontend-cov", "test-server-cov"], "test-dev": ["test-frontend-dev", "test-server-dev"], "test-watch": () => exec(`pgrep -fl 'webpack-dev-server.*${archetype.webpack.testPort}`) .then(() => exec(`gulp test-frontend-dev-watch`)) .catch(() => exec(`gulp test-watch-all`)), "test-watch-all": ["server-test", "test-frontend-dev-watch"], "test-frontend": `karma start ${config.karma}/karma.conf.js --colors`, "test-frontend-ci": `karma start --browsers PhantomJS,Firefox ${config.karma}/karma.conf.coverage.js --colors`, "test-frontend-cov": `karma start ${config.karma}/karma.conf.coverage.js --colors`, "test-frontend-dev": () => exec(`pgrep -fl 'webpack-dev-server.*${archetype.webpack.testPort}'`) .then(() => exec(`karma start ${config.karma}/karma.conf.dev.js --colors`)) .catch(() => exec(`gulp test-frontend`)), "test-frontend-dev-watch": `karma start ${config.karma}/karma.conf.watch.js --colors --browsers Chrome --no-single-run --auto-watch`, "test-server": () => [["lint-server", "lint-server-test"], "test-server-cov"], "test-server-cov": () => shell.test("-d", "test/server") && exec(`istanbul cover _mocha -- -c --opts ${config.mocha}/mocha.opts test/server`), "test-server-dev": () => shell.test("-d", "test/server") && exec(`mocha -c --opts ${config.mocha}/mocha.opts test/server`) }; module.exports = function (gulp) { setupPath(); createElectrodeTmpDir(); gulpHelper.loadTasks(tasks, gulp || require("gulp")); };
export default class Drip extends Phaser.Sprite { constructor(game, x = 320, rotation = 0, xSpeed, frame) { super(game, x, 20, 'cuberdonDrip', frame); this.game = game; this.xSpeed = xSpeed; this.angle += rotation; this.mask = game.add.graphics(0, 0); this.mask.beginFill(0xff0000); this.mask.drawRect(100, 210, 400, 250); this.dripIsClicked = false; this.inputEnabled = true; this.input.useHandCursor = true; } update() { this.events.onInputDown.add(this.spriteIsClicked, this); if(this.game.input.mousePointer.isUp){ this.spriteClickReleased(); } if (this.dripIsClicked) { let mouseDifference = this.game.input.mousePointer.y - this.previousY; this.updatePreviousYValue(); this.y += mouseDifference; this.x += mouseDifference * this.xSpeed; } if (this.y > 1) { this.y += 1; this.x += this.xSpeed; } if (this.y > 200) { //this.gameOver(); } } gameOver(){ this.game.state.start('Intro'); } spriteIsClicked(){ this.dripIsClicked = true; this.previousY = this.game.input.mousePointer.y; } spriteClickReleased(){ this.dripIsClicked = false; } updatePreviousYValue(){ this.previousY = this.game.input.mousePointer.y; } }
/** * 获取数据, url:文件地址, callback:成功调用方法, * variableName:json数据变量名称,默认tmp_www_szmb_gov_cn; */ var getJSON = function(url, callback, variableName) { if (url.indexOf("http") != 0) { url = DATA_PATH + url; } var re = new RegExp("\\?"); if (re.test(url)) { url = url + "&random=" + Math.random(); } else { url = url + "?random=" + Math.random(); } if (typeof variableName == 'undefined' || variableName == '') { // 默认 variableName = "tmp_www_szmb_gov_cn"; } jQuery.getScript(url, function(response, status) { if (status == 'success' && typeof eval(variableName) != 'undefined' && eval(variableName) != null) { callback(eval(variableName)); eval(variableName + "=null;"); } else { callback(null); } }); }; var createScript = function(src,callback,tag,arg){ var oScript = document.createElement('script'); oScript.setAttribute('type','text/javascript'); oScript.src = src; if(typeof tag != 'undefined' && tag!='') oScript.setAttribute('tag',tag); oScript[document.all?"onreadystatechange":"onload"]=function(){ if(typeof arg=='undefined'){ var arg=false; } if(typeof callback=='function'){ callback(arg); } } document.getElementsByTagName('head')[0].appendChild(oScript); }; var getText = function(url, callback) { var re = new RegExp("\\?"); if (re.test(url)) { url = url + "&random=" + Math.random(); } else { url = url + "?random=" + Math.random(); } $.ajax({ url : url, dataType : 'text', type : 'GET', async : false, timeout : 5000, error : function(e) { callback(null); }, success : function(data) { callback(data); } }); }; /** * * @param str * yyyy-MM-dd hh:mm:ss * @returns {Date} */ function strToDate(str) { var year = parseInt(str.substr(0, 4)); var month = parseInt(str.substr(5, 2)) - 1; var day = parseInt(str.substr(8, 2)); var hour = parseInt(str.substr(11, 2)); var minute = parseInt(str.substr(14, 2)); var s = parseInt(str.substr(17, 2)); var date = new Date(year, month, day, hour, minute, s); return date; } /** * 日期的格式化输出 * * @param format * [必需] 要输出的格式类型如 "yyyy-MM-dd hh:mm:ss" */ Date.prototype.format = function(format) { var o = { "M+" : this.getMonth() + 1, // month "d+" : this.getDate(), // day "h+" : this.getHours(), // hour "m+" : this.getMinutes(), // minute "s+" : this.getSeconds(), // second "q+" : Math.floor((this.getMonth() + 3) / 3), // quarter "S" : this.getMilliseconds() // millisecond }; if (/(y+)/.test(format)) { format = format.replace(RegExp.$1, (this.getFullYear() + "") .substr(4 - RegExp.$1.length)); } for ( var k in o) { if (new RegExp("(" + k + ")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); } } return format; }; function formatDate (d, format) { if(typeof d == 'undefined' || format == 'undefined')return; var o = { "M+" : d.getMonth() + 1, // month "d+" : d.getDate(), // day "h+" : d.getHours(), // hour "m+" : d.getMinutes(), // minute "s+" : d.getSeconds(), // second "q+" : Math.floor((d.getMonth() + 3) / 3), // quarter "S" : d.getMilliseconds() // millisecond }; if (/(y+)/.test(format)) { format = format.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length)); } for (var k in o) { if (new RegExp("(" + k + ")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); } } return format; }; /** * 将String类型的日期(如:"yyyy-MM-dd hh:mm:ss" )格式化为指定的中文日期字符串 * * @param d * String [必需] 指定的日期 * @param format * String [必需] 要输出的格式类型如 "ymdhiw" * @param addDay * Number [可选] 要增加的是天数或小时 * @param t * String [可选] 决定要增加的是天还是小时 */ function formatDateStr2CH(d, format, addDay, t) { if (typeof d == 'undefined') return; if (typeof t == 'undefined' || t == 'day') addDay = (typeof addDay != 'undefined') ? 86400 * addDay * 1000 : 0; else if (t == 'hour') { addDay = (typeof addDay != 'undefined') ? 3600 * addDay * 1000 : 0; } else { return; } var arr = d.split('-'); if (typeof arr[3] != 'undefined' && arr[3].indexOf(':') > 0) { var arrH = arr[3].split(':'); var time = parseInt(Date.parse(arr[0] + '/' + arr[1] + '/' + arr[2] + " " + arrH[0] + ':' + arrH[1])) + addDay; } else { var time = parseInt(Date.parse(arr[0] + '/' + arr[1] + '/' + arr[2])) + addDay; } var d = new Date(); d.setTime(time); if (typeof format == 'undefined') return (d.getMonth() + 1) + '月' + d.getDate() + '日'; var s = ''; format = format.toLowerCase(); if (format.indexOf('y') >= 0) s = (d.getFullYear()) + '年'; if (format.indexOf('m') >= 0) s += (d.getMonth() + 1) + '月'; if (format.indexOf('d') >= 0) s += d.getDate() + '日'; if (format.indexOf('h') >= 0) s += (d.getHours()) + '时'; if (format.indexOf('i') >= 0) s += (d.getMinutes()) + '分'; if (format.indexOf('w') >= 0) { var week = [ '星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六' ]; s += ' ' + week[d.getDay()]; } return s; } function _w_table_rowspan(_w_table_id, _w_table_colnum) { $(_w_table_id).each(function() { _w_table_firsttd = ""; _w_table_currenttd = ""; _w_table_SpanNum = 0; _w_table_Obj = $("tr td:nth-child(" + _w_table_colnum + ")", this); _w_table_Obj.each(function(i) { if (i == 0) { _w_table_firsttd = $(this); _w_table_SpanNum = 1; } else { _w_table_currenttd = $(this); if (_w_table_firsttd.text() == _w_table_currenttd.text()) { _w_table_SpanNum++; _w_table_currenttd.hide(); // remove(); _w_table_firsttd.attr("rowSpan", _w_table_SpanNum); } else { _w_table_firsttd = $(this); _w_table_SpanNum = 1; } } }); }); } function _w_table_colspan(_w_table_id, _w_table_rownum, _w_table_maxcolnum) { $(_w_table_id) .each( function() { if (_w_table_maxcolnum == void 0) { _w_table_maxcolnum = 0; } _w_table_firsttd = ""; _w_table_currenttd = ""; _w_table_SpanNum = 0; $(" tr:nth-child(" + _w_table_rownum + ")", this) .each( function(i) { _w_table_Obj = $(this).children(); _w_table_Obj .each(function(i) { if (i == 0) { _w_table_firsttd = $(this); _w_table_SpanNum = 1; } else if ((_w_table_maxcolnum > 0) && (i > _w_table_maxcolnum)) { return ""; } else { _w_table_currenttd = $(this); if (_w_table_firsttd .text() == _w_table_currenttd .text()) { _w_table_SpanNum++; _w_table_currenttd .hide(); // remove(); _w_table_firsttd .attr( "colSpan", _w_table_SpanNum); } else { _w_table_firsttd = $(this); _w_table_SpanNum = 1; } } }); }); }); } /** * Vanwins JavaScript Library v1.0 * @company: Vanwins * @date 2013/1/25 */ /* 扩展内置对象的方法 start */ /** * 日期的格式化输出 * * @param format * [必需] 要输出的格式类型如 "yyyy-MM-dd hh:mm:ss" */ Date.prototype.format = function(format) { var o = { "M+" : this.getMonth() + 1, // month "d+" : this.getDate(), // day "h+" : this.getHours(), // hour "m+" : this.getMinutes(), // minute "s+" : this.getSeconds(), // second "q+" : Math.floor((this.getMonth() + 3) / 3), // quarter "S" : this.getMilliseconds() // millisecond }; if (/(y+)/.test(format)) { format = format.replace(RegExp.$1, (this.getFullYear() + "") .substr(4 - RegExp.$1.length)); } for ( var k in o) { if (new RegExp("(" + k + ")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); } } return format; }; /* 扩展内置对象的方法 end */ // /////////////////////////// /* vanwins Namespace start */ (function() { if (!window.vanwins) { window['vanwins'] = {}; window['vanwins']['net'] = {}; window['vanwins']['view'] = {}; window['vanwins']['util'] = {}; } /* vanwins.net Namespace start */ /** * 查询url参数 * * @param name * [必需] 要查询的参数名称 */ vanwins.net.getQueryString = function(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var test = "helllo"; var r = window.location.search.substr(1).match(reg); if (r != null) { return unescape(r[2]); } return null; }; /** * 从服务器文件中获取字符窜或解析数据 * * @param name * String [必需] 文件路径 * @param type * String [必需] 数据类型:json , text * @param name * Function [必需] 要查询的参数名称 * @return 获取失败将返回 null 成功怎根据参数type的值返回String或json对象 */ vanwins.net.getDataFromServerFile = function(urlpath, type, callback) { if (typeof callback != 'function') { return; } var re = new RegExp("\\?"); if (re.test(urlpath)) { urlpath = urlpath + "&random=" + Math.random(); } else { urlpath = urlpath + "?random=" + Math.random(); } $.ajax({ url : urlpath, dataType : 'text', type : 'GET', async : false, timeout : 5000, error : function(e) { callback(null); }, success : function(data) { if (type == "json") { eval("tempval = " + (data == "" ? "''" : data)); callback(tempval); } else if (type == "text") { callback(data); } } }); }; /** * 存取cookies值 */ vanwins.net.cookies = { // 设置cookie set : function(name, value, time, path, domain) { var expires = ""; if (time) { var date = new Date(); date.setTime(date.getTime() + time * 1000); expires = "; expires=" + date.toGMTString(); } if (!path) path = "/"; if (domain) { document.cookie = name + "=" + value + expires + "; path=" + path + "; domain=" + domain + ";"; } else { document.cookie = name + "=" + value + expires + "; path=" + path + ";"; } }, // 取得cookie值 get : function(name) { var name = name + "="; var cookies = document.cookie.split(";"); for ( var i = 0; i < cookies.length; i++) { var c = cookies[i]; while (c.charAt(0) == " ") c = c.substring(1, c.length); if (c.indexOf(name) == 0) return c.substring(name.length, c.length); } return null; } }; /* vanwins.net Namespace end */ /* vanwins.view Namespace start */ /** * 根据iframe的内容设置iframe的高度 该函数的常规调用方式为绑定iframe元素的onload事件, * 当iframe页面内容包含异步加载时,该函数的常规调用方式并不能保证获取正确的高度。 * 在iframe页面异加载操作完成的代码后面显式调用该函数能获取正确的高度。 */ vanwins.view.setCwinHeight = function(obj) { var cwin = obj; if (document.getElementById) { if (cwin && !window.opera) { if (cwin.contentDocument && cwin.contentDocument.body.offsetHeight) cwin.height = cwin.contentDocument.body.offsetHeight + 10; // FF // NS else if (cwin.Document && cwin.Document.body.scrollHeight) cwin.height = cwin.Document.body.scrollHeight; // IE } else { if (cwin.contentWindow.document && cwin.contentWindow.document.body.scrollHeight) cwin.height = cwin.contentWindow.document.body.scrollHeight + 10; // Opera } } }; /** * 加载一个js数据文件 * * @param src * String [必需] 文件路径 * @param callback * Function [可选] 文件加载完成后的回调函数 * @param tag * String [可选] 标签的tag属性 * @param arg * Object [可选] 回调函数需要的参数 */ vanwins.view.createScript = function(src, callback, tag, arg) { var oScript = document.createElement('script'); oScript.setAttribute('type', 'text/javascript'); oScript.src = src; if (typeof tag != 'undefined' && tag != '') oScript.setAttribute('tag', tag); oScript[document.all ? "onreadystatechange" : "onload"] = function() { //if (typeof arg == 'undefined') { // var arg = false; //} if (typeof callback == 'function') { callback(arg); } } document.getElementsByTagName('head')[0].appendChild(oScript); }; /** * 不使用浏览器缓存,重新加载一个js数据文件 * * @param src * String [必需] 文件路径 * @param callback * Function [可选] 文件加载完成后的回调函数 * @param tag * String [可选] 标签的tag属性 * @param arg * Object [可选] 回调函数需要的参数 */ vanwins.view.createScriptNoCache = function(src, callback, tag, arg) { var oScript = document.createElement('script'); oScript.setAttribute('type', 'text/javascript'); var re = new RegExp("\\?"); if (re.test(src)) { oScript.src = src + "&random=" + Math.random(); } else { oScript.src = src + "?random=" + Math.random(); } if (typeof tag != 'undefined' && tag != '') oScript.setAttribute('tag', tag); oScript[document.all ? "onreadystatechange" : "onload"] = function() { if (typeof arg == 'undefined') { var arg = false; } if (typeof callback == 'function') { callback(arg); } } document.getElementsByTagName('head')[0].appendChild(oScript); }; /* vanwins.util Namespace end */ })(); /* vanwins Namespace end */ // ///////////////////////// // /////////////////////////// /* szmb Namespace start */ (function() { if (!window.szmb) { window['szmb'] = {}; } szmb.getWindLevel = function(l, renum) { if (typeof l == 'undefined') return; if (l <= 0.3) return renum == true ? 0 : '小于3级'; else if (l <= 1.6) return renum == true ? 1 : '小于3级'; else if (l <= 3.4) return renum == true ? 2 : '小于3级'; else if (l <= 5.4) return renum == true ? 3 : '3级'; else if (l <= 7.9) return renum == true ? 4 : '4级'; else if (l <= 10.7) return renum == true ? 5 : '5级'; else if (l <= 13.8) return renum == true ? 6 : '6级'; else if (l <= 17.1) return renum == true ? 7 : '7级'; else if (l <= 20.7) return renum == true ? 8 : '8级'; else if (l <= 24.4) return renum == true ? 9 : '9级'; else if (l <= 28.4) return renum == true ? 10 : '10级'; else if (l <= 32.6) return renum == true ? 11 : '11级'; else if (l > 32.6) return renum == true ? 12 : '12级'; } /** * 判断是否使用夏季温度标准,每年11月到3月监控低温 */ szmb.isSummer = function() { var month = (new Date()).getMonth(); if (month >= 10 || month < 2) { return false; } return true; } /** * 初始化决策网顶部区域选择select */ szmb.initMyRegionForTop = function() { var userfenqu; if (typeof MESIS_USER_AREA != 'undefined') { userfenqu = MESIS_USER_AREA; } if (userfenqu == null || userfenqu == "" || typeof userfenqu == 'undefined') { userfenqu = vanwins.net.cookies.get('fenquyubaouserlikeregion'); } else if (document.cookie != "") { vanwins.net.cookies.set('fenquyubaouserlikeregion', userfenqu, 3600000); } if (userfenqu == null || userfenqu == "" || typeof userfenqu == 'undefined') { userfenqu = 'ft'; } var temp = $("#MyRegionForTop option[value='" + userfenqu + "']").attr( "selected"); if (typeof temp == 'undefined' || temp == false) { $("#MyRegionForTop option[value='" + userfenqu + "']").attr( "selected", true); } } /* 设置区域 ,用于网站顶部 */ szmb.SetMyRegionForTop = function(fenquPinyin, fenquZh) { if (document.cookie == "") { alert("您的浏览器禁用了cookie,请启用您的cookie功能。"); return; } if (MESIS_USER_AREA_CN == null || typeof MESIS_USER_AREA_CN == 'undefined') { var currentCookie = vanwins.net.cookies .get('fenquyubaouserlikeregion'); vanwins.net.cookies.set('fenquyubaouserlikeregion', fenquPinyin, 3600000); alert("设置成功! \n 您的默认分区为:" + fenquZh); } else { alert("部门信息设置的区域为 " + MESIS_USER_AREA_CN + "\n\n请进入决策用户中心修改您的所在区域"); szmb.initMyRegionForTop(); } }; })(); /* szmb Namespace end */ // ///////////////////////// /* global function start */ /** * 加载一个js数据文件, 不建议直接使用该函数名称。 为与老系统兼容,声明此全局函数名称,该函数的功能由 * vanwins.view.createScript(src,callback,tag,arg) 实现。 为避免命名冲突请使用 * vanwins.view.createScript(src,callback,tag,arg) 调用 * * @param src * String [必需] 文件路径 * @param callback * Function [可选] 文件加载完成后的回调函数 * @param tag * String [可选] 标签的tag属性 * @param arg * Object [可选] 回调函数需要的参数 */ var createScript = vanwins.view.createScript; /** * 不使用浏览器缓存,重新加载一个js数据文件 为与老系统兼容,声明此全局函数名称,该函数的功能由 * vanwins.view.createScriptNoCache(src,callback,tag,arg) 实现。 为避免命名冲突请使用 * vanwins.view.createScriptNoCache(src,callback,tag,arg) 调用 * * @param src * String [必需] 文件路径 * @param callback * Function [可选] 文件加载完成后的回调函数 * @param tag * String [可选] 标签的tag属性 * @param arg * Object [可选] 回调函数需要的参数 */ var createScriptNoCache = vanwins.view.createScriptNoCache; /** * 根据iframe的内容设置iframe的高度 为与老系统兼容,声明此全局函数名称,该函数的功能由 * vanwins.view.setCwinHeight(obj) 实现。 为避免命名冲突请使用 * vanwins.view.setCwinHeight(obj) 调用 该函数的常规调用方式为绑定iframe元素的onload事件, * 当iframe页面内容包含异步加载时,该函数的常规调用方式并不能保证获取正确的高度。 * 在iframe页面异加载操作完成的代码后面显式调用该函数能获取正确的高度。 */ var SetCwinHeight = vanwins.view.setCwinHeight; /** * 将String类型的日期(如:"yyyy-MM-dd hh:mm:ss" )格式化为指定的中文日期字符串 * 为与老系统兼容,声明此全局函数名称,该函数的功能由 vanwins.util.formatDateStr2CH(d,format,addDay,t) * 实现。 为避免命名冲突请使用 vanwins.util.formatDateStr2CH(d,format,addDay,t) 调用 * * @param d * String [必需] 指定的日期 * @param format * String [必需] 要输出的格式类型如 "ymdhiw" * @param addDay * Number [可选] 要增加的是天数或小时 * @param t * String [可选] 决定要增加的是天还是小时 */ /* global function end */
import Card from "../Card"; export default function Secretarias(props) { return ( <> <h2 className="text-center text-3xl text-gray-700 font-bold mt-8 mb-2"> {props.title} </h2> <hr /> {props.secretaria && props.secretaria.sort((a, b) => a.ordem + b.ordem).map((props) => ( <div key={props.id}> <Card src={props.imagem.url} alt={props.alt} cargo={props.cargo} nome={props.nome} email={props.email} description={props.biografia} /> </div> ))} </> ) }
var messageService = angular.module('messageService', []); messageService.factory('Message', function($rootScope) { return { send : function(array) { $rootScope.$broadcast('msg', array); }, ask : function(array, success) { $rootScope.$broadcast('ask', [array,success]); }, input : function(array, success) { $rootScope.$broadcast('input', [array, success]); } } });
// Compiled by ClojureScript 0.0-3211 {:optimize-constants true, :static-fns true} goog.provide('tetris.core'); goog.require('cljs.core'); goog.require('tetris.board'); goog.require('reagent.core'); tetris.core.GRAVITY_WAIT = (400); tetris.core.ADJUST_WAIT = (300); cljs.core.enable_console_print_BANG_(); tetris.core.appstate = reagent.core.atom.cljs$core$IFn$_invoke$arity$1(new cljs.core.PersistentArrayMap(null, 4, [cljs.core.constant$keyword$piece,null,cljs.core.constant$keyword$cells,cljs.core.PersistentVector.EMPTY,cljs.core.constant$keyword$active,true,cljs.core.constant$keyword$score,(0)], null)); tetris.core.current_piece = reagent.ratom.make_reaction((function (){ return cljs.core.constant$keyword$piece.cljs$core$IFn$_invoke$arity$1((function (){var G__10344 = tetris.core.appstate; return (cljs.core.deref.cljs$core$IFn$_invoke$arity$1 ? cljs.core.deref.cljs$core$IFn$_invoke$arity$1(G__10344) : cljs.core.deref.call(null,G__10344)); })()); })); tetris.core.current_cells = reagent.ratom.make_reaction((function (){ return cljs.core.constant$keyword$cells.cljs$core$IFn$_invoke$arity$1((function (){var G__10345 = tetris.core.appstate; return (cljs.core.deref.cljs$core$IFn$_invoke$arity$1 ? cljs.core.deref.cljs$core$IFn$_invoke$arity$1(G__10345) : cljs.core.deref.call(null,G__10345)); })()); })); tetris.core.current_score = reagent.ratom.make_reaction((function (){ return cljs.core.constant$keyword$score.cljs$core$IFn$_invoke$arity$1((function (){var G__10346 = tetris.core.appstate; return (cljs.core.deref.cljs$core$IFn$_invoke$arity$1 ? cljs.core.deref.cljs$core$IFn$_invoke$arity$1(G__10346) : cljs.core.deref.call(null,G__10346)); })()); })); tetris.core.gravitate = (function tetris$core$gravitate(p__10347){ var map__10351 = p__10347; var map__10351__$1 = ((cljs.core.seq_QMARK_(map__10351))?cljs.core.apply.cljs$core$IFn$_invoke$arity$2(cljs.core.hash_map,map__10351):map__10351); var data = map__10351__$1; var cells = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__10351__$1,cljs.core.constant$keyword$cells); var piece = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__10351__$1,cljs.core.constant$keyword$piece); if(cljs.core.truth_(piece)){ var piece2 = cljs.core.update_in.cljs$core$IFn$_invoke$arity$3(piece,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.constant$keyword$y], null),cljs.core.inc); if(cljs.core.truth_(tetris.board.valid_QMARK_(piece2,cells))){ return cljs.core.assoc.cljs$core$IFn$_invoke$arity$3(data,cljs.core.constant$keyword$piece,piece2); } else { var G__10352_10354 = ((function (piece2,map__10351,map__10351__$1,data,cells,piece){ return (function (){ return cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$2(tetris.core.appstate,tetris.board.remove_piece); });})(piece2,map__10351,map__10351__$1,data,cells,piece)) ; var G__10353_10355 = tetris.core.ADJUST_WAIT; setTimeout(G__10352_10354,G__10353_10355); return data; } } else { var piece2 = tetris.board.new_piece(); if(cljs.core.truth_(tetris.board.valid_QMARK_(piece2,cells))){ return cljs.core.assoc.cljs$core$IFn$_invoke$arity$3(data,cljs.core.constant$keyword$piece,piece2); } else { return cljs.core.assoc.cljs$core$IFn$_invoke$arity$3(data,cljs.core.constant$keyword$active,false); } } }); tetris.core.cell_view = (function tetris$core$cell_view(p__10356){ var map__10358 = p__10356; var map__10358__$1 = ((cljs.core.seq_QMARK_(map__10358))?cljs.core.apply.cljs$core$IFn$_invoke$arity$2(cljs.core.hash_map,map__10358):map__10358); var color = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__10358__$1,cljs.core.constant$keyword$color); var y = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__10358__$1,cljs.core.constant$keyword$y); var x = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__10358__$1,cljs.core.constant$keyword$x); return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.constant$keyword$rect,new cljs.core.PersistentArrayMap(null, 8, [cljs.core.constant$keyword$x,x,cljs.core.constant$keyword$y,y,cljs.core.constant$keyword$width,(1),cljs.core.constant$keyword$height,(1),cljs.core.constant$keyword$stroke,"black",cljs.core.constant$keyword$stroke_DASH_width,0.01,cljs.core.constant$keyword$rx,0.1,cljs.core.constant$keyword$fill,color], null)], null); }); tetris.core.piece_view = (function tetris$core$piece_view(){ return (function (){ return cljs.core.into.cljs$core$IFn$_invoke$arity$2(new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.constant$keyword$g], null),cljs.core.map.cljs$core$IFn$_invoke$arity$2(tetris.core.cell_view,tetris.board.piece__GT_cells((function (){var G__10360 = tetris.core.current_piece; return (cljs.core.deref.cljs$core$IFn$_invoke$arity$1 ? cljs.core.deref.cljs$core$IFn$_invoke$arity$1(G__10360) : cljs.core.deref.call(null,G__10360)); })()))); }); }); tetris.core.cells_view = (function tetris$core$cells_view(){ return cljs.core.into.cljs$core$IFn$_invoke$arity$2(new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.constant$keyword$g], null),cljs.core.map.cljs$core$IFn$_invoke$arity$2(tetris.core.cell_view,(function (){var G__10362 = tetris.core.current_cells; return (cljs.core.deref.cljs$core$IFn$_invoke$arity$1 ? cljs.core.deref.cljs$core$IFn$_invoke$arity$1(G__10362) : cljs.core.deref.call(null,G__10362)); })())); }); tetris.core.board = (function tetris$core$board(){ return new cljs.core.PersistentVector(null, 4, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.constant$keyword$svg,new cljs.core.PersistentArrayMap(null, 2, [cljs.core.constant$keyword$style,new cljs.core.PersistentArrayMap(null, 3, [cljs.core.constant$keyword$border,"1px solid black",cljs.core.constant$keyword$width,((25) * tetris.board.boardW),cljs.core.constant$keyword$height,((25) * tetris.board.boardH)], null),cljs.core.constant$keyword$view_DASH_box,[cljs.core.str("0 0 "),cljs.core.str(tetris.board.boardW),cljs.core.str(" "),cljs.core.str(tetris.board.boardH)].join('')], null),new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [tetris.core.piece_view], null),new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [tetris.core.cells_view], null)], null); }); tetris.core.score_panel = (function tetris$core$score_panel(){ return (function (){ return new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.constant$keyword$h2,"Score ",(function (){var G__10364 = tetris.core.current_score; return (cljs.core.deref.cljs$core$IFn$_invoke$arity$1 ? cljs.core.deref.cljs$core$IFn$_invoke$arity$1(G__10364) : cljs.core.deref.call(null,G__10364)); })()], null); }); }); tetris.core.page = (function tetris$core$page(){ return new cljs.core.PersistentVector(null, 4, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.constant$keyword$div,new cljs.core.PersistentArrayMap(null, 1, [cljs.core.constant$keyword$style,new cljs.core.PersistentArrayMap(null, 1, [cljs.core.constant$keyword$text_DASH_align,"center"], null)], null),new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [tetris.core.board], null),new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [tetris.core.score_panel], null)], null); }); tetris.core.maybe = (function tetris$core$maybe(appstate,f){ var piece = (function (){var G__10366 = appstate; return (f.cljs$core$IFn$_invoke$arity$1 ? f.cljs$core$IFn$_invoke$arity$1(G__10366) : f.call(null,G__10366)); })(); if(cljs.core.truth_(tetris.board.valid_QMARK_(piece,cljs.core.constant$keyword$cells.cljs$core$IFn$_invoke$arity$1(appstate)))){ return cljs.core.assoc.cljs$core$IFn$_invoke$arity$3(appstate,cljs.core.constant$keyword$piece,piece); } else { return appstate; } }); tetris.core.key_action = new cljs.core.PersistentArrayMap(null, 4, [(37),tetris.board.move_left,(38),tetris.board.move_rotate,(39),tetris.board.move_right,(40),tetris.board.move_down], null); tetris.core.handle_keydown = (function tetris$core$handle_keydown(event){ tetris.core.event = event; if(cljs.core.truth_((function (){var and__4323__auto__ = cljs.core.constant$keyword$active.cljs$core$IFn$_invoke$arity$1((function (){var G__10372 = tetris.core.appstate; return (cljs.core.deref.cljs$core$IFn$_invoke$arity$1 ? cljs.core.deref.cljs$core$IFn$_invoke$arity$1(G__10372) : cljs.core.deref.call(null,G__10372)); })()); if(cljs.core.truth_(and__4323__auto__)){ return cljs.core.constant$keyword$piece.cljs$core$IFn$_invoke$arity$1((function (){var G__10373 = tetris.core.appstate; return (cljs.core.deref.cljs$core$IFn$_invoke$arity$1 ? cljs.core.deref.cljs$core$IFn$_invoke$arity$1(G__10373) : cljs.core.deref.call(null,G__10373)); })()); } else { return and__4323__auto__; } })())){ var temp__4126__auto__ = (function (){var G__10374 = event.keyCode; return (tetris.core.key_action.cljs$core$IFn$_invoke$arity$1 ? tetris.core.key_action.cljs$core$IFn$_invoke$arity$1(G__10374) : tetris.core.key_action.call(null,G__10374)); })(); if(cljs.core.truth_(temp__4126__auto__)){ var f = temp__4126__auto__; event.preventDefault(); return cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$3(tetris.core.appstate,tetris.core.maybe,f); } else { return null; } } else { return null; } }); var G__10375_10377 = (function (){ return cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$2(tetris.core.appstate,tetris.core.gravitate); }); var G__10376_10378 = tetris.core.GRAVITY_WAIT; setInterval(G__10375_10377,G__10376_10378); document.addEventListener("keydown",tetris.core.handle_keydown); tetris.core.main = (function tetris$core$main(){ return reagent.core.render.cljs$core$IFn$_invoke$arity$2(new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [tetris.core.page], null),document.getElementById("app")); }); goog.exportSymbol('tetris.core.main', tetris.core.main);
import React from 'react'; const Item = (props) =>{ return ( <div className="item"> <div className="left"> <ItemImage/> <div className="imageDescription"> <ItemTitle title={props.title}/> <ItemDescription description={props.description}/> </div> </div> <div className="right"> <ItemPrice price={props.price}/> {props.children} </div> </div> ); } const ItemImage = () =>{ return ( <div className="itemImage"> </div> ); } const ItemTitle = (props) =>{ return( <p className="itemTitle">{props.title}</p> ); } const ItemDescription = (props) =>{ return( <p className="itemDescription">{props.description}</p> ); } const ItemPrice = (props) =>{ return ( <span className="itemPrice">${props.price}</span> ); } export default (Item);
(function($, Drupal, drupalSettings) { $(document).ready(function() { $('.block h2').click(function() { $(this).parent().find('.content').toggle(); }); }); })(jQuery, Drupal, drupalSettings);
// ====================== // = Calcul de vecteurs = // ====================== var K = 250; function Vector( deltaX, deltaY ) { this.x = deltaX; this.y = deltaY; } Vector.prototype = { x: 0, y: 0, opposite: function() { return new Vector( -this.x, -this.y ); }, add: function( v ) { return new Vector( this.x + v.x, this.y + v.y ); }, substract: function( v ) { var neg = v.opposite(); return this.add( neg ); }, multiply: function( a ) { return new Vector( this.x * a, this.y * a ); }, norm: function() { return Math.sqrt( (this.x * this.x) + (this.y * this.y) ); }, normalize: function() { var n = this.norm(); if( n > 0 ) return new Vector( this.x / n, this.y / n ); else return new Vector( 0,0 ); } }; // ======================= // = Point = // ======================= function Point( x, y ) { this.x = x; this.y = y; } Point.prototype = { vectorTo: function( point ) { return new Vector( point.x - this.x, point.y - this.y ); } } // ======================= // = GraphNode = // ======================= function Node( x, y, spring ) { Point.call( this, x, y ); this.spring = spring; this.direction = new Vector(0,0); this.speed = new Vector( 0, 0 ); } Node.prototype = new Point; // Fonction de répulsion. Node.prototype.repulse = function( node, coef ) { coef = coef || 1; var distance = node.vectorTo(this); var dist = distance.norm(); dist = dist > K ? 0 : dist; if( dist > 0 ) { var strength = -dist * (( Math.cos( dist / K * Math.PI ) + 1) ); node.direction = node.direction.add( distance.normalize().multiply( strength *coef ) ); } return node.direction; } Node.prototype.attract = function() { var distance = this.spring; var dist = distance.norm(); this.direction = this.direction.substract( distance.normalize().multiply( (dist*dist) / K ) ); return this.direction; } // ======================================= // = Node Set. Nodes couramment affichés = // ======================================= function NodeSet() { this.index = 0; } NodeSet.prototype = new Array; NodeSet.prototype.ratataPlop = function(me) { if( me == undefined ) me = this; // setTimeOut assigne l'objet "window" à "this", donc on sauve "this" ailleurs. if( me.index == me.length ) me.attractionRepulsion(); else me[me.index].plop(); if( me.index < me.length ) { me.index += 1; setTimeout( function(){ me.ratataPlop(me) }, 100 ); // delayed recursivity. Love that. } } NodeSet.prototype.attractionRepulsion = function( me ) { if( me == undefined ) me = this; // setTimeOut assigne l'objet "window" à "this", donc on sauve "this" ailleurs. if( this.temperature == undefined ) this.temperature = 5; var nodes = new Array(me.length); var origins = new Array(me.length); for( var i = 0; i< me.length; i++) { nodes[i] = nodes[i] || me[i].getNode(); for( var j = 0; j < me.length; j++ ) { if( i != j ) { // histoire de ne pas masquer les points. origins[j] = origins[j] || me[j].getNodeOrigin(); origins[j].repulse(nodes[i], 0.2); nodes[j] = nodes[j] || me[j].getNode(); nodes[j].repulse(nodes[i]); // les positions géo des spots repoussent les bulles qui ne leur appartiennent pas. } } nodes[i].attract(); } for( var i = me.length-1; i >=0; i-=2 ) { // } for( var i = 0; i < me.length; i ++ ) me[i].applyForce( nodes[i].direction.multiply( 0.25 ) ); if( this.temperature > 0 ) { this.temperature -= 0.035; } else { this.temperature = 0; } setTimeout( function(){ me.attractionRepulsion(me) }, 40 ); }
import Ember from 'ember'; export function timeSlice(params) { var body = params[0]; return body.toString().substring(0,10); } export default Ember.Helper.helper(timeSlice); // date.toString().substring(16, 24);
const express = require('express'); const router = express.Router(); const models = require('../../../../../models'); const ResponseTemplate = require("../../../../ResponseTemplate"); const errors = require("../../../../errors"); const SimpleValidators = require("../../../../../util/SimpleValidators"); const JalaliDate = require("../../../../../util/JalaliDate"); const TypeChecker = require("../../../../../util/TypeChecker"); const JalaliTime = require("../../../../../util/JalaliTime"); const {asyncFunctionWrapper} = require("../../../util"); router.get('/all', asyncFunctionWrapper(getAllMessages)); router.get('/outgoing', asyncFunctionWrapper(getOutgoingMessages)); router.get('/incoming', asyncFunctionWrapper(getIncomingMessages)); router.get('/incoming/:messageId', asyncFunctionWrapper(getSingleIncomingMessageData)); router.post('/outgoing', asyncFunctionWrapper(sendMessage)); async function getAllMessages(req, res, next) { const patientQuery = SimpleValidators.hasValue(req.query.patientUserId) ? {patientUserId: req.query.patientUserId} : {}; const outgoing = (await models.PhysicianToPatientMessage .findAll({where: {physicianUserId: req.principal.userId, ...patientQuery}})) .map(message => message.getApiObject()); const incoming = (await models.PatientToPhysicianMessage .findAll({where: {physicianUserId: req.principal.userId, ...patientQuery}})) .map(message => message.getApiObject()); const response = ResponseTemplate.create() .withData({ outgoing, incoming }) .toJson(); res.json(response); } async function getOutgoingMessages(req, res, next) { const patientQuery = SimpleValidators.isNumber(req.query.patientUserId || null) ? {patientUserId: req.query.patientUserId} : {}; let messages = await models.PhysicianToPatientMessage.findAll({ where: { physicianUserId: req.principal.userId, ...patientQuery }, include: [ 'patientInfo', ] }); messages = messages.map(message => message.getApiObject()); sortMessageListByDateDESC(messages); const response = ResponseTemplate.create() .withData({ messages: messages, }); res.json(response); } async function getSingleIncomingMessageData(req, res, next) { const messageId = req.params.messageId; let message = await models.PatientToPhysicianMessage.findOne({ where: { id: messageId, physicianUserId: req.principal.userId, }, include: [ 'patientInfo', ] }); if (message == null) { next(new errors.NotFound("Message was not found")); return; } const lastVisitPromise = models.Visit.getLastVisitOfPatient(message.patientUserId); const lastWarfarinDosagePromise = models.WarfarinDosageRecord.getLast7DosageRecordsForPatient(message.patientUserId); let [lastVisit, lastWarfarinDosage] = await Promise.all([lastVisitPromise, lastWarfarinDosagePromise]); const response = ResponseTemplate.create() .withData({ message: message.getApiObject(), lastVisit: lastVisit.getApiObject(), lastWarfarinDosage: lastWarfarinDosage, }) .toJson(); res.json(response); } async function getIncomingMessages(req, res, next) { const patientQuery = SimpleValidators.isNumber(req.query.patientUserId || null) ? {patientUserId: req.query.patientUserId} : {}; let messages = await models.PatientToPhysicianMessage.findAll({ where: { physicianUserId: req.principal.userId, ...patientQuery, }, include: [ 'patientInfo', ] }); sortMessageListByDateDESC(messages); messages = messages.map(message => message.getApiObject()); if (req.query.onlyNew == 'true') { let outgoingMessages = await models.PhysicianToPatientMessage.findAll({ where: { physicianUserId: req.principal.userId, }, }); sortMessageListByDateDESC(outgoingMessages); messages = filterNewIncomingMessages(messages, outgoingMessages); } else if (req.query.groupByNew == 'true') { let outgoingMessages = await models.PhysicianToPatientMessage.findAll({ where: { physicianUserId: req.principal.userId, }, }); sortMessageListByDateDESC(outgoingMessages); messages = groupMessagesByNewOrPrevious(messages, outgoingMessages); } const response = ResponseTemplate.create() .withData({ messages: messages, }) .toJson(); res.json(response); } async function sendMessage(req, res, next) { const messageToAdd = req.body.message; const patientUserId = req.query.patientUserId; if (!TypeChecker.isObject(messageToAdd)) { next(new errors.IncompleteRequest("Message info was not provided.")); return; } if (!SimpleValidators.isNonEmptyString(patientUserId)) { next(new errors.QueryParameterMissing("Missing or invalid query parameter {patientUserId}")); return; } messageToAdd.patientUserId = patientUserId; messageToAdd.physicianUserId = req.principal.userId; messageToAdd.messageDate = JalaliDate.now().toJson().jalali.asString; messageToAdd.messageTime = JalaliTime.now().toJson().asObject; await models.Visit.sequelize.transaction(async (tr) => { if (SimpleValidators.hasValue(messageToAdd.nextVisitDate || null)) { const jDate = JalaliDate.create(messageToAdd.nextVisitDate); const dateAsString = jDate.toJson().jalali.asString; messageToAdd.visitDate = dateAsString; if (jDate.isValidDate()) { const appointmentToAdd = { patientUserId: patientUserId, approximateVisitDate: dateAsString, } var insertedAppointment = await models.VisitAppointment.create(appointmentToAdd, {transaction: tr}); } } const insertedDosageRecords = await models.WarfarinDosageRecord.insertPrescriptionRecords(messageToAdd.prescription, patientUserId, new Date(), tr); const insertedMessage = await models.PhysicianToPatientMessage.create(messageToAdd, {}); const response = ResponseTemplate.create() .withData({ message: insertedMessage.getApiObject(), appointment: insertedAppointment || null, prescription: insertedDosageRecords || null, }) .toJson(); res.json(response); }) } function sortMessageListByDateDESC(messages) { messages.sort((m1, m2) => compareTwoMessageDates(m2, m1)) } function filterNewIncomingMessages(incoming, outgoing) { return incoming.filter((incomingMessage) => { const latestOutgoingForPatient = outgoing.find(item => item.patientUserId == incomingMessage.patientUserId) || null; if (latestOutgoingForPatient == null) return false; return compareTwoMessageDates(incomingMessage, latestOutgoingForPatient) > 0; }) } function groupMessagesByNewOrPrevious(incoming, outgoing) { const groupedMessages = { new: [], previous: [], } incoming.forEach((incomingMessage) => { const latestOutgoingForPatient = outgoing.find(item => item.patientUserId == incomingMessage.patientUserId) || null; const isNew = !latestOutgoingForPatient || (compareTwoMessageDates(incomingMessage, latestOutgoingForPatient) > 0); if (isNew) groupedMessages.new.push(incomingMessage); else groupedMessages.previous.push(incomingMessage); }); return groupedMessages; } function compareTwoMessageDates(m1, m2) { const m1Date = JalaliDate.create(m1.messageDate); const m2Date = JalaliDate.create(m2.messageDate); const dateCmp = m1Date.compareWithJalaliDate(m2Date) || 0; const m1Time = JalaliTime.ofSerializedJalaliTime(m1.messageTime); const m2Time = JalaliTime.ofSerializedJalaliTime(m2.messageTime); const timeCmp = m1Time.compareWithJalaliTime(m2Time) || 0; return dateCmp !== 0 ? dateCmp : timeCmp; } module.exports = router;
import test from 'ava'; import isPlainObject from 'lodash/isPlainObject'; import sinon from 'sinon'; import fs from 'fs'; import path from 'path'; import * as utils from 'src/transform/utils'; test.todo('applyCssModules'); test.todo('generateTransformedStylesFile'); test.todo('getPrefixedCss'); test.todo('getRenderedCss'); test('if resolveUrlPath maps the url correctly', (t) => { const unchangedReference = 'foo'; const pathedReference = '~foo'; const unchangedResult = utils.resolveUrlPath(unchangedReference); t.is(unchangedResult, unchangedReference); const pathedResult = utils.resolveUrlPath(pathedReference); t.is(pathedResult, path.join(__dirname, '..', '..', 'node_modules', 'ava', 'lib', 'node_modules', 'foo')); }); test.serial('if saveFile will trigger the writing of the file with the correct value', (t) => { const hash = 'foo'; const id = `${hash}_Scoped_Styles`; const target = 'bar.css'; const injectableSource = '._foo__bar{display:block}'; const exportTokens = { bar: '_foo__bar' }; const expectedBufferString = `module.exports = {'css':'${injectableSource}', 'id':'${id}', 'selectors':{'bar':'${exportTokens.bar}'}};\n`; const stub = sinon.stub(fs, 'writeFileSync', (passedTarget, buffer) => { t.is(passedTarget, target); t.is(buffer.toString('utf8'), expectedBufferString); }); const saveFileFunction = utils.saveFile(hash, target); const result = saveFileFunction({ exportTokens, injectableSource }); t.true(isPlainObject(result)); stub.restore(); });
const request = require('request-promise'); const cheerio = require('cheerio'); const fs = require('fs-extra'); const writeStream = fs.createWriteStream('quotes.json'); var writeJson = require('write-json'); /* async function init2() { // async const data = []; try { // const response = await request('http://quotes.toscrape.com/'); const $ = await request({ uri: 'https://www.gob.cl/coronavirus/pasoapaso#documentos/', transform: body => cheerio.load(body) }); writeStream.write('Quote|Author|Tags\n'); const tags = []; $('.card').each((i, el) => { const text = $(el).find('h5 .card-title').text() .replace(/(^\“|\”$)/g, ""); const author = $(el).find('a').text(); const doc = $(el).find('a').html(); const tag = $(el).find('.tags a').html(); tags.push(tag); const feed = { text: text, pdf: doc, autor: author, field2: tag, }; data.push(feed); console.log("kipa") console.log("dattaa", data) }) writeJson('foo.json', { data }, function (err) { console.log("erro") }); console.log(data) } catch (e) { console.log(e); } } */ async function init() { // async const data = []; try { // const response = await request('http://quotes.toscrape.com/'); const $ = await request({ uri: 'https://www.bcn.cl/publicaciones/ediciones-bcn', transform: body => cheerio.load(body) }); writeStream.write('Quote|Author|Tags\n'); //const tags = []; $('.informes').each((i, el) => { const text = $(el).find('h3').text().replace(/(^\“|\”$)/g, ""); const author = $(el).find('p').text(); //const doc = $(el).find('a').html(); //const tag = $(el).find('.tags a').html(); //tags.push(tag); console.log('text', text) console.log('auth', author) const feed = { text: text, //pdf: doc, autor: author, /* field2: tag, */ }; data.push(feed); console.log("dattaa", data) }) writeJson('foo.json', { data }, function (err) { console.log("erro") }); console.log(data) } catch (e) { console.log(e); } } init();
var expect = require('expect') describe('lib', function(){ var Lib, ContextTree before(function(){ Lib = require('../lib') ContextTree = require('../lib/context-tree') }) describe('applyPatches', function(){ describe('just these operations', function(){ it('should add', function(){ var state = {one: 1} Lib.applyPatches(state, Lib.add(['two'], 2)) expect(state).toEqual({ one: 1, two: 2 }) }) it('should add with a root', function(){ var state = {one: 1} Lib.applyPatches(state, Lib.add(['two'], 2)) expect(state).toEqual({ one: 1, two: 2 }) }) }) describe.skip('need to migrate these tests', function(){ it.skip('should NOT add, deep', function(){ var state = {one: 1} state = expect(function(){ Lib.applyPatches(state, Lib.add(['middle', 'deep'], {yay: true})) }).toThrow() }) it('should replace', function(){ var state = {one: 1} state = Lib.applyPatches(state, Lib.replace(['one'], {yay: true})) expect(state.toJS()).toEqual({ one: {yay: true} }) }) it('should remove', function(){ var state = makeState.set({one: 1, deep: {two: 2}}) state = Lib.applyFreezerPatch(state, Lib.remove(['deep', 'two'])) expect(state.toJS()).toEqual({ one: 1, deep: {} }) }) it('should not hold onto pivot, if remove path does not exist', function(){ // Remove var state = makeState.set({one: 1, deep: {two: 2, deeper: {three: 3}}}) state = Lib.applyFreezerPatch(state, Lib.remove(['deep', 'deeper', 'four'])) expect(state.toJS()).toEqual(state.toJS()) state = Lib.applyFreezerPatch(state, Lib.add(['deep', 'deeper', 'four'], 4)) expect(state.toJS()).toEqual({one: 1, deep: {two: 2, deeper: {three: 3, four: 4}}}) }) it('should merge, shallow', function(){ var state = makeState.set({one: 1, deep: {two: 2}}) state = Lib.applyFreezerPatch(state, Lib.merge(['deep'], {three: 3, four: 4})) expect(state.toJS()).toEqual({ one: 1, deep: { two: 2, three: 3, four: 4 } }) }) it('should merge into arrays', function(){ var state = makeState.set({ arr: [ { one: 1 } ] }) state = Lib.applyFreezerPatch(state, Lib.merge(['arr', 0], {two: 2, three: 3})) expect(state.toJS()).toEqual({ arr: [ { one:1, two: 2, three: 3} ] }) }) it('can merge with root', function(){ var state = makeState state = Lib.applyFreezerPatch(state, Lib.merge([], {three: 3})) expect(state.toJS()).toEqual({ three: 3 }) }) }) }) describe('lib/context-tree', function(){ it('should set and get a deep value', function(){ var tree = ContextTree() tree.set(['one', 'two'], {one: 1}) var res = tree.get(['one', 'two']) expect(res.one).toEqual(1) }) it('should set/get the root value', function(){ var tree = ContextTree() tree.set([], {one: 1}) var res = tree.get([]) expect(res.one).toEqual(1) }) it('should set/get parent value without changing the children', function(){ var tree = ContextTree() tree.set(['one'], {one: 1}) tree.set(['one', 'two'], {two: 2}) expect(tree.get(['one']).one).toEqual(1) expect(tree.get(['one', 'two']).two).toEqual(2) tree.set(['one'], {alsoOne: 1}) expect(tree.get(['one']).alsoOne).toEqual(1) expect(tree.get(['one', 'two']).two).toEqual(2) }) it('should not override the root parent', function(){ var tree = ContextTree() tree.set(['one', 'two'], {two: 2}) tree.set([], {root: 'rooty'}) expect(tree.get(['one', 'two']).two).toEqual(2) expect(tree.get([]).root).toEqual('rooty') expect(tree.get(['one', 'two']).root).toEqual('rooty') }) it('should allow setting the root from contructor and get without arg, returns root', function(){ var tree = ContextTree({two: 2}) var res = tree.get() expect(res).toEqual({two: 2}) }) it('should get the nearest path', function(){ var tree = ContextTree() tree.set(['one', 'two'], {two: 2}) expect(tree.get(['one', 'two', 'three', 'four']).two).toEqual(2) }) it('should return a value that inherits from the parents', function(){ var tree = ContextTree() tree.set(['one'], {one: 1}) tree.set(['one', 'two'], {two: 2}) tree.set(['one', 'two', 'three'], {three: 3}) var res = tree.get(['one', 'two', 'three']) expect(res.one).toEqual(1) expect(res.two).toEqual(2) expect(res.three).toEqual(3) }) }) describe('parentPathMatch', function(){ it('should match an exact path', function(){ expect(Lib.parentPathMatch( ['one', 'two'], ['one', 'two'] )).toEqual(true) }) it('should NOT match a child path', function(){ expect(Lib.parentPathMatch( ['one', 'two'], ['one', 'two', 'three'] )).toEqual(false) }) it('should match a parent path', function(){ expect(Lib.parentPathMatch( ['one', 'two'], ['one'] )).toEqual(true) }) }) })
module.exports = [ { fieldName: 'Left', type: 'integer', explanationDetails: 'One of the players in the match up', required: true, }, { fieldName: 'Right', type: 'integer', explanationDetails: 'Another one of the players in the match up', required: true, }, { fieldName: 'Winner', type: 'integer', explanationDetails: 'The winner of the match up', }, { fieldName: 'Match Up Number', type: 'integer', explanationDetails: 'The unique match number for the pool play portion of a given event', }, { fieldName: 'Event ID', type: 'integer', explanationDetails: 'The unique ID number for the event', required: true, }, { fieldName: 'Type', type: 'string', explanationDetails: 'The type of game this is: Pool or Bracket.', }, { fieldName: 'Secondary Identifier', type: 'string', explanationDetails: 'A combination of eventId, the type of game, the match up number, the player id, and the opponent id', required: true, }, ];
$(document.forms['updateUser']).on('submit', function() { var form = $(this); $('.error', form).html(''); $(":submit", form).button("loading"); $.ajax({ url: "/settings/profile", method: "POST", data: form.serialize(), complete: function() { $(":submit", form).button("reset"); console.log(); }, statusCode: { 200: function() { var msg = '<div class="alert alert-dismissable alert-success">'+ '<button type="button" class="close" data-dismiss="alert">×</button>'+ '<strong>Well done!</strong> Info has been successfully updated!</a>'+ '</div>'; $('.notification').html(msg); }, 403: function(jqXHR) { var error = JSON.parse(jqXHR.responseText); $('.error', form).html(error.message); } } }); return false; });
import React from "react"; import { connect } from "react-redux"; import { withStyles } from "@material-ui/core"; import PropTypes from "prop-types"; import { Button, MuiThemeProvider, Drawer } from "@material-ui/core"; const Filter = withStyles(theme => ({ root: { backgroundColor: "#d8d8d8", borderRadius: "3px", opacity: "0.52", width: "115px", height: "36px", marginLeft: "7px", marginRight: "7px", color: "#37404b", }, }))(Button); function FilterButton(props) { const rightPanel = props.rightPanel; function handleDrawerToggle() { if (!props.filter.panelOpen) { } props.showFilterPanel(); } let leftSidebar = { show: true, mode: 'full', // full, close, compact, mobile, } return ( <MuiThemeProvider theme={leftSidebar}> <Filter variant="contained" onClick={handleDrawerToggle} > Filter <img src="/assets/images/people/filter.svg" alt="filter"/> </Filter> <Drawer width={"100px"} // container={container} variant="temporary" anchor={"right"} open={props.filter.panelOpen} onClose={handleDrawerToggle} ModalProps={{ keepMounted: true }} > {rightPanel} </Drawer> </MuiThemeProvider> ); } const mapStateToProps = state => ({ filter: state.filter, showFilterPanel: PropTypes.func.isRequired, }); export default withStyles({}, { withTheme: true })(connect( mapStateToProps, { } )(FilterButton));
ROOT = process.cwd(); HELPERS = require(ROOT + '/helpers/general.js'); log = HELPERS.log; var config = require(ROOT + '/config.json'); var mongoose = require('mongoose'); var ObjectId = mongoose.Schema.ObjectId; var locationSchema = mongoose.Schema({ name: { type: String, required: true, unique: true}, owner: { type: String, ref: "clubs", required: true}, about: { type: String} }); locationSchema.methods.toJson = function(){ var locationObject = this.toObject(); var response = { name: locationObject.name ? locationObject.name : null, owner: locationObject.owner ? locationObject.owner : null, about: locationObject.about ? locationObject.about : null }; return response; } module.exports = mongoose.model('locations', locationSchema);
var BookModel = Backbone.Model.extend({ idAttribute: 'id', urlRoot: function() { return "/api/books/"; }, initialize: function() { console.log("Hello, my CID is " +this.cid + " and my ID is " + this.id); }, updateAuthor: function(name) { this.set("author", name); }, defaults: { author: "", title: "", counter: 0 } });
/** * 下拉菜单效果 * @author: xiaweiwei * @date: 2013-12-3 14:12 * 1.配置url,存放div内容的文件,可以存放多个div * 2.配置splitstr,即div内容文件中,每个div之间的分隔符,默认为<br> * 3.配置遮罩层背景色,透明度需要在jquery_ui_pop.css的ui-widget-overlay中修改 * 4.关闭弹出框的代码为 $("#divPOP").dialog("close") * 5.按钮触发事件配置,请参考$("#btnPOP")的click事件 * 6.参考页面为divPOPtest.html,需要引用的jquery相应css和js * 7.引用loaddiv.js时的参数No为对应要加载的div序号(参考url对应的文件的注释)页面有多个时用逗号分隔 */ var url = "assets/js/mods/overlay/div.html"; var splitstr = "<br>"; var scriptid = "loaddiv";//引用页面script的id名,用于取参数 getDivHtml();//读取div内容 function bindBtnEvent(divNo, i) { //$("#" + getPar(scriptid, "BtnName").split(",")[i]).bind('click', function () { btnclick(divNo); });//委托弹窗按钮事件 $("#divPOP" + divNo).delegate('.close', 'click', function () { $("#divPOP" + divNo).dialog("close"); getDivHtml(); });//委托弹窗赵红close按钮事件 } function OverLayOpen(divNo) { //弹窗按钮触发事件 var w = $("#divPOP" + divNo + " >.overlay").width();//自适应宽度,长度默认为auto $("#divPOP" + divNo).dialog({ autoOpen: true,//自动打开窗口 bgiframe: true, resizable: false, modal: true,//模块化 title: null, width: w, show: { effect: "blind", duration: 100 }, hide: { effect: "blind", duration: 100 } }) $(".ui-dialog-titlebar").hide();//关闭jquery dialog自带的title功能,若打开功能则自带关闭按钮 } function OverLayClose(divNo) { $("#divPOP" + divNo).dialog("close"); } //读取加载js后的参数 function getPar(scrID, par) { var local_url = document.getElementById(scrID).src; var get = local_url.indexOf(par + "="); if (get == -1) { return false; } var get_par = local_url.slice(par.length + get + 1); var nextPar = get_par.indexOf("&"); if (nextPar != -1) { get_par = get_par.slice(0, nextPar); } return get_par; } function getDivHtml() { AddConfirm(); AddAlert(); try { var No = getPar(scriptid, "No").split(",");//读取js后的参数No var i = 0; loadDiv(No, i); } catch (ex) { } } function AddConfirm() { //var confirm = document.createElement("div"); //confirm.id = "divConfirm"; //document.body.appendChild(confirm); loadDiv([6], 0); } function DivConfirm(content, callback, title, title_en, width) { if (width == undefined) width = $("#divPOP6 .overlay").width(); if (title == undefined) title = "确认框"; if (title_en == undefined) title_en = "Confirm"; var innerHTML = $("#divPOP6")[0].innerHTML; innerHTML = ProcessData(innerHTML, "Title", title); innerHTML = ProcessData(innerHTML, "T_en", title_en); innerHTML = ProcessData(innerHTML, "Content", content); $("#divPOP6")[0].innerHTML = innerHTML; $("#divPOP6").dialog({ autoOpen: true,//自动打开窗口 bgiframe: true, resizable: false, modal: true,//模块化 title: title, width: width, show: { effect: "blind", duration: 100 }, hide: { effect: "blind", duration: 100 } }) $(".ui-dialog-titlebar").hide();//关闭jquery dialog自带的title功能,若打开功能则自带关闭按钮 $(".btnl-normal.qingbg").bind("click", function () { OverLayClose(6); AddConfirm(); if ($.isFunction(callback)) { callback.apply(); } }); $(".btnl-normal.orgbg").bind("click", function () { OverLayClose(6); AddConfirm(); }) } function AddAlert() { //var confirm = document.createElement("div"); //confirm.id = "divAlert"; //document.body.appendChild(confirm); loadDiv([5], 0); } function DivAlert(content, title, title_en, width) { if (width == undefined) width = $("#divPOP5 .overlay").width(); if (title == undefined) title = "提示"; if (title_en == undefined) title_en = "Alert" var innerHTML = $("#divPOP5")[0].innerHTML; innerHTML = ProcessData(innerHTML, "Title", title); innerHTML = ProcessData(innerHTML, "T_en", title_en); innerHTML = ProcessData(innerHTML, "Content", content); $("#divPOP5")[0].innerHTML = innerHTML; $("#divPOP5").dialog({ autoOpen: true,//自动打开窗口 bgiframe: true, resizable: false, modal: true,//模块化 title: title, width: width, show: { effect: "blind", duration: 100 }, hide: { effect: "blind", duration: 100 } }) $(".ui-dialog-titlebar").hide();//关闭jquery dialog自带的title功能,若打开功能则自带关闭按钮 $(".btnl-normal.orgbg").bind("click", function () { OverLayClose(5); AddAlert(); }) } function loadDiv(No, i) { var sum = No.length; if (i >= sum) { return; } var divNo = No[i]; if (!isNaN(divNo)) { var result = document.getElementById("divPOP" + divNo);//创建弹窗div if (result == undefined) { result = document.createElement("div"); result.id = "divPOP" + divNo; document.body.appendChild(result); } result.innerHTML = ""; if (url != undefined && url != "") { $.ajax({ type: 'get', url: url, dataType: 'text', success: function (data) { var DIVs = data.split(splitstr);//读取div.html result.innerHTML = DIVs[divNo];//将对应的div存入 result.style.display = "none"; bindBtnEvent(divNo, i); loadDiv(No, i + 1);//循环加载多个 } }) } } } function ProcessData(str, name, value) { return str.replace("%" + name, value); }
/*------------------------ LES SELECTYEURS jQUERY -----------------------*/ // -- Format : $('selecteur'); // -- En jQuery, tous les selecteurs CSS sont disponibles ... $(function() { // -- DOM READY ! l = e => console.log(e) // -- Sélectionner toutes les balises SPAN ! // En JS l( document.getElementsByTagName('span')); // En JQ l( $('span')); // -- Selection Menu grâce à son ID // En JS l( document.getElementsById('menu')); // En JQ l( $('#menu')); // -- Selection Menu grâce à sa class // En JS l( document.getElementsByClassName('MaClasse')); // En JQ l( $('.MaClasse')); // --Sélectionner un Attribut l($('[href="https://www.google.fr"]')) });
import React from 'react'; import Contain from './Contain' import containing from './containing' const Bottom = ()=>{ return ( <div> <div className="contb"> <div className="container"> <div className="row"> <div className="col-lg-4"> <div className="cont-1"> <Contain name={containing[0].name} imgUrl={containing[0].imgUrl} par={containing[0].par} verified={containing[0].verified} /> </div> </div> <div className="col-lg-4"> <div className="cont-2"> <Contain name={containing[1].name} imgUrl={containing[1].imgUrl} par={containing[1].par} verified={containing[1].verified} /> </div> </div> <div className="col-lg-4"> <div className="cont-3"> <Contain name={containing[2].name} imgUrl={containing[2].imgUrl} par={containing[2].par} verified={containing[2].verified} /> </div> </div> </div> </div> </div> </div> ); } export default Bottom;
import { Col, Container, Row } from 'react-bootstrap' import './Footer.css' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faInstagram, faFacebook, faTwitter, faLinkedin } from '@fortawesome/free-brands-svg-icons' import { faLocationArrow, faEnvelope, faPhone } from '@fortawesome/free-solid-svg-icons' import '../../shared/UserNavigation/UserNavigation.css' import { Link } from 'react-router-dom' const Footer = () => { return ( <> <footer> <Container className="bottom_border"> <Row> <Col> <div className='footer-box'> <h5 className="col-color pt2">Acerca de Nosotros</h5> <p className="mb10">Somos 2 intentos de programadores que les toca escribir este párrafo a las 2 de la madrugada , gracias Ironhack por esta experiencia.</p> </div> </Col> <Col> <div className='footer-box'> <h5 className="col-color pt2">Acceso Rápido</h5> <ul className="footer-ul"> <li><Link className="nav-link" to="/">Home</Link></li> <li><Link className="nav-link" to="/habitaciones">Habitaciones</Link></li> <li><Link className="nav-link" to="/habitaciones">Iron Hack</Link></li> </ul> </div> </Col> <Col className='contact-box'> <div className='footer-box'> <h5 className="col-color pt2">Contacto</h5> <p><FontAwesomeIcon icon={faLocationArrow} className='icon-font' /> En algún lugar de la mancha </p> <p><FontAwesomeIcon icon={faPhone} className='icon-font' /> +34-667253882 </p> <p><FontAwesomeIcon icon={faEnvelope} className='icon-font' /> info@holi.com </p> </div> </Col> </Row> </Container> <Container> <p className="footer-box">Desarrollo por:<strong> Pepe & Lali </strong>|| © Todos los derechos reservados para Carol</p> <ul className="social-footer"> <li><Link className="nav-link" to=""><FontAwesomeIcon icon={faFacebook} className='icon-font' /></Link></li> <li><Link className="nav-link" to=""><FontAwesomeIcon icon={faInstagram} className='icon-font' /></Link></li> <li><Link className="nav-link" to=""><FontAwesomeIcon icon={faLinkedin} className='icon-font' /></Link></li> <li><Link className="nav-link" to=""><FontAwesomeIcon icon={faTwitter} className='icon-font' /></Link></li> </ul> </Container> </footer> </> ) } export default Footer
const { response } = require("express"); const { get } = require("mongoose"); //create the variableto hold DB connection let db; const request = indexedDB.open('budget-tracker', 1); request.onupgradeneeded = function (event) { const db = event.target.result; db.createObjectStore('new-transaction', { autoIncrement: true}); }; request.onsuccess = function (event) { deb = event.target.result; if (navigator.onLine) { uploadTransaction(); } }; request.onerror = function (event) { console.log(event.target.errorCode); }; // save the data with no connection function saveRecord(record) { const transaction =db.transaction(['new-transaction'], 'readwrite'); const budgetObjectStore = transaction.objectStore('new-transaction'); budgetObjectStore.add(record); }; function uploadTransaction() { const transaction = db.transaction(['new-transaction'], 'readwrite'); const budgetObjectStore = transaction.objectStore('new-transaction'); const getAll = budgetObjectStore.getAll(); //send data to transaction api getAll.onsuccess = function () { if (getAll.result.length > 0) { fetch('/api/transaction', { method: 'POST', body: JSON.stringify(getAll.result), headers: { Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(serverResponse => { if (serverResponse.message){ throw new Error(serverResponse); } const transaction = db.transaction(['new-transaction'], 'readwrite'); const budgetObjectStore = transaction.objectStore('new-transaction'); budgetObjectStore.clear(); alert('All transactions have been entered!'); }) .catch(err => { console.log(err); }); } } };
import React, { Component} from 'react' export class NavBar_Tabs extends Component{ render(){ return( <div className="ui container"> <div className="ui row vertical segment"> <h1 className="ui header">NavBar <div className="sub header">{`<NavBar_Tabs />`}</div> </h1> </div> <div className="ui row vertical segment"> <div className="ui ignored message"> <code> <span><b>import </b></span> <span>{`{NavBar_Tabs}`} </span> <span><b>from </b></span> <span><font color="red">'./../components/NavBar_Tabs'</font></span> </code> </div> </div> <div className="ui row vertical segment"> <h3 className="ui header">Preview</h3> <div className="ui secondary menu nav-item"> <div className="ui secondary pointing menu"> <a className="item active" href="#">Search</a> <a className="item" href="#">Company</a> </div> </div> </div> <div className="ui row vertical segment"> <h3 className="ui header">Code</h3> <div className="ui ignored message"> <pre> { `<div className="ui secondary menu nav-item"> <div className="ui secondary pointing menu"> <a className="item active" href="#">Search</a> <a className="item" href="#">Company</a> </div> </div>` } </pre> </div> </div> </div> ) } }
import React, { Component } from 'react'; import Input from './Input'; import Joi from 'joi-browser'; class Form extends Component { state ={ fields: {}, errors: {} }; validateField = () => { const options = {abortEarly: false}; const { error } = Joi.validate(this.state.fields, this.schema, options); if (!error) return null; const errors = {}; for (let item of error.details) errors[item.path[0]] = item.message; return errors; }; validateProperty = ({ name, value }) => { const obj = { [name]: value }; const schema = { [name]: this.schema[name]} const { error } = Joi.validate(obj, schema); return error ? error.details[0].message : null; }; handleFormChange = ({currentTarget: input }) => { const errors = {...this.state.errors} const errorMessage = this.validateProperty(input); if (errorMessage) errors[input.name] = errorMessage; else delete errors[input.name]; const fields = {...this.state.fields}; fields[input.name] = input.value; this.setState({fields, errors}); }; handleSubmit = e => { e.preventDefault(); const errors = this.validateField(); this.setState({errors: errors || {} }); if (!errors) return; this.doSubmit(); }; renderInput(name, label, type='text'){ const { fields, errors } = this.state return ( <Input value={fields[name]} name={name} type={type} label={label} error={errors[name]} onChange={this.handleFormChange} /> ) } renderButton = label => { return ( <button className="btn btn--green" disabled={this.validateField()} >{label}</button> ); } } export default Form;
'use strict'; module.exports.format = function (str, options) { var mask; if (options && options.international) { mask = '(+$1)$2-$3-$4'; } else { mask = '$2-$3-$4'; } if (str.length === 12) { return str.replace(/^\+(\d{1})(\d{3})(\d{3})(\d{4}).*/, mask); } else if (str.length === 13) { return str.replace(/^\+(\d{2})(\d{3})(\d{3})(\d{4}).*/, mask); } else { return str; } };
var express = require('express'); var mongoose = require('mongoose'); var router = express.Router(); mongoose.connect('mongodb://localhost:27017/project', function(err) { if(!err) { console.log('数据库连接成功!!!'); } }); var userSchema = new mongoose.Schema({ username: String, password: String, name: String, role: String, department: String, orderNum: Number, status: Number }); var logSchema = new mongoose.Schema({ adminuser:String, content:String, intime:Date, result:String, ip:String }); var userModel = mongoose.model('user', userSchema, 'user'); var logModel = mongoose.model('log', logSchema, 'log'); router.get('/userlogin.html', function(req, res) { // 获取用户传递的用户名和密码 var username = req.query.username; var password = req.query.password; userModel.find({ 'username': username, 'password': password }).exec(function(err, data) { // 如果查询有数据 则将用户名写入cookie中 if(data.length) { res.cookie('username', username); } var log = new logModel(); log.adminuser=username; log.content = '登录了系统'; log.intime = new Date().toLocaleString(); log.result = '成功'; log.ip = req.ip; log.save(function(err){ res.send(data); }) }); }); // 判断用户是否登陆过 router.get('/checklogin.js', function(req, res) { // 判断是否存在usernamecookie,如果存在,则不作别的处理,如果不存在,则提示用户,并跳转登录页面 if(req.cookies.username) { res.send(''); } else { res.send('alert("你还未登录,快去登录吧!");location.href="login.html";') } }); /*退出登录 清除cookie并跳转登录页面*/ router.get('/loginout.html', function(req, res) { //清除cookies res.clearCookie('username'); res.send('<script>alert("退出登录成功!");location.href="/admin/pages/login.html";</script>'); }); /*添加新用户*/ router.post('/user_add.html', function(req, res) { var username = req.body.username; var password = req.body.password; var name = req.body.name; var role = req.body.role; var department = req.body.department; var orderNum = parseInt(req.body.orderNum); var status = parseInt(req.body.status); // console.log(username,password,name,role,department,orderNum,status); var user = new userModel(); user.username = username; user.password = password; user.name = name; user.role = role; user.department = department; user.orderNum = orderNum; user.status = status; user.save(function(err){ if (err) { res.send('0'); }else{ var log = new logModel(); log.adminuser=req.cookies.username; log.content = '创建了新用户:'+username; log.intime = new Date().toLocaleString(); log.result = '成功'; log.ip = req.ip; log.save(function(err){ res.send('1'); }) } }) }); /*分页显示用户*/ router.get('/user_showpage.html',function(req,res){ var pagesize = 4;// 每页显示的行数 //条件二:获取当前的页码,如果没有传值,默认在第1页 var page = req.query.page?req.query.page:1; userModel.find({}).exec(function(err,data){ // 总页数=向上取整(数据总长度/每页行数) var pagecount = Math.ceil(data.length/pagesize); /* * 必须要知道从哪里开始读取(起始位置)多少条数据(pagesize) * 当前在第1页 跳过 0 * 当前在第2页 跳过 3 * 当前在第3页 跳过 6 * 当前在第4页 跳过 9 * * start=(page-1)*pagesize */ var start = (page-1)*pagesize; userModel.find({}).skip(start).limit(pagesize).sort({'orderNum':1}).exec(function(err,data){ // data是一个数组 可以直接使用push将pagecount添加进去,将data相应给浏览器 data.push({'pagecount':pagecount}); // console.log(data[0]._id); res.send(data); }); }); }); /*删除用户*/ router.post('/user_delete.html',function(req,res){ var idsArr = req.body.idsArr; // console.log(idsArr); // 将接收到的id字符串转换成数组 var idsArr = idsArr.split(','); userModel.find({'_id':{$in:idsArr}}).exec(function(err,data){ for (var i in data) { // 删除数据 data[i].remove(); } var log = new logModel(); log.adminuser=req.cookies.username; log.content = '删除'+data.length+'个用户'; log.intime = new Date().toLocaleString(); log.result = '成功'; log.ip = req.ip; log.save(function(err){ res.send('1'); }) }); }); /*修改用户 * 根据客户端提交的id进行查找并返回数据 */ router.get('/user_show.html',function(req,res){ var id = req.query.id; // console.log(id); userModel.findById(id).exec(function(err,data){ if (err) { throw err; } else{ res.send(data); } }) }); /* * 保存修改的数据 */ router.post('/user_edit.html',function(req,res){ var id = req.body.id; var name = req.body.name; var role = req.body.role; var status = parseInt(req.body.status); var orderNum = parseInt(req.body.orderNum); var username = req.body.username; var department = req.body.department; // console.log(id,name,role,status,orderNum,username,department) userModel.findById(id).exec(function(err,data){ data.username = username; data.name = name; data.role = role; data.department = department; data.orderNum = orderNum; data.status = status; data.save(function(err){ if (err) { res.send('0'); }else{ var log = new logModel(); log.adminuser=req.cookies.username; log.content = '修改了户名为:'+username; log.intime = new Date().toLocaleString(); log.result = '成功'; log.ip = req.ip; log.save(function(err){ res.send('1'); }) } }) }); }); /* * 修改密码 */ router.get('/edit_password.html',function(req,res){ // 获取cookie中的username var username = req.cookies.username var password = req.query.oldpassword; var newpassword = req.query.newpassword; // console.log(username,password,newpassword) userModel.find({'username':username,'password':password}).exec(function(err,data){ if (data.length) { data[0].password=newpassword; data[0].save(function(err){ if (err) { throw err; res.send('0'); } else{ res.send('1'); } }) }else{ res.send('0'); } }); }); /*查询用户*/ router.get('/search.html',function(req,res){ var username = req.query.username; var department = req.query.department; var role = req.query.role; // console.log(username,department,role); var obj={}; if (department!='全部') { obj.department=department; } if (role!='全部') { obj.role=role; } if (username!='') { // 如果用户名不等于空 通过正则表达式将username传入 obj.username = new RegExp(username); } // console.log(obj); userModel.find(obj).sort({'orderNum':1}).exec(function(err,data){ res.send(data); }); }); /*显示所有日志*/ router.get('/log_show.html',function(req,res){ var page = req.query.page?req.query.page:1; var pagesize = 5;//每页显示log条数 logModel.find({}).exec(function(err,data){ //获取总页数 var pagecount = Math.ceil(data.length/pagesize); //,每页显示哪条数据开始 var start = (page-1)*pagesize; logModel.find({}).skip(start).limit(pagesize).sort({'intime':-1}).exec(function(err,data){ if (!err) { // 将总页数加入到data数组中返回给浏览器 data.push({'pagecount':pagecount}); res.send(data); } }); }); }); module.exports = router;
let counterValue = 0; const btnIncrementRef = document.querySelector( '#counter button[data-action="increment"]' ); const btnDecrementRef = document.querySelector( '#counter button[data-action="decrement"]' ); const textRef = document.querySelector('#value'); const increment = () => { textRef.textContent = (counterValue += 1); }; const decrement = () => { textRef.textContent = (counterValue -= 1); }; btnIncrementRef.addEventListener('click', increment); btnDecrementRef.addEventListener('click', decrement);
const express = require('express'); const router = express.Router(); const auth = require('../middleware/auth') const { check, validationResult} = require('express-validator'); const User = require('../models/User') const Budget = require('../models/Budget') // @route GET api/budget // @desc Get all user's budget // @access Private router.get('/', auth, async (req,res) => { try { const budget = await Budget.find({user: req.user.id}).sort({date: -1}) res.json(budget) } catch (err) { console.error(err.message) res.status(500).send('Server Error') } }); // @route POST api/budget // @desc Add a new budget // @access Private router.post('/', [auth, check('name', 'Name is required') .not() .isEmpty(), ], async (req,res) => { const errors = validationResult(req) if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const {name} = req.body try { const newBudget = new Budget({ name, user: req.user.id }) const budget = await newBudget.save() res.json(budget) } catch (err) { console.error(err.message) res.status(500).send('Server Error') } }); // @route GET api/budget/:id // @desc gets a single budget // @access Private router.get('/:id', auth, async(req,res) => { try { const budget = await Budget.findById(req.params.id) if(!budget) return res.status(404).send({msg:'Not found'}) if(budget.user.toString() !== req.user.id) return res.status(401).send({msg:'Not authorized'}) res.json(budget) } catch (err) { console.error(err.message) res.status(500).send('Server Error') } }); // @route POST api/budget/:id // @desc adds item to a budget // @access Private router.post('/:id', [auth, [check('amount', 'Amount is required') .not() .isEmpty(), check('amount', 'Amount must be a number') .isNumeric(), check('description', 'Description is required') .trim() .not() .isEmpty(), check('type', 'Type is required') .not() .isEmpty()] ],async(req,res) => { const errors = validationResult(req) if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } try { let budget = await Budget.findById(req.params.id) if(!budget) return res.status(404).send({msg:'Not found'}) if(budget.user.toString() !== req.user.id) return res.status(401).send({msg:'Not authorized'}) const {amount, description, type} = req.body budget = await Budget.findOneAndUpdate({_id: req.params.id}, {$push: {[type] : {amount,description,type}}}, {new:true} ) res.json(budget ) } catch (err) { console.error(err.message) res.status(500).send('Server Error') } }); // @route PUT api/budget/:id // @desc Update a budget expense or income based on id // @access Private router.put('/:id', [auth, [check('amount', 'Amount is required') .not() .isEmpty(), check('amount', 'Amount must be a number') .isNumeric(), check('description', 'Description is required') .trim() .not() .isEmpty(), check('type', 'Type is required') .not() .isEmpty()] ], async (req,res) => { const errors = validationResult(req) if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } try { let budget = await Budget.findById(req.params.id) if(!budget) return res.status(404).send({msg:'Not found'}) if(budget.user.toString() !== req.user.id) return res.status(401).send({msg:'Not authorized'}) const {_id,amount, description, type} = req.body budget = await Budget.updateOne( {_id: req.params.id,[`${type}._id`]: _id}, {$set: { [`${type}.$.description`]:description, [`${type}.$.amount`]:amount }}) res.json(budget) } catch (err) { console.error(err.message) res.status(500).send('Server Error') } }); // @route Delete api/budget/:id // @desc Delete a budget expense or income item by id // @access Private router.delete('/:id',auth, async (req,res) => { try { let budget = await Budget.findById(req.params.id) if(!budget) return res.status(404).send({msg:'Not found'}) if(budget.user.toString() !== req.user.id) return res.status(401).send({msg:'Not authorized'}) const {_id,type} = req.body budget = await Budget.updateOne( {_id: req.params.id,[`${type}._id`]: _id}, {$pull: {[type]:{_id}}} ) res.json(budget) } catch (err) { console.error(err.message) res.status(500).send('Server Error') } }); module.exports = router;
const methods = { torrents: { stop: 'torrent-stop', start: 'torrent-start', startNow: 'torrent-start-now', verify: 'torrent-verify', reannounce: 'torrent-reannounce', set: 'torrent-set', setTypes: { 'bandwidthPriority': true, 'downloadLimit': true, 'downloadLimited': true, 'files-wanted': true, 'files-unwanted': true, 'honorsSessionLimits': true, 'ids': true, 'location': true, 'peer-limit': true, 'priority-high': true, 'priority-low': true, 'priority-normal': true, 'seedRatioLimit': true, 'seedRatioMode': true, 'uploadLimit': true, 'uploadLimited': true }, add: 'torrent-add', addTypes: { 'download-dir': true, 'filename': true, 'metainfo': true, 'paused': true, 'peer-limit': true, 'files-wanted': true, 'files-unwanted': true, 'priority-high': true, 'priority-low': true, 'priority-normal': true }, rename: 'torrent-rename-path', remove: 'torrent-remove', removeTypes: { 'ids': true, 'delete-local-data': true }, location: 'torrent-set-location', locationTypes: { 'location': true, 'ids': true, 'move': true }, get: 'torrent-get', fields: [ 'activityDate', 'addedDate', 'bandwidthPriority', 'comment', 'corruptEver', 'creator', 'dateCreated', 'desiredAvailable', 'doneDate', 'downloadDir', 'downloadedEver', 'downloadLimit', 'downloadLimited', 'error', 'errorString', 'eta', 'files', 'fileStats', 'hashString', 'haveUnchecked', 'haveValid', 'honorsSessionLimits', 'id', 'isFinished', 'isPrivate', 'leftUntilDone', 'magnetLink', 'manualAnnounceTime', 'maxConnectedPeers', 'metadataPercentComplete', 'name', 'peer-limit', 'peers', 'peersConnected', 'peersFrom', 'peersGettingFromUs', 'peersKnown', 'peersSendingToUs', 'percentDone', 'pieces', 'pieceCount', 'pieceSize', 'priorities', 'rateDownload', 'rateUpload', 'recheckProgress', 'seedIdleLimit', 'seedIdleMode', 'seedRatioLimit', 'seedRatioMode', 'sizeWhenDone', 'startDate', 'status', 'trackers', 'trackerStats', 'totalSize', 'torrentFile', 'uploadedEver', 'uploadLimit', 'uploadLimited', 'uploadRatio', 'wanted', 'webseeds', 'webseedsSendingToUs'] }, session: { stats: 'session-stats', get: 'session-get', set: 'session-set', setTypes: { 'start-added-torrents': true, 'alt-speed-down': true, 'alt-speed-enabled': true, 'alt-speed-time-begin': true, 'alt-speed-time-enabled': true, 'alt-speed-time-end': true, 'alt-speed-time-day': true, 'alt-speed-up': true, 'blocklist-enabled': true, 'dht-enabled': true, 'encryption': true, 'download-dir': true, 'peer-limit-global': true, 'peer-limit-per-torrent': true, 'pex-enabled': true, 'peer-port': true, 'peer-port-random-on-start': true, 'port-forwarding-enabled': true, 'seedRatioLimit': true, 'seedRatioLimited': true, 'speed-limit-down': true, 'speed-limit-down-enabled': true, 'speed-limit-up': true, 'speed-limit-up-enabled': true } }, other: { blockList: 'blocklist-update', port: 'port-test', freeSpace: 'free-space' } } export const torrentStatusMap = [ 'Stopped', /* Torrent is stopped */ 'Queued', /* Queued to check files */ 'Checking', /* Checking files */ 'Queued for DL', /* Queued to download */ 'Downloading', /* Downloading */ 'Queue to seed', /* Queued to seed */ 'Seeding' /* Seeding */ ] export default methods
import React, { Component, Fragment } from 'react'; import CardBlog from './CardBlog'; import API from '../../services/index'; export class Blog extends Component { state = { post: [], form: { userId: 1, id: 1, title: '', body: '' }, isUpdate: false } getAPI = () => { API.getNewBlog().then(res => { this.setState({ post: res }) }) } removeAPI = (id) => { API.deleteNewBlog(id).then(() => this.getAPI()); } handleFormChange = (e) => { let newForm = { ...this.state.form }; newForm[e.target.name] = e.target.value; if (!this.state.isUpdate) { newForm['id'] = new Date().getTime(); } this.setState({ form: newForm }) } postAPI = () => { API.postNewBlog(this.state.form).then(() => { this.getAPI(); this.setState({ form: { userId: 1, id: 1, title: '', body: '' } }) }) } handleUpdate = (data) => { this.setState({ form: data, isUpdate: true }) } updateAPI = () => { API.putNewBLog(this.state.form, this.state.form.id).then(() => { this.getAPI(); this.setState({ isUpdate: false, form: { userId: 1, id: 1, title: '', body: '' } }) }) } onClickAdd = (e) => { e.preventDefault(); if (this.state.isUpdate) { this.updateAPI(); } else { this.postAPI(); } } handleDetail = (id) => { this.props.history.push(`/blog/${id}`); } componentDidMount() { this.getAPI(); } render() { return ( <Fragment> <div className="row mb-4"> <div className="col-md-8"> <form> <div className="row"> <div className="col"> <input type="text" value={this.state.form.title} className="form-control" onChange={this.handleFormChange} name="title" placeholder="Title.." /> </div> <div className="col"> <input type="text" value={this.state.form.body} className="form-control" onChange={this.handleFormChange} name="body" placeholder="Body.." /> </div> <div className="col"> <button className="btn btn-primary float-left" onClick={this.onClickAdd}>Add</button> </div> </div> </form> </div> </div> <div className="row"> {this.state.post.map(post => ( <CardBlog key={post.id} data={post} remove={(id) => this.removeAPI(id)} update={(data) => this.handleUpdate(data)} goDetail={(id) => this.handleDetail(id)} /> ))} </div> </Fragment> ) } } export default Blog
const { Schema, model } = require('mongoose'); const UsuarioSchema = Schema({ nombre: { type: String, required: true, }, email: { type: String, required: true, unique: true, }, password: { type: String, required: true, }, online: { type: Boolean, default: false, }, }); // Esta funcion se ejecuta cuando lo pasan al JSON, no se ven en el codigo // pero es al responder en auth.js UsuarioSchema.method('toJSON', function(){ // Se extraen los valores que no queremos devolver const { __v, _id, password, ...object } = this.toObject(); // Se añade un valor que queríamos renombrar object.uid = _id; return object; }); module.exports = model('Usuario', UsuarioSchema ); //se utiliza en controller auth
const { flex } = require('csstips/lib/flex') module.exports = ({ } = {}) => { return [ flex, { $debugName: 'Flexible', } ] }
// 将目录中所有文件中的汉字,可以内嵌数字,扫描提取出来 let fs = require('fs') let join = require('path').join function getJsonFiles(jsonPath) { let jsonFiles = [] function findJsonFile(path) { let files = fs.readdirSync(path) files.forEach(function(item, index) { let fPath = join(path, item) let stat = fs.statSync(fPath) if (stat.isDirectory() === true) { findJsonFile(fPath) } if (stat.isFile() === true) { jsonFiles.push(fPath) } }) } findJsonFile(jsonPath) return jsonFiles } function stripscript(s) { let pattern = new RegExp( "[`__~!@#$^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*()——|{}\"【】‘;:”“'。,、?]" ) let rs = '' for (let i = 0; i < s.length; i++) { rs = rs + s.substr(i, 1).replace(pattern, '') } return rs } function GetChinese(strValue) { if (strValue != null && strValue != '') { let reg = /([\u4E00-\u9FA5]+)|(.*[\u4E00-\u9FA5].*)/g let reg2 = /[a-zA-Z]/g let str = strValue.replace(reg2, '') let str2 = stripscript(str) return str2.match(reg).join('</br>') } else{ return '' } } function readFiles(source) { let Files = getJsonFiles(source) let data = [] Files.forEach(function(item) { if (item.split('.').pop() == 'js' || item.split('.').pop() == 'vue') { let idata = fs.readFileSync(item, 'utf-8') data = data.concat(idata) } }) return data } function copySync(source, target) { let data = readFiles(source) let result = GetChinese(data.toString()) fs.writeFileSync(target, result) } copySync('./src', './out.html')
import { Paper, Grid, Container } from '@material-ui/core'; import { makeStyles } from '@material-ui/core/styles'; import { Card, Typography, Button } from 'antd'; import { Link } from 'react-router-dom'; import { WHAT_NEW_LIST } from '../../../helper/_listNavURL'; import { RightOutlined, LeftOutlined } from '@ant-design/icons'; import { useRef, useEffect } from 'react'; const useStyles = makeStyles((theme) => ({ paper: { margin: '10px 0', background: 'white', }, gridRoot: { padding: theme.spacing(1), }, textSpacing: { display: 'flex', justifyContent: 'space-between', padding: theme.spacing(2), }, link: { textDecoration: 'underline', }, sectionXFLow: { display: 'flex', overflowX: 'hidden', height: 'fit-content', overflowY: 'hidden', }, cardImageWrapper: { width: 'fit-content', }, imageScrollContainer: { position: 'relative', height: 400, width: 300, overflow: 'hidden', marginBottom: 10, }, image: { width: '100%', }, topImageText: { width: 'fit-content', padding: theme.spacing(0.4), position: 'absolute', top: 0, left: 0, }, moveBtnWrapper: { width: 100, display: 'flex', justifyContent: 'space-around', }, })); const { Title, Paragraph } = Typography; const NewArrivalSection = () => { const classes = useStyles(); const cardContainerRef = useRef(null); const moveRightButtonRef = useRef(null); const moveLeftButtonRef = useRef(null); useEffect(() => { if ( cardContainerRef.current && moveLeftButtonRef.current && moveRightButtonRef.current ) { NodeList.prototype.forEach = Array.prototype.forEach; const cartItemsList = cardContainerRef.current; let currentScrollPosition = 0; const maxWidth = cartItemsList.scrollWidth; const scrolledSize = cartItemsList.childNodes[0].clientWidth; const handleMove = (_, command) => { if (command === 'left') { cartItemsList.scroll({ behavior: 'smooth', left: currentScrollPosition === 0 ? currentScrollPosition : (currentScrollPosition -= scrolledSize), }); } else { cartItemsList.scroll({ behavior: 'smooth', left: currentScrollPosition >= maxWidth - cartItemsList.clientWidth ? maxWidth : (currentScrollPosition += scrolledSize), }); } }; const leftButton = moveLeftButtonRef.current; const rightButton = moveRightButtonRef.current; leftButton.addEventListener( 'click', handleMove.bind(this, undefined, 'left') ); rightButton.addEventListener( 'click', handleMove.bind(this, undefined, 'right') ); return () => { leftButton.removeEventListener('click', handleMove); rightButton.removeEventListener('click', handleMove); }; } }, []); return ( <section className='section-container'> <Container> <Paper elevation={0} className={classes.paper}> <Grid container className={classes.gridRoot}> <Grid item xs={12} className={classes.textSpacing}> <Title level={4}>WHAT'S NEW</Title> <div className={classes.moveBtnWrapper}> <Button shape='circle' ref={moveLeftButtonRef}> <LeftOutlined /> </Button> <Button shape='circle' ref={moveRightButtonRef}> <RightOutlined /> </Button> </div> <Link to='/new-arrivals' className={classes.link}> View all </Link> </Grid> <Grid item xs={12}> <div className={`${classes.sectionXFLow} section-flow`} ref={cardContainerRef} > {WHAT_NEW_LIST.map((item) => { return ( <Card key={item.imageURL} className={classes.cardImageWrapper} > <Link to={item.url}> <div className={classes.imageScrollContainer}> <img src={item.imageURL} alt={item.title} className={classes.image} /> </div> </Link> <div className={classes.cardInfoWrapper}> <Paragraph>{item.desc}</Paragraph> <Title level={5}>{item.title}</Title> </div> </Card> ); })} </div> </Grid> </Grid> </Paper> </Container> </section> ); }; export default NewArrivalSection;
// +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997-2002 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 2.02 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available at through the world-wide-web at | // | http://www.php.net/license/2_02.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Author: Richard Heyes <richard@phpguru.org> | // | Harald Radi <harald.radi@nme.at> | // +----------------------------------------------------------------------+ // // original-Id: TreeMenu.js,v 1.3 2002/06/22 14:45:36 richard Exp // $Id$ function TreeMenu(layer, iconpath, myname, linkTarget) { // Properties this.layer = layer; this.iconpath = iconpath; this.myname = myname; this.linkTarget = linkTarget; this.n = new Array(); this.branches = new Array(); this.branchStatus = new Array(); this.layerRelations = new Array(); this.childParents = new Array(); // Methods //this.preloadImages = preloadImages; this.drawMenu = drawMenu; this.toggleBranch = toggleBranch; this.swapImage = swapImage; this.doesMenu = doesMenu; this.doesPersistence = doesPersistence; this.getLayer = getLayer; this.saveExpandedStatus = saveExpandedStatus; this.loadExpandedStatus = loadExpandedStatus; this.resetBranches = resetBranches; } function TreeNode(title, icon, link, expanded) { this.title = title; this.icon = icon; this.link = link; this.expanded = expanded; this.n = new Array(); } /** * Preload images hack for CrapZilla */ function preloadImages() { var plustop = new Image; plustop.src = this.iconpath + '/plustop.gif'; var plusbottom = new Image; plusbottom.src = this.iconpath + '/plusbottom.gif'; var plus = new Image; plus.src = this.iconpath + '/plus.gif'; var minustop = new Image; minustop.src = this.iconpath + '/minustop.gif'; var minusbottom = new Image; minusbottom.src = this.iconpath + '/minusbottom.gif'; var minus = new Image; minus.src = this.iconpath + '/minus.gif'; } /** * Main function that draws the menu and assigns it * to the layer (or document.write()s it) */ function drawMenu()// OPTIONAL ARGS: nodes = [], level = [], prepend = '', expanded = false, visbility = 'inline', parentLayerID = null { /** * Necessary variables */ var output = ''; var modifier = ''; var layerID = ''; var parentLayerID = ''; /** * Parse any optional arguments */ var nodes = arguments[0] ? arguments[0] : this.n var level = arguments[1] ? arguments[1] : []; var prepend = arguments[2] ? arguments[2] : ''; var expanded = arguments[3] ? arguments[3] : false; var visibility = arguments[4] ? arguments[4] : 'inline'; var parentLayerID = arguments[5] ? arguments[5] : null; var currentlevel = level.length; for (var i=0; i<nodes.length; i++) { level[currentlevel] = i+1; layerID = this.layer + '_' + 'node_' + implode('_', level); /** * Store the child/parent relationship */ this.childParents[layerID] = parentLayerID; /** * Gif modifier */ if (i == 0 && parentLayerID == null) { modifier = nodes.length > 1 ? "top" : 'single'; } else if(i == (nodes.length-1)) { modifier = "bottom"; } else { modifier = ""; } /** * Single root branch is always expanded */ if (!doesMenu() || (parentLayerID == null && nodes.length == 1)) { expanded = true; } /** * Setup branch status and build an indexed array * of branch layer ids */ if (nodes[i].n.length > 1) { this.branchStatus[layerID] = expanded; this.branches[this.branches.length] = layerID; } /** * Setup toggle relationship */ if (!this.layerRelations[parentLayerID]) { this.layerRelations[parentLayerID] = new Array(); } this.layerRelations[parentLayerID][this.layerRelations[parentLayerID].length] = layerID; /** * Branch images */ var gifname = nodes[i].n.length && this.doesMenu() ? (expanded ? 'minus' : 'plus') : 'branch'; var iconimg = nodes[i].icon ? sprintf('<img src="%s/%s" align="absbottom">', this.iconpath, nodes[i].icon) : ''; /** * Build the html to write to the document */ var divTag = sprintf('<div id="%s" style="display: %s; behavior: url(#default#userdata)">', layerID, visibility); var onMDown = doesMenu() && nodes[i].n.length ? sprintf('onmousedown="%s.toggleBranch(\'%s\', true)" style="cursor: pointer; cursor: hand"', this.myname, layerID) : ''; var imgTag = sprintf('<img src="%s/%s%s.gif" align="absbottom" border="0" name="img_%s" %s />', this.iconpath, gifname, modifier, layerID, onMDown); var linkStart = nodes[i].link ? sprintf('<a href="%s" target="%s">', nodes[i].link, this.linkTarget) : ''; var linkEnd = nodes[i].link ? '</a>' : ''; output = sprintf('%s<nobr>%s%s%s%s%s%s</nobr><br></div>', divTag, prepend, parentLayerID == null && nodes.length == 1 ? '' : imgTag, iconimg, linkStart, nodes[i].title, linkEnd); /** * Write out the HTML. Uses document.write for speed over layers and * innerHTML. This however means no dynamic adding/removing nodes on * the client side. This could be conditional I guess if dynamic * adding/removing is required. */ if (this.doesMenu()) { //this.getLayer(this.layer).innerHTML += output document.write(output); } else { document.write(output); } /** * Traverse sub nodes ? */ if (nodes[i].n.length) { /** * Determine what to prepend. If there is only one root * node then the prepend to pass to children is nothing. * Otherwise it depends on where we are in the tree. */ if (parentLayerID == null && nodes.length == 1) { var newPrepend = ''; } else if (i < (nodes.length - 1)) { var newPrepend = prepend + sprintf('<img src="%s/line.gif" align="absbottom">', this.iconpath); } else { var newPrepend = prepend + sprintf('<img src="%s/linebottom.gif" align="absbottom">', this.iconpath); } this.drawMenu(nodes[i].n, explode('_', implode('_', level)), // Seemingly necessary to enforce passing by value newPrepend, nodes[i].expanded, expanded ? 'inline' : 'none', layerID); } } } function toggleBranch(layerID, updateStatus) // OPTIONAL ARGS: noSave = false { var currentDisplay = this.getLayer(layerID).style.display; var newDisplay = (this.branchStatus[layerID] && currentDisplay == 'inline') ? 'none' : 'inline' for (var i=0; i<this.layerRelations[layerID].length; i++) { if (this.branchStatus[this.layerRelations[layerID][i]]) { this.toggleBranch(this.layerRelations[layerID][i], false); } this.getLayer(this.layerRelations[layerID][i]).style.display = newDisplay; } if (updateStatus) { this.branchStatus[layerID] = !this.branchStatus[layerID]; /** * Persistence */ if (this.doesPersistence() && !arguments[2]) { this.saveExpandedStatus(layerID, this.branchStatus[layerID]); } // Swap image this.swapImage(layerID); } } /** * Swaps the plus/minus branch images */ function swapImage(layerID) { imgSrc = document.images['img_' + layerID].src; re = /^(.*)(plus|minus)(bottom|top|single)?.gif$/ if (matches = imgSrc.match(re)) { document.images['img_' + layerID].src = sprintf('%s%s%s%s', matches[1], matches[2] == 'plus' ? 'minus' : 'plus', matches[3] ? matches[3] : '', '.gif'); } } /** * Can the browser handle the dynamic menu? */ function doesMenu() { return (is_ie5up || is_nav6up || is_gecko); } /** * Can the browser handle save the branch status */ function doesPersistence() { return is_ie5up; } /** * Returns the appropriate layer accessor */ function getLayer(layerID) { if (document.getElementById(layerID)) { return document.getElementById(layerID); } else if (document.all(layerID)) { return document.all(layerID); } } /** * Save the status of the layer */ function saveExpandedStatus(layerID, expanded) { document.all(layerID).setAttribute("expandedStatus", expanded); document.all(layerID).save(layerID); } /** * Load the status of the layer */ function loadExpandedStatus(layerID) { document.all(layerID).load(layerID); if (val = document.all(layerID).getAttribute("expandedStatus")) { return val; } else { return null; } } /** * Reset branch status */ function resetBranches() { if (!this.doesPersistence()) { return false; } for (var i=0; i<this.branches.length; i++) { var status = this.loadExpandedStatus(this.branches[i]); // Only update if it's supposed to be expanded and it's not already if (status == 'true' && this.branchStatus[this.branches[i]] != true) { if (this.childParents[this.branches[i]] == null || (in_array(this.childParents[this.branches[i]], this.branches) && this.branchStatus[this.childParents[this.branches[i]]])) { this.toggleBranch(this.branches[i], true, true); } else { this.branchStatus[this.branches[i]] = true; this.swapImage(this.branches[i]); } } } } /** * Javascript mini implementation of sprintf() */ function sprintf(strInput) { var strOutput = ''; var currentArg = 1; for (var i=0; i<strInput.length; i++) { if (strInput.charAt(i) == '%' && i != (strInput.length - 1) && typeof(arguments[currentArg]) != 'undefined') { switch (strInput.charAt(++i)) { case 's': strOutput += arguments[currentArg]; break; case '%': strOutput += '%'; break; } currentArg++; } else { strOutput += strInput.charAt(i); } } return strOutput; } function explode(seperator, input) { var output = []; var tmp = ''; skipEmpty = arguments[2] ? true : false; for (var i=0; i<input.length; i++) { if (input.charAt(i) == seperator) { if (tmp == '' && skipEmpty) { continue; } else { output[output.length] = tmp; tmp = ''; } } else { tmp += input.charAt(i); } } if (tmp != '' || !skipEmpty) { output[output.length] = tmp; } return output; } function implode(seperator, input) { var output = ''; for (var i=0; i<input.length; i++) { if (i == 0) { output += input[i]; } else { output += seperator + input[i]; } } return output; } function in_array(item, arr) { for (var i=0; i<arr.length; i++) { if (arr[i] == item) { return true; } } return false; }
/** * Created by Evgi on 10/24/2017. */ import React from 'react' export default class AnswerFrame extends React.Component{ render() { var numbers = []; var alreadySelected = this.props.property1; var unselectFunction = this.props.clickWrongAnswer; alreadySelected.forEach(function (selected) { numbers.push( <div key={selected} className="well"> <div className="number" onClick={unselectFunction.bind(null,selected)}>{selected}</div> </div> ) }); return ( <div id="answer-frame"> {numbers} </div> ) } };
import initAnimation from "./sarcasnimation.js"; const d = document, w = window; const toggleButtonMenu = (evt, $menu) => { if ($menu.classList.contains("show")) { iconButtonMenu.classList.remove("fa-bars"); iconButtonMenu.classList.add("fa-times"); } else { iconButtonMenu.classList.add("fa-bars"); iconButtonMenu.classList.remove("fa-times"); } }; document.addEventListener("DOMContentLoaded", (e) => { const $nav = d.querySelector(".nav"); initAnimation(); d.addEventListener("click", (evt) => { // console.log(evt.target); if (evt.target.dataset.trigger == "buttonMenu") { const $menu = d.getElementById(evt.target.dataset.collapsed); $menu.classList.toggle("show"); toggleButtonMenu(evt, $menu); } if (evt.target.matches(".ads__promo")) { d.querySelector(".adsbox").classList.add("show"); } if ( evt.target.matches("#buttonCloseModal") || evt.target.matches(".adsbox") || evt.target.matches(".adsbox__container") ) { d.querySelector(".adsbox").classList.remove("show"); } }); //Eventos de Scroll para el menu w.addEventListener("scroll", (evt) => { if (w.innerWidth > 580) { if ( w.scrollY + $nav.offsetHeight > d.querySelector(".header__heading").offsetTop ) { // console.log("dark", w.scrollY, $nav.offsetHeight); $nav.classList.add("dark"); } else { // console.log("claro", w.scrollY, $nav.offsetHeight); $nav.classList.remove("dark"); } } }); });
import styled from "styled-components"; const PostTitle = styled.h1` text-align: center; font-size: ${props => props.theme.fontSizes.sizeFive}; font-weight: bold; `; const StyledDate = styled.p` text-align: center; margin: 18px 0; color: ${props => props.theme.colors.black.tertiaryBlack}; font-size: ${props => props.theme.fontSizes.sizeOne}; `; const StyledImage = styled.img` max-width: 100%; `; const CoverImage = styled.img` max-width: 100%; margin-bottom: 20px; ` const BlogContainer = styled.main` color: ${props => props.theme.colors.black.quartenaryBlack}; font-size: ${props => props.theme.fontSizes.sizeThree}; line-height: 1.4; `; const Tags = styled.div` display: flex; color: ${props => props.theme.colors.black.tertiaryBlack}; `; const TagList = styled.ul` display: flex; white-space: pre-wrap; `; const TagItem = styled.li` &:hover { color: ${props => props.theme.colors.purple.primaryPurple}; cursor: pointer; } &::after { content: ', '; color: ${props => props.theme.colors.black.tertiaryBlack}; } &:last-child { &::after { content: ''; } } transition: color .2s linear; `; const BlogContent = styled.section` p { font-size: ${props => props.theme.fontSizes.sizeThree}; margin-bottom: 10px; } h2 { font-size: ${props => props.theme.fontSizes.sizeFour}; font-weight: bold; margin: 10px 0; } p code { font-family: 'Roboto Mono', monospace; font-size: ${props => props.theme.fontSizes.sizeThree}; display: inline-block; width: 100%; background-color: ${props => props.theme.colors.black.secondaryBlack}; border-radius: 4px; padding: 5px 10px; white-space: pre-wrap; } `; export { PostTitle, StyledDate, StyledImage, CoverImage, BlogContainer, TagList, Tags, TagItem, BlogContent };
import React, { useState, useEffect } from 'react'; import './App.css'; function App() { const [pokemon, setPokemon] = useState([]); useEffect(() => { fetchData() }); function fetchData() { fetch('https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json') .then(resp => { return resp.json() }) .then(data => { setPokemon(data.pokemon) }) } return ( <div className="App"> {pokemon.map(pokemon => { return ( <p>{pokemon.name}</p> ) })} </div> ); } export default App;
import logo from "./logo.png" import './estilos.css' const Home = () => { return ( <div className="principal fundo-escuro"> <div> <h1>LUNA PET SHOP</h1> <img alt="Logo da Pet" src={logo}></img> <h2>A melhor loja de Pet da região!!</h2> <h4>Endereço: R. Jardel Hottz - Parque Sao Clemente, Nova Friburgo - RJ, 28625-180</h4> </div> </div> ); } export default Home
var config = require('../config.json'), DataSift = require('datasift'), tracker = require('./tracker'); module.exports = { consumer: null, sourceBrands: new Array(), // Connects to DataSift streaming API start: function() { console.log("Connecting to DataSift API."); $this = this; this.consumer = new DataSift(config.datasift.username, config.datasift.apikey); this.consumer.on("connect", this.on_connected); this.consumer.on("interaction", this.on_interaction.bind(this)); this.consumer.connect(); }, // On connected event, susbribe to stream on_connected: function() { console.log("Connected to DataSift API."); $this.consumer.subscribe(config.datasift.stream); }, // When an interaction (piece of content) is received, track the appropriate events on_interaction: function(data) { try { tracker.trackEvents(data.data); } catch(err) { console.log("WARNING: Failed to process interaction: " + err.stack); } } };
$(document).ready(function(){ // Menu scroll $(window).scroll(function(){ if(this.scrollY > 20){ $(".navbar").addClass("sticky") }else{ $(".navbar").removeClass("sticky") } if(this.scrollY > 500){ $(".scroll-up-btn").addClass("show") }else{ $(".scroll-up-btn").removeClass("show") } }) // Slide-up $(".scroll-up-btn").click(function(){ $("html").animate({scrollTop:0}) $('html').css("scrollBehavior", "auto") }) $('.navbar .menu li a').click(function(){ $('html').css("scrollBehavior", "smooth") }); // Toggle Menu $(".menu-btn").click(function(){ $(".navbar .menu").toggleClass("active") $(".menu-btn i").toggleClass("active") }) // Typing new Typed(".typing",{ strings:["Desarrollador Web","Programador"], typeSpeed:100, backSpeed:60, loop:true }) new Typed(".typing-2", { strings:["Desarrollador Web","Programador"], typeSpeed: 100, backSpeed: 60, loop: true }); //Vanilla Tilt VanillaTilt.init(document.querySelector(".curriculum") ,{ max:25, speed:400, glare:true, "max-glare":1 }) //Text oculto $(".skills .skills-content .left .text2").toggle(); $(".skills .skills-content .left .despliegue").click(function(){ $(".skills .skills-content .left .text2").animate({ height: "toggle" }, 300); ($(".skills .skills-content .left .despliegue").text() == "Desplegar") ? $(".skills .skills-content .left .despliegue").text("Ocultar") : $(".skills .skills-content .left .despliegue").text("Desplegar"); }) // owl carousel $('.carousel').owlCarousel({ margin: 20, loop: true, autoplayTimeOut: 2000, autoplayHoverPause: true, responsive: { 0:{ items: 1, nav: false }, 600:{ items: 2, nav: false }, 1000:{ items: 3, nav: false } } }); })
var group___bias_modes = [ [ "HMC_BIAS_NEGATIVE", "group___bias_modes.html#ga7698c66ff164b76fbb22630762470d0a", null ], [ "HMC_BIAS_NONE", "group___bias_modes.html#ga9ae8e2b4da80627c555a1ed3747ebc10", null ], [ "HMC_BIAS_POSITIVE", "group___bias_modes.html#gaf14afb57269789d0f8d2a1b58bb1a8b4", null ] ];
import regeneratorRuntime from '../../../lib/regenerator-runtime' import { connect } from '../../../lib/wechat-weapp-redux' import { fetching, fetchend, clearError } from '../../../store/actions/loader' import { fetchProfile, fetchDailySign, postDailySign, fetchGroupCoupon } from '../../../store/actions/mine' import { navigateErrorPage, alertError } from '../../../utils' import { USER_ROLE, DAILY_SIGN } from '../../../constants' import { postGroupCoupon } from '../../../api/mine' const store = getApp().store const mapStateToData = state => ({ displayError: state.loader.displayError, profile: state.mine.profile, USER_ROLE, DAILY_SIGN, groupId: state.global.group.id, dailySign: state.dailySign, groupCoupon: state.mine.groupCoupon }) const mapDispatchToPage = dispatch => ({ clearError: _ => dispatch(clearError()), fetching: _ => dispatch(fetching()), fetchend: _ => dispatch(fetchend()), fetchProfile: isRefresh => dispatch(fetchProfile(isRefresh)), fetchDailySign: id => dispatch(fetchDailySign(id)), postDailySign: id => dispatch(postDailySign(id)), fetchGroupCoupon: id => dispatch(fetchGroupCoupon(id)) }) const pageConfig = { data: { loading: true, dailySignModal: false, signSuccessModal: false, GroupCouponModal:false, GroupCouponSuccessModal:false }, async onLoad () { await this.fetchProfile(true) this.setData({ loading: false }) }, onShow () { const { loading } = this.data if (!loading && !store.getState().mine.profile) this.onLoad() }, async getSign () { const { groupId } = this.data this.fetching() await this.fetchDailySign(groupId) this.setData({ dailySignModal: true }) this.fetchend() }, async postSign () { const { groupId } = this.data this.fetching() const isSuccess = await this.postDailySign(groupId) if (isSuccess) { this.setData({ dailySignModal: false, signSuccessModal: true, }) } this.fetchend() }, async gift () { this.fetching() const { groupId } = this.data await this.fetchGroupCoupon(groupId) if (this.data.groupCoupon.isReceive == 1) { this.setData({ GroupCouponModal:true, GroupCouponSuccessModal:true }) } else { this.setData({ GroupCouponModal:true }) } this.fetchend() }, async closeCouponModal () { this.fetching() if (this.data.GroupCouponModal == true && this.data.GroupCouponSuccessModal == false) { const { groupId } = this.data await postGroupCoupon(groupId) this.setData({ GroupCouponModal:false, GroupCouponSuccessModal:true }) } else if(this.data.GroupCouponModal == false && this.data.GroupCouponSuccessModal == true) { this.setData({ GroupCouponModal:false, GroupCouponSuccessModal:false }) }else if(this.data.GroupCouponModal == true && this.data.GroupCouponSuccessModal == true) { this.setData({ GroupCouponModal:false, GroupCouponSuccessModal:false }) } this.fetchend() }, closeGroupCoupon () { this.fetching() this.setData({ GroupCouponModal:false, GroupCouponSuccessModal:false }) this.fetchend() }, closeDailySignModal () { this.setData({ dailySignModal: false }) }, closeSignSuccessModal () { this.setData({ signSuccessModal: false }) }, gotoLuckDraw (event) { const { groupId } = this.data wx.navigateTo({ url: `/pages/mine/luckDraw/luckDraw?id=${groupId}`}) }, reload () { this.clearError() this.onLoad() }, onUnload () { this.clearError() } } Page( connect( mapStateToData, mapDispatchToPage )(pageConfig) )
var Stack = function() { // Hey! Rewrite in the new style. Your code will wind up looking very similar, // but try not not reference your old code in writing the new style. var someInstance = {}; someInstance.items = 0; someInstance.storage = {}; //add properties from stackMethods to someInstance _.extend(someInstance, stackMethods); return someInstance; }; var stackMethods = { size: function() { if ( this.items < 0 ) { this.items = 0; } return this.items; }, push: function(value) { this.storage[this.items] = value; this.items++; }, pop: function() { this.items--; var lastItem = this.storage[this.items]; delete this.storage[this.items]; return lastItem; } };
//During the test the env variable is set to test process.env.NODE_ENV = 'test'; //Require the dev-dependencies let chai = require('chai'); let chaiHttp = require('chai-http'); let server = require('../server'); let should = chai.should(); chai.use(chaiHttp); //Our parent block describe('Hello API', () => { /* * Test the /GET route */ describe('/Hello API', () => { it('it should GET /', (done) => { chai.request(server) .get('/') .end((err, res) => { res.should.have.status(200); res.body.should.have.property('core'); res.body.should.have.property('version'); res.body.should.have.property('date'); done(); }); }); it('it should GET 404 trying to access an invalid endpoint', (done) => { chai.request(server) .get('/blah') .end((err, res) => { res.should.have.status(404); res.body.should.have.property('error'); res.body.should.have.property('error').to.be.equal('URL not found') res.body.should.have.property('message'); done(); }); }); it('it should GET Hello API with an invalid request param', (done) => { chai.request(server) .get('/api/v1/hello/cpf') .end((err, res) => { res.should.have.status(400); res.body.should.have.property('error'); res.body.should.have.property('message'); done(); }); }); it('it should GET Hello API using valid request params', (done) => { chai.request(server) .get('/api/v1/hello/39421298764') .end((err, res) => { res.should.have.status(200); res.body.should.have.property('code'); res.body.should.have.property('message'); done(); }); }); it('it should GET Hello API using valid request params, but forcing a business error', (done) => { chai.request(server) .get('/api/v1/hello/11111111111') .end((err, res) => { res.should.have.status(404); res.body.should.have.property('error'); res.body.should.have.property('message'); done(); }); }); }); });
'use strict' const mongoose = require('mongoose'), Schema = mongoose.Schema let pollSchema = new Schema({ name: String, labels: Array, data: Array }) let Poll = module.exports = mongoose.model('Poll', pollSchema)
import { useState } from 'react'; import './App.css'; import ColorBox from './conponents/ColorBox'; import TodoList from './conponents/TodoList'; function App() { const [todoList, setTodoList] = useState([ { id: 1, title: '1. tittle 1' }, { id: 2, title: '2. tittle 2' }, { id: 3, title: '3. tittle 3' }, ]) const handleTodoClick = (item) => { console.log(item) const index = todoList.findIndex(x => x.id === item.id) if(index < 0) return; //clone arrray const newTodoList= [...todoList] newTodoList.splice(index, 1) setTodoList(newTodoList) } return ( <div className="App"> <h1>React hooks - To Do List</h1> {/* <ColorBox /> */} <TodoList todoProps={todoList} onTodoClick={handleTodoClick} /> </div> ); } export default App;
import { lerp, EPSILON } from "./math.js"; export class Vector3 { static ZERO = new Vector3(0, 0, 0); static UP = new Vector3(0, 1, 0); constructor(x = 0, y = 0, z = 0) { this.set(x, y, z); } set(x, y, z) { this.x = x; this.y = y; this.z = z; return this; } copy(from) { this.set(from.x, from.y, from.z); return this; } clone() { return new Vector3().copy(this); } toArray(destination = undefined) { if (destination === undefined) destination = new Array(); destination.push(this.x, this.y, this.z); return destination; } magnitude(abs = true) { let result = Math.hypot(this.x, this.y, this.z); if (abs) result = Math.abs(result); return result; } magnitudeSquared() { return Math.pow(this.x, 2) + Math.pow(this.y, 2) + Math.pow(this.z, 2); } add(other) { this.x += other.x; this.y += other.y; this.z += other.z; return this; } sub(other) { this.x -= other.x; this.y -= other.y; this.z -= other.z; return this; } mul(other) { this.x *= other.x; this.y *= other.y; this.z *= other.z; return this; } mulScalar(scalar) { this.x *= scalar; this.y *= scalar; this.z *= scalar; return this; } div(other) { this.x /= other.x; this.y /= other.y; this.z /= other.z; return this; } divScalar(scalar) { this.x /= scalar; this.y /= scalar; this.z /= scalar; return this; } ceil(ceilTo) { this.x = Math.ceil(ceilTo.x); this.y = Math.ceil(ceilTo.y); this.z = Math.ceil(ceilTo.z); return this; } floor(floorTo) { this.x = Math.floor(floorTo.x); this.y = Math.floor(floorTo.y); this.z = Math.floor(floorTo.z); return this; } min(minTo) { this.x = Math.min(this.x, minTo.x); this.y = Math.min(this.y, minTo.y); this.z = Math.min(this.z, minTo.z); return this; } max(maxTo) { this.x = Math.max(this.x, maxTo.x); this.y = Math.max(this.y, maxTo.y); this.z = Math.max(this.z, maxTo.z); return this; } round(roundTo) { this.y = Math.round(roundTo.y); this.x = Math.round(roundTo.x); this.z = Math.round(roundTo.z); return this; } dist(other) { return Math.hypot(other.x - this.x, other.y - this.y, other.z - this.z); } distSquared(other) { return Math.pow(other.x - this.x, 2) + Math.pow(other.y - this.y, 2) + Math.pow(other.z - this.z, 2); } negate() { this.set(-this.x, -this.y, -this.z); return this; } inverse() { this.x = 1 / this.x; this.y = 1 / this.y; this.z = 1 / this.z; return this; } normalize() { this.divScalar(this.magnitude()); return this; } dot(other) { return this.x * other.x + this.y * other.y + this.z * other.z; } cross(a, b) { this.set(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); return this; } lerp(to, by) { this.x = lerp(this.x, to.x, by); this.y = lerp(this.y, to.y, by); this.z = lerp(this.z, to.z, by); return this; } angle(other) { let mag = this.magnitude() * other.magnitude(); let cosine = mag && this.dot(other) / mag; return Math.acos(Math.min(Math.max(cosine, -1), 1)); } rotate(around = Vector3.ZERO, byRadianAngles) { let offsetX = this.x - around.x; let offsetY = this.y - around.y; let offsetZ = this.z - around.z; throw "Not implemented yet"; return this; } copyFromMatrix4x4Pos(from) { this.x = from.data[12]; this.y = from.data[13]; this.z = from.data[14]; return this; } copyFromMatrix4x4Scale(from) { this.set(Math.hypot(from.data[0], from.data[1], from.data[2]), Math.hypot(from.data[4], from.data[5], from.data[6]), Math.hypot(from.data[8], from.data[9], from.data[10])); return this; } copyFromQuaternionAxisAngle(from) { let rad = Math.acos(from.w) * 2; let s = Math.sin(rad / 2); if (s > EPSILON) { this.x = from.x / s; this.y = from.y / s; this.z = from.z / s; } else { // If s is zero, return any axis (no rotation - axis does not matter) this.x = 1; this.y = 0; this.z = 0; } return this; } }
const { CodeExecutor } = require('code-executor'); const codeExecutor = new CodeExecutor('myExecutor', process.env.REDIS_URL); const executeCode = async (language, code, testCases) => { const input = { language, code, testCases, timeout: 2, }; const results = await codeExecutor.runCode(input); return results; }; module.exports = executeCode;
function ContextTree(value) { if(!(this instanceof ContextTree)) { return new ContextTree(value) } this.root = createNode(value || {}) } module.exports = ContextTree ContextTree.prototype.set = function (path, value) { var parent = this.getParent(path, true) if(!parent) { updateNode(this.root, value, null) return } var key = path[path.length - 1] var children = parent.children if(children[key]) { updateNode(children[key], value, parent) return } children[key] = createNode(value, parent) } function setProps(obj, objB) { for (var prop in objB) { obj[prop] = objB[prop] } return obj } /** * Get the best node (node or nearest parent) and return its .value * */ ContextTree.prototype.get = function (path) { path = path || [] if(path.length < 1) { return this.root.value } var branch = this.root var child var token for (var i = 0, len = path.length; i < len; i++) { token = path[i] child = branch.children if(!child[token]) { break } branch = child[token] } if(!branch) { return null } return branch.protoValue } ContextTree.prototype.getParent = function(path, ensureExists) { if(!path || path.length < 1) return null if(path.length < 2) { return this.root } return path.slice(0, -1).reduce(function (branch, token) { if(!branch) { return branch } var children = branch.children if(!children[token] && ensureExists) { children[token] = createNode() } return children[token] }, this.root) } function updateNode(node, value, parent) { node.value = value || {} if(parent) { node.protoValue = setProps(Object.create(parent.protoValue), node.value) } else { node.protoValue = node.value } for (var prop in node.children) { var child = node.children[prop] node.children[prop] = updateNode(child, child.value, node) } return node } function createNode(value, parent) { return updateNode({ children: {} }, value, parent) }
function runTest() { var pageURI = basePath + "net/1308/issue1308.html"; var scriptURI = basePath + "net/1308/issue1308.js"; FBTest.openNewTab(pageURI, function(win) { FBTest.enableNetPanel(function(win) { win.runTest(checkCopyLocationWithParametersAction); }); }); } function checkCopyLocationWithParametersAction(request) { // Expand the test request with params var panel = FBTest.selectPanel("net"); var netRow = FW.FBL.getElementByClass(panel.panelNode, "netRow", "category-xhr", "hasHeaders", "loaded"); if (!netRow) { FBTest.ok(false, "There must be a XHR entry within the Net panel."); return FBTest.testDone(); } // Test the "Copy Location With Parameters action" available in the context menu // for specific Net panel entry. panel.copyParams(netRow.repObject); // Get data from the clipboard. var clipboard = FW.FBL.CCSV("@mozilla.org/widget/clipboard;1", "nsIClipboard"); var trans = FW.FBL.CCIN("@mozilla.org/widget/transferable;1", "nsITransferable"); trans.addDataFlavor("text/unicode"); clipboard.getData(trans, Ci.nsIClipboard.kGlobalClipboard); var str = new Object(); var strLength = new Object(); trans.getTransferData("text/unicode", str, strLength); str = str.value.QueryInterface(Ci.nsISupportsString); var actual = str.data.substring(0, strLength.value / 2); // Complete expected result. var requestUri = FBTest.getHTTPURLBase() + "net/1308/issue1308.txt"; var expected = requestUri + "?param1=1%20%2B%202"; // Verification. FBTest.compare(expected, actual, "Verify that the copied URL is properly encoded."); // Finish test FBTest.testDone(); }
// controller for the new object modal Discourse.KbObjNewController = Discourse.ObjectController.extend(Discourse.ModalFunctionality, { // whether the submission process is complete done: false, flashMessage: null, saving: false, objPage: null, relatedHeading: function() { var self = this; return I18n.t('diaedu.' + self.get('model.preferredParentDataType.shortName') + '.related_heading'); }.property('model.preferredParentDataType'), onShow: function() { var self = this; self.set('done', false); // get the parent's datatype and request an obj page var dataType = self.get('model.preferredParentDataType'); if (dataType) Discourse.KbObjPage.find({dataType: dataType, filterParams: 'all', pageNum: 1, perPage: 1000000000}).then(function(objPage){ self.set('objPage', objPage); }); }, actions: { save: function() { var self = this; self.set('saving', true); self.get('model').save().then(function(success) { // set the done variable so the modal changes if (success) self.set('done', true); // turn off the loading indicator self.set('saving', false); }); } } });
"use strict"; angular.module("demoApp", ['ui.bootstrap', 'angular.directives']); angular.module("demoApp") .controller("DemoCtrl", [function() { this.welcome="Angular Really Click Demo"; this.ok = function() { alert("Do Action!"); }; this.cancle = function() { alert("Cancle"); }; }]);
/* eslint-disable import/prefer-default-export */ // import { toastr } from 'react-redux-toastr'; import axios from 'axios'; import { toastr } from 'react-redux-toastr'; import C from '../constants/actions'; import config from '../config'; export const fetchTimezones = () => dispatch => { axios({ method: 'get', url: `${config.api.serverUrl}/v1/timezone`, headers: { [config.apiKeyHeader]: config.apiKey, }, }) .then(res => { if (res.status === 200) { dispatch({ type: C.SET_TIME_ZONES, payload: res.data, }); } }) .catch(err => { if (err.response && err.response.data.error) { toastr.error( err.response.data.error.title, err.response.data.error.description, ); } }); }; export const updateTimezone = timezoneId => (dispatch, getState) => { const lastTimezoneId = getState().userInfo.profile.timezoneId; // update currency client side dispatch({ type: C.UPDATE_USER_PROFILE, payload: { timezoneId }, }); axios({ method: 'post', url: `${config.api.serverUrl}/v1/user/timezone/${timezoneId}`, headers: { authorization: getState().userInfo.authToken, [config.apiKeyHeader]: config.apiKey, }, }) .then(res => { if (res.status !== 200) { dispatch({ type: C.UPDATE_USER_PROFILE, payload: { timezoneId: lastTimezoneId }, }); } }) .catch(err => { // role back in case of server error dispatch({ type: C.UPDATE_USER_PROFILE, payload: { timezoneId: lastTimezoneId }, }); if (err.response.data.error) { toastr.error( err.response.data.error.title, err.response.data.error.description, ); } }); };
({ doAction : function(component) { var input1 = component.find("check1"); var input2 = component.find("check2"); var input3 = component.find("check3"); var input4 = component.find("check4"); //alert(input1); var value1 = input1.get("v.value"); var value2 = input2.get("v.value"); var value3 = input3.get("v.value"); var value4 = input4.get("v.value"); //alert(value1); if (value1 === false || value2=== false || value3=== false || value4=== false) { component.set("v.alertMessage","Please make sure to select all the items for member verification."); $A.util.removeClass(component.find('msg-id'), 'hideContent'); } else { // input.set("v.errors", null); $A.util.addClass(component.find('msg-id'), 'hideContent'); var action = component.get("c.createtask"); action.setParams({ 'memberId': component.get("v.MemberDetails.MemberId") }); action.setCallback(this, function(response) { var state = response.getState(); if (state === "SUCCESS") { var toastEvent = $A.get("e.force:showToast"); toastEvent.setParams({ "title": "Success!", "message": "Member is Verified. Task is created" }); toastEvent.fire(); component.getEvent('sendtoParent').setParams({ memberdetails : component.get("v.MemberDetails"), type : 'MemberDetails', spinner : component.get("v.showSpinner") }).fire(); } }); $A.enqueueAction(action); } }, handleError: function(component, event){ var errorsArr = event.getParam("errors"); for (var i = 0; i < errorsArr.length; i++) { console.log("error " + i + ": " + JSON.stringify(errorsArr[i])); } }, handleClearError: function(component, event) { }, doinit : function(component, event, helper) { console.log('Member Verification'+component.get("v.MemberDetails")); } })
//Written by Nabanita Maji and Cliff Shaffer, March 2015 /*global ODSA */ $(document).ready(function() { "use strict"; var input; var iparr; var pair1; var pair2; var pair11; var pair21; var pairs; var oparr; var paired; var line1; var yoffset = 20; var av_name = "sortToPairCON"; var jsav = new JSAV(av_name); // Slide 1 jsav.umsg("Sorting of a given array by reducing it to Pairing problem."); jsav.displayInit(); jsav.step(); // Slide 2 input = new Array(23,42,17,93,88,12,57,90); iparr = jsav.ds.array(input, {left: 230, top: -8 + yoffset,indexed:true}); for(var i=0;i<8;i++) iparr.css(i,{"background-color":"AntiqueWhite"}); jsav.label("<b>Array to be sorted</b>",{left: 290, top: -28 + yoffset}); jsav.step(); // Slide 3 jsav.umsg("Transformation step to reduce into pairing problem"); var l1= jsav.g.line(355,40 + yoffset,355,83 + yoffset); l1.show(); jsav.label("<b>Transformation (Cost=O(n))</b>",{left: 375, top: 45 + yoffset}); var r1 = jsav.g.rect(80,85 + yoffset,550,45); r1.show(); jsav.step(); // Slide 4 jsav.umsg("The Input array and Position array is given as an input to the Pairing problem. The Position array contains a value <i>k</i> at the k<sup>th</sup> index"); pair1 = jsav.ds.array([0,1,2,3,4,5,6,7], {left: 90 , top: 75 + yoffset}); for(var i=0;i<8;i++) pair1.css(i,{color:"blue","background-color":"WhiteSmoke"}); jsav.label("Position <br>array",{left: 20, top: 75 + yoffset}); pair2 = jsav.ds.array(input, {left: 370, top: 75 + yoffset}); for(var i=0;i<8;i++) pair2.css(i,{"background-color":"AntiqueWhite"}); jsav.label("Input <br>array",{left: 640, top: 75 + yoffset}); jsav.step(); // Slide 5 jsav.umsg("The two arrays are fed into the Pairing problem as input"); jsav.label("<b>Pairing</b>",{left: 375, top: 120 + yoffset}); var l2= jsav.g.line(355,130 + yoffset,355,160 + yoffset); l2.show(); var r2 = jsav.g.rect(215,160 + yoffset,280,110); r2.show(); jsav.step(); // Slide 6 jsav.umsg("Pairing problem is to be solved on the two arrays"); pair11 = jsav.ds.array([0,1,2,3,4,5,6,7], {left: 230 , top: 152 + yoffset}); for(var i=0;i<8;i++) pair11.css(i,{color:"blue","background-color":"WhiteSmoke"}); pair21 = jsav.ds.array(input, {left: 230, top: 212 + yoffset}); for(var i=0;i<8;i++) pair21.css(i,{"background-color":"AntiqueWhite"}); jsav.step(); // Slide 7 jsav.umsg("Pairing problem is solved on the two arrays"); pairs = new Array([23,2],[42,3],[17,1],[93,7],[88,5],[12,0],[57,4],[90,6]); var pairing = new Array(); for(var i=0;i<8;i++){ var x2=i*30+250; var x1=pairs[i][1]*30+250; pairing[i]=jsav.g.line([x1,197 + yoffset,x2,229 + yoffset]); pairing[i].show(); } jsav.step(); jsav.umsg("Pairing problem is solved on the two arrays"); var l3= jsav.g.line(355,270 + yoffset,355,300 + yoffset); l3.show(); jsav.label("<b>Pairs generated</b>",{left: 375, top:260 + yoffset}); paired = jsav.ds.array(pairs,{left: 194, top: 285 + yoffset}); for(var i=0;i<8;i++) paired.css(i,{"width":"40px","min-width":"40px"}); jsav.step(); jsav.umsg("Reverse transformation: " +"In each pair, the second number determines the position of the first in Output Array"); var l4= jsav.g.line(355,330 + yoffset,355,360 + yoffset); l4.show(); jsav.label("<b>Reverse Transformation Cost=O(n)</b>",{left: 375,top: 320 + yoffset}); var r1 = jsav.g.rect(215,360 + yoffset,280,80); r1.show(); oparr= jsav.ds.array([" "," "," "," "," "," "," "," "], {left: 230, top: 360 + yoffset,indexed:true}); for(var i=0;i<8;i++) oparr.css(i,{"background-color":"Snow"}); jsav.step(); oparr.show(); var curr; for(var i=0;i<8;i++){ if(i>0){ paired.unhighlight(i-1); oparr.unhighlight(curr); //oparr.css(curr,{"background-color":"ForestGreen"}); } var str=paired.value(i)+","; var arr=str.split(","); curr=arr[1]; curr=curr*1; oparr.value(curr,arr[0]); paired.highlight(i); oparr.highlight(curr); jsav.umsg("Placing "+arr[0]+" at "+curr); jsav.step() } paired.unhighlight(i-1); oparr.unhighlight(curr); jsav.umsg("The output array gives the sorted array" ); jsav.step(); var l5= jsav.g.line(495,412 + yoffset,522,412 + yoffset); jsav.label("<b>Output</b>",{left: 620,top: 410 + yoffset}); var op= jsav.ds.array([" "," "," "," "," "," "," "," "], {left: 520, top: 380 + yoffset}); for(var i=0;i<8;i++) op.value(i,oparr.value(i)); for(var i=0;i<8;i++) op.css(i,{"background-color":"#CCFF99"}); jsav.umsg("Total cost of sorting = O(n) + Cost of Pairing"); jsav.step(); jsav.recorded(); });
import { useState, useEffect } from "react"; import Head from "next/head"; import { useRouter } from "next/router"; import { getCurrentUser } from "../components/utils/utils.current-user"; const MainPage = () => { const [currentUser, setCurrentUser] = useState(getCurrentUser()); const router = useRouter(); useEffect(() => { if (currentUser) { return router.push(`/${currentUser.userID}/1`); } return router.push("/signin"); }, []); return ( <div> <Head> <meta name="description" content="This is an application where users can create polls. Any user that has an account can vote on the polls. A poll can be open in which anyone can vote or private which requires a password to vote." /> <meta name="keywords" content="polle, poll, polls, private polls, open polls, vote" /> </Head> </div> ); }; export default MainPage;
$(document).ready(function () { commonScroll(".left-side"); //Load currency symbol var currency = JSON.parse($('#hdSettings').val()).CurrencySymbol; $('.currency').html(currency); $(document).on('click', '.filter-data', function () { var customerId = $('#ddlCustomer').val() == '0' ? null : $('#ddlCustomer').val(); var fromDate = $('#txtDate').data('daterangepicker').startDate.format('YYYY-MMM-DD'); var toDate = $('#txtDate').data('daterangepicker').endDate.format('YYYY-MMM-DD'); refreshTable(customerId, fromDate, toDate); }) refreshTable(null, null, null); //Function for loading list of orders function refreshTable(customerId, fromDate, toDate) { $.ajax({ url: $('#hdApiUrl').val() + 'api/JobCard/get?customerid=' + customerId + '&from=' + fromDate + '&to=' + toDate, method: 'POST', contentType: 'application/json;charset=utf-8', dataType: 'JSON', data: JSON.stringify($.cookie('bsl_2')), success: function (data) { $('#invoiceList').DataTable().destroy(); $('#invoiceList tbody').empty(); if (data == null || data.length <= 0) { $('#invoiceList tbody').children().remove(); $('.empty-state-wrap').show(); return; } else { $('.empty-state-wrap').hide(); } var html = ''; var count = 0; $(data).each(function (index) { count++; html += '<tr>'; html += '<td style="display:none">' + this.ID + '</td>'; html += '<td class="show-on-collapsed">' + this.JobCardNumber + '</td>'; html += '<td class="show-on-collapsed">' + this.EntryDateString + '</td>'; html += '<td>' + this.CustomerName + '&nbsp;' + this.CustMiddleName + '&nbsp;' + this.CustLastName + '</td>'; html += '<td style="text-align:right">' + this.TaxAmount + '</td>'; html += '<td style="text-align:right">' + this.Gross + '</td>'; html += '<td class="show-on-collapsed" style="text-align:right">' + this.NetAmount + '</td>'; html += '<td class="hidden">' + this.CustomerLandLine + '</td>'; html += '<td class="hidden">' + this.CustomerMob + '</td>'; html += '<td class="hidden">' + this.EmiratesId + '</td>'; html += '<td class="hidden">' + this.VehicleNumber + '</td>'; html += '</tr>'; }); $('#invoiceList tbody').children().remove(); $('#countOfInvoices').text('(' + count + ')'); $('#invoiceList tbody').append(html); //Initing datatable after loading data into table //$('#invoiceList').DataTable(); $('#invoiceList').dataTable({ destroy: true, aaSorting: [], "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]], "language": { "paginate": { "previous": "<<", "next": ">>" } } }); }, error: function (err) { alert(err.responseText); }, beforeSend: function () { loading('start') }, complete: function () { loading('stop')} }); } $('input[name="daterange"]').daterangepicker({ "opens": "left", "startDate": moment().subtract(1, 'month'), "endDate": moment(), "alwaysShowCalendars": false, locale: { format: 'DD MMM YYYY' }, ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], //'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(1, 'month').subtract(0, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] } }); //Toggle list info when list is clicked listingInfoInit('.left-side table tbody tr', (e) => { $.ajax({ url: $('#hdApiUrl').val() + 'api/JobCard/get/' + id, method: 'POST', contentType: 'application/json;charset=utf-8', dataType: 'JSON', data: JSON.stringify($.cookie('bsl_2')), success: function (data) { $('#hdRegisterId').val(data.ID); $('#hdnCustomerID').val(data.CustomerId); if (data.ApprovedStatus == 1) { $('#ApproveStatus').removeClass('warning'); $('#ApproveStatus').show(); $('#ApproveStatus').addClass('success'); $('#ApproveStatusText').text("Approved"); $('#btnApproval').hide(); } else { $('#ApproveStatus').removeClass('success'); $('#ApproveStatus').show(); $('#ApproveStatus').addClass('warning'); $('#ApproveStatusText').text("Not Approved"); $('#btnApproval').show(); } if (data.Status == 1) { $('#btnJobCard').addClass('hidden'); } else if (data.Status == 0) { $('#btnJobCard').removeClass('hidden'); } //$('#hdEmail').val(data.Insurance_Email); //$('#hdEmail').val(data.Insurance[0].Email); $('#lblCustName').html(data.CustomerName + '&nbsp;' + data.CustMiddleName + '&nbsp;' + data.CustLastName); $('#lblCustAddr1').text(data.CustomerAddress1); $('#lblCustAddr2').text(data.CustomerAddress2); $('#lblCustphone').text(data.CustomerLandLine); $('#lblCustTaxNo').text(data.CustomerTaxNo); $('#lblDate').text(data.EntryDateString); $('#lblInvoiceNo').text(data.JobCardNumber); $('#listTable tbody').children().remove(); //alert(data.Insurance_Email); //$('#ddlMailAddress').val(data.Insurance_Email); $(data.Products).each(function () { if (this.IsService == true) { if ($('#listTable').children('tbody').find('.estimate-service').length == 0) { html = '<tr class="estimate-service"><td colspan="7">Service</td></tr><tr><td class="item-id" style="display:none">' + this.ItemID + '</td><td class="item-code">' + this.ItemCode + '</td><td class="item-name"><b>' + this.Name + '</b></td><td class="item-qty">' + this.Quantity + '</td><td class="item-rate">' + this.SellingPrice + '</td><td style="text-align:right" class="item-tax">' + this.TaxAmount + '</td><td style="text-align:right" class="item-gross">' + this.Gross + '</td><td style="text-align:right" class="item-net">' + this.NetAmount + '</td><td class="item-perc" style="display:none">' + this.TaxPercentage + '</td><td class="item-instance" style="display:none">' + this.InstanceId + '</td><td class="item-scheme" style="display:none">' + this.SchemeId + '</td></tr>'; $('#listTable > tbody').append(html); } else { html = ''; html = '<tr><td class="item-id" style="display:none">' + this.ItemID + '</td><td class="item-code">' + this.ItemCode + '</td><td class="item-name"><b>' + this.Name + '</b></td><td class="item-qty">' + this.Quantity + '</td><td class="item-rate">' + this.SellingPrice + '</td><td style="text-align:right" class="item-tax">' + this.TaxAmount + '</td><td style="text-align:right" class="item-gross">' + this.Gross + '</td><td style="text-align:right" class="item-net">' + this.NetAmount + '</td><td class="item-perc" style="display:none">' + this.TaxPercentage + '</td><td class="item-instance" style="display:none">' + this.InstanceId + '</td><td class="item-scheme" style="display:none">' + this.SchemeId + '</td></tr>'; $(html).insertAfter('.estimate-service'); } } else if (this.TrackInventory == true) { if ($('#listTable').children('tbody').find('.estimate-spare').length == 0) { html = ''; html = '<tr class="estimate-spare"><td colspan="7">Spare</td></tr><tr><td class="item-id" style="display:none">' + this.ItemID + '</td><td class="item-code">' + this.ItemCode + '</td><td class="item-name"><b>' + this.Name + '</b></td><td class="item-qty">' + this.Quantity + '</td><td class="item-rate">' + this.SellingPrice + '</td><td style="text-align:right" class="item-tax">' + this.TaxAmount + '</td><td style="text-align:right" class="item-gross">' + this.Gross + '</td><td style="text-align:right" class="item-net">' + this.NetAmount + '</td><td class="item-perc" style="display:none">' + this.TaxPercentage + '</td><td class="item-instance" style="display:none">' + this.InstanceId + '</td><td class="item-scheme" style="display:none">' + this.SchemeId + '</td></tr>'; $('#listTable > tbody').append(html); } else { html = ''; html = '<tr><td class="item-id" style="display:none">' + this.ItemID + '</td><td class="item-code">' + this.ItemCode + '</td><td class="item-name"><b>' + this.Name + '</b></td><td class="item-qty">' + this.Quantity + '</td><td class="item-rate">' + this.SellingPrice + '</td><td style="text-align:right" class="item-tax">' + this.TaxAmount + '</td><td style="text-align:right" class="item-gross">' + this.Gross + '</td><td style="text-align:right" class="item-net">' + this.NetAmount + '</td><td class="item-perc" style="display:none">' + this.TaxPercentage + '</td><td class="item-instance" style="display:none">' + this.InstanceId + '</td><td class="item-scheme" style="display:none">' + this.SchemeId + '</td></tr>'; $(html).insertAfter('.estimate-spare'); } } else { if ($('#listTable').children('tbody').find('.estimate-consumables').length == 0) { html = ''; html = '<tr class="estimate-consumables"><td colspan="7">Consumable</td></tr><tr><td class="item-id" style="display:none">' + this.ItemID + '</td><td class="item-code">' + this.ItemCode + '</td><td class="item-name"><b>' + this.Name + '</b></td><td class="item-qty">' + this.Quantity + '</td><td class="item-rate">' + this.SellingPrice + '</td><td style="text-align:right" class="item-tax">' + this.TaxAmount + '</td><td style="text-align:right" class="item-gross">' + this.Gross + '</td><td style="text-align:right" class="item-net">' + this.NetAmount + '</td><td class="item-perc" style="display:none">' + this.TaxPercentage + '</td><td class="item-instance" style="display:none">' + this.InstanceId + '</td><td class="item-scheme" style="display:none">' + this.SchemeId + '</td></tr>'; $('#listTable > tbody').append(html); } else { html = ''; html = '<tr><td class="item-id" style="display:none">' + this.ItemID + '</td><td class="item-code">' + this.ItemCode + '</td><td class="item-name"><b>' + this.Name + '</b></td><td class="item-qty">' + this.Quantity + '</td><td class="item-rate">' + this.SellingPrice + '</td><td style="text-align:right" class="item-tax">' + this.TaxAmount + '</td><td style="text-align:right" class="item-gross">' + this.Gross + '</td><td style="text-align:right" class="item-net">' + this.NetAmount + '</td><td class="item-perc" style="display:none">' + this.TaxPercentage + '</td><td class="item-instance" style="display:none">' + this.InstanceId + '</td><td class="item-scheme" style="display:none">' + this.SchemeId + '</td></tr>'; $(html).insertAfter('.estimate-consumables'); } } }); $('#lblTotal').text(data.Gross); $('#lblTax').text(data.TaxAmount); $('#lblDiscount').text(data.Discount); $('#lblroundOff').text(data.RoundOff); $('#lblNet').text(data.NetAmount); $('#lblInvoiceAmount').text(data.NetAmount); }, error: function (xhr) { alert(xhr.responseText); }, beforeSend: function () { miniLoading('start', '.right-side'); }, complete: function () { miniLoading('stop', '.right-side'); }, }); }); //Loads The country for customer modal var CountryData; $.ajax({ type: "POST", url: $(hdApiUrl).val() + "api/customers/Getcountry?CompanyId=" + $.cookie('bsl_1'), contentType: "application/json; charset=utf-8", data: JSON.stringify($.cookie('bsl_1')), dataType: "json", success: function (data) { CountryData = data; }, failure: function () { } }); //Click event to trigger edit of customer $('.edit-cust').click(function () { LoadCustomer($('#hdnCustomerID').val()); }); $('#btnJobCard').on('click', function () { var EstID = $('#hdRegisterId').val(); window.location = '/Registration/JobCard?MODE=new&UID=' + EstID; }); function LoadCustomer(id) { $.ajax({ url: $('#hdApiUrl').val() + 'api/Customers/get?id=' + id, method: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'Json', data: JSON.stringify($.cookie("bsl_1")), success: function (response) { var customerModal = new Customer(CountryData, function () { refreshTable(null); }) customerModal.ID = response.ID; customerModal.Name = response.Name; customerModal.Salutation = response.Salutation; customerModal.Contact_Name = response.Contact_Name; customerModal.Address1 = response.Address1; customerModal.Address2 = response.Address2; customerModal.City = response.City; customerModal.ZipCode = response.ZipCode; customerModal.Phone1 = response.Phone1; customerModal.Phone2 = response.Phone2; customerModal.LicenceNumber = response.LicenceNumber; customerModal.LicenceExpiryDateString = response.LicenceExpiryDateString; customerModal.CountryId = response.CountryId; customerModal.StateId = response.StateId; customerModal.Email = response.Email; customerModal.Taxno1 = response.Taxno1; customerModal.Taxno2 = response.Taxno2; customerModal.Status = response.Status; customerModal.CreditAmount = response.CreditAmount; customerModal.CreditPeriod = response.CreditPeriod; customerModal.LockAmount = response.LockAmount; customerModal.LockPeriod = response.LockPeriod; customerModal.ProfileImagePath = response.ProfileImagePath; customerModal.FaxNo = response.FaxNo; customerModal.renderAsModal(); customerModal.openModal(); } }); } //Approve order $('#btnApproval').click(function () { var id = $('#hdRegisterId').val(); var ModifiedBy = $.cookie('bsl_3'); $.ajax ({ url: $('#hdApiUrl').val() + 'api/TicketEstimate/Confirm/' + id, method: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'Json', data: JSON.stringify(ModifiedBy), success: function (data) { var response = data; if (response.Success) { $('#ApproveStatus').removeClass('warning'); $('#ApproveStatus').show(); $('#ApproveStatus').addClass('success'); $('#ApproveStatusText').text("Approved"); $('#btnApproval').hide(); } else { errorAlert(response.Message); } }, error: function (xhr) { alert(xhr.responseText); console.log(xhr); miniLoading('stop') }, beforeSend: function () { miniLoading('start') }, complete: function () { miniLoading('stop'); }, }); }); $(document).on('click', '.edit-register', function () { window.open('/Registration/JobCard?MODE=edit&UID=' + $('#hdRegisterId').val(), '_self'); }); //Convert to invoice Click event $(document).on('click', '.convert-to-invoice', function () { window.open('/Sales/Entry?MODE=convert&TYPE=SQT&UID=' + $('#hdRegisterId').val(), '_self'); }); //Convert to Delivery Click event $(document).on('click', '.convert-to-delivery', function () { window.open('/Sales/DeliveryNote?MODE=convert&TYPE=SQT&UID=' + $('#hdRegisterId').val(), '_self'); }); $(document).on('click', '.print-register', function () { PopupCenter('/Registration/Print/JobCard?id=' + $('#hdRegisterId').val() + '&location=' + $.cookie('bsl_2'), 'JobCard', screen.availWidth, screen.availHeight); }); $(document).on('click', '.clone-register', function () { window.open('/Registration/JobCard?MODE=clone&UID=' + $('#hdRegisterId').val(), '_self'); }); $(document).on('click', '.new-register', function () { window.open('/Registration/JobCard?MODE=new', '_self'); }); $(document).on('click', '.delete-register', function () { if ($('#hdRegisterId').val() != 0) { swal({ title: "Delete?", text: "Are you sure you want to delete?", showConfirmButton: true, closeOnConfirm: true, showCancelButton: true, cancelButtonText: "Back to Entry", confirmButtonClass: "btn-danger", confirmButtonText: "Delete" }, function (isConfirm) { var id = $('#hdRegisterId').val(); var modifiedBy = $.cookie('bsl_3'); if (isConfirm) { $.ajax({ url: $('#hdApiUrl').val() + 'api/JobCard/delete/' + id, method: 'DELETE', datatype: 'JSON', contentType: 'application/json;charset=utf-8', data: JSON.stringify(modifiedBy), success: function (response) { if (response.Success) { successAlert(response.Message); $('.md-cancel').trigger('click'); refreshTable(); } else { errorAlert(response.Message); } }, error: function (xhr) { alert(xhr.responseText); console.log(xhr); } }); } }); } }); $("#modalMail").on('hidden.bs.modal', function () { $('.before-send').show(); $('.after-send').hide(); $('#ddlMailAddress').val(''); }); $(document).on('click', '.email-register', function (e) { $('#ddlMailAddress').val($('#hdEmail').val()); }); $(document).on('click', '#btnSend', function (e) { $('.before-send').fadeOut('slow', function () { $('.after-send').fadeIn(); var toaddr = $('#ddlMailAddress').val(); var id = $('#hdRegisterId').val(); var modifiedBy = $.cookie('bsl_3'); var type = JSON.parse($('#hdSettings').val()).TemplateType; var number = JSON.parse($('#hdSettings').val()).TemplateNumber; $.ajax({ url: $('#hdApiUrl').val() + 'api/TicketEstimate/SendMail?TicketId=' + id + '&toaddress=' + toaddr + '&userid=' + $.cookie('bsl_3'), method: 'POST', datatype: 'JSON', contentType: 'application/json;charset=utf-8', data: JSON.stringify($(location).attr('protocol') + '//' + $(location).attr('host') + '/Registration/Print/Estimate.aspx?id=' + id + '&location=' + $.cookie('bsl_2'), '+&lid'), success: function (response) { if (response.Success) { successAlert(response.Message); $("#modalMail").modal('hide'); } else { errorAlert(response.Message); $("#modalMail").modal('hide'); } }, error: function (xhr) { alert(xhr.responseText); console.log(xhr); } }); }); }); commonScroll(".right-side, .left-side"); $('.listing-search-entity').on('change keyup', function () { searchOnTable($('.listing-search-entity'), $('#invoiceList'), 1); }); //loading("stop"); });
const mongoose = require('mongoose'); //create class code var shortid = require('shortid'); /** * Required restrictions */ // Created by this teacher const teacherRestriction = { type: mongoose.Schema.Types.ObjectId, ref: 'Teacher', required: [true, 'Teacher id required'], }; const classCodeRestriction = { type: String, 'default': shortid.generate, index: { unique: true, }, }; const classNameRestriction = { type: String, required: [true, 'Class name required'], }; const yearRestriction = { type: Number, min: 1900, required: [true, 'Year required'], }; const capacityRestriction = { type: Number, required: [true, 'Capacity required'], }; const courseRestriction = { type: String, required: [true, 'Course required'], } const themeRestriction = { type: String, required: [true, 'Theme required'], } const statusRestriction = { type: Boolean, required: [true, 'Status required'] } // Will be modified by ObjectId const schoolRestriction = { type: String, required: [true, 'School required'] } /** * Optional restrictions */ const startDateRestriction = { type: String, } const endDateRestriction = { type: String, } const commentsRestriction = { type: String, } const classSchema = new mongoose.Schema({ teacher: teacherRestriction, code: classCodeRestriction, name: classNameRestriction, year: yearRestriction, capacity: capacityRestriction, course: courseRestriction, theme: themeRestriction, school: schoolRestriction, status: statusRestriction, startDate: startDateRestriction, endDate: endDateRestriction, comments: commentsRestriction, }); module.exports = mongoose.model('Class', classSchema);
import {createActions} from 'src/App/helpers' const actions = createActions('SEARCH', [ 'SUGGESTIONS_FETCH_REQUEST', 'SET_NEW_SUGGESTIONS', 'SET_EMPTY_SUGGESTIONS', 'RUN_SEARCH', ]) export default actions
var express = require('express'); var morgan = require('morgan'); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); var config = require('./config'); var app = express(); // app è istanza di express() var api = require('./public/app/routes/api')(app,express); // MongoDB: // Tolgo in quanto uso config.js var dbUri = 'mongodb://localhost:27017/agendalegale'; var server = require('http'); /* on('connected')... oppure once('open') */ mongoose.connection.once("open", function() { console.log("Connesso al DB!"); server = server.createServer(app) .listen(config.port, function(){ console.log('Server in ascolto sulla porta '+config.port); } ).on('error', function(err) { console.log('Errore di avvio: '+err); } ); }).on("error", function(err) { console.error('Impossibile collegarsi al DB in fase di avvio: ', err); }).on("disconnected", function () { console.log('Mongoose è stato disconnesso!'); //server.close(); }); mongoose.connect(config.database); app.use(bodyParser.urlencoded({extended:true})); app.use(bodyParser.json()); app.use(morgan('dev')); app.use(express.static(__dirname+'/public')); app.use('/api',api); app.get('*',function(req,res){ res.sendFile(__dirname + '/public/app/views/index.html'); });