text
stringlengths
7
3.69M
const mongoose = require('mongoose'); const { EloCalculator } = require('toefungi-elo-calculator'); const db = require('./models'); const eloCalculator = new EloCalculator(); exports.addPlayer = function(name) { db.Player.create({ name }).then(function() { mongoose.connection.close(); }); }; async function updateScore(name, score) { await db.Player.findOneAndUpdate({ name }, { score }); } exports.updateName = async function(originalName, newName) { await db.Player.findOneAndUpdate({ name: originalName }, { name: newName }); mongoose.connection.close(); }; exports.getRankings = async function() { const players = await db.Player.find().sort({ score: -1 }); mongoose.connection.close(); return players; }; exports.playGame = async function(result) { const player1 = await db.Player.findOne({ name: result.playerOne }); const player2 = await db.Player.findOne({ name: result.playerTwo }); const scoreDiff1 = result.playerOneScore - result.playerTwoScore; const scoreDiff2 = result.playerTwoScore - result.playerOneScore; await updateScore( result.playerOne, await eloCalculator.calculateElo( player1.score, player2.score, 0.5 + 0.5 * Math.sign(scoreDiff1), Math.abs(scoreDiff1) ) ); await updateScore( result.playerTwo, await eloCalculator.calculateElo( player2.score, player1.score, 0.5 + 0.5 * Math.sign(scoreDiff2), Math.abs(scoreDiff2) ) ); mongoose.connection.close(); }; exports.showRankings = function(players) { console.log(`${'Rank'.padEnd(15)}${'Name'.padEnd(15)}${'ELO'.padEnd(15)}`); for (let i = 0; i < players.length; i++) { const rank = `${i + 1}.`; let { name, score } = players[i]; name += ''; score += ''; console.log(`${rank.padEnd(15)}${name.padEnd(15)}${score.padEnd(15)}`); } };
import React from 'react'; import Box from "@material-ui/core/Box"; import '../assets/styles/pagination.css'; const SwiperComponent = () => { return ( <Box className="pagination__content" boxShadow={2}> <video width="580" height="255" controls > <source src="/videos/tutorial-edited.mp4" type="video/mp4" /> </video> </Box> ); } export default SwiperComponent;
const func = (t,y) => (((2*t-5)/Math.pow(t,2)*y)+5); function koshi_explicit(){ let y0=4; let h=0.05; let t0=2; let i=0; do{ let y1=y0+h*func(t0,y0); console.log(`i=${i} t=${t0} y=${y1} || difference between y= ${Math.abs(y1-y0)}\n`); y0=y1; t0+=h; i++; } while(t0<3); } function koshi_eiler(){ let y0=4; let h=0.1; let t0=2; let i=0; do{ let y_1=y0+h*func(t0,y0); let y1=y0+h/2*(func(t0,y0)+func(t0+h,y_1)); console.log(`i=${i} t=${t0} y=${y1} || difference between y= ${Math.abs(y1-y0)}\n`); y0=y1; t0+=h; i++; } while(t0<3); } koshi_explicit(); console.log("\n\n"); koshi_eiler(); // ----------task2--------------// const func_y = (x,y,z) => Math.sin(x)-2*y-z; const func_z = (x,y,z)=> Math.cos(x)+4*y+2*z; const ym = x =>1+x+2*Math.sin(x); const zm = x => (-3-2*x-3*Math.sin(x)-2*Math.cos(x)); function EilerSystem() { let y0=1; let z0= -5; let h=0.2; for(let x0=0;x0<=(Math.PI/2);x0+=h){ y0= y0+h*func_y(x0,y0,z0); z0= z0+h*func_z(x0,y0,z0); console.log(`y=${y0},z=${z0},Ym=${ym(x0)},Zm=${zm(x0)}`) } } EilerSystem();
import React, {Component} from 'react'; import { View, Text, StyleSheet, TouchableOpacity, Image, Keyboard, AsyncStorage, FlatList, NativeModules, TextInput, BackHandler, Alert, Modal, ActivityIndicator, } from 'react-native'; import AntIcon from 'react-native-vector-icons/AntDesign'; import RNRestart from 'react-native-restart'; import axios from 'axios'; import * as CONSTANT from '../Constants/Constant'; import CustomHeader from '../Header/CustomHeader'; import TopRatedCard from '../Home/TopRatedCard'; import {withNavigation} from 'react-navigation'; import {ScrollableTabView} from '@valdio/react-native-scrollable-tabview'; import {Button} from 'native-base'; const Entities = require('html-entities').XmlEntities; const entities = new Entities(); class FavHospitals extends Component { state = { data: [], TopRatedData: [], isLoading: true, }; componentDidMount() { this.fetchFavhospitalsData(); } fetchFavhospitalsData = async () => { const id = await AsyncStorage.getItem('projectProfileId'); const response = await fetch( CONSTANT.BaseUrl + 'user/get_wishlist?profile_id=' + id + '&type=hospitals', ); const json = await response.json(); if ( Array.isArray(json) && json[0] && json[0].type && json[0].type === 'error' ) { this.setState({TopRatedData: [], isLoading: false}); // empty data set } else { this.setState({TopRatedData: json, isLoading: false}); } }; render() { const { isLoading } = this.state; return ( <View style={styles.container}> {isLoading ? ( <View style={{ justifyContent: "center", height: "100%" }}> <ActivityIndicator size="small" color={CONSTANT.primaryColor} style={{ height: 30, width: 30, borderRadius: 60, alignContent: "center", alignSelf: "center", justifyContent: "center", backgroundColor: "#fff", elevation: 5 }} /> </View> ) : null} <View style={styles.TopRatedCardManagment}> {this.state.TopRatedData.length >= 1 ? ( <FlatList style={styles.favListStyle} data={this.state.TopRatedData} ListEmptyComponent={this._listEmptyComponent} keyExtractor={(x, i) => i.toString()} renderItem={({item}) => ( <TouchableOpacity activeOpacity={0.9} // onPress = { () => this.props.navigation.navigate("DetailDoctorScreen", {doc_id: item.ID})} onPress={() => { this.props.navigation.navigate('DetailDoctorScreen', { itemId: item.ID, }); }}> <TopRatedCard profileImage={{uri: `${item.image}`}} specialities={`${entities.decode(item.specialities.name)}`} name={`${entities.decode(item.name)}`} sub_heading={`${entities.decode(item.sub_heading)}`} total_rating={`${entities.decode(item.total_rating)}`} average_rating={`${entities.decode(item.average_rating)}`} featured_check={`${entities.decode(item.featured)}`} verified={`${entities.decode(item.is_verified)}`} verified_medically={`${entities.decode(item.is_verified)}`} role={`${entities.decode(item.role)}`} /> </TouchableOpacity> )} /> ) : ( <View style={styles.favArea}> <Image resizeMode={'contain'} style={styles.favImageStyle} source={require('../../Assets/Images/arrow.png')} /> <Text style={styles.favOopsText}> {CONSTANT.OopsText} </Text> <Text style={styles.favNoDataText}> {CONSTANT.NoDataText} </Text> </View> )} </View> </View> ); } } export default withNavigation(FavHospitals); const styles = StyleSheet.create({ container: { flex: 1, }, TopRatedCardManagment: { marginRight: 5, marginLeft: 5, }, favListStyle: {paddingLeft: 5}, favArea: { flex: 1, marginTop: '40%', alignContent: 'center', height: '100%', width: '100%', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', }, favImageStyle: { width: 250, height: 250, }, favOopsText: { fontSize: 25, fontWeight: '700', marginVertical: 10, }, favNoDataText: { fontSize: 17, fontWeight: '700', }, });
"use strict" var EventEmitter = require('events').EventEmitter, f = require('util').format, ERRORS = require('../../mongodb/errors'); // Connection Id var id = 0; class Connection extends EventEmitter { constructor(url, server, handlers) { super(); var self = this; this.handlers = handlers; this.id = (id++) % Number.MAX_VALUE; // Execute pre handlers var executeHandlers = function(index, handlers, connection, channel, data, callback) { // Return if there are no pre handlers if(index == handlers.length) return callback(); // Execute the next handler var handler = handlers.shift(); // Execute it handler(connection, channel, data, function(err) { if(err) return callback(err); executeHandlers(index++, handlers, connection, channel, data, callback); }); } console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! server post 1 :: " + url) // Register the handler for the REST endpoint server.post(url, function(req, res) { console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! server post 2") // We have no body if(!req.body) { return res.end(JSON.stringify({ ok: false, code: ERRORS.TRANSPORT_FAILURE, message: 'no json object passed in body' })); } // Locate a handler by channel, error out if no handler available var channelHandler = self.handlers[req.body.channel]; if(!channelHandler) { return res.end(JSON.stringify({ ok: false, code: ERRORS.NO_CHANNEL_TRANSPORT_FAILURE, message: f('channel [%s] not valid', req.body.channel) })); } // PRE HANDLERS executeHandlers(0, channelHandler.pre, self, req.body.channel, req.body.obj, function(err) { // Do we have an error if(err) { return channelHandler.errorHandler(self, req.body.channel, req.body.obj, Array.isArray(err) ? err : [err]); } // Return a object that allows us to write back in same context var connection = { write: function(channel, doc) { res.send(JSON.stringify({ channel: channel, obj: doc })); } } // Library MongoDB handler channelHandler.handler(connection, req.body.channel, req.body.obj); }); }); } write(channel, doc) { this.connection.emit(channel, doc); } } module.exports = Connection;
/** * @license * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Externs for prefixed EME v20140218 as supported by IE11/Edge * (http://www.w3.org/TR/2014/WD-encrypted-media-20140218). * @externs */ /** * @constructor * @param {string} keySystem */ function MSMediaKeys(keySystem) {} /** * @param {string} keySystem * @param {string} contentType * @return {boolean} */ MSMediaKeys.isTypeSupported = function(keySystem, contentType) {}; /** * @param {string} contentType * @param {Uint8Array} initData * @param {Uint8Array=} opt_cdmData * @return {!MSMediaKeySession} */ MSMediaKeys.prototype.createSession = function(contentType, initData, opt_cdmData) {}; /** * @interface * @extends {EventTarget} */ function MSMediaKeySession() {} /** * @param {Uint8Array} message */ MSMediaKeySession.prototype.update = function(message) {}; MSMediaKeySession.prototype.close = function() {}; /** @type {MSMediaKeyError} */ MSMediaKeySession.prototype.error; /** @override */ MSMediaKeySession.prototype.addEventListener = function(type, listener, useCapture) {}; /** @override */ MSMediaKeySession.prototype.removeEventListener = function(type, listener, useCapture) {}; /** @override */ MSMediaKeySession.prototype.dispatchEvent = function(evt) {}; /** * @param {MSMediaKeys} mediaKeys */ HTMLMediaElement.prototype.msSetMediaKeys = function(mediaKeys) {}; /** @constructor */ function MSMediaKeyError() {} /** @type {number} */ MSMediaKeyError.prototype.code; /** @type {number} */ MSMediaKeyError.prototype.systemCode; /** @type {number} */ MSMediaKeyError.MS_MEDIA_KEYERR_UNKNOWN; /** @type {number} */ MSMediaKeyError.MS_MEDIA_KEYERR_CLIENT; /** @type {number} */ MSMediaKeyError.MS_MEDIA_KEYERR_SERVICE; /** @type {number} */ MSMediaKeyError.MS_MEDIA_KEYERR_OUTPUT; /** @type {number} */ MSMediaKeyError.MS_MEDIA_KEYERR_HARDWARECHANGE; /** @type {number} */ MSMediaKeyError.MS_MEDIA_KEYERR_DOMAIN; /** @type {number} */ MediaError.prototype.msExtendedCode;
var app = angular.module('userProfiles'); app.service('mainService', function ($http, $q) { this.getUsers = function () { var deferred = $q.defer(); $http({ method: 'GET', url: 'http://reqr.es/api/users?page=1' }).then(function(result){ result = result.data.data; //Used only to show that the data can be manipulated before sending to controller for(var i = 0; i < result.length; i++){ result[i].first_name = "Ralf"; } deferred.resolve(result); }); return deferred.promise; } });
"use strict"; exports.__esModule = true; console.clear(); var auto_1 = require("./auto"); var auto1 = new auto_1["default"]("Fiat", 2018); var auto2 = new auto_1["default"]("Chevrolet", 2017); var auto3 = new auto_1["default"]("Ford", 2019); auto1.imprimirAuto(); console.log(auto1); auto2.imprimirAuto(); console.log(auto2); auto3.imprimirAuto(); console.log(auto3);
// Chapter 1 Task 1 // alert("Welcome to my site"); // Chapter 1 Task 2 // alert("Error ! Please enter a valid password"); // Chapter 1 Task 3 // alert("Welcome to JS Land\nHappy Coding "); // Chapter 1 Task 4 // alert("Welcome to JS Land"); // alert("Happy coding"); // Chapter 1 Task 5 // Done // Chapter 1 Task 6 // Done // Chapter 1 Task 7 // Done // Chapter 2 Task 1 var username = 5; // Chapter 2 Task 2 var myname = "myname"; // Chapter 2 Task 3 var z = x + y; document.getElementById("demo").innerHTML = "The value of z is: " + z;
const mongoose = require('mongoose'); const joi = require('joi'); joi.objectId = require('joi-objectid')(joi); const joigoose = require('joigoose')(mongoose); // Allowed OS values for 'model' // It must be a REGEX because joi's force uppercase only proccess after the expressions const MODELS = /^ANDROID|IOS$/; const name = joi.string().max(50).required(); // Used for device registration let DeviceJoiSchema = joi.object().keys({ userId: joi.string().required(), name: name, model: joi.string().uppercase({ force: true }).regex(/^ANDROID|IOS$/).required(), date_added: joi.date() }) // Used for device update let DeviceIdNameSchema = joi.object().keys({ id: joi.objectId().label('Invalid objectId'), name: name }) // Mongoose Schema, converted from joi let DeviceMongooseSchema = new mongoose.Schema(joigoose.convert(DeviceJoiSchema)); let DeviceModel = mongoose.model('Device', DeviceMongooseSchema); // Exporting the mongoose model and joi schema module.exports = { DeviceModel, DeviceJoiSchema, DeviceIdNameSchema }
import React, { useState, useEffect } from "react"; import Head from "next/head"; import { getTokens } from "../functions/UIStateFunctions.js"; import Hero from "../components/Hero"; import CardRow from "../components/CardRow"; import CardRowHeader from "../components/CardRowHeader"; import Loader from "../components/Loader"; import Hiring from "../pages/Hiring"; export default () => { return <Hiring/> } /* export default () => { const [avatars, setAvatars] = useState(null); const [art, setArt] = useState(null); const [models, setModels] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { (async () => { const tokens1 = await getTokens(1, 100); const tokens2 = await getTokens(100, 200); const tokens = tokens1.concat(tokens2); setAvatars( tokens.filter((o) => o.properties.ext.toLowerCase().includes("vrm") ) ); setArt( tokens.filter((o) => o.properties.ext.toLowerCase().includes("png") ) ); setModels( tokens.filter((o) => o.properties.ext.toLowerCase().includes("glb") ) ); setLoading(false); })(); }, []); return ( <> <Head> <title>Webaverse</title> <meta name="description" content={"The virtual world built with NFTs."} /> <meta property="og:title" content={"Webaverse"} /> <meta property="og:image" content={"https://webaverse.com/webaverse.png"} /> <meta name="theme-color" content="#c4005d" /> <meta name="twitter:card" content="summary_large_image" /> </Head> <Hero heroBg="/hero.gif" title="Webaverse" subtitle="The virtual world built with NFTs" callToAction="Play" ctaUrl="https://app.webaverse.com" /> <div className="container"> {loading ? ( <Loader loading={loading} /> ) : ( <> <CardRowHeader name="Avatars" /> <CardRow data={avatars} cardSize="small" /> <CardRowHeader name="Digital Art" /> <CardRow data={art} cardSize="small" /> <CardRowHeader name="3D Models" /> <CardRow data={models} cardSize="small" /> </> )} </div> </> ); }; */
import logo from './logo.svg'; import './App.css'; import { useEffect, useState } from 'react'; function App() { return ( <div className="App"> <Countries></Countries> </div> ); } function Countries() { const [countries, setCountries] = useState([]); useEffect(() => { }, []) return ( <div> <h2>Traveling around the world!!</h2> </div> ) } export default App;
console.log("FUNZIONAAAA :)");
/** * Created by kunnisser on 2017/1/20. * 场景stage切换 */ import Graphics from '../utils/Graphics'; import Configer from '../config/Configer'; class StateTransition extends Phaser.Plugin{ constructor (game) { super(game, game.stage); let blackRect = Graphics.createRectTexture(game, 1, 1, '#000000', 'black_rect'); this.overlay = this.game.add.image(0, 0, blackRect); this.overlay.visible = !1; this.overlayDuration = 400; game.stage.addChild(this.overlay); }; fillStage () { this.overlay.scale.set(Configer.GAME_WIDTH, Configer.GAME_HEIGHT); } changeState (nextLevel, bool) { this.fillStage(); this.overlay.visible = !0; this.overlay.alpha = 0; this.showLay = this.game.add.tween(this.overlay).to({ alpha: 1 }, this.overlayDuration, Phaser.Easing.Cubic.Out, !0); this.showLay.onComplete.addOnce(() => { this.doChangeState(nextLevel, bool); }); } doChangeState (n, b) { this.game.state.start(n, !0, !1, {overlay: this.overlay, param: b}); } }; export default StateTransition;
// var name = "" let today = new Date(); let year = today.getFullYear(); let month = ('0' + (today.getMonth() + 1)).slice(-2); let day = ('0' + today.getDate()).slice(-2); let hours = ('0' + today.getHours()).slice(-2); let minutes = ('0' + today.getMinutes()).slice(-2); let date = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes function recipe() { $.ajax({ type: "GET", url: "/recipe/read", data: {}, success: function (response) { // console.log(response) let recipes = response['recipes'] let ing = recipes['ingredient'] let name = recipes['name'] // let desc = recipes['desc'] let making = recipes['making'] let precook = recipes['precook'] let title_html = `<img class="cook-img" src="../static/recipe-image/${name}.png" alt=""> ${name}</img>` let btn_html = `<button class="btn-main" id="btn-add-review" onclick="add_review('${name}')">리뷰 추가</button>` let ingredient__html = `${ing}` for (let i = 0; i < precook.length; i++) { let precook = recipes['precook'][i] let temp_html = `<li> ${precook}. </li>` $('.ready_detail').append(temp_html) } for (let i = 0; i < making.length; i++) { let making2 = recipes['making'][i] let temp_html = `<li> ${making2}. </li>` $('.making_detail').append(temp_html) } $('.cook-name').append(title_html) $('.ing').append(ingredient__html) $('#add-review').append(btn_html) review_show(name) } }) } function review_show(name){ $.ajax({ type: "POST", url: "/review/show", data: {name_give:name}, success: function (response) { let reviews = response['all_reviews'] for (let i = 0; i < reviews.length; i++) { let comment = reviews[i]['comment'] let user_id = reviews[i]['user_id'] let datetime = reviews[i]['datetime'] let review_html = `<li> ${comment} / ${user_id} / ${datetime} </li>` $('#review-list').append(review_html) } } }) } function add_review(name){ let comment = $('#new-review').val(); $.ajax({ type: "POST", url: "/review", data: {recipe_give:name, comment_give:comment}, success: function (response) { let user_id = response['user_id'] let review_html = `<li> ${comment} / ${user_id} / ${date} </li>` if (user_id == undefined) { alert('로그인 후 이용해주세요.') } else{ $('#review-list').append(review_html) alert('추가 완료') } } }) } function request_show(){ $.ajax({ type: "GET", url: "/request/show", data: {}, success: function (response) { let requests = response['all_requests'] for (let i = 0; i < requests.length; i++) { let uid = requests[i]['user_id'] let request = requests[i]['request'] let datetime = requests[i]['datetime'] let request_html = `<li> ${uid}: ${request} / ${datetime} </li>` $('.request_list').append(request_html) } } }) } function add_request(){ let comment = $('#new-request').val(); $.ajax({ type: "POST", url: "/request", data: {request_give:comment}, success: function (response) { let user_id = response['user_id'] let req_html = `<li> ${user_id}: ${comment} / ${date} </li>` if (user_id == undefined) { alert('로그인 후 이용해주세요.') } else{ $('.request_list').append(req_html) alert('추가 완료') } } }) }
const db = require("../models"); const product = require("../models/product"); const Product = db.products; exports.addProduct = function (req, res) { // Validate request if (!req.body.name || !req.body.price || !req.body.description || !req.body.stock || !req.body.published || !req.body.color) { res.status(400).send({ message: "Name, Price, description, stock, published and color can not be empty!" }); return; } // Create an Products const product = { id: req.body.id, brand_id: req.body.brand_id, name: req.body.name, price: req.body.price, description: req.body.description, published: req.body.published, color: req.body.color, stock: req.body.stock }; // Save Product in the database Product.create(product) .then(data => { res.send({ 'Data': data, 'Status': 200 }); }) .catch(err => { res.status(500).send({ message: err.message || "Some error occurred while creating a new Product." }); }); } exports.getProduct = function (req, res) { Product.findByPk(req.params.id) .then(data => { res.send({ 'Data': data, 'Status': 200 }); }) .catch(err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving the Product " + req.params.id + "." }); }); } exports.getAllProducts = function (req, res) { Product.findAll() .then(data => { res.send({ 'Data': data, 'Status': 200 }); }) .catch(err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving Products." }); }); } exports.deleteAllProducts = function (req, res) { Product.destroy({ where: {}, truncate: false }) .then(num => { res.send({ message: `${num} Products were deleted successfully!` }); }) .catch(err => { res.status(500).send({ message: "Error deleting Products" }); }); } exports.deleteProduct = function (req, res) { const id = req.params.id; Product.destroy({ where: { id: id } }) .then(num => { if (num == 1) { res.send({ message: "Product was deleted successfully." }); } else { res.send({ message: `Cannot delete Product with id ${id}. Maybe Product was not found!` }); } }) .catch(err => { res.status(500).send({ message: "Error deleting Product with id " + id }); }); } exports.updateProduct = function (req, res) { const id = req.params.id; Product.update(req.body, { where: { id: id } }) .then(num => { if (num == 1) { res.send({ message: "Product was updated successfully." }); } else { res.send({ message: `Cannot update the Product with id=${id}. Maybe Product was not found!` }); } }) .catch(err => { res.status(500).send({ message: `Error updating Product with id=${id}` }); }); }
import React, { useState, useEffect } from 'react' import { useParams } from 'react-router-dom' import firebase from 'firebase' import 'bootstrap/dist/css/bootstrap.min.css' const NewsLink = () => { const db = firebase.firestore() const [inform, setInform] = useState({}) const [term,setTerm] =useState('everything') const { id: id } = useParams() // get data by id useEffect(() => { fetch(`https://api.nytimes.com/svc/search/v2/articlesearch.json?q=everything&api-key=hgGZ9Qf26H4JZSuum97ZdjfSvdrM1GG0 ` + id) .then((res) => { return res.json() }) .then((data) => { setInform(data) }) .catch((err)=>{console.log(err)}) },[]) return ( <> Default functional {id} {inform.abstract} <div className="card"> <h5 className="card-header">No: {id}</h5> <div className="card-body"> <h5 className="card-title">{inform.status}</h5> <p className="card-text">With supporting text below as a natural lead-in to additional content.</p> <a href="#" className="btn btn-primary">Go somewhere</a> </div> </div> </> ) } export default NewsLink
exports.defaults = { production: { server: "https://updates.push.services.mozilla.com/push/", connectTimeout: 1000 }, testmode: { server: "http://localhost", connectTimeout: 1000 } }; exports.check = function(options) { for (let prop in exports.defaults.production) { if (!options[prop]) { throw new Error("moz." + prop + " is missing from options"); } } return true; };
import React, { Component } from "react"; import { Link } from "react-router-dom"; import socketEvent from "./socket"; class EmployeeList extends Component { constructor() { super(); this.state = { empData: null, }; } componentDidMount() { socketEvent.initEmpData(this.getData); } getData = (empData) => { this.setState({ empData, }); }; getTableHeader = () => { return ( <thead className="thead-dark"> <tr> <th>Emp ID</th> <th>Name</th> <th>Gender</th> <th>Email</th> <th>Mobile</th> <th>Cost Center</th> <th>Action</th> </tr> </thead> ); }; deleteData = (empId) => { socketEvent.deleteEmp(empId); }; getTableData = () => { const { empData } = this.state; if (!!empData) { return empData.map((data) => { return ( <tr key={data._id}> <td>{data.empId}</td> <td>{data.name}</td> <td>{data.gender}</td> <td>{data.emailId}</td> <td>{data.mobile}</td> <td>{data.costCenter}</td> <td style={{ cursor: "pointer" }}> <Link to={`/edit/${data._id}`}> <span className="badge badge-secondary mr-2">Edit</span> </Link> <span className="badge badge-danger" onClick={this.deleteData.bind(this, data._id)} > Delete </span> </td> </tr> ); }); } else { return ( <tr> <td colSpan="8">Loading...</td> </tr> ); } }; render() { return ( <div className="container mt-4"> <Link to="/add"> <button type="button" className="btn btn-primary mb-2 float-right btn-sm" > Add Employee </button> </Link> <table className="table"> {this.getTableHeader()} <tbody>{this.getTableData()}</tbody> </table> </div> ); } } export default EmployeeList;
import $ from '../../../core/renderer'; import { isDefined } from '../../../core/utils/type'; import { WIDGET_CLASS, FIELD_ITEM_LABEL_CONTENT_CLASS, FIELD_ITEM_LABEL_CLASS } from '../constants'; // TODO: exported for tests only export var GET_LABEL_WIDTH_BY_TEXT_CLASS = 'dx-layout-manager-hidden-label'; export var FIELD_ITEM_REQUIRED_MARK_CLASS = 'dx-field-item-required-mark'; export var FIELD_ITEM_LABEL_LOCATION_CLASS = 'dx-field-item-label-location-'; export var FIELD_ITEM_OPTIONAL_MARK_CLASS = 'dx-field-item-optional-mark'; export var FIELD_ITEM_LABEL_TEXT_CLASS = 'dx-field-item-label-text'; export function renderLabel(_ref) { var { text, id, location, alignment, labelID = null, markOptions = {} } = _ref; if (!isDefined(text) || text.length <= 0) { return null; } return $('<label>').addClass(FIELD_ITEM_LABEL_CLASS + ' ' + FIELD_ITEM_LABEL_LOCATION_CLASS + location).attr('for', id).attr('id', labelID).css('textAlign', alignment).append($('<span>').addClass(FIELD_ITEM_LABEL_CONTENT_CLASS).append($('<span>').addClass(FIELD_ITEM_LABEL_TEXT_CLASS).text(text), _renderLabelMark(markOptions))); } function _renderLabelMark(_ref2) { var { isRequiredMark, requiredMark, isOptionalMark, optionalMark } = _ref2; if (!isRequiredMark && !isOptionalMark) { return null; } return $('<span>').addClass(isRequiredMark ? FIELD_ITEM_REQUIRED_MARK_CLASS : FIELD_ITEM_OPTIONAL_MARK_CLASS).text(String.fromCharCode(160) + (isRequiredMark ? requiredMark : optionalMark)); } export function getLabelWidthByText(renderLabelOptions) { var $hiddenContainer = $('<div>').addClass(WIDGET_CLASS).addClass(GET_LABEL_WIDTH_BY_TEXT_CLASS).appendTo('body'); var $label = renderLabel(renderLabelOptions).appendTo($hiddenContainer); var labelTextElement = $label.find('.' + FIELD_ITEM_LABEL_TEXT_CLASS)[0]; // this code has slow performance var result = labelTextElement.offsetWidth; $hiddenContainer.remove(); return result; }
Pokedex.Views = {} Pokedex.Views.PokemonIndex = Backbone.View.extend({ events: { "click li": "selectPokemonFromList" }, initialize: function (options) { this.listenTo(this.collection, "sync", this.render); }, addPokemonToList: function (pokemon) { this.$el.append(JST['pokemonListItem']({ pokemon: pokemon})); }, refreshPokemon: function (callback) { this.collection.fetch( { success: function () { this.render(); callback(); }.bind(this) } ); }, render: function () { this.$el.empty(); this.collection.each( function (pokemon) { this.addPokemonToList(pokemon); }, this); }, selectPokemonFromList: function (event) { var id = $(event.currentTarget).data("id"); var pokemon = this.collection.get(id); Backbone.history.navigate('pokemon/' + id, { trigger: true }); } }); Pokedex.Views.PokemonDetail = Backbone.View.extend({ events: { "click li.toy-list-item": "selectToyFromList" }, refreshPokemon: function (options) { var pokemon = this.model; pokemon.fetch({ success: function () { this.render(); }.bind(this) }); }, render: function () { var pokemon = this.model; var that = this; this.$el.append(JST['pokemonDetail']({ pokemon: pokemon })); pokemon.toys().each(function(toy) { that.$el.append(JST['toyListItem']({ pokemon: pokemon, toy: toy, shortInfo: ['name', 'happiness', 'price'] })); }); }, selectToyFromList: function (event) { var toy = this.model.toys().get($(event.currentTarget).data("id")); Backbone.history.navigate('pokemon/' + toy.escape('pokemon_id') + '/toys/' + toy.id, { trigger: true } ); } }); Pokedex.Views.ToyDetail = Backbone.View.extend({ render: function (pokes) { var that = this; this.$el.append(JST["toyDetail"]({ toy: this.model, pokes: pokes})); } }); // // $(function () { // var pokemons = new Pokedex.Collections.Pokemon(); // pokemons.fetch(); // var pokemonIndex = new Pokedex.Views.PokemonIndex({ // collection: pokemons // }); // pokemonIndex.refreshPokemon(); // // $("#pokedex .pokemon-list").html(pokemonIndex.$el); // });
import React from "react"; import { MDBCol, MDBContainer, MDBRow, MDBFooter } from "mdbreact"; import {Container} from "react-bootstrap"; import { Link } from "react-router-dom"; import { MDBIcon, MDBBtn } from 'mdbreact'; const FooterPagePro = () => { return ( <Container fluid style={{ backgroundColor: '#000', color: '#fff', }}> <MDBFooter className="page-footer font-small pt-4 mt-4"> <MDBContainer fluid className="text-center text-md-left"> <MDBRow style={{justifyContent: "space-between"}}> <MDBCol md="6"> <h5 className="text-uppercase mb-4 mt-3 font-weight-bold"> Snow Shop </h5> <p> Best skies and snowboards from beginners to experts </p> </MDBCol> <hr className="clearfix w-100 d-md-none" /> <MDBCol md="2" > <h5 className="text-uppercase mb-4 mt-3 font-weight-bold"> Links </h5> <ul className="list-unstyled"> <li> <a href="#!">Company</a> </li> <li> <a href="#!">Skis Snowboards</a> </li> <li> <a href="#!">Jalal-Abad</a> </li> <li> <a href="#!">+996550157055</a> </li> </ul> </MDBCol> </MDBRow> </MDBContainer> <hr /> <div className="text-center"> <ul className="list-unstyled list-inline mb-0"> <li className="list-inline-item"> <h5 className="mb-1">Register for free</h5> </li> <li className="list-inline-item"> <Link to ='/register'> <a href="#!" className="btn btn-danger btn-rounded"> Sign up! </a> </Link> </li> </ul> </div> <hr /> <div className="text-center"> <ul className="list-unstyled list-inline"> <li className="list-inline-item"> <a className="btn-floating btn-sm btn-fb mx-1"> <i className="fab fa-facebook-f"> </i> </a> </li> <li className="list-inline-item"> <a className="btn-floating btn-sm btn-tw mx-1"> <i className="fab fa-twitter"> </i> </a> </li> <li className="list-inline-item"> <a className="btn-floating btn-sm btn-gplus mx-1"> <i className="fab fa-google-plus"> </i> </a> </li> <li className="list-inline-item"> <a className="btn-floating btn-sm btn-li mx-1"> <i className="fab fa-linkedin-in"> </i> </a> </li> <li className="list-inline-item"> <a className="btn-floating btn-sm btn-dribbble mx-1"> <i className="fab fa-dribbble"> </i> </a> </li> </ul> </div> <div className="footer-copyright text-center"> <MDBContainer fluid> &copy; {new Date().getFullYear()} Copyright: <a href="https://www.MDBootstrap.com"> ARVB </a> </MDBContainer> </div> </MDBFooter> </Container> ); } export default FooterPagePro;
// Code your solution in this file! function distanceFromHqInBlocks(address){ if(address > 42){ return address - 42 }else{ return 42-address } } function distanceFromHqInFeet(n){ return distanceFromHqInBlocks(n) * 264 } function distanceTravelledInFeet(start, end){ if (end > start){ let distance = (end - start) * 264 return distance; } else { let distance = (start - end) * 264 return distance; } } function calculatesFarePrice(start, destination){ let distance = distanceTravelledInFeet(start, destination) if (distance < 400){ return 0 } else if (400 < distance && distance < 2000){ return distance * .02 } else if (distance < 2500){ return 25 } else { return "cannot travel that far" }}
const { execSync } = require("child_process"); const fs = require("fs"); const files = fs.readdirSync(process.cwd()); const vpkfiles = files.filter(file => file.endsWith('.vpk')); const matches = []; for (const file of vpkfiles) { const stdout = execSync('vpk -l ' + file) if (stdout.includes(process.argv[2])) { matches.push(file); } } console.log(matches.join('\n'));
(function(){ var navigation = Array.prototype.slice.call(document.querySelectorAll('ul#navigation li')); var sections = Array.prototype.slice.call(document.querySelectorAll('section')); var hideAllSections = function() { sections.forEach(function(section) { section.classList.remove('active'); }); navigation.forEach(function(nav) { nav.classList.remove('active'); }); }; var showSection = function(index) { if (index < sections.length) { var section = sections[index]; section.classList.add('active'); var nav = navigation[index]; nav.classList.add('active'); } }; navigation.forEach(function(entry, index) { entry.addEventListener('click', function() { hideAllSections(); showSection(index); }); }); hideAllSections(); if (navigation.length > 0) { showSection(0); } }());
/** * HELPER * * console.log wrap * * @param params */ const chalk = require('chalk'); let helper = function (params) { let self = this; self.print_level = 1; // > default print out to console [error] self.method = 4; // default method console[log] self.module_name = params && params.module_name || "logger_undefined_module"; self.fn_name = params && params.fn_name || "logger_undefined_function_name"; self.method_map = [false, "error", "warn", "debug", "log", "info", "trace"]; if (process.env.DEBUG_LEVEL !== undefined) { //console.log( "ENV DEBUG_LEVEL SET", process.env.DEBUG_LEVEL ); self.print_level = process.env.DEBUG_LEVEL; } if (params !== undefined && params.level !== undefined) { self.print_level = params.level; } self.o = function (input, settings, override_method, override_level) { let print_level = self.print_level; let method = self.method; let module_name = self.module_name; let fn_name = self.fn_name; if (typeof settings === 'object') { if (settings.method) { method = settings.method; delete settings.method; } if (settings.module_name) { module_name = settings.module_name; delete settings.module_name; } if (settings.fn_name) { fn_name = settings.fn_name; delete settings.fn_name; } } else { fn_name = settings; } if (override_method !== undefined) { method = self.method_map.indexOf( override_method ); } if (override_level !== undefined) { print_level = override_level; } if (override_level !== undefined || print_level < method) return; //silence let cl = self.method_map[method], cl_chalked = "[" + cl + "]"; let called = "[" + module_name + "." + fn_name + "]"; if (input instanceof Error || method == "error") { if( print_level == 6 ){ console.trace(chalk.red(input)); } input = input.message; cl = "error"; } if (cl == "warn") { cl_chalked = chalk.yellow("[" + cl + "]"); called = chalk.yellow(called); } if (cl == "error") { cl_chalked = chalk.red("[" + cl + "]"); called = chalk.red(called); } if (!Array.isArray(input)) { console[cl](cl_chalked, called, input); return; } if (input.length == 2) { console[cl](cl_chalked, called, input[0], input[1]); return; } for (let i = 0, l = input.length; i < l; i++) { console[cl](cl_chalked, called, input[i]); } }; }; module.exports = helper;
$(document).ready(function() { Checkout.signUpToggle(); Session.create("#sign-in", "#sign-in-container", true); Checkout.confirmAdress("#adress-confirmation"); // CALLING AJAX FUNTION TO FETCH RESULT OF STRIPE SCRIPT const stripeSecret = "<?php echo STRIPE_PUBLISHABLE_KEY ?>"; const appStripe = new AppStripe(); appStripe.checkout("#stripe-checkout"); });
import React from 'react' import './style.css' export default function Avatar({contact}) { const firstLetter = contact.first_name.charAt(0).toUpperCase(); const secondLetter = contact.last_name.charAt(0).toUpperCase(); return ( <div className="d-flex align-items-center justify-content-center"> {contact.picture_id ? <img className="avatar" width="100" height="100" src="https://dogtime.com/assets/uploads/2011/03/puppy-development.jpg" alt="avatar"/> : <div className="avatar default-avatar"> {firstLetter}{secondLetter} </div> } </div> ) }
import {combineReducers, createStore, applyMiddleware} from 'redux' import thunk from 'redux-thunk'; import {dataReducer} from './modules/dataReducer.js' import {changeProjectReducer} from './modules/changeProject.js' import {loginReducer} from './modules/loginReducer.js' const reducer = combineReducers({ dataReducer, changeProjectReducer, loginReducer }) const store = createStore(reducer, applyMiddleware(thunk)) export default store;
describe('VglPointsMaterial:', function suite() { const { VglPointsMaterial, VglNamespace } = VueGL; it('without properties', function test(done) { const vm = new Vue({ template: '<vgl-namespace><vgl-points-material ref="m" /></vgl-namespace>', components: { VglPointsMaterial, VglNamespace }, }).$mount(); vm.$nextTick(() => { try { const expected = new THREE.PointsMaterial(); const { inst } = vm.$refs.m; expect(inst).to.deep.equal(Object.assign(expected, { uuid: inst.uuid })); done(); } catch (e) { done(e); } }); }); it('with properties', function test(done) { const vm = new Vue({ template: '<vgl-namespace><vgl-points-material color="#8aeda3" size="3" disable-size-attenuation ref="m" /></vgl-namespace>', components: { VglPointsMaterial, VglNamespace }, }).$mount(); vm.$nextTick(() => { try { const expected = new THREE.PointsMaterial({ color: 0x8aeda3, size: 3, sizeAttenuation: false, }); const { inst } = vm.$refs.m; expect(inst).to.deep.equal(Object.assign(expected, { uuid: inst.uuid })); done(); } catch (e) { done(e); } }); }); it('after properties are changed', function test(done) { const vm = new Vue({ template: '<vgl-namespace><vgl-points-material :color="color" :size="size" :disable-size-attenuation="!attenuation" ref="m" /></vgl-namespace>', components: { VglPointsMaterial, VglNamespace }, data: { color: '#dafbc4', size: 8, attenuation: false }, }).$mount(); vm.$nextTick(() => { vm.color = '#abbcaf'; vm.size = 4.88; vm.attenuation = true; vm.$nextTick(() => { try { const expected = new THREE.PointsMaterial({ color: 0xabbcaf, size: 4.88, sizeAttenuation: true, }); const { inst } = vm.$refs.m; expect(inst).to.deep.equal(Object.assign(expected, { uuid: inst.uuid })); done(); } catch (e) { done(e); } }); }); }); });
/* * ScanLoginPage * */ import React from 'react' import { injectIntl } from 'react-intl' import PropTypes from 'prop-types' import { Form, Alert, Button, Input, message, Modal } from 'antd' import { connect } from 'react-redux' import { createStructuredSelector } from 'reselect' import { makeSelectNetwork } from '../../containers/LanguageProvider/selectors' import styleComps from './styles' import axios from 'axios' import { getEos } from '../../utils/utils' import { LayoutContentBox, FormComp } from '../../components/NodeComp' // import request from 'request'; import utilsMsg from '../../utils/messages' import { BrowserQRCodeReader } from '../../utils/zxing.qrcodereader.min' const FormItem = Form.Item const { TextArea } = Input export class ScanLoginPage extends React.Component { constructor (props) { super(props) this.state = { transactionId: '', formatMessage: this.props.intl.formatMessage } } handleOpenCamera = () => { this.setState({ VideoElement: ( <FormItem> <video id="video" width="500" height="200"> <track kind="captions" /> </video> </FormItem> ) }) this.handleScanQrcode() }; handleScanQrcode = () => { const codeReader = new BrowserQRCodeReader() codeReader.getVideoInputDevices().then(videoInputDevices => { codeReader .decodeFromInputVideoDevice(videoInputDevices[0].deviceId, 'video') .then(result => { this.props.form.setFieldsValue({ jsonInfo: result.text }) }) }) }; /** * 用户点击发送签名报文,并提示用户已发送 * */ sendMessage = () => { const data = this.props.form.getFieldsValue().jsonInfo let info = JSON.parse(data) console.log('info===',info) // request.post(info.loginUrl , info).then(res=> { // console.log('request==',request) // }) .catch(err=>{ // console.log('err==',err) // }) var instance = axios.create({ headers: { // "Content-Type":"application/json", 'Access-Control-Allow-Origin':'*' } }); instance.post(info.loginUrl , info ).then(res=>{ console.log('response==',res) message.success( `${this.state.formatMessage( utilsMsg.SendSuccessMessage, )}transactionId=${res.transaction_id}`, ) this.setState({ transactionId: res.transaction_id }) }).catch(err => { console.log('err==',err) message.error(`发送失败,原因:${err}`) }) }; render () { const { getFieldDecorator } = this.props.form const { formatMessage } = this.props.intl const description = formatMessage(utilsMsg.JsonAlertDescription) const OpenCameraButtonName = formatMessage(utilsMsg.OpenCameraButtonName) const JsonInfoPlaceholder = formatMessage(utilsMsg.JsonInfoPlaceholder) const FieldAlertSendMessageNew = formatMessage( utilsMsg.FieldAlertSendMessageNew, ) return ( <LayoutContentBox> <styleComps.ConBox> <FormComp style={{ maxWidth: '500px' }}> <FormItem> <Alert message={FieldAlertSendMessageNew} description={description} type="info" /> </FormItem> {this.state.VideoElement} <FormItem style={{ textAlign: 'center' }}> <Button type="primary" className="form-button" style={{ display: 'inline', marginRight: 5 }} onClick={this.handleOpenCamera} > {OpenCameraButtonName} </Button> </FormItem> <FormItem> {getFieldDecorator('jsonInfo', { rules: [{ required: true, message: JsonInfoPlaceholder }] })(<TextArea placeholder={JsonInfoPlaceholder} rows="6" />)} </FormItem> <FormItem style={{ textAlign: 'center' }}> <Button type="primary" className="form-button" onClick={this.sendMessage} disabled={false} > {FieldAlertSendMessageNew} </Button> </FormItem> <FormItem style={{ textAlign: 'left' }}> {this.state.transactionId ? `txid:${this.state.transactionId}` : ''} </FormItem> </FormComp> </styleComps.ConBox> </LayoutContentBox> ) } } ScanLoginPage.propTypes = { form: PropTypes.object, intl: PropTypes.object, SelectedNetWork: PropTypes.string } const ScanLoginPageIntl = injectIntl(ScanLoginPage) const ScanLoginPageForm = Form.create()(ScanLoginPageIntl) const mapStateToProps = createStructuredSelector({ SelectedNetWork: makeSelectNetwork() }) export default connect(mapStateToProps)(ScanLoginPageForm)
import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import Button from '@material-ui/core/Button'; import Container from '@material-ui/core/Container'; import TextField from '@material-ui/core/TextField'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogTitle from '@material-ui/core/DialogTitle'; import { selectTodos } from './selector'; import { addTodo } from '../features/todo/todoSlice'; // import TodoDependency from '../containers/TodoDependency'; export default function TodoControl(props) { // eslint-disable-next-line react/prop-types // const { addTodo, todos } = props; const todos = useSelector(selectTodos); const dispatch = useDispatch(); const [open, setOpen] = React.useState(false); const [description, setDescription] = React.useState(''); const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; const handleDescriptionChange = (e) => { setDescription(e.target.value); }; const handleAdd = () => { setOpen(false); dispatch( addTodo({ todo: { description, }, }) ); }; /* <TodoDependency initiallyChecked={[]} todos={todos} /> */ return ( <Container> <Button variant="contained" color="primary" onClick={handleClickOpen}> Add Project </Button> <Dialog open={open} onClose={handleClose} aria-labelledby="form-dialog-title" > <DialogTitle id="form-dialog-title">Add TODO</DialogTitle> <DialogContent> <DialogContentText>Add a TODO, enter description</DialogContentText> <TextField autoFocus margin="dense" id="name" label="Description" fullWidth onChange={handleDescriptionChange} /> </DialogContent> <DialogActions> <Button onClick={handleClose} color="primary"> Cancel </Button> <Button onClick={handleAdd} color="primary"> Add </Button> </DialogActions> </Dialog> </Container> ); }
function largestSequenceInGrid(grid, seqLength) { const gridRows = grid.length, gridCols = grid[0].length; const largestHoriz = largestInLine(grid, (r,c) => [r, c + 1]); const largestVert = largestInLine(grid, (r,c) => [r + 1, c]); const largestDiag = largestInLine(grid, (r,c) => [r + 1, c + 1]); const largestRevDiag = largestInLine(grid, (r,c) => [r + 1, c - 1]); return Math.max(largestHoriz, largestVert, largestDiag, largestRevDiag); function largestInLine(grid, nextCoord) { let largest = 0; for(let row = 0; row < gridRows; row ++) { for(let col = 0; col < gridCols; col ++) { const seq = sequenceFrom(row, col, nextCoord) || [0]; const prod = seq.reduce((acc, el) => acc * el, 1); if(prod > largest) { largest = prod; } } } return largest; } function sequenceFrom(startRow, startCol, nextCoord) { const seq = []; let row = startRow, col = startCol; for(let inc = 0; inc < seqLength; inc ++) { if(row >= gridRows || col >= gridCols) return; seq.push(grid[row][col]); [row, col] = nextCoord(row, col); } return seq; } } let grid; if(typeof window === 'undefined') { grid = require('fs').readFileSync('./resources/11.txt', { encoding: 'utf8' }); } else { grid = document.querySelector('.problem_content p:nth-child(2)').innerText .trim() .split("\n") .map(row => row.split(/\s+/) .map(el => parseInt(el)) ); } console.log(largestSequenceInGrid(grid, 4));
import React, { Component } from 'react'; import { connect } from 'react-redux'; import {removeFromCart, getCart, getCartItems, getCartInfo} from "../../store/reducers/actions/cartActions"; import CartItems from './checkout/CartItems.jsx'; class Cart extends Component { componentDidMount() { if(!this.props.minicartId){ this.props.getCart(); }else{ this.props.getCartItems(this.props.minicartId); this.props.getCartInfo(this.props.minicartId); } } render() { return ( <main className="main checkout-cart-index"> <h1 className="cart-title">{'Your Shopping Cart'} { this.props.minicartQty > 0 ? '(' + this.props.minicartQty + ')' : '' }</h1> <div className="cart-table"> <ul className="cart-table-items"> { this.props.minicartItems.length ? this.props.minicartItems.map(product => { return ( <CartItems key={product.item_id} removeFromCart={(event) => this.props.removeFromCart(this.props.minicartId,product.item_id,product.sku)} title={product.name} price={product.price} qty={product.qty} /> ); }) : <li>{'You have no items in your shopping cart.'}</li> } </ul> <div className="cart-sidebar"> <div className="cart-summary"> {this.props.minicartSubtotals ? <div className="cart-summary-row cart-subtotals"> <strong>{'Cart Subtotal: '}</strong><span>{this.props.minicartSubtotals.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') + ' USD' }</span> </div> : '' } { this.props.minicartDiscount ? <div className="cart-summary-row cart-discount"> <strong>{'Cart Discount: '}</strong><span>{this.props.minicartDiscount.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') + ' USD' }</span> </div> : '' } {this.props.minicartShipping ? <div className="cart-summary-row cart-shipping"> <strong>{'Shipping: '}</strong><span>{this.props.minicartShipping.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') + ' USD' }</span> </div> : '' } {this.props.minicartTotals ? <div className="cart-summary-row cart-totals"> <strong>{'Cart Total: '}</strong><span>{this.props.minicartTotals.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') + ' USD' }</span> </div> : <div className="cart-summary-row cart-totals"> 0.00 USD </div> } </div> <div className="cart-actions"> {this.props.minicartTotals ? <button className="button-primary">{'Proceed to Checkout'}</button> : '' } </div> </div> </div> <div className="cart-subtitle"><strong>{'Cart ID: '}</strong><span>{ this.props.minicartId }</span></div> </main> ); } } function mapStateToProps(state){ return { minicartId: state.cart.minicartId, minicartItems: state.cart.minicartItems, minicartTotals: state.cart.minicartTotals, minicartSubtotals: state.cart.minicartSubtotals, minicartDiscount: state.cart.minicartDiscount, minicartShipping: state.cart.minicartShipping, minicartQty: state.cart.minicartQty, minicartCurrency: state.cart.minicartCurrency }; } const mapDispatchToProps = dispatch => { return { getCart: (minicartId,itemid,sku) => dispatch(getCart(minicartId,itemid,sku)), getCartItems: (minicartId,item,sku) => dispatch(getCartItems(minicartId,item,sku)), getCartInfo: (minicartId,item,sku) => dispatch(getCartInfo(minicartId,item,sku)), removeFromCart: (minicartId,itemid,sku) => dispatch(removeFromCart(minicartId,itemid,sku)) } }; export default connect(mapStateToProps, mapDispatchToProps)(Cart);
import { createStore, applyMiddleware} from 'redux'; import reducer from '../reducer/index'; import thunk from 'redux-thunk'; const enhanser = applyMiddleware(thunk); const store = createStore(reducer, {}, enhanser); //dev only window.store = store; export default store
import {useRecoilState} from "recoil"; import ComponentSelector from "~/components/organisms/DynamicTextBuilder_bak/components/ComponentSelector/ComponentSelector"; import TagExpander from "~/components/pageComponents/tagExpander/TagExpander"; import {pageRenderState} from "../templates/pageRender/PageRenderAtom"; import AddComponentLine from "./componentMenu/AddComponentLine"; import {StyledComponentRender} from "./ComponentRender.style"; import Container from "./container/Container"; import DynamicText from "./dynamicText/DynamicText"; import Grid from "./grid/Grid"; import GridCell from "./gridCell/GridCell"; import GridCollectionCell from "./gridCollectionCell/GridCollectionCell"; import Header from "./header/Header"; import PhotoCard from "./photoCard/photoCard"; import Title from "./title/Title"; import Paragraph from "./paragraph/Paragraph"; import Menu from "./menu/Menu"; import {defaultImageProps} from "./image/defaultProps"; import Image from "./image/Image"; import Tabs from "./tabs/Tabs"; import IfBlock from "./ifBlock/IfBlock"; import CurrencyConverter from "./currencyConverter/CurrencyConverter"; import CurrencyRateTable from "./currencyRateTable/CurrencyRateTable"; const ComponentRender = function ({component, apiData, parent, ...props}) { const [liveMode, setLiveMode] = useRecoilState(pageRenderState); if (liveMode == false) { if (Array.isArray(component)) { return ( <> {component.map((child, key) => { child = JSON.parse(JSON.stringify(child)); child.tags = [...parent.tags]; if (child.data && child.data.tags) child.tags = [...child.tags, ...child.data.tags]; return <ComponentRender index={key} key={key} parent={parent} component={child} />; })} {component.length == 0 && parent != null && <AddComponentLine parent={parent} component={null} location="before" className="add-component-line" />} </> ); } return ( <> {parent != null && component != null && props.index == 0 && ( <AddComponentLine parent={parent} component={component} location="before" className="add-component-line" /> )} {component != null && <Component component={component} />} {parent != null && <AddComponentLine parent={parent} component={component} location="after" className="add-component-line" />} </> ); } else { if (Array.isArray(component)) { return ( <> {component.map((child, key) => { child = JSON.parse(JSON.stringify(child)); child.tags = [...child.tags, ...parent.tags]; return <ComponentRender apiData={apiData} index={key} key={key} parent={parent} component={child} />; })} </> ); } return <Component apiData={apiData} component={component} />; } }; const Component = function ({component, apiData, ...props}) { const [liveMode, setLiveMode] = useRecoilState(pageRenderState); if (component != null) { switch (component.name) { case "title": return <Title liveMode={liveMode} component={component} apiData={apiData} />; case "paragraph": return <Paragraph liveMode={liveMode} component={component} apiData={apiData} />; case "grid": return <Grid liveMode={liveMode} component={component} apiData={apiData} />; case "gridCollectionCell": return <GridCollectionCell liveMode={liveMode} component={component} apiData={apiData} />; case "gridCell": return <GridCell liveMode={liveMode} component={component} apiData={apiData} />; case "container": return <Container liveMode={liveMode} component={component} apiData={apiData} />; case "header": return <Header liveMode={liveMode} component={component} apiData={apiData} />; case "photoCard": return <PhotoCard liveMode={liveMode} component={component} apiData={apiData} />; case "tagExpander": return <TagExpander liveMode={liveMode} component={component} apiData={apiData} />; case "dynamicText": return <DynamicText liveMode={liveMode} component={component} apiData={apiData} />; case "menu": return <Menu liveMode={liveMode} component={component} apiData={apiData} />; case "image": return <Image liveMode={liveMode} component={component} apiData={apiData} />; case "tabs": return <Tabs liveMode={liveMode} component={component} apiData={apiData} />; case "ifBlock": return <IfBlock liveMode={liveMode} component={component} apiData={apiData} />; case "currencyConverter": return <CurrencyConverter liveMode={liveMode} component={component} apiData={apiData} />; case "currencyRateTable": return <CurrencyRateTable liveMode={liveMode} component={component} apiData={apiData} />; default: return <>Component not in renderer '{component.name}'</>; } } return <></>; }; export default ComponentRender;
Ext.define('ESSM.controller.sys.UserController', { extend : 'Ext.app.Controller', requires : ['Ext.ux.TreePicker'], views : ['sys.UserView','sys.UserForm'], stores : ['sys.UserStore','sys.RoleStore'], models : ['sys.User'], refs : [{ ref : 'form', selector : 'userForm' },{ ref : 'grid', selector : 'userView' }], getMainView : function(){ return this.getView('sys.UserView'); }, init : function() { this.control({ 'userView button[action=create]' : { click : this.onCreateUser }, //更新 'userView button[action=update]': { click : this.onUpdateUser }, //删除 'userView button[action=delete]': { click : this.onDeleteUser }, //查询 'userView userFilter button[action=query]' : { click : this.onQuery },// 重置密码 'userView textactioncolumn': { resetpwdclick: this.resetPwd }, //同步用户 'userView button[action=sycUser]' : { click : this.sycUser }// 重置密码 }); }, sycUser:function(){ var me = this; wr.openFormWin({ title : '同步基础数据', items : { xtype: 'form', layout: 'column', fieldDefaults: { msgTarget: 'side', columnWidth: .3, style : { marginLeft : '25px' }, labelWidth: 90 }, items:[ { style : { marginTop : '20px' }, xtype: 'fieldcontainer', anchor: '60% 5%', items:[ { xtype: "datefield", name: "beginDate", width :250, format: 'Y-m-d', fieldLabel: "开始时间", id:'synBaseBeginTime1', vtype : 'daterange',//daterange类型为上代码定义的类型 endDateField : 'synBaseEndTime1'//必须跟endDate的id名相同 },{ xtype: "datefield", name: "endDate", width :250, format: 'Y-m-d', fieldLabel: "结束时间", id:'synBaseEndTime1', //axValue:new Date(), vtype : 'daterange',//daterange类型为上代码定义的类型 startDateField : 'synBaseBeginTime1' } ] } ] } },function(form,win){ form.form.submit({ url : "rest/sys/user/synchronismUserData.json", method : 'post', waitMsg : '正在同步数据...', success : function(form,r) { form.reset(); win.close(); Ext.Msg.alert('操作成功', '通过接口同步基础数据信息成功'); }, failure : function(form,action) { Ext.Msg.alert('操作失败', '通过接口同步基础数据信息异常'); } }); }); }, /** *新增用户 */ onCreateUser : function() { var me = this; //打开窗口 wr.openFormWin({ title : '新增用户', items : { xtype : 'userForm' } },function(form,win) { form.form.submit({ url : me.getGrid().getStore().getProxy().api.create, method : 'post', waitMsg : '正在保存数据...', success : function(form,action) { form.reset(); win.close(); me.getGrid().getStore().load(); }, failure : function(form,action) { Ext.Msg.alert('保存失败', action.result.message+'!'); } }); }); var content = me.getForm().queryById('departmentIdContent'); var store = Ext.create('ESSM.store.sys.DepartmentTreeStore'); content.add({ xtype:'treepicker', displayField : 'deptName', valueField : 'deptCode', fieldLabel: '<span style="color:red">*</span>所属部门', forceSelection : true, width : 300, store : store, name: 'departCode', allowBlank: false, tooltip: '请选择所选部门' }); }, /** *更新用户信息 */ onUpdateUser : function() { var records = this.getGrid().getSelectionModel().getSelection(), me = this; if(records.length==0) { Ext.MessageBox.alert('提示','请选择一条记录!'); return; } var record = records[0]; //打开窗口 wr.openFormWin({ title : '更新用户', items : { xtype : 'userForm' } },function(form,win) { form.form.submit({ url : me.getGrid().getStore().getProxy().api.update, method : 'post', waitMsg : '正在保存数据...', success : function(form,action) { form.reset(); win.close(); var records = me.getGrid().getSelectionModel().getSelection(); me.getGrid().getSelectionModel().deselect(records); me.getGrid().getStore().load(); }, failure : function(form,action) { Ext.Msg.alert('保存失败', '更新资源信息失败!'); } }); }); var pass = this.getForm().queryById('pass'); pass.setDisabled(true); pass.setVisible(false); var pass1 = this.getForm().queryById('pass1'); pass1.setDisabled(true); pass1.setVisible(false); this.getForm().queryById('user_username').setReadOnly(true); //设置角色setvalue Ext.Ajax.request({ url: 'rest/sys/user/findRolesByUserId.json', params: { id: record.get('id') }, success: function(response){ var text = response.responseText,vals =[],obj=[]; if(text){ obj = eval ("(" + text + ")"); vals = eval(text); } me.getForm().queryById("combo").setValue(vals); // me.getForm().queryById("combo").select(vals);/ } }); this.getForm().loadRecord(record); var store = Ext.create('ESSM.store.sys.DepartmentTreeStore'); this.getForm().queryById('departmentIdContent').add( Ext.create('Ext.ux.TreePicker',{ xtype:'treepicker', store : store, displayField : 'deptName', valueField : 'deptCode', fieldLabel: '<span style="color:red">*</span>所属部门', forceSelection : true, anchor : '60%', value : record.get('departCode'), width : 300, name: 'departCode', allowBlank: false, tooltip: '请选择所属部门' }) ); }, /** * 删除用户信息 */ onDeleteUser : function(){ var records = this.getGrid().getSelectionModel().getSelection(), url = this.getGrid().getStore().getProxy().api['destroy'], me = this; if(records.length==0) { Ext.MessageBox.alert('提示','请选择一条记录!'); return; } Ext.MessageBox.confirm('提示','您确实要删除选定的记录吗?', function(btn){ if(btn=='yes'){ Ext.Ajax.request({ url : url, params : {id : records[0].get('id')}, success:function(){ Ext.MessageBox.alert("成功","删除成功!"); me.getGrid().getStore().load(); } }); } }); }, /** *查询 */ onQuery : function(btn) { var me = this, form = btn.up('form'), values = form.getForm().getValues(); //查询 me.getStore('sys.UserStore').loadPage(1,{ params : values }); } , resetPwd : function (record, grid, rowIndex, colIndex, item, e) { // if(!record){ return; } if(!record.data){ return; } var data = {}; Ext.apply(data, record.data); // data.newPassword = randomPassword(data.name); var resetPwdForm = Ext.create("ESSM.view.sys.ResetPwdForm", { }); resetPwdForm.loadRecord({ data : data, getData: function(){ return this.data; } }); // var win = Ext.create('Ext.window.Window', { title: '重置密码', height: 260, width: 480, layout: 'fit', buttonAlign: 'center', modal : true, items: [resetPwdForm], buttons: [ { text: '确定', handler: resetHandler },{ text: '取消', handler: function (btn) { var w = btn.up('window'); w.close(); } } ] }); // win.show(); // function resetHandler(OKbtn) { // var form = resetPwdForm.getForm(); var isValid = form.isValid(); if(!isValid){ return; } // var params = form.getValues(); if(!params){ return; } var name = params.name; if(!name){ return; } Ext.MessageBox.confirm('提示','确定重置用户[' + name+']的密码?', function(btn){ if(btn=='yes'){ // url = "rest/sys/user/resetPwd.json"; // Ext.Ajax.request({ url : url, params : params, success:function(){ Ext.MessageBox.alert("成功","重置密码成功!"); // var w = OKbtn.up('window'); w.close(); } }); } }); // }; // function randomPassword(name){ name = name || "pwd"; name = name.substr(0,3); var r = 1000 + 9000 * Math.random(); // return name + "_"+ r.toFixed(0); }; } });
import flux from 'flux-react'; import actions from '../actions/actions.js'; var NavBarStore = flux.createStore({ status : { buttonVisible : false }, actions: [ actions.showBackButton, actions.hideBackButton ], showBackButton : function(){ this.status.buttonVisible = true; this.emit('app.toggleBackButton'); }, hideBackButton : function(){ this.status.buttonVisible = false; this.emit('app.toggleBackButton'); }, exports: { getButtonVisible : function(){ return this.status.buttonVisible; } } }); export default NavBarStore;
import { LightningElement, wire } from "lwc"; import fetchAttachment from "@salesforce/apex/FileUploader.fetchAttachment"; export default class PdfGenerate extends LightningElement { pdfData; @wire(fetchAttachment) wiredAttachment({ error, data }) { if (data) { this.pdfData = data; this.onLoad(); } else if (error) { console.log(error); } } onLoad() { this.template .querySelector("iframe") .contentWindow.postMessage(this.pdfData, "*"); } }
angular.module('jobzz') .controller('ProfileEmployeeCtrl', ['$scope', 'profileService', function ($scope, profileService) { profileService.getFullAccount('/employee/account/full').then(function (response) { $scope.employee = response; }); profileService.getAllReview('/employee/all/reviews').then(function (response) { $scope.responses = response; }); }]);
import React from 'react' import Image from './illustration.png' import './CSS/illustration.css' function Illustration({text}) { return ( <div className="illustration-main"> <div className="illustration-main-image"> <img src={Image}></img> </div> <div className="illustration-main-text"> <center><h1>{text}</h1></center> </div> </div> ) } export default Illustration
"use strict"; require("./core"); /* global DevExpress */ /* eslint-disable import/no-commonjs */ module.exports = DevExpress.renovation = {};
import React from "react"; import hero from "./../images/illustration-hero.svg"; import "./index.css"; const Header = () => { return ( <div className="header"> <div className="description"> <h1>A Simple Bookmark Manager</h1> <p> A clean and simple interface to organize your favourite websites .Open a new browser tab and see your sites load instantly. Try it for free. </p> <button className="g">Get it on Chrome</button> <button className="f">Get it on Firefox</button> </div> <div className="hero"> <img src={hero} alt="" /> </div> <div className="bluebox"></div> </div> ); }; export default Header;
//variable declarations var express = require('express'), mongoose = require('mongoose'), router = new express.Router(), isLoggedIn = require("../isLoggedIn.js"), request = require("request"); //mongoose connections var Video = require("../models/video"); var Location = require("../models/location"); router.get("/locations", function(req, res) { Location.find({}, function(err, allLocations){ if(err) { console.log("locations error"); } else { console.log(allLocations); res.render("./locations/locations", {locations: allLocations}); } }); }); //NEW location router.post("/videos/:id/locations", function(req, res){ Video.findById(req.params.id, function(err, video){ if (err) { console.log("error finding video") } else { var inputCoordinates = {lat:req.body.location.lat, lon: req.body.location.lon}; getAddressComponents(inputCoordinates, video); } }); }); function getAddressComponents(inputCoordinates, video) { var latlng = inputCoordinates.lat + "," + inputCoordinates.lon; var options = { method: 'GET', url: 'https://maps.googleapis.com/maps/api/geocode/json', qs: { latlng: latlng, key: 'AIzaSyDrZYTTKuilFIAwHNJgXbIgZH88D-PFdGw' }, headers: { 'postman-token': '79c75d32-259b-3219-4d20-aa6b462ac175', 'cache-control': 'no-cache' } }; request(options, function (error, response, body) { if (error) throw new Error(error); var inputLocation = {}; var obj = JSON.parse(body); var topResult = obj.results[0]; var components = topResult.address_components; components.forEach(function(component) { component.types.forEach(function(type){ if(type == "country"){ inputLocation.country = component.short_name; } if(type == "administrative_area_level_1"){ inputLocation.state = component.short_name; } if(type == "locality" || type == "sublocality") { inputLocation.city = component.long_name; } }); }); Location.findOneAndUpdate({'city': inputLocation.city, 'state': inputLocation.state, 'country': inputLocation.country}, inputLocation, {upsert:true}, function(err, location) { if(err) { console.log("location error"); console.log(err); } else { video.locations.push(location); video.save(); location.videos.push(video); location.save(); } }); }); }; module.exports = router;
(function() { var Main; Main = (function() { function Main(name) { this.name = name; this.hello; } Main.prototype.hello = function() { return alert(this.name); }; return Main; })(); document.Main = new Main("sammy"); }).call(this);
import angular from "/ui/web_modules/angular.js"; import {MnElementCargoComponent, MnElementDepotComponent} from "/ui/app/mn.element.crane.js"; import {downgradeComponent} from "/ui/web_modules/@angular/upgrade/static.js"; export default "mnElementCrane"; angular .module('mnElementCrane', []) .directive('mnElementDepot', downgradeComponent({component: MnElementDepotComponent})) .directive('mnElementCargo', downgradeComponent({component: MnElementCargoComponent}));
import { Router } from 'express'; import MenuController from '../controllers/menu.controller'; import CheckAuth from '../middleware/check-auth'; const router = Router(); router.get('/', MenuController.fetchMenu); router.post('/', CheckAuth.caterer, MenuController.addMeal); router.delete('/', CheckAuth.caterer, MenuController.deleteMeal); router.delete('/:menu_id', CheckAuth.caterer, MenuController.deleteMenu); export default router;
function printError(elemId, hintMsg) { document.getElementById(elemId).innerHTML = hintMsg; } function validateForm() { var name = document.contactForm.name.value; var email = document.contactForm.email.value; var password = document.contactForm.password.value; var gender = document.contactForm.gender.value; var toc = document.contactForm.toc; var nameErr = emailErr = passwordErr = genderErr = tocErr = true; // Validate name if(name == "") { printError("nameErr", "Please enter your name"); } else { printError("nameErr", ""); nameErr = false; } // Validate email address if(email == "") { printError("emailErr", "Please enter your email address"); } else { printError("emailErr", ""); emailErr = false; } // Validate password if(password == "") { printError("passwordErr", "Please enter your password"); } else { printError("passwordErr", ""); passwordErr = false; } // Validate gender if(gender == "") { printError("genderErr", "Please select your gender"); } else { printError("genderErr", ""); genderErr = false; } // Validate termCond checkbox if(!toc.checked){ printError("tocErr", "Please check this Terms and Conditions"); } else{ printError("tocErr", ""); tocErr = false; } if((nameErr && emailErr && passwordErr && genderErr && tocErr) == true) { document.getElementById("myForm").reset(); } if((nameErr || emailErr || passwordErr || genderErr || tocErr) == true) { return false; } };
import { getFirebase } from 'react-redux-firebase'; export default function fetchHosEnded(countryCode) { const firebase = getFirebase(); return firebase.unWatchEvent('value', countryCode); }
import React from "react"; import { url } from "./constants"; import { setChannels } from "./actions"; import { connect } from "react-redux"; import Routes from "./components/Routes"; class App extends React.Component { source = new EventSource(`${url}/stream`); componentDidMount() { this.source.onmessage = event => { const { data } = event; const channels = JSON.parse(data); this.props.setChannels(channels); }; } render() { return <Routes />; } } const mapDispatchToProps = { setChannels }; const mapStateToProps = state => { return { channels: state.channels }; }; export default connect( mapStateToProps, mapDispatchToProps )(App);
import { getUser } from './get-user'; describe('When everything is OK', () => { test('should return a response', async () => { const result = await getUser(); expect(result).toEqual({id: "1", name: "Paula"}); }); });
var path = require('path'); var View = require('./completion_rate'); var templatePath = path.resolve(__dirname, '../../templates/modules/user-satisfaction-graph.html'); module.exports = View.extend({ templatePath: templatePath, templateContext: function () { return { hasBarChart: this.model.get('parent').get('page-type') === 'module' }; } });
var noneCheck = false; $(document).ready(function(){ $('.questions').jScrollPane(); $("input:checkbox").change(function(){ processCheckboxEvent($(this)); }); $("input:checkbox").each(function(){ var noneFlag = $(this).attr("noneFlag"); if(noneFlag == "true" && $(this).is(':checked')){ noneCheck = true; } }); if(noneCheck){ $("input:checkbox").each(function(){ var noneFlag = $(this).attr("noneFlag"); if(noneFlag != "true"){ $(this).removeAttr("checked"); $(this).attr("disabled",true); } }); } if ( window.addEventListener ){ window.addEventListener('unload', function(){ if(syncFlag == false) _syncQuestionGroup(_questionGroupId); },false); }else{ window.attachEvent('onunload',function(){ if(syncFlag == false) _syncQuestionGroup(_questionGroupId); }); } if(_nurseViewFlag){ $("input:checkbox").each(function(){ var nurseCheck = $(this).attr("nurseCheck"); if(nurseCheck != true){ $(this).attr('disabled','disabled'); } }); $("input:radio").each(function(){ var nurseCheck = $(this).attr("nurseCheck"); if(nurseCheck != true){ $(this).attr('disabled','disabled'); } }); $("input:text").each(function(){ var nurseCheck = $(this).attr("nurseCheck"); if(nurseCheck != true){ $(this).attr('disabled','disabled'); } }); } if(_needRequest == "true"){ $.fancybox.open({ href : _requestPath + "/member/resultRequestForm",type : 'iframe', openEffect : 'elastic',closeEffed : 'elastic', autoSize : false,width : 720,height : 800 }); } }); function clickCheckboxLink(id){ if(_nurseViewFlag == "true"){ return; } var checkObj = $("#"+id); if(checkObj.is(':disabled')){ return; } if(!checkObj.is(':checked')){ checkObj.attr("checked",true); }else{ checkObj.attr("checked",false); } processCheckboxEvent(checkObj); } function processCheckboxEvent($checkObj){ var toggleFlag = ""; var questionItemId = $checkObj.attr("id"); var noneFlag = $checkObj.attr("noneFlag"); if(noneFlag == "true"){ if($checkObj.is(':checked')){ toggleFlag = "true"; //다른 값들을 다 check해제하고 disable처리한다. doToggle(questionItemId,true); noneCheck = true; }else{ toggleFlag = "false"; noneCheck = false; //다른 값들을 enable처리한다. doToggle(questionItemId,false); } //서버에 Ajax를 이용해서 현재 질문의 답을 submit한다. var params = {questionItemId:questionItemId,toggleFlag:toggleFlag}; doSubmit(params,questionItemId); } } function doToggle(questionItemId,disable){ $("input:checkbox").each(function(){ var itemId = $(this).attr("id"); if(questionItemId != itemId){ if(disable){ $(this).removeAttr("checked"); $(this).attr("disabled",true); }else{ $(this).removeAttr("disabled"); } } }); } function doSubmit(params,itemId){ $.ajax({ dataType: 'json', type : 'POST', async : false, url : _requestPath + '/member/checkup/nutrition/toggleNoneFlag', timeout : 12000, data : params, beforeSubmit : function(){ }, success : function(result){ var success = result.success; if(success){ }else{ alert(result.msg); } }, error : function(response, status, err){ alert("네트워크가 불안정합니다. 다시한번 시도해보세요."); } }); //Ajax로 호출한다. } function clickCompleted(itemId,existChild){ if(existChild == 'true') showDepth(itemId); } function showDepth(){ if(noneCheck){ _syncQuestionGroup(_questionGroupId,function(){ syncFlag = true; document.location.href = _requestPath + _nextUrl; }); // setTimeout(function(){ // //다음페이지로 이동한다. // document.location.href = _requestPath + _nextUrl; // },100); return; } $("html, body").animate({ scrollTop: 0 }, "fast"); wrapWindowByMask(); var questionId; var itemIds = new Array(); $("input:checkbox").each(function(){ if($(this).is(':checked')){ var itemId = $(this).attr("id"); itemIds.push(itemId); questionId = $(this).attr("questionId"); } }); if(itemIds.length == 0){ alert("먼저 항목을 체크하세요."); hideMask(); return; } $("#second-depth-question-container").show(500); var secondFrame = $("#second-depth-frame"); if(_nurseViewFlag){ secondFrame.attr("src",_requestPath + "/nurse/nutrition/secondDepth/" + questionId + "?selectedItemIds=" + itemIds.join(",") + "&instanceId=" + _instanceId); }else{ secondFrame.attr("src",_requestPath + "/member/checkup/nutrition/secondDepth/" + questionId + "?selectedItemIds=" + itemIds.join(",")); } secondFrame.load(function(){ }); } function hideDepth(itemId){ //서버에 해당 item에 대한 대답을 clear시켜주어야한다. close2Depth(); } function close2Depth(){ hideMask(); $("#second-depth-question-container").hide(); //갤럭시 노트에서만 이것을 안하게 해야할듯... if(!_isMobile()){ $("#second-depth-frame").attr("src","about:blank"); } } /** * 2Depth이하의 질문이 완료된 경우에 호출된다. * @param itemId */ function complete2Depth(itemId,questionId,isRadio,goNext){ close2Depth(); checkCompleted(itemId,questionId,isRadio); if(goNext){ _syncQuestionGroup(_questionGroupId); syncFlag = true; setTimeout(function(){ //다음페이지로 이동한다. document.location.href = _requestPath + _nextUrl; },100); } } function goPre(url){ _syncQuestionGroup(_questionGroupId); syncFlag = true; setTimeout(function(){ //다음페이지로 이동한다. document.location.href = _requestPath + url; },100); } function goNext(url){ //모든것을 다 했는지 체크해야한다. var canGoNext = true; $("input:hidden").each(function(){ var id = $(this).attr("id"); if(id.startsWith("complete_flag_")){ var val = $(this).val(); if(val == "false"){ canGoNext = false; } } }); if(canGoNext){ _syncQuestionGroup(_questionGroupId); syncFlag = true; setTimeout(function(){ //다음페이지로 이동한다. document.location.href = _requestPath + url; },100); }else{ alert("필수 질문에 답변을 하셔야 이동가능합니다."); } } function goQuestionGroup(groupId,sortOrder){ if(_nurseViewFlag==true || _nurseViewFlag == "true"){ document.location.href = _requestPath + "/nurse/view/" + _patientNo + "?instanceId=" + _instanceId + "&questionGroupId=" + groupId; }else{ var canGoNext = true; if(_lastQuestionGroupSortOrder >= sortOrder){ }else{ $("input:hidden").each(function(){ var id = $(this).attr("id"); if(id.startsWith("complete_flag_")){ var val = $(this).val(); if(val == "false"){ canGoNext = false; } } }); } if(canGoNext){ _syncQuestionGroup(_questionGroupId); syncFlag = true; setTimeout(function(){ //다음페이지로 이동한다. document.location.href = _requestPath + "/member/checkup/questionGroup/" + groupId; },100); }else{ alert("필수 질문에 답변을 하셔야 이동가능합니다."); } } } function viewHelp(questionGroupId){ $.fancybox.open({ href : _requestPath + "/member/checkup/help/" + questionGroupId,type : 'iframe', openEffect : 'elastic',closeEffed : 'elastic', autoSize : false,width : 600,height : 500 }); } function wrapWindowByMask(){ //화면의 높이와 너비를 구한다. var maskHeight = $(document).height(); var maskWidth = $(window).width(); //마스크의 높이와 너비를 화면 것으로 만들어 전체 화면을 채운다. $('#mask').css({'width':maskWidth,'height':maskHeight}); //애니메이션 효과 $('#mask').show(); } function hideMask(){ $('#mask, .window').hide(); } function checkCompleted(){ //TODO }
$(function () { massageObjects = [{ name : "Sports Massage", description : "A massage specific to athletes and the muscles they use in their particular sport.\ <br><br>\ Sports massages help to prevent injury and maintain a healthy body that performs at the optimum level.\ The focus is on stretching and lengthening the muscles while keeping the area warm, and \ reducing lactic acid build up.\ <br><br>\ Sports massages can be used pre-event, post-event, or just to maintain flexibility and overall health!", images : [{image: 'muscle_guy.jpg', tags: "Kalamazoo Massage sports massage"}, {image: 'sports_massage_volleyball.jpg', tags: "Kalamazoo Massage sports massage"}], links : [{name: 'Benefits of Massage For Atheletes - Kerrie Ann Frey', url: 'http://www.healthfitnessmag.com/Health-Fitness-Magazine/February-2013/Benefits-Of-Massage-For-Athletes/'}, {name: 'The Role of Massage in Sports Performance and Rehabilitation: Current Evidence and Future Direction - Jason Brummitt', url: 'https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2953308/'}] }, { name: "Children's Massage", description: "I cater my massages to everybody, even your child! Let me help your little one relax and feel the magic of what a true massage is like.\ <br><br>\ Massages have countless benefits for children, especially children with ADHD and other behavioral issues.\ It's very important to learn to relax when you're stressed out, so let me teach your child relaxation methods while they lay \ on the massage table.\ <br><br>\ If you want, I can even teach you some techniques to use on your children at home!", images: [{image: "baby_massage.jpg", tags: "Kalamazoo Massage child massage"}, {image:"child_massage.jpg", tags: "Kalamazoo Massage child massage"}], links: [{name: "Some Benefits of Massage for Children", url: "http://www.livestrong.com/article/114384-benefits-massage-children/"}] }, { name : "Deep Tissue Massage", description : "A good deep tissue massage can assist you with years of pain, and release tension in chronically tense \ areas such as the neck, lower back, and shoulders.\ <br><br>\ These types of massages work by physically breaking down \ adhesions in the muscle to relieve pain and restore normal movement. Just to warn you, this type of massage will \ probably give discomfort, but the benefits to the discomfort are <u>so</u> worth it.", images : [{image: "Funnydeeptissue.jpg", tags: "Kalamazoo Massage deep tissue massage"}], links :[{name: 'Information about Deep Tissue Massage', url: 'http://www.happymassage.com/wiki/Deep_Tissue_Massage'}] }, { name : "Trigger Point Therapy", description : "Trigger point therapy is one of the most basic and essential parts of professional massage.\ <br><br> \ Have you ever heard anyone use the term 'knot' before, when they're talking about their body? Well that's what \ a trigger point is, a 'knot'!\ <br><br>\ Trigger point therapy is the process of helping your body release all of that 'bunched up' tension, \ and let me be the first to tell you that a professional session with me will make you think twice about ever getting your \ trigger points worked on by anybody else.", images : [{image: "trigger_point_therapy.jpg", tags: "Kalamazoo Massage trigger point therapy"}, {image: 'trigger_point_diagram.jpg', tags: "Diagram of trigger points"}], links : [{name: 'Myofascial Trigger Point - Wikipedia Article', url: 'https://en.wikipedia.org/wiki/Myofascial_trigger_point'}] }, { name : "Lymphatic Drainage Massage", description : "Your body's lymph nodes help to cleanse your blood from toxins that are released throughout the day. \ They also help to regulate your immune system!\ <br><br>\ Lymphatic drainage massages help to increase lymph node performance, and decrease lymph adema; swelling and water-retention.\ <br><br>\ These types of massages are usually prescribed by doctors after a surgery on the lymph nodes, but don't let that stop you from asking me to massage these areas. It feels too good not to!", images : [{image :"lymphatic_drainage_massage.jpg", tags:"Kalamazoo Massage lymphatic drainage massage"}], links : [{name: "Information about the Lymphatic System", url:"https://en.wikipedia.org/wiki/Lymphatic_system"}] }, { name : "Pregnancy Massage", description : "Are you feeling stressed out and tired from carrying all that extra weight? \ Can you feel pain and strain on your lower back, or legs?\ <br><br>\ As a mother of two, I know what pregnancy can do to the body. I also know how to help relieve some of the stress that comes with it!\ Side-lying massages are always an option when needed.\ <br><br>\ I'll make sure to make you feel completely comforted as I work on your strained back and legs, and other overworked muscles. \ <br><br>\ The inherent benefits on mood from massage will also help you and your partner in these challenging times!\ Near your due date, I can apply trigger point therapy to help induce labor, and loosen the muscles in your hips for an easier delivery", images : [{image :"pregnancy_massage_img.jpg", tags: "Kalamazoo Massage pregnancy massage"}], links : [] }, { name : "Pre and Post Operation Massage", description : "Surgery is very stressful. I'm here to help relieve that stress, and directly improve\ your healing time.\ <br><br>\ Massages before any operation help to relieve any stress and anxiety that \ you may have, and even help to build the immune system up against those nasty hospital germs you'll be exposed to!\ <br><br>\ After surgery, massages help healing time dramatically by providing extra blood flow, \ reducing swelling and scar tissue, and promoting flexibility and mobility in the affected area.\ <br><br>\ In general, you'll also feel better because \ massages help promote better overall moods! Basically, if you aren't getting massages before or after your operations \ you're really missing out!", images : [{image: "pre_post_surgery_img.jpg", tags: "Kalamazoo Massage Pre and Post Operation Massage"}], links : [{name: '8 Science-Backed Benefits of Massage After Surgery', url: 'http://www.surgerysupplements.com/8-science-backed-benefits-of-massage-after-surgery/'}] }] serviceObjects = [ { name: "Massages at the office", description: "Quite possibly the best way that you can show your employees that you care about them \ is by offering them massages at the workplace!\ <br><br>\ I bring my personal massage chair to every in-office massage, \ so you can rest easy knowing that your employees are being given the best possible care.\ <br><br>\ If you feel like you want to set up massages for your employees (and yourself, of course), please give me a call or an e-mail!", images: [{image: "office_massage.jpg", tags: "Kalamazoo Massage Office Massage"}, {image: "chair_mossage.jpg", tags: "Homemade flyer for chair Massages!"}], links: [] }, { name : "On-Site Event Massages", description : "I have brought my massage chair to many different types of events and retreats, including spiritual retreats, church luncheons,\ fundraising events, and even 5K, bike, and triathalon races.\ <br><br>\ Any event that has people standing for long hours or doing any type of repeated movements is an opportunity for me \ to help relax their tired muscles. If you have an event that you feel would be made even better with massages, please call or e-mail me \ and we can set something up!", images: [{image: "event_massages.jpg", tags: "Kalamazoo Massage Event Massage"}, {image: "mo_event_massage.jpg", tags: "Mo massaging another happy customer"}], links: [] }] codeOfConductObj = { name: "Code of Conduct/Ethics", embed: "code_of_ethics.pdf" } var Massage = function (data) { this.name = ko.observable(data.name); this.description = ko.observable(data.description); this.images = ko.observableArray(data.images); this.links = ko.observableArray(data.links); } var Service = function (data) { this.name = ko.observable(data.name); this.description = ko.observable(data.description); this.images = ko.observableArray(data.images); this.links = ko.observableArray(data.links); } var codeOfConduct = function (data) { this.name = ko.observable(data.name); this.embed = ko.observable(data.embed); this.images = ko.observable(undefined); } var viewModel = function () { var self = this; this.massages = ko.observableArray([]); this.services = ko.observableArray([]); this.codeOfConduct = ko.observable(); for (m in massageObjects) { this.massages.push(new Massage(massageObjects[m])) } for (s in serviceObjects) { this.services.push(new Service(serviceObjects[s])) } this.codeOfConduct(new codeOfConduct(codeOfConductObj)) this.currentObject = ko.observable(this.massages()[0]) this.leftNavItems = ["About", "Services", "Booking", "Contact"] this.switchCurrentObject = function (object) { self.currentObject(object); } this.toggleMassagePage = function() { var overlay = $("#overlay"); var body = $("body") if (overlay.css('display') == 'none') { overlay.show('slow') body.toggleClass("noscroll") } else { overlay.hide('fast'); body.toggleClass("noscroll") } } this.reviews = ko.observableArray([]) } ko.applyBindings(new viewModel()); // Applies custom click event to the '.nav-texts' and based on the value they get, scrolls to that // specific anchor. var about = $("#about-body"); var services = $("#services-div"); var booking = $("#booking-div"); var contact = $("#footer-div"); var offset = 100; $('.nav-text, #brand-name').click(function (object) { var x, y var navItemLoc = { "brand-name": [0,0], "about" : [about.offset().left, about.offset().top - offset], "services" : [services.offset().left, services.offset().top - offset], "contact" : [contact.offset().left, contact.offset().top - offset], "booking" : [booking.offset().left, booking.offset().top - offset] } x = navItemLoc[object.currentTarget.id][0] y = navItemLoc[object.currentTarget.id][1] $('#navbar-meat').collapse('hide'); $('html, body').animate({ scrollTop: y }, 2000); }) $('.collapse').on('show.bs.collapse', function() { $('.navbar-toggle').html('close').toggleClass('red'); }) $('.collapse').on('hide.bs.collapse', function() { $('.navbar-toggle').html('<span class="icon-bar"></span>\ <span class="icon-bar"></span>\ <span class="icon-bar"></span>').toggleClass('red'); }) })
import {useContext} from 'react'; import {Link} from 'react-router-dom'; import {AppContext} from '../../context-provider/App-Context'; import classes from './MainHeader.module.css'; function MainHeader() { const context = useContext(AppContext); return ( <header className={classes.header}> <div className={classes.logo}>React Meetup</div> <nav> <ul> <Link to={"/"}> <li>All Meetups</li> </Link> <Link to={"/new_meetup"}> <li>New Meetup</li> </Link> <Link to={"/favourites"}> <li> Favourites <span className={classes.badge}>{context.totalFavourites}</span> </li> </Link> </ul> </nav> </header> ) } export default MainHeader;
(function() { angular .module('loc8rApp') .service('pharmaReport', pharmaReport); pharmaReport.$inject = ['$http']; function pharmaReport ($http) { var getPharmaReportSummary = function (profile_id, offset, limit) { return $http.get('/api/getPharmacogenomicReport?profile_id=' + profile_id); }; return { getPharmaReportSummary : getPharmaReportSummary }; } })();
module.exports.home = (req,res,next)=>{ var fs = require('fs'); var names = fs.readdirSync('public/images/'); var paths = []; for (var i = 0, len = names.length; i < len; i++) { var s ='images/'+names[i]; paths.push(s); }; res.render('gallery', { imgs: paths, layout:false}); };
import "./index.scss"; const change = msg => { document.querySelector("body").innerText = msg; }; document.querySelector("body").innerText = "Hello, World!"; setTimeout(() => { change("Deferred hello world!"); }, 3000);
var mn = mn || {}; mn.components = mn.components || {}; mn.components.MnBucketsItemDetails = (function (Rx) { "use strict"; mn.core.extend(MnBucketsItemDetails, mn.core.MnEventableComponent); MnBucketsItemDetails.annotations = [ new ng.core.Component({ selector: "mn-buckets-item-details", templateUrl: "app-new/mn-buckets-item-details.html", inputs: [ "bucket" ], changeDetection: ng.core.ChangeDetectionStrategy.OnPush }) ]; MnBucketsItemDetails.parameters = [ mn.services.MnBuckets, mn.services.MnPermissions, mn.services.MnTasks, window['@uirouter/angular'].UIRouter, mn.services.MnAdmin, ngb.NgbModal ]; MnBucketsItemDetails.prototype.getWarmUpTasks = getWarmUpTasks; MnBucketsItemDetails.prototype.getBucketRamGuageConfigParams = getBucketRamGuageConfigParams; MnBucketsItemDetails.prototype.getGuageConfig = getGuageConfig; return MnBucketsItemDetails; function MnBucketsItemDetails(mnBucketsService, mnPermissionsService, mnTasksService, uiRouter, mnAdminService, modalService) { mn.core.MnEventableComponent.call(this); this.editButtonClickEvent = new Rx.Subject(); this.isRebalancing = mnAdminService.stream.isRebalancing; var bucketCurrentValue = this.mnOnChanges.pipe(Rx.operators.pluck("bucket", "currentValue")); var bucketName = bucketCurrentValue.pipe(Rx.operators.pluck("name")); var thisBucketCompactionTask = Rx.combineLatest( bucketName.pipe(Rx.operators.distinctUntilChanged()), mnTasksService.stream.tasksBucketCompaction ).pipe( Rx.operators.map(function (values) { return _.find(values[1], function (task) { return task.bucket === values[0]; }); }) ); this.editButtonClickEvent.pipe( Rx.operators.takeUntil(this.mnOnDestroy) ).subscribe(function (bucket) { var ref = modalService.open(mn.components.MnBucketsDialog); ref.componentInstance.bucket = bucket; }); this.thisBucketCompactionProgress = thisBucketCompactionTask.pipe( Rx.operators.map(function (task) { return task ? (task.progress + "% complete") : "Not active"; }) ); this.tasksRead = mnPermissionsService.createPermissionStream("tasks!read"); this.warmUpTasks = mnTasksService.stream.tasksWarmingUp.pipe( Rx.operators.withLatestFrom(bucketCurrentValue), Rx.operators.map(this.getWarmUpTasks.bind(this)) ); this.bucketSettingsWrite = mnPermissionsService.createPermissionStream("settings!write", bucketName); this.bucketRamGuageConfig = bucketCurrentValue.pipe( Rx.operators.map(this.getBucketRamGuageConfigParams.bind(this)), Rx.operators.map(mnBucketsService.getBucketRamGuageConfig), mn.core.rxOperatorsShareReplay(1) ); this.bucketRamGuageConfigTotal = this.bucketRamGuageConfig.pipe( Rx.operators.pluck("topRight", "value"), mn.core.rxOperatorsShareReplay(1) ); this.bucketDiskGuageConfig = bucketCurrentValue.pipe( Rx.operators.map(this.getGuageConfig.bind(this)), Rx.operators.map(mnBucketsService.getGuageConfig), mn.core.rxOperatorsShareReplay(1) ); this.bucketDiskGuageConfigTotal = this.bucketDiskGuageConfig.pipe( Rx.operators.pluck("topRight", "value"), mn.core.rxOperatorsShareReplay(1) ); } function getWarmUpTasks(values) { var bucket = values[1]; var tasks = values[0]; if (!bucket || !tasks) { return; } return _.filter(tasks, function (task) { var isNeeded = task.bucket === bucket.name; if (isNeeded) { task.hostname = _.find(bucket.nodes, function (node) { return node.otpNode === task.node; }).hostname; } return isNeeded; }); } function getBucketRamGuageConfigParams(details) { if (!details) { return; } return { total: details.basicStats.storageTotals.ram.quotaTotalPerNode * details.nodes.length, thisAlloc: details.quota.ram, otherBuckets: details.basicStats.storageTotals.ram.quotaUsedPerNode * details.nodes.length - details.quota.ram }; } function getGuageConfig(details) { return { total: details.basicStats.storageTotals.hdd.total, thisBucket: details.basicStats.diskUsed, otherBuckets: details.basicStats.storageTotals.hdd.usedByData - details.basicStats.diskUsed, otherData: details.basicStats.storageTotals.hdd.used - details.basicStats.storageTotals.hdd.usedByData }; } })(window.rxjs);
/** * Defines user agent for browser instances * * @type {{desktop: {name: string, userAgent: string, viewport: {width: number, height: number}}}} */ module.exports = { desktop: { 'name': 'Desktop', 'userAgent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36', 'viewport': { 'width': 1280, 'height': 800, } } };
$(document).ready(function () { /* |-------------------------------------------------------------------------- | CHANGING PASSWORD FUNCTION |-------------------------------------------------------------------------- | WHEN THE ADD CURRENCY FORM SUBMIT BUTTON IS CLICKED |-------------------------------------------------------------------------- | */ $("#form").submit(function (e) { e.preventDefault(); fade_in_loader_and_fade_out_form("loader", "form"); var form_data = $("#form").serialize(); var bearer = "Bearer " + localStorage.getItem("worker_access_token"); send_restapi_request_to_server_from_form("post", worker_api_security_change_password_url, bearer, form_data, "json", change_password_success_response_function, change_password_error_response_function); }); }); /* |-------------------------------------------------------------------------- | CHANGING PASSWORDRESPONSE FUNCTIONS |-------------------------------------------------------------------------- |-------------------------------------------------------------------------- | */ function change_password_success_response_function(response) { show_notification("msg_holder", "success", "Success:", "Password changed successfully. You will have to sign-in again"); fade_out_loader_and_fade_in_form("loader", "form"); $('#form')[0].reset(); } function change_password_error_response_function(errorThrown) { fade_out_loader_and_fade_in_form("loader", "form"); show_notification("msg_holder", "danger", "Error", errorThrown); }
'user strict' module.exports = (sequelize, DataTypes) => { const Bookmark = sequelize.define('bookmark', { active: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true } }, { paranoid: true }); return Bookmark }
// Tags in double mustaches automatically escape HTML: {{ contents }}
/* * 解析body * eg:post来传递表单,json数据,或者上传文件 * (xml数据没办法通过koa-bodyparse解析,有另一个中间件koa-xml-body) */ const bodyParser = require("koa-bodyparser"); // 用来处理跨域的中间件 const cors = require("kcors"); // 静态资源请求中间件 const serve = require("koa-static"); const path = require("path"); const requestBodyParser = bodyParser({ enableTypes: ["json", "form"], formLimit: "10mb", jsonLimit: "10mb" // 参数 // enableTypes:设置解析类型,默认为[‘json’, ‘form’]。 // encoding:请求编码。默认值是utf-8。 // formLimit:表单大小上限。如果大于此限制,则返回413错误代码。默认是56kb。 // jsonLimit:json大小上限。默认是1mb。 // textLimit:text大小上限。默认是1mb。 // strict:当设置为true时,为严格模式,JSON解析器只接受数组和对象。默认是true。 // detectJSON:自定义json请求检测功能。默认是null。 }); // 为header加上CORS,客户端即可跨域发送请求 const corsSet = (ctx, next) => { const { origin } = ctx.request.header; //根据前台 return cors({ // 允许所有客户端的访问,非安全配置 origin: origin, credentials: true, //是否允许用户发送、处理 cookie allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH", "OPTIONS"], exposeHeaders: ["X-Request-Id"] //允许脚本访问的返回头 -->X-Request-Id:客户端可以创建一些随机ID并将其传递给服务器 })(ctx, next); /** * CORS middleware * * @param {Object} [options] * - {String|Function(ctx)} origin `Access-Control-Allow-Origin`, default is request Origin header * - {String|Array} allowMethods `Access-Control-Allow-Methods`, default is 'GET,HEAD,PUT,POST,DELETE,PATCH' * - {String|Array} exposeHeaders `Access-Control-Expose-Headers` * - {String|Array} allowHeaders `Access-Control-Allow-Headers` * - {String|Number} maxAge `Access-Control-Max-Age` in seconds * - {Boolean} credentials `Access-Control-Allow-Credentials` * - {Boolean} keepHeadersOnError Add set headers to `err.header` if an error is thrown * @return {Function} cors middleware * @api public */ }; //引入静态资源文件夹 //way1 const staticPath = (app, paths = ["public"]) => { return paths.map(path => app.use(serve(path))); }; //way2 // const staticPath = (app, paths = "../../../public") => { // app.use(serve(path.join(__dirname, paths))); // }; module.exports = { requestBodyParser, corsSet, staticPath };
class Paddle extends GameObject { constructor(x, y) { super(x, y); this._paddleSpeed = 10; this.width = 15; this.height = 100; this.view = new PaddleView(this); } get paddleSpeed() { return this._paddleSpeed; } goUp() { if (this.position.y > 0) { this.position.add(createVector(0, -this._paddleSpeed)); } } goDown() { if (this.position.y + this.height < window.innerHeight) { this.position.add(createVector(0, this._paddleSpeed)); } } }
import React from 'react'; import BlogPost from '../BlogPost/BlogPost'; import tony from '../../../images/bloger.png'; import './Blogs.css' const blogData = [ { title : 'Troubleshooting Anti-Lock Brakes', description : 'The brakes on your vehicle work hard every time you drive. When you slow down in traffic, stop at a red light, or must maneuver a quick hard stop because of an obstruction in the road your brakes are at work. Over time the use of your brakes causes normal wear and tear, which can […]', author:'Mr.Mechanic', authorImg : tony, date : '23 April 2019' }, { title : 'ABS has become pretty much standard equipment on most vehicles', description : 'This process repeats many times per second until the vehicle stops or you lift your foot off the brake pedal. The ABS computer does a power-on self test every time you cycle the ignition.', author:'Mr.Mechanic', authorImg : tony, date : '23 April 2019' }, { title : 'How to Diagnose Car Problems If You Don’t Know Much About Cars', description : 'Lorem ipsum dolor sit amet consectetur, adipisicing elit. Ea, placeat totam laborum maiores, esse assumenda porro error natus sit ipsam. ', author:'Mr.Mechanic', authorImg : tony, date : '23 April 2019' }, ] const Blogs = () => { return ( <section className="blogs my-5" id="blogs"> <div className="container"> <div className="section-header text-center"> <h5 className="text-primary text-uppercase">our blog</h5> <h1>From Our Blog News</h1> </div> <div className="card-deck mt-5"> { blogData.map(blog => <BlogPost blog={blog} key={blog.title}/>) } </div> </div> </section> ); }; export default Blogs;
//============ LetsUpgrade JavaScript DAY 2 Assignment ================== //============================== Program 1 ============================== //Program to search for a particular character in a string function search_character(str) { return str.search("Developer") } console.log(search_character("I am a JavaScript Developer")) //============================== Program 2 ============================== //Program to convert minutes to seconds function convert_min_to_sec(min) { return min * 60 } console.log(convert_min_to_sec(5)) //============================== Program 3 ============================== //Program to search for an element in an array of strings function search_element(arr) { return arr.indexOf('A') } console.log(search_element(['B', 'O', 'A', 'M'])) //============================== Program 4 ============================== //Program to display only elements containing 'a' in them from a array function containing_elements_a(arr) { return arr.includes('A') } console.log(containing_elements_a(['B', 'M', 'A', 'O'])) //============================== Program 5 ============================== //Print an array in reverse order function reverse_array(arr) { return arr.reverse() } console.log(reverse_array(['End', 'The'])) //============================== THE END =================================
import React from 'react' import PropTypes from 'prop-types' import {connect} from 'react-redux' import TopbarVilla from "../topbar/villa/TopbarVilla"; import SidebarVilla from "../sidebar/dashboard/villa/SidebarVilla"; const MainVilla = (props)=> { return( <div className={'site-villa'}> <TopbarVilla/> <SidebarVilla/> {props.children} </div> ) } MainVilla.propTypes = { children : PropTypes.element.isRequired } const mapStateToProps = state => ({ }) export default connect(mapStateToProps, {})(React.memo(MainVilla))
var _=require("lodash"); var worker =function getActiveUsers(users){ return _.where (users, active:true); }; module.exports=worker;
"use strict"; //Very simple module that handles mouse position based parallax //Could easily be expanded to include more layers app.parallax = (function() { let a = app; function update() { let sp = a.state.parallax; if (!sp.enabled) return; let mouse = a.keys.mouse(); if (!mouse) return; let center = [ a.viewport.width / 2, a.viewport.height / 2 ]; let vec = [ mouse[0] - center[0], mouse[1] - center[1] ]; sp.mainParallax = [ vec[0] * sp.mainScale, vec[1] * sp.mainScale ]; sp.scrubberParallax = [ vec[0] * sp.scrubberScale, vec[1] * sp.scrubberScale ]; sp.scrubberShadow = [ a.utils.norm(mouse[0], a.viewport.width * 2, 0) * 0.5, a.utils.norm(mouse[1], -a.viewport.height, a.viewport.height) * 0.5 ]; } return {update: update} }());
import { REQUEST_POSTS, requestPosts } from '../actions' describe("actions", () => { it("creates an action to update isFetching", () => { const sub = 'reactjs' const expectedAction = { type: REQUEST_POSTS, sub } expect(requestPosts('reactjs')).toEqual(expectedAction) }) })
import React, { useContext, useEffect } from "react"; import { Link as RouterLink } from "react-router-dom"; import { Button, Divider, Grid, IconButton, Link, Typography, } from "@mui/material"; import { Box } from "@mui/system"; import { GlobalContext } from "../../context/GlobalState"; import EditIcon from "@mui/icons-material/Edit"; import DeleteIcon from "@mui/icons-material/Delete"; import userService from "../../api/services/userService"; export const UserList = (props) => { let { users, removeUser, fetchUsers, isDataLoaded, updateNotificationStatus, } = useContext(GlobalContext); class Person { constructor(openNotification, notificationType, notificationMessage) { this.openNotification = openNotification; this.notificationType = notificationType; this.notificationMessage = notificationMessage; } } const dispatchNotification = (snackBarOptions) => { updateNotificationStatus(snackBarOptions); }; const removeUserFn = (id) => { userService .deleteUser(id) .then((res) => { removeUser(id); updateNotificationStatus({ openNotification: true, notificationType: "success", notificationMessage: "User Deleted", }); }) .catch((err) => { dispatchNotification( new Person(true, "error", "Failed to delete the user") ); }); }; useEffect(() => { !isDataLoaded && userService .getUser() .then((res) => { fetchUsers(res.data.data); }) .catch((err) => { dispatchNotification( new Person(true, "error", "Failed to fetch the users") ); }); }, []); return ( <> <Box sx={{ p: 2 }}> <Grid container justifyContent="space-between" spacing={2}> <Grid item> <Typography variant="h4">Users List</Typography> </Grid> <Grid item> <RouterLink to="/add"> <Button variant="contained">Add User</Button> </RouterLink> </Grid> </Grid> </Box> <Divider /> <Box sx={{ p: 2 }}> {users.length ? ( <Grid container direction="row" alignItems={"center"} spacing={2}> {users.map(({ first_name, last_name, email, id }) => ( <React.Fragment key={id}> <Grid item xs={8} sm={10}> <Typography> {first_name} {last_name} </Typography> <Link href={`mailto:${email}`} target="_blank" rel="noopener" underline="hover" > {email} </Link> </Grid> <Grid item xs={2} sm={1}> <RouterLink to={`edit/${id}`}> <IconButton color="info"> <EditIcon /> </IconButton> </RouterLink> </Grid> <Grid item xs={2} sm={1}> <IconButton color="error" onClick={() => removeUserFn(id)}> <DeleteIcon /> </IconButton> </Grid> </React.Fragment> ))} </Grid> ) : ( <Typography align="center" color="error" variant="h4" component="p"> No users Found </Typography> )} </Box> </> ); };
$(document).ready(function () { $('.ee-search-block-2 .last-queries span').click(function () { $('.ee-search-block-2 .form-text').val($(this).text()); }); $('.ee-search-block-2 .last-queries .expand-toggle').click(function () { $(this).parent().addClass('-expanded'); }); });
const test = require('tape'); const isMap = require('./isMap.js'); test('Testing isMap', (t) => { //For more information on all the methods supported by tape //Please go to https://github.com/substack/tape t.true(typeof isMap === 'function', 'isMap is a Function'); //t.deepEqual(isMap(args..), 'Expected'); //t.equal(isMap(args..), 'Expected'); //t.false(isMap(args..), 'Expected'); //t.throws(isMap(args..), 'Expected'); t.end(); });
import db from '../../models' const config = require('../../config').config import RESPONSES from '../../utils/responses' import { Sequelize } from '../../models' import * as bcrypt from 'bcryptjs' import * as jwt from 'jsonwebtoken' class AuthController { static async Login(req, res) { const { body } = req db.User.findOne({ where: { accountName: body.accountName } }).then(user => { // si el usuario no existe if (!user) { return res.status(400).json({ ok: false, message: 'Credenciales incorrectas', errors: 'Credenciales incorrectas', }) } // si existe analizamos el password if (!bcrypt.compareSync(body.password, user.password)) { return res.status(400).json({ ok: false, message: 'Credenciales incorrectas', errors: 'Credenciales incorrectas', }) } // Crear un token // expira en 4hs user.password = ':P' const token = jwt.sign({ user: user }, config.authJwtSecret, { expiresIn: 3600 }) res.status(200).json({ ok: true, user, token, id: user.id }) }) .catch(err => { res.status(400).json({ message: RESPONSES.DB_CONNECTION_ERROR.message + err }) }) } static RenewToken(req, res) { const token = jwt.sign({ user: req.user }, config.authJwtSecret, { expiresIn: 14400 }); res.status(200).json({ ok: true, token, }); } } export default AuthController
var BaseModel = require('./base_model') var db = require('../db') class PricingModel extends BaseModel { static table = 'pricings' // constructor () { // super('pricings') // } static prices (id) { const sql = `select prices.id, prices.price, prices.name, prices.value from prices join pricing_price on prices.id = pricing_price.price_id and pricing_price.pricing_id = $1 order by prices.id` return db.query(sql, [id]) } } module.exports = PricingModel
app.controller('blogCtrl', ['$scope', function($scope){ $scope.blogs = []; $scope.title = []; $scope.getTitle = function(index){ return $scope.title[index]; }; $scope.init = function(){ $scope.title = ['Book','Movie','Review','Tech','Travel'] $scope.blogs = [ { Name:"ไอสไตน์ กล่าวไว้ !", Content:"สวัสดีค่ะน้องๆ ชาว Dek-D.com... ไอน์สไตน์เคยบอกไว้ว่าจินตนาการสำคัญกว่าความรู้ แต่ในความเป็นจริง ถ้ามีทั้งจินตนาการและความรู้ไปพร้อมๆ กันก็จะเพอร์เฟคที่สุด เหมือนอย่างวันนี้ที่พี่มิ้นท์จะมาแนะนำเว็บไซต์ที่ให้ความรู้ครอบจักรวาล... ครอบจักรวาลยังไง เดี๋ยวตามมาดูค่ะ", Img:"static/imgs/a.jpg", Type:'tech' }, { Name:"TitleBook", Content:"The titles of Washed Out's breakthrough song and the first single from Paracosm share the two most important words in Ernest Greene's musical language: feel it. It's a simple request, as well...", Img:"static/imgs/b.jpg", Type:'book' }, { Name:"TitleTravel", Content:"The titles of Washed Out's breakthrough song and the first single from Paracosm share the two most important words in Ernest Greene's musical language: feel it. It's a simple request, as well...", Img:"static/imgs/c.jpg", Type:'travel' }, { Name:"TitleReview", Content:"The titles of Washed Out's breakthrough song and the first single from Paracosm share the two most important words in Ernest Greene's musical language: feel it. It's a simple request, as well...", Img:"static/imgs/d.jpg", Type:'review' }, { Name:"TitleMovie", Content:"The titles of Washed Out's breakthrough song and the first single from Paracosm share the two most important words in Ernest Greene's musical language: feel it. It's a simple request, as well...", Img:"static/imgs/e.jpg", Type:'movie' }, { Name:"TitleMovie", Content:"The titles of Washed Out's breakthrough song and the first single from Paracosm share the two most important words in Ernest Greene's musical language: feel it. It's a simple request, as well...", Img:"static/imgs/f.jpg", Type:'movie' }, { Name:"TitleTech", Content:"The titles of Washed Out's breakthrough song and the first single from Paracosm share the two most important words in Ernest Greene's musical language: feel it. It's a simple request, as well...", Img:"static/imgs/g.jpg", Type:'tech' }, { Name:"TitleBook", Content:"The titles of Washed Out's breakthrough song and the first single from Paracosm share the two most important words in Ernest Greene's musical language: feel it. It's a simple request, as well...", Img:"static/imgs/h.jpg", Type:'book' }, { Name:"TitleTech", Content:"The titles of Washed Out's breakthrough song and the first single from Paracosm share the two most important words in Ernest Greene's musical language: feel it. It's a simple request, as well...", Img:"static/imgs/i.jpg", Type:'tech' }, { Name:"TitleMovie", Content:"The titles of Washed Out's breakthrough song and the first single from Paracosm share the two most important words in Ernest Greene's musical language: feel it. It's a simple request, as well...", Img:"static/imgs/j.jpg", Type:'movie' } ]; }; }]);
'use strict'; module.exports = (sequelize, DataTypes) => { const Questions = sequelize.define( 'questions', { title: DataTypes.STRING, content: DataTypes.STRING, users_id: DataTypes.INTEGER, categories_id: DataTypes.INTEGER }, {} ); Questions.associate = function(models) { // associations can be defined here // Questions.belongsTo(models.User), Questions.belongsTo(models.Category); }; return Questions; };
function Header(){ return ( <header> <h1>Borgers R Us</h1> </header> ) } export default Header
"use strict" let userName = prompt("whos`s there?", ""); if(userName === "Admin"){ let pass = prompt("Password?", ""); if(pass === "TheMaster"){ alert("Welcome"); }else if(pass === "" || pass === null){ alert("cancelled"); }else { alert("Wrong Password"); } }else if(userName === "" || userName === null){ alert("cancelled"); }else{ alert("i don`t know you"); }
const Showcase = () => { return ( <div id="showcase" className="ptb_100"> <img src="show-case.png" className="full-image" width="100%" alt="Showcase"></img> </div> ) } export default Showcase
module.exports = (db) => { return { async createUsers(users) { await db.collection('users').insertMany(users) return users }, } }
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { hashMemo } from '@/utils/hashData'; import injectStyles from '@/utils/injectStyles'; import { CHART_TYPE } from './constants'; import Fill from './elements/Fill'; import FillVertical from './elements/FillVertical'; import Stacked from './elements/Stacked'; import styles from './styles'; let Bar; class BarChart extends Component { constructor(props) { super(props); switch (props.type) { case CHART_TYPE.STACKED: Bar = Stacked; break; case CHART_TYPE.FILL_VERTICAL: Bar = FillVertical; break; case CHART_TYPE.FILL: default: Bar = Fill; break; } } render() { const { className, data, lineSize, units } = this.props; return <Bar className={className} data={data} lineSize={lineSize} units={units} />; } } BarChart.propTypes = { // Used by StyledComponents barSize: PropTypes.string, // eslint-disable-line className: PropTypes.string.isRequired, // eslint-disable-next-line react/require-default-props data: PropTypes.oneOfType([PropTypes.array, PropTypes.object]).isRequired, // Used by StyledComponents lineSize: PropTypes.string, // eslint-disable-line // Used by StyledComponents outerSize: PropTypes.string, // eslint-disable-line type: PropTypes.oneOf(Object.values(CHART_TYPE)), units: PropTypes.string }; BarChart.defaultProps = { barSize: '100%', lineSize: '30px', outerSize: '110px', type: CHART_TYPE.FILL, units: '' }; BarChart.displayName = 'BarChartComponent'; BarChart.whyDidYouRender = true; export const TYPE = CHART_TYPE; export default injectStyles(hashMemo(BarChart), styles);
import React from 'react'; function ChannelPeoples({display}) { return ( display ? <div className='channelPage-peopleList-right'> <div className='channelPage_channelUsers'> <div className='channelPage_userGroup'> <p className='peopleList-roleTitle'>Admin - 1</p> <div className='peopleList-user'> <div className='channelPage_userAvatar'> <svg width='32' height='32' viewBox='0 0 32 32'> <foreignObject x='0' y='0' width='32' height='32'> <img className='avatar-img' src='https://cdn.discordapp.com/avatars/364095318658121729/64c9b3a2111c69340537515f04613322.png?size=256' /> </foreignObject> <svg width='16' height='16' viewBox='0 0 23 23' x='19' y='19'> <circle cx='11.5' cy='11.5' r='11.5' fill='#2F3136' /> </svg> <svg width='10' height='10' viewBox='0 0 23 23' x='22' y='22'> <circle cx='11.5' cy='11.5' r='11.5' fill='#399F58' /> </svg> </svg> </div> <div className='peopleList-nameOfPeople'> <span>dashersw</span> </div> </div> <div className='peopleList-user'> <div className='channelPage_userAvatar'> <svg width='32' height='32' viewBox='0 0 32 32'> <foreignObject x='0' y='0' width='32' height='32'> <img className='avatar-img' src='https://cdn.discordapp.com/avatars/364095318658121729/64c9b3a2111c69340537515f04613322.png?size=256' /> </foreignObject> <svg width='16' height='16' viewBox='0 0 23 23' x='19' y='19'> <circle cx='11.5' cy='11.5' r='11.5' fill='#2F3136' /> </svg> <svg width='10' height='10' viewBox='0 0 23 23' x='22' y='22'> <circle cx='11.5' cy='11.5' r='11.5' fill='#399F58' /> </svg> </svg> </div> <div className='peopleList-nameOfPeople'> <span>dashersw</span> </div> </div> <div className='peopleList-user'> <div className='channelPage_userAvatar'> <svg width='32' height='32' viewBox='0 0 32 32'> <foreignObject x='0' y='0' width='32' height='32'> <img className='avatar-img' src='https://cdn.discordapp.com/avatars/364095318658121729/64c9b3a2111c69340537515f04613322.png?size=256' /> </foreignObject> <svg width='16' height='16' viewBox='0 0 23 23' x='19' y='19'> <circle cx='11.5' cy='11.5' r='11.5' fill='#2F3136' /> </svg> <svg width='10' height='10' viewBox='0 0 23 23' x='22' y='22'> <circle cx='11.5' cy='11.5' r='11.5' fill='#399F58' /> </svg> </svg> </div> <div className='peopleList-nameOfPeople'> <span>dashersw</span> </div> </div> <div className='peopleList-user'> <div className='channelPage_userAvatar'> <svg width='32' height='32' viewBox='0 0 32 32'> <foreignObject x='0' y='0' width='32' height='32'> <img className='avatar-img' src='https://cdn.discordapp.com/avatars/364095318658121729/64c9b3a2111c69340537515f04613322.png?size=256' /> </foreignObject> <svg width='16' height='16' viewBox='0 0 23 23' x='19' y='19'> <circle cx='11.5' cy='11.5' r='11.5' fill='#2F3136' /> </svg> <svg width='10' height='10' viewBox='0 0 23 23' x='22' y='22'> <circle cx='11.5' cy='11.5' r='11.5' fill='#399F58' /> </svg> </svg> </div> <div className='peopleList-nameOfPeople'> <span>dashersw</span> </div> </div> <div className='peopleList-user'> <div className='channelPage_userAvatar'> <svg width='32' height='32' viewBox='0 0 32 32'> <foreignObject x='0' y='0' width='32' height='32'> <img className='avatar-img' src='https://cdn.discordapp.com/avatars/364095318658121729/64c9b3a2111c69340537515f04613322.png?size=256' /> </foreignObject> <svg width='16' height='16' viewBox='0 0 23 23' x='19' y='19'> <circle cx='11.5' cy='11.5' r='11.5' fill='#2F3136' /> </svg> <svg width='10' height='10' viewBox='0 0 23 23' x='22' y='22'> <circle cx='11.5' cy='11.5' r='11.5' fill='#399F58' /> </svg> </svg> </div> <div className='peopleList-nameOfPeople'> <span>dashersw</span> </div> </div> <div className='peopleList-user'> <div className='channelPage_userAvatar'> <svg width='32' height='32' viewBox='0 0 32 32'> <foreignObject x='0' y='0' width='32' height='32'> <img className='avatar-img' src='https://cdn.discordapp.com/avatars/364095318658121729/64c9b3a2111c69340537515f04613322.png?size=256' /> </foreignObject> <svg width='16' height='16' viewBox='0 0 23 23' x='19' y='19'> <circle cx='11.5' cy='11.5' r='11.5' fill='#2F3136' /> </svg> <svg width='10' height='10' viewBox='0 0 23 23' x='22' y='22'> <circle cx='11.5' cy='11.5' r='11.5' fill='#399F58' /> </svg> </svg> </div> <div className='peopleList-nameOfPeople'> <span>dashersw</span> </div> </div> <div className='peopleList-user'> <div className='channelPage_userAvatar'> <svg width='32' height='32' viewBox='0 0 32 32'> <foreignObject x='0' y='0' width='32' height='32'> <img className='avatar-img' src='https://cdn.discordapp.com/avatars/364095318658121729/64c9b3a2111c69340537515f04613322.png?size=256' /> </foreignObject> <svg width='16' height='16' viewBox='0 0 23 23' x='19' y='19'> <circle cx='11.5' cy='11.5' r='11.5' fill='#2F3136' /> </svg> <svg width='10' height='10' viewBox='0 0 23 23' x='22' y='22'> <circle cx='11.5' cy='11.5' r='11.5' fill='#399F58' /> </svg> </svg> </div> <div className='peopleList-nameOfPeople'> <span>dashersw</span> </div> </div> </div> </div> </div> : "" ); } export default ChannelPeoples;
const mongoose = require('mongoose') const Schema = mongoose.Schema const questionSchema = new Schema({ title: { type: String, required: [true, 'cannot post blank title question'] }, body: { type: String, required: [true, 'cannot post blank body question'] }, userId: { type: Schema.Types.ObjectId, ref: 'User' }, voteUp: [{ type: Schema.Types.ObjectId, ref: 'User' }], voteDown: [{ type: Schema.Types.ObjectId, ref: 'User' }], createdAt: { type: Date, default: new Date() }, updatedAt: { type: Date, default: new Date() }, tags: Array, answerId: [{ type: Schema.Types.ObjectId, ref: 'Aswer' }], }) const Question = mongoose.model('Question', questionSchema) module.exports = Question
Ext.ns('App', 'App.locale'); App.init = function() { Ext.QuickTips.init(); App.security.createLoginWindow(); App.security.checkLogin(); App.accordion = App.createAccordion(); App.viewProcessDefinition = App.createViewProcessDefinition(); App.processDefinitions.store.load(); App.uploadNewProcessDefinition = App.createUploadNewProcessDefinition(); //App.chart = App.createColumnChart(); App.centerTabPanel = { id: 'centerTabPanel', activeTab: 0, region: 'center', xtype: 'tabpanel', layoutOnTabChange: true, enableTabScroll: true, items: [ App.viewProcessDefinition, App.uploadNewProcessDefinition ] }; var viewPort = new Ext.Viewport({ layout: 'border', items: [{ region: 'north', height: 50, contentEl: 'nav_area' },{ region: 'south', height: 18, contentEl: 'state_area' },App.centerTabPanel,App.accordion] }); setTimeout(function(){ Ext.get('loading').remove(); Ext.get('loading-mask').fadeOut({remove:true}); }, 100); } Ext.onReady(App.init, App);
import basefunction from "../reusable/orgBaseFunctions"; import customerBaseFunction from "../reusable/cstBaseFunctions01"; import adminPage from "../pageObject/cypMailPage"; import cstBaseFunction2 from "../reusable/cstBaseFunctions02"; import orgPg from "../pageObject/solePage"; describe("organization admin operations", () => { const aTWOrgMail = Cypress.env("aTWOrgMail"), aTWOrgPwd = Cypress.env("aTWOrgPwd"), orgUserEmail = Cypress.env("mail"), newOrgUser = Cypress.env("newOrgUser"), existingEmail = Cypress.env("existingEmail"), existingEmailPwd = Cypress.env("existingEmailPwd"); it("changes organization admin password from the menu" + "Existing org (created prior to a release) can login", () => { //log in with existing mail id basefunction.login(aTWOrgMail, aTWOrgPwd); //select reset password orgPg.resetPwdLinkFromProfile(); //reset password orgPg.resetPwdFromProfile(aTWOrgPwd); //log out basefunction.logOut(); //log in with set pwd basefunction.login(aTWOrgMail, aTWOrgPwd); //check url is correct cy.url().should("include", "/admin/preview"); }); it("creates a new organization user" + "Existing org (created prior to a release) can edit org page", () => { //log in with existing mail id basefunction.login(aTWOrgMail, aTWOrgPwd); orgPg.selectEditdetails(); //add new user orgPg.addNewUserToOrg(newOrgUser, orgUserEmail); //check user added cy.get("td").contains(newOrgUser); }); it("sets organization opening hours" + "Existing org (created prior to a release) can alter opening hours", () => { //log in with existing mail id basefunction.login(existingEmail, existingEmailPwd); orgPg.selectEditdetails(); //set up opening time for working days orgPg.setOpeningHrsWeekDays(); // set up opening time for sat and sun orgPg.setOpeningHrsWeekend(); //check opening time listed correct cy.get("tbody > tr").eq(0).should("contain.text", "Sun No Yes"); cy.get("tbody > tr").eq(1).should("contain.text", "Mon No No 07:00:00 - 17:00:00"); cy.get("tbody > tr").eq(2).should("contain.text", "Tue No No 07:00:00 - 17:00:00"); cy.get("tbody > tr").eq(3).should("contain.text", "Wed No No 07:00:00 - 17:00:00"); cy.get("tbody > tr").eq(4).should("contain.text", "Thu No No 07:00:00 - 17:00:00"); cy.get("tbody > tr").eq(5).should("contain.text", "Fri No No 07:00:00 - 17:00:00"); cy.get("tbody > tr").eq(6).should("contain.text", "Sat No Yes"); //log out basefunction.logOut(); }); it("Sends a password reset email to the new organization user" + "Existing org (created prior to a release) can change password", () => { //log in with existing mail id basefunction.login(aTWOrgMail, aTWOrgPwd); orgPg.selectEditdetails(); cy.get(".btn-actions-pane-right").click(); orgPg.selectResetMailPwd(); orgPg.pwdResetMsg(orgUserEmail); orgPg.pwdResetConfirmMsg(orgUserEmail); //log out basefunction.logOut(); }); // this test is connected with the previous one, due to password reset expiring in 60 min it("0.1 - resets the password for the new organization user when receiving the password-reset email", () => { basefunction.mailLoging(); adminPage.selectFirstMail(); adminPage.resrePwdNotification(); adminPage.newPwdlink(); adminPage.mailLogout(); }); it("0.2 - resets the password for the new organization user when receiving the password-reset email", () => { cy.readFile("cypress/fixtures/link.json").then((url) => { cy.visit(url.link); }); adminPage.newPWDForUser(aTWOrgMail, aTWOrgPwd); Cypress.on("uncaught:exception", (err, runnable) => { return false; }); cy.wait(1000); cy.writeFile("cypress/fixtures/link.json", { flag: "a+" }); cy.get(".col-md-6").contains("Around the World").click(); //Need to write function for logout cy.wait(2000); //log out basefunction.logOut(); }); }); describe("customer operations", () => { const custEmail = Cypress.env("customerMail"), custUrl = Cypress.env("cstUrl"); it("books a service", () => { cstBaseFunction2.logInAsCustomer(custEmail); logIn.globalSearch("Jill's"); cstBaseFunction2.clickOnElementWithText("h3", "Jill's"); cstBaseFunction2.clickOnChildWithParentWithText("p", "Garden", "input"); cstBaseFunction2.clickOnText("Check Availability"); cstBaseFunction2.changeCalendarDate("2028-09-11"); cstBaseFunction2.clickOnMultipleChildAtIndex(".comments-reply>ul", 0); customerBaseFunction.clickOnElement('input[type="radio"]'); cstBaseFunction2.clickOnText("Book Now"); cstBaseFunction2.sliceTextAsVariable("Date : ", 7, 17, "date"); cstBaseFunction2.sliceTextAsVariable(" Time: ", 7, 12, "time"); customerBaseFunction.clickOnElement('input[value="Confirm Booking"]'); cy.wait(5000); cstBaseFunction2.clickOnElementWithText("a", "My Appointments"); cstBaseFunction2.findAliasInMultipleChildAtIndex("date"); cstBaseFunction2.findAliasInMultipleChildAtIndex("time"); }); });
import React from 'react' import htmlImage from '../../../assets/images/html.png'; import cssImage from '../../../assets/images/css.png'; import jsImage from '../../../assets/images/js.png'; import nodeImage from '../../../assets/images/node.png'; import webpackImage from '../../../assets/images/webpack.png'; import reactImage from '../../../assets/images/react.png'; import classes from './AboutCube.module.scss'; const AboutCube = () => { return ( <div className={classes.AboutCube}> <div className={[classes.Box, classes.ShowFront].join(' ')}> <div className={[classes.Face, classes.Front].join(' ')}> <img src={htmlImage} alt="Html" /> </div> <div className={[classes.Face, classes.Back].join(' ')}> <img src={cssImage} alt="css" /> </div> <div className={[classes.Face, classes.Right].join(' ')}> <img src={jsImage} alt="JavaScript" /> </div> <div className={[classes.Face, classes.Left].join(' ')}> <img src={nodeImage} alt="Node" /> </div> <div className={[classes.Face, classes.Top].join(' ')}> <img src={webpackImage} alt="Webpack" /> </div> <div className={[classes.Face, classes.Bottom].join(' ')}> <img src={reactImage} alt="React" /> </div> </div> </div> ) } export default AboutCube
import createReducer from '../helpers/createReducer'; import { NavigationActions } from 'react-navigation'; import { AppNavigator } from '../../navigators/AppNavigator'; import { StatusBar } from 'react-native'; const firstAction = AppNavigator.router.getActionForPathAndParams('LoggedIn'); const initialNavState = AppNavigator.router.getStateForAction(firstAction); export const nav = (state = initialNavState, action) => { let nextState = AppNavigator.router.getStateForAction(action, state); if (action.routeName === 'TurnOnNotifications' || action.routeName === 'LoggedIn' ) { StatusBar.setBarStyle('dark-content', true); } return nextState || state; }; /* 初期ステートと次のステートを返すreducer StatusBar.setBarStyle('light-content', true); The other color options are 'default' and 'dark-content' <How to set iOS status bar background color> 1-) Add this to your info.plist file: <key>UIViewControllerBasedStatusBarAppearance</key> <string>YES</string> 2-) then add StatusBar.setBarStyle('light-content', true); as the first line in your render() to change the status bar text/icons to white. The other color options are 'default' and 'dark-content'. else if (typeof action.routeName ==='undefined', action.routeName === 'LoggedOut') { StatusBar.setBarStyle('light-content', true); } */
// @flow import Protobuf from 'pbf' export type Projection = 'vector' | 'll' | 'uv' | 'st' export default class VectorTileFeature { properties: Object = {} extent: number type: number = 0 scheme: number = 0 _pbf: Protobuf _projection: number = 1 _geometry: number = -1 _keys: Array<string> _values: Array<any> constructor (pbf, end, extent, keys: Array<string>, values: Array<any>) { this.extent = extent this._pbf = pbf this._keys = keys this._values = values pbf.readFields(this.readFeature, this, end) } readFeature (tag: number, feature: VectorTileFeature, pbf: Protobuf) { if (tag === 1) feature.id = pbf.readVarint() else if (tag === 2) feature.readTag(pbf, feature) else if (tag === 3) feature.type = pbf.readVarint() else if (tag === 4) feature._geometry = pbf.pos else if (tag === 5) feature._projection = pbf.readVarint() } readTag (pbf, feature: VectorTileFeature) { const end = pbf.readVarint() + pbf.pos while (pbf.pos < end) { const key = feature._keys[pbf.readVarint()] const value = feature._values[pbf.readVarint()] feature.properties[key] = value } } projection (): Projection { switch (this._projection) { case 1: return 'vector' case 2: return 'll' case 3: return 'uv' case 4: return 'st' default: return 'vector' } } loadGeometry (): Array<any> { this._pbf.pos = this._geometry const polys = [] let lines = [] const end = this._pbf.readVarint() + this._pbf.pos const poly3d = (this.type > 4) ? true : false const vector = this._projection === 1 let cmd = 1 let length = 0 let x = 0 let y = 0 let r = 0 let line = null while (this._pbf.pos < end) { if (length <= 0) { const cmdLen = this._pbf.readVarint() cmd = cmdLen & 0x7 length = cmdLen >> 3 } length-- if (cmd === 1 || cmd === 2) { if (vector) { x += this._pbf.readSVarint() y += this._pbf.readSVarint() if (poly3d) r += this._pbf.readSVarint() } else { x = this._pbf.readDouble() y = this._pbf.readDouble() if (poly3d) r = this._pbf.readDouble() } if (cmd === 1) { // moveTo if (line) { if (this.type === 1) lines.push(...line) else lines.push(line) } line = [] } if (poly3d) line.push([x, y, r]) else line.push([x, y]) } else if (cmd === 4) { // next poly if (line) lines.push(line) polys.push(lines) lines = [] line = null } else if (cmd === 7) { // close poly if (line) { line.push([line[0][0], line[0][1]]) lines.push(line) line = null } } else { throw new Error('unknown command ' + cmd) } } if (line && line.length) { if (this.type === 1) lines.push(...line) else lines.push(line) } if (polys.length) return polys return lines } }
/* * Kita * * cookies.js * * A handy helper to CRUD client side cookies * * Shann McNicholl (@shannmcnicholl) * * License Pending */ define( ["../src/is"], function(is) { if(!is(document, "htmldocument") || !is(document.cookie, "string")) return false; return { /* * getAll * * Returns an object containing all existing cookies */ getAll: function() { var cookies = {}; document.cookie.split("; ").forEach(function(cookie) { // Skip empty cookies if(cookie === "") return false; cookie = cookie.split("="); cookies[cookie[0]] = cookie[1]; return true; }); return cookies; }, /* * get * * Returns the value of the given cookie, otherwise `undefined` */ get: function(name) { var cookies = this.getAll(); if(!is(cookies, "object")) return undefined; return cookies[name]; // returns the value or undefined }, /* * set * * Sets a new cookie or updates an existing one */ set: function(name, value, expires, path, domain, secure) { var cookie = []; if(!is(name, "string")) return false; cookie.push(name +"="+ value); // Optional if(is(expires, "number")) cookie.push(" expires="+ this.getExpiresDate(expires)); if(is(path, "string")) cookie.push(" path="+ path); if(is(domain, "string")) cookie.push(" domain="+ domain); if(secure) cookie.push(" secure"); document.cookie = cookie.join(";") +";"; return true; }, /* * delete * * Immediately expires a cookie */ delete: function(attr) { if(!is(attr, "string")) return false; this.set(attr, null, -1); return true; }, /* * deleteAll * * Cycles through and deletes all cookies */ deleteAll: function() { var cookies = this.getAll(); for(var c in cookies) { this.delete(c); } return true; }, /* * getExpiresDate * * Returns a GMT Date string that is x `days` in advance of `right now` */ getExpiresDate: function(days) { return (new Date(new Date().getTime() + days * 1000 * 60 * 60 * 24)).toGMTString(); } } });
import { getDateId } from '../utils' const day0 = new Date() const y = day0.getFullYear() const m = day0.getMonth() const d = day0.getDate() const day0Id = getDateId(day0) const activityDataInit = { list: ['1','2','3','4','5'], schedule: ['3','4'], data: { '1': { id: '1', time: (new Date(y,m,d+1)).getTime(), desc: '重訓', max: '5', participating: '1', participants: ['1'], participation: '0', location: '', locationName: '訓練中心', owner: '1', ownerName: 'Steve Rogers', distance: 5, }, '2': { id: '2', time: (new Date(y,m,d+3)).getTime(), desc: '路跑', max: '30', participating: '1', participants: ['3'], participation: '1', location: '', locationName: '台北101', owner: '3', ownerName: '王小明', distance: 20, }, '3': { id: '3', time: (new Date(y,m,d+3)).getTime(), desc: 'IBM棒球明星賽', max: '40', participating: '2', participants: ['4','lukeskywalker'], participation: '2', location: '', locationName: '河濱公園', owner: '4', ownerName: '華生', distance: 100, }, '4': { id: '4', time: (new Date(y,m,d+5)).getTime(), desc: '3v3鬥牛', max: '15', participating: '3', participants: ['2','1','lukeskywalker'], participation: '2', location: '', locationName: '橋下', owner: '2', ownerName: '周傑倫', distance: 80, }, '5': { id: '5', time: (new Date(y,m+1,d)).getTime(), desc: 'Fight Club', max: '2', participating: '2', participants: ['1','5'], participation: '0', location: '', locationName: '地下室', owner: '5', ownerName: 'Tyler Durden', distance: 15, }, } } export const activityData = (state = activityDataInit, action) => { switch (action.type) { case 'ACTIVITY_UPDATE_SCHEDULE': return { ...state, schedule: action.schedule } case 'ACTIVITY_JOIN_SUBMIT_END': case 'ACTIVITY_EDIT_SUBMIT_END': if (action.activity) { const isNew = state.list.indexOf(action.activity.id) < 0 return { ...state, list: isNew? [...state.list, action.activity.id]: state.list, data: { ...state.data, [action.activity.id]: action.activity } } } else return state default: return state } } const activityFormInit = { TIME: '', DESC: '', MAX: '', } const activityUIInit = { viewing: null, viewingMode: null, loading: false, sorting: 'TIME', filter: 'ALL', list: ['1','2','3','4','5'], previewScheduleIndex: 0, form: activityFormInit } const activityForm = (state , action) => { console.log('ACTIVITYFORM', action) switch (action.type) { case 'ACTIVITY_FORM_CHANGE': let changeMade = {} Object.keys(action.change).map( name => { changeMade[name] = action.change[name] }) return { ...state, ...changeMade } default: return state } } export const activityUI = (state = activityUIInit, action) => { console.log('ACTIVITYUI', action) switch (action.type) { case 'ACTIVITY_LIST_SORT_START': return { ...state, viewing: null, viewingMode: null, sorting: action.sorting, loading: true } case 'ACTIVITY_LIST_SORT_END': return { ...state, sorting: action.sorting, loading: false, list: action.list } case 'ACTIVITY_LIST_FILTER_START': return { ...state, viewing: null, viewingMode: null, filter: action.filter, sorting: action.sorting, loading: true } case 'ACTIVITY_LIST_FILTER_END': return { ...state, filter: action.filter, sorting: action.sorting, loading: false, list: action.list } case 'ACTIVITY_VIEW': return { ...state, viewing: action.viewing == state.viewing && state.viewingMode == 'VIEW'? null: action.viewing, viewingMode: 'VIEW', } case 'ACTIVITY_FORM_CHANGE': return { ...state, form: activityForm(state.form, action) } case 'ACTIVITY_EDIT_START': return { ...state, viewing: action.editing, viewingMode: 'EDIT', } case 'ACTIVITY_EDIT_END': return { ...state, viewing: null, viewingMode: null, } case 'ACTIVITY_EDIT_SUBMIT_START': case 'ACTIVITY_JOIN_SUBMIT_START': return { ...state, loading: true } case 'ACTIVITY_EDIT_SUBMIT_END': case 'ACTIVITY_JOIN_SUBMIT_END': if (action.activity) { const isNew = state.list.indexOf(action.activity.id) < 0 return { ...state, loading: false, viewing: null, viewingMode: null, list: isNew? [...state.list, action.activity.id]: state.list, form: activityForm(state.form, action), } } else return { ...state, loading: false } case 'ACTIVITY_UPDATE_SCHEDULE': case 'ACTIVITY_PREVIEW_SCHEDULE': return { ...state, previewScheduleIndex: action.index } default: return state } }
/* Write a function allConstruct(target, wordBank) the function should return a 2d array containing all of the ways that the target can be constructed by concatenating elements of the wordBank array. Each element of the 2D array should represent one combination that constructs the target You may reuse elements */ const allConstruct = (target, wordBank, table = {}) => { if (target === "") return [[]]; if (target in table) return table[target]; let results = []; for (let word of wordBank) { if (target.indexOf(word) === 0) { let suffixWays = allConstruct(target.slice(word.length), wordBank, table); if (suffixWays.length != 0) { suffixWays = suffixWays.map((way) => [...way, word]); results.push(...suffixWays); } } } table[target] = results; return table[target]; }; console.log( allConstruct("skateboard", ["bo", "rd", "ate", "t", "ska", "sk", "boar"]) ); console.log( allConstruct("abcdef", ["ab", "abc", "cd", "def", "abcd", "ef", "c"]) ); console.log(allConstruct("purple", ["purp", "p", "ur", "le", "purpl"])); console.log( allConstruct("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef", [ "e", "ee", "eee", "eeee", "eeeee", "eeeeee", ]) ); //USING TABULATION const allConstruct2 = (target, wordBank) => { const table = Array(target.length + 1) .fill() .map(() => []); table[0] = [[]]; for (let i = 0; i <= target.length; i++) { if (table[i].length !== 0) { for (let word of wordBank) { if (target.slice(i).indexOf(word) === 0) { const newCombinations = table[i].map((way) => [...way, word]); table[i + word.length].push(...newCombinations); } } } } return table[target.length]; }; console.log( allConstruct2("skateboard", ["bo", "rd", "ate", "t", "ska", "sk", "boar"]) ); console.log( allConstruct2("abcdef", ["ab", "abc", "cd", "def", "abcd", "ef", "c"]) ); console.log(allConstruct2("purple", ["purp", "p", "ur", "le", "purpl"])); console.log( allConstruct2("eeeeeeeeeef", ["e", "ee", "eee", "eeee", "eeeee", "eeeeee"]) );
var elixir = require('laravel-elixir'); require('laravel-elixir-vueify'); /* |-------------------------------------------------------------------------- | Elixir Asset Management |-------------------------------------------------------------------------- | | Elixir provides a clean, fluent API for defining some basic Gulp tasks | for your Laravel application. By default, we are compiling the Sass | file for our application, as well as publishing vendor resources. | elixir.config.assetsPath = 'public/themes/default/assets'; elixir.config.publicPath = elixir.config.assetsPath; */ elixir.config.publicPath = 'public/themes/default/assets'; elixir.config.js.browserify.watchify.options.poll = true; /* elixir.config.css.sass.pluginOptions.includePaths = [ 'node_modules/foundation-sites/scss', 'node_modules/font-awesome/scss' ]; */ elixir.config.css.sass.pluginOptions.includePaths = [ 'node_modules/foundation-sites/scss', 'node_modules/font-awesome/scss' ]; elixir(function(mix) { //mix.copy('node_modules/bootstrap-sass/assets/fonts', elixir.config.publicPath+'/fonts'); // mix.copy(elixir.config.assetsPath + '/foundation-icons', elixir.config.publicPath+'/fonts/foundation-icons'); mix.copy('node_modules/font-awesome/fonts', elixir.config.publicPath+'/fonts'); // mix.copy(elixir.config.assetsPath + '/foundation-icons', elixir.config.publicPath+'/fonts/foundation-icons'); // mix.copy('node_modules/bootstrap-sass/assets/javascripts/bootstrap.min.js', elixir.config.assetsPath+'/js/bootstrap.js'); //mix.copy('node_modules/jquery/dist/jquery.min.js', elixir.config.assetsPath+'/js/jquery.js'); //mix.copy('node_modules/foundation-sites/scss/settings/_settings.scss', elixir.config.assetsPath+'/sass/settings.scss'); //mix.copy('node_modules/foundation-sites/dist/foundation.js', elixir.config.assetsPath+'/js/foundation.js'); //mix.copy('node_modules/moment/min/moment.min.js', elixir.config.assetsPath+'/js/moment.js'); /* mix.copy('node_modules/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js', elixir.config.assetsPath+'/js/datepicker.js'); mix.copy('node_modules/eonasdan-bootstrap-datetimepicker/src/sass/_bootstrap-datetimepicker.scss', elixir.config.assetsPath+'/sass/datepicker.scss'); mix.copy('node_modules/simplemde/dist/simplemde.min.css', elixir.config.publicPath+'/css/simplemde.css'); mix.copy('node_modules/simplemde/dist/simplemde.min.js', elixir.config.assetsPath+'/js/simplemde.js'); */ mix.copy('node_modules/ckeditor', elixir.config.publicPath+'/js/ckeditor'); //mix.sass('foundation_backend.scss'); // Combine Styles for the public facing site pages mix.styles([ 'foundation.css', 'site.css', 'site-mediaqueries.css' ], 'public/themes/default/assets/css/public-styles.css'); mix.styles([ 'foundation.css', 'admin.css' ], 'public/themes/default/assets/css/admin-styles.css'); mix.scripts([ 'vendor/jquery.min.js', 'vendor/what-input.min.js', 'moment.js', 'foundation.js', 'app.js' ], 'public/themes/default/assets/js/public-scripts.js' ); mix.scripts([ 'vendor/jquery.min.js', 'vendor/what-input.min.js', 'moment.js', 'foundation.js', 'app.js' ], 'public/themes/default/assets/js/admin-scripts.js' ); // mix.sass('app.scss'); // mix.browserify('main.js'); });
(function () { 'use strict'; angular.module('itemModule') .controller('ItemDetailController', [ '$scope', '$stateParams', 'Items', function ($scope, $stateParams, Items) { var vm = this; Items.get({ id: $stateParams.id }, function (item) { vm.item = item; }); } ]); })();
import React from 'react'; import Review from './Review' let ramenData = require('../data/ramen.json') class Ramen extends React.Component { state = { country: ramenData[0]["country"], ramen_brand: ramenData[0]["brand"], ramen_variety: ramenData[0]["variety"], review_score: ramenData[0]["stars"], isHidden: true } updateReview = (review) => { this.setState( review ) } render() { return ( <div class="center"> <h1>This is the Ramen Page!</h1> <hr></hr> <h3>Select the Button Below to View a Random Ramen Review!</h3> <br/> <br/> <Review updateReview={this.updateReview}/> </div> ) } } export default Ramen
import React, { useRef, useEffect } from 'react'; import { BrowserRouter as Router, } from "react-router-dom"; import Wrapper from "./components/Wrapper" import Footer from "./components/Footer" import Home from "./components/Home" import About from "./components/About" import RecentProjects from "./components/RecentProjects" import Contact from "./components/Contact" import Navbar from './components/Navbar' // the following is for Google Analytics import ReactGA from 'react-ga'; function App() { ReactGA.initialize('UA-199525036-1'); useEffect(() => { // to report page view ReactGA.pageview(window.location.pathname + window.location.search); }, []) const aboutRef = useRef() const projectsRef = useRef() const contactRef = useRef() function moveToAbout() { aboutRef.current.scrollIntoView() ReactGA.event({ category: "Button Click", action: "About me button is clicked" }) } function moveToProjects() { projectsRef.current.scrollIntoView() } function moveToContact() { contactRef.current.scrollIntoView() } return ( <div> <Router> <Wrapper> <Navbar moveToAbout={moveToAbout} moveToProjects={moveToProjects} moveToContact={moveToContact} /> <Home moveTo={moveToAbout} /> <About refName={aboutRef} /> <RecentProjects refName={projectsRef} /> <Contact refName={contactRef} /> </Wrapper> <Footer /> </Router> </div> ); } export default App;
import Vue from 'vue' import Vuex from 'vuex' import { deleteToken } from '../common/jwt.storage' import { API_SERVICE } from '../common/api' import * as games from '@/store/modules/games.module' import * as players from '@/store/modules/players.module' import * as tournament from '@/store/modules/tournament.module' import * as files from '@/store/modules/files.module' Vue.use(Vuex) export default new Vuex.Store({ modules: { games, players, tournament, files }, actions: { resetAllStatesAndToken: ({ dispatch }) => { deleteToken() API_SERVICE.clearHeader() dispatch('resetTournament') dispatch('resetPlayer') dispatch('resetGames') } } })
var admin = require('firebase-admin'); var serviceAccount = require('./credentials.js'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "https://cohesive-79cd9.firebaseio.com" }); console.log('Application initiliazed'); var db = admin.database(); var ref = db.ref("Test"); var usersRef = ref.child("users"); usersRef.set({ alanisawesome: { date_of_birth: "June 23, 1912", full_name: "Alan Turing" }, gracehop: { date_of_birth: "December 9, 1906", full_name: "Grace Hopper" }, MOTHEFUCKINGWORKINGGGDAWGGGG: { date_of_birth: "December 9, 1906", full_name: "Grace Hopper" } });
/** * create time 2017/03/01 * author cash * */ import {updateCtrl} from '../js/service/updateVersion/updateVersionCtrl'; function JsBridge (fnName, data, callback, f7){ const handler = (fnName, data, callback) => { window.WebViewJavascriptBridge.callHandler( fnName, data, callback ); }; const {android} = window.currentDevice; if (window.WebViewJavascriptBridge){ handler(fnName, data, callback); } else { if (android){ window.document.addEventListener( 'WebViewJavascriptBridgeReady', function (){ window.WebViewJavascriptBridge.init(function (message, responseCallback){ var data = { 'Javascript Responds': '测试中文!' }; responseCallback(data); }); // app后台唤醒后js做的操作 window.WebViewJavascriptBridge.registerHandler('appWillEnterForeground', (data, responseCallback) => { updateCtrl(f7); }); handler(fnName, data, callback); }, false ); } else { let WVJBIframe = window.document.createElement('iframe'); WVJBIframe.style.display = 'none'; WVJBIframe.src = 'https://__bridge_loaded__'; window.WVJBCallbacks = []; window.document.documentElement.appendChild(WVJBIframe); setTimeout(function (){ window.document.documentElement.removeChild(WVJBIframe); if (window.WebViewJavascriptBridge){ handler(fnName, data, callback); // app后台唤醒后js做的操作 window.WebViewJavascriptBridge.registerHandler('appWillEnterForeground', () => { updateCtrl(f7); }); } }, 30); } } } function registerHandler (fnName, callback){ if (!window.bridge){ console.log('bridge 未初始化!'); return; } window.bridge.registerHandler(fnName, callback); } export { JsBridge, registerHandler };