text
stringlengths
7
3.69M
const ZtMeta = require("../lib"); it("list database method with system",()=>{ let ztmeta=new ZtMeta({ host:'127.0.0.1', user:'root', password:'123456' }); let data_actual=['']; ztmeta.listDatabases({},(err,dbs,info)=>{ // expect(typeof data).toBe('object'); expect(dbs.includes('mysql')).toBe(true); }) }); it("show database method without system",()=>{ let ztmeta=new ZtMeta({ host:'127.0.0.1', user:'root', password:'123456' }); ztmeta.listDatabases({withSystemDataBases:false},(err,data,info)=>{ // expect(typeof data).toBe('object'); expect(data.includes('mysql')).toBe(false); }) });
/* ๐Ÿค– this file was generated by svg-to-ts*/ export const EOSIconsAbstract = { name: 'abstract', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M16 3H8a2 2 0 00-1.71 1l-4 7a2 2 0 000 2l4 7A2 2 0 008 21h8a2 2 0 001.74-1l4-7a2 2 0 000-2l-4-7A2 2 0 0016 3z"/></svg>` };
const express = require('express'); const controller = require('./sowing.controller'); //const authJWT = require('../../middlewares/authJWT'); const router = express.Router(); router.get('/', controller.getSowings); // Coleccion (plural) router.get('/:id', controller.getSowing); // Documento (singular) router.post('/', controller.createSowing); router.put('/:id', controller.updateSowing); //router.patch('/:id/update-passwd', controller.updatePasswd); // (Controlador - verbos) POST /users/20/reset-password router.delete('/:id', controller.deleteSowing); module.exports = router;
console.log("connected") ////////////addEventListener//// function hiddelton(){ console.log("I got picked by taylor on her jet"); var div = document.createElement('div'); div.setAttribute('id', 'just-an-id') document.body.appendChild(div); document.getElementById("just-an-id").innerHTML="Hidd: mom meet my girlfriend Taylor" } document.getElementById("taylor").addEventListener("click", hiddelton) /////////////////////////////// // for enter key/////////////// document.getElementById("photograpger-name").addEventListener('keypress', function (e) { var key = e.which || e.keyCode; if (key === 13) { // 13 is enter var photographerName = document.getElementById("photograpger-name").value console.log(photographerName) if (photographerName=="Bill Cunningham"){ console.log("You are missed.") } else { console.log("Take a Hint: Minimalism makes people humble.") } } }) /////////////////////////////// ////////////this /////////////// function showArtists(e){ // Notes/////// // Always true // console.log(this === e.currentTarget); // true when currentTarget and target are the same object // console.log(this === e.target); // this.style.backgroundColor = '#A5D9F3'; // if (this === e.target) ///////////////// var forHiphop = document.body.querySelector(".hiphop") var forRock = document.body.querySelector(".rock") var forPop = document.body.querySelector(".pop") var span = document.createElement('span'); if (this === forHiphop){ console.log("hip hop selected"); span.innerHTML = "Kendrick Lamar"; forHiphop.appendChild(span); } else if(this === forRock){ console.log("rock selected"); span.innerHTML = "Foo Fighters"; forRock.appendChild(span); } else if(this === forPop){ console.log("Pop selected") span.innerHTML = "RIRI"; forPop.appendChild(span); } } var elem = document.body.querySelectorAll(".all") console.log(elem) for (var i=0 ; i<elem.length ; i++) { elem[i].addEventListener('click', showArtists, false); } ///////////////////
// LICENSE BELOW IS FOR ACCESSIBILITY FUNCTIONS /* ============================================ License for Application ============================================ This license is governed by United States copyright law, and with respect to matters of tort, contract, and other causes of action it is governed by North Carolina law, without regard to North Carolina choice of law provisions. The forum for any dispute resolution shall be in Wake County, North Carolina. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // jQuery formatted selector to search for focusable items var focusableElementsString = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]'; // store the item that has focus before opening the modal window var focusedElementBeforeModal; var modal = $('.modal'), modalOverlay = $('#modal-overlay'), modalTrigger = '.modal-trigger', modalClose = $('.modal-close'), modalContent = $('.modal-content'), galleryModalContent = $('#gallery-modal .modal-content'), modalVideo = $('.modal-video'), body = $('body'), section = $('section'); $(document).ready(function () { //Open appropriate modal after closing all other modals, and create modal bkg. $(document).on('click', modalTrigger, function (e) { e.preventDefault(); openModal(this); }); // Close modal on close button click or overlay click $(modalClose).on('click touchstart', function (e) { e.preventDefault(); resetModal(); }); $(modalOverlay).on('click touchstart', function (e) { e.preventDefault(); resetModal(); }); $(modalClose).on('touchstart', function () { resetModal(); }); $(modalOverlay).on('touchstart', function () { resetModal(); }); $(document).keyup(function (e) { e.preventDefault(); if (e.keyCode == 27) { // escape key maps to keycode `27` resetModal(e); } }); $(modal).keydown(function (event) { trapTabKey($(this), event); }) $(modal).keydown(function (event) { trapEscapeKey($(this), event); }) }); function openModal(that) { // save current focus focusedElementBeforeModal = $(':focus'); $(modal).removeClass('open'); var modalToOpen = '#' + $(that).data('open-modal'); $(body).addClass('no-scroll'); $(modalToOpen).addClass('open').removeClass('closed'); if (!$(that).hasClass('collections-modal')) { $(modalOverlay).addClass('open').removeClass('closed'); } $(section).attr('aria-hidden', 'true'); $(modalToOpen).attr('aria-hidden', 'false'); // mark the modal window as visible $(modalToOpen).find('.modal-close').focus(); if (modalToOpen === '#gallery-modal') { var itemIndex = $(that).parent('.item').index() - 1, galleryPrev = '<a role="button" href="#" class="prev"><svg class="icon-chevron-right"><use xlink:href="#chevron-right"></use></svg></a>', galleryNext = '<a role="button" href="#" class="next"><svg class="icon-chevron-right"><use xlink:href="#chevron-right"></use></svg></a>'; $(galleryModalContent).slick({ dots: false, arrows: true, infinite: true, speed: 500, prevArrow: galleryPrev, nextArrow: galleryNext, slidesToShow: 1, slidesToScroll: 1, swipe: true, adaptiveHeight: true, initialSlide: itemIndex }); } $(galleryModalContent).on('beforeChange', function(event, slick, currentSlide) { var galleryModal = document.getElementById('gallery-modal'), video = galleryModal.querySelector('video'); if (video) { video.pause(); } }); // attach a listener to redirect the tab to the modal window if the user somehow gets out of the modal window $(body).one('focusin', 'section', function() { $(modalClose).focus(); }); } function resetModal() { // var galleryModal = document.getElementById('gallery-modal'), // video = galleryModal.querySelector('video'); // if (video) { // video.pause(); // } $(body).removeClass('no-scroll'); $(modal).addClass('closed').removeClass('open').attr('aria-hidden', 'true'); $(modalOverlay).addClass('closed').removeClass('open'); $(section).attr('aria-hidden', 'false'); $(body).off('focusin', 'section'); // if ($(galleryModalContent).children().length > 0) { // $(galleryModalContent).slick('unslick'); // } focusedElementBeforeModal.focus(); } function trapEscapeKey(obj, evt) { // if escape pressed if (evt.which == 27) { // get list of all children elements in given object var o = obj.find('*'); // get list of focusable items var cancelElement; cancelElement = o.filter("#cancel") // close the modal window cancelElement.click(); evt.preventDefault(); } } function trapTabKey(obj, evt) { // if tab or shift-tab pressed if (evt.which == 9) { // get list of all children elements in given object var o = obj.find('*'); // get list of focusable items var focusableItems; focusableItems = o.filter(focusableElementsString).filter(':visible') // get currently focused item var focusedItem; focusedItem = jQuery(':focus'); // get the number of focusable items var numberOfFocusableItems; numberOfFocusableItems = focusableItems.length // get the index of the currently focused item var focusedItemIndex; focusedItemIndex = focusableItems.index(focusedItem); if (evt.shiftKey) { //back tab // if focused on first item and user preses back-tab, go to the last focusable item if (focusedItemIndex == 0) { focusableItems.get(numberOfFocusableItems - 1).focus(); evt.preventDefault(); } } else { //forward tab // if focused on the last item and user preses tab, go to the first focusable item if (focusedItemIndex == numberOfFocusableItems - 1) { focusableItems.get(0).focus(); evt.preventDefault(); } } } }
// pages/order_wuliu/order_wuliu.js const request_01 = require('../../utils/request/request_01.js'); const method = require('../../utils/tool/method.js'); const router = require('../../utils/tool/router.js'); const authorization = require('../../utils/tool/authorization.js'); const alert = require('../../utils/tool/alert.js'); const app = getApp();//่Žทๅ–ๅบ”็”จๅฎžไพ‹ Page({ /** * ้กต้ข็š„ๅˆๅง‹ๆ•ฐๆฎ */ data: { orderWuliu:{}, }, /** * ็”Ÿๅ‘ฝๅ‘จๆœŸๅ‡ฝๆ•ฐ--็›‘ๅฌ้กต้ขๅŠ ่ฝฝ */ onLoad: function (options) { request_01.login(()=>{ this.initData(options) }) }, /** * ็”Ÿๅ‘ฝๅ‘จๆœŸๅ‡ฝๆ•ฐ--็›‘ๅฌ้กต้ขๅˆๆฌกๆธฒๆŸ“ๅฎŒๆˆ */ onReady: function () { }, /** * ็”Ÿๅ‘ฝๅ‘จๆœŸๅ‡ฝๆ•ฐ--็›‘ๅฌ้กต้ขๆ˜พ็คบ */ onShow: function () { }, /** * ็”Ÿๅ‘ฝๅ‘จๆœŸๅ‡ฝๆ•ฐ--็›‘ๅฌ้กต้ข้š่— */ onHide: function () { }, /** * ็”Ÿๅ‘ฝๅ‘จๆœŸๅ‡ฝๆ•ฐ--็›‘ๅฌ้กต้ขๅธ่ฝฝ */ onUnload: function () { }, /** * ้กต้ข็›ธๅ…ณไบ‹ไปถๅค„็†ๅ‡ฝๆ•ฐ--็›‘ๅฌ็”จๆˆทไธ‹ๆ‹‰ๅŠจไฝœ */ onPullDownRefresh: function () { }, /** * ้กต้ขไธŠๆ‹‰่งฆๅบ•ไบ‹ไปถ็š„ๅค„็†ๅ‡ฝๆ•ฐ */ onReachBottom: function () { }, /** * ็”จๆˆท็‚นๅ‡ปๅณไธŠ่ง’ๅˆ†ไบซ */ onShareAppMessage: function () { }, //้กต้ขๅˆๅง‹ๅŒ– initData(options){ const userInfo = wx.getStorageSync('userInfo'); let promise; if( options.pageType == 'o_prize_detail' ){ //ๅฅ–ๅ“่ฏฆๆƒ…็‰ฉๆตไฟกๆฏ promise = Promise.all([ request_01.prizeWuliu({ user_id:userInfo.user_id, prize_id:options.prize_id, }) ]) } else{ //่ฎขๅ•่ฏฆๆƒ…็‰ฉๆตไฟกๆฏ promise = Promise.all([ request_01.orderWuliu({ user_id:userInfo.user_id, order_id:options.order_id, }) ]) } promise .then((value)=>{ //success const orderWuliu = value[0].data.data; this.setData({ orderWuliu, }) }) .catch((reason)=>{ //fail }) }, })
// An array of all the questions const questionsArr =[ {question: "HTML stands for?", correctAnswer: "Hyper Text Markup Language", incorrectAnswersArr: ["High Text Markup Language", "Hyper Tabular Markup Language", "None of these"] }, { question: "Which of the following tag is used to mark a beginning of paragraph?", correctAnswer: "<P>", incorrectAnswersArr: ["<TD>", "<br>", "<TR>"] }, { question: "From which tag descriptive list starts?", correctAnswer: "<DL>", incorrectAnswersArr: ["<DS>", "<LL>", "<DD>"] }, { question: "Correct HTML tag for the largest heading is", correctAnswer: "<h1>", incorrectAnswersArr: ["<head>", "<h6>", "<heading>"] }, { question: "How to create an unordered list (a list with the list items in bullets) in HTML?", correctAnswer: "<ul>", incorrectAnswersArr: ["<ol>", "<li>", "<i>"] }, { question: "Which character is used to represent the closing of a tag in HTML?", correctAnswer: "/" , incorrectAnswersArr: [".", "<", "!"] }, { question: "How to create a hyperlink in HTML?", correctAnswer: "<a href = \"www.realalgorithm.co.uk/\"> realalgorithm.co.uk/ <a>", incorrectAnswersArr: ["<a url = \"www.realalgorithm.co.uk/\" realalgorithm.co.uk/ <a>", "<a link = \"www.realalgorithm.co.uk/\"> realalgorithm.co.uk/ <<a>", "<a> www.realalgorithm.co.uk/ <realalgorithm.co.uk/ <a>"] }, { question: "How to create an ordered list (a list with the list items in numbers) in HTML?", correctAnswer: "<ol>", incorrectAnswersArr: ["<ul>", "<li>", "<i>"] }, { question: "How to insert an image in HTML?", correctAnswer: "<img src = \"image.png\" >", incorrectAnswersArr: ["<img href = \"image.png\" >", "<img url = \"image.png\" >", "<img link = \"image.png\" >"] }, { question: "How to create a checkbox in HTML?", correctAnswer: "<input type = \"checkbox\">", incorrectAnswersArr: ["<input type = \"button\">", "<checkbox>", "<input type = \"check\">"] }, { question: "Which of the following is the paragraph tag in HTML?", correctAnswer: "<p>", incorrectAnswersArr: ["<b>", "<pre>", "None of these."] }, { question: "A program in HTML can be rendered and read by -", correctAnswer: "Web browser", incorrectAnswersArr: ["Server", "Interpreter", "None of these"] }, { question: "The tags in HTML are -", correctAnswer: "not case-sensitive", incorrectAnswersArr: ["in upper case", "case sensitive", "in lowercase"] }, { question: "Which of the following is the root tag of the HTML document?", correctAnswer: "<html>", incorrectAnswersArr: ["<body>", "<head>", "<title>"] }, { question: "In HTML5, which of the following tag is used to initialize the document type?", correctAnswer: "<!DOCTYPE html>", incorrectAnswersArr: ["<Doctype HTML>", "<\\Doctype html>", "<Doctype>"] }] // for testing /* let emptyQuestionObj = { question: "", correctAnswer: "", incorrectAnswersArr: ["", "", ""] } */ // Declaring variables let playerScore = 0; let timerValue = 90; //seconds const startBtn = document.getElementById("start-btn"); const quizDiv = document.getElementById("quiz-box"); let currentQuestionIndex; let correctAnswerIndex; let invervalTimer; const highScoreDiv = document.getElementById("highscore"); function startTimer(){ // 1000 ms = 1 second timerInterval = setInterval(decreaseTimer, 1000); } function stopTimer(){ clearInterval(timerInterval); } function refreshQuiz() { location.reload(); } function getRandomIndex(numberOfIndexes){ randomInd = Math.floor(Math.random() * numberOfIndexes); return randomInd; } function writeHTML(id, htmlToWrite){ elToUpdate = document.getElementById(id); elToUpdate.innerHTML = htmlToWrite; } function letterToIndex(letter){ let index; switch(letter) { case "a": index = 0; break; case "b" : index = 1; break; case "c" : index = 2; break; case "d" : index = 3; break; default: break; } return index; } function openSaveBox(){ // clear div quizDiv.innerHTML = ""; // give player their final score let saveH1 = document.createElement("h1"); saveH1.textContent = `You scored ${playerScore} would you like to save?` quizDiv.append(saveH1); //container for answer to save or not let contYesNo = document.createElement("div"); contYesNo.id= "container-y-n"; quizDiv.appendChild(contYesNo); // button to load form to save score let btnSave = document.createElement("button"); btnSave.id= "save-score"; btnSave.textContent = "Yes" contYesNo.appendChild(btnSave); // refeshesh the page / quiz let btnRefresh = document.createElement("button"); btnRefresh.id= "btn-refresh"; btnRefresh.textContent = "No" contYesNo.appendChild(btnRefresh); btnSave.addEventListener("click", openRecordScore); btnRefresh.addEventListener("click", refreshQuiz); } function endGame(){ openSaveBox(); stopTimer(); } function saveScore(event){ event.preventDefault(); let highScoresArr = getHighScores(); let playerInitals = document.getElementById("intials").value; // add to begining of array so later when iterating the last score interated over (with increasing index) will // be the oldest therefore if 2 high scores are the same the oldest will be kept highScoresArr.unshift([playerScore, playerInitals]); // using local storage to store string representing an array of high scores. localStorage.setItem("highScores", JSON.stringify(highScoresArr)); refreshQuiz(); } function openRecordScore(){ // Create amend append // new main div let mainDiv = document.getElementById("main"); mainDiv.innerHTML = ""; // new container for form let divRecordIntials = document.createElement("div") divRecordIntials.setAttribute("id", "div-record-highscore") mainDiv.appendChild(divRecordIntials); // new form to take input for players initials let recordScoreForm = document.createElement("form"); recordScoreForm.setAttribute("action", "#") divRecordIntials.appendChild(recordScoreForm); // label of input for players initials let recordScoreLabel = document.createElement("label"); recordScoreLabel.setAttribute("for", "intials"); recordScoreLabel.textContent = "Please enter you intials"; recordScoreForm.appendChild(recordScoreLabel) // label of input for players initials let recordScoreInput = document.createElement("input"); recordScoreInput.setAttribute("id", "intials"); recordScoreInput.setAttribute("name", "intials"); recordScoreInput.setAttribute("type", "text"); recordScoreInput.setAttribute("maxlength", "3"); recordScoreForm.appendChild(recordScoreInput); // submit button for form let recordScoreButton = document.createElement("input"); recordScoreButton.setAttribute("type", "submit"); recordScoreButton.setAttribute("id", "intitals-submit"); recordScoreButton.setAttribute("value", "Submit"); recordScoreForm.appendChild(recordScoreButton); recordScoreForm.addEventListener("submit", saveScore); } function setQuestion(){ // remove last question to stop repeating questions questionsArr.splice(currentQuestionIndex, 1); //select a random question currentQuestionIndex = getRandomIndex(questionsArr.length - 1); // leave on in array to prevent bugs on calls made after last question removed if (questionsArr.length == 1){ endGame(); } } function prepareQuestionReturnAnswer(){ setQuestion() let currentquestionObj = questionsArr[currentQuestionIndex]; // create an array with correct let answersArray = []; // create an array of incorrect answers let incorrectAnswersArr = currentquestionObj.incorrectAnswersArr // iterate over incorrect answers and add to answers array // leaving correct answer at index 0 for (let i = 0; i < 3; i++){ answersArray.unshift(incorrectAnswersArr[i]) } // place correct answer in random index // storing position in a global variable correctAnswerIndex = getRandomIndex(4); answersArray.splice(correctAnswerIndex, 0, currentquestionObj.correctAnswer) return answersArray; } function decreaseTimer(amount = 1){ // decrease to zero when timer to deducted is greater than current time left if (amount > timerValue){ timerValue = 0; }else{ timerValue -= amount; } isTimerGreaterThenZero = timerValue > 0; // decrease timer if (!isTimerGreaterThenZero){ writeHTML("timer", `time's up!`); endGame(); return; } writeHTML("timer", `${timerValue} second(s) left.`); } function changeScore(amountToChangeBy = 0){ playerScore += amountToChangeBy; writeHTML("currentScore", `Current score: ${playerScore}`); } function getHighScores(){ // get high scores from local storage let highScores = JSON.parse(localStorage.getItem("highScores")); // check to see if score has been saved previously // if not set to an empty array if (!highScores){ highScores = []; localStorage.setItem("highScores", JSON.stringify(highScores)); } return highScores; } function createQandAHTML(){ let answerArr = prepareQuestionReturnAnswer(); // clear previous question quizDiv.innerHTML = ""; let question = questionsArr[currentQuestionIndex].question; // create, ammend, append // question questionH1 = document.createElement("h1"); questionH1.textContent = question; quizDiv.appendChild(questionH1); // answers // div to contain all the containers for the answers answersDiv = document.createElement("div"); answersDiv.id = "answers-div"; quizDiv.appendChild(answersDiv); currentAnswersDiv = document.getElementById("answers-div"); // loop for each answer // Limit to 4 answers for (let i = 0;/* i < answerArr.length &&*/ i < 4; i++){ // Answer letter depending on i let currentLetter = "A"; switch(i) { case 1 : currentLetter = "B"; break; case 2 : currentLetter = "C"; break; case 3 : currentLetter = "D"; break; } // Add the container for the answers let answerContainer = document.createElement("div"); answerContainer.className = "answer-container"; answerContainer.id = `answer-container-${currentLetter.toLowerCase()}`; currentAnswersDiv.appendChild(answerContainer); // create referance to newest container currentAnswerContainer = document.getElementById(`answer-container-${currentLetter.toLowerCase()}`); // Answers letter div let answerLetter = document.createElement("div"); answerLetter.className = "answer-letter shadow"; answerLetter.id = `letter-${currentLetter.toLowerCase()}` answerLetter.textContent = currentLetter; currentAnswerContainer.appendChild(answerLetter); // Answers string div let currentAnswerString = answerArr[i]; let answerString = document.createElement("div"); answerString.className = "answer-string"; answerString.id = `string-${currentLetter.toLowerCase()}` answerString.textContent = currentAnswerString; currentAnswerContainer.appendChild(answerString); } } function answerSelected(letterClicked){ indexClicked = letterToIndex(letterClicked); if (indexClicked == correctAnswerIndex){ changeScore(1); }else{ decreaseTimer(10); } createQandAHTML() } function quizDivClicked(event){ splitId = event.target.id.split("-"); if (splitId[0] == "letter" || splitId[0] == "string") { answerSelected(splitId[1]) } // bug fix click on incorrect answer after timer hit 0 if (timerValue <= 0){ endGame(); } } function updateCurrentHighScore(){ highScoresArr = getHighScores(); let tempHighScore = 0; let tempHighScorePlayer = ""; if (highScoresArr.length != 0){ for (let i in highScoresArr){ if (highScoresArr[i][0] >= tempHighScore){ tempHighScore = highScoresArr[i][0]; tempHighScorePlayer = highScoresArr[i][1]; } } highScoreDiv.innerHTML = `High score: ${tempHighScore} recorded by ${tempHighScorePlayer}`; } } function startGame(){ startBtn.style.display = "none"; createQandAHTML(); quizDiv.addEventListener("click", quizDivClicked) startTimer(); changeScore(); } updateCurrentHighScore(); startBtn.addEventListener("click", startGame);
const initialState = { map: {}, } const expresses = function (state = initialState, action) { switch (action.type) { case 'FETCH_EXPRESS_SUCCESS': const { id, express } = action.payload state.map[id] = express return { ...state } default: return state } } export default expresses
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; export class Input extends React.Component { constructor(props) { super(props); this.state = { value: props.value || "", touched: false }; this.handleOnChange = this.handleOnChange.bind(this); this.handleOnBlur = this.handleOnBlur.bind(this); this.handleOnFocus = this.handleOnFocus.bind(this); } /** * handleOnChange() is called every this a change is made to the value of the component. The value od the component is stored in it's state which is used to update the rendering of the component * If the parent component provided a callback function via the onChange property, toe callback function is called with the change * @param event The change event */ handleOnChange(event) { // update the control this.setState({ value: event.target.value }); // and send the evaluation result to the parent, if they want to receive it this.props.onChange && this.props.onChange(event); } /** * handleOnBlur() is called every time the input field loses the input focus. The function will call a callback function if it was provided by the parent component via the onBlur property. */ handleOnBlur(event) { this.props.onBlur && this.props.onBlur(event); } handleOnFocus(event) { this.props.onFocus && this.props.onFocus(event); } render() { return ( <input id={this.props.id} type={this.props.type || 'text'} name={this.props.name} value={this.state.value} className={classNames('atom-textInput', this.props.className, {"readonly": this.props.readonly})} onChange={this.handleOnChange} onBlur={this.handleOnBlur} onFocus={this.handleOnFocus} required={this.props.required && 'required'} placeholder={this.props.placeholder} readOnly={this.props.readonly || false} /> ); } } Input.propTypes = { type: PropTypes.oneOf(['text', 'email', 'number']), name: PropTypes.string.isRequired, className: PropTypes.string, id: PropTypes.string, required: PropTypes.bool, value: PropTypes.string, onChange: PropTypes.func, onBlur: PropTypes.func, onFocus: PropTypes.func, placeholder: PropTypes.string, readonly:PropTypes.bool };
(function (angular) { "use strict"; function CountryController($scope, $http) { $http.get('../demo-data/countries.json').success(function (data) { $scope.countries = data; }); } angular.module('app1', []) .controller('CountryController', CountryController); })(window.angular);
//Meteor.methods({ // getCities : function(){ // return Cities.find(); // } //})
import React, { Component } from 'react'; import './index.css'; import partnershipsLabel from './partnerships_label.svg'; import stoneLabel from './stone_label.svg'; import goldLabel from './gold_label.svg'; import platinumLabel from './platinum_label.svg'; import thanks from './thanks.svg'; import BalsamiqLogo from './logos/balsamiq.png'; import BoschLogo from './logos/bosch.svg'; import BurocratikLogo from './logos/burocratik.svg'; import DankeLogo from './logos/danke.svg'; import FarfetchLogo from './logos/farfetch.svg'; import FullsixLogo from './logos/fullsix.svg'; import GinettaLogo from './logos/ginetta.svg'; import HiLogo from './logos/hi.svg'; import HostelworldLogo from './logos/hostelworld.svg'; import MediawebLogo from './logos/mediaweb.png'; import OutsystemsLogo from './logos/outsystems.svg'; import PixelmattersLogo from './logos/pixelmatters.svg'; import PWITLogo from './logos/pwit.svg'; import ProzisLogo from './logos/prozis.svg'; import SeegnoLogo from './logos/seegno.svg'; import StartupBragaLogo from './logos/startup@2x.png'; import TndsLogo from './logos/tnds.svg'; import UtrustLogo from './logos/utrust.svg'; import WitLogo from './logos/wit.png'; import XingLogo from './logos/xing.svg'; export default class Sponsors extends Component { render() { return ( <section className="Sponsors" id="sponsors"> <div className="Sponsors-content"> <div className="Sponsors-group"> <img alt="Platinum sponsors" src={platinumLabel} /> <div className="Sponsors-groupContent"> <a href="http://www.utrust.com/"> <img alt="Utrust" className="Sponsors-pwit" src={UtrustLogo} /> </a> </div> </div> <div className="Sponsors-group"> <img alt="Gold sponsors" src={goldLabel} /> <div className="Sponsors-groupContent"> <a href="http://www.farfetch.com/"> <img alt="Farfetch" className="Sponsors-logo" src={FarfetchLogo} /> </a> <a href="https://www.hostelworld.com/"> <img alt="Hostelworld" className="Sponsors-logo" src={HostelworldLogo} /> </a> <a href="https://www.xing.com/en"> <img alt="Xing" className="Sponsors-logo" src={XingLogo} /> </a> <a href="https://www.hi-interactive.pt/en/"> <img alt="Hi-Interactive" className="Sponsors-logo" src={HiLogo} /> </a> <a href="https://www.hi-interactive.pt/en/"> <img alt="SeegnoLogo" className="Sponsors-logo" src={SeegnoLogo} /> </a> <a href="https://ginetta.net/"> <img alt="Ginetta" className="Sponsors-logo" src={GinettaLogo} /> </a> <a href="https://www.outsystems.com/"> <img alt="Outsystems" className="Sponsors-logo" src={OutsystemsLogo} /> </a> <a href="https://www.wit-software.com/"> <img alt="Wit Software" className="Sponsors-logo" src={WitLogo} /> </a> </div> </div> <div className="Sponsors-group"> <img alt="Stone sponsors" src={stoneLabel} /> <div className="Sponsors-groupContent"> <a href="https://balsamiq.com/"> <img alt="Balsamiq" className="Sponsors-logo" src={BalsamiqLogo} /> </a> <a href="http://pixelmatters.com/"> <img alt="Pixelmatters" className="Sponsors-logo" src={PixelmattersLogo} /> </a> <a href="https://mediaweb.pt/"> <img alt="Mediaweb" className="Sponsors-logo" src={MediawebLogo} /> </a> <a href="https://www.burocratik.com/"> <img alt="Burocratik" className="Sponsors-logo" src={BurocratikLogo} /> </a> <a href="https://www.prozis.com/pt/en"> <img alt="Prozis" className="Sponsors-logo" src={ProzisLogo} /> </a> <a href="http://www.fullsix.pt/"> <img alt="Fullsix" className="Sponsors-logo" src={FullsixLogo} /> </a> <a href="https://www.bosch.pt/"> <img alt="Bosch" className="Sponsors-logo" src={BoschLogo} /> </a> <a href="https://www.danke.pt/"> <img alt="Danke" className="Sponsors-logo" src={DankeLogo} /> </a> </div> </div> <div className="Sponsors-group"> <img alt="Partnerships" src={partnershipsLabel} /> <div className="Sponsors-groupContent"> <a href="http://www.portuguesewomenintech.com/"> <img alt="Portuguese Women In Tech" className="Sponsors-pwit" src={PWITLogo} /> </a> <a href="https://www.startupbraga.com/"> <img alt="Startup Braga" className="Sponsors-logo" src={StartupBragaLogo} /> </a> <a href="http://thenewdigitalschool.com/"> <img alt="The New Digital School" className="Sponsors-logo" src={TndsLogo} /> </a> </div> </div> <div className="Sponsors-group"> <img alt="Thank you!" src={thanks} /> </div> <div className="Sponsors-firePlaholder" /> </div> </section> ); } }
/** * Created by admin on 09-10-2015. */ quizMod.controller('QuizController',function($scope,QuizService){ $scope.question = {}; })
import React from 'react'; import './App.scss'; function App () { return ( <React.Fragment> <h1>Custom Create-React-App template and setup</h1> <h2> Start by editing <code>src/components/App/App.jsx</code> </h2> </React.Fragment> ); } export default App;
// cards array holds all cards let card = global.window.getElementsByClassName("card"); let cards = [...card]; // deck of all cards in game const deck = global.window.getElementById("card-deck"); // declaring variable of matchedCards let matchedCard = global.window.getElementsByClassName("match"); // close icon in modal let closeIcon = global.window.querySelector(".close"); // declare modal let modal = global.window.getElementById("popup1"); // array for opened cards let openedCards = []; //Fisher-Yates shuffles cards method. function shuffle(arr){ let newPos, temp; for(let i = arr.length - 1; i > 0; i--) { newPos = Math.floor(Math.random() * (i+1)); temp = arr[i]; arr[i] = arr[newPos]; arr[newPos] = temp; } return arr; }; //function to start a new play function startGame() { // empty the openCards array openedCards = []; // shuffle deck cards = shuffle(cards); // remove all existing classes from each card for (let i = 0; i < cards.length; i++) { deck.innerHTML = ""; cards.forEach(function(item) { deck.appendChild(item); }); } } // toggle open and show class to display cards const displayCard = function() { this.classList.toggle("open"); this.classList.toggle("show"); this.classList.toggle("disabled"); // console.log('line 55 displayCard') }; // add opened cards to OpenedCards list and check if cards are match or not function cardOpen() { openedCards.push(this); if (openedCards.length === 2) { if (openedCards[0].type === openedCards[1].type) { matched(); } else { unmatched(); } } } // function when cards do match function matched() { openedCards[0].classList.add("match", "disabled"); openedCards[1].classList.add("match", "disabled"); openedCards[0].classList.remove("show", "open", "no-event"); openedCards[1].classList.remove("show", "open", "no-event"); openedCards = []; } // function when cards don't match function unmatched() { openedCards[0].classList.add("unmatched"); openedCards[1].classList.add("unmatched"); disable(); setTimeout(function() { openedCards[0].classList.remove( "show", "open", "no-event", "unmatched" ); openedCards[1].classList.remove( "show", "open", "no-event", "unmatched" ); enable(); openedCards = []; }, 1100); } // disable cards temporarily function disable() { cards.filter(function(card) { card.classList.add("disabled"); }); } // enable cards and disable matched cards function enable() { cards.filter(function(card) { card.classList.remove("disabled"); for (let i = 0; i < matchedCard.length; i++) { matchedCard[i].classList.add("disabled"); } }); } // congratulations when all cards match, show modal function congratulations() { if (matchedCard.length == 16) { // show congratulations modal modal.classList.add("show"); //closeIcon on modal closeModal(); } } // close icon on modal function closeModal() { closeIcon.addEventListener("click", function(e) { modal.classList.remove("show"); startGame(); }); } // function for user to play Again function playAgain() { modal.classList.remove("show"); startGame(); } // loop to add event listeners to each card for (let i = 0; i < cards.length; i++) { card = cards[i]; card.addEventListener("click", displayCard); card.addEventListener("click", cardOpen); card.addEventListener("click", congratulations); } module.exports = { playAgain, closeModal, congratulations, enable, disable, unmatched, matched, displayCard, startGame, shuffle, openedCards, cards }
const mongoose = require("mongoose"); const user = mongoose.Schema({ login: { type: String, required: true }, fullName: { type: String, required: true }, email: { type: String, required: true }, rol: { type: String, required: true, default: "Vendedor" }, estado: { type: String, required: true, default: "Pendiente" }, }); module.exports = mongoose.model("User", user);
/** * @param {number[]} houses * @param {number[]} heaters * @return {number} */ var findRadius = function(houses, heaters) { var n = heaters.length, j = 0, res = 0; houses.sort((a,b) => { return a-b; }); heaters.sort((a,b) => { return a-b; }); for(var i = 0 ; i < houses.length; i++) { var cur = houses[i]; while(j<n-1 && Math.abs(heaters[j+1]-cur) <=Math.abs(heaters[j]-cur)) { j++; } res = Math.max(res, Math.abs(heaters[j] - cur)); } return res; }; console.log(findRadius([1,2,3], [2]));
import Vue from 'vue' import App from './App.vue' import router from './router' // ๅผ•ๅ…ฅmuse-ui import MuseUI from 'muse-ui'; import 'muse-ui/dist/muse-ui.css'; import 'typeface-roboto' Vue.use(MuseUI) Vue.config.productionTip = true new Vue({ router, render: h => h(App) }).$mount('#app')
var NUM_HISTS = 50; var NUM_LINES = 50; var SW = 640; var SH = 480; var MAX_DIST = 400; var TIMEOUT_MSEC = 16; var Z_FACTOR = 200; var WIDTH_FACTOR = 50; var LINE_VEL = 20; var CAM_VEL_FACTOR = 30; var FILL_ALPHA = 10; var FILL_ALPHA_STR = ''; var V = function(x, y, z) { if (this == window) return new V(x, y, z); this.x = x; this.y = y; this.z = z; this.assign = function(p) { this.x = p.x; this.y = p.y; this.z = p.z; }; this.add = function(p) { this.x += p.x; this.y += p.y; this.z += p.z; }; this.neg = function() { this.x = -this.x; this.y = -this.y; this.z = -this.z; }; this.dist = function(p) { var dx = this.x - p.x; var dy = this.y - p.y; var dz = this.z - p.z; return Math.sqrt(dx * dx + dy * dy + dz * dz); }; }; var Line = function(p, v) { if (this == window) return new Line(p, v); this.hist = new Array(NUM_HISTS); for (var i = 0; i < this.hist.length; i++) { this.hist[i] = V(p.x, p.y, p.z); } this.index = 0; this.v = v; this.cur = function() { return this.hist[this.index]; }; this.next = function() { this.index = (this.index + 1) % this.hist.length; return this.cur(); }; this.nextIndex = function(index) { return (index + 1) % this.hist.length; }; }; var Camera = function() { this.angle = 0; this.x = function() { return Math.cos(this.angle) * 1000; }; this.y = function() { return Math.sin(this.angle) * 1000; }; this.z = function() { return 0; }; this.p = function() { return V(this.x(), this.y(), this.z()); }; this.move = function() { this.angle += CAM_VEL_FACTOR * 0.0001; } }; var Timer = function() { this.times = new Array(60); for (var i = 0; i < this.times.length; i++) { this.times[i] = new Date().getTime(); } this.index = 0; this.move = function() { this.index = (this.index + 1) % this.times.length; var prev = this.times[this.index]; var now = new Date().getTime(); this.times[this.index] = now; var diff = now - prev; if (diff == 0) { return "???"; } var fps = this.times.length * 1000 / diff; var fpsInt = Math.floor(fps); return fpsInt + "." + Math.round((fps - fpsInt) * 100); }; }; var camera = null; var timer = null; var lines = null; var out = V(0, 0, 0); var timeoutId = null; var MONOCHROME_COLORS = null; var make2d_funcs = { "xz" : function(p, c) { out.x = p.x - c.x + SW / 2; out.y = p.z - c.z + SH / 2; out.z = 255; }, "xy" : function(p, c) { out.x = p.x - c.x + SW / 2; out.y = p.y - c.y + SH / 2; out.z = 255; }, "xz_p3d" : function(p, c) { var dz = (p.y - c.y + MAX_DIST) * 0.5 / MAX_DIST; var r = 1 / (dz + 1); out.x = (p.x - c.x) * r + SW / 2; out.y = (p.z - c.z) * r + SH / 2; out.z = Math.floor(256 - dz * Z_FACTOR); }, "bug" : function(p, c) { var dz = (p.y - c.y); var r = 1 / (dz + 1); out.x = (p.x - c.x) * r + SW / 2; out.y = (p.z - c.z) * r + SH / 2; out.z = Math.floor(256 - dz * Z_FACTOR); } }; var zeffect_funcs = { "none": function(ctx, z) { }, "width": function(ctx, z) { ctx.lineWidth = z / WIDTH_FACTOR; }, "color": function(ctx, z) { ctx.strokeStyle = MONOCHROME_COLORS[z]; }, "w+c": function(ctx, z) { ctx.lineWidth = z / WIDTH_FACTOR; ctx.strokeStyle = MONOCHROME_COLORS[z]; } }; function hexstr(v) { v = new Number(v).toString(16); return v.length == 1 ? "0" + v : v; } function rgb(r, g, b) { r = hexstr(r); g = hexstr(g); b = hexstr(b); return "#" + r + g + b; } var gencolor_funcs = { "alpha": function(c) { return "rgba(255,255,255," + (c / 256) + ")"; }, "gray": function(c) { c = hexstr(c); return "#" + c + c + c; }, "red": function(c) { return "red"; }, "rainbow": function(c) { if (c < 64) { return rgb(255, c * 4, 0); } if (c < 128) { return rgb(255 - (c - 64) * 4, 255, 0); } if (c < 192) { return rgb(0, 255, (c - 128) * 4); } return rgb(0, 255 - (c - 192) * 4, 255); }, "chaos": function(c) { var g = function() { return Math.floor(Math.random() * 255); } return rgb(g(), g(), g()); } }; var CATEGORIES = [ { "id": "make2d", "name": "3D=>2D", "funcs": make2d_funcs, "default_func": "xz_p3d" }, { "id": "zeffect", "name": "Z effect", "funcs": zeffect_funcs, "default_func": "w+c" }, { "id": "gencolor", "name": "Colors", "funcs": gencolor_funcs, "default_func": "alpha", "onchange": initColors } ]; var category_map = {}; function log(msg) { document.getElementById("console").innerHTML += msg + "<br>"; } function initLine(cp) { var pg = function() { return Math.random() * 200 - 100; }; var t = Math.random() * Math.PI * 2; var p = Math.random() * Math.PI; var vr = LINE_VEL; var vx = vr * Math.sin(t) * Math.cos(p); var vy = vr * Math.sin(t) * Math.sin(p); var vz = vr * Math.cos(t); return Line(V(cp.x + pg(), cp.y + pg(), cp.z + pg()), V(vx, vy, vz)); } function selectCategory(self) { var id = self.name; var category = category_map[id]; window[id] = category.funcs[self.value]; if (category.onchange) { category.onchange(); } } function changeParameter(self) { var id = self.name; var val = parseInt(self.value, 10); if (window[id] == val) { return; } log(id + ": " + window[id] + " => " + val); window[id] = val; if (timeoutId) { clearTimeout(timeoutId); } initDemo(); } function initUI() { var html = ""; for (var i = 0; i < CATEGORIES.length; i++) { var category = CATEGORIES[i]; category_map[category.id] = category; html += ['<div>', category.name, ': '].join(''); var funcs = category.funcs; for (var key in funcs) { checked = ""; if (key == category.default_func) { checked = " checked"; } html += ['<input type="radio" name="', category.id, '" value="', key, '"', checked, ' onchange="selectCategory(this)">', key].join(''); } } PARAMETERS = [ 'NUM_HISTS', 'NUM_LINES', 'MAX_DIST', 'TIMEOUT_MSEC', 'WIDTH_FACTOR', 'Z_FACTOR', 'LINE_VEL', 'CAM_VEL_FACTOR', 'FILL_ALPHA' ]; for (var i = 0; i < PARAMETERS.length; i++) { var param = PARAMETERS[i]; html += ['<div>', param, ': ', '<input size="10" name="', param, '" value="', window[param], '" onkeyup="changeParameter(this)">'].join(""); } document.getElementById("ui").innerHTML = html; } function initColors() { MONOCHROME_COLORS = []; for (var i = 0; i < 256; i++) { var c = gencolor(i); MONOCHROME_COLORS.push(c); } } function initDemo() { FILL_ALPHA_STR = 'rgba(0, 0, 0, ' + FILL_ALPHA * 0.01 + ')'; initColors(); timer = new Timer(); camera = new Camera(); var cp = camera.p(); lines = new Array(NUM_LINES); for (var i = 0; i < NUM_LINES; i++) { lines[i] = initLine(cp); } cont(); } function init() { initUI(); for (var i = 0; i < CATEGORIES.length; i++) { var category = CATEGORIES[i]; window[category.id] = category.funcs[category.default_func]; } initDemo(); log("init done"); } function cont() { timeoutId = setTimeout("run();", TIMEOUT_MSEC); } function reflect(d, n, v, c) { if (Math.abs(n[d] - c) > MAX_DIST) { v[d] = -v[d]; for (var j = 0; Math.abs(n[d] - c) > MAX_DIST; j++) { if (j > 10) { return false; } n[d] += v[d]; } } return true; } function move() { document.getElementById("fps").textContent = timer.move(); camera.move(); var cp = camera.p(); for (var i = 0; i < lines.length; i++) { var line = lines[i]; var p = line.cur(); var n = line.next(); n.assign(p); n.add(line.v); if (!reflect("x", n, line.v, cp.x) || !reflect("y", n, line.v, cp.y) || !reflect("z", n, line.v, cp.z)) { lines[i] = initLine(cp); } } } function draw() { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.fillStyle = FILL_ALPHA_STR; ctx.globalCompositeOperation = "source-over"; ctx.fillRect(0, 0, SW, SH); ctx.strokeStyle = 'rgb(255, 255, 255)'; ctx.fillStyle = 'rgb(255, 255, 255)'; ctx.lineWidth = 1; var cp = camera.p(); for (var i = 0; i < lines.length; i++) { var line = lines[i]; var k = 0; for (var j = line.nextIndex(line.index); j != line.index; j = k) { var k = line.nextIndex(j); var p = line.hist[j]; var n = line.hist[k]; ctx.beginPath(); make2d(p, cp); if (out.z <= 0) continue; if (out.z > 255) out.z = 255; zeffect(ctx, out.z); ctx.moveTo(out.x, out.y); make2d(n, cp); ctx.lineTo(out.x, out.y); ctx.closePath(); ctx.stroke(); } } } function run() { move(); draw(); cont(); }
import styled from 'styled-components'; import React from 'react'; function Logo() { return ( <svg xmlns="http://www.w3.org/2000/svg" width="208.664" height="78.221" viewBox="0 0 208.664 78.221"> <g id="Group_1" data-name="Group 1" transform="translate(-179 -495)"> <text id="Elixir" transform="translate(179 549)" fill="#a5e02e" fontSize="60" fontFamily="PTSans-Caption, PT Sans Caption"><tspan x="0" y="0">Elixir</tspan></text> <text id="Quiz" transform="matrix(0.94, -0.342, 0.342, 0.94, 300.269, 562.885)" fill="#f62671" fontSize="40" fontFamily="PTSans-CaptionBold, PT Sans Caption" fontWeight="700"><tspan x="0" y="0">Quiz</tspan></text> </g> </svg> ); } const QuizLogo = styled(Logo)` margin: auto; display: block; @media screen and (max-width: 500px) { margin: 0; } `; export default QuizLogo;
const secondHand = document.querySelector('.secondHand'); const minuteHand = document.querySelector('.minuteHand'); const hourHand = document.querySelector('.hourHand'); const body = document.querySelector('body'); function setDate() { const now = new Date(); const seconds = now.getSeconds(); const secondsDegrees = ((seconds / 60) * 360) + 90; secondHand.style.transform = `rotate(${secondsDegrees}deg)`; const minutes = now.getMinutes(); const minutesDegrees = ((minutes / 60) * 360) + 90; minuteHand.style.transform = `rotate(${minutesDegrees}deg)`; const hours = now.getHours(); const hoursDegrees = ((hours / 60) * 360) + 90; hourHand.style.transform = `rotate(${hoursDegrees}deg)`; const randomColor = JSON.stringify(Math.floor(Math.random() * 1000000)); body.style.backgroundColor = `#${randomColor}`; } setInterval(setDate, 1000); setDate();
// import your node modules const express = require('express'); const cors = require('cors'); const db = require('./data/db.js'); // add your server code starting here const server = express(); server.use(cors()); server.get('/api/posts', (request, response) => { db .find() .then(posts => { console.log('posts: ', posts) response.json(posts) }) .catch(err => response.send(err)) }); // server.post('/api/posts', (request, response) => { // const {title, contents} = request.body; // const newPost = {title, contents}; // db.insert(newPost) // .then(postId => { // const {id} = postId; // db.findById(id).then(post => { // if(title === null || contents === null){ // return response.status(400).send({errorMessage: "No title or contents provided for post."}) // } // console.log(post); // if (!post) { // return response // .status(422) // .send({Error: `No post with that id ${id} exists.`}) // } else if (!post.title || !post.body){ // return response // .status(400) // .send({Error: `Title or contents missing from post`}) // } else { // response.status(201).send(post); // } // }) // .catch(err => response.status(500).send({error: 'Error while saving post to database.'})) // }) // }) const port = 3000; server.listen(port, () => console.log(`API is running on port ${port}.`) );
import './details.css' import {withRouter} from 'react-router'; // import '../../js/common' // import $ from '../../js/jquery-3.2.1' // import '../../js/details' // import '../../js/swipeslider.min' import React from 'react' import http from '../../utils/httpclients' var styleh1 = { position: 'sticky', top: 0, zIndex: 10, } var styleh2 = { transitionTimingFunction: 'cubic-bezier(0.1, 0.57, 0.1, 1)', transitionDuration: '120ms', transform: 'translate(0px, 0px) translateZ(0px)', } var styleh3 = { touchAction: 'pan-y', userSelect: 'none', userDrag: 'none', tapHighlightColor: 'rgba(0, 0, 0, 0)', } var styhide = { transitionTimingFunction: 'cubic-bezier(0.1, 0.57, 0.1, 1)', transitionDuration: '0ms', transform: 'translate(0px, 0px) translateZ(0px)', } var stylemar = { margin: '10px 10px 0px', } class Details extends React.Component{ state = { mydetails: '', skushow:'skuclose', propbtnred:'', btnred:'', num: 1, btncol:'', pushshow:{display:'none'}, } sku_show(){ this.setState({ skushow:'skushow' }); } sku_close(){ this.setState({ skushow:'skuclose' }) } changered(){ this.setState({ propbtnred:'v-propbtn-1', btnred:'', btncol:'btn-2' }) } removered(){ this.setState({ propbtnred:'', btnred:'v-propbtn-1', btncol:'btn-2' }) } addnum(){ this.setState({ num:this.state.num + 1 }) } reducenum(){ this.setState({ num:this.state.num - 1, }) if(this.state.num<=1){ this.setState({ num:1 }) } } //ๆ˜พ็คบๅŠ ๅ…ฅ่ดญ็‰ฉ่ฝฆๅผน็ช— push_show(e){ this.setState({ skushow:'', }) console.log(e.target) if(e.target.className.indexOf('btn-2') > 0){ $('.success').fadeIn(400,()=>{ setTimeout(()=>{ $('.success').fadeOut(350) },700) }) } } t_car(){ this.props.router.push({pathname: '/car', query: {id: "en"}}) } pan_dl(){ var yonghu=window.localStorage.getItem("username"); if(yonghu){ http.get("users").then(res=>{ res.data.map(item=>{ if(item.username==yonghu){ var naduotiaoshuju = item.arr || []; if(typeof naduotiaoshuju === 'string'){ naduotiaoshuju = JSON.parse(naduotiaoshuju); }; $(".n-btnwrap .count").html(naduotiaoshuju.length); } }) }) } } componentDidMount(){ $('#full_feature').swipeslider(); $('.v-returnicon').click(function(){ history.go(-1) }) var id = this.props.location.query.id // console.log(id) http.get('stores').then((res)=>{ // console.log(res) res.data.map((item,idx)=>{ if(item.id==id){ // console.log(item) this.setState({ mydetails:item }) } }) }) this.pan_dl(); $("#c_main").scroll(()=>{ console.log(666) }) } jiagou(e){ if(e.target.className.indexOf('btn-2') > 0){ this.setState({ skushow:'', }) $('.success').fadeIn(400,()=>{ setTimeout(()=>{ $('.success').fadeOut(350) },700) }) var id = this.props.location.query.id; var yonghu=window.localStorage.getItem("username"); if(yonghu){ var num=$(".ctrnum-wrap .qty").val(); http.get("users").then(res=>{ res.data.map(item=>{ if(item.username==yonghu){ console.log(item); var naduotiaoshuju = item.arr || []; if(typeof naduotiaoshuju === 'string'){ naduotiaoshuju = JSON.parse(naduotiaoshuju); }; var idx; var has = naduotiaoshuju.some(function(g,i){ idx = i; return g.s_id == id; }); if(has){ naduotiaoshuju[idx].qty=(naduotiaoshuju[idx].qty)*1+num*1; }else{ naduotiaoshuju.push({s_id:id,qty:num}); } var arr=JSON.stringify(naduotiaoshuju) http.post("c_shuju",{y_id:item._id,arr}).then(res=>{ console.log(res) this.pan_dl(); }) } }) }) }else{ if(confirm("ๅ…ˆ็™ปๅฝ•ๅ†ๅŠ ๅ…ฅ่ดญ็‰ฉ่ฝฆๅง๏ผ")==true){ this.props.router.push({pathname: '/user', query: {id: "tan"}}) } } } } render(){ return( <div> <header className="m-topnavwrap" style={styleh1}> <div className="m-sticknav nav-fixed"> <div className="navbar" id="auto-id-1526117494383" style={styleh2}> <ul className="tabbox"> <li data-index="0" className="itm cur" id="auto-id-1526117494386">ๅ•†ๅ“</li> <li data-index="1" className="itm" id="auto-id-1526117494388">่ฏ„ไปท</li> <li data-index="2" className="itm" id="auto-id-1526117494390">ๆŽจ่</li> <li data-index="3" className="itm" id="auto-id-1526117494392">่ฏฆๆƒ…</li> </ul> <span className="v-returnicon" style={styleh3} ></span> <a href="#" className="v-homeicon" style={styleh3}></a> </div> </div> </header> <main id="c_main"> <div className="n-imgbox"> <div id="full_feature" className="swipslider"> <ul className="sw-slides"> <li className="sw-slide"><img className="v-img" src={this.state.mydetails.img} /></li> <li className="sw-slide"><img className="v-img" src={this.state.mydetails.img} /></li> <li className="sw-slide"><img className="v-img" src={this.state.mydetails.img} /></li> <li className="sw-slide"><img className="v-img" src={this.state.mydetails.img} /></li> <li className="sw-slide"><img className="v-img" src={this.state.mydetails.img} /></li> <li className="sw-slide"><img className="v-img" src={this.state.mydetails.img} /></li> <li className="sw-slide"><img className="v-img" src={this.state.mydetails.img} /></li> </ul> </div> </div> <div className="n-colorimg"> <div className="colorimgwrap"> <div className="imgbox imgbox-1 active"> <img className="v-mainimg" src={this.state.mydetails.img} /> </div> <span className="txt">้ขœ่‰ฒ๏ผš</span> <ul className="colorimg"> <li className="itm"><div className="imgbox "><img className="v-colorimg" src={this.state.mydetails.img} /></div></li> <li className="itm"><div className="imgbox "><img className="v-colorimg" src={this.state.mydetails.img} /></div></li> </ul> </div> </div> <div className="n-price"> <div className="n-price__left"> <span className="curprice">ยฅ<i className="curnum">{this.state.mydetails.sell}</i></span> <span className="mrkprice">ยฅ{this.state.mydetails.price}</span> <span className="tag">็‰นไปท</span> </div> </div> <div id="J_wb_rebate" style={stylemar}></div> <h4 className="n-title f-els-2">{this.state.mydetails.name} </h4> <p className="n-subtit"> ่ตฐ่ฟ‡่ทฏ่ฟ‡๏ผŒไธ่ฆ้”™่ฟ‡๏ผŒๆœบไธๅฏๅคฑ๏ผŒๆ—ถไธๅ†ๆฅใ€‚ {this.state.mydetails.name} </p> <div className="n-tagbox"> <div className="n-taginfo"> <img src="./src/images/d_usa.png" height="32" width="32" className="v-flagimg" /> <span className="tagtxt">ไธญๅ›ฝๅ“็‰Œ</span> <img src="./src/images/d_kl.png" height="32" width="32" className="v-flagimg" /> <span className="tagtxt">ไป™ๅ›่‡ช่ฅ</span> </div> </div> <p className="v-sperate"></p> <ul className="n-activitybox"> <li className="itm n-selectprops" onClick={this.sku_show.bind(this)}> <div className="name">่ฏท้€‰ๆ‹ฉ๏ผš</div> <div className="cnt propinfo"> <p className="props f-els-1">้ขœ่‰ฒ</p> </div> <div className="v-linkicon"></div> </li> <li className="itm n-distribution"> <div className="name">้…&nbsp;&nbsp;้€๏ผš</div> <div className="cnt"> <div className="addr"> <p className="f-els-1"><span className="section">่‡ณ</span> ๅนฟๅทžๅธ‚่”ๆนพๅŒบ</p> <div className="v-linkicon"></div> </div> </div> </li> <li className="itm n-expressinfo"> <div className="name">่ฟ&nbsp;&nbsp;่ดน๏ผš</div> <div className="cnt expressinfo f-els-1"> <p className="expresstxt">ๆปก88ๅ…ƒๅ…่ฟ่ดน</p> </div> <div className="v-linkicon"></div> </li> <li className="itm n-description"> <div className="name">่ฏด&nbsp;&nbsp;ๆ˜Ž๏ผš</div> <ul className="cnt descwrap f-els-1"> <li className="txt">ๅ‡ไธ€่ต”ๅ</li> <li className="txt">ไธๆ”ฏๆŒ7ๅคฉๆ— ็†็”ฑ้€€่ดง</li> <li className="txt">ไธๅฏไฝฟ็”จไผ˜ๆƒ ๅˆธ</li> <li className="txt">่‡ช่ฅๅ›ฝๅ†…ไป“ๅ‘่ดง</li> </ul> <div className="v-linkicon"></div> </li> </ul> <p className="v-sperate"></p> <div className="n-commentbox"> <h4 className="tit" >ๅ…ถไป–ๅฐไผ™ไผดไปฌ่ฏด(995) <div className="v-linkicon"></div> </h4> </div> <p className="v-sperate"></p> <div className="n-recommendbox"> <h4 className="tit">XXXๆŽจ่</h4> <div className="listwrap"> <ul className="recommendlist"> <li className="itm"> <a className="v-link" href="/product/1791117.html"> <img className="v-img u-lazyimg-loaded " src="https://haitao.nos.netease.com/b8df3f01577049be9f388aa5695363e91506603055292j84gk5gj10756.jpg?imageView&amp;thumbnail=250x0&amp;quality=75&amp;type=webp" data-src="https://haitao.nos.netease.com/b8df3f01577049be9f388aa5695363e91506603055292j84gk5gj10756.jpg?imageView&amp;thumbnail=250x0&amp;quality=75&amp;type=webp" /> <p className="subtit f-els-2">Apple ่‹นๆžœ iPhone X 256GB็งปๅŠจ่”้€š็”ตไฟก4Gๆ‰‹ๆœบ ๅ›ฝๅ†…่กŒ่ดง</p> <p className="priceinfo"> <span className="curprice">ยฅ8899</span>&nbsp;&nbsp;<span className="mrkprice">ยฅ9605</span> </p> </a> </li> <li className="itm"> <a className="v-link" href="/product/1791083.html"> <img className="v-img u-lazyimg-loaded " src="https://haitao.nosdn2.127.net/2bde8731568b4e42851da21864d6ba271505287418196j7ip9hdo10719.jpg?imageView&amp;thumbnail=250x0&amp;quality=75&amp;type=webp" data-src="https://haitao.nosdn2.127.net/2bde8731568b4e42851da21864d6ba271505287418196j7ip9hdo10719.jpg?imageView&amp;thumbnail=250x0&amp;quality=75&amp;type=webp" /> <p className="subtit f-els-2">Apple ่‹นๆžœ iPhone8 Plus (A1864) 64GB ็งปๅŠจ่”้€š็”ตไฟก4Gๆ‰‹ๆœบ ๅ›ฝๅ†…่กŒ่ดง</p> <p className="priceinfo"> <span className="curprice">ยฅ5688</span>&nbsp;&nbsp;<span className="mrkprice">ยฅ6630</span> </p> </a> </li> <li className="itm"> <a className="v-link" href="/product/1791060.html"> <img className="v-img u-lazyimg-loaded " src="https://haitao.nos.netease.com/1a07c21f51754b61bf6f295c6b25462d1505286424478j7ioo6mb10655.jpg?imageView&amp;thumbnail=250x0&amp;quality=75&amp;type=webp" data-src="https://haitao.nos.netease.com/1a07c21f51754b61bf6f295c6b25462d1505286424478j7ioo6mb10655.jpg?imageView&amp;thumbnail=250x0&amp;quality=75&amp;type=webp" /> <p className="subtit f-els-2">Apple ่‹นๆžœ iPhone8(A1863) 64GB ็งปๅŠจ่”้€š็”ตไฟก4Gๆ‰‹ๆœบ ๅ›ฝๅ†…่กŒ่ดง</p> <p className="priceinfo"> <span className="curprice">ยฅ4688</span>&nbsp;&nbsp;<span className="mrkprice">ยฅ5837</span> </p> </a> </li> <li className="itm"> <a className="v-link" href="/product/1497530.html"> <img className="v-img u-lazyimg-loaded " src="https://haitao.nos.netease.com/1bfjh59as71_800_800.jpg?imageView&amp;thumbnail=250x0&amp;quality=75&amp;type=webp" data-src="https://haitao.nos.netease.com/1bfjh59as71_800_800.jpg?imageView&amp;thumbnail=250x0&amp;quality=75&amp;type=webp" /> <p className="subtit f-els-2">Apple ่‹นๆžœ iPhone 6 32GB ็งปๅŠจ่”้€š็”ตไฟก4Gๆ‰‹ๆœบ</p> <p className="priceinfo"> <span className="curprice">ยฅ1988</span>&nbsp;&nbsp;<span className="mrkprice">ยฅ2499</span> </p> </a> </li> <li className="itm"> <a className="v-link" href="/product/2060174.html"> <img className="v-img u-lazyimg-loaded " src="https://pop.nosdn.127.net/4344f133-0930-4da7-bdec-43fa3dc3c48b?imageView&amp;thumbnail=250x0&amp;quality=75&amp;type=webp" data-src="https://pop.nosdn.127.net/4344f133-0930-4da7-bdec-43fa3dc3c48b?imageView&amp;thumbnail=250x0&amp;quality=75&amp;type=webp" /> <p className="subtit f-els-2">Apple ่‹นๆžœ iPhone X ็งปๅŠจ่”้€š็”ตไฟก4Gๆ‰‹ๆœบ ๅ›ฝๅ†…่กŒ่ดง ่‹นๆžœXๆ‰‹ๆœบ</p> <p className="priceinfo"> <span className="curprice">ยฅ7958</span>&nbsp;&nbsp;<span className="mrkprice">ยฅ8388</span> </p> </a> </li> <li className="itm"> <a className="v-link" href="/product/1791096.html"> <img className="v-img u-lazyimg-loaded " src="https://haitao.nosdn1.127.net/efa4414b27f94f8d971cd85dc1a4983a1505287676238j7ipf0hj10752.jpg?imageView&amp;thumbnail=250x0&amp;quality=75&amp;type=webp" data-src="https://haitao.nosdn1.127.net/efa4414b27f94f8d971cd85dc1a4983a1505287676238j7ipf0hj10752.jpg?imageView&amp;thumbnail=250x0&amp;quality=75&amp;type=webp" /> <p className="subtit f-els-2">ใ€้ป‘ๅก96ๆŠ˜ใ€‘Apple ่‹นๆžœ iPhone8 Plus(A1864) 256GB็งปๅŠจ่”้€š็”ตไฟก4Gๆ‰‹ๆœบ ๅ›ฝๅ†…่กŒ่ดง</p> <p className="priceinfo"> <span className="curprice">ยฅ7288</span>&nbsp;&nbsp;<span className="mrkprice">ยฅ7919</span> </p> </a> </li> </ul> </div> </div> <p className="v-sperate"></p> </main> <article className="m-buybar f-safeArea" > <div className="n-btnwrap"> <a className="collect " style={styleh3}>ๆ”ถ่—</a> <a className="cart" onClick={this.t_car.bind(this)}>่ดญ็‰ฉ่ฝฆ<span className="count">0</span></a> <a href="javascript:;" className="btn btn-1" style={styleh3} onClick={this.sku_show.bind(this)}>ๅŠ ๅ…ฅ่ดญ็‰ฉ่ฝฆ</a> <a href="javascript:;" className="btn btn-2" style={styleh3} onClick={this.sku_show.bind(this)}>็ซ‹ๅณ่ดญไนฐ</a> </div> </article> <div className="success" style={this.state.pushshow}> <p className="push">ๅŠ ๅ…ฅ่ดญ็‰ฉ่ฝฆๆˆๅŠŸ</p> </div> <div className={`n-prdskubody ${this.state.skushow}`}> <h4 className="tit"> ๅ“็‰Œใ€ๅˆ†็ฑป <span className="v-closebtn" style={styleh3} onClick={this.sku_close.bind(this)}>&times;</span> </h4> <div className="prdbox"> <img className="v-img" src={this.state.mydetails.img} /> <div className="info"> <p className="price"> <span className="num">ยฅ{this.state.mydetails.sell}</span> <span className="promotiontag">็‰นไปท</span> </p> <p className="tips">่ฏท้€‰ๆ‹ฉ้ขœ่‰ฒ</p> </div> </div> <div className="cntbox"> <ul style={styhide}> <li className="itm"> <p className="propname"><span>ๅ“็‰Œ</span></p> <div className="propbox"> <a href="javascript:;" className="v-propbtn v-propbtn-1" >{this.state.mydetails.brand}</a> </div> </li> <li className="itm"> <p className="propname"><span>ๅˆ†็ฑป</span></p> <div className="propbox"> <a href="javascript:;" className={`v-propbtn ${this.state.propbtnred ? 'v-propbtn-1' : ''}`} onClick={this.changered.bind(this)}>{this.state.mydetails.type}</a> <a href="javascript:;" className={`v-propbtn ${this.state.btnred ? 'v-propbtn-1' : ''}`} onClick={this.removered.bind(this)}>{this.state.mydetails.classify}</a> </div> </li> <div className="n-numbox"> <p className="propname">ๆ•ฐ้‡</p> <div> <span className="ctrnum-wrap"> <span className="minus" onClick={this.reducenum.bind(this)}>-</span> <input type="text" className="qty" value={this.state.num} /> <span className="plus" onClick={this.addnum.bind(this)}>+</span> </span> <div className="tipwrap"> <p className="tip">ๅบ“ๅญ˜ๅ……่ถณ</p> </div> </div> </div> </ul> </div> <div className="n-btnwrap"> <a href="javascript:;" className={`btn btn-1 ${this.state.btncol ? 'btn-2' :''}`} style={styleh3} onClick={this.jiagou.bind(this)}>็กฎ่ฎค</a> </div> </div> <footer className="m-docfoot" data-pagename="product" id="pagedocfooter"> <div className="navlist f-cb" id="ft-statusbox"> <div className="m-ft-status"> <a className="toidx" href="#">้ฆ–้กต</a> <span className="sep">|</span> <a className="downloadapp" href="#">ๅฎขๆˆท็ซฏ</a> <span className="sep">|</span> <span className="nickname">ๆ‰‹ๆœบ็”จๆˆท2328</span> <span className="sep">|</span> <a className="tologout" href="#">้€€ๅ‡บ</a> </div> </div> <div id="ft-cpbox" data-kltime="1526266901738"> <div className="m-ft-copyright"> <p id="copyright" className="aboutnest">XXๅ…ฌๅธ็‰ˆๆƒๆ‰€ๆœ‰@1997-2018</p> </div> </div> </footer> </div> ) } } export default withRouter(Details);
'use strict'; var letter = "abcdefghijklmnopqrstuvwxyz"; function get_letter_com(num, result){ if(parseInt(num/26)){ var char = "" char += letter[parseInt(num/26)-1] + letter[num % 26]; result.push(char); }else{ result.push(letter[num]); } return result; } function get_letter_interval_2(number_a, number_b) { //ๅœจ่ฟ™้‡Œๅ†™ๅ…ฅไปฃ็  var result = []; if(number_a < number_b){ /*่ฟ™้‡Œ้œ€่ฆๆณจๆ„็š„ๆ˜ฏไผ ๅ…ฅ็š„ๅ‚ๆ•ฐ้œ€่ฆๅ‡ไธ€๏ผŒๅ› ไธบๆ•ฐ็ป„็š„็ดขๅผ•ๆ˜ฏ็”จ0ๅผ€ๅง‹็š„*/ for(var i = number_a; i <= number_b; i++){ result = get_letter_com(i-1, result); } }else if(number_a > number_b){ for(var i = number_a; i >= number_b; i--){ result = get_letter_com(i-1, result); } }else{ result = get_letter_com(number_a-1, result); } return result; } module.exports = get_letter_interval_2;
/** * @license Licensed under the Apache License, Version 2.0 (the "License"): * http://www.apache.org/licenses/LICENSE-2.0 */ /** * @fileoverview Blocks for Arduino Tone generation * The Arduino function syntax can be found at * https://www.arduino.cc/en/Reference/tone * */ 'use strict'; goog.provide('Blockly.Blocks.hackinvent'); goog.require('Blockly.Blocks'); goog.require('Blockly.Types'); /** Common HSV hue for all blocks in this category. */ Blockly.Blocks.hackinvent.HUE = 230; Blockly.Blocks['hi_led'] = { init: function() { this.appendValueInput('INTENSITY') .appendField(Blockly.Msg.HI_SETLED) .appendField(new Blockly.FieldDropdown( Blockly.Arduino.Boards.selected.pwmPins), 'LEDPIN') .appendField(Blockly.Msg.HI_SETINTENSITY) .setCheck(Blockly.Types.NUMBER.output); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour(Blockly.Blocks.hackinvent.HUE); this.setTooltip(Blockly.Msg.HI_SETLED_TIP); this.setHelpUrl('https://www.hackinvent.com/l/tinker-led.html'); }, /** @return {!string} The type of input value for the block, an integer. */ getBlockType: function() { return Blockly.Types.NUMBER; } }; Blockly.Blocks['hi_led_digi'] = { init: function() { this.appendValueInput('STATE') .appendField(Blockly.Msg.HI_SETLED) .appendField(new Blockly.FieldDropdown( Blockly.Arduino.Boards.selected.digitalPins), 'LEDPIN') .appendField(Blockly.Msg.HI_SETSTATE) .setCheck(Blockly.Types.BOOLEAN.checkList); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour(Blockly.Blocks.hackinvent.HUE); this.setTooltip(Blockly.Msg.HI_SETLED_TIP); this.setHelpUrl('https://www.hackinvent.com/l/tinker-led.html'); }, /** @return {!string} The type of input value for the block, an integer. */ getBlockType: function() { return Blockly.Types.NUMBER; } }; Blockly.Blocks['hi_rgbled'] = { init: function() { this.appendValueInput('REDVAL') .appendField(Blockly.Msg.HI_RGBLED) .appendField(Blockly.Msg.HI_SETRED) .appendField(new Blockly.FieldDropdown( Blockly.Arduino.Boards.selected.pwmPins), 'REDLEDPIN') .appendField(Blockly.Msg.HI_SETVAULE) .setCheck(Blockly.Types.NUMBER.output); this.appendValueInput('GREENVAL') .appendField(Blockly.Msg.HI_SETGREEN) .appendField(new Blockly.FieldDropdown( Blockly.Arduino.Boards.selected.pwmPins), 'GREENLEDPIN') .appendField(Blockly.Msg.HI_SETVAULE) .setCheck(Blockly.Types.NUMBER.output); this.appendValueInput('BLUEVAL') .appendField(Blockly.Msg.HI_SETBLUE) .appendField(new Blockly.FieldDropdown( Blockly.Arduino.Boards.selected.pwmPins), 'BLUELEDPIN') .appendField(Blockly.Msg.HI_SETVAULE) .setCheck(Blockly.Types.NUMBER.output); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour(Blockly.Blocks.hackinvent.HUE); this.setTooltip(Blockly.Msg.HI_SETLED_TIP); this.setHelpUrl('https://www.hackinvent.com/l/tinker-rgb-led.html'); }, /** @return {!string} The type of input value for the block, an integer. */ getBlockType: function() { return Blockly.Types.NUMBER; } }; Blockly.Blocks['hi_button'] = { init: function() { this.appendDummyInput() .appendField(Blockly.Msg.HI_BUTTON) .appendField(new Blockly.FieldDropdown( Blockly.Arduino.Boards.selected.digitalPins), 'PIN'); this.setOutput(true, Blockly.Types.BOOLEAN.output); this.setColour(Blockly.Blocks.hackinvent.HUE); this.setTooltip(Blockly.Msg.HI_BUTTON_TIP); this.setHelpUrl('https://www.hackinvent.com/l/tinker-button.html'); }, /** @return {!string} The type of input value for the block, an integer. */ getBlockType: function() { return Blockly.Types.NUMBER; } }; Blockly.Blocks['hi_potentiometer'] = { init: function() { this.appendDummyInput() .appendField(Blockly.Msg.HI_POTENTIOMETER) .appendField(new Blockly.FieldDropdown( Blockly.Arduino.Boards.selected.analogPins), 'PIN'); this.setOutput(true, Blockly.Types.NUMBER.output); this.setColour(Blockly.Blocks.hackinvent.HUE); this.setTooltip(Blockly.Msg.HI_BUTTON_TIP); this.setHelpUrl('https://www.hackinvent.com/l/tinker-button.html'); }, /** @return {!string} The type of input value for the block, an integer. */ getBlockType: function() { return Blockly.Types.NUMBER; } };
import React, { Component } from "react" import { logout } from "../../helpers/auth" export default class ForumNav extends Component { render() { return( <nav class="navbar navbar-expand-md navbar-light bg-light"> <a class="navbar-brand"><img src="../../../../icon.png" alt="Logo" style={{width: "50px"}}/></a> <a class="navbar-brand" style={{fontSize: "30px"}}>Forum</a> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a href="/forum" class="nav-link">Forum</a> </li> <li> <a href="/profile" class="nav-link">Profile</a> </li> <li> <a onClick={logout} class="nav-link">Log Out</a> </li> </ul> </nav> ) } }
import Grow from './Grow' import Fade from './Fade' import Slide from './Slide' export default { Grow, Fade, Slide, }
/** * Expanded Math Object */ // var myMath = Object.create(Math); // // myMath.randomInt = function (max, min = 0){ // return Math.floor(Math.random() * (max - min + 1) + min); // } // // console.log(myMath.randomInt(5)); // 3 for example // console.log(myMath.randomInt(10)); // 10 for example // console.log(myMath.random()); // 10 for example // console.log(myMath.round(0.5)); // console.log(myMath.randomInt(10, -4)); // -3 for example /** * Add reverse method to String object */ // String.prototype.reverse = function () { // return this.split("").reverse().join(""); // } // console.log('hello'.reverse()); /** * myEach */ // function myEach (arr, fn){ // let arrResult = []; // if (arr.constructor !== Array) throw "Is not an array"; // if (typeof fn !== "function") throw "Is not a function"; // for(let i = 0; i < arr.length; i++){ // if(typeof arr[i] !== "undefined"){ // let result = fn(arr[i], i, arr); // arrResult.push(result); // } // } // if (arguments[2] === true) return arrResult; // } // // function logArrayElements(element, index, array) { // //console.log("a[" + index + "] = " + element); // } // var arr = [2, 5, 9]; // var pe = myEach([2, 5, 9], logArrayElements); // var pe = arr.forEach(logArrayElements); // console.log(pe); // /** * myMap // */ // Array.prototype.myMap = function (fn){ // return myEach (this, fn, true); // } // function convertToUppercase (str) { // return str.toUpperCase(); // } // // var arrayTestMap = ["macarena", "pepe"]; // console.log(arrayTestMap.myMap(convertToUppercase)); // /** // * myFilter // */ // Array.prototype.myFilter = function (fn){ // let arrResult = []; // if (this.constructor !== Array) throw "Is not an array"; // if (typeof fn !== "function") throw "Is not a function"; // for(let i = 0; i < this.length; i++){ // if(typeof this[i] !== "undefined"){ // let result = fn(this[i], i, this); // if (result) arrResult.push(this[i]); // } // } // return arrResult // } // // function filterToCheck (num) { // return num > 8; // } // // var arrayTestFilter = [2,5,7,9,11]; // console.log(arrayTestFilter.myFilter(filterToCheck)); /** * Merge */ function merge (){ let objResult = {}; for (let i = 0; i < arguments.length; i++) { if (typeof arguments[i] !== "object") throw "Argument is not an object"; for (key in arguments[i]){ if (!objResult[key])objResult[key] = arguments[i][key]; } } return objResult; } console.log(merge({ a: 3, b: 2 }, { a: 2, c: 4 })); // { a: 3, b: 2, c: 4 } console.log(merge({ a: 3, b: 2 }, { a: 2, c: 4 }, { e: 8, c: 5})); // { a: 3, b: 2, c: 4, e: 8 } /** * invert */ // function invert () { // let objResult = {}; // for (let i = 0; i < arguments.length; i++) { // if (typeof arguments[i] !== "object") throw "Argument is not an object"; // for (key in arguments[i]){ // objResult[arguments[i][key]] = key; // } // } // return objResult; // } // // // console.log(invert({ a: 3, b: 2 })); // { 3: 'a', 2: 'b' }
angular.module('notebook', []) .controller('NotebookController', function ($scope, $location, Notebook) { $scope.allNotebooks = []; $scope.notebook = { title: '' }; $scope.useNotebook = function(notebook) { Notebook.currentNotebook = notebook; $location.url('/display-notes'); }; $scope.saveNotebook = function() { Notebook.saveNotebook($scope.notebook) .then(function(resp) { console.log(resp); Notebook.currentNotebook = resp.data; $location.url('/display-notes'); }) .catch(function(err) { console.error(err); }); }; $scope.getNotebooks = function() { Notebook.getNotebooks() .then(function(resp) { console.log(resp); $scope.allNotebooks = resp.data; }) .catch(function(err) { console.error(err); }); }; });
import { FlowRouter } from 'meteor/ostrio:flow-router-extra'; import './home.html'; Template.home.events({ 'click .js-logout'(event, instance) { Meteor.logout(); }, 'click .js-learn'(event, instance) { FlowRouter.go('/apprendre'); }, 'click .js-train'(event, instance) { FlowRouter.go('/entrainement'); }, });
import React, {Component,StyleSheet,Text,TouchableHighlight,View, Dimensions, TouchableOpacity} from 'react-native'; const hairlineWidth = StyleSheet.hairlineWidth; const window = Dimensions.get('window'); class TouchableButton extends TouchableHighlight { touchableGetHighlightDelayMS() { return 50; } } export default class NumericKeyPad extends Component { row1 = [1,2,3] row2 = [4,5,6] row3 = [7,8,9] row4 = ['<-', 0, 'Enter'] constructor(props) { super(props) this.handleEnter = this.props.onEnter this.handleOnChange = this.props.onChange this.numbers = [] console.log(`received ${this.props.value} having ${this.numbers}`) } onPress(key) { console.log(key) if(key == 'Enter') { this.handleEnter(this.numbers.join('')) } else { if(key == '<-') { this.numbers.pop() } else { if(this.numbers.length <= 5 ) this.numbers.push(key) } this.handleOnChange(this.numbers.join('')) } } renderKey(key) { return( <TouchableHighlight key={key} style={styles.touchable} underlayColor='darkgrey' onPress={this.onPress.bind(this, key)}> <Text style={styles.mainText}>{key}</Text> </TouchableHighlight> ) } renderRow(row) { return( <View style={styles.keyRow}> { row.map((num) => { return this.renderKey(num) }) } </View> ) } render() { // this.numbers = thus.props.value.split('') return( <View style={styles.container}> {this.renderRow(this.row1)} {this.renderRow(this.row2)} {this.renderRow(this.row3)} {this.renderRow(this.row4)} </View> ) } } var styles = StyleSheet.create({ container: { paddingBottom: 10, }, keyRow: { flexDirection: 'row', flex: 1, width: window.width - 100, alignSelf: 'center' }, touchable: { flex: 1, borderWidth: 1, margin: 2, backgroundColor: 'lightgrey', height: 40, alignItems: 'center', justifyContent: 'center', alignSelf: 'center' }, akey: { flex: 1, borderWidth: 1, margin: 2, backgroundColor: 'lightgrey', opacity: 1, height: 40, }, mainText: { fontWeight:'bold', }, })
var jsfac = (function (self) { var _utils = { isNullOrWhitespace: function (string) { return !string ? true : !/\S/.test(string); }, isString : function(obj){ return typeof obj !== typeof "string"; }, isUndefined: function(ob){ return typeof ob === 'undefined'; }, toArray: function(obj){ return Array.prototype.slice.apply(obj); }, extend: function(target, source){ target = target || {}; for(var p in source) { if(source.hasOwnProperty(p) && source[p]) { target[p] = source[p]; } } return target; }, forEach: function(obj, iterator) { if(_utils.isUndefined(obj.length)) { for(var key in obj) { if(obj.hasOwnProperty(key)) { iterator.call(null, obj[key], key); } } } else { if(Array.prototype.forEach) { Array.prototype.forEach.call(obj, iterator); } else { for(var i=0; i<obj.length; i++) { iterator.call(null, obj[i], i); } } } return obj; } }; // Scope has the ability to resolve a specified service // based on modules configured. var _scope = function (modules) { var sharedInstances = {}; var _fqsn = function (module, service) { return module.name + '-' + service; }; var _getOrCreate = function (name, registration, factory) { if (registration.options.sharingMode !== 'single') { return factory(); } if (!_utils.isUndefined(sharedInstances[name])) return sharedInstances[name]; sharedInstances[name] = factory(); return sharedInstances[name]; }; var _findRegistration = function (module, service) { var r = { module: module, match: module.find(service) }; for (var i in module.imports) { var imported = modules[module.imports[i]] || {}; var next = imported.find(service); if (!next) continue; if (r.match) throw 'An ambiguous resolution'; r.module = imported; r.match = next; } return r; }; var _buildLazy = function(module, service){ return function(){ return _resolveCore(module, service, {}); }; }; var _resolveCore = function (module, service, pending) { var ctx = _findRegistration(module, service); if (!ctx.match) return ctx.match; var fqsn = _fqsn(ctx.module, service); if (pending[fqsn]) throw 'Cyclic dependency detected.'; var r = ctx.match; if (r.dependencies.length == 0) return _getOrCreate(fqsn, r, r.implementation); pending[fqsn] = true; var deps = []; for (var dep in r.dependencies) { var d = r.dependencies[dep]; deps.push( d.lazy ? _buildLazy(ctx.module, d.name) : _resolveCore(ctx.module, d.name, pending)); } var service = _getOrCreate(fqsn, r, function () { return r.implementation.apply(null, deps); }); pending[fqsn] = false; return service; }; return { resolve: function (module, service) { var m = modules[module]; var root = m && m.find(service); if (!root) return root; return _resolveCore(m, service, {}); } }; }; var _dependencyDescriptions = function(dependencies){ var r = []; for(var d in dependencies){ var item = dependencies[d]; if(typeof item === 'string'){ r.push({ name: item, lazy: false }); } else{ if(!item.name) throw 'Dependency name is required'; r.push(item); } } return r; }; var _createModule = function (modName, imports, debug) { var _registry = {}; var _register = function (name, dependencies, implementation, options) { if (_utils.isString(name) || _utils.isNullOrWhitespace(name)) throw new Error('Valid name is required.'); if(!debug) { _registry[name] = { name: name, dependencies: _dependencyDescriptions(dependencies), implementation: implementation, options: options || {} }; } else { _registry[name] = { name: name, dependencies: _dependencyDescriptions(dependencies), implementation: function() { var deps = _utils.toArray(arguments); return { module:modName, name:name, deps:deps }; }, options: {} }; } }; return { name: modName, imports: imports, register: _register, find: function (service) { return _registry[service]; }, register: _register, registry : _registry }; }; var _debug = function() { var modules = {}; var rootScope = _scope(modules); return { resolve: function (module, service) { return rootScope.resolve(module, service); }, graph : function() { var r = []; _utils.forEach(modules, function(module){ _utils.forEach(module.registry, function(service){ r.push(rootScope.resolve(module.name, service.name)); }); }); return r; }, createModule : function(name, imports) { modules[name] = _createModule(name, imports, true); }, modules: modules }; }; var container = function () { var modules = {}; var rootScope = _scope(modules); var debug = _debug(); return { module: function (name, imports, initializer) { if (_utils.isNullOrWhitespace(name)) throw new Error('Valid name is required.'); if (_utils.isUndefined(imports) && _utils.isUndefined(initializer)) { return modules[name]; } var existing = modules[name]; if (!existing) { existing = modules[name] = _createModule(name, imports); debug.createModule(name, imports); } else { for (var i in imports) { if (existing.imports.indexOf(imports[i]) < 0) { existing.imports.push(imports[i]); } } } initializer(function(){ existing.register.apply(existing, arguments); debug.modules[name].register.apply(existing, arguments); }); return existing; }, resolve: function (module, service) { return rootScope.resolve(module, service); }, // Returns the actual definition of a service in the specified module. // Useful when writing tests or user needs manual control over construction. // No dependencies are resolved if you manually invoke value returned by this // function. def: function (module, name) { var module = modules[module] || _utils.undefined; var registration = module ? module.find(name) : module; return registration ? registration.implementation : registration; }, debug: { resolve: debug.resolve, graph : debug.graph } }; }; var c = container(); _utils.extend(self, c); self.container = container; return self; })(jsfac || {});
/* eslint-disable */ /* global angular */ /* global document */ /* global localStorage */ /* global introJs */ angular.module('mean.system') .controller('GameController', [ '$scope', 'game', 'dashboard', '$timeout', '$http', '$location', 'MakeAWishFactsService', '$firebaseArray', ($scope, game, dashboard, $timeout, $http, $location, MakeAWishFactsService, $firebaseArray) => { $scope.hasPickedCards = false; $scope.winningCardPicked = false; $scope.showTable = false; $scope.modalShown = false; $scope.gameLog = dashboard.getGameLog(); $scope.leaderGameLog = dashboard.leaderGameLog(); $scope.userDonations = dashboard.userDonations(); $scope.game = game; $scope.selectedUsers = []; $scope.invitedUsers = []; $scope.messages = ''; $scope.sendInviteButton = true; $scope.pickedCards = []; // $scope.invitesSent = []; $scope.invitedFriends = []; let makeAWishFacts = MakeAWishFactsService.getMakeAWishFacts(); $scope.makeAWishFact = makeAWishFacts.pop(); $scope.$watch('game.gameID', () => { if ($scope.game.gameID !== null) { // firebase reference const messagesRef = new Firebase(`https://isildur-cfh.firebaseio.com/message/${$scope.game.gameID}`);// eslint-disable-line // get messages as an array $scope.messagesArray = $firebaseArray(messagesRef); // notifications $scope.messagesArray.$watch((event) => { const newMessage = $scope.messagesArray.$getRecord(event.key); if (newMessage !== null) { if (newMessage.author !== game.players[game.playerIndex].username) { $scope.notificationCount = 1; } } }); } }); $scope.gameTour = introJs(); $scope.gameTour.setOptions({ steps: [{ intro: `Hey there! Welcome to the Cards for Humanity game, I'm sure you're as excited as I am. Let me show you around.` }, { element: '#question-container-outer', intro: `Game needs a minimum of 3 players and a maxium of 12 players to start. Wait for the minimum number of players and start the game.` }, { element: '#inner-info', intro: 'Here are the rules of the game.', }, { element: '.pull-right button', intro: 'Click here to invite your friends', }, { element: '.pull-left button', intro: 'When you\'re all set, click here to start the game.', }, { element: '#inner-timer-container', intro: `You have just 20 seconds to submit an awesome answer. Your time will appear here.` }, { element: '#player-container', intro: 'Players in the current game are shown here', }, { element: '.game-abandon', intro: `I don't know why you'd wanna, but you can click this button to quit the game` }, { element: '.take-tour', intro: `In case you wanna, you can click this button to retake my tour` }, { element: '#inner-info', intro: 'The submitted answers will show here', position: 'top' }, { element: '.chat', intro: 'Chat while the game is on here', position: 'top' }, { element: '.pull-left button', intro: 'When everyone is ready, click here to start the game', position: 'top' } ] }); $scope.takeTour = () => { if (!localStorage.takenTour) { const timeout = setTimeout(() => { $scope.gameTour.start(); clearTimeout(timeout); }, 500); localStorage.setItem('takenTour', true); } }; $scope.retakeTour = () => { localStorage.removeItem('takenTour'); $scope.takeTour(); }; $scope.pointerCursorStyle = () => { if ($scope.isCzar() && $scope.game.state === 'waiting for czar to decide') { return { cursor: 'pointer' }; } return {}; }; // send message $scope.sendMessage = (message) => { if (message.trim().length > 0) { $scope.messagesArray.$add({ gameId: $scope.game.gameID, messageContent: message.trim(), author: $scope.game.players[game.playerIndex].username }); } $scope.message = ''; }; $scope.pickCard = (card) => { if (!$scope.hasPickedCards) { if ($scope.pickedCards.indexOf(card.id) < 0) { $scope.pickedCards.push(card.id); if (game.curQuestion.numAnswers === 1) { $scope.sendPickedCards(); $scope.hasPickedCards = true; } else if (game.curQuestion.numAnswers === 2 && $scope.pickedCards.length === 2) { // delay and send $scope.hasPickedCards = true; $timeout($scope.sendPickedCards, 300); } } else { $scope.pickedCards.pop(); } } }; $scope.pointerCursorStyle = () => { if ($scope.isCzar() && $scope.game.state === 'waiting for czar to decide') { return { cursor: 'pointer' }; } return {}; }; $scope.sendPickedCards = () => { game.pickCards($scope.pickedCards); $scope.showTable = true; }; $scope.cardIsFirstSelected = (card) => { if (game.curQuestion.numAnswers > 1) { return card === $scope.pickedCards[0]; } return false; }; $scope.cardIsSecondSelected = (card) => { if (game.curQuestion.numAnswers > 1) { return card === $scope.pickedCards[1]; } return false; }; $scope.firstAnswer = ($index) => { if ($index % 2 === 0 && game.curQuestion.numAnswers > 1) { return true; } return false; }; $scope.secondAnswer = ($index) => { if ($index % 2 === 1 && game.curQuestion.numAnswers > 1) { return true; } return false; }; $scope.pickCard = (card) => { if (!$scope.hasPickedCards) { if ($scope.pickedCards.indexOf(card.id) < 0) { $scope.pickedCards.push(card.id); if (game.curQuestion.numAnswers === 1) { $scope.sendPickedCards(); $scope.hasPickedCards = true; } else if (game.curQuestion.numAnswers === 2 && $scope.pickedCards.length === 2) { // delay and send $scope.hasPickedCards = true; $timeout($scope.sendPickedCards, 300); } } else { $scope.pickedCards.pop(); } } }; $scope.pointerCursorStyle = () => { if ($scope.isCzar() && $scope.game.state === 'waiting for czar to decide') { return { cursor: 'pointer' }; } return {}; }; $scope.sendPickedCards = () => { game.pickCards($scope.pickedCards); $scope.showTable = true; }; $scope.cardIsFirstSelected = (card) => { if (game.curQuestion.numAnswers > 1) { return card === $scope.pickedCards[0]; } return false; }; $scope.showFirst = card => game.curQuestion.numAnswers > 1 && $scope.pickedCards[0] === card.id; $scope.showSecond = card => game.curQuestion.numAnswers > 1 && $scope.pickedCards[1] === card.id; $scope.isCzar = () => game.czar === game.playerIndex; $scope.isPlayer = $index => $index === game.playerIndex; $scope.isCustomGame = () => !(/^\d+$/).test(game.gameID) && game.state === 'awaiting players'; $scope.isPremium = $index => game.players[$index].premium; $scope.currentCzar = $index => $index === game.czar; $scope.winningColor = ($index) => { if (game.winningCardPlayer !== 1 && $index === game.winningCard) { return $scope.colors[game.players[game.winningCardPlayer].color]; } return '#f9f9f9'; }; $scope.pickWinning = (winningSet) => { if ($scope.isCzar()) { game.pickWinning(winningSet.card[0]); $scope.winningCardPicked = true; } }; $scope.winnerPicked = () => game.winningCard !== 1; $scope.startGame = () => { game.startGame(); }; // Search Users and Send Invite const invitesSent = []; /** * * @param {*} email * @return {*} promise * send Invite method api call */ const sendInvite = email => new Promise((resolve, reject) => { const userEmail = email; const gameUrl = encodeURIComponent(window.location.href); const postData = { userEmail, gameUrl }; $http.post('/api/users/sendInvitation', postData) .success((response) => { if (invitesSent.indexOf(response) <= -1) { invitesSent.push(response); } resolve({ message: 'Invitation Links has been sent via Email', invitesSent }); }) .error((error) => { reject({ message: 'Oops, Could not send Email Invitations', error }); }); }); $scope.sendInvites = (email) => { sendInvite(email) .then((response) => { console.log(response); // $scope.messages = response.message; if (invitesSent.length >= 11) { $scope.message = 'Heyya! Maximum number of players invited'; $scope.sendInviteButton = false; } }) .catch((error) => { $scope.messages = error; }); }; /** * * @param {*} userName * @return {*} promise * Search User Method api call */ const searchUsers = userName => new Promise((resolve, reject) => { $http.get(`api/users/search?name=${userName}`) .success((response) => { const gameUsers = response; resolve(gameUsers); }) .error((error) => { reject(error); }); }); $scope.searchedUsers = () => { const username = $scope.userName; if ($scope.userName === undefined) { $scope.message = 'Please enter a name'; } else { searchUsers(username) .then((foundUsers) => { $scope.foundUsers = foundUsers; }); } }; // ==========End of Search Users and Send Invite========= const getUsers = () => new Promise((resolve, reject) => { $http.get('api/users/getUsers') .success((response) => { console.log(response); const allUsers = response; resolve(allUsers); }) .error((error) => { reject(error); }); }); $scope.getAllUsers = () => { getUsers() .then((allUsers) => { $scope.allUsers = allUsers; }); }; // Add user as friend and Get FriendsList // $scope.addUserAsFriend = (user) => { // }; // ==========End of add user as friend=============== $scope.abandonGame = () => { game.leaveGame(); $location.path('/'); }; $scope.shuffleCards = () => { const card = $(`#${event.target.id}`); //eslint-disable-line card.addClass('animated flipOutY'); setTimeout(() => { $scope.startNextRound(); card.removeClass('animated flipOutY'); $('#start-modal').modal('hide'); //eslint-disable-line }, 500); }; $scope.startNextRound = () => { if ($scope.isCzar()) { game.startNextRound(); } }; // Catches changes to round to update when no players pick card // (because game.state remains the same) $scope.$watch('game.round', () => { $scope.hasPickedCards = false; $scope.showTable = false; $scope.winningCardPicked = false; $scope.makeAWishFact = makeAWishFacts.pop(); if (!makeAWishFacts.length) { makeAWishFacts = MakeAWishFactsService.getMakeAWishFacts(); } $scope.pickedCards = []; }); $scope.winnerPicked = () => game.winningCard !== 1; $scope.startGame = () => { game.startGame(); }; $scope.abandonGame = () => { game.leaveGame(); $location.path('/'); }; // Catches changes to round to update when no players pick card // (because game.state remains the same) $scope.$watch('game.round', () => { $scope.hasPickedCards = false; $scope.showTable = false; $scope.winningCardPicked = false; $scope.makeAWishFact = makeAWishFacts.pop(); if (!makeAWishFacts.length) { makeAWishFacts = MakeAWishFactsService.getMakeAWishFacts(); } $scope.pickedCards = []; }); $scope.retractChat = () => { const chatHead = document.querySelector('.chat-header'); const chat = document.querySelector('.chat'); chatHead.addEventListener('click', () => { chat.classList.toggle('retract-chat'); }); }; $scope.scrollTop = () => { const chatMsg = document.querySelector('.chat-message'); chatMsg.scrollTop = chatMsg.scrollHeight; }; // In case player doesn't pick a card in time, show the table $scope.$watch('game.state', () => { if (game.state === 'waiting for czar to decide' && $scope.showTable === false) { $scope.showTable = true; } if ( $scope.isCzar() && game.state === 'czar pick card' && game.table.length === 0 ) { $('#start-modal').modal('show'); //eslint-disable-line } if (game.state === 'game dissolved') { $('#start-modal').modal('hide'); //eslint-disable-line } if ($scope.isCzar() === false && game.state === 'czar pick card' && game.state !== 'game dissolved' && game.state !== 'awaiting players' && game.table.length === 0) { $scope.czarHasDrawn = 'Wait! Czar is drawing Card'; } if (game.state !== 'czar pick card' && game.state !== 'awaiting players' && game.state !== 'game dissolve') { $scope.czarHasDrawn = ''; } }); $scope.$watch('game.gameID', () => { if (game.gameID && game.state === 'awaiting players') { if (!$scope.isCustomGame() && $location.search().game) { // If the player didn't successfully enter the request room, // reset the URL so they don't think they're in the requested room. $location.search({}); } else if ($scope.isCustomGame() && !$location.search().game) { // Once the game ID is set, update the URL // if this is a game with friends, // where the link is meant to be shared. $location.search({ game: game.gameID }); if (!$scope.modalShown) { setTimeout(() => { const link = document.URL; const txt = `Give the following link to your friends so they can join your game: `; $('#lobby-how-to-play').text(txt); //eslint-disable-line $('#oh-el').css({ //eslint-disable-line 'text-align': 'center', 'font-size': '22px', background: 'white', color: 'black' }).text(link); }, 200); $scope.modalShown = true; } } } }); if ($location.search().game && !(/^\d+$/).test( $location.search().game)) { game.joinGame( 'joinGame', $location.search().game, null, localStorage.getItem('region')); // add region in localstorage } else if ($location.search().custom) { game.joinGame('joinGame', null, true, localStorage.getItem('region')); } else { game.joinGame(null, null, null, localStorage.getItem('region')); } }]);
export default class EventEmitter { constructor() { this.eventListStore = {}; } getEventInfo(eventName) { const [event, ...rest] = eventName.split(':'); const id = rest.join(':'); return [event, id]; } on(eventInfo, cb) { const [event, id] = this.getEventInfo(eventInfo); const eventStore = this.eventListStore[event]; if (!eventStore) { this.eventListStore[event] = {}; } this.eventListStore[event][id] = cb; } emit(event, data) { if (this.eventListStore[event]) { Object.values(this.eventListStore[event]).forEach((cb) => cb(data)); } } }
import React from 'react'; import { InView } from 'react-intersection-observer'; const Hobby = (props) => { const { id, desc, img, alt, value } = props.properties; let counter = (active, e) => { if (active) { const currentHobby = document.getElementById(e); const hobbyValue = currentHobby.value; let currentValue = 0; let intervalTime = 200; if (hobbyValue > 100) intervalTime = 20; else if (hobbyValue < 100 && hobbyValue > 10) intervalTime = 30; else intervalTime = 200; let count = () => { const checkCounter = () => { if (currentValue < hobbyValue) currentValue++; currentHobby.textContent = currentValue; if (currentValue < hobbyValue) { if (currentValue <= 1) { count = setInterval(count, intervalTime) } } else { clearInterval(count) } } checkCounter(); } count(); active = false; } } return ( <div className="stats"> <div className="statImg"> <img src={img} alt={alt} /> </div> <InView as="button" className="number" id={id} onChange={(inView) => counter(inView, id)} triggerOnce={true} threshold={.9} value={value} disabled>0</InView> <p className="hobby">{desc}</p> </div> ) } export default Hobby;
export let one = 1; let two = 2; export {two}; //ััƒั‰ะฝะพัั‚ัŒ ั‡ะตะณะพ ั‚ะพ ัะบัะฟะพั€ั‚ะธั€ัƒะตั‚ัั ะฒ ัะบะพะฑะบะฐั… export default function sayHi(){ //default - ัะบัะฟะพั€ั‚ ะฟะพ ัƒะผะพะปั‡ะฐะฝะธัŽ console.log("hello"); }
var vm = Backbone.ViewManager = {}; vm.Core = (function() { var _regions = {}; return { // register a region // name: a unique name for this region // selector: a DOM selector for this region addRegion: function(name, selector) { _regions[name] = { el: $(selector) }; }, // render a new view in a region // region: the name of the region // newView: the Backbone view object to render swap: function(region, newView) { region = _regions[region]; if (!region) { return false; } // if a current view exists in region, unset and remove it if (region.view) { region.view.unsetView(); region.view.unset(); } // set the new view as current for the region region.view = newView; // render the new view into the region region.el.empty().html(newView.render().el); } }; })(); // a simple Base view vm.BaseView = Backbone.View.extend({ templateData: {}, // to render the template on the view, just add a 'template' // variable to it which is the ID of the template on the page // // NOTE: this is only a demo for simple views. write your own // render() method in your view if you have special requirements render: function() { if (this.template) { var template = _.template($(this.template).html()); $(this.el).html(template(this.templateData)); } return this; }, // clean up before removing the view unset: function() { // turn off all bindings on the view this.off(); // remove self from the page this.remove(); }, // NOTE: override this in a view to run any custom code before unset() // eg. turning off extra bindings unsetView: function() { // ... } });
import React from "react"; import { shallow, mount } from "enzyme"; import GuessCount from "./guess-count"; describe("Render Guess Count", () => { it("renders Guess Count", () => { shallow(<GuessCount />); }); it('renders guess count plural', () => { const wrapper = shallow(<GuessCount guessCount={3} />); expect(wrapper.html()).toContain('guesses'); }); });
// test 27 function filterArray(numbers, value) { // ะŸะธัˆะธ ะบะพะด ะฝะธะถะต ัั‚ะพะน ัั‚ั€ะพะบะธ const filteredNumbers = []; for (const num of numbers) { const number = num; if (number > value) { filteredNumbers.push(number); } } return filteredNumbers; } console.log(filterArray([1, 2, 3, 4, 5], 3)); console.log(filterArray([1, 2, 3, 4, 5], 4)); console.log(filterArray([1, 2, 3, 4, 5], 5)); console.log(filterArray([12, 24, 8, 41, 76], 38)); console.log(filterArray([12, 24, 8, 41, 76], 20)); // test28 const a = 3 % 3; const b = 4 % 3; const c = 11 % 4; const d = 12 % 7; const e = 8 % 6; // ะ—ะฝะฐั‡ะตะฝะธะต ะฟะตั€ะตะผะตะฝะฝะพะน a ัั‚ะพ ั‡ะธัะปะพ 0 // ะ—ะฝะฐั‡ะตะฝะธะต ะฟะตั€ะตะผะตะฝะฝะพะน b ัั‚ะพ ั‡ะธัะปะพ 1 // ะ—ะฝะฐั‡ะตะฝะธะต ะฟะตั€ะตะผะตะฝะฝะพะน c ัั‚ะพ ั‡ะธัะปะพ 3 // ะ—ะฝะฐั‡ะตะฝะธะต ะฟะตั€ะตะผะตะฝะฝะพะน d ัั‚ะพ ั‡ะธัะปะพ 5 // ะ—ะฝะฐั‡ะตะฝะธะต ะฟะตั€ะตะผะตะฝะฝะพะน e ัั‚ะพ ั‡ะธัะปะพ 2 // test29 const getEvenNumbers = function (start, end) { // ะŸะธัˆะธ ะบะพะด ะฝะธะถะต ัั‚ะพะน ัั‚ั€ะพะบะธ const arr = []; for (let i = start; i <= end; i += 1) { if (i % 2 === 0) { arr.push(i); } } return arr; }; console.log(getEvenNumbers(2, 5)); console.log(getEvenNumbers(3, 11)); console.log(getEvenNumbers(6, 12)); console.log(getEvenNumbers(8, 8)); console.log(getEvenNumbers(7, 7)); // ะะฐะฟะธัˆะธ ั„ัƒะฝะบั†ะธัŽ getEvenNumbers(start, end) ะบะพั‚ะพั€ะฐั ะฒะพะทะฒั€ะฐั‰ะฐะตั‚ ะผะฐััะธะฒ ะฒัะตั… ั‡ั‘ั‚ะฝั‹ั… ั‡ะธัะตะป ะพั‚ start ะดะพ end. // test31 function findNumber(start, end, divisor) { // ะŸะธัˆะธ ะบะพะด ะฝะธะถะต ัั‚ะพะน ัั‚ั€ะพะบะธ let number; for (let i = start; i < end; i += 1) { if (i % divisor === 0) { return i; } } } findNumber(2, 6, 5); findNumber(8, 17, 3); findNumber(6, 9, 4); findNumber(16, 35, 7); // ะ’ั‹ะฟะพะปะฝะธ ั€ะตั„ะฐะบั‚ะพั€ะธะฝะณ ั„ัƒะฝะบั†ะธะธ findNumber(start, end, divisor) ั‚ะฐะบ, ั‡ั‚ะพะฑั‹ ะพะฝะฐ: // ะฒะพะทะฒั€ะฐั‰ะฐะปะฐ ะฟะตั€ะฒะพะต ั‡ะธัะปะพ ะพั‚ start ะดะพ end, ะบะพั‚ะพั€ะพะต ะดะตะปะธั‚ัั ะฝะฐ divisor ะฑะตะท ะพัั‚ะฐั‚ะบะฐ; // ะฝะต ะธัะฟะพะปัŒะทะพะฒะฐะปะฐ ะพะฟะตั€ะฐั‚ะพั€ break; // ะฝะต ะธัะฟะพะปัŒะทะพะฒะฐะปะฐ ะฟะตั€ะตะผะตะฝะฝัƒัŽ number.
// ๅค„็†ๅˆ—่กจๅŠ ่ฝฝๆ›ดๅคšๅ’Œๅˆทๆ–ฐ /** * * @param {*Object} params // ๅ‚ๆ•ฐ * @param {*Object} respone // ๆŽฅๅฃ่ฟ”ๅ›žๆ•ฐๆฎ * @param {*Arrary} prevData // ๅทฒ็ป่Žทๅ–็š„ๆ•ฐๆฎ */ export function handleListLoadMore(params, respone, prevData) { let _data; if (params.page === 1) { _data = respone ? respone.data : []; } else { _data = respone ? [...prevData.data, ...respone.data] : prevData.data; } const _total = params.page === 1 ? (respone) ? respone.total : 0 : prevData.total; const hasMore = respone ? _total !== _data.length : false; return { data: _data, params: { page: params.page, limit: params.limit, refreshing: false, hasMore, total: _total, }, }; } /** * ่Žทๅ–ๅคบๅฅ–ๆดพๅฏนๆ•ฐๆฎ * @param {Object} params ่ฏทๆฑ‚ๅ‚ๆ•ฐ * @param {Number} nowStatusIndex ๅฝ“ๅ‰ๅˆ†็ฑป็ดขๅผ• * @param {Object} respone ๆœๅŠกๅ™จๅ“ๅบ”ๆ•ฐๆฎ * @param {Objecg} prevData ๅทฒ็ป่Žทๅ–็š„ๆ•ฐๆฎ ็”จไฝœloadMore็ดฏๅŠ  */ export function handleStatusListLoadMore(params, nowStatusIndex, respone, prevData) { const _prevCategoryData = prevData[nowStatusIndex] ? prevData[nowStatusIndex] : []; let _data; if (params.page === 1) { _data = respone ? respone.data : []; } else { _data = respone ? [..._prevCategoryData.data, ...respone.data] : _prevCategoryData.data; } const _total = params.page === 1 ? (respone) ? respone.total : 0 : prevData.total; const hasMore = respone ? _total !== _data.length : false; prevData[nowStatusIndex] = { data: _data, params: { page: params.page, limit: params.limit, refreshing: false, hasMore, total: _total, }, }; return prevData; }
import React from "react"; import styled from "styled-components"; export const Filter = ({ filter, setFilter, currentPage, setCurrentPage }) => { return ( <> <Wrapper> <Button onClick={() => currentPage === 1 ? alert("Already at the beginning!") : setCurrentPage(currentPage - 1) } > Prev </Button> <Input value={filter} onChange={e => setFilter(e.target.value)} type="text" placeholder="filter list" ></Input> <Button onClick={() => setCurrentPage(currentPage + 1)}>Next</Button> </Wrapper> </> ); }; const Button = styled.button` border: none; background-color: #2f3136; color: #bbb; border-radius: 3px; padding: 1rem 2rem; &:hover { cursor: pointer; background-color: white; color: black; } `; const Wrapper = styled.div` display: flex; flex-wrap: wrap; align-items: center; justify-content: space-around; padding: 0 2rem; margin: 2rem 0 1rem 0; @media (max-width: 500px) { justify-content: space-between; } `; const Input = styled.input` background: #2f3136; border: none; padding: 5px; font-family: "IBM Plex Mono"; color: white; width: 24%; &::placeholder { color: #bbb; } @media (max-width: 1200px) { width: 50%; } @media (max-width: 500px) { width: 97.5%; margin: 1rem 0; order: 1; } `;
import React, { Component } from 'react'; import axios from 'axios'; class ReviewComponent extends Component{ constructor(){ super(); this.state={ Reviews:null } } componentDidMount(){ const { resID }=this.props.location.state; const URL='https://developers.zomato.com/api/v2.1/reviews?res_id='+resID; axios({ url:URL, method:"GET", headers:{ "user-key":"3a8321b70f68f4d7c9072aaa947c87e3", "Accept":"application/json" } }).then(response=>{ console.log(response); this.setState({ Reviews:response.data }) }).catch(error=>{ console.log(error); }); } render(){ if(this.state.Reviews){ return( <div className='container'> { this.state.Reviews.user_reviews.map(r=>{ return( <div className="container" key={r.review.id}> <div className="row"> <div className="col s12"> <div className="card horizontal"> <div className="card-image"> <img src="https://img.icons8.com/bubbles/50/000000/user.png"/> </div> <div className="card-stacked"> <div className="card-content"> <h3>{r.review.user.name}</h3> <p className="flow-text">{r.review.review_text}</p> </div> <div className="card-action"> <a className="btn-floating btn-large waves-effect waves-light green">{r.review.rating}</a> </div> </div> </div> </div> </div> </div> ) }) } </div> ) }else{ return( <div> <h2>No Reviews available</h2> </div> ) } } } export default ReviewComponent;
import React, { PureComponent } from "react"; import { expect } from "chai"; import { render, cleanIt, jsdom } from "reshow-unit"; jsdom(null, { url: "http://localhost" }); import { AjaxPage, ajaxDispatch } from "organism-react-ajax"; import urlStore from "../stores/urlStore"; describe("Test Handle New Url", () => { after(() => { ajaxDispatch({ onUrlChange: null }); cleanIt(); }); it("test history back", (done) => { const myUpdate = () => { expect(true).to.be.true; done(); }; ajaxDispatch({ onUrlChange: myUpdate }); render( <AjaxPage win={window} themes={{ fake: <div /> }} themePath="fake" /> ); window.history.pushState(null, "title", "http://localhost/bbb"); window.history.pushState(null, "title", "http://localhost/ccc"); setTimeout(() => window.history.back()); }); });
import { REHYDRATE } from 'redux-persist/constants'; import * as types from 'kitsu/store/types'; function updateObjectInArray(array, entry) { return array.map((currentItem) => { if (currentItem.id !== entry.id) { return currentItem; } return { ...currentItem, ...entry, }; }); } function removeObjectFromArray(array, entry) { return array.filter(currentItem => currentItem.id !== entry.id); } const userLibraryInitial = { anime: { completed: { data: [], loading: false }, current: { data: [], loading: false }, dropped: { data: [], loading: false }, on_hold: { data: [], loading: false }, planned: { data: [], loading: false }, }, manga: { completed: { data: [], loading: false }, current: { data: [], loading: false }, dropped: { data: [], loading: false }, on_hold: { data: [], loading: false }, planned: { data: [], loading: false }, }, }; const INITIAL_STATE = { profile: {}, favoritesLoading: {}, networkLoading: {}, character: {}, manga: {}, anime: {}, library: {}, userLibrary: { ...userLibraryInitial, loading: false, }, userLibrarySearch: { ...userLibraryInitial, loading: false, searchTerm: '', }, followed: {}, follower: {}, errorFav: {}, loading: false, error: '', signingUp: false, signupError: {}, }; export const profileReducer = (state = INITIAL_STATE, action) => { switch (action.type) { case types.FETCH_USER: return { ...state, loading: true, error: '', }; case types.FETCH_USER_SUCCESS: return { ...state, loading: false, profile: { ...state.profile, [action.payload.id]: action.payload, }, error: '', }; case types.FETCH_USER_FAIL: return { ...state, loading: false, error: action.payload, }; case types.FETCH_USER_FEED: return { ...state, loadingLibrary: true, library: {}, error: '', }; case types.FETCH_USER_FEED_SUCCESS: return { ...state, loadingLibrary: false, library: { [action.payload.userId]: action.payload.entries }, error: '', }; case types.FETCH_USER_FEED_FAIL: return { ...state, loadingLibrary: false, error: action.payload, }; case types.FETCH_USER_LIBRARY: return { ...state, userLibrary: { ...userLibraryInitial, loading: true, userId: action.userId, }, }; case types.FETCH_USER_LIBRARY_SUCCESS: return { ...state, userLibrary: { ...state.userLibrary, loading: false, }, }; case types.FETCH_USER_LIBRARY_FAIL: return { ...state, userLibrary: { ...state.userLibrary, loading: false, }, }; case types.FETCH_USER_LIBRARY_TYPE: return { ...state, userLibrary: { ...state.userLibrary, [action.library]: { ...state.userLibrary[action.library], [action.status]: { ...state.userLibrary[action.library][action.status], loading: true, }, }, }, }; case types.FETCH_USER_LIBRARY_TYPE_SUCCESS: return { ...state, userLibrary: { ...state.userLibrary, [action.library]: { ...state.userLibrary[action.library], [action.status]: { data: action.data, fetchMore: action.fetchMore, meta: action.data.meta, loading: false, }, }, }, }; case types.FETCH_USER_LIBRARY_TYPE_FAIL: return { ...state, userLibrary: { ...state.userLibrary, [action.library]: { ...state.userLibrary[action.library], [action.status]: { ...state.userLibrary[action.library][action.status], loading: false, }, }, }, }; case types.UPDATE_USER_LIBRARY_ENTRY: if (action.previousLibraryStatus !== action.newLibraryStatus) { return { ...state, userLibrary: { ...state.userLibrary, [action.libraryType]: { ...state.userLibrary[action.libraryType], // remove from previousLibraryEntry.status [action.previousLibraryStatus]: { ...state.userLibrary[action.libraryType][action.previousLibraryStatus], data: removeObjectFromArray( state.userLibrary[action.libraryType][action.previousLibraryStatus].data, action.newLibraryEntry, ), }, // add to newLibraryEntry.status [action.newLibraryStatus]: { ...state.userLibrary[action.libraryType][action.newLibraryStatus], data: [ { ...action.previousLibraryEntry, ...action.newLibraryEntry }, ...state.userLibrary[action.libraryType][action.newLibraryStatus].data, ], }, }, }, }; } return { ...state, userLibrary: { ...state.userLibrary, [action.libraryType]: { ...state.userLibrary[action.libraryType], [action.libraryStatus]: { ...state.userLibrary[action.libraryType][action.libraryStatus], data: updateObjectInArray( state.userLibrary[action.libraryType][action.libraryStatus].data, action.newLibraryEntry, ), }, }, }, }; case types.SEARCH_USER_LIBRARY: return { ...state, userLibrarySearch: { ...userLibraryInitial, loading: true, searchTerm: action.searchTerm, userId: action.userId, }, }; case types.SEARCH_USER_LIBRARY_SUCCESS: return { ...state, userLibrarySearch: { ...state.userLibrarySearch, loading: false, }, }; case types.SEARCH_USER_LIBRARY_FAIL: return { ...state, userLibrarySearch: { ...state.userLibrarySearch, loading: false, }, }; case types.SEARCH_USER_LIBRARY_TYPE: return { ...state, userLibrarySearch: { ...state.userLibrarySearch, [action.library]: { ...state.userLibrarySearch[action.library], [action.status]: { ...state.userLibrarySearch[action.library][action.status], loading: true, }, }, searchTerm: action.searchTerm, }, }; case types.SEARCH_USER_LIBRARY_TYPE_SUCCESS: return { ...state, userLibrarySearch: { ...state.userLibrarySearch, [action.library]: { ...state.userLibrarySearch[action.library], [action.status]: { data: action.data, fetchMore: action.fetchMore, meta: action.data.meta, loading: false, }, }, }, }; case types.SEARCH_USER_LIBRARY_TYPE_FAIL: return { ...state, userLibrarySearch: { ...state.userLibrarySearch, [action.library]: { ...state.userLibrarySearch[action.library], [action.status]: { ...state.userLibrarySearch[action.library][action.status], loading: false, }, }, }, }; case types.UPDATE_USER_LIBRARY_SEARCH_ENTRY: if (action.previousLibraryStatus !== action.newLibraryStatus) { return { ...state, userLibrarySearch: { ...state.userLibrarySearch, [action.libraryType]: { ...state.userLibrarySearch[action.libraryType], // remove from previousLibraryEntry.status [action.previousLibraryStatus]: { ...state.userLibrarySearch[action.libraryType][action.previousLibraryStatus], data: removeObjectFromArray( state.userLibrarySearch[action.libraryType][action.previousLibraryStatus].data, action.newLibraryEntry, ), }, // add to newLibraryEntry.status (newLibraryStatus alias on_hold to on_hold for us) [action.newLibraryStatus]: { ...state.userLibrarySearch[action.libraryType][action.newLibraryStatus], data: [ { ...action.previousLibraryEntry, ...action.newLibraryEntry }, ...state.userLibrarySearch[action.libraryType][action.newLibraryStatus].data, ], }, }, }, }; } return { ...state, userLibrarySearch: { ...state.userLibrarySearch, [action.libraryType]: { ...state.userLibrarySearch[action.libraryType], [action.libraryStatus]: { ...state.userLibrarySearch[action.libraryType][action.libraryStatus], data: updateObjectInArray( state.userLibrarySearch[action.libraryType][action.libraryStatus].data, action.newLibraryEntry, ), }, }, }, }; case types.DELETE_USER_LIBRARY_ENTRY: return { ...state, userLibrary: { ...state.userLibrary, [action.libraryType]: { ...state.userLibrary[action.libraryType], [action.libraryStatus]: { ...state.userLibrary[action.libraryType][action.libraryStatus], data: state.userLibrary[action.libraryType][action.libraryStatus].data .filter(entry => entry.id !== action.id), }, }, }, userLibrarySearch: { ...state.userLibrarySearch, [action.libraryType]: { ...state.userLibrarySearch[action.libraryType], [action.libraryStatus]: { ...state.userLibrarySearch[action.libraryType][action.libraryStatus], data: state.userLibrarySearch[action.libraryType][action.libraryStatus].data .filter(entry => entry.id !== action.id), }, }, }, }; case types.UPDATE_USER_LIBRARY_SEARCH_TERM: return { ...state, userLibrarySearch: { ...state.userLibrarySearch, searchTerm: action.searchTerm, }, }; case types.FETCH_USER_FAVORITES: return { ...state, favoritesLoading: { ...state.favoritesLoading, [action.payload.type]: true, }, errorFav: { ...state.errorFav, [action.payload.type]: '', }, }; case types.FETCH_USER_FAVORITES_SUCCESS: return { ...state, favoritesLoading: { ...state.favoritesLoading, [action.payload.type]: false, }, [action.payload.type]: { [action.payload.userId]: action.payload.favorites, }, errorFav: { ...state.errorFav, [action.payload.type]: '', }, }; case types.FETCH_USER_NETWORK: return { ...state, networkLoading: { ...state.networkLoading, [action.payload.type]: true, }, errorNetwork: { ...state.errorNetwork, [action.payload.type]: '', }, }; case types.FETCH_USER_NETWORK_SUCCESS: return { ...state, networkLoading: { ...state.networkLoading, [action.payload.type]: false, }, [action.payload.type]: { [action.payload.userId]: action.payload.network, }, errorNetwork: { ...state.errorNetwork, [action.payload.type]: '', }, }; case types.FETCH_USER_NETWORK_FAIL: return { ...state, networkLoading: { ...state.networkLoading, [action.payload.type]: false, }, errorNetwork: { ...state.errorNetwork, [action.payload.type]: action.payload.error, }, }; case types.FETCH_USER_FAVORITES_FAIL: return { ...state, favoritesLoading: { ...state.favoritesLoading, [action.payload.type]: false, }, errorFav: { ...state.errorFav, [action.payload.type]: action.payload.error, }, }; case types.CREATE_USER: return { ...state, signingUp: true, signupError: {}, }; case types.CREATE_USER_SUCCESS: return { ...state, signingUp: false, profile: action.payload, signupError: {}, }; case types.CREATE_USER_FAIL: return { ...state, signingUp: false, signupError: action.payload, }; case types.LOGOUT_USER: return INITIAL_STATE; case REHYDRATE: return { ...state, ...action.payload.user, signingIn: false, signingUp: false, signupError: {}, rehydratedAt: new Date(), }; default: return state; } };
let year = (new Date()).getFullYear(); if(year != 2019) $("#year").html("- "+year);
/** * ๅ…จๅฑ€ๅŠจ็”ป้…็ฝฎ * @author: terry <jfengsky@gmail.com> * @date: 2013-10-21 10:47 */ define(function(require, exports, module) { var $ = require('jquery'); require('jquery-easing'); function Move(id, obj, fn){ $(id).animate(obj, 100, 'swing', fn); }; module.exports = Move; });
var spawn = require('child_process').spawn var env = process.env.NODE_ENV === 'production' ? 'prod' : 'dev' console.log('> run node in ' + env) spawn('npm', ['run', env], { stdio: 'inherit' })
var express = require('express'); var router = express.Router(); var db = require('../db/queries'); const { loginRequired } = require("../auth/helpers"); /*------------------------------GET Request------------------------------------*/ router.get('/logout', loginRequired, db.logoutUser); router.get('/sortedconceptsbylikes', db.sortedconceptsbylikes); router.get('/', loginRequired, db.getUser); router.get('/profile/:user_id', db.getSingleUser); router.get('/profile/skills/:user_id', db.getSingleUserSkills); router.get('/userlikes/:user_id', db.getAllUserLikes); router.get('/singleconcept/:concept_id', db.getSingleConcept); router.get('/isfavorite/:concept_id', loginRequired, db.isFavorite); router.get('/conceptskills/:concept_id', loginRequired, db.getSingleConceptSkills); router.get('/comment/:concept_id', db.getConceptComments); router.get('/getsinglecomment/:comment_id', loginRequired, db.getSingleComment); router.get('/seenComments/:user_id', loginRequired, db.getSeenForCommentsByUserId); router.get('/seenLikes/:user_id', loginRequired, db.getSeenForLikesByUserId); router.get('/userconcept/:user_id', loginRequired, db.getUserConcept); router.get('/accountOwnerPoints', loginRequired, db.getAccountOwnerPoints); router.get('/allconcepts', loginRequired, db.getAllConcepts); router.get('/user_skills', loginRequired, db.getUserSkills); router.get('/seenCommentsByConcept_id/:concept_id', loginRequired, db.seenCommentsByConcept_id); /*------------------------------POST Request------------------------------------*/ router.post('/login', db.loginUser); router.post('/register', db.registerUser); router.post('/addPoints', db.addPoints); router.post('/addSkills', db.addSkills); router.post('/createconcept', db.createConcept); router.post('/conceptskills/:concept_id', loginRequired, db.conceptSkills); router.post('/favorite', loginRequired, db.favoriteConcept); router.post('/unfavorite', loginRequired, db.unfavoriteConcept); router.post('/addComment', loginRequired, db.addConceptComment); /*------------------------------PATCH Request------------------------------------*/ router.patch('/editComment/:comment_id', loginRequired, db.editConceptComment); router.patch('/deleteConceptSkills', loginRequired, db.deleteConceptSkills); router.patch('/deleteComments', loginRequired, db.deleteComments); router.patch('/deleteLikes', loginRequired, db.deleteLikes); router.patch('/deleteConcept', loginRequired, db.deleteConcept); router.patch('/editconcept/:concept_id', loginRequired, db.editConcept); router.patch('/editconceptskills/:concept_id', loginRequired, db.editConceptSkills); router.patch('/seenCommentsChangeByConceptId/:concept_id', loginRequired, db.seenCommentsChangeByConceptId); router.patch('/seenLikesChangeByUserId/:user_id', loginRequired, db.seenLikesChangeByUserId); module.exports = router;
import React, { useEffect, useState } from 'react'; import formatCurrency from '../helper/currency'; import Fade from 'react-reveal/Fade'; import { connect } from "react-redux"; import { removeFromCart } from "../actions/productActions"; function Cart(CartData) { const [proceed, setProceed] = useState(false); useEffect(() => { // console.log(CartData) }, []) const funProceed = () => { setProceed(true); } return ( <> <br /><br /><br /> <ul class="collection"> {CartData.CartData && CartData.CartData.map((item, index) => { return <Fade left cascade> <li key={index} class="collection-item avatar"> <div class="col s12 m12 "> <div class="card-panel grey lighten-5 z-depth-1"> <div class="row valign-wrapper"> <div class="col s2"> <img style={{ maxWidth: 30, paddingTop: '1rem' }} src={item.image} alt="" class="circle" /> </div> <div class="col s10"> <span class="black-text"> Title {item.title} </span> </div> </div> </div> <div class="row valign-wrapper "> <div class="col s2 offset-m1"> <a class="btn-floating btn-small waves-effect waves-light red" onClick={() => { CartData.removeFromCart(CartData.CartData, item._id) }}> <i class="material-icons"> clear </i> </a> </div> <div class="col s10"> <span class="black-text"> <p>Price {formatCurrency(item.price)} * {item.count} = {formatCurrency(item.price * (item.count))}<br /> </p> </span> </div> </div> </div> </li> </Fade> }) } </ul> Total : { CartData.CartData && formatCurrency(CartData.CartData.reduce((a, c) => a + c.price * c.count, 0)) } <br /> { CartData.CartData && <button onClick={funProceed}> Proceed </button> } {proceed && <div class="row"> <Fade right cascade> <form class="col s12"> <div class="row"> <div class="input-field col s12"> <input id="email" type="email" class="validate" /> <label for="email">Email</label> </div> </div> <div class="row"> <div class="input-field col s12"> <input id="password" type="password" class="validate" /> <label for="password">Password</label> </div> </div> <div class="row"> <div class="input-field col s12"> <input id="Address" type="text" class="validate" /> <label for="Address">Address</label> </div> </div> <div class="row"> <div class="input-field col s12"> <input type="submit" value="Submit" /> </div> </div> </form> </Fade> </div> } </> ); } export default connect((state) => ({ CartData: state.products.cartItems }), { removeFromCart })(Cart);
/* global navigator */ (function () { // eslint-disable-line wrap-iife,func-names if (typeof navigator.serviceWorker !== 'undefined') { navigator.serviceWorker.register('js/sw.js'); } })();
'use strict'; var dragula = require('dragula'); /*jshint unused: false*/ function register (angular) { return ['dragulaService', function angularDragula (dragulaService) { return { restrict: 'A', scope: { dragulaScope: '=', dragulaModel: '=' }, link: link }; function link (scope, elem, attrs) { var dragulaScope = scope.dragulaScope || scope.$parent; var container = elem[0]; var name = scope.$eval(attrs.dragula); var drake; var bag = dragulaService.find(dragulaScope, name); if (bag) { drake = bag.drake; drake.containers.push(container); } else { drake = dragula({ containers: [container] }); dragulaService.add(dragulaScope, name, drake); } scope.$on('$destroy', function() { var containerIndex = drake.containers.indexOf(container); if (containerIndex >= 0) { drake.containers.splice(containerIndex, 1); if (drake.models && drake.models[containerIndex]) { drake.models.splice(containerIndex, 1); } } }); scope.$watch('dragulaModel', function (newValue, oldValue) { if (!newValue) { return; } if (drake.models) { var modelIndex = oldValue ? drake.models.indexOf(oldValue) : -1; if (modelIndex >= 0) { drake.models.splice(modelIndex, 1, newValue); } else { drake.models.push(newValue); } } else { drake.models = [newValue]; } dragulaService.handleModels(dragulaScope, drake); }); } }]; } module.exports = register;
module.exports = function (channel, queueName) { channel.prefetch(1); channel.assertQueue(queueName, {durable: false}).then(function (ok) { console.log(' [*] Waiting for requests..'); channel.consume(queueName, function (message) { var result = "HELLOOOOOOOO " + message.content.toString(); console.log('[.] got a request! processing!', result); channel.sendToQueue(message.properties.replyTo, new Buffer(result), {correlationId: message.properties.correlationId}); channel.ack(message); }, {noAck: false}); }); }
import sendgrid from '@sendgrid/mail' try { sendgrid.setApiKey(process.env.SENDGRID_API_KEY) } catch (error) { console.log(error) } const emailService = () => ({ sendMail: async (to, subject, name) => { return sendgrid.send({ to, from: 'vieiraneto88@gmail.com', templateId: process.env.TMPL_ID, dynamicTemplateData: { subject, username: name, company: 'NodeStore' } }) } }) export default emailService()
import React, { useState } from "react"; import "antd/dist/antd.css"; import "../css/LectureMenu.css"; import { Menu } from "antd"; import { Link } from "react-router-dom"; import { firebaseApp } from "./Firebase"; const setShow = (number) => { var isShow; firebaseApp .database() .ref("Lecture/Inform/Lecture" + number + "/isShow") .on("value", function (snapshot) { if (snapshot.exists) { isShow = snapshot.val(); } }); if (isShow) { return false; } else { return true; } }; const LectureMenu = () => { const [count, setCount] = useState( 0 + "ngร y " + 0 + "giแป " + 0 + "phรบt " + 0 + "giรขy " ); var x = setInterval(function () { var countDownDate = new Date("Jan 5, 2030 15:37:25").getTime(); // Get today's date and time var now = new Date().getTime(); // Find the distance between now and the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor( (distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60) ); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Display the result in the element setCount( days + "ngร y " + hours + "giแป " + minutes + "phรบt " + seconds + "giรขy " ); }, 100); const handleClick = (e) => { if (localStorage.getItem("emailID") !== null) { localStorage.setItem("Lecture", e.key); firebaseApp .database() .ref( "Lecture/" + localStorage.getItem("emailID") + "/Lecture" + localStorage.getItem("Lecture") ) .set({ isRead: true, }); } }; const setColor = (key) => { var isRead; firebaseApp .database() .ref( "Lecture/" + localStorage.getItem("emailID") + "/Lecture" + key + "/isRead" ) .on("value", function (snapshot) { if (snapshot.exists) { isRead = snapshot.val(); } }); if (isRead) { return "blue"; } else { return null; } }; return ( <div className="LectureMenu"> <p hidden>{count}</p> <div id="lectureMenu"> <Menu onClick={handleClick} style={{ width: "360px" }} mode="inline"> <h4>Tร i liแป‡u C</h4> <Menu.Item key="1" hidden={setShow(1)}> <Link style={{ color: setColor(1) }} to="/studyc/lecture"> Chฦฐฦกng 1: Giแป›i thiแป‡u </Link> </Menu.Item> <Menu.Item key="2" hidden={setShow(2)}> <Link style={{ color: setColor(2) }} to="/studyc/lecture"> Chฦฐฦกng 2: Kiแปƒu dแปฏ liแป‡u cฦก sแปŸ vร  cรกc phรฉp toรกn </Link> </Menu.Item> <Menu.Item key="3" hidden={setShow(3)}> <Link style={{ color: setColor(3) }} to="/studyc/lecture"> Chฦฐฦกng 3: Cแบฅu trรบc ฤ‘iแปu khiแปƒn </Link> </Menu.Item> <Menu.Item key="4" hidden={setShow(4)}> <Link style={{ color: setColor(4) }} to="/studyc/lecture"> Chฦฐฦกng 4: Con trแป vร  hร m </Link> </Menu.Item> <Menu.Item key="5" hidden={setShow(5)}> <Link style={{ color: setColor(5) }} to="/studyc/lecture"> Chฦฐฦกng 5: Mแบฃng dแปฏ liแป‡u </Link> </Menu.Item> <Menu.Item key="6" hidden={setShow(6)}> <Link style={{ color: setColor(6) }} to="/studyc/lecture"> Chฦฐฦกng 6: Chuแป—i </Link> </Menu.Item> <Menu.Item key="7" hidden={setShow(7)}> <Link style={{ color: setColor(7) }} to="/studyc/lecture"> Chฦฐฦกng 7: Kiแปƒu dแปฏ liแป‡u cแบฅu trรบc </Link> </Menu.Item> <Menu.Item key="8" hidden={setShow(8)}> <Link style={{ color: setColor(8) }} to="/studyc/lecture"> Chฦฐฦกng 8: Kiแปƒu tแบญp tin </Link> </Menu.Item> <Menu.Item key="9" hidden={setShow(9)}> <Link style={{ color: setColor(9) }} to="/studyc/lecture"> Chฦฐฦกng 9: Kแปน thuแบญt duyแป‡t mแบฃng sแปญ dแปฅng con trแป </Link> </Menu.Item> <Menu.Item key="10" hidden={setShow(10)}> <Link style={{ color: setColor(10) }} to="/studyc/lecture"> Chฦฐฦกng 10: Bแป™ nhแป› ฤ‘แป™ng vร  แปฉng dแปฅng trong DSLK </Link> </Menu.Item> </Menu> </div> </div> ); }; export default LectureMenu;
const sqlite3 = require('sqlite3').verbose(); /** * Get scan of next level one. Async mode. * @param {string} dir - Project directory * @param {number} minrt - minimum retention time * @param {number} maxrt - maximum retention time * @param {number} minmz - minimum m/z * @param {number} maxmz - maximum m/z * @param {function} callback - Callback function that handles query results * @returns {function} Callback function * @async */ function loadMzrtData(dir, minrt, maxrt, minmz, maxmz, callback) { let sql = `SELECT * FROM feature WHERE NOT (rt_low >= ? OR rt_high <= ? OR mz_low >= ? OR mz_high <= ?) LIMIT 500;`; let dbDir = dir; let resultDb = new sqlite3.Database(dbDir, (err) => { if (err) { console.error("error during db generation", err.message); } // console.log('Connected to the result database.'); }); resultDb.all(sql, [maxrt, minrt, maxmz, minmz], (err, row) => { if (err) { console.error(err.message); } return callback(null, row); }); resultDb.close(); } module.exports = loadMzrtData;
// // LLamadas a la API // // const URLAPI = "https://ctd-todo-api.herokuapp.com/v1"; const usuarios = { // // metodo crear un nuevo usuario // @param String nombre // @param String apellido // @param String correo // @param String contrasenna // @return Promise // registrar: (nombre, apellido, correo, contrasenna) => { return new Promise((resolve, reject) => { fetch(`${URLAPI}/users`, { method: "POST", headers: { "Content-Type": "application/json", }, body: `{"firstName":"${nombre}","lastName":"${apellido}","email":"${correo}","password":"${contrasenna}"}`, }) .then((response) => response.json()) .then((response) => { // cuerpo formateado if (response.jwt) { // si recibo el token localStorage.setItem("jwt", response.jwt); window.location.href = "mis-tareas.html"; } else { // si recibo algun otro tipo de error resolve(response); } }) .catch((err) => reject("Fallo la aplicacion, lo sentimos.")); // si el servidor no esta disponible }); }, // // metodo para validar un usuario // @param String correo // @param String contrasenna // @return Promise // login: (correo, contrasenna) => { return new Promise((resolve, reject) => { fetch(`${URLAPI}/users/login`, { method: "POST", headers: { "Content-Type": "application/json", }, body: `{"email":"${correo}","password":"${contrasenna}"}`, }) .then((response) => response.json()) .then((response) => { // cuerpo formateado if (response.jwt) { // si recibo el token localStorage.setItem("jwt", response.jwt); window.location.href = "mis-tareas.html"; } else { // si recibo algun otro tipo de error resolve(response); } }) .catch((err) => reject("Fallo la aplicacion, lo sentimos.")); // si el servidor no esta disponible }); }, // // metodo para obtener los datos de un usuario desde su jwt // @return Promise // obtenerDatos: () => { return new Promise((resolve, reject) => { let jwt = localStorage.getItem("jwt"); fetch(`${URLAPI}/users/getMe`, { method: "GET", headers: { Authorization: jwt, }, }) .then((response) => response.json()) .then((response) => { if (typeof response === "object") { resolve(response); } else { reject(response); } }) .catch((err) => { alert("Fallo la aplicacion, lo sentimos."); // si el servidor no esta disponible }); }); }, }; const tareas = { // // metodo para agregar una nueva tarea // @param Object description // @return Promise // agregar: (descripcion) => { // Agrega una nueva tarea return new Promise((resolve, reject) => { fetch(`${URLAPI}/tasks`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: localStorage.getItem("jwt"), }, body: `{"description":"${descripcion}","completed":false}`, }) .then((response) => response.json()) .then((response) => { // si la tarea se creo correctamente if (typeof response === "object") { resolve(response); } else { // si la aplicacion devuelve otro status code reject(response); } }) .catch((err) => { alert("Fallo la aplicacion, lo sentimos."); // si el servidor no esta disponible }); }); }, // // metodo para listar todas las tareas // @return Promise // listado: () => { return new Promise((resolve, reject) => { fetch(`${URLAPI}/tasks`, { method: "GET", headers: { Authorization: localStorage.getItem("jwt"), }, }) .then((response) => response.json()) .then((response) => { // si trajo todas las tareas if (typeof response === "object") { resolve(response); } else { // si la aplicacion devuelve otro status code reject(response); } }) .catch((err) => { alert("Fallo la aplicacion, lo sentimos."); // si el servidor no esta disponible }); }); }, // // metodo para completar una tarea // @param String idTarea // @return Promise // completar: (idTarea) => { return new Promise((resolve, reject) => { fetch(`${URLAPI}/tasks/${idTarea}`, { method: "PUT", headers: { Authorization: localStorage.getItem("jwt"), "Content-Type": "application/json", }, body: '{"completed": true}', }) .then((response) => response.json()) .then((response) => { // si se actualizo correctamente if (typeof response === "object") { resolve(response); } else { // si la aplicacion devuelve otro status code reject(response); } }) .catch((err) => { alert("Fallo la aplicacion, lo sentimos."); // si el servidor no esta disponible }); }); }, // // metodo para pasar una tarea que esta completa a pendiente // @param String idTarea // @return Promise // descompletar: (idTarea) => { return new Promise((resolve, reject) => { fetch(`${URLAPI}/tasks/${idTarea}`, { method: "PUT", headers: { Authorization: localStorage.getItem("jwt"), "Content-Type": "application/json", }, body: '{"completed": false}', }) .then((response) => response.json()) .then((response) => { // si se actualizo correctamente if (typeof response === "object") { resolve(response); } else { // si la aplicacion devuelve otro status code reject(response); } }) .catch((err) => { alert("Fallo la aplicacion, lo sentimos."); // si el servidor no esta disponible }); }); }, // // metodo para eliminar una tarea // @param String idTarea // @return Promise // eliminar: (idTarea) => { return new Promise((resolve, reject) => { fetch(`${URLAPI}/tasks/${idTarea}`, { method: "DELETE", headers: { Authorization: localStorage.getItem("jwt"), "Content-Type": "application/json", }, }) .then((response) => { // Si la api respinde con el codido 200 // no hago response.json() por que no necesito el cuerpo if (response.status === 200) { resolve("ok"); } else { // si no sale bien el borrar una tarea, quiero obtener el mensaje de error response.json(); } }) .then((response) => { // envio el mensaje de error al usuario reject(response); }) .catch((err) => { alert("Fallo la aplicacion, lo sentimos."); // si el servidor no esta disponible }); }); }, };
let x = 10; function text() { console.log(x); } global.num=x; global.f=text;
import styled from 'styled-components/native'; export const Container = styled.SafeAreaView` flex: 1; padding: 30px; `; export const Content = styled.View` border: 1px solid #ddd; border-radius: 4px; `; export const Question = styled.View` padding: 20px; flex-direction: row; flex-wrap: wrap; `; export const Awnser = styled.View` padding: 0 20px 20px; flex-direction: row; flex-wrap: wrap; justify-content: space-between; `; export const Title = styled.Text` color: #444; font-weight: bold; font-size: 14px; flex-basis: 50%; `; export const InfoDate = styled.Text` color: #666; flex-basis: 50%; font-size: 14px; text-align: right; `; export const Text = styled.Text` color: #666; font-size: 14px; line-height: 26px; margin-top: 16px; flex-basis: 100%; `;
const jwt = require('jsonwebtoken'); const { constants } = require("../helpers/constants"); const apiResponse = require('../helpers/apiResponses'); const authenticateJWT = (req, res, next) => { const authHeader = req.headers.authorization; if (authHeader) { const token = authHeader.split(' ')[1]; jwt.verify(token, constants.accessTokenSecret, (err, user) => { if (err) { return apiResponse.unauthorizedResponse(res, "Invalid credentials"); } // if token is valid then add user details into req and continue req.user = user; next(); }); } else { return apiResponse.unauthorizedResponse(res, "Invalid credentials"); } }; module.exports = authenticateJWT;
'use strict'; angular.module('userAuth', []) .constant('USER_ROLES', { user : 'user', admin : 'admin' }) .factory('JWTInterceptor', [ '$window', function ($window) { return { request : function (config) { config.headers = config.headers || {}; if ($window.sessionStorage.token) { config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token; } return config; } }; } ]) .factory('AuthService', [ '$http', '$window', function ($http, $window) { var _user = null; var _userRoles = {}; return { getRoles : function () { return $http .get('/api/users/roles') .then(function (res) { _userRoles = res.data; }); }, userRoles : function () { return _userRoles; }, signin : function (credentials) { return $http .post('/api/users/signin', credentials) .then( function (res) { $window.sessionStorage.token = res.data.token; _user = res.data.user; return { success : true }; }, function (res) { return { success : false, message : res.data.message }; } ); }, tryRemoteAuth : function () { return $http .get('/api/users/whoami') .then( function (res) { _user = res.data; return true; }, function (res) { _user = null; return false; } ); }, signout : function () { delete $window.sessionStorage.token; _user = null; }, currentUser : function () { return _user; }, isAuthenticated : function () { return _user !== null; }, isAuthorized : function (authorizedRoles) { if (this.isAuthenticated()) { for (var i = 0; i < _user.roles.length; i++) { if (authorizedRoles.indexOf(_user.roles[i]) > -1) { return true; } } } return false; } }; } ]) ;
/*! * More Math JS <https://github.com/smujmaiku/moremath-js> * Copyright(c) 2016-2019 Michael Szmadzinski * MIT Licensed */ const objEntries = obj => Object.keys(obj).map(k => [k, obj[k]]); /** * Evalulates for valid numbers * @param {*} val * @returns {boolean} */ function isNumber(val) { return typeof val === 'number' && !isNaN(val) && isFinite(val); } /** * Processes all nested numbers * @param {*} list * @param {Function?} fn * @returns {*} */ function all(list, fn = v => v) { if (typeof list === 'number') { return fn(list); } if (list instanceof Array) { return list.map(v => all(v, fn)); } if (list instanceof Object) { return objEntries(list) .map(([k, v]) => [k, all(v, fn)]) .reduce((o, [k, v]) => Object.assign(o, { [k]: v }), {}); } return NaN; } /** * Limit value between two endpoints * @param {number} val * @param {number} low * @param {number} high * @returns {number} */ function limit(val, low = 0, high = 1) { return Math.min(Math.max(val, low), high); } /** * Limit values and wrap overflows * @param {number} val * @param {number?} low * @param {number?} high * @param {boolean} inclusiveHigh * @returns {number} */ function limitWrap(val, low = 0, high = 1, inclusiveHigh = false) { const range = high - low; const temp = low + ((val - low) % range); if (inclusiveHigh && val >= high && temp === low) return high; return temp < low ? temp + range : temp; } /** * Rounds value to an exponent * @param {number} val * @param {number?} exp * @returns {number} */ function round(val, exp = 0) { const rounded = Math.round(val / Math.pow(10, exp)) * Math.pow(10, exp); if (rounded === 0) return 0; return rounded; } /** * Rounds all nested numbers to an exponent * @param {*} list * @param {number?} exp * @returns {*} */ function roundAll(list, exp = 0) { return all(list, v => round(v, exp)); } /** * Sums all numbers between Arrays * @param {Array} a * @param {Array} b * @returns {Array} */ function addVectors(a, b) { return a.map((v, i) => v + b[i]); } /** * Subtract all numbers between Arrays * @param {Array} a * @param {Array} b * @returns {Array} */ function subtractVectors(a, b) { return a.map((v, i) => v - b[i]); } /** * Get vector distance * @param {Array} target * @param {Array?} origin * @returns {number} */ function getVectorDistance(target, origin = undefined) { if (origin) return getVectorDistance(subtractVectors(target, origin)); return target.reduce((t, v) => Math.sqrt(t * t + v * v), 0); } /** * Get maximun distance of a point * @param {Array} list * @param {Array?} origin * @returns {number} */ function getVectorDistanceLazy(target, origin = undefined) { if (origin) return getVectorDistanceLazy(subtractVectors(target, origin)); return target .map((v) => Math.abs(v)) .reduce((t, v) => Math.max(t, v), 0); } /** * Processes the direction of two endpoints * @param {number} a * @param {number} b * @returns {number} */ function getDirection(a, b) { if (a < b) return 1; if (b < a) return -1; return 0; } /** * fade between two endpoints * @param {number} a * @param {number} b * @param {number} t * @param {function?} easing */ function fade(a, b, t, easing = v => v) { return easing(t) * (b - a) + a; } /** * fade between two vectors * @param {number} a * @param {number} b * @param {number} t * @param {function?} easing */ function fadeVector(a, b, t, easing = v => v) { return a.map((v, i) => fade(v, b[i], t, easing)); } /** * Get a vector by distance between two vectors * @param {Array} origin * @param {Array} target * @param {number} distance * @param {function?} easing * @returns {Array} */ function fadeVectorByDistance(origin, target, distance, easing = v => v) { const actualDistance = getVectorDistance(subtractVectors(origin, target)); const ratio = distance / actualDistance; if (ratio <= 0) return origin; if (ratio >= 1) return target; return fadeVector(origin, target, ratio, easing); } /** * Get a vector by largest item distance between two vectors * @param {Array} origin * @param {Array} target * @param {number} distance * @param {function?} easing * @returns {Array} */ function fadeVectorByDistanceLazy(origin, target, distance, easing = v => v) { const lazyDistance = getVectorDistanceLazy(target, origin); const ratio = distance / lazyDistance; if (ratio <= 0) return origin; if (ratio >= 1) return target; return fadeVector(origin, target, ratio, easing); } /** * Processes percentage value is along two endpoints * @param {number} val * @param {number} a * @param {number} b */ function getFade(val, a, b) { if (val === a) return 0; if (val === b) return 1; return (val - a) / (b - a); } /** * Determines if a value is between two endpoints * @param {number} val * @param {number} a * @param {number} b */ function isBetween(val, a, b) { const progress = getFade(val, a, b); return progress >= 0 && progress <= 1; } /** * Converts Degrees to Radians * @param {number} degrees * @returns {number} */ function toRadians(degrees) { return degrees * Math.PI / 180; } /** * Converts Radians to Degrees * @param {number} radians * @returns {number} */ function toDegrees(radians) { return radians * 180 / Math.PI; } /** * Calculates magnitude of vector from origin * @param {Array} vector * @param {Array?} origin * @returns {number} */ function getMagnitude(vector, origin = undefined) { if (origin) { return getMagnitude(vector.map((v, i) => origin[i] - v)); } return Math.sqrt(vector.reduce((t, v) => t + Math.pow(v, 2), 0)); } /** * Adjusts vector to a specific magnitude * @param {Array} vector * @param {number?} magnitude * @returns {Array} */ function fixVectorMagnitude(vector, magnitude = 1) { const scale = magnitude / getMagnitude(vector); return vector.map(v => v * scale); } /** * Reduces a box inside a container * @param {Array} box * @param {Array} container * @param {Function?} reducer * @returns {Array} */ function containBox(box, container, reducer = Math.min) { if (container.length < 2) return container; const scales = container.map((v, i) => v / box[i]); const scale = scales.reduce((a, b) => reducer(a, b)); return box.map(v => v * scale); }; /** * Concats the following point to each point * @param {Array} poly * @returns {Array} */ function makeLinesFromPoly(poly) { return poly.map((v, i) => { if (i + 1 === poly.length) return v.concat(poly[0]); return v.concat(poly[i + 1]); }); } /** * Average list of values with weights * @param {Array} list * @param {Function?} reducer [value, weight] * @returns {Array} [average, sum] */ function averageWithWeight(list, reducer = ([v, w]) => ([v, w])) { const array = list.map(reducer); const sum = array.reduce((t, [v, w]) => t + v * w, 0); const count = array.reduce((t, [, w]) => t + w, 0); return [sum / count, sum]; } /** * Group list neighbors * @param {Array} list * @param {number?} limit * @param {Function?} reducer * @returns {Array(Array)} */ function groupNeighbors(list, limit = 1, reducer = v => v) { return list.reduce((res, value, index, array) => { if (index && Math.abs(reducer(value) - reducer(array[index - 1])) <= limit) { res[res.length - 1].push(value); } else { res.push([value]); } return res; }, []); }; exports = module.exports = { objEntries, isNumber, all, limit, limitWrap, round, roundAll, addVectors, subtractVectors, getVectorDistance, getVectorDistanceLazy, fadeVectorByDistance, fadeVectorByDistanceLazy, getDirection, fade, fadeVector, getFade, isBetween, toRadians, toDegrees, getMagnitude, fixVectorMagnitude, containBox, makeLinesFromPoly, averageWithWeight, groupNeighbors, };
import React, { Component } from 'react'; import { Map, GoogleApiWrapper, Marker, InfoWindow } from 'google-maps-react'; import './Map.css'; class GoogleMap extends Component { state = { activeMarker: this.props.activeMarker }; displayRestaurants = () => { if (this.props.restaurants) { return this.props.restaurants.map((rest, index) => { return <Marker key={index} id={rest.zomatoInfo.id} position={{ lat: rest.zomatoInfo.location.latitude, lng: rest.zomatoInfo.location.longitude }} rest={rest} onClick={this.selectRestaurant} title={rest.zomatoInfo.address} name={rest.zomatoInfo.name} /> }); } } selectRestaurant = (props, marker, e) => { this.props.selectRestaurant(props, marker, e); } onMapClicked = (props) => { if (this.props.showingInfoWindow) { this.props.onMapClicked(props); } } // render() { return ( <Map google={this.props.google} zoom={17} initialCenter = {this.props.position} center = {this.props.position} onClick={this.onMapClicked} > {this.displayRestaurants()} <InfoWindow marker={this.props.activeMarker} visible={this.props.showingInfoWindow}> <div> <h1>{this.props.selectedPlace.googleInfo.name}</h1> <p>Rating: {this.props.selectedPlace.averageRating} / 5</p> <p>{this.props.selectedPlace.zomatoInfo.location.address}</p> </div> </InfoWindow> </Map> ); } } export default GoogleApiWrapper({ apiKey: 'AIzaSyAjDXZHujgWXP2CP27sTJ3uy1J1BrFzEW4' }) (GoogleMap);
"use strict"; // Written by Mohammed Farghally and Cliff Shaffer $(document).ready(function () { var av = new JSAV("UFconcomCON", {"animationMode": "none"}); var gr = av.ds.graph({width: 500, height: 300, layout: "manual", directed: false}); var a = gr.addNode("A", {"left": 0, "top": 100}); var b = gr.addNode("B", {"left": 100, "top": 100}); var c = gr.addNode("C", {"left": 0, "top": 200}); var d = gr.addNode("D", {"left": 200, "top": 100}); var e = gr.addNode("E", {"left": 200, "top": 200}); var f = gr.addNode("F", {"left": 300, "top": 100}); var g = gr.addNode("G", {"left": 300, "top": 200}); var h = gr.addNode("H", {"left": 100, "top": 200}); var i = gr.addNode("I", {"left": 300, "top": 0}); var j = gr.addNode("J", {"left": 400, "top": 100}); gr.addEdge(a, c); gr.addEdge(a, b); gr.addEdge(a, h); gr.addEdge(c, h); gr.addEdge(b, h); gr.addEdge(h, e); gr.addEdge(d, e); gr.addEdge(d, f); gr.addEdge(e, g); gr.addEdge(e, f); gr.addEdge(f, g); gr.addEdge(f, i); gr.layout(); });
const User = require('../models/User'); const bcrypt = require('bcrypt'); function add(req, res) { let { username, email, message } = req.session; res.render('users/register', { title: 'Register User', message, username, email, }); } function getLogin(req, res) { let message = req.session.message; res.render('users/login', { title: 'Login', message }); req.session.message = null; } async function login(req, res) { try { req.session.message = null; let { email, password } = req.body; if (!email || !password) return res.redirect('/users/login'); let re = new RegExp(`^${email}$`, 'i'); user = await User.findOne({ email: re }); if (!user) { req.session.message = 'Invalid User Name or Password'; return res.redirect('/users/login'); } if (!(await bcrypt.compare(password, user.hashedPassword))) { req.session.message = 'Invalid User Name or Password'; return res.redirect('/users/login'); } req.session.user = user._id; let redirectURL = req.session.history[req.session.history.length - 2]; return res.redirect(redirectURL); } catch (err) { console.log(err); } } async function create(req, res) { try { req.session.message = null; let { username, email, password, passwordVerify } = req.body; req.session.username = username; req.session.email = email; if (!username || !password || !email || !passwordVerify) return res.redirect('/users/register'); if (password !== passwordVerify) { req.session.message = 'Passwords Do Not Match'; return res.redirect('/users/register'); } let re = new RegExp(`^${username}$`, 'i'); let user = await User.findOne({ username: re }); if (user) { req.session.message = 'Username Already Exists'; return res.redirect('/users/register'); } re = new RegExp(`^${email}$`, 'i'); user = await User.findOne({ email: re }); if (user) { req.session.message = 'Email Already Exists'; return res.redirect('/users/register'); } let hashedPassword = await bcrypt.hash(password, 10); user = new User({ username, email, hashedPassword }); await user.save(); req.session.username = ''; req.session.email = ''; return res.redirect('/users/login'); } catch (err) { console.log(err); } } function logout(req, res) { req.session.user = ''; res.redirect('/'); } module.exports = { add, create, getLogin, login, logout };
const mongoose = require('mongoose'); // const recipeSchema = mongoose.Schema({ // title: { // type: String, // required: true, // minLength: 5, // trim: true, // }, // description: { // type: String, // required: true, // minLength: 10, // trim: true, // }, // image: { // type: String, // }, // // body: { // // type: String, // // required: true, // // minLength: 20, // // }, // instructions: { // type: Array, // }, // creator: { // // type: mongoose.Schema.Types.ObjectId, // // ref: 'User', // type: String, // }, // creationDate: { // type: Date, // default: Date.now, // }, // ingredients: { // type: Array, // }, // category: { // type: String, // }, // tags: { // type: Array, // }, // }); const recipeSchema = mongoose.Schema({ editorData: { type: { time: { type: Number, required: true, }, blocks: { type: [Object], required: true, }, version: { type: String, required: true, }, }, }, creator: { id: { type: mongoose.Schema.Types.ObjectId, ref: 'User', }, username: String, }, header: { type: String, }, imageUrl: { type: String, }, summary: { type: String, }, lastEdited: { type: Date, }, }); const Recipe = mongoose.model('Recipe', recipeSchema); module.exports = Recipe;
module.exports = { extraction: (apiData) => { let result = []; for(var i = 0; i < apiData.length; i++) { let temp = {}; temp.code = apiData[i].data[0].code.split('-')[1]; temp.openingPrice = apiData[i].data[0].openingPrice; temp.highPrice = apiData[i].data[0].highPrice; temp.lowPrice = apiData[i].data[0].lowPrice; temp.tradePrice = apiData[i].data[0].tradePrice; result.push(temp); }; return result } };
(function () { 'use strict'; angular.module('category', ['cetegory-details']) .config(categoryConfig); /*@ngInject*/ function categoryConfig($stateProvider) { $stateProvider .state('category', { url: "/category", parent: 'page', views: { 'content@page': { templateUrl: 'main/category/category.tpl.html', controller: 'CategoryController as vm' } } }); } })();
angular.module('app.signin', ['app.services']) .controller('signinController', ['$scope', '$location', 'HttpRequests', function($scope, $location, Signin){ $scope.user = { talents: [] }; $scope.newTalent = {}; $scope.addTalent = function(){ if ( $scope.newTalent.talent !== "" && $scope.newTalent.level !== ""){ $scope.user.talents.push({ talent: $scope.newTalent.talent, level: $scope.newTalent.level }); $scope.newTalent.talent = ""; $scope.newTalent.level = ""; } else { // TODO: add a message that one of the forms is blank } }; $scope.signUp = function() { $scope.user.talents = convertTalentsToObject() console.log($scope.user); HttpRequests.signupUser($scope.user) // signupUser returns a promise .then(function(response){ console.log('user posted', response); $location.path('/'); // TODO: where should this lead to? }, function(err) { console.log('error posting user', err); }); }; var convertTalentsToObject = function() { var converted = {}; for (var i = 0; i < $scope.user.talents.length; i++){ converted[$scope.user.talents.talent] = $scope.user.talents.level; } return converted; }; }]);
import {StyleSheet} from 'react-native'; export default StyleSheet.create({ inputsWrapper: { marginVertical: 15, marginBottom: 45, }, footerWrapper: { height: 50, flex: 1, justifyContent: 'center', alignItems: 'center', }, });
import React, { useState } from 'react' import { deletePole } from '../../../store/ducks/poles/fetch-actions' import { Table } from 'react-bootstrap' import { useDispatch, useSelector } from 'react-redux' import { Button, Spinner } from 'react-bootstrap' import { Trash, PencilSquare } from 'react-bootstrap-icons' import { PropTypes } from 'prop-types' import './style.scss' import Pagination from '../../Pagination' export default function PolesTable({ openEditModal }) { const poles = useSelector(state => state.poles.items) const [page, setPage] = useState(1) const loading = useSelector(state => state.poles.loading) const dispatch = useDispatch() const perPage = 8 const totalPages = Math.ceil(poles.length / perPage) const tryDelete = id => { const confirmation = window.confirm( `Deseja realmente remover o poste ${id}?` ) if (!confirmation) return dispatch(deletePole(id)) if (filteredItems().length === 1 && page > 1) setPage(page - 1) } const filteredItems = () => { const startIndex = (page - 1) * perPage let items = [...poles] items = items.splice(startIndex, perPage) return items } return ( <div className="poles-table"> {loading ? ( <div className="poles-table__loading"> <Spinner animation="border" variant="primary" /> </div> ) : ( <> <Table hover responsive size="sm"> <thead> <tr> <th>ID</th> <th>Tipo</th> <th>Aรงรตes</th> </tr> </thead> <tbody> {filteredItems().map(pole => ( <tr key={pole.id}> <td>{pole.id}</td> <td>{pole.tipo}</td> <td> <Button onClick={() => openEditModal(pole)} className="mr-2" title="Editar" > <PencilSquare color="white" size={20} /> </Button> <Button onClick={() => tryDelete(pole.id)} variant="danger" title="Remover" > <Trash color="white" size={20} /> </Button> </td> </tr> ))} </tbody> </Table> {totalPages > 1 && ( <Pagination page={page} totalPages={totalPages} setPage={setPage} /> )} </> )} </div> ) } PolesTable.propTypes = { openEditModal: PropTypes.func }
import React, { Component } from 'react'; import { ScrollView, View, TouchableOpacity, Text } from 'react-native'; import { Tabs, Tab, Icon } from 'react-native-elements' export default class ScreenD extends Component { constructor() { super() this.state = { hideTabBar: false, } } hideTabBar(value) { this.setState({ hideTabBar: value }); } render() { let tabBarStyle = {}; let sceneStyle = {}; if (this.state.hideTabBar) { tabBarStyle.height = 0; sceneStyle.paddingBottom = 0; } console.log('Profile1'); return ( <Text hideTabBar={this.hideTabBar.bind(this)}>Profile1</Text> ) } }
function centerOf(string) { let halfLength = string.length / 2 if (parseInt(halfLength) === halfLength) { return string[halfLength - 1] + string[halfLength] } else { return string[Math.floor(halfLength)] } } console.log(centerOf('I Love JavaScript')); // "a" console.log(centerOf('Launch School')); // " " console.log(centerOf('Launch')); // "un" console.log(centerOf('Launchschool')); // "hs" console.log(centerOf('x')); // "x"
import { eventBus } from '../../../service/eventBus'; import { Utils } from '../../../helpers/Utils'; export class ViewTodo { constructor() { this.todoContainer = document.querySelector('.todo-container-js'); this.todoBtn = document.querySelector('.todo-btn-js'); this.todoList = document.querySelector('.todo-list-js'); this.doneList = document.querySelector('.done-list-js'); this.todoTitle = document.querySelector('.todo-title-js'); this.doneTitle = document.querySelector('.todo-title-done-js'); this.input = document.querySelector('.todo-input-js'); this.todoTab = document.querySelector('.tab-todo-js'); this.doneTab = document.querySelector('.tab-done-js'); } render(tasks) { let templateActive = ''; let templateDone = ''; this.todoTitle.textContent = tasks.todoTitle; this.doneTitle.textContent = tasks.doneTitle; this.input.setAttribute('placeholder', tasks.placeholder); if (!tasks.props.length) { return; } tasks.props.forEach(task => { if (task.isActive) { templateActive += this.getTaskTemplate( task.text, task.id, task.isActive ); } else { templateDone += this.getTaskTemplate(task.text, task.id, task.isActive); } }); this.todoList.innerHTML = templateActive; this.doneList.innerHTML = templateDone; } getTaskTemplate(text, id, isActive = true) { return `<li class="todo-item ${ isActive ? '' : 'todo-item-done' }" id="${id}"> <input class="todo-item-checkbox todo-item-checkbox-js" type="checkbox" name="todo" ${ isActive ? '' : 'checked disabled' }> <div class="todo-item-text todo-item-text-js"> <input class="todo-item-input todo-item-input-js" type="text" value="${text}" disabled> </div> <div class="btn-container btn-container-js"> ${ isActive ? '<button class="todo-edit-btn todo-edit-btn-js"></button>' : '' } <button class="todo-delete-btn todo-delete-btn-js"></button> </div> </li>`; } renderTask(args) { const [val, id] = args; this.todoList.insertAdjacentHTML( 'beforeend', this.getTaskTemplate(val, id, true) ); } setEvents() { this.todoBtn.addEventListener('click', () => { this.toggleContainer(); this.toggleBtn(); }); document.addEventListener('click', e => { if ( !e.target.classList.contains('todo-btn-js') && !e.target.closest('.todo-container-js') ) { this.closeContainer(); } }); this.todoTab.addEventListener('click', () => { this.doneTab.classList.remove('active'); this.todoTab.classList.add('active'); this.todoList.classList.remove('d-none'); this.doneList.classList.add('d-none'); this.input.removeAttribute('disabled'); }); this.doneTab.addEventListener('click', () => { this.todoTab.classList.remove('active'); this.doneTab.classList.add('active'); this.todoList.classList.add('d-none'); this.doneList.classList.remove('d-none'); this.input.setAttribute('disabled', ''); }); this.input.addEventListener('change', e => { const value = this.input.value; if (value) { const id = Utils.getId(); eventBus.post('add-todo', [value, id]); this.input.value = ''; } }); this.todoContainer.addEventListener('click', e => { e.stopPropagation(); if (e.target.classList.contains('todo-delete-btn-js')) { const id = e.target.closest('.todo-item').id; eventBus.post('remove-todo', id); } if (e.target.classList.contains('todo-edit-btn-js')) { const id = e.target.closest('.todo-item').id; eventBus.post('edit-todo', id); } if (e.target.classList.contains('todo-item-checkbox-js')) { const id = e.target.closest('.todo-item').id; eventBus.post('done-todo', id); } }); } removeTask(id) { document.getElementById(id).remove(); } editTask(id) { const taskItem = document.getElementById(id); const buttonsContainer = taskItem.querySelector('.btn-container-js'); const taskInput = taskItem.querySelector('.todo-item-input-js'); const originalValue = taskInput.value; buttonsContainer.classList.add('hidden'); taskInput.removeAttribute('disabled'); taskInput.scrollLeft = taskInput.scrollWidth; taskInput.setSelectionRange(taskInput.value.length, taskInput.value.length); taskInput.focus(); taskInput.addEventListener('change', () => { const value = taskInput.value; if (value !== originalValue) { eventBus.post('save-task-text', [value, id]); } buttonsContainer.classList.remove('hidden'); taskInput.blur(); }); } hideBlock() { this.todoContainer.classList.add('hidden'); this.todoBtn.classList.add('hidden'); } showBlock() { this.todoContainer.classList.remove('hidden'); this.todoBtn.classList.remove('hidden'); } toggleContainer() { this.todoContainer.classList.toggle('open'); this.todoContainer.classList.toggle('closed'); } toggleBtn() { this.todoBtn.classList.toggle('active-btn'); } closeContainer() { this.todoContainer.classList.remove('open'); this.todoContainer.classList.add('closed'); } }
const mongoose = require('mongoose'); const projectsSchema = new mongoose.Schema({ name: {type: String}, img: {type: String}, url: {type: String}, description: {type: String} }); const Projects = mongoose.model('Projects', projectsSchema); module.exports = Projects;
import BaseLfo from '../../core/BaseLfo'; import SourceMixin from '../../core/SourceMixin'; const AudioContext = window.AudioContext ||ย window.webkitAudioContext; const definitions = { frameSize: { type: 'integer', default: 512, constant: true, }, channel: { type: 'integer', default: 0, constant: true, }, sourceNode: { type: 'any', default: null, constant: true, }, audioContext: { type: 'any', default: null, constant: true, }, }; /** * Use a `WebAudio` node as a source for the graph. * * @param {Object} options - Override parameter' default values. * @param {AudioNode} [options.sourceNode=null] - Audio node to process * (mandatory). * @param {AudioContext} [options.audioContext=null] - Audio context used to * create the audio node (mandatory). * @param {Number} [options.frameSize=512] - Size of the output blocks, define * the `frameSize` in the `streamParams`. * @param {Number} [options.channel=0] - Number of the channel to process. * * @memberof module:client.source * * @example * import * as lfo from 'waves-lfo/client'; * * const audioContext = new AudioContext(); * const sine = audioContext.createOscillator(); * sine.frequency.value = 2; * * const audioInNode = new lfo.source.AudioInNode({ * audioContext: audioContext, * sourceNode: sine, * }); * * const signalDisplay = new lfo.sink.SignalDisplay({ * canvas: '#signal', * duration: 1, * }); * * audioInNode.connect(signalDisplay); * * // start the sine oscillator node and the lfo graph * sine.start(); * audioInNode.start(); */ class AudioInNode extends SourceMixin(BaseLfo) { constructor(options = {}) { super(definitions, options); const audioContext = this.params.get('audioContext'); const sourceNode = this.params.get('sourceNode'); if (!audioContext || !(audioContext instanceof AudioContext)) throw new Error('Invalid `audioContext` parameter'); if (!sourceNode || !(sourceNode instanceof AudioNode)) throw new Error('Invalid `sourceNode` parameter'); this.sourceNode = sourceNode; this._channel = this.params.get('channel'); this._blockDuration = null; this.processFrame = this.processFrame.bind(this); } /** * Propagate the `streamParams` in the graph and start to propagate signal * blocks produced by the audio node into the graph. * * @see {@link module:core.BaseLfo#processStreamParams} * @see {@link module:core.BaseLfo#resetStream} * @see {@link module:client.source.AudioInNode#stop} */ start() { if (this.initialized === false) { if (this.initPromise === null) // init has not yet been called this.initPromise = this.init(); this.initPromise.then(this.start); return; } const audioContext = this.params.get('audioContext'); const frameSize = this.params.get('frameSize'); this.frame.time = 0; // @note: recreate each time because of a firefox weird behavior this.scriptProcessor = audioContext.createScriptProcessor(frameSize, 1, 1); this.scriptProcessor.onaudioprocess = this.processFrame; this.started = true; this.sourceNode.connect(this.scriptProcessor); this.scriptProcessor.connect(audioContext.destination); } /** * Finalize the stream and stop the whole graph. * * @see {@link module:core.BaseLfo#finalizeStream} * @see {@link module:client.source.AudioInNode#start} */ stop() { this.finalizeStream(this.frame.time); this.started = false; this.sourceNode.disconnect(); this.scriptProcessor.disconnect(); } /** @private */ processStreamParams() { const audioContext = this.params.get('audioContext'); const frameSize = this.params.get('frameSize'); const sampleRate = audioContext.sampleRate; this.streamParams.frameSize = frameSize; this.streamParams.frameRate = sampleRate / frameSize; this.streamParams.frameType = 'signal'; this.streamParams.sourceSampleRate = sampleRate; this.streamParams.sourceSampleCount = frameSize; this._blockDuration = frameSize / sampleRate; this.propagateStreamParams(); } /** * Basically the `scriptProcessor.onaudioprocess` callback * @private */ processFrame(e) { if (this.started === false) return; this.frame.data = e.inputBuffer.getChannelData(this._channel); this.propagateFrame(); this.frame.time += this._blockDuration; } } export default AudioInNode;
import React from "react"; import withUserInfo from "./withUserInfo"; import Avatar from "../BaseComponents/Avatar"; export default withUserInfo( ({ user }) => user && user.avatarSrc && <Avatar user={user} /> );
const randomAnswers = [ {id: 1, a: 'I like to settle these sorts of issues with a good old fashioned game of catchphrase'}, {id: 2, a: 'Never eat mayonaise. It\'s disgusting.'}, {id: 3, a: 'Yes'}, {id: 4, a: 'No, that\'s a bad idea.'}, {id: 5, a: 'When in doubt, annoy your mentors.'}, {id: 6, a: 'Maybe'}, {id: 7, a: 'I wouldn\'t say no.'}, {id: 8, a: 'If you have to'} ]
define(['jquery','template','nprogress','bootstrap'],function($,template,NProgress){ //1.1ๅ‘่ฏทๆฑ‚ $.get('/api/teacher',function(data){ console.log(data.code); if(data.code==200){ //1.2ๆŠŠ่ฏทๆฑ‚ๅพ—ๅˆฐ็š„ๆ•ฐๆฎๆ”พๅˆฐ้กต้ขไธญๅŽป var html=template('tpl_data',{list:data.result}); //1.3ๆŠŠๆœ€็ปˆ็š„htmlๅญ—็ฌฆไธฒๆทปๅŠ ๅˆฐdomไธญ $('#tec_list tbody').html(html); } }) //2.1 ๆณจๅ†Œ็‚นๅ‡ปไบ‹ไปถ(ไบ‹ไปถๅง”ๆ‰˜) //็ป™็ˆถ็บงๆณจๅ†Œไบ‹ไปถ๏ผŒๅœจ็ˆถ็บงไบ‹ไปถๆ–นๆณ•้‡Œๅˆคๆ–ญ็‚นไบ†ๅ“ชไธชๅญๅ…ƒ็ด  //jqueryๅ†…้ƒจๅทฒ็ปๅธฎๅŠฉๆˆ‘ไปฌๅˆคๆ–ญๅฅฝไบ† ๆˆ‘ไปฌๅช้œ€่ฆๅ†™ๅŠŸ่ƒฝๅฐฑๅฏไปฅไบ† $('#tec_list').on('click','.see',function(){ //2.2ๅผนๅ‡บๆจกๆ€ๆก† // $('#teacherModal').modal(); //2.3ๅ‘ajax่ฏทๆฑ‚ ่Žทๅ–่ฎฒๅธˆ็š„่ฏฆ็ป†ไฟกๆฏ // http://api.botue.com/teacher/view var tc_id=$(this).closest('tr').attr('tc_id'); $.get('/api/teacher/view?tc_id='+tc_id,function(data){ //2.4ๅพ—ๅˆฐๆ•ฐๆฎไน‹ๅŽ ้€š่ฟ‡ๆจกๆฟๅผ•ๆ“Ž ๆŠŠๆ•ฐๆฎๆธฒๆŸ“ๅˆฐๆจกๆ€ๆก†ไธญ data.result.mm='<h1>็ญ‰้ฃŽๆฅ</h1>'; var html=template('tec_detail',{datail:data.result}); console.log(html); //2.5ๆŠŠๆœ€็ปˆ็š„htmlๅญ—็ฌฆไธฒๆทปๅŠ ๅˆฐdomไธญ $('#body_tec_detail').html(html); }) }) $('#tec_list').on('click','.status',function(){ var $this=$(this); var tc_status=$this.attr('tc_status'); var tc_id=$this.closest('tr').attr('tc_id'); $.ajax({ url:'/api/teacher/handle', type:'post', data:{tc_id:tc_id,tc_status:tc_status}, beforeSend:function(){ NProgress.start(); }, success:function(data){ NProgress.done(); if(data.code==200){ var status=data.result.tc_status; $this.attr('tc_status',status); if(status==0){ $this.text('ๆณจ้”€'); }else{ $this.text('ๅฏ็”จ'); } } } }) }) })
// underscore ๆ˜ฏไธ€ไธชๅผ€ๆบๅบ“๏ผŒๆไพ›ไบ†ไธฐๅฏŒ็š„้ซ˜ๆ€ง่ƒฝ็š„ๅฏนๆ•ฐ็ป„๏ผŒ้›†ๅˆ็ญ‰็š„ๆ“ไฝœ // api ๆ‰‹ๅ†Œ๏ผšhttp://learningcn.com/underscore // ไธบไบ†ๅฐ‘ๅŠ ่ฝฝไธๅฟ…่ฆ็š„ไปฃ็ ๏ผŒ้ป˜่ฎคๆ˜ฏไธๅผ•ๅ…ฅ underscore ็š„๏ผŒ้œ€่ฆ็”จๅˆฐ็š„่ฏ // ๅฐ†defineๆ‰€ๅœจไธญ็š„'underscore'็š„ๆณจ้‡ŠๅŽปๆމๅณๅฏใ€‚ๅณๆ”นไธบ // define(['underscore'], function() { // ... // }); define([/* 'underscore' */], function() { // data ๆ˜ฏGraph็š„่พ“ๅ…ฅๆ•ฐๆฎใ€‚ // ไฝฟ็”จdataๅ‚ๆ•ฐๆ—ถ๏ผŒ่ฏทๅŠกๅฟ…ไฟๆŒๅช่ฏป // ้™ค้žไฝ ๅพˆๆธ…ๆฅšไฝ ้œ€่ฆๅฏนdataๅšไป€ไนˆ๏ผŒๅนถไธ”ไบ†่งฃAngularJS็š„digestๅพช็Žฏๆœบๅˆถ // ๅฆๅˆ™่ฏทไธ่ฆๅขžๅˆ ๆ”นdata็š„ไปปไฝ•ๅฑžๆ€ง๏ผŒ่ฟ™ไผšๅผ•่ตทdigestๆญปๅพช็Žฏ // context ๆ˜ฏ็”Ÿๆˆๅ›พๅฝขๅฎšไน‰็š„่พ…ๅŠฉๆ•ฐๆฎ๏ผŒ้ป˜่ฎคๅ€ผๆ˜ฏๅบ”็”จ็š„scopeใ€‚ // ๅœจ็”Ÿๆˆๅคๆ‚ๅ›พๅฝข็š„ๆ—ถๅ€™๏ผŒไป…้ dataๆœฌ่บซไธ่ถณไปฅ็”Ÿๆˆไธ€ไธชๅ›พๅฝขๅฎšไน‰ // ๆญคๆ—ถๅฐฑ้œ€่ฆ็”จๅˆฐ่ฟ™ไธชๅฏน่ฑกๆฅ่พ…ๅŠฉ // GraphService ๆ˜ฏไธ€ไธชๅ‡ฝๆ•ฐ้›†๏ผŒไธป่ฆๆไพ›ไบ†ๅฏนไบŒ็ปดๆ•ฐ็ป„็š„ๅธธ็”จๆ“ไฝœ // attributes ๆ˜ฏๅฝ“ๅ‰Graphๆ‰€ๅœจ็š„html่Š‚็‚น็š„ๆ‰€ๆœ‰ๅฑžๆ€ง้›†ใ€‚ไนŸๆ˜ฏไธ€็ง่พ…ๅŠฉๆ•ฐๆฎใ€‚ return function(data, context, GraphService, attributes) { return { title: { text: 'Sankey Diagram' }, tooltip: { trigger: 'item', triggerOn: 'mousemove' }, series: [ { type: 'sankey', layout: 'none', data: data.nodes, links: data.links, itemStyle: { normal: { borderWidth: 1, borderColor: '#aaa' } }, lineStyle: { normal: { color: 'source', curveness: 0.5 } } } ] }; }});
import React from 'react'; import PropTypes from 'prop-types'; const InStock = ({ inStock }) => ( <div> {inStock <= 5 && <span className="size-medium color-price"> {`Only ${inStock} left in stock - order soon.`} </span>} {inStock > 5 && <span className="size-medium color-success"> In Stock. </span>} </div> ); InStock.propTypes = { inStock: PropTypes.number.isRequired, }; export default InStock;
/** * ํ™”๋ฉด ์ดˆ๊ธฐํ™” - ํ™”๋ฉด ๋กœ๋“œ์‹œ ์ž๋™ ํ˜ธ์ถœ ๋จ */ function _Initialize() { // ๋‹จ์œ„ํ™”๋ฉด์—์„œ ์‚ฌ์šฉ๋  ์ผ๋ฐ˜ ์ „์—ญ ๋ณ€์ˆ˜ ์ •์˜ // $NC.setGlobalVar({ // }); // ๊ทธ๋ฆฌ๋“œ ์ดˆ๊ธฐํ™” grdT1MasterInitialize(); grdT1DetailInitialize(); grdT1SubInitialize(); grdT2MasterInitialize(); // ํƒญ ์ดˆ๊ธฐํ™” $NC.setInitTab("#divMasterView", { tabIndex: 0, onActivate: tabOnActivate }); // ์กฐํšŒ์กฐ๊ฑด - ๋ฌผ๋ฅ˜์„ผํ„ฐ ์„ธํŒ… $NC.setInitCombo("/WC/getDataSet.do", { P_QUERY_ID: "WC.POP_CSUSERCENTER", P_QUERY_PARAMS: $NC.getParams({ P_USER_ID: $NC.G_USERINFO.USER_ID, P_CENTER_CD: "%" }) }, { selector: "#cboQCenter_Cd", codeField: "CENTER_CD", nameField: "CENTER_NM", onComplete: function() { $NC.setValue("#cboQCenter_Cd", $NC.G_USERINFO.CENTER_CD); } }); // ์ถ”๊ฐ€ ์กฐํšŒ์กฐ๊ฑด ์‚ฌ์šฉ $NC.setInitAdditionalCondition(); // ์กฐํšŒ์กฐ๊ฑด - ์‚ฌ์—…๋ถ€ ์ดˆ๊ธฐ๊ฐ’ ์„ค์ • $NC.setValue("#edtQBu_Cd", $NC.G_USERINFO.BU_CD); $NC.setValue("#edtQBu_Nm", $NC.G_USERINFO.BU_NM); $NC.setValue("#edtQCust_Cd", $NC.G_USERINFO.CUST_CD); // ์กฐํšŒ์กฐ๊ฑด - ๊ณต๊ธ‰์ฒ˜ ์ดˆ๊ธฐ๊ฐ’ ์„ค์ • $NC.setValue("#edtQVendor_Cd"); $NC.setValue("#edtQVendor_Nm"); // ์กฐํšŒ์กฐ๊ฑด - ์ž…๊ณ ์ผ์ž์— ๋‹ฌ๋ ฅ์ด๋ฏธ์ง€ ์„ค์ • $NC.setInitDatePicker("#dtpQInbound_Date1"); $NC.setInitDatePicker("#dtpQInbound_Date2"); // ์กฐํšŒ์กฐ๊ฑด - ์ƒํ’ˆ ์ดˆ๊ธฐ๊ฐ’ ์„ค์ • $NC.setValue("#edtQItem_Cd"); $NC.setValue("#edtQItem_Nm"); $("#btnQBu_Cd").click(showUserBuPopup); $("#btnQBrand_Cd").click(showBuBrandPopup); $("#btnQVendor_Cd").click(showVendorPopup); } function _OnLoaded() { // ๋ฏธ์ฒ˜๋ฆฌ/์˜ค๋ฅ˜ ๋‚ด์—ญ ํƒญ ํ™”๋ฉด์— splitter ์„ค์ • $NC.setInitSplitter("#divT1SubView", "h", 300); } /** * ํ™”๋ฉด ๋ฆฌ์‚ฌ์ด์ฆˆ Offset ์„ธํŒ… */ function _SetResizeOffset() { $NC.G_OFFSET.bottomRightViewWidth = 300; $NC.G_OFFSET.nonClientHeight = $("#divConditionView").outerHeight() + $NC.G_LAYOUT.nonClientHeight + $NC.G_LAYOUT.border1; $NC.G_OFFSET.gridHeightOffset = $NC.G_LAYOUT.tabHeader + $NC.G_LAYOUT.header + $NC.G_OFFSET.nonClientHeight + ($NC.G_LAYOUT.border1 * 3); $NC.G_OFFSET.subViewHeightOffset = $NC.G_LAYOUT.tabHeader + $NC.G_OFFSET.nonClientHeight + ($NC.G_LAYOUT.border1 * 3); } /** * Window Resize Event - Window Size ์กฐ์ •์‹œ ํ˜ธ์ถœ ๋จ */ function _OnResize(parent) { var clientWidth = parent.width() - $NC.G_LAYOUT.border2; var clientHeight = parent.height() - $NC.G_OFFSET.nonClientHeight; $NC.resizeContainer("#divMasterView", clientWidth, clientHeight); clientWidth -= $NC.G_LAYOUT.border1; clientHeight = parent.height() - $NC.G_OFFSET.subViewHeightOffset; $NC.resizeContainer("#divT1TabSheetView", clientWidth, clientHeight); $NC.resizeContainer("#divT2TabSheetView", clientWidth, clientHeight); // ์ž…๊ณ ์ค‘๋Ÿ‰๋“ฑ๋ก ํƒญ if ($("#divMasterView").tabs("option", "active") === 0) { // Splitter ์ปจํ…Œ์ด๋„ˆ ํฌ๊ธฐ ์กฐ์ • var container = $("#divT1SubView"); $NC.resizeContainer(container, clientWidth, clientHeight); // Grid ์‚ฌ์ด์ฆˆ ์กฐ์ • $NC.resizeGrid("#grdT1Master", clientWidth, $("#grdT1Master").parent().height() - $NC.G_LAYOUT.header); clientWidth -= $NC.G_OFFSET.bottomRightViewWidth + $NC.G_LAYOUT.border1 + $NC.G_LAYOUT.margin1; clientHeight = $("#divBottom").height(); $NC.resizeContainer("#divBottom_Left", clientWidth, clientHeight); // Grid ์‚ฌ์ด์ฆˆ ์กฐ์ • $NC.resizeGrid("#grdT1Detail", clientWidth, $("#grdT1Detail").parent().height() - $NC.G_LAYOUT.header); $NC.resizeContainer("#divBottom_Right", $NC.G_OFFSET.bottomRightViewWidth, clientHeight); // Grid ์‚ฌ์ด์ฆˆ ์กฐ์ • $NC.resizeGrid("#grdT1Sub", $NC.G_OFFSET.bottomRightViewWidth, $("#grdT1Sub").parent().height() - $NC.G_LAYOUT.header); } else { clientHeight = parent.height() - $NC.G_OFFSET.gridHeightOffset; // Grid ์‚ฌ์ด์ฆˆ ์กฐ์ • $NC.resizeGrid("#grdT2Master", clientWidth, clientHeight); } } /** * Input, Select Change Event ์ฒ˜๋ฆฌ * * @param e * ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ * @param view * ๋Œ€์ƒ Object */ function _OnConditionChange(e, view, val) { // ์กฐํšŒ ์กฐ๊ฑด์— Object Change var id = view.prop("id").substr(4).toUpperCase(); switch (id) { case "BU_CD": var P_QUERY_PARAMS; var O_RESULT_DATA = [ ]; if (!$NC.isNull(val)) { P_QUERY_PARAMS = { P_USER_ID: $NC.G_USERINFO.USER_ID, P_BU_CD: val }; O_RESULT_DATA = $NP.getUserBuInfo({ queryParams: P_QUERY_PARAMS }); } if (O_RESULT_DATA.length <= 1) { onUserBuPopup(O_RESULT_DATA[0]); } else { $NP.showUserBuPopup({ queryParams: P_QUERY_PARAMS, queryData: O_RESULT_DATA }, onUserBuPopup, onUserBuPopup); } return; case "BRAND_CD": var P_QUERY_PARAMS; var O_RESULT_DATA = [ ]; if (!$NC.isNull(val)) { var BU_CD = $NC.getValue("#edtQBu_Cd"); P_QUERY_PARAMS = { P_BU_CD: BU_CD, P_BRAND_CD: val }; O_RESULT_DATA = $NP.getBuBrandInfo({ queryParams: P_QUERY_PARAMS }); } if (O_RESULT_DATA.length <= 1) { onBuBrandPopup(O_RESULT_DATA[0]); } else { $NP.showBuBrandPopup({ queryParams: P_QUERY_PARAMS, queryData: O_RESULT_DATA }, onBuBrandPopup, onBuBrandPopup); } return; case "VENDOR_CD": var P_QUERY_PARAMS; var O_RESULT_DATA = [ ]; if (!$NC.isNull(val)) { var CUST_CD = $NC.getValue("#edtQCust_Cd"); P_QUERY_PARAMS = { P_CUST_CD: CUST_CD, P_VENDOR_CD: val, P_VIEW_DIV: "2" }; O_RESULT_DATA = $NP.getVendorInfo({ queryParams: P_QUERY_PARAMS }); } if (O_RESULT_DATA.length <= 1) { onVendorPopup(O_RESULT_DATA[0]); } else { $NP.showVendorPopup({ queryParams: P_QUERY_PARAMS, queryData: O_RESULT_DATA }, onVendorPopup, onVendorPopup); } return; case "INBOUND_DATE1": $NC.setValueDatePicker(view, val, "๊ฒ€์ƒ‰ ์‹œ์ž‘์ผ์ž๋ฅผ ์ •ํ™•ํžˆ ์ž…๋ ฅํ•˜์‹ญ์‹œ์˜ค."); break; case "INBOUND_DATE2": $NC.setValueDatePicker(view, val, "๊ฒ€์ƒ‰ ์ข…๋ฃŒ์ผ์ž๋ฅผ ์ •ํ™•ํžˆ ์ž…๋ ฅํ•˜์‹ญ์‹œ์˜ค."); break; } // ํ™”๋ฉดํด๋ฆฌ์–ด onChangingCondition(); } /** * Inquiry Button Event - ๋ฉ”์ธ ์ƒ๋‹จ ์กฐํšŒ ๋ฒ„ํŠผ ํด๋ฆญ์‹œ ํ˜ธ์ถœ ๋จ */ function _Inquiry() { var CENTER_CD = $NC.getValue("#cboQCenter_Cd"); if ($NC.isNull(CENTER_CD)) { alert("๋ฌผ๋ฅ˜์„ผํ„ฐ๋ฅผ ์„ ํƒํ•˜์‹ญ์‹œ์˜ค."); $NC.setFocus("#cboQCenter_Cd"); return; } var BU_CD = $NC.getValue("#edtQBu_Cd"); if ($NC.isNull(BU_CD)) { alert("์‚ฌ์—…๋ถ€์ฝ”๋“œ๋ฅผ ์ž…๋ ฅํ•˜์‹ญ์‹œ์˜ค."); $NC.setFocus("#edtQBrand_Cd"); return; } var INBOUND_DATE1 = $NC.getValue("#dtpQInbound_Date1"); if ($NC.isNull(INBOUND_DATE1)) { alert("์‹œ์ž‘์ผ์ž๋ฅผ ์ž…๋ ฅํ•˜์‹ญ์‹œ์˜ค."); $NC.setFocus("#dtpQInbound_Date1"); return; } var INBOUND_DATE2 = $NC.getValue("#dtpQInbound_Date2"); if ($NC.isNull(INBOUND_DATE2)) { alert("์ข…๋ฃŒ์ผ์ž๋ฅผ ์ž…๋ ฅํ•˜์‹ญ์‹œ์˜ค."); $NC.setFocus("#dtpQInbound_Date2"); return; } var BRAND_CD = $NC.getValue("#edtQBrand_Cd", true); var VENDOR_CD = $NC.getValue("#edtQVendor_Cd", true); var ITEM_CD = $NC.getValue("#edtQItem_Cd", true); var ITEM_NM = $NC.getValue("#edtQItem_Nm", true); // ์ž…๊ณ ์ค‘๋Ÿ‰๋“ฑ๋ก ํƒญ if ($("#divMasterView").tabs("option", "active") === 0) { // ์กฐํšŒ์‹œ ๊ฐ’ ์ดˆ๊ธฐํ™” $NC.clearGridData(G_GRDT1MASTER); $NC.clearGridData(G_GRDT1DETAIL); $NC.clearGridData(G_GRDT1SUB); G_GRDT1MASTER.queryParams = $NC.getParams({ P_CENTER_CD: CENTER_CD, P_BU_CD: BU_CD, P_INBOUND_DATE1: INBOUND_DATE1, P_INBOUND_DATE2: INBOUND_DATE2, P_VENDOR_CD: VENDOR_CD, P_BRAND_CD: BRAND_CD, P_ITEM_CD: ITEM_CD, P_ITEM_NM: ITEM_NM }); // ๋ฐ์ดํ„ฐ ์กฐํšŒ $NC.serviceCall("/LI05020E/getDataSet.do", $NC.getGridParams(G_GRDT1MASTER), onGetT1Master); // ์ž…๊ณ ์ค‘๋Ÿ‰๋‚ด์—ญ ํƒญ } else { // ์กฐํšŒ์‹œ ์ „์—ญ ๋ณ€์ˆ˜ ๊ฐ’ ์ดˆ๊ธฐํ™” $NC.setInitGridVar(G_GRDT2MASTER); G_GRDT2MASTER.queryParams = $NC.getParams({ P_CENTER_CD: CENTER_CD, P_BU_CD: BU_CD, P_INBOUND_DATE1: INBOUND_DATE1, P_INBOUND_DATE2: INBOUND_DATE2, P_VENDOR_CD: VENDOR_CD, P_BRAND_CD: BRAND_CD, P_ITEM_CD: ITEM_CD, P_ITEM_NM: ITEM_NM }); // ๋ฐ์ดํ„ฐ ์กฐํšŒ $NC.serviceCall("/LI05020E/getDataSet.do", $NC.getGridParams(G_GRDT2MASTER), onGetT2Master); } } /** * New Button Event - ๋ฉ”์ธ ์ƒ๋‹จ ์‹ ๊ทœ ๋ฒ„ํŠผ ํด๋ฆญ์‹œ ํ˜ธ์ถœ ๋จ */ function _New() { } /** * Save Button Event - ๋ฉ”์ธ ์ƒ๋‹จ ์ €์žฅ ๋ฒ„ํŠผ ํด๋ฆญ์‹œ ํ˜ธ์ถœ ๋จ */ function _Save() { } /** * Delete Button Event - ๋ฉ”์ธ ์ƒ๋‹จ ์‚ญ์ œ ๋ฒ„ํŠผ ํด๋ฆญ์‹œ ํ˜ธ์ถœ ๋จ */ function _Delete() { } /** * Cancel Button Event - ๋ฉ”์ธ ์ƒ๋‹จ ์ทจ์†Œ ๋ฒ„ํŠผ ํด๋ฆญ์‹œ ํ˜ธ์ถœ ๋จ */ function _Cancel() { } /** * Print Button Event - ๋ฉ”์ธ ์ƒ๋‹จ ์ถœ๋ ฅ ๋ฒ„ํŠผ ํด๋ฆญ์‹œ ํ˜ธ์ถœ ๋จ * * @param printIndex * ์„ ํƒํ•œ ์ถœ๋ ฅ๋ฌผ Index */ function _Print(printIndex, printName) { } /** * Tab Active Event * * @param event * @param ui * newTab: The tab that was just activated.<br> * oldTab: The tab that was just deactivated.<br> * newPanel: The panel that was just activated.<br> * oldPanel: The panel that was just deactivated */ function tabOnActivate(event, ui) { var id = ui.newTab.prop("id").substr(3).toUpperCase(); if (id === "TAB1") { // ์Šคํ”Œ๋ฆฌํ„ฐ๊ฐ€ ์ดˆ๊ธฐํ™”๊ฐ€ ๋˜์–ด ์žˆ์œผ๋ฉด _OnResize ํ˜ธ์ถœ if ($NC.isSplitter("#divT1SubView")) { // ์Šคํ•„๋ฆฌํ„ฐ๋ฅผ ํ†ตํ•œ _OnResize ํ˜ธ์ถœ $("#divT1SubView").trigger("resize"); } else { // ์Šคํ”Œ๋ฆฌํ„ฐ ์ดˆ๊ธฐํ™” $NC.setInitSplitter("#divT1SubView", "h"); } } else { _OnResize($(window)); } } function grdT1MasterOnGetColumns() { var columns = [ ]; $NC.setGridColumn(columns, { id: "INBOUND_DATE", field: "INBOUND_DATE", name: "์ž…๊ณ ์ผ์ž", minWidth: 80, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "INBOUND_NO", field: "INBOUND_NO", name: "์ž…๊ณ ๋ฒˆํ˜ธ", minWidth: 70, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "INBOUND_STATE_D", field: "INBOUND_STATE_D", name: "์ง„ํ–‰์ƒํƒœ", minWidth: 90 }); $NC.setGridColumn(columns, { id: "INOUT_NM", field: "INOUT_NM", name: "์ž…๊ณ ๊ตฌ๋ถ„", minWidth: 120 }); $NC.setGridColumn(columns, { id: "VENDOR_CD", field: "VENDOR_CD", name: "๊ณต๊ธ‰์ฒ˜", minWidth: 70 }); $NC.setGridColumn(columns, { id: "VENDOR_NM", field: "VENDOR_NM", name: "๊ณต๊ธ‰์ฒ˜๋ช…", minWidth: 150 }); $NC.setGridColumn(columns, { id: "CAR_NO", field: "CAR_NO", name: "์ฐจ๋Ÿ‰๋ฒˆํ˜ธ", minWidth: 80, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "ORDER_DATE", field: "ORDER_DATE", name: "์˜ˆ์ •์ผ์ž", minWidth: 80, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "ORDER_NO", field: "ORDER_NO", name: "์˜ˆ์ •๋ฒˆํ˜ธ", minWidth: 70, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "BU_DATE", field: "BU_DATE", name: "์ „ํ‘œ์ผ์ž", minWidth: 80, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "BU_NO", field: "BU_NO", name: "์ „ํ‘œ๋ฒˆํ˜ธ", minWidth: 80 }); $NC.setGridColumn(columns, { id: "LOCATION_ID_CNT", field: "LOCATION_ID_CNT", name: "๋กœ์ผ€์ด์…˜ID์ˆ˜", minWidth: 100, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "PLANED_DATETIME", field: "PLANED_DATETIME", name: "๋„์ฐฉ์˜ˆ์ •์ผ์‹œ", minWidth: 130, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "REMARK1", field: "REMARK1", name: "๋น„๊ณ ", minWidth: 150 }); return $NC.setGridColumnDefaultFormatter(columns); } /** * ์ž…๊ณ ์ค‘๋Ÿ‰๋“ฑ๋กํƒญ์˜ ์ƒ๋‹จ๊ทธ๋ฆฌ๋“œ ์ดˆ๊ธฐํ™” */ function grdT1MasterInitialize() { var options = { frozenColumn: 3 }; // Grid Object, DataView ์ƒ์„ฑ ๋ฐ ์ดˆ๊ธฐํ™” $NC.setInitGridObject("#grdT1Master", { columns: grdT1MasterOnGetColumns(), queryId: "LI05020E.RS_T1_MASTER", sortCol: "INBOUND_NO", gridOptions: options }); G_GRDT1MASTER.view.onSelectedRowsChanged.subscribe(grdT1MasterOnAfterScroll); } function grdT1DetailOnGetColumns() { var columns = [ ]; $NC.setGridColumn(columns, { id: "ITEM_CD", field: "ITEM_CD", name: "์ƒํ’ˆ์ฝ”๋“œ", minWidth: 90 }); $NC.setGridColumn(columns, { id: "ITEM_NM", field: "ITEM_NM", name: "์ƒํ’ˆ๋ช…", minWidth: 150 }); $NC.setGridColumn(columns, { id: "ITEM_SPEC", field: "ITEM_SPEC", name: "๊ทœ๊ฒฉ", minWidth: 80 }); $NC.setGridColumn(columns, { id: "BRAND_NM", field: "BRAND_NM", name: "๋ธŒ๋žœ๋“œ๋ช…", minWidth: 80 }); $NC.setGridColumn(columns, { id: "QTY_IN_BOX", field: "QTY_IN_BOX", name: "์ž…์ˆ˜", minWidth: 70, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "ENTRY_QTY", field: "ENTRY_QTY", name: "๋“ฑ๋ก์ˆ˜๋Ÿ‰", minWidth: 70, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "ENTRY_BOX", field: "ENTRY_BOX", name: "๋“ฑ๋กBOX", minWidth: 70, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "ENTRY_EA", field: "ENTRY_EA", name: "๋“ฑ๋กEA", minWidth: 70, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "ENTRY_WEIGHT", field: "ENTRY_WEIGHT", name: "๋“ฑ๋ก์ค‘๋Ÿ‰", minWidth: 70, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "REMARK1", field: "REMARK1", name: "๋น„๊ณ ", minWidth: 150 }); return $NC.setGridColumnDefaultFormatter(columns); } /** * ์ž…๊ณ ์ค‘๋Ÿ‰๋“ฑ๋กํƒญ์˜ ํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ ์ดˆ๊ธฐํ™” */ function grdT1DetailInitialize() { var options = { frozenColumn: 3 }; // Grid Object, DataView ์ƒ์„ฑ ๋ฐ ์ดˆ๊ธฐํ™” $NC.setInitGridObject("#grdT1Detail", { columns: grdT1DetailOnGetColumns(), queryId: "LI05020E.RS_T1_DETAIL", sortCol: "ITEM_CD", gridOptions: options, canDblClick: true }); G_GRDT1DETAIL.view.onClick.subscribe(grdT1DetailOnClick); G_GRDT1DETAIL.view.onSelectedRowsChanged.subscribe(grdT1DetailOnAfterScroll); G_GRDT1DETAIL.view.onDblClick.subscribe(grdT1DetailOnDblClick); } /** * ์ƒ๋‹จ๊ทธ๋ฆฌ๋“œ ๋”๋ธ” ํด๋ฆญ : ํŒ์—… ํ‘œ์‹œ */ function grdT1DetailOnDblClick(e, args) { if (!$NC.getProgramPermission().canSave) { alert("ํ•ด๋‹น ํ”„๋กœ๊ทธ๋žจ์˜ ์ €์žฅ๊ถŒํ•œ์ด ์—†์Šต๋‹ˆ๋‹ค."); return; } if (G_GRDT1DETAIL.lastRow == null || G_GRDT1DETAIL.data.getLength() === 0) { return; } var rowData = G_GRDT1DETAIL.data.getItem(args.row); if (rowData) { $NC.G_MAIN.showProgramSubPopup({ PROGRAM_ID: "LI05021P", PROGRAM_NM: "์ž…๊ณ ์ค‘๋Ÿ‰๋“ฑ๋ก/์ˆ˜์ •", url: "li/LI05021P.html", width: 650, height: 450, userData: { P_CENTER_CD: rowData.CENTER_CD, P_BU_CD: rowData.BU_CD, P_BRAND_CD: rowData.BRAND_CD, P_INBOUND_DATE: rowData.INBOUND_DATE, P_INBOUND_NO: rowData.INBOUND_NO, P_ITEM_CD: rowData.ITEM_CD, P_ITEM_NM: rowData.ITEM_NM, P_ITEM_SPEC: rowData.ITEM_SPEC, P_ENTRY_QTY: rowData.ENTRY_QTY, P_SUB_DS: G_GRDT1SUB.data.getItems() }, onOk: function() { popUpOnOk(); } }); } } /** * ์ž…๊ณ ์ค‘๋Ÿ‰ ๋“ฑ๋ก ํŒ์—… ํ˜ธ์ถœ ํ›„ */ function popUpOnOk() { var rowData = G_GRDT1DETAIL.data.getItem(G_GRDT1DETAIL.lastRow); // ์กฐํšŒ์‹œ ์ „์—ญ ๋ณ€์ˆ˜ ๊ฐ’ ์ดˆ๊ธฐํ™” $NC.setInitGridVar(G_GRDT1SUB); G_GRDT1SUB.queryParams = $NC.getParams({ P_CENTER_CD: rowData.CENTER_CD, P_BU_CD: rowData.BU_CD, P_INBOUND_DATE: rowData.INBOUND_DATE, P_INBOUND_NO: rowData.INBOUND_NO, P_BRAND_CD: rowData.BRAND_CD, P_ITEM_CD: rowData.ITEM_CD }); // ๋ฐ์ดํ„ฐ ์กฐํšŒ $NC.serviceCall("/LI05020E/getDataSet.do", $NC.getGridParams(G_GRDT1SUB), onGetT1Sub); } function grdT1SubOnGetColumns() { var columns = [ ]; $NC.setGridColumn(columns, { id: "ITEM_WEIGHT", field: "ITEM_WEIGHT", name: "์ƒํ’ˆ์ค‘๋Ÿ‰", minWidth: 80, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "ENTRY_QTY", field: "ENTRY_QTY", name: "๋“ฑ๋ก์ˆ˜๋Ÿ‰", minWidth: 70, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "REMARK1", field: "REMARK1", name: "๋น„๊ณ ", minWidth: 100 }); return $NC.setGridColumnDefaultFormatter(columns); } /** * ์ž…๊ณ ์ค‘๋Ÿ‰๋“ฑ๋กํƒญ์˜ ํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ ์ดˆ๊ธฐํ™” */ function grdT1SubInitialize() { var options = { frozenColumn: 0 }; // Grid Object, DataView ์ƒ์„ฑ ๋ฐ ์ดˆ๊ธฐํ™” $NC.setInitGridObject("#grdT1Sub", { columns: grdT1SubOnGetColumns(), queryId: "LI05020E.RS_T1_SUB", sortCol: "ITEM_CD", gridOptions: options }); G_GRDT1SUB.view.onClick.subscribe(grdT1SubOnClick); G_GRDT1SUB.view.onSelectedRowsChanged.subscribe(grdT1SubOnAfterScroll); } function grdT2MasterOnGetColumns() { var columns = [ ]; $NC.setGridColumn(columns, { id: "INBOUND_DATE", field: "INBOUND_DATE", name: "์ž…๊ณ ์ผ์ž", minWidth: 100, cssClass: "align-center", summaryTitle: "[ํ•ฉ๊ณ„]" }); $NC.setGridColumn(columns, { id: "INBOUND_NO", field: "INBOUND_NO", name: "์ž…๊ณ ๋ฒˆํ˜ธ", minWidth: 80, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "VENDOR_CD", field: "VENDOR_CD", name: "๊ณต๊ธ‰์ฒ˜", minWidth: 100 }); $NC.setGridColumn(columns, { id: "VENDOR_NM", field: "VENDOR_NM", name: "๊ณต๊ธ‰์ฒ˜๋ช…", minWidth: 150 }); $NC.setGridColumn(columns, { id: "ITEM_CD", field: "ITEM_CD", name: "์ƒํ’ˆ์ฝ”๋“œ", minWidth: 90 }); $NC.setGridColumn(columns, { id: "ITEM_NM", field: "ITEM_NM", name: "์ƒํ’ˆ๋ช…", minWidth: 200 }); $NC.setGridColumn(columns, { id: "ITEM_SPEC", field: "ITEM_SPEC", name: "๊ทœ๊ฒฉ", minWidth: 80 }); $NC.setGridColumn(columns, { id: "BRAND_NM", field: "BRAND_NM", name: "๋ธŒ๋žœ๋“œ๋ช…", minWidth: 80 }); $NC.setGridColumn(columns, { id: "QTY_IN_BOX", field: "QTY_IN_BOX", name: "์ž…์ˆ˜", minWidth: 70, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "ITEM_WEIGHT", field: "ITEM_WEIGHT", name: "์ƒํ’ˆ์ค‘๋Ÿ‰", minWidth: 70, cssClass: "align-right", aggregator: "SUM" }); $NC.setGridColumn(columns, { id: "WEIGHT_QTY", field: "WEIGHT_QTY", name: "๋“ฑ๋ก์ˆ˜๋Ÿ‰", minWidth: 70, cssClass: "align-right", aggregator: "SUM" }); $NC.setGridColumn(columns, { id: "INOUT_CD_F", field: "INOUT_CD_F", name: "์ž…๊ณ ๊ตฌ๋ถ„", minWidth: 120 }); $NC.setGridColumn(columns, { id: "BU_DATE", field: "BU_DATE", name: "์ „ํ‘œ์ผ์ž", minWidth: 100, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "BU_NO", field: "BU_NO", name: "์ „ํ‘œ๋ฒˆํ˜ธ", minWidth: 100 }); $NC.setGridColumn(columns, { id: "REMARK1", field: "REMARK1", name: "๋น„๊ณ ", minWidth: 150 }); return $NC.setGridColumnDefaultFormatter(columns); } /** * ์ž…๊ณ ์ค‘๋Ÿ‰๋‚ด์—ญ ํƒญ์˜ ๊ทธ๋ฆฌ๋“œ ์ดˆ๊ธฐํ™” */ function grdT2MasterInitialize() { var options = { frozenColumn: 6, summaryRow: { visible: true } }; // Grid Object, DataView ์ƒ์„ฑ ๋ฐ ์ดˆ๊ธฐํ™” $NC.setInitGridObject("#grdT2Master", { columns: grdT2MasterOnGetColumns(), queryId: "LI05020E.RS_T2_MASTER", sortCol: "INBOUND_NO", gridOptions: options }); G_GRDT2MASTER.view.onSelectedRowsChanged.subscribe(grdT2MasterOnAfterScroll); } /** * ์ž…๊ณ ์ค‘๋Ÿ‰๋“ฑ๋ก ํƒญ ํ•˜๋‹จ ๊ทธ๋ฆฌ๋“œ ํ–‰ ํด๋ฆญ์‹œ * * @param e * @param args */ function grdT1DetailOnClick(e, args) { G_GRDT1DETAIL.focused = true; } /** * ์ž…๊ณ ์ค‘๋Ÿ‰๋“ฑ๋ก ํƒญ ํ•˜๋‹จ ๊ทธ๋ฆฌ๋“œ ํ–‰ ํด๋ฆญ์‹œ * * @param e * @param args */ function grdT1SubOnClick(e, args) { G_GRDT1SUB.focused = true; } /** * ์ž…๊ณ ์ค‘๋Ÿ‰๋“ฑ๋กํƒญ ์ƒ๋‹จ๊ทธ๋ฆฌ๋“œ ํ–‰ ํด๋ฆญ์‹œ ํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ ๊ฐ’ ์ทจ๋“ํ•ด์„œ ํ‘œ์‹œ ์ฒ˜๋ฆฌ * * @param e * @param args */ function grdT1MasterOnAfterScroll(e, args) { var row = args.rows[0]; var rowData = G_GRDT1MASTER.data.getItem(row); if (G_GRDT1MASTER.lastRow != null) { if (row == G_GRDT1MASTER.lastRow) { e.stopImmediatePropagation(); return; } } // ์กฐํšŒ์‹œ ๊ฐ’ ์ดˆ๊ธฐํ™” $NC.setInitGridVar(G_GRDT1DETAIL); $NC.setInitGridData(G_GRDT1DETAIL); $NC.setGridDisplayRows("#grdT1Detail", 0, 0); $NC.setInitGridVar(G_GRDT1SUB); $NC.setInitGridData(G_GRDT1SUB); $NC.setGridDisplayRows("#grdT1Sub", 0, 0); G_GRDT1DETAIL.queryParams = $NC.getParams({ P_CENTER_CD: rowData.CENTER_CD, P_BU_CD: rowData.BU_CD, P_INBOUND_DATE: rowData.INBOUND_DATE, P_INBOUND_NO: rowData.INBOUND_NO }); // ๋ฐ์ดํ„ฐ ์กฐํšŒ $NC.serviceCall("/LI05020E/getDataSet.do", $NC.getGridParams(G_GRDT1DETAIL), onGetT1Detail); // ์ƒ๋‹จ ํ˜„์žฌ๋กœ์šฐ/์ด๊ฑด์ˆ˜ ์—…๋ฐ์ดํŠธ $NC.setGridDisplayRows("#grdT1Master", row + 1); } /** * ์ž…๊ณ ์ค‘๋Ÿ‰๋‚ด์—ญ ํƒญ์˜ ๊ทธ๋ฆฌ๋“œ ํ–‰ ํด๋ฆญ์‹œ ์ฒ˜๋ฆฌ * * @param e * @param args */ function grdT2MasterOnAfterScroll(e, args) { var row = args.rows[0]; if (G_GRDT2MASTER.lastRow != null) { if (row == G_GRDT2MASTER.lastRow) { e.stopImmediatePropagation(); return; } } // ์ƒ๋‹จ ํ˜„์žฌ๋กœ์šฐ/์ด๊ฑด์ˆ˜ ์—…๋ฐ์ดํŠธ $NC.setGridDisplayRows("#grdT2Master", row + 1); } /** * ์ž…๊ณ ์ค‘๋Ÿ‰๋“ฑ๋กํƒญ ํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ ํ–‰ ํด๋ฆญ์‹œ ํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ ๊ฐ’ ์ทจ๋“ํ•ด์„œ ํ‘œ์‹œ ์ฒ˜๋ฆฌ * * @param e * @param args */ function grdT1DetailOnAfterScroll(e, args) { var row = args.rows[0]; var rowData = G_GRDT1DETAIL.data.getItem(row); if (G_GRDT1DETAIL.lastRow != null) { if (row == G_GRDT1DETAIL.lastRow) { e.stopImmediatePropagation(); return; } } // ์กฐํšŒ์‹œ ๊ฐ’ ์ดˆ๊ธฐํ™” $NC.setInitGridVar(G_GRDT1SUB); $NC.setInitGridData(G_GRDT1SUB); $NC.setGridDisplayRows("#grdT1Sub", 0, 0); G_GRDT1SUB.queryParams = $NC.getParams({ P_CENTER_CD: rowData.CENTER_CD, P_BU_CD: rowData.BU_CD, P_INBOUND_DATE: rowData.INBOUND_DATE, P_INBOUND_NO: rowData.INBOUND_NO, P_BRAND_CD: rowData.BRAND_CD, P_ITEM_CD: rowData.ITEM_CD }); // ๋ฐ์ดํ„ฐ ์กฐํšŒ $NC.serviceCall("/LI05020E/getDataSet.do", $NC.getGridParams(G_GRDT1SUB), onGetT1Sub); // ์ƒ๋‹จ ํ˜„์žฌ๋กœ์šฐ/์ด๊ฑด์ˆ˜ ์—…๋ฐ์ดํŠธ $NC.setGridDisplayRows("#grdT1Detail", row + 1); } /** * ์ž…๊ณ ์ค‘๋Ÿ‰๋“ฑ๋กํƒญ ํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ ํ–‰ ํด๋ฆญ์‹œ ํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ ๊ฐ’ ์ทจ๋“ํ•ด์„œ ํ‘œ์‹œ ์ฒ˜๋ฆฌ * * @param e * @param args */ function grdT1SubOnAfterScroll(e, args) { var row = args.rows[0]; if (G_GRDT1SUB.lastRow != null) { if (row == G_GRDT1SUB.lastRow) { e.stopImmediatePropagation(); return; } } // ์ƒ๋‹จ ํ˜„์žฌ๋กœ์šฐ/์ด๊ฑด์ˆ˜ ์—…๋ฐ์ดํŠธ $NC.setGridDisplayRows("#grdT1Sub", row + 1); } /** * ์ž…๊ณ ์ค‘๋Ÿ‰๋“ฑ๋ก ํƒญ ์กฐํšŒ๋ฒ„ํŠผ ํด๋ฆญํ›„ ์ƒ๋‹จ ๊ทธ๋ฆฌ๋“œ์— ๋ฐ์ดํ„ฐ ํ‘œ์‹œ์ฒ˜๋ฆฌ */ function onGetT1Master(ajaxData) { $NC.setInitGridData(G_GRDT1MASTER, ajaxData); if (G_GRDT1MASTER.data.getLength() > 0) { if ($NC.isNull(G_GRDT1MASTER.lastKeyVal)) { $NC.setGridSelectRow(G_GRDT1MASTER, 0); } else { $NC.setGridSelectRow(G_GRDT1MASTER, { selectKey: "INBOUND_NO", selectVal: G_GRDT1MASTER.lastKeyVal }); } } else { $NC.setGridDisplayRows("#grdT1Master", 0, 0); } } /** * ์ž…๊ณ ์ค‘๋Ÿ‰๋‚ด์—ญ ํƒญ ์กฐํšŒ๋ฒ„ํŠผ ํด๋ฆญํ›„ ์ƒ๋‹จ ๊ทธ๋ฆฌ๋“œ์— ๋ฐ์ดํ„ฐ ํ‘œ์‹œ์ฒ˜๋ฆฌ */ function onGetT2Master(ajaxData) { $NC.setInitGridData(G_GRDT2MASTER, ajaxData); if (G_GRDT2MASTER.data.getLength() > 0) { if ($NC.isNull(G_GRDT2MASTER.lastKeyVal)) { $NC.setGridSelectRow(G_GRDT2MASTER, 0); } else { $NC.setGridSelectRow(G_GRDT2MASTER, { selectKey: "INBOUND_NO", selectVal: G_GRDT2MASTER.lastKeyVal }); } } else { $NC.setGridDisplayRows("#grdT2Master", 0, 0); } } /** * ์ž…๊ณ ์ค‘๋Ÿ‰๋“ฑ๋ก ํƒญ ํ•˜๋‹จ ๊ทธ๋ฆฌ๋“œ์— ๋ฐ์ดํ„ฐ ํ‘œ์‹œ์ฒ˜๋ฆฌ */ function onGetT1Detail(ajaxData) { $NC.setInitGridData(G_GRDT1DETAIL, ajaxData); if (G_GRDT1DETAIL.data.getLength() > 0) { if ($NC.isNull(G_GRDT1DETAIL.lastKeyVal)) { $NC.setGridSelectRow(G_GRDT1DETAIL, 0); } else { $NC.setGridSelectRow(G_GRDT1DETAIL, { selectKey: "ITEM_CD", selectVal: G_GRDT1DETAIL.lastKeyVal }); } } else { $NC.setGridDisplayRows("#grdT1Detail", 0, 0); } G_GRDT1DETAIL.view.getCanvasNode().focus(); } /** * ์ž…๊ณ ์ค‘๋Ÿ‰๋“ฑ๋ก ํƒญ ํ•˜๋‹จ ๊ทธ๋ฆฌ๋“œ์— ๋ฐ์ดํ„ฐ ํ‘œ์‹œ์ฒ˜๋ฆฌ */ function onGetT1Sub(ajaxData) { $NC.setInitGridData(G_GRDT1SUB, ajaxData); if (G_GRDT1SUB.data.getLength() > 0) { if ($NC.isNull(G_GRDT1SUB.lastKeyVal)) { $NC.setGridSelectRow(G_GRDT1SUB, 0); } else { $NC.setGridSelectRow(G_GRDT1SUB, { selectKey: "ITEM_CD", selectVal: G_GRDT1SUB.lastKeyVal }); } } else { $NC.setGridDisplayRows("#grdT1Sub", 0, 0); } G_GRDT1SUB.view.getCanvasNode().focus(); } /** * ์ €์žฅ ์ฒ˜๋ฆฌ ์„ฑ๊ณต ํ–ˆ์„ ๊ฒฝ์šฐ ์ฒ˜๋ฆฌ */ function onSave(ajaxData) { var lastRowData = G_GRDT1MASTER.data.getItem(G_GRDT1MASTER.lastRow); _Inquiry(); G_GRDT1MASTER.lastKeyVal = lastRowData.INBOUND_NO; } /** * ์ €์žฅ ์ฒ˜๋ฆฌ ์‹คํŒจ ํ–ˆ์„ ๊ฒฝ์šฐ ์ฒ˜๋ฆฌ */ function onSaveError(ajaxData) { $NC.onError(ajaxData); } /** * ๊ฒ€์ƒ‰ํ•ญ๋ชฉ ๊ฐ’ ๋ณ€๊ฒฝ์‹œ ํ™”๋ฉด ํด๋ฆฌ์–ด */ function onChangingCondition() { $NC.setInitGridVar(G_GRDT1MASTER); $NC.setInitGridData(G_GRDT1MASTER); $NC.setGridDisplayRows("#grdT1Master", 0, 0); $NC.setInitGridVar(G_GRDT1DETAIL); $NC.setInitGridData(G_GRDT1DETAIL); $NC.setGridDisplayRows("#grdT1Detail", 0, 0); $NC.setInitGridVar(G_GRDT1SUB); $NC.setInitGridData(G_GRDT1SUB); $NC.setGridDisplayRows("#grdT1Sub", 0, 0); $NC.setInitGridVar(G_GRDT2MASTER); $NC.setInitGridData(G_GRDT2MASTER); $NC.setGridDisplayRows("#grdT2Master", 0, 0); } /** * ๊ฒ€์ƒ‰์กฐ๊ฑด์˜ ์‚ฌ์—…๋ถ€ ๊ฒ€์ƒ‰ ํŒ์—… ํด๋ฆญ */ function showUserBuPopup() { $NP.showUserBuPopup({ P_USER_ID: $NC.G_USERINFO.USER_ID, P_BU_CD: "%" }, onUserBuPopup, function() { $NC.setFocus("#edtQBu_Cd", true); }); } /** * ๊ฒ€์ƒ‰์กฐ๊ฑด์˜ ๋ธŒ๋žœ๋“œ ๊ฒ€์ƒ‰ ํŒ์—… ํด๋ฆญ */ function showBuBrandPopup() { var BU_CD = $NC.getValue("#edtQBu_Cd"); $NP.showBuBrandPopup({ P_BU_CD: BU_CD, P_BRAND_CD: "%" }, onBuBrandPopup, function() { $NC.setFocus("#edtQBrand_Cd", true); }); } /** * ์‚ฌ์—…๋ถ€ ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ * * @param seletedRowData */ function onUserBuPopup(resultInfo) { if (!$NC.isNull(resultInfo)) { $NC.setValue("#edtQBu_Cd", resultInfo.BU_CD); $NC.setValue("#edtQBu_Nm", resultInfo.BU_NM); } else { $NC.setValue("#edtQBu_Cd"); $NC.setValue("#edtQBu_Nm"); $NC.setFocus("#edtQBu_Cd", true); } $NC.setValue("#edtQBrand_Cd"); $NC.setValue("#edtQBrand_Nm"); onChangingCondition(); } /** * ๋ธŒ๋žœ๋“œ ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ * * @param seletedRowData */ function onBuBrandPopup(resultInfo) { if (!$NC.isNull(resultInfo)) { $NC.setValue("#edtQBrand_Cd", resultInfo.BRAND_CD); $NC.setValue("#edtQBrand_Nm", resultInfo.BRAND_NM); } else { $NC.setValue("#edtQBrand_Cd"); $NC.setValue("#edtQBrand_Nm"); $NC.setFocus("#edtQBrand_Cd", true); } onChangingCondition(); } /** * ๊ฒ€์ƒ‰์กฐ๊ฑด์˜ ๊ณต๊ธ‰์ฒ˜ ๊ฒ€์ƒ‰ ์ด๋ฏธ์ง€ ํด๋ฆญ */ function showVendorPopup() { var CUST_CD = $NC.getValue("#edtQCust_Cd"); $NP.showVendorPopup({ queryParams: { P_CUST_CD: CUST_CD, P_VENDOR_CD: "%", P_VIEW_DIV: "1" } }, onVendorPopup, function() { $NC.setFocus("#edtQVendor_Cd", true); }); } function onVendorPopup(resultInfo) { if (!$NC.isNull(resultInfo)) { $NC.setValue("#edtQVendor_Cd", resultInfo.VENDOR_CD); $NC.setValue("#edtQVendor_Nm", resultInfo.VENDOR_NM); } else { $NC.setValue("#edtQVendor_Cd"); $NC.setValue("#edtQVendor_Nm"); $NC.setFocus("#edtQVendor_Cd", true); } onChangingCondition(); }
// lesson 3 import _ from "lodash"; const normalize = (obj) => { obj.name = obj.name.substr(0, 1).toUpperCase() + obj.name.substr(1).toLowerCase(); obj.description = obj.description.toLowerCase(); return obj; }; export default normalize; // lesson 4 const is = (obj1, obj2) => { if ((obj1.name === obj2.name) && (obj1.state === obj2.state) && (obj1.website === obj2.website)) { return true; } return false; }; export default is; // lesson 5 const getDomainInfo = (domain) => { const info = {}; if (domain.startsWith('https://')) { info.scheme = 'https'; } else { info.scheme = 'http'; } info.name = _.last(domain.split('/')); return info; }; export default getDomainInfo; // lesson 6 const countWords = (str) => { const arrayOfWords = str.toLowerCase().split(' '); const result = {}; for (const word of arrayOfWords) { result[word] = (result[word] ?? 0) + 1; } return result; }; export default countWords; // lesson 7 const pick = (obj, arr) => { const result = {}; for (const item of arr) { if (_.has(obj, item)) { result[item] = obj[item]; } } return result; }; export default pick; // lesson 8 const get = (obj, arr) => { if (arr.length === 1) { if (Object.prototype.hasOwnProperty.call(obj, String(arr[0]))) { return obj[String(arr[0])]; } else { return null; } } else { let tempObj = obj; for (let i = 0; i < arr.length; i += 1) { if (!Object.prototype.hasOwnProperty.call(tempObj, String(arr[i]))) { return null; } else { tempObj = tempObj[arr[i]]; } } return tempObj; } }; export default get; // lesson 9 const fill = (obj1, arr, obj2) => { if (arr.length === 0) { Object.assign(obj1, obj2); } else { for (let i = 0; i < arr.length; i += 1) { obj1[arr[i]] = obj2[arr[i]]; } } return obj1; }; export default fill; // lesson 10 const cloneDeep20 = (obj) => { const result = {}; for (const item in obj) { if (!_.isObject(item)) { result[item] = _.clone(obj[item]); } else { result[item] = _.clone(cloneDeep(item)); } } return result; }
// This references the #pointr id tag in your HTML markup. let pointr = document.getElementById('pointr'); document.addEventListener('mousemove', function(e) { var x = e.clientX; var y = e.clientY; pointr.style.left = x + 'px'; pointr.style.top = y + 'px'; } );
// ไบ‘ๅ‡ฝๆ•ฐๅ…ฅๅฃๆ–‡ไปถ const cloud = require('wx-server-sdk') cloud.init() const db = cloud.database() // ไบ‘ๅ‡ฝๆ•ฐๅ…ฅๅฃๅ‡ฝๆ•ฐ exports.main = async(event, context) => { var result var userInfo if (event.validateUserResult) { userInfo = event.validateUserResult.userInfo if (event.validateUserResult.isAdmin) { result = await db.collection('che').get() } else if (event.validateUserResult.isAuthUser && userInfo.base) { result = await db.collection('che').where({ base: userInfo.base }).get() } } if (!result) {result = {data:[]}} return result }
import React from "react"; import { makeStyles } from '@material-ui/core/styles'; import CardMedia from '@material-ui/core/CardMedia'; import Typography from '@material-ui/core/Typography'; import Grid from '@material-ui/core/Grid'; import IconButton from '@material-ui/core/IconButton'; import FacebookIcon from '@material-ui/icons/Facebook'; import TwitterIcon from '@material-ui/icons/Twitter'; import InstagramIcon from '@material-ui/icons/Instagram'; const useStyles = makeStyles((theme) => ({ bannerContainer: { height: '100vh', width: '100%', backgroundPosition: 'center bottom', backgroundSize: 'cover', backgroundImage: 'url(https://samahan.stdcdn.com/21-22/landing.png), linear-gradient(to right, #1637BC, #2D8AEA)', paddingLeft: 'clamp(50px, 10vw, 100px)', paddingRight: 'clamp(50px, 10vw, 100px)' }, bannerTextContainer: { position: 'relative', float: 'right', fontWeight: 20, color: theme.palette.secondary.main, zIndex: 3 }, bannerText: { textAlign: 'right', zIndex: 3, margin: 0, fontFamily: 'Open Sans', fontWeight: 300 }, bannerHeader: { textAlign: 'right', fontSize: '7.5vw', margin: 0 }, })); const List = () => { // Get the data of the current list. const classes = useStyles(); return ( <div className={classes.bannerContainer}> <Grid container direction="column" justify="center" style={{ height: '80%', paddingTop: 20 }} spacing={4}> <Grid item> <CardMedia component="img" image="https://samahan.stdcdn.com/21-22/OTF-2_white.png" style={{ width: 'clamp(250px, 60vw, 60%)' }} /> </Grid> <Grid item style={{ color: 'white', fontStyle: 'italic' }}> <Typography>The future is ours.</Typography> <Typography>We decide what is next for us.</Typography> <Typography>We no longer wait for the future;</Typography> <Typography>we own the future.</Typography> </Grid> <Grid item style={{ color: 'white' }}> <Grid container spacing={2}> <Grid item> <IconButton color="secondary" onClick={() => window.open('https://www.facebook.com/AdDUSAMAHAN/', '_blank').focus()}> <FacebookIcon /> </IconButton> </Grid> <Grid item> <IconButton color="secondary" onClick={() => window.open('https://twitter.com/addusamahan/', '_blank').focus()}> <TwitterIcon /> </IconButton> </Grid> <Grid item> <IconButton color="secondary" onClick={() => window.open('https://instagram.com/samahan_ateneo/', '_blank').focus()}> <InstagramIcon /> </IconButton> </Grid> </Grid> </Grid> </Grid> </div> ); }; export default List;
/******** Korea Main Jquery 2017 *********/ /* visual */ $(function(){ var visualArea = $("#visualarea .area"); var visualCont = visualArea.find(".txt"); var current = 0; var active; var returnNodes; var last; visualCont.css({"opacity":0}).hide().eq(0).css({"opacity":1}).show(); visualCont.each(function(i){ $(this).attr("id","area_" + i); visualArea.find(".control").append("<a href=#area_"+ i +">" + (i+1) + "</a>"); $("#visual").append("<div id=area_"+ i +"></div>"); last = i; }); $("#visual > div").css({"opacity":0}).eq(0).css({"opacity":1}); visualArea.find(".control a[href='#area_0']").addClass("active"); function _rotate(){ clearInterval(returnNodes); returnNodes = setInterval(function(){ if(current === last){ current = 0; }else{ current = current + 1; } visualArea.find(".control a").removeClass("active"); visualArea.find(".control a[href='#area_"+ current +"']").addClass("active"); $("#visual").find("div").stop(true,true).animate({"opacity":0, "z-index":0}, 800); $("#visual").find("#area_" + current).stop(true,true).animate({"opacity":1, "z-index":1}, 800); visualCont.stop(true,true).animate({"opacity":0}, 1000).hide(); visualArea.find("#area_" + current).show().stop(true,true).animate({"opacity":1}, 1000); },10000); } if(last != 0){ _rotate(); } visualArea.find(".control a").click(function(event){ if(active != $(this).attr("href")){ clearInterval(returnNodes); active = $(this).attr("href"); visualArea.find(".control a").removeClass("active"); $(this).addClass("active"); $("#visual").find("div").stop(true,true).animate({"opacity":0, "z-index":0}, 800); $("#visual").find(active).stop(true,true).animate({"opacity":1, "z-index":1}, 800); visualCont.stop(true,true).animate({"opacity":0}, 1000).hide(); visualArea.find(active).show().stop(true,true).animate({"opacity":1}, 1000); } event.preventDefault(); }); visualArea.find("#control a").click(function(){ if($(this).attr("class").indexOf("icon-play") > -1) { _rotate(); $(this).attr("class", "icon-pause"); $(this).find("span").text("์ž๋™์žฌ์ƒ ์ค‘์ง€"); } else if($(this).attr("class").indexOf("icon-pause") > -1){ clearInterval(returnNodes); $(this).attr("class", "icon-play"); $(this).find("span").text("์ž๋™์žฌ์ƒ ์‹œ์ž‘"); } }); }); $(document).on("click", "#control a", function(){ }); /* days info */ $(function(){ var wrap = $(".service"); var day = $(".days"); var dayObj = day.find(".days_info"); var nssao = $(".nssao"); var nssaoObj = nssao.find(".nssao_info"); var responsive = $(document).width(); var grab = $(".popup_wrap").width(); var active; $(window).resize(function(){ responsive = $(document).width(); grab = $(".popup_wrap").width(); _objControl(); }); function _objControl(){ if(responsive > 980){ wrap.css({"width":"243px"}); dayObj.css({"width":"auto"}).hide(); nssaoObj.css({"width":"auto"}).hide(); wrap.find(".sv_tab").unbind("click"); wrap.find(".sv_tab").bind("click",function(event){ active = $(this).attr("id"); $("." + active).slideToggle(function(){ if($("." + active).is(":visible")){ $("#" + active).find("span").addClass("active").text("-"); }else{ $("#" + active).find("span").removeClass("active").text("+"); } }); event.preventDefault(); }); }else if($("html").attr("id") != "ie8"){ if(responsive < 628){ wrap.css({"width":"100%"}); dayObj.css({"width":"100%"}); nssaoObj.css({"width":"100%"}); }else{ wrap.css({"width":(grab-282)+"px"}); dayObj.css({"width":(grab-282)+"px"}); nssaoObj.css({"width":(grab-282)+"px"}); } dayObj.hide(); nssaoObj.show(); wrap.find(".sv_tab").unbind("click"); wrap.find(".sv_tab").bind("click",function(event){ active = $(this).attr("id"); dayObj.hide(); nssaoObj.hide(); $("." + active).show(); if($("." + active).is(":visible")){ $("#" + active).find("span").addClass("active").text("-"); }else{ $("#" + active).find("span").removeClass("active").text("+"); } event.preventDefault(); }); } } _objControl(); }); /* ๋…ผ๋ฌธ, ์ฝœ๋กœํ€ด์›€ */ function paperBoard(wrap){ var wrap = $(wrap); var objGroup = wrap.find("ul") var obj = wrap.find(".obj"); var control = wrap.find(".control"); var objNum = objGroup.find("li").length; var objStartNum = 1; control.find(".num strong").text(objStartNum); control.find(".num span").text(objNum); objGroup.find("li").hide().eq(0).show(); control.find("a").click(function(event){ if($(this).attr("class") === "prev"){ if(objStartNum === 1){ objStartNum = objNum; }else{ objStartNum = objStartNum-1; } } if($(this).attr("class") === "next"){ if(objStartNum === objNum){ objStartNum = 1; }else{ objStartNum = objStartNum+1; } } control.find(".num strong").text(objStartNum); objGroup.find("li").hide().eq(objStartNum-1).show().find("a").focus(); event.preventDefault(); }); }
$('.link-select').select2({ ajax: { url: $('.link-select').data('url'), delay: 250, type: 'POST', dataType: 'json', data: function (params) { var query = { name: params.term, } return query; }, processResults: function (data) { return { results: data.topics }; } }, templateResult: formatState, templateSelection: template, minimumInputLength: 1, escapeMarkup: function (markup) { return markup; }, }); function formatState(state) { if (!state.id) { return state.name; } var $state = $( '<span>' + state.name + '</span>' ); return $state; }; function template(data) { return data.name; } $(".link-select").select2("data", $(".link-select").select2('data')[0]['id']); $('body').on('keyup','.select2-search__field',function() { $(this).parent().parent().parent().parent().find(".link-select option ").val($(this).val()); $(this).parent().parent().parent().parent().find(".link-select").next().find('.selection').find('.select2-selection').find(".select2-selection__rendered").html($(this).val()); });
import React, { Component } from 'react'; import { Route, Link,Router } from 'react-router-dom'; import './App.css'; import Users from "./users"; import Moment from 'moment'; import idBox from "./IDbox"; import Groups from "./groups"; import Settings from "./settings"; import Select from 'react-select'; import DyDrop from "./DropDown"; import history from './history'; import DyTree from "./tree"; import Pane from "./pane" import TreeView from "./TreeView"; import Document from "./documents"; const Home = () => ( <div> <h2> Home </h2> </div> ); const Airport = () => ( <div> <ul> <li>Jomo Kenyatta</li> <li>Tambo</li> <li>Murtala Mohammed</li> </ul> </div> ); const City = () => ( <div> <ul> <li>San Francisco</li> <li>Istanbul</li> <li>Tokyo</li> </ul> </div> ); class App extends Component { constructor(props) { super(props); console.log("start"); // ["name"] const key = localStorage.key; const group = localStorage.group; const groupId = localStorage.groupId; this.state = { key: key, group: group ? group: " ", groupId: groupId ? groupId: " ", }; } onChangeDrop = (value) => { console.log("event"); this.setState({ group: value}); } settingsChange = (value) => { console.log("here"); const { key, group,groupId } = value; localStorage.setItem('key', key); localStorage.setItem('group', group); localStorage.setItem('groupId', groupId); //this.setState({ group: group}); //this.setState({ groupId: groupId}); this.setState({ key: key}); console.log("here2"); } componentDidMount() { const key = localStorage.getItem('key'); const group = localStorage.getItem('group'); const groupId = localStorage.getItem('groupId'); this.setState({ group: group}); this.setState({ groupId: groupId}); this.setState({ key: key}); } handleChange = (field, value) =>{ } onSubmit = (st) => { const { key, group,groupId } = st; localStorage.setItem('key', key); localStorage.setItem('group', group); localStorage.setItem('groupId', groupId); this.setState({ group: group}); this.setState({ groupId: groupId}); this.setState({ key: key}); } onIDChange = (event) => { this.setState({ uid: event.target.value }); } render() { return ( <div> <nav className="navbar navbar-expand-lg navbar-light bg-light"> <ul className="navbar-nav"> <li className="nav-item"> <Link className="nav-link" to="/groups">Table</Link> </li> <li className="nav-item"> <Link className="nav-link" to="/tree">Tree</Link> </li> <li className="nav-item"> <Link className="nav-link" to="/settings">Settings</Link> </li> </ul> <div className="navbar-collapse collapse w-100 order-3 dual-collapse2"> <ul className="navbar-nav ml-auto"> <li className="nav-item"> <DyDrop onChange={this.onChangeDrop} value={{group:this.state.group,groupId:this.state.groupId}} /><input type="text" value={this.state.key+"a"} autoFocus="autofocus" onChange={this.onIDChange}/> </li> </ul> </div> </nav> <Route path="/users/:uid?" render={(props) => <Users {...props} state={this.state} />} /> <Route path="/document/:uri?" render={(props) => <Document {...props} state={this.state} />} /> <Route path="/groups/:gid?" render={(props) => <Groups {...props} state={this.state} />} /> <Route path="/tree/:gid?/:uid?" render={(props) => <TreeView {...props} state={this.state} />} /> <Route path="/settings" render={(props) => <Settings {...props} onSubmit={this.settingsChange} state={this.state} />} /> </div> ); } } export default App;
const passport = require('passport'); const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; const Users = require('../users/users.entity'); const configAuth = require('../../config/config.js'); passport.use(new GoogleStrategy({ clientID: configAuth.GOOGLE_AUTH.clientID, clientSecret: configAuth.GOOGLE_AUTH.clientSecret, callbackURL: configAuth.GOOGLE_AUTH.callbackURL }, function(token, refreshToken, profile, done) { console.log("token by passport",token); process.nextTick(function() { // checking for the existence of user details in database Users.findOne({ username: profile.emails[0].value }, function(err, user) { if (err) return done(err); if (user) { return done(null, user); } // otherwise creating a new record of user details in database var newUser = new Users(); newUser.username = profile.emails[0].value; newUser.token = token; newUser.name = profile.displayName; newUser.email = profile.emails[0].value; newUser.profilePic = profile.photos[0].value; newUser.save(function(err) { if (err) return done(err); return done(null, newUser); }); return done(null, false); }); }); })); module.exports = passport
exports.up = function(knex) { return knex.schema.createTable('projetos', table => { table.increments('id').primary(); table .string('nome') .notNull() .unique(); }); }; exports.down = function(knex) { return knex.schema.dropTable('projetos'); };
/** @type {import('tailwindcss').Config} */ module.exports = { darkMode: 'class', content: [`./src/pages/**/*.{js,jsx,ts,tsx}`, `./src/templates/**/*.{js,jsx,ts,tsx}`, `./src/components/**/*.{js,jsx,ts,tsx}`], theme: { fontFamily: { sans: ['Mona Sans', `-apple-system`, `system-ui`, `BlinkMacSystemFont`, `Segoe UI`, `Roboto`, `Helvetica Neue`, `Arial`, `sans-serif`], serif: [`calluna`, `-apple-system`, `system-ui`, `BlinkMacSystemFont`, `Segoe UI`, `serif`], mono: [`ui-monospace`, `SFMono-Regular`, `Menlo`, `Monaco`, `Consolas`, `Liberation Mono`, `Courier New`, `monospace`], }, colors: { transparent: `transparent`, current: `currentColor`, black: `#04080F`, white: `#FBFBFB`, light: `#F5F5F5`, slate: `#63768D`, 'slate-light': `#AAB8C2`, blue: `#00FFEE`, pink: `#FF00BB`, purple: `#9588FC`, yellow: `#FFF200`, green: `#C2FE0C`, aqua: `#29FCA5`, 'purple-light': `#B3ACE3`, 'purple-dark': `#1B1B24`, 'purple-slate': `#333345`, red: `#FF0000`, }, fontSize: { xs: ['.8rem', '1.4'], sm: ['1rem', '1.4'], base: ['1.25rem', '1.5'], lg: ['1.363rem', '1.2'], xl: ['1.663rem', '1.2'], '2xl': ['1.953rem', '1.2'], '3xl': ['2.441rem', '1.2'], '4xl': ['2.752rem', '1.2'], '5xl': ['3.815rem', '1.2'], '6xl': ['4.168rem', '1'], '7xl': ['4.5rem', '1'], '8xl': ['6rem', '1'], }, extend: {}, }, plugins: [require(`tailwindcss`), require(`precss`), require(`autoprefixer`)], }
'use strict'; const Service = require('egg').Service; const path = require('path'); const fs = require('fs'); const request = require('request'); const WebHDFS = require('webhdfs'); const xlsx = require('xlsx'); const PassThrough = require('stream').PassThrough; const hdfs = WebHDFS.createClient({ user: 'hdfs', host: '192.168.1.212', port: 50070, path: 'webhdfs/v1', }); class WebhdfsService extends Service { getDownloadPath(filePath) { return encodeURI(this.app.config.remote.webhdfs + filePath); } async downloadFile(remoteFilePath, downloadFolderPath) { const url = this.getDownloadPath(remoteFilePath) + '?op=OPEN'; const fileName = path.basename(remoteFilePath); const downloadFilePath = path.resolve(downloadFolderPath, fileName); await this.ctx.helper.requestFile(url, downloadFilePath); return { downloadFilePath, fileName, }; } downloadFileWithStream(remoteFilePath) { const url = this.getDownloadPath(remoteFilePath) + '?op=OPEN'; return request(url); } async getList(filePath) { const url = this.getDownloadPath(filePath) + '?op=LISTSTATUS'; const { FileStatuses: { FileStatus }, } = await this.ctx.helper.requestGet(url); return FileStatus.map(one => ({ remoteFilePath: filePath + '/' + one.pathSuffix, type: one.type, })); } async downloadFolder(remoteFilePath, downloadPath) { if (!fs.existsSync(downloadPath)) { fs.mkdirSync(downloadPath); } const dirName = path.basename(remoteFilePath); const folderPath = path.resolve(downloadPath, dirName); const arr = await this.getList(remoteFilePath); await this.download(arr, folderPath); } async downloadMultiple(arr, downloadFolderPath) { const folders = arr.filter(one => one.type !== 'FILE'); const files = arr.filter(one => one.type === 'FILE'); const folderPromises = folders.map(({ remoteFilePath }) => this.downloadFolder(remoteFilePath, downloadFolderPath) ); const filePromises = files.map(one => this.downloadFile(one.remoteFilePath, downloadFolderPath) ); await Promise.all([ ...filePromises, ...folderPromises ]); } async uploadOne(localFileStream, pathToUpload) { await new Promise((resolve, reject) => { const remoteFileStream = hdfs.createWriteStream( encodeURI(pathToUpload + '/' + localFileStream.filename) ); localFileStream.pipe(remoteFileStream); remoteFileStream.on('error', function onError(err) { if ( [ 'HPE_LF_EXPECTED', 'HPE_INVALID_HEADER_TOKEN' ].includes(err.code) ) { resolve(); return; } console.log('ๅ‡บ้”™', err, err.code); reject(err); }); remoteFileStream.on('finish', function onFinish() { console.log('ๅฎŒๆˆ' + localFileStream.filename); resolve(); }); }); } async upload(localFileStream, pathToUpload, getJson, piciId) { if (getJson) { const p1 = this.getExcelJsonFromStream(localFileStream); const p2 = this.uploadOne(localFileStream, pathToUpload); const [ json ] = await Promise.all([ p1, p2 ]); const newJson = this.ctx.service.quota.transformJson(json); await this.ctx.service.quota.createOrUpdate(newJson, piciId); return newJson; } await this.uploadOne(localFileStream, pathToUpload); } async getJsonFromHdfs(filePath) { const url = this.getDownloadPath(filePath) + '?op=OPEN'; const json = await this.getExcelJsonFromStream(request(url)); return json; } getExcelJsonFromStream(localFileStream) { const pass = new PassThrough(); return new Promise(resolve => { const buf = []; localFileStream.pipe(pass); pass.on('data', chunk => { buf.push(chunk); }); pass.on('end', function() { const buffer = Buffer.concat(buf); const { SheetNames, Sheets } = xlsx.read(buffer, { type: 'buffer', // cellDates: true, // cellNF: false, // cellText: false, }); const res = xlsx.utils.sheet_to_json(Sheets[SheetNames[0]], { raw: false, }); resolve(res); }); }); } async download(arr, downloadFolderPath) { if (!fs.existsSync(downloadFolderPath)) { fs.mkdirSync(downloadFolderPath); } const isSingleFolder = arr.length === 1 && arr[0].type !== 'FILE'; const compressPath = isSingleFolder ? path.resolve(downloadFolderPath, path.basename(arr[0].remoteFilePath)) : downloadFolderPath; await this.downloadMultiple(arr, downloadFolderPath); return { compressPath, fileName: path.basename(compressPath) + '.zip', filePath: compressPath + '.zip', isSingleFolder, }; } } module.exports = WebhdfsService;
import { displayTeacherInfo } from './app.js'; import { displayStudentInfo } from './app.js'; const requestingLogingInfos = (usernameValue, passwordValue) => { const user = { "username": usernameValue, "password": passwordValue } let chosenData = document.querySelector('select').value; let endpoint = ""; if (chosenData == "Teacher") { endpoint = "http://localhost:8080/login/teacher"; fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(user) }) .then(response => response.json()) // .then(JSONresponse => console.log(JSONresponse)) .then(JSONresponse => displayTeacherInfo(JSONresponse)) .catch(err => console.error(err)); } else { endpoint = "http://localhost:8080/login/student"; fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(user) }) .then(response => response.json()) //.then(JSONresponse => console.log(JSONresponse)) .then(JSONresponse => displayStudentInfo(JSONresponse)) .catch(err => console.error(err)); } } export { requestingLogingInfos }
/** * Created by myl17 on 2017/9/12. */ module.exports = { entry: './app.js', output: { filename: 'bundle.js' } }
jQuery(function($){ $("#submit_payment_confirmation").click(function(){ if ( $("#order-number").val() == '' ) { alert("Error : Masukan Order Number"); $("#order-number").focus(); return false; } else if ( $("#payment-code").val() == '' ) { alert("Error : Masukan Kode Pembayaran"); $("#payment-code").focus(); return false; } else if ( $("#payment-nominal").val() == '' ) { alert("Error : Masukan Nominal Pembayaran"); $("#payment-nominal").focus(); return false; } else if ( $("#transfer-date").val() == '' ) { alert("Error : Masukan Tanggal Transfer"); $("#transfer-date").focus(); return false; } else if ( $("#destination-bank").val() == '' ) { alert("Error : Pilih Bank Tujuan"); return false; } else if ( $("#bank").val() == '' ) { alert("Error : Masukan Bank Pengirim"); $("#bank").focus(); return false; } else if ( $("#bank-name").val() == '' ) { alert("Error : Masukan Atas Nama Rekening yang Digunakan"); $("#bank-name").focus(); return false; } else if ( $("#payment-file").val() == '' ) { alert("Error : Upload Bukti Pembayaran"); $("#payment-file").focus(); return false; } else { return true; } }); });
๏ปฟ WAF.onAfterInit = function onAfterInit() {// @lock // @region namespaceDeclaration// @startlock var btnAdd = {}; // @button var btnCompleted = {}; // @button var btnAll = {}; // @button var btnActive = {}; // @button // @endregion// @endlock // eventHandlers// @lock btnAdd.click = function btnAdd_click (event)// @startlock {// @endlock sources.items.addNewElement; sources.items.name = textFieldTodo.getValue(); sources.items.save(); };// @lock btnCompleted.click = function btnCompleted_click (event)// @startlock {// @endlock sources.items.filterQuery('done = true'); };// @lock btnAll.click = function btnAll_click (event)// @startlock {// @endlock sources.items.filterQuery(''); sources.item. };// @lock btnActive.click = function btnActive_click (event)// @startlock {// @endlock sources.items.filterQuery('done = false'); };// @lock // @region eventManager// @startlock WAF.addListener("btnAdd", "click", btnAdd.click, "WAF"); WAF.addListener("btnCompleted", "click", btnCompleted.click, "WAF"); WAF.addListener("btnAll", "click", btnAll.click, "WAF"); WAF.addListener("btnActive", "click", btnActive.click, "WAF"); // @endregion };// @endlock
import React from "react"; import "components/InterviewerList.scss"; import InterviewerListItem from "./InterviewerListItem"; import PropTypes from "prop-types"; export default function InterviewerList(props) { const parsedInterviewers = props.interviewers.map((inter) => { return ( <InterviewerListItem key={inter.id} name={inter.name} avatar={inter.avatar} selected={inter.id === props.interviewer} setInterviewer={(event) => props.onChange(inter.id)} /> ); }); return ( <section className="interviewers"> <h4 className="interviewers__header text--light">Interviewer</h4> <ul className="interviewers__list">{parsedInterviewers}</ul> </section> ); } InterviewerList.propTypes = { interviewers: PropTypes.array.isRequired, };
๏ปฟ $('#ratingForm .ratingRadio').change(function () { $('#ratingForm').submit(); });
let output = ""; for (let i = 100; i <= 200; i++) { //Clear output first every time output = ""; //Check for first condition if (i % 3 === 0) { output += "Loopy"; } if (i % 4 === 0) { output += "Lighthouse"; } if (!(i % 3 === 0 || i % 4 === 0)) { output = i; } console.log(output); }
const base_url = 'http://localhost:3000' $(document).ready(() => { auth() $('#login').on('click', (e) => { e.preventDefault(); $('#register-form').hide() $('#login-form').show() }) $('#register').on('click', (e) => { e.preventDefault(); $('#login-form').hide() $('#register-form').show() }) $('#register-form').on('submit', (e) => { e.preventDefault(); register() }) $('#login-form').on('submit', (e) => { e.preventDefault(); login() }) $('#logout').on('click', (e) => { e.preventDefault(); logout() }) $('#favorite').on('click', (e) => { e.preventDefault(); favorite() }) $('#home').on('click', (e) => { e.preventDefault(); home() }) $("#") }) function auth() { if (!localStorage.getItem('access_token')) { $('#login-form').show() $('#register-form').hide() $('#card-cat').hide() $('#home').hide() $('#logout').hide() $('#login').show() $('#register').show() $('#favorite').hide() } else { $('#login-form').hide() $('#register-form').hide() $('#card-cat').show() $('#home').show() $('#logout').show() $('#login').hide() $('#register').hide() $('#favorite').show() getApi() } $('#loginFail').hide() } function register() { const name = $('#register-name').val() const email = $('#register-email').val() const password = $('#register-password').val() $.ajax({ url: base_url + '/register', method: 'post', data: { name, email, password } }).done(response => { console.log(response) auth() }).fail((xhr, text) => { console.log(xhr, text) }).always(_ => { console.log('register') }) } function login() { const email = $('#login-email').val() const password = $('#login-password').val() $.ajax({ url: base_url + '/login', method: 'post', data: { email, password } }).done(response => { localStorage.setItem('access_token', response.access_token) localStorage.setItem('name', response.name) auth() console.log(response) }).fail((xhr, text) => { $('#loginFail').text(xhr.responseJSON.errors) $('#loginFail').show() $('#login-email').val('') $('#login-password').val('') console.log(xhr.responseJSON) }).always(_ => { console.log('success login') }) } function logout() { var auth2 = gapi.auth2.getAuthInstance(); auth2.signOut().then(function () { console.log('User signed out.'); }); localStorage.clear() auth() } function onSignUp(googleUser) { var id_token = googleUser.getAuthResponse().id_token; $.ajax({ url: base_url + '/RegisterGoogle', method: 'post', data: { googleToken: id_token } }).done(response => { console.log('berhasil masuk') var auth2 = gapi.auth2.getAuthInstance(); auth2.signOut().then(function () { console.log('User signed out.'); }); auth() }).fail((xhr, text) => { console.log(xhr, text) }) } function onSignIn(googleUser) { var id_token = googleUser.getAuthResponse().id_token; $.ajax({ url: base_url + '/LoginGoogle', method: 'post', data: { googleToken: id_token } }) .done(response => { localStorage.setItem('access_token', response.access_token) localStorage.setItem('nama', response.name) localStorage.setItem('id', response.id) $('#login-email').val('') $('#login-password').val('') auth() }) .fail(err => { console.log(err, "ini error") }) } function getApi() { $.ajax({ url: base_url + '/home', method: "GET", headers: { access_token: localStorage.getItem("access_token") } }) .done((response) => { console.log(response) $("#card-cat").empty() $("#card-cat").append( `<img class="card-img-top img-thumbnail" src="${response.data}" alt="Card image cap" style="height : 70%"> <div class="card-body"> <h1 class="card-title">Cats</h1> <h5 class="card-text">${response.result}</h5> <a href="#" class="btn btn-info" id="random-pict">Random Pict</a> <a href="#" class="btn btn-info" id="add-favorite">Add To Favorite</a> </div>` ) $("#background-web").attr("background", response.fact) $('#random-pict').on('click', (e) => { e.preventDefault() random() }) $('#add-favorite').on('click', (e) => { e.preventDefault() addFav(response.data, response.result, response.fact) }) }) .fail((xhr, text) => { console.log(xhr, text) }) .always(() => { console.log('INI DATA KU') }) } function random() { console.log('trigger random') getApi() } function addFav(data, result, fact) { $.ajax({ url: base_url + '/addFav', method: 'post', data: { data, result, fact, UserId: localStorage.getItem('id') }, headers: { access_token: localStorage.getItem("access_token") } }) .done(response => { console.log(response) }) .fail((xhr, text) => { console.log(xhr, text) }) } function favorite() { // console.log('trigger favorite') $.ajax({ url: base_url + '/findFav', method: 'get', headers: { access_token: localStorage.getItem("access_token"), UserId: localStorage.getItem('id') } }) .done(response => { console.log(response) $("#card-cat").empty() // for(let i of response){ // console.log(i) // } response.forEach(el => { $("#card-cat").append( `<img class="card-img-top img-thumbnail" src="${el.data}" alt="Card image cap" style="height : 70%"> <div class="card-body" style="background-color:black"> <h1 class="card-title">Cats</h1> <h5 class="card-text">${el.result}</h5> <h5 class="card-text">${el.fact}</h5> <a href="#" class="btn btn-info" id="add-favorite" onclick="deleteFav(${el.id})">Delete</a> </div><br>` ) }) }) .fail((xhr, text) => { console.log(xhr, text) }) } function home() { auth() } function deleteFav(id) { $.ajax({ url: base_url + '/deleteFav', method: 'delete', headers: { access_token: localStorage.getItem("access_token"), id: id } }) .done(response => { // console.log(response) favorite() }) .fail((xhr, txt) => { console.log(xhr, txt) }) console.log('id delete', id) }