text
stringlengths
7
3.69M
import React, { Profiler, memo } from 'react' const onRender = (id, phase, actualDuration) => { console.log(id, phase, actualDuration) } const Children = ({ resource }) => { console.log(resource) const n = resource.num.read() return ( <Profiler id="Children" onRender={onRender}> <div>{n}</div> </Profiler> ) } export default memo(Children)
import * as actionTypes from '../../constants/action-types' import { connectorDetails } from '../../services/detail-service' export default function fetchDownloadURL({ downloadURL, error, fetching, otp }) { return (dispatch) => { if (fetching) return if (downloadURL || error) return dispatch(fetchDownloadURLFetching()) connectorDetails({ githubSlug: 'octoblu/electron-meshblu-connector-installer' }, (error, details) => { if (error) { dispatch(fetchDownloadURLFailure({ error })) return } dispatch(fetchDownloadURLSuccess({ details, otp })) }) } } function fetchDownloadURLFetching() { return { type: actionTypes.FETCH_DOWNLOAD_URL_FETCHING, } } function fetchDownloadURLFailure() { return { type: actionTypes.FETCH_DOWNLOAD_URL_FAILURE, } } function fetchDownloadURLSuccess({ details, otp }) { return { type: actionTypes.FETCH_DOWNLOAD_URL_SUCCESS, details, otp, } }
meta: { 'xlsx' : { exports: 'XLSX' // <-- tell SystemJS to expose the XLSX variable } } map: { 'xlsx' : 'node_modules/xlsx/dist/xlsx.core.min.js', 'fs' : '', // <--| 'crypto' : '', // <--| suppress native node modules 'stream' : '', // <--| 'file-saver' : 'node_modules/file-saver/FileSaver.js', }
import rpc from "./rpc" export { rpc } export default { rpc }
import React, { useEffect, useState } from "react"; import { Route, Switch } from "react-router-dom"; import "./App.css"; import Header from "../Header/Header"; import Footer from "../Footer/Footer"; import CardsContainer from "../CardsContainer/CardsContainer"; import SearchForm from "../SearchForm/SearchForm"; import NotFound from "../NotFound/NotFound"; import Popup from "../Popup/Popup"; import api from "../../utils/api"; import { useMediaQuery } from "react-responsive"; import { ESC_KEYCODE } from "../../utils/constants"; export default function App() { const [cards, setCards] = useState([]); const [searchName, setSearchName] = useState(""); const [searchSpecies, setSearchSpecies] = useState(""); const [searchType, setSearchType] = useState(""); const [count, setCount] = useState(""); const [pages, setPages] = useState(""); const [isError, setIsError] = useState(false); const [isLoading, setIsLoading] = useState(false); const [filteredValueByStatus, setFilteredValueByStatus] = useState("all"); const [filteredValueByGender, setFilteredValueByGender] = useState("all"); const [isNoData, setIsNoData] = useState(false); const [selectedCard, setSelectedCard] = useState(null); const [currentPage, setCurrentPage] = useState(1); const isMobile = useMediaQuery({ maxWidth: 630 }); const isTablet = useMediaQuery({ maxWidth: 930 }); useEffect(() => { if ( !!searchName || !!searchSpecies || !!searchType || filteredValueByStatus || filteredValueByGender ) { setIsLoading(true); const urlName = searchName !== "" ? `&name=${searchName.toLowerCase()}` : ""; const urlSpecies = searchSpecies !== "" ? `&species=${searchSpecies.toLowerCase()}` : ""; const urlType = searchType !== "" ? `&type=${searchType.toLowerCase()}` : ""; const urlStatus = filteredValueByStatus && filteredValueByStatus !== "all" ? `&status=${filteredValueByStatus}` : ""; const urlGender = filteredValueByGender && filteredValueByGender !== "all" ? `&gender=${filteredValueByGender}` : ""; const filtersString = `${urlName}${urlStatus}${urlSpecies}${urlType}${urlGender}`; api .getAllCharacters(currentPage, filtersString) .then((filteredCards) => { if (filteredCards?.error !== "There is nothing here") { setCards(filteredCards.results); setCount(filteredCards.info.count); setPages(filteredCards.info.pages); } else { setCount(0); setPages(0); setIsNoData(true); } }) .catch(() => { setIsError(true); }) .finally(() => { setIsLoading(false); }); } }, [ searchName, searchSpecies, searchType, filteredValueByStatus, filteredValueByGender, currentPage, ]); useEffect(() => { if (!isError) { if ( !cards.length && (searchName || searchSpecies || searchType || filteredValueByStatus || filteredValueByGender) ) { setIsNoData(true); } else { setIsNoData(false); } } }, [ cards, searchName, searchSpecies, searchType, filteredValueByStatus, filteredValueByGender, isError, ]); function handleSearchClick( searchName, searchSpecies, searchType, filteredValueByStatus, filteredValueByGender ) { setIsError(false); setSearchName(searchName); setSearchSpecies(searchSpecies); setSearchType(searchType); setFilteredValueByStatus(filteredValueByStatus); setFilteredValueByGender(filteredValueByGender); } function handleCardClick(card) { setSelectedCard(card); document.addEventListener("keydown", handleEscClose); } function closeAllPopups() { setSelectedCard(null); document.removeEventListener("keydown", handleEscClose); } function handleEscClose(evt) { const key = evt.keyCode; if (key === ESC_KEYCODE) { closeAllPopups(); } } function goToPreviousPage(evt) { evt.preventDefault(); currentPage - 1 > 1 && setCurrentPage(currentPage - 1); } function goToNextPage(evt) { evt.preventDefault(); currentPage + 1 <= pages && setCurrentPage(currentPage + 1); } function handlePageClick(evt, number) { evt.preventDefault(); number !== currentPage && setCurrentPage(number); } return ( <div className='app'> <Header /> <SearchForm onSearchSubmit={handleSearchClick} /> <Switch> <Route exact path='/'> <CardsContainer searchedCards={cards} onCardClick={handleCardClick} isMobile={isMobile} isTablet={isTablet} isLoading={isLoading} isNoData={isNoData} isError={isError} pages={pages} count={count} currentPage={currentPage} onPreviousPage={goToPreviousPage} onPageClick={handlePageClick} onNextPage={goToNextPage} /> </Route> <Route path='*'> <NotFound /> </Route> </Switch> <Footer /> <Popup onClose={closeAllPopups} card={selectedCard} /> </div> ); }
import React from 'react' const CardContent = () => { return <div> <p>Card content</p> <p>Card content</p> <p>Card content</p> </div> } export default CardContent
// a. Nathan Ko // b. nathan_ko@cs.uml.edu // c. I'm a student for GUI I class // d. I created this webpage on 11/15/16 // e. This is a multiplication table using javascript and jQuery // f. It passed both html and css validators listed in the syllabus // e. Sources used: W3Schools, StackOverflow, https://jqueryvalidation.org/jQuery.validator.addMethod/ //Makes sure the DOM is ready $().ready(function () { //Function checks that the value is greater than the parameter $.validator.addMethod("greaterThan", function (value, element, param) { //Get the value of the parameter var $min = $(param); if (this.settings.onfocusout) { //Makes sure the element is greater $min.off(".validate-greaterThan").on("blur.validate-greaterThan", function () { $(element).valid(); }); } //Returns whether to display the message or not return parseInt(value) > parseInt($min.val()); }, " The high must be greater than the low!"); //Function checks that the value is lesser than the parameter $.validator.addMethod("lessThan", function (value, element, param) { //Get the value of the parameter var $max = $(param); if (this.settings.onfocusout) { //Makes sure the element is lesser $max.off(".validate-lessThan").on("blur.validate-lessThan", function () { $(element).valid(); }); } return parseInt(value) < parseInt($max.val()); }, " The low must be lesser than the high!"); //This is the one that utilizes the built in rules //In the jQuery validation plugin //And also utilizes the rules outlined above //Must target the form which has id='multForm' $('#multForm').validate({ rules: { 'x-range-low': { required: true, number: true, range: [-100, 100], lessThan: '#x-range-high' }, 'x-range-high': { required: true, number: true, range: [-100, 100], greaterThan: '#x-range-low' }, 'y-range-low': { required: true, number: true, range: [-100, 100], lessThan: '#y-range-high' }, 'y-range-high': { required: true, number: true, range: [-100, 100], greaterThan: '#y-range-low' } }, // This specifies the messages for the rules given, // unless it was already defined. messages: { 'x-range-low': { required: "Please enter a number", number: "Your input is not a number", range: " Please enter a value between [-100, 100]" }, 'x-range-high': { required: "Please enter a number", number: "Your input is not a number", range: " Please enter a value between [-100, 100]" }, 'y-range-low': { required: "Please enter a number", number: "Your input is not a number", range: " Please enter a value between [-100, 100]" }, 'y-range-high': { required: "Please enter a number", number: "Your input is not a number", range: " Please enter a value between [-100, 100]" } }, //Makes sure the form is submitted to action //And runs the corresponding funtion to create table submitHandler: function() { buttonClick(); return false; }, // It empties the table if the input is wrong invalidHandler: function() { $("#multTable").empty(); } }); }); // This is the function called when the inputs are valid // It operates on the DOM tree after creating the chart function manipTable(xL, xH, yL, yH) { // For ES5 "use strict"; // Decrement so there are n + 1 rows and colums yL = yL - 1; xL = xL - 1; // Declaration of variables var i, j, // And a table body element as well tbody = document.createElement('tbody'), // More variables to be used later on tr, te, originalTable; // Start the loop // From the yLow value to yHigh, create the rows for (i = yL; i <= yH; i += 1) { // Set the tr to the HTML element 'tr' tr = document.createElement('tr'); // If it's the first row, make sure it's marked as head if (i === yL) { tr.className += " head"; // Every odd row gets marked even for greater visibility } else if (i % 2 === 0) { tr.className += " even"; } // The marking of last row as tail for the rounded corners if (i == yH) { tr.className += " tail"; } // Now insert the actual values for each tr for (j = xL; j <= xH; j += 1) { // This sets te as 'th' because it's the first row and column if (j === xL && i === yL) { te = document.createElement('th'); tr.appendChild(te); // If j is equal to xL, that means it's the first column } else if (j === xL) { te = document.createElement('th'); // Being marked as x-head so it can be colored white instead te.className += " x-head"; te.innerHTML = i; tr.appendChild(te); // Another case where it's a head } else if (i === yL) { te = document.createElement('th'); te.innerHTML = j; tr.appendChild(te); // For the rest of the non special elements } else { te = document.createElement('td'); te.innerHTML = j * i; tr.appendChild(te); } } // Add the newly created row to the table body tbody.appendChild(tr); } // This selects then deletes the previous table on the DOM tree originalTable = document.getElementById("multTable"); while (originalTable.firstChild) { originalTable.removeChild(originalTable.firstChild); } // This then places the newly created tree into the DOM originalTable.appendChild(tbody); } // This is the function triggered when the button is clicked function buttonClick() { // For ES5 Compatibility "use strict"; // Get the x low and high from input box var xLow = document.getElementById("x-range-low").value, xHigh = document.getElementById("x-range-high").value, // Get the y low and high from input box yLow = document.getElementById("y-range-low").value, yHigh = document.getElementById("y-range-high").value; // Check the inputs are valid // First by checking none of the fields are empty or non numbers // if (!xLow || !xHigh || !yLow || !yHigh) { // document.getElementById("error-message").innerHTML = "Invalid Input: Please make sure you have inputted all numbers correctly."; // // Then check that the numbers are integers // } else if (!(xLow % 1 === 0)|| !(xHigh % 1 === 0) || !(yLow % 1 === 0) || !(yHigh % 1 === 0)) { // document.getElementById("error-message").innerHTML = "The input numbers must be integers."; // } else if (Math.abs(yLow - yHigh) > 100 || Math.abs(xLow - xHigh) > 100) { // document.getElementById("error-message").innerHTML = "Range cannot be greater than 100."; // // Then check that the low is not greater than the high // } else if (Number(yLow) > Number(yHigh) || Number(xLow) > Number(xHigh)) { // document.getElementById("error-message").innerHTML = "The Low values need to be less than or equal to the High values."; // // Then execute the function manipTable, which builds a chart and switches the chart on the DOM tree // } else { // // Make sure there is no error message when it's properly working // document.getElementById("error-message").innerHTML = ""; // // Call the function // //But make sure to pass in integers just in case // manipTable(Number(xLow), Number(xHigh), Number(yLow), Number(yHigh)); // } manipTable(Number(xLow), Number(xHigh), Number(yLow), Number(yHigh)); } // This is the event listenener that listens for button click then calls the buttonClick function // No longer needed // document.getElementById("form-button").addEventListener("click", buttonClick);
import React, { Component } from "react"; import "./css/ToDoList.css" class ToDoItems extends Component { subDelete = (key) => { this.props.superDelete(key) } render() { const myList = this.props.entries.map((item) => { return <li key={item.key} onClick={() => this.subDelete(item.key)} >{item.text}</li> }); return ( <ul className="theList"> {myList} </ul> ); } } export default ToDoItems;
import { useState } from 'react' import { useRouter } from 'next/router' import Link from 'next/link' import { auth } from '../utils/fire-config/firebase'; const Login = () => { const router = useRouter() const [content, setContent] = useState({ email: '', password: '' }) const onChange = (e) => { const { value, name } = e.target; setContent(prevState => ({ ...prevState, [name]: value })); } const handleSubmit = () => { const { email, password } = content; auth.signInWithEmailAndPassword(email, password) .then(authUser => { // console.log(authUser.user) document.querySelector('#error').textContent = ''; document.querySelector('#success').textContent = 'success'; setTimeout(() => { router.back(); }, 1000); }) .catch(error => { let msg = `${error.code}: ${error.message}`; document.querySelector('#success').textContent = ''; document.querySelector('#error').textContent = msg; }) } return ( <div style={{ padding: '0 10%', display: 'grid', placeItems: 'center' }}> <h1>SIGN IN</h1> <br /> <form action="" onSubmit={(e) => { e.preventDefault(); handleSubmit() }}> <div> <label htmlFor="email">Email</label><br /> <input value={content.email} onChange={onChange} type="email" id="email" name="email" className="form-control" /> </div><br /> <div> <label htmlFor="password">Password</label><br /> <input value={content.password} onChange={onChange} type="password" id="password" name="password" className="form-control" /> </div> <br /> <div id="error" style={{ color: 'red' }}></div> <div id="success" style={{ color: 'green' }}></div> <button type="submit" className="btnSolid">LOGIN</button> <div style={{ display: 'flex', alignItems: 'center' }}> <div style={{ marginLeft: 20, color: 'red' }}>Don't have account?</div> <Link href="/signup"><a><button type="button" style={{ marginLeft: 20 }}>SIGNUP</button></a></Link> </div> </form> </div> ) } export default Login
var lXdelta3 = require('../xdelta3'); var fs = require('fs'); var path = require('path'); var aSrcFd = fs.openSync(path.resolve(__dirname, 'files/txt1src'), 'r'); var aDstFd = fs.openSync(path.resolve(__dirname, 'files/txt1result'), 'w'); var aPatch = new lXdelta3.PatchStream(aSrcFd, aDstFd); aPatch.write(fs.readFileSync(path.resolve(__dirname, 'files/txt1gent'))); aPatch.end(); aPatch.on('close', function() { fs.closeSync(aSrcFd); fs.closeSync(aDstFd); if (fs.readFileSync(path.resolve(__dirname, 'files/txt1dst')).toString() == fs.readFileSync(path.resolve(__dirname, 'files/txt1result')).toString()) console.log('OK: Basic Patch'); else console.log('FAIL: Basic Patch'); });
//Hecho por Saulo Fernandes. //Molde de billetes. class Billete { constructor(valor, cantidad, index) { this.index = index; //Posicion en el array this.valor = valor; //Valor del billete. this.cantidad = cantidad; //Cantidad del billete. this.imagen = new Image(); // Imagen del billete. this.imagen.src = `${valor}dolares.jpg`; // URL Imagen del billete. } } //Objeto Cajero Automatico. var cajeroAutomatico = { dineroDisponible: 0, caja: [], //Cuenta la cantidad de billetes individual que hay en la caja y el total en el cajero. contador() { console.log("[contador()] Activado!"); this.dineroDisponible = 0; for (const billete in cajeroAutomatico.caja) { this.dineroDisponible += cajeroAutomatico.caja[billete].valor * cajeroAutomatico.caja[billete].cantidad; } console.log( "[contador()] Dinero disponible en el cajero: " + this.dineroDisponible ); console.log( "[contador()] Cantidad billetes de 50$ en el cajero: " + cajeroAutomatico.caja[0].cantidad ); console.log( "[contador()] Cantidad billetes de 20$ en el cajero: " + cajeroAutomatico.caja[1].cantidad ); console.log( "[contador()] Cantidad billetes de 10$ en el cajero: " + cajeroAutomatico.caja[2].cantidad ); }, //Funcion para entregar los billetes al usuario y descontar la cantidad de billetes en la caja. retiroDinero() { //Variable que almacena el dinero Solicitado por el usuario en el input. dineroSolicitado = numerosRetiro.value; //Restante de dinero por entregar al usuario. restanteSolicitado = dineroSolicitado; //Cantidad de billetes que se le entregaran al usuario. billetesEntregados = [0, 0, 0]; //Comprueba si hay suficiente dinero en el cajero. if (cajeroAutomatico.dineroDisponible >= dineroSolicitado) { //Comprueba si el monto solicitado se puede dar con los billetes disponibles. if ( dineroSolicitado % 50 == 0 || dineroSolicitado % 20 == 0 || dineroSolicitado % 10 == 0 ) { //Ciclo que recorre los billetes para ejecutar la formula. for (const billete of cajeroAutomatico.caja) { //Comprueba si el restante por entregar al cliente es 0, en otras palabras, si ya el cliente recibio todo el dinero solicitado.Si es asi rompe el ciclo for. if (restanteSolicitado == 0) { break; //Si falta dinero por entregar entra al siguiente else. } else { //Formula para saber cuantos billetes se deben entregar. cantidadBilletesEntregar = Math.floor( restanteSolicitado / billete.valor ); //Ciclo while que mantiene viva la comprobacion. while (true) { //Si hay suficientes billetes en el cajero para la cantidad que retorno la formula, entra en el if. if ( billete.cantidad >= cantidadBilletesEntregar && billete.cantidad > 0 ) { //Le restamos la cantidad de billetes entregada, a la cantidad que tenemos en la caja. billete.cantidad -= cantidadBilletesEntregar; //Al restante de dinero por entregar le restamos el monto entregado al cliente. restanteSolicitado -= cantidadBilletesEntregar * billete.valor; //Guardo en un array la cantidad de billetes entregados al usuario, segun su index. billetesEntregados[billete.index] = cantidadBilletesEntregar; console.log( "Restante de dinero por entregar = ", restanteSolicitado ); //Si el restante por entregar es 0, entramos en el siguiente if. Activamos la funcion entregarDinero() y rompemos el ciclo while. if (restanteSolicitado == 0) { cajeroAutomatico.entregarDinero(); break; //Si la cantidad no es 0, entramos al else, rompemos el ciclo while para que el ciclo for pase al siguiente billete. } else { break; } //Si no hay suficientes billetes en el cajero para la cantidad que retorno la formula, entra en el else. } else { //Comprobamossi la cantidad de billetes a entregar es 0, y si es asi rompemos el ciclo while. if (cantidadBilletesEntregar == 0) { break; //Si la cantidad no es 0, le restamos 1 a la cantidad de billetes a entregar, y vuelve a empezar el ciclo while con todas las comprobaciones. } else { cantidadBilletesEntregar -= 1; } } } } } //Si no se puede dar el monto con los valores de billetes disponibles, entra en el siguiente else y da el siguiente mensaje. } else { alert( "Los billetes disponibles no te pueden dar esa cantidad, redondealo a multiplos de 10" ); } //Si la cantidad disponible en el cajero es menor a la solicitada por el usuario, entramos en el else y le avisamos que no hay suficiente dinero. } else { alert("No hay suficiente dinero disponible."); } }, entregarDinero() { console.log("[entregarDinero()] Activado!"); for (const billete of cajeroAutomatico.caja) { cajeroAutomatico.dineroDisponible -= billetesEntregados[billete.index] * billete.valor; console.log( `[entregarDinero()] Fueron entregados ${ billetesEntregados[billete.index] } billetes de ${billete.valor}$ ` ); for (let i = 0; i < billetesEntregados[billete.index]; i++) { imagen = new Image(); imagen.src = billete.imagen.src; imprimirBilletes.appendChild(imagen); } } console.log( "Dinero disponible en el cajero, despues de la transaccion: ", cajeroAutomatico.dineroDisponible ); }, }; //Variables Globales. var dineroSolicitado, restanteSolicitado; var billetesEntregados = []; var botonRetiro = document.getElementById("button_retiro"); var numerosRetiro = document.getElementById("number_retiro"); var imprimirBilletes = document.getElementById("imprimir_billetes"); //Ingresando billetes en el cajero (caja). cajeroAutomatico.caja.push(new Billete(50, 10, 0)); //Billetes de 50. console.log( "Se ha ingresado en el cajero: " + cajeroAutomatico.caja[cajeroAutomatico.caja.length - 1].cantidad + " billetes de 50." ); cajeroAutomatico.caja.push(new Billete(20, 10, 1)); //Billetes de 20. console.log( "Se ha ingresado en el cajero: " + cajeroAutomatico.caja[cajeroAutomatico.caja.length - 1].cantidad + " billetes de 20." ); cajeroAutomatico.caja.push(new Billete(10, 10, 2)); //Billetes de 10. console.log( "Se ha ingresado en el cajero: " + cajeroAutomatico.caja[cajeroAutomatico.caja.length - 1].cantidad + " billetes de 10." ); //Activando la funcion contador() cajeroAutomatico.contador(); //Boton que activa la funcion retiroDinero. botonRetiro.addEventListener("click", cajeroAutomatico.retiroDinero);
$(function(){ // item model // item view // collection // collection view // http://danielarandaochoa.com/backboneexamples/blog/2012/02/22/real-world-usage-of-a-backbone-collection/ // http://stackoverflow.com/questions/19713613/backbone-fetch-callback-the-proper-way var HackathonItemModel = Backbone.Model.extend({ defaults: { name: '', display_name: 'zzz' } }); var HackathonItemView = Backbone.View.extend({ tagName: 'li', template: null, events: { }, initialize: function(){ /* This is useful to bind(or delegate) the this keyword inside all the function objects to the view. Read more here: http://documentcloud.github.com/underscore/#bindAll */ _.bindAll(this); this.template = _.template('<span>Name: <strong><%= name %></strong> - <%= display_name %> </span>'); }, render: function(){ $(this.el).html( this.template( this.model.toJSON() ) ); return this; } }); // HackathonItemView //Define the collection, associate the map for every item in the list //and define the url that fetch will be using to load remote data var HackathonCollection = Backbone.Collection.extend({ model: HackathonItemModel, url: 'data/data.json', parse: function(response){ return response.zdata; } }); var DataView = Backbone.View.extend({ id: "real-world-id", tagName: "ul", className: "real-world", events: { }, initialize: function(){ //This is useful to bind(or delegate) the this keyword inside all the function objects to the view //Read more here: http://documentcloud.github.com/underscore/#bindAll _.bindAll(this); this.collection.bind('add', this.addItemHandler); }, load: function(){ //AJAX Request to get json file with callbacks this.collection.fetch({ add: true, success: this.loadCompleteHandler, error: this.errorHandler }); }, //we arrived here one time per item in our list, so if we received 4 items we //will arrive into this function 4 times addItemHandler: function(model){ //model is an instance of HackathonItemModel var myItemView = new HackathonItemView({model:model}); myItemView.render(); $(this.el).append(myItemView.el); }, loadCompleteHandler: function(collection, response, options){ console.log(collection, response, options); this.render(); }, errorHandler: function(){ throw "Error loading JSON file"; }, render: function(){ //we assign our element into the available dom element $('#main').append($(this.el)); return this; } }); //We create the instance of our collection: var myCollection = new HackathonCollection(); //we pass the collection to our testing View var test = new DataView({collection: myCollection}); test.load(); });
/**权限参考值_查看权限【00001】 */ var ROLE_LOOK=ROLEVALUE_ROLE_LOOK_VALUE; /**权限参考值_添加权限【00010】 */ var ROLE_ADD=ROLEVALUE_ROLE_ADD_VALUE; /**权限参考值_更新权限【00100】 */ var ROLE_UPDATE=ROLEVALUE_ROLE_UPDATE_VALUE; /** 权限参考值_删除权限【01000】*/ var ROLE_DELETE=ROLEVALUE_ROLE_DELETE_VALUE; /** 权限参考值_导出权限【10000】 */ var ROLE_DOWNLOAD=ROLEVALUE_ROLE_DOWNLOAD_VALUE; /** 权限参考值_带有下载权限的全部权限【11111】 */ var ROLE_ALL=ROLEVALUE_ROLE_ALL_VALUE; /** :input.ace[name='All'] */ var inputNameAll=":input.ace[name='All']"; /** :input.ace:not([name='All']) */ var inputNameNotAll=":input.ace:not([name='All'])"; $(function() { // // 根据编辑flg设置是否可编辑 getEditFlg // setDisable(); $("#leftRow .row:last").css("padding-bottom","20px"); //重置 输入状态 reset(); //自适应大小 winResize(); $(window).resize(function(){ winResize(); }); //下拉列表 $("#roleGroupId").multiselect({ buttonContainer: '<div class="btn-group" />', enableFiltering: false, buttonClass: 'btn btn-white multiselect-btn', maxHeight:300, enableClean:false }); $("#appRoleGroupType").multiselect({ buttonContainer: '<div class="btn-group" />', enableFiltering: false, buttonClass: 'btn btn-white multiselect-btn', maxHeight:300, enableClean:false }); // $("#visitCustomerFlgLabel").tooltip({ // show: null, // position: { // my: "left top", // at: "left bottom" // }, // open: function( event, ui ) { // ui.tooltip.animate({ top: ui.tooltip.position().top + 10 }, "fast" ); // } // }); }); function myRefresh(){ } /** * 页面Resize */ function winResize(){ var winHeight = $(window).height();//窗口高度 winHeight=winHeight-45;//窗口高度 减去 logo栏高度45 var height=0;//高度 height+=$(".page-header").outerHeight();//页标题栏 height+=$("#subTitle").outerHeight();//标题 height+=$("#titleRow").outerHeight();//菜单标题 height=winHeight-height-80;//留底边80 //菜单权限 高度 $("#menusRow").height(height); //菜单权限 标题 宽度 var width=$("#categoryListDiv").width(); $("#heightWithcbk").width(width); } /** * 截取菜单ID * @param str * @returns */ function getMenuId(str){ if(str != "" && str != undefined && str.length != 0){ return str.substring(0,str.length-3); } } /** * 全选 * @param obj * @param flg */ function chooseAll(obj,flg){ switch (flg){ case 1: //模块 chooseAllMenu(obj); break; case 2: //子画面 chooseAllSubMenu(obj); break; case 3: //所有模块 chooseAllMax(obj); break; default: break; } } /** * 全选 所有模块 * @param obj */ function chooseAllMax(obj){ var boo = false; $("#div_left").find(":input.ace").each(function(i){ $this=$(this); if(!$this.is(':checked')){ //有cbk尚未选中,就将全部模块选中 boo= true; } }); $("#div_left").find(":input.ace").prop("checked",boo); } /** * 全选 子菜单 * @param obj */ function chooseAllSubMenu(obj){ //全选checkbox子节点 var $input = $(obj).find("input");//全选cbk //checkbox的对应子菜单ID var subMenuId=getMenuId($input.attr("id"));//(1001All) 1001 var $subMenuId="#"+subMenuId;//(1001All) 1001 //模块菜单ID var menuId=$("#"+subMenuId+"Row").offsetParent().attr("data-menuId");//1000 var $menuId="#"+menuId;//1000 //整个模块的主 li 包含模块和其所有子菜单 var $menuLi="#branch_"+menuId; //只含有所有子菜单,不含模块 var $menuUl="#menu_"+menuId; /**子菜单全选*/ if ($input.is(':checked')) {//子菜单 全选input 选中 $($subMenuId).find(".ace").prop("checked","checked"); //遍历子菜单所有input 如果全部选中了 就把子菜单的全选选中 var boo=true; $($menuUl).find(inputNameNotAll).each(function(i){//同一模块级其所有子菜单中 input 不是全选的checkbox集合 $this=$(this); if(!$this.is(':checked')){ boo=false; } }); $($menuId).find(".ace").prop("checked",boo); } else {//子菜单 全选input 取消选中 $($subMenuId).find(inputNameAll).prop("checked",""); //取消模块的全选 $($menuId).find(inputNameAll).prop("checked",""); } } /** * 全选 模块 * @param obj */ function chooseAllMenu(obj){ //全选checkbox子节点 var $input = $(obj).find("input");//全选cbk //checkbox的对应菜单ID var menuId=getMenuId($input.attr("id"));//(1000All) 1000 //整个模块的主 li 包含模块和其所有子菜单 var $menuLi="#branch_"+menuId; /**模块全选*/ if ($input.is(':checked')) {//模块全选 选中 $($menuLi).find(".ace").prop("checked","checked"); } else {//模块全选 取消选中 $($menuLi).find(".ace").prop("checked",""); } } /** * 单选 * @param obj * @param flg */ function chooseOne(obj,flg){ switch (flg){ case 1: //模块input chooseOneMenu(obj); break; case 2: //子画面input chooseOneSubMenu(obj); break; case 3: //所有模块 chooseOneMax(obj); break; default: break; } } /** * 单选 所有模块 * @param obj */ function chooseOneMax(obj){ var boo=false; var name=$(obj).attr("data-name"); $("#div_left").find(':input.ace[name="'+name+'"]').each(function(i){ $this=$(this); if(!$this.is(':checked')){//全部模块对应name的cbk有未选中 boo = true; } }); $("#div_left").find(':input.ace[name="'+name+'"]').prop("checked",boo); /*单选全部模块 非All 全选中 All选中*/ boo=true; $("#div_left").find(inputNameNotAll).each(function(i){ $this=$(this); if(!$this.is(':checked')){//全部模块 除了全选 有cbx未选中 boo=false; } }); $("#div_left").find(inputNameAll).prop("checked",boo); } /** * 单选 子菜单 * @param obj */ function chooseOneSubMenu(obj){ //单选cbk var $input=$(obj).find("input");//input#1001Lok //input的name var name=$input.attr("name");//Lok //input对应菜单ID var subMenuId=getMenuId($input.attr("id"));//(1001Lok) 1001 var $subMenuId="#"+subMenuId;//(1001Lok) 1001 //模块ID var menuId=$("#"+subMenuId+"Row").offsetParent().attr("data-menuId");//1000 var $menuId="#"+menuId;//#1000 /**子画面input*/ if($input.is(':checked')){//子菜单单选 选中 //遍历子菜单所有input 如果全部选中了 就把子菜单的全选选中 var boo=true; $($subMenuId).find(inputNameNotAll).each(function(i){//行级 //遍历除了 全选的 同一 行 子菜单input $this=$(this); if(!$this.is(':checked')){// boo=false; } }); $($subMenuId+"All").prop("checked",boo); boo=true; $("#menu_"+menuId).find(":input.ace[name='"+name+"']").each(function(i){//列级别 //遍历除了 全选的 同一模块下的同名 列 子菜单input $this=$(this); if(!$this.is(':checked')){ boo=false; } }); $($menuId+name).prop("checked",boo); boo=true; $("#menu_"+menuId).find(inputNameNotAll).each(function(i){ //遍历除了 全选的子菜单input $this=$(this); if(!$this.is(':checked')){ boo=false; } }); $($menuId+"All").prop("checked",boo); }else{//子菜单单选 取消选中 //取消当前子画面的全选 $($subMenuId+"All").prop("checked",""); //取消对应模块name的选中 $($menuId+name).prop("checked",""); //取消对应模块All的选中 $($menuId+"All").prop("checked",""); } } /** * 单选 模块 * @param obj */ function chooseOneMenu(obj){ //单选cbk var $input=$(obj).find("input");//input#1000Lok //input的name var name=$input.attr("name");//Lok //input对应菜单ID var menuId=getMenuId($input.attr("id"));//(1000Lok) 1000 //带#的模块ID var $menuId="#"+menuId;//#1000 //整个模块的主 li 包含模块和其所有子菜单 var $menuLi="#branch_"+menuId;//#branch_1000 /**模块input*/ //取消模块的全选 $($menuId+"All").prop("checked",""); //找到子画面的主div if($input.is(':checked')){//模块单选 选中 $($menuLi).find("."+name).prop("checked","checked"); //遍历子菜单所有input 如果全部选中了 就把子菜单的全选选中 var boo=true; $($menuId).find(inputNameNotAll).each(function(i){ //遍历除了 全选的子菜单input $this=$(this); if(!$this.is(':checked')){ boo=false; } }); $($menuLi).find(".All").prop("checked",boo); }else{//模块单选 取消选中 $($menuLi).find("."+name).prop("checked",""); $($menuLi).find(".All").prop("checked",""); } } /** * checkbox btn 状态重置 */ function reset(){ //特殊checkbox 状态 重置 $("input[type='checkBox']").prop("checked",false); //hidden项 最后更新时间 重置 $("#lastUpdTsText").val(""); //更新权限按钮 重置 $("#updRole").removeAttr("disabled"); $("#updRole").html('<i class="ace-icon fa fa-pencil bigger-120"></i>&nbsp;修改当前权限'); } /** * 根据编辑flg设置是否可编辑 getEditFlg * APP权限select联动、特殊权限cbk联动 */ function setDisable(){ //重置选项 reset(); $.ajax({ type:'post', url:contextPath + '/roleGroupList/getEditFlg', async:false,//取消异步 success:function(data){ if (data.success){ $.each(data.resultData,function(index,item){ var selected=$("#roleGroupId").val(); var roleGroupId=this.roleGroupId; if(selected!="" && (selected==roleGroupId)){ //权限组与APP对应权限组联动 $("#appRoleGroupType").val(this.appRoleGroupType); $("#appRoleGroupType").multiselect('refresh'); if(this.editFlg == '1'){ //不可编辑的权限组 $("#updRole").attr("disabled","true"); $("#updRole").html('<i class="ace-icon fa fa-lock bigger-120"></i>&nbsp;不可修改权限');/*fa-ban*/ } if(this.adminFlg == '1'){ //管理员 $("input#adminFlg").click(); } if(this.lookCustomerPhoneFlg == '1'){ //是否可以查看顾客手机号 (0:不可:1:可以) $("input#lookCustomerPhoneFlg").click(); } if(this.visitCustomerFlg == '1'){ //是否可以回访,提醒顾客(0:不可:1:可以) $("input#visitCustomerFlg").click(); } if(this.lookPaymentInfoFlg == '1'){ //是否可以查看支付信息(0:不可:1:可以) $("input#lookPaymentInfoFlg").click(); } } }); }else{ top.showErrorMsg(data.errorMsg); } }, error:function(XMLHttpRequest, textStatus, errorThrown){ top.showErrorMsg(textStatus); } }); } /** * 查询套餐 getRole */ function getRole(){ setDisable(); $.ajax({ type: 'post', url: contextPath + '/roleGroupList/getRole', data: {"roleGroupId":$("#roleGroupId").val()}, success: function(data) { if (data.success){ roleValueSet(data.resultData); }else{ top.showErrorMsg(data.errorMsg); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { top.showErrorMsg(textStatus); } }); } /** * 绑定套餐值 * @param data */ function roleValueSet(data){ if(data != undefined && data.length > 0){ $("#lastUpdTsText").val(data[0].lastUpdTsText); $.each(data,function(index,item){ var menuId="#"+item.menuId; if(item.allRole == true){ $(menuId+"All").prop("checked",true); } if(item.lookRole == true){ $(menuId+"Lok").prop("checked",true); } if(item.addRole == true){ $(menuId+"Ins").prop("checked",true); } if(item.updRole == true){ $(menuId+"Upd").prop("checked",true); } if(item.delRole == true){ $(menuId+"Del").prop("checked",true); } if(item.dldRole == true){ $(menuId+"Dld").prop("checked",true); } }); } } /** * 获取参数 getMenuList * @returns {String} */ function getParam(){ var map = new Map(); var param= "roleGroupId="+$("#roleGroupId").val(); $.ajax({ type: 'post', url: contextPath + '/roleGroupList/getMenuList', traditional: true, async:false,//取消异步 success: function(data) { if (data.success){ $.each(data.resultData,function(index,item){ /** 菜单ID */ var menuId = "#"+item.menuId; /** 权限 */ var roleValue = 0; $(menuId).find("input:checked").each(function(){ if ($(this).attr("name") == 'All') { roleValue = ROLE_ALL; } else { if($(this).attr("name") == "Lok"){ roleValue = roleValue | ROLE_LOOK; } else if ($(this).attr("name") == 'Ins'){ roleValue = roleValue | ROLE_ADD; } else if ($(this).attr("name") == 'Upd') { roleValue = roleValue | ROLE_UPDATE; } else if($(this).attr("name") == 'Del'){ roleValue = roleValue | ROLE_DELETE; } else{ roleValue = roleValue | ROLE_DOWNLOAD; } } }); map.put(item.menuId,roleValue); }); //菜单ID list param+="&keys="+map.keys(); //权限值 list param+="&values="+map.values(); //app对应权限组 param+="&appRoleGroupType="+$("#appRoleGroupType").val(); //最后更新时间 排他 param+="&lastUpdTsText="+$("#lastUpdTsText").val(); //查看所有数据 param+="&adminFlg="+cbkGetValue("adminFlg"); //手机查看权限 param+="&lookCustomerPhoneFlg="+cbkGetValue("lookCustomerPhoneFlg"); //是否可以回访,提醒顾客(0:不可:1:可以) param+="&visitCustomerFlg="+cbkGetValue("visitCustomerFlg"); //是否可以查看支付信息 (0:不可:1:可以) param+="&lookPaymentInfoFlg="+cbkGetValue("lookPaymentInfoFlg"); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { top.showErrorMsg(textStatus); } }); return param; } /** * 特殊checkbox取值 * @param cbkId * @returns */ function cbkGetValue(cbkId){ return $("#"+cbkId).is(":checked")?'1':'0'; } /** * 回访权限 与 手机号查看权限 * @returns {Boolean} */ function validatePhoneFlg(){ var phoneFlg=$("#lookCustomerPhoneFlg").is(":checked"); var visitFlg=$("#visitCustomerFlg").is(":checked"); if(visitFlg==true && phoneFlg==false){ //选中了 回访 没选中 手机查看权限 return true; } } /** * 权限更新 * @returns {Boolean} */ function doUpdate(obj){ //必须入力项 var roleGroupId = $("#roleGroupId").val(); /*验证*/ //是否选择权限组 if (roleGroupId == undefined || roleGroupId == "") { showErrorTips("roleGroupIdErrorDiv","请选择权限组"); $('#updRole').button('reset'); return false; } //回访权限与手机查看权限 if(validatePhoneFlg()){ showErrorTips("lookCustomerPhoneFlgErrorDiv","选中回访权限建议同时选中手机查看权限"); } //取值 var param = getParam(); top.dialog("确定要更新此权限吗?",function updateRole(){ //按钮loading $('#updRole').button('loading'); //更新数据 $.ajax({ type: 'post', url: contextPath + '/roleGroupList/update', data: param, //async:false,//取消异步 success: function(data) { if (data.success) { top.showSuccessMsg(data.okMsg); getRole(); } else { top.showErrorMsg(data.errorMsg); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { top.showErrorMsg(errorThrown); }, complete: function(XMLHttpRequest, textStatus) { $("#updRole").button("reset"); } }); } ); } /**Tree的打开与关闭*/ //项目的打开和关闭方法(Tree的打开与关闭) function openFolder(el) { var openIcon = 'ace-icon tree-minus'; var closeIcon = 'ace-icon tree-plus'; var $el = $(el); // tree-branch-name var $branch; var $treeFolderContent; var $treeFolderContentFirstChild; $branch = $el.closest('.tree-branch'); $treeFolderContent = $branch.find('.tree-branch-children'); $treeFolderContentFirstChild = $treeFolderContent.eq(0); // manipulate branch/folder var eventType, classToTarget, classToAdd; if ($el.find('.' + $.trim(closeIcon.replace(/(\s+)/g, '.'))).length) {//ACE eventType = 'opened'; classToTarget = closeIcon;//ACE classToAdd = openIcon;//ACE $branch.addClass('tree-open'); $branch.attr('aria-expanded', 'true'); $treeFolderContentFirstChild.removeClass('hide'); } else if ($el.find('.' + $.trim(openIcon.replace(/(\s+)/g, '.')))) { eventType = 'closed'; classToTarget = openIcon;//ACE classToAdd = closeIcon;//ACE $branch.removeClass('tree-open'); $branch.attr('aria-expanded', 'false'); $treeFolderContentFirstChild.addClass('hide'); } $branch.find('> .tree-branch-header .icon-folder').eq(0).removeClass( classToTarget)//ACE .addClass(classToAdd); } /**Map*/ var Map=function(){ this.mapArr={}; this.arrlength=0; //假如有重复key,则不存入 this.put=function(key,value){ if(!this.containsKey(key)){ this.mapArr[key]=value; this.arrlength=this.arrlength+1; } } //根据key取得对应value this.get=function(key){ return this.mapArr[key]; } //传入的参数必须为Map结构 this.putAll=function(map){ if(Map.isMap(map)){ var innermap=this; map.each(function(key,value){ innermap.put(key,value); }) }else{ top.showErrorMsg("传入的非Map结构"); } } this.remove=function(key){ delete this.mapArr[key]; this.arrlength=this.arrlength-1; } this.size=function(){ return this.arrlength; } //判断是否包含key this.containsKey=function(key){ return (key in this.mapArr); } //判断是否包含value this.containsValue=function(value){ for(var p in this.mapArr){ if(this.mapArr[p]==value){ return true; } } return false; } //得到所有key 返回数组 this.keys=function(){ var keysArr=[]; for(var p in this.mapArr){ keysArr[keysArr.length]=p; } return keysArr; } //得到所有value 返回数组 this.values=function(){ var valuesArr=[]; for(var p in this.mapArr){ valuesArr[valuesArr.length]=this.mapArr[p]; } return valuesArr; } this.isEmpty=function(){ if(this.size()==0){ return false; } return true; } this.clear=function(){ this.mapArr={}; this.arrlength=0; } //循环 this.each=function(callback){ for(var p in this.mapArr){ callback(p,this.mapArr[p]); } } this.toString = function () { var str = "{"; for(var p in this.mapArr){ str += "\""+ p+"\" : \""+this.mapArr[p]+"\","; } str = str.substring(0,str.length - 1) ; str += "}"; return str; } } //判断是否是map对象 Map.isMap=function(map){ return (map instanceof Map); } //遍历Map //myMap.each(function (key, value) { // document.write("each "+key+" = "+value); // document.write("<br/>"); //});
import React from 'react'; import APIEpisodes from './APIEpisodes'; import ApiImg from './ApiImg'; import Description from './Description'; import Gallery from './Gallery'; import Header from './Header'; import Spacer from './Spacer'; import Title from './Title'; const blocks = new Map(); blocks .set('DESCRIPTION', Description) .set('TITLE', Title) .set('API_IMAGE', ApiImg) .set('GALLERY', Gallery) .set('API_EPISODE_LIST', APIEpisodes) .set('HEADER', Header) .set('SPACER', Spacer); // TODO: class화 한 후, render method 를 통해 렌더해도 될 듯 export default blocks;
import React from 'react' import {Link} from 'react-router-dom' import './style.css' class Forms extends React.Component{ state={ formTitle: '', formDescription: '', question: '', answer: '', select : [ 'select option', 'Short Answer', 'Multiple Choice', 'Checkboxes' ], option: '', count: [] } handleChange = (e) => { this.setState({ [e.target.name]:e.target.value }) } handleSelect = (e) => { this.setState({ option: e.target.value }) } handleAddCount = () => { this.setState({ count: [...this.state.count, ''] }) console.log('set state', this.state.count) } render(){ const select = this.state.select let selectList = select.map((ele, i)=>{ return ( <option key={i}> {ele} </option> ) }) const multipleChoice = this.state.option == 'Multiple Choice' && this.state.count.map((item, i) => { return( <div> <input type='radio' /> <label> {`option ${i+2}`} </label> </div> ) }) const checkBox = this.state.option == 'Checkboxes' && this.state.count.map((item, i) => { return( <div> <input type = 'checkbox' /> <label> {`option ${i+2}`} </label> </div> ) }) return( <div> <form> <div className='card-form input'> <h3>Form Title</h3> <input type='text' name = 'formTitle' value = {this.state.formTitle} onChange={this.handleChange} className='input' /> </div> <div className='card-form'> <h3>Form Description</h3> <input type='text' name = 'formDescription' value = {this.state.formDescription} onChange={this.handleChange} className='input' /> <br/> </div> <label>Question</label> <br/> <input type='text' name = 'question' value = {this.state.question} onChange={this.handleChange} className='input' /> <br/> <select onChange={this.handleSelect} name='option' className='select'> {selectList} </select><br/> { this.state.option == 'Short Answer' && <input type='text' className='input' /> } { this.state.option == 'Multiple Choice' && ( <div> <input type='radio' /> <label>option 1</label></div> ) } {multipleChoice} { this.state.option == 'Multiple Choice' && this.state.count.length!=4 ? <Link onClick={this.handleAddCount}>Add option</Link> : '' } { this.state.option == 'Checkboxes' && ( <div> <input type='checkbox' /> <label>option 1</label></div> ) } {checkBox} { this.state.option == 'Checkboxes' && this.state.count.length!=4 ? <Link onClick={this.handleAddCount}>Add option</Link> : '' } </form> </div> ) } } export default Forms
var express = require('express'); var router = express.Router(); var Todo = require('../models/todo'); Todo.methods(['get', 'put', 'post', 'delete']); Todo.register(router, '/todos'); module.exports = router;
import { postModel } from '../../models/postModel'; export const resolver = { Query: { getAllPosts: () => postModel.getAllPosts(), }, Mutation: { createPost: (root, { input: PostInput }) => { return postModel.createPost(PostInput); } } }
//importamos el modelo persona var Persona = require('../Modelos/persona.js'); var md_auth = require('../Middlewares/auth.js') //-------obtener personal -------- let obtenerPersonas = (req, res)=> { Persona.find({}, (err, personas) => { if (err) { return res.status(500).json({ ok:false, mensaje: 'Error al cargar personas' }); } else { { return res.status(200).json({ ok:true, persona: personas }) } } }) } let crearPersona = (req, res) => { var body = req.body; var personaNueva = new Persona( { nombre: body.nombre, apellido: body.apellido, legajo: body.legajo, rol: body.rol, Persona: body.Persona } ); personaNueva.save( (err, personaGuardada) => { if (err) { return res.status(500).json({ ok:false, mensaje: 'Error al crear persona' }); } else { res.status(200).json({ ok:true, persona: personaGuardada, personaToken: req.persona }) } }); } //------Actualizar persona -------- let actualizarPersona = (req, res, next) => { var id = req.params.id; var body = req.body; Persona.findById(id, (err, persona)=>{ if(err){ return res.status(500).json({ ok:false, mensaje:'Error al buscar persona en la DB', errors: err }); } if(!persona){ return res.status(400).json({ ok:false, mensaje:'El persona no existe', errors: {message: 'no existe el persona con ese id'} }); } persona.nombre = body.nombre; persona.apellido = body.apellido; persona.legajo=body.legajo; persona.rol=body.rol; persona.Persona=body.Persona; persona.save((err,personaGuardado)=>{ if(err){ return res.status(400).json({ ok:false, mensaje:'Error al guardar nuevo persona en la DB', errors: err }); } res.status(200).json({ ok:true, persona:personaGuardado }); }); }); } let borrarPersonaId = (req, res)=>{ var id = req.params.id; Persona.findByIdAndRemove(id, (err, PersonaBorrado)=>{ if(err){ return res.status(500).json({ ok:false, mensaje:'No existe Persona con ese Id' }); } if(!PersonaBorrado){ return res.status(400).json({ ok:false, mensaje: 'No existe el Persona' }) } res.status(200).json({ ok:true, Persona: PersonaBorrado }) }); }; module.exports = { obtenerPersonas, crearPersona, actualizarPersona, borrarPersonaId }
(function(){ angular.module('app') .controller('UsersController',['$route','$log','$http', '$routeParams', '$location', UsersController]); function UsersController($route,$log,$http,$routeParams,$location){ var vc = this; vc.items = []; vc.user = {id:1,name:"",about:""}; vc.raiz = 'https://damp-savannah-3340.herokuapp.com'; vc.refresh = function() { $log.debug($route.current); $log.debug($route.routes); $route.reload(); } vc.getUsers = function () { $http({ method: 'GET', url: vc.raiz +'/users', headers: { 'Accept': 'application/json' } }).success(function (data, status) { vc.items = data; }).error(function (data, status) { alert("Error"); }) } vc.getUser = function () { $http({ method: 'GET', url: vc.raiz + '/users/'+$routeParams.id, headers: { 'Accept': 'application/json' } }).success(function (data, status) { vc.user = data; console.log(data); $log.debug(data); }).error(function (data, status) { alert("Error"); }) } vc.guardar = function (){ $http({ method:'PUT', url :vc.raiz + '/users/' + $location.path().split("/users/")[1], headers:{ 'Accept': 'application/json' }, data:vc.user }).success(function(){ alert("Guardado"); $location.url('/users/'); vc.refresh(); }).error(function(){ alert("Error"); }); } } }());
var alpha = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L' , 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U' ,'V' , 'W', 'X', 'Y', 'Z']; function numberArr(int) { // if number is 5 => alpha[4] var newArray = []; var count = 25; int--; while((int) > alpha.length){ for(var i = 0; i < alpha.length; i++){ alpha.push(alpha[i] + alpha[i]); } } console.log(alpha); } numberArr(29);
import * as React from "react"; function VolumeHalf(props) { return ( <svg xmlns="http://www.w3.org/2000/svg" width={16} height={16} viewBox="0 0 16 16" {...props} > <path d="M9 4a.5.5 0 00-.812-.39L5.825 5.5H3.5A.5.5 0 003 6v4a.5.5 0 00.5.5h2.325l2.363 1.89A.5.5 0 009 12V4zm3.025 4a4.486 4.486 0 01-1.318 3.182L10 10.475A3.489 3.489 0 0011.025 8 3.49 3.49 0 0010 5.525l.707-.707A4.486 4.486 0 0112.025 8z" /> </svg> ); } export default VolumeHalf;
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Card } from 'react-bootstrap'; import { addUser } from '../redux/actions/registerAction'; import { Formik, Form, Field, ErrorMessage } from 'formik'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faUser, faEnvelope, faKey } from '@fortawesome/free-solid-svg-icons'; import * as Yup from 'yup'; import axios from 'axios'; import Swal from 'sweetalert2/dist/sweetalert2.js' import '../style/style.scss'; const RegisterSchema = Yup.object().shape({ fullname: Yup.string() .required('Fullname is Required'), password: Yup.string() .min(3, 'Please Enter less then 3 letters') .required('Password is Required'), confirmpassword: Yup.string() .min(3, 'Please Enter less then 3 letters') .required('Password is Required') .test('passwords-match', 'Passwords must match ya fool', function (value) { return this.parent.password === value; }), email: Yup.string() .email('Invalid email') .required('Email is Required'), }); class Register extends Component { reguster = async (values) => { try { const apiUrl = 'https://6d777be4-93ea-4ec2-8335-ffd0777cd339.mock.pstmn.io/register'; const response = await axios.post(apiUrl, values); this.props.dispatch(addUser(values, this.props.users)); if (this.props.message === "This email has already been registered.") { Swal.fire('Oops...', this.props.message, 'error') } else { await Swal.fire(response.data.message) await this.props.history.replace({ pathname: '/' }); } } catch (error) { // console.log(error) alert(error.response.data); } } render() { return ( <> <div className="container mt-5"> <div className="row justify-content-center"> <div className="col-md-4"> <Card className="py-0"> <Card.Body> <Formik initialValues={{ fullname: '', email: '', password: '', confirmpassword: '' }} validationSchema={RegisterSchema} onSubmit={(values, { setSubmitting }) => { this.reguster(values) setSubmitting(false) }} > {({ isSubmitting, touched, errors }) => ( <Form noValidate> <div className="row justify-content-center"> <div className="col-md-12 text-topic"> <span style={{ fontSize: '2em', fontWeight: '500' }}>Register</span> <div className="line-border"></div> </div> </div> <div className="row justify-content-center"> <div className="col-md-12"> <label htmlFor="name" className="text-label">Fullname</label> <div className="input-group input-group-sm mb-3"> <div className="input-group-prepend"> <span className="input-group-text"><FontAwesomeIcon className="mr-1" icon={faUser} /> </span> </div> <Field type="text" name="fullname" placeholder="Fullname" className={ `form-control ${touched.fullname && errors.fullname ? 'is-invalid' : ''}` } /> <ErrorMessage name="fullname" className="invalid-feedback" component="div" /> </div> </div> </div> <div className="row justify-content-center"> <div className="col-md-12"> <label htmlFor="email" className="text-label">Email</label> <div className="input-group input-group-sm mb-3"> <div className="input-group-prepend"> <span className="input-group-text"><FontAwesomeIcon className="mr-1" icon={faEnvelope} /> </span> </div> <Field type="email" name="email" placeholder="Email" className={ `form-control ${touched.email && errors.email ? 'is-invalid' : ''}` } /> <ErrorMessage name="email" className="invalid-feedback" component="div" /> </div> </div> </div> <div className="row justify-content-center"> <div className="col-md-12"> <label htmlFor="password" className="text-label">Password</label> <div className="input-group input-group-sm mb-3"> <div className="input-group-prepend"> <span className="input-group-text"><FontAwesomeIcon className="mr-1" icon={faKey} /> </span> </div> <Field type="password" name="password" placeholder="Password" className={ `form-control ${touched.password && errors.password ? 'is-invalid' : ''}` } /> <ErrorMessage name="password" className="invalid-feedback" component="div" /> </div> </div> </div> <div className="row justify-content-center"> <div className="col-md-12"> <label htmlFor="confirmpassword" className="text-label">Confirm Password</label> <div className="input-group input-group-sm mb-3"> <div className="input-group-prepend"> <span className="input-group-text"><FontAwesomeIcon className="mr-1" icon={faKey} /> </span> </div> <Field type="password" name="confirmpassword" placeholder="Password" className={ `form-control ${touched.confirmpassword && errors.confirmpassword ? 'is-invalid' : ''}` } /> <ErrorMessage name="confirmpassword" className="invalid-feedback" component="div" /> </div> </div> </div> <div className="row justify-content-center mt-1"> <div className="col-md-12"> <button type="submit" disabled={isSubmitting} className="btn bg-btn-primary w-100"> Register </button> </div> </div> </Form> )} </Formik> </Card.Body> </Card> </div> </div> <div style={{ marginTop: '5rem' }}></div> </div> </> ) } } const mapStateToProps = (state) => { return { users: state.registerReducer.users, message: state.registerReducer.message } } export default connect(mapStateToProps)(Register);
/** * 表单验证插件 * 开发者:刘鹏 * 开发时间:2012-7-9 * 使用方法: * jQuery对象之后直接使用.validate()方法,返回值为true|false。具体的默认参数如下: * require : true, // 是否是必填项 * requiretext : "*必填项", // 必填项显示的文字 * min : 1, // 字符最小长度 * max : 50, // 字符最大长度 * num : false, // 是否是数字验证 * specialnum : false, // 是否是带特殊字符-和_的数字 * price : false, // 是否是价格验证 * email : false, // 是否是邮箱验证 * mobile : false, // 是否是手机号码验证 * zip : false, // 是否是邮编验证 * errElement : "em", // 错误提示信息展示元素 * formatmsg : "输入不正确" // 格式错误提示文字 * * 示例: * 1、$("input").validate();不传递参数,表示采用默认值 * 2、$("input").validate({require:true, max:50});传递json对象格式的参数,require:true表示必选,max:50表示最大可输入50个字符 * 3、$("input").validate({email:true});表示邮箱的验证方法 */ ;(function ($){ $.fn.extend({ "validate" : function(options){ // 设置默认值 options = $.extend({ require : true, requiretext : "*必填项", min : 1, max : 50, num : false, minnum : 1, maxnum : 9999999, specialnum : false, // 带特殊字符-和_的数字 price : false, // 价格验证 minprice : 0.01, maxprice : 9999999.99, rate : false, email : false, mobile : false, zip : false, date : false, letter_num : false, tel_mobile : false, errElement : "em", formatmsg : "输入不正确" }, options); // 设置错误信息提示对象 var $err = null; if (this.next("span").length>0) { if (this.parent().has(options.errElement).length==0) { $err = $("<" + options.errElement + "></" + options.errElement + ">").appendTo(this.parent()); }else{ $err = $(this.parent().find(options.errElement)); } }else{ $err = this.next(options.errElement); if ($err.length==0) { $err = $("<" + options.errElement + "></" + options.errElement + ">").insertAfter(this); } } // 必填验证 var val = $.trim(this.val()); this.val(val); var vallength = this.chineselength(); if (options.require) { if (vallength<options.min) { $err.removeClass("success").addClass("err").text(options.requiretext); return false; } } // 长度范围验证 if (vallength<options.min || vallength>options.max) { $err.removeClass("success").addClass("err").text(options.formatmsg); return false; } // 数字验证 if (options.num) { if(!/^[0-9]{1,50}$/.test(val)) { $err.removeClass("success").addClass("err").text(options.formatmsg); return false; }else{ var parseNum = parseInt(val, 10); if (options.minnum > parseNum || options.maxnum < parseNum) { $err.removeClass("success").addClass("err").text(options.formatmsg); return false; } } } // 带特殊字符的数字验证 if (options.specialnum){ if(!/^[0-9\-_]{1,50}$/.test(val)) { $err.removeClass("success").addClass("err").text(options.formatmsg); return false; } } // 价格验证 if (options.price){ if(!/^\d{0,7}\.{0,1}(\d{1,2})?$/.test(val)) { $err.removeClass("success").addClass("err").text(options.formatmsg); return false; }else{ var parsePrice = parseFloat(val); if (options.minprice > parsePrice || options.maxprice < parsePrice) { $err.removeClass("success").addClass("err").text(options.formatmsg); return false; } } } // 比率 if(options.rate){ if(!/^\d{0,7}\.{0,1}(\d{1,3})?$/.test(val)) { $err.removeClass("success").addClass("err").text(options.formatmsg); return false; } } // Email验证 if (options.email) { if (!/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(val)) { $err.removeClass("success").addClass("err").text(options.formatmsg); return false; } } // 手机号验证 if (options.mobile) { /* 可验证的手机号码段: 130、131、132、133、134、135、136、137、138、139、 145、147、 150、151、152、153、155、156、157、158、159、 180、182、183、185、186、187、188、189 */ if (!/^(13[0-9]{9})|(14[57][0-9]{8})|(15([0-3]|[5-9])[0-9]{8})|(18([023]|[5-9])[0-9]{8})$/.test(val)) { $err.removeClass("success").addClass("err").text(options.formatmsg); return false; } } // 邮编验证 if (options.zip) { if (!/^[1-9][0-9]{5}$/.test(val)) { $err.removeClass("success").addClass("err").text(options.formatmsg); return false; } } // 日期 if (options.date) { if (!/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(val)) { $err.removeClass("success").addClass("err").text(options.formatmsg); return false; } } // 字母和数字A-Za-z0-9 if (options.letter_num) { if (!/^[A-Za-z0-9]+$/.test(val)) { $err.removeClass("success").addClass("err").text(options.formatmsg); return false; } } // 座机和手机验证 if (options.tel_mobile) { if (!/^[0-9]{7,11}$/.test(val)) { // 手机号验证 /* 可验证的手机号码段: 130、131、132、133、134、135、136、137、138、139、 145、147、 150、151、152、153、155、156、157、158、159、 180、182、183、185、186、187、188、189 */ if (!/^(13[0-9]{9})|(14[57][0-9]{8})|(15([0-3]|[5-9])[0-9]{8})|(18([023]|[5-9])[0-9]{8})$/.test(val)) { $err.removeClass("success").addClass("err").text(options.formatmsg); return false; } } } $err.remove(); return true; }, // 获取含中文字符的长度,1个中文占2个字符 "chineselength" : function(){ var val = $.trim(this.val()); if (val.length==0) return 0; // 中文字符 var regChinese = new RegExp("[\u4E00-\u9FA5\uF900-\uFA2D]", "g"); var chinese = val.match(regChinese); if (chinese==null) chinese = ""; // 全角字符 var regFullwidth = new RegExp("[\uFF00-\uFFEF]", "g"); var fullwidth = val.match(regFullwidth); if (fullwidth==null) fullwidth = ""; return (val.length-chinese.length-fullwidth.length) + 2*(chinese.length+fullwidth.length); }, "parseStr2Date" : function(){ var val = $.trim(this.val()); if (val.length==0 || !/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(val)) { return null; } return date= new Date(Date.parse(val.replace(/\-/g, "/"))); } }); })(jQuery); function trim(str) { return str.replace(/(^\s*)|(\s*$)/g, ""); } /** * 隐藏点击按钮 * @param e * @return */ function clickDisabled(e) { if (e == null || typeof(e) != "object") { return false; } var obj = e; if (typeof(obj.length) == "undefined") { obj = $(obj); } obj.hide().before("<span style='display:inline-block;border:#01B703 1px solid;padding:1px 3px 1px 3px;margin-bottom:2px;background:#F1FDE5;font-size:12px;color:#01B703;line-height:16px;width:48px;'>提交中..</span>"); } /** * 显示点击按钮 * @param e * @return */ function clickEnabled(e) { if (e == null || typeof(e) != "object") { return false; } var obj = e; if (typeof(obj.length) == "undefined") { obj = $(obj); } obj.show().prev("span").remove(); } /** * 输出千位分隔符形式的金额 * @param number * @return */ function outputMoney(number) { if (isNaN(number) || ""+number == "") return ""; if (number == "0" || number == "0.00" || number == 0) { return "0.00"; } number = replaceComma(number); number = Math.round(parseFloat(number) * 100) / 100; if (number < 0) return '-' + outputDollars(Math.floor(Math.abs(number) - 0) + '') + outputCents(Math.abs(number) - 0); else return outputDollars(Math.floor(number - 0) + '') + outputCents(number - 0); } /** * 过滤逗号 * @param str * @return */ function replaceComma(number){ return ("" + number).replace(/\,/g, ""); } function outputDollars(number) { number += ""; if (number.length <= 3) return (number == '' ? '0' : number); else { var mod = number.length % 3; var output = (mod == 0 ? '' : (number.substring(0, mod))); for (i = 0; i < Math.floor(number.length / 3); i++) { if ((mod == 0) && (i == 0)) output += number.substring(mod + 3 * i, mod + 3 * i + 3); else output += ',' + number.substring(mod + 3 * i, mod + 3 * i + 3); } return (output); } } function outputCents(amount) { amount = parseFloat(amount); amount = Math.round(((amount) - Math.floor(amount)) * 100); return (amount < 10 ? '.0' + amount : '.' + amount); } /** * 验证礼品卡编号 * @param $table * @return */ function validateGiftCardIds($table) { var $beginId = $table.find(".beginId"); var val_beginId = $.trim($beginId.removeClass("input_err").val()); var $endId = $table.find(".endId"); var val_endId = $.trim($endId.removeClass("input_err").val()); var $singleId = $table.find(".singleId"); var val_singleId = $.trim($singleId.removeClass("input_err").val()); // 1. 验证是否为空 if (val_beginId.length==0 && val_endId.length==0 && val_singleId.length==0) { $beginId.addClass("input_err"); $endId.addClass("input_err"); $singleId.addClass("input_err"); alert("必须要输入礼品卡号"); return false; } else if (val_beginId.length==0 && val_endId.length==0 && val_singleId.length>0){ } else if (val_beginId.length==0 || val_endId.length==0) { $beginId.addClass("input_err"); $endId.addClass("input_err"); alert("连续的礼品卡必须要同时输入开始和结束的礼品卡号"); return false; } // 2. 验证连续卡号是否正确 var out_begin_prefix = ""; var out_begin_num = 0; var out_end_prefix = ""; var out_end_num = 0; if (val_beginId.length>0 && val_endId.length>0) { out_begin_prefix = val_beginId.substr(0, val_beginId.length-6); out_begin_num = parseInt(val_beginId.substr(val_beginId.length-6, 6), 10); out_end_prefix = val_endId.substr(0, val_endId.length-6); out_end_num = parseInt(val_endId.substr(val_endId.length-6, 6), 10); if (out_begin_prefix != out_end_prefix) { $beginId.addClass("input_err"); $endId.addClass("input_err"); alert("连续礼品卡卡号必须要“开始卡号”与“结束卡号”的标识符一致。"); return false; } else if (out_begin_num >= out_end_num){ $beginId.addClass("input_err"); $endId.addClass("input_err"); alert("连续礼品卡卡号的“开始卡号”一定要比“结束卡号”小。"); return false; } } // 3. 验证非连续卡号是否在连续卡号区间内 var result = true; var out_singleIds = val_singleId.split(","); if(out_singleIds!=""){ for ( var si = 0; si < out_singleIds.length; si++) { var out_single_prefix = out_singleIds[si].substr(0, out_singleIds[si].length-6); var out_single_num = parseInt(out_singleIds[si].substr(out_singleIds[si].length-6, 6), 10); if (out_single_prefix == out_begin_prefix && out_single_num >= out_begin_num && out_single_num <= out_end_num) { $singleId.addClass("input_err"); alert("连续礼品卡卡号中已经包含了非连续卡号,请重新输入"); result = false; break; } // 判断非连续礼品卡卡号是否重复 for ( var j = si + 1; j < out_singleIds.length; j++) { if (out_singleIds[si] == out_singleIds[j]) { $singleId.addClass("input_err"); alert("不能输入相同的非连续礼品卡卡号,请重新输入"); result = false; break; } } if (!result) { break; } } } if (!result) { return result; } // 4. 验证输入卡数与要求数量是否一致 var $giftCardNum = $table.find("input.giftcardnum"); if ($giftCardNum && $giftCardNum.length > 0) { var contnNum = (out_end_num==0 || out_begin_num==0) ? 0 : (out_end_num - out_begin_num + 1); var total_giftcard = contnNum + (val_singleId.length>0 ? out_singleIds.length : 0); if (parseInt($giftCardNum.val(),10)!=total_giftcard) { $giftCardNum.addClass("input_err"); alert("输入的礼品卡数量与“数量”不一致。"); result = false; } } return result; } /** * 检查礼品卡卡号 * @return */ function checkGiftCardIds() { var result = true; var $giftCardList = $(".beginId"); for ( var i = 0; i < $giftCardList.length; i++) { var $out_beginId = $($giftCardList.get(i)); var $out_table = $out_beginId.parent().parent().parent().parent("table"); // 1. 验证礼品卡卡号 result = validateGiftCardIds($out_table); if (!result) break; var val_out_beginId = $.trim($out_beginId.val()); var out_prefix = val_out_beginId.substr(0, val_out_beginId.length-6); var out_begin_num = parseInt(val_out_beginId.substr(val_out_beginId.length-6, 6), 10); var $out_endId = $out_table.find(".endId"); var val_out_endId = $.trim($out_endId.val()); var out_end_num = parseInt(val_out_endId.substr(val_out_endId.length-6, 6), 10); var $out_singleId = $out_table.find(".singleId"); var val_out_singleId = $.trim($out_singleId.val()); var out_singleIds = val_out_singleId.split(","); // 2. 验证卡号是否重复 var repeat = false; for ( var j = i+1; j < $giftCardList.length; j++) { var $in_beginId = $($giftCardList.get(j)); var $in_table = $in_beginId.parent().parent().parent().parent("table"); // 2.1. 验证礼品卡卡号 result = validateGiftCardIds($in_table); if (!result) break; var val_in_beginId = $.trim($in_beginId.val()); var in_prefix = val_in_beginId.substr(0, val_in_beginId.length-6); var in_begin_num = parseInt(val_in_beginId.substr(val_in_beginId.length-6, 6), 10); var $in_endId = $in_table.find(".endId"); var val_in_endId = $.trim($in_endId.val()); var in_end_num = parseInt(val_in_endId.substr(val_in_endId.length-6, 6), 10); // 2.2. 验证外部连续礼品卡卡号前缀与内部连续礼品卡卡号前缀是否相等 if ((in_prefix == out_prefix) && ((out_end_num >= in_begin_num && out_end_num <= in_end_num) || (out_begin_num >= in_begin_num && out_begin_num <= in_end_num))) { $in_beginId.addClass("input_err"); $in_endId.addClass("input_err"); alert("连续礼品卡卡号与上面的连续礼品卡卡号重复,请重新输入"); repeat = true; } if (repeat) break; // 2.3. 验证外部非连续卡号是否在内部连续卡号中重复 if(val_out_singleId!=""){ for ( var os = 0; os < out_singleIds.length; os++) { var out_single_prefix = out_singleIds[os].substr(0, out_singleIds[os].length-6); var out_single_num = parseInt(out_singleIds[os].substr(out_singleIds[os].length-6, 6), 10); if (out_single_prefix == in_prefix && out_single_num >= in_begin_num && out_single_num <= in_end_num) { $in_beginId.addClass("input_err"); $in_endId.addClass("input_err"); alert("连续礼品卡卡号中已经包含了上面的非连续卡号,请重新输入"); repeat = true; break; } } } if (repeat) break; // 2.4. 验证内部非连续卡号是否在外部连续卡号中重复 var $in_singleId = $in_table.find(".singleId"); var val_in_singleId = $.trim($in_singleId.val()); var in_singleIds = val_in_singleId.split(","); if(val_in_singleId!=""){ for ( var is = 0; is < in_singleIds.length; is++) { var in_single_prefix = in_singleIds[is].substr(0, in_singleIds[is].length-6); var in_single_num = parseInt(in_singleIds[is].substr(in_singleIds[is].length-6, 6), 10); if (in_single_prefix == out_prefix && in_single_num >= out_begin_num && in_single_num <= out_end_num) { $in_singleId.addClass("input_err"); alert("非连续礼品卡卡号已经在上面的连续卡号中存在了,请重新输入"); repeat = true; break; } } } if (repeat) break; // 2.5. 验证内部非连续卡号是否与外部非连续卡号重复 if(val_out_singleId!="" && val_in_singleId!=""){ for ( var os = 0; os < out_singleIds.length; os++) { for ( var is = 0; is < in_singleIds.length; is++) { if (out_singleIds[os] == in_singleIds[is]) { $in_singleId.addClass("input_err"); alert("非连续礼品卡卡号已经存在了,请重新输入"); repeat = true; break; } } if (repeat) break; } } if (repeat) break; } if (repeat) result = false; if (!result) break; } return result; }
let cont = 1; let jogoAtivo = true; let boot = false; let para = false; let nivel = ''; let tabuleiro = Array(3); tabuleiro['a'] = Array(3); tabuleiro['b'] = Array(3); tabuleiro['c'] = Array(3); tabuleiro['a']['1'] = 0; tabuleiro['a']['2'] = 0; tabuleiro['a']['3'] = 0; tabuleiro['b']['1'] = 0; tabuleiro['b']['2'] = 0; tabuleiro['b']['3'] = 0; tabuleiro['c']['1'] = 0; tabuleiro['c']['2'] = 0; tabuleiro['c']['3'] = 0; function setBot(nivelJogo) { boot = true; nivel = nivelJogo; } function reload() { window.location.reload(); } const inserirImagem = (img, id) => { document.getElementById(id).innerHTML = `<img src="./img/${img}.png">`; document.getElementById(id).setAttribute('onclick', ''); let separa = id.split('_'); tabuleiro[separa[0]][separa[1]] = img; if (verifica()) { document.getElementById('resultado').innerHTML = verifica(); window.scrollTo(0,2000); } } function entrada(id) { cont ++; if (jogoAtivo) { if (cont % 2 == 0) { inserirImagem('x', id); if (boot) { inteligentao(id); cont ++; } } else { if (!boot) { inserirImagem('o', id); } } } } function verifica() { if(tabuleiro['a']['1'] == 'x' && tabuleiro['a']['2'] == 'x' && tabuleiro['a']['3'] == 'x') { jogoAtivo = false; return "X é o vencedor"; } else if (tabuleiro['a']['1'] == 'o' && tabuleiro['a']['2'] == 'o' && tabuleiro['a']['3'] == 'o') { jogoAtivo = false; return "O é o vencedor"; } else if (tabuleiro['b']['1'] == 'x' && tabuleiro['b']['2'] == 'x' && tabuleiro['b']['3'] == 'x') { jogoAtivo = false; return "X é o vencedor"; } else if(tabuleiro['b']['1'] == 'o' && tabuleiro['b']['2'] == 'o' && tabuleiro['b']['3'] == 'o') { jogoAtivo = false; return "O é o vencedor"; } else if(tabuleiro['c']['1'] == 'x' && tabuleiro['c']['2'] == 'x' && tabuleiro['c']['3'] == 'x') { jogoAtivo = false; return "X é o vencedor"; } else if(tabuleiro['c']['1'] == 'o' && tabuleiro['c']['2'] == 'o' && tabuleiro['c']['3'] == 'o') { jogoAtivo = false; return "O é o vencedor"; } else if(tabuleiro['a']['1'] == 'x' && tabuleiro['b']['1'] == 'x' && tabuleiro['c']['1'] == 'x') { jogoAtivo = false; return "X é o vencedor"; } else if(tabuleiro['a']['1'] == 'o' && tabuleiro['b']['1'] == 'o' && tabuleiro['c']['1'] == 'o') { jogoAtivo = false; return "O é o vencedor"; } else if(tabuleiro['a']['2'] == 'x' && tabuleiro['b']['2'] == 'x' && tabuleiro['c']['2'] == 'x') { jogoAtivo = false; return "X é o vencedor"; } else if(tabuleiro['a']['2'] == 'o' && tabuleiro['b']['2'] == 'o' && tabuleiro['c']['2'] == 'o') { jogoAtivo = false; return "O é o vencedor"; } else if(tabuleiro['a']['3'] == 'x' && tabuleiro['b']['3'] == 'x' && tabuleiro['c']['3'] == 'x') { jogoAtivo = false; return "X é o vencedor"; } else if(tabuleiro['a']['3'] == 'o' && tabuleiro['b']['3'] == 'o' && tabuleiro['c']['3'] == 'o') { jogoAtivo = false; return "O é o vencedor"; } else if(tabuleiro['a']['1'] == 'x' && tabuleiro['b']['2'] == 'x' && tabuleiro['c']['3'] == 'x') { jogoAtivo = false; return "X é o vencedor"; } else if(tabuleiro['a']['1'] == 'o' && tabuleiro['b']['2'] == 'o' && tabuleiro['c']['3'] == 'o') { jogoAtivo = false; return "O é o vencedor"; } else if(tabuleiro['a']['3'] == 'x' && tabuleiro['b']['2'] == 'x' && tabuleiro['c']['1'] == 'x') { jogoAtivo = false; return "X é o vencedor"; } else if(tabuleiro['a']['3'] == 'o' && tabuleiro['b']['2'] == 'o' && tabuleiro['c']['1'] == 'o') { jogoAtivo = false; return "O é o vencedor"; } else if(cont == 10) { jogoAtivo = false; return `Deu velha! <img src='./img/palmirinha.jpg'>` } } function inteligentao(id) { para = false; let jogada = id.split('_'); jogada = jogada.toString(); if (nivel == 'facil') { if (!para && jogoAtivo) verificaDiagonal('o'); if (!para && jogoAtivo) verificaDiagonalSecundaria('o'); if (!para && jogoAtivo) verificaLinha('a', 'o'); if (!para && jogoAtivo) verificaLinha('b', 'o'); if (!para && jogoAtivo) verificaLinha('c', 'o'); if (!para && jogoAtivo) verificaDiagonalSecundaria('x'); if (!para && jogoAtivo) verificaDiagonal('x'); if (!para && jogoAtivo) verificaLinha('a', 'x'); if (!para && jogoAtivo) verificaLinha('b', 'x'); if (!para && jogoAtivo) verificaLinha('c', 'x'); if (!para && jogoAtivo) verificaColuna(1, 'o'); if (!para && jogoAtivo) verificaColuna(2, 'o'); if (!para && jogoAtivo) verificaColuna(3, 'o'); if (!para && jogoAtivo) verificaColuna(1, 'x'); if (!para && jogoAtivo) verificaColuna(2, 'x'); if (!para && jogoAtivo) verificaColuna(3, 'x'); if (!para && jogoAtivo) randown(); } else if (nivel == 'medio') { if (!para && jogoAtivo) jogaMeio(); if (!para && jogoAtivo) verificaDiagonal('o'); if (!para && jogoAtivo) verificaDiagonalSecundaria('o'); if (!para && jogoAtivo) verificaLinha('a', 'o'); if (!para && jogoAtivo) verificaLinha('b', 'o'); if (!para && jogoAtivo) verificaLinha('c', 'o'); if (!para && jogoAtivo) verificaDiagonalSecundaria('x'); if (!para && jogoAtivo) verificaDiagonal('x'); if (!para && jogoAtivo) verificaLinha('a', 'x'); if (!para && jogoAtivo) verificaLinha('b', 'x'); if (!para && jogoAtivo) verificaLinha('c', 'x'); if (!para && jogoAtivo) verificaColuna(1, 'o'); if (!para && jogoAtivo) verificaColuna(2, 'o'); if (!para && jogoAtivo) verificaColuna(3, 'o'); if (!para && jogoAtivo) verificaColuna(1, 'x'); if (!para && jogoAtivo) verificaColuna(2, 'x'); if (!para && jogoAtivo) verificaColuna(3, 'x'); if (!para && jogoAtivo) randown(); } else if (nivel == 'dificil') { if (!para && jogoAtivo) jogaMeio(); if (!para && jogoAtivo) verificaDiagonal('o'); if (!para && jogoAtivo) verificaDiagonalSecundaria('o'); if (!para && jogoAtivo) verificaLinha('a', 'o'); if (!para && jogoAtivo) verificaLinha('b', 'o'); if (!para && jogoAtivo) verificaLinha('c', 'o'); if (!para && jogoAtivo) verificaDiagonalSecundaria('x'); if (!para && jogoAtivo) verificaDiagonal('x'); if (!para && jogoAtivo) verificaLinha('a', 'x'); if (!para && jogoAtivo) verificaLinha('b', 'x'); if (!para && jogoAtivo) verificaLinha('c', 'x'); if (!para && jogoAtivo) verificaColuna(1, 'o'); if (!para && jogoAtivo) verificaColuna(2, 'o'); if (!para && jogoAtivo) verificaColuna(3, 'o'); if (!para && jogoAtivo) verificaColuna(1, 'x'); if (!para && jogoAtivo) verificaColuna(2, 'x'); if (!para && jogoAtivo) verificaColuna(3, 'x'); if (!para && jogoAtivo) jogaCanto(); if (!para && jogoAtivo) randown(); } } const verificaLinha = (indice, img) => { let c = 0; let aux = 0; for (let i = 1; i < 4; i++) { if (tabuleiro[indice][i] == img) { c ++; } } if (c == 2) { for (let i = 1; i < 4; i++) { if (tabuleiro[indice][i] == 0) { aux = i; } } if (tabuleiro[indice][aux] == 0) { inserirImagem('o', `${indice}_${aux}`); return para = true; } } } const verificaColuna = (indice, img) => { let c = 0; let col = ['a','b','c']; let aux = 0; for (let i = 0; i < 3; i++) { if (tabuleiro[col[i]][indice] == img) { c ++; } } if (c == 2) { for (let i = 0; i < 3; i++) { if (tabuleiro[col[i]][indice] == 0) { aux = i; } } if (tabuleiro[col[aux]][indice] == 0) { inserirImagem('o', `${col[aux]}_${indice}`); return para = true; } } } const verificaDiagonal = (img) => { let c = 0; if (tabuleiro['a']['1'] == img) { c ++; } if (tabuleiro['b']['2'] == img) { c ++; } if (tabuleiro['c']['3'] == img) { c ++; } if (c == 2) { if (tabuleiro['a']['1'] == 0) { inserirImagem('o', 'a_1'); return para = true; } else if (tabuleiro['b']['2'] == 0) { inserirImagem('o', 'b_2'); return para = true; } else if (tabuleiro['c']['3'] == 0) { inserirImagem('o', 'c_3'); return para = true; } } } const verificaDiagonalSecundaria = (img) => { let c = 0; if (tabuleiro['a']['3'] == img) { c ++; } if (tabuleiro['b']['2'] == img) { c ++; } if (tabuleiro['c']['1'] == img) { c ++; } if (c == 2) { if (tabuleiro['a']['3'] == 0) { inserirImagem('o', 'a_3'); return para = true; } else if (tabuleiro['b']['2'] == 0) { inserirImagem('o', 'b_2'); return para = true; } else if (tabuleiro['c']['1'] == 0) { inserirImagem('o', 'c_1'); return para = true; } } } const randown = () => { let indice = ['a','b','c']; let aleatorio1 = Math.floor(Math.random() * 3); let aleatorio2 = Math.floor(Math.random() * 3); if (tabuleiro[indice[aleatorio1]][aleatorio2] == 0) { inserirImagem('o', `${indice[aleatorio1]}_${aleatorio2}`); return para = true; } else { randown(); } } const jogaMeio = () => { if (tabuleiro['b']['2'] == 0) { inserirImagem('o','b_2'); return para = true; } else { if (cont == 2 && nivel == 'dificil') { inserirImagem('o','a_1'); return para = true; } } } const jogaCanto = () => { if (tabuleiro['a']['1'] == 0) { inserirImagem('o','a_1'); return para = true; } else if (tabuleiro['a']['3'] == 0) { inserirImagem('o', 'a_3'); return para = true; } else if (tabuleiro['c']['1'] == 0) { inserirImagem('o', 'c_1'); return para = true; } else if(tabuleiro['c']['3']) { inserirImagem('o','c_3'); return para = true; } }
import './index.css'; import { sidedrawer, drawerToggler, backdrop } from './js/UI'; import { showSideDrawer, hideSideDrawer } from './js/events/sideDrawer'; import { displayProductNutrient, closeProductNutrient } from './js/events/productNutrient'; if (drawerToggler) { drawerToggler.addEventListener('click', () => showSideDrawer(sidedrawer, backdrop)); } if (sideDrawerCloseBtn) { sideDrawerCloseBtn.addEventListener('click', () => hideSideDrawer(sidedrawer, backdrop)); } window.displayProductNutrient = displayProductNutrient; window.closeProductNutrient = closeProductNutrient;
// import React, { useRef } from "react"; // import { useLocalStore, useObserver } from "mobx-react-lite"; // import Typography from "@material-ui/core/Typography"; // import { createStyles, makeStyles, Theme } from "@material-ui/core/styles"; // import Checkbox from "@material-ui/core/Checkbox"; // import FormControlLabel from "@material-ui/core/FormControlLabel"; // import IconButton from "@material-ui/core/IconButton"; // import TextField from "@material-ui/core/TextField"; // import Input from "@material-ui/core/Input"; // import InputLabel from "@material-ui/core/InputLabel"; // import InputBase from "@material-ui/core/InputBase"; // import { KeyboardDateTimePicker } from "@material-ui/pickers"; // import InputAdornment from "@material-ui/core/InputAdornment"; // import Avatar from "@material-ui/core/Avatar"; // import Autocomplete from "@material-ui/lab/Autocomplete"; // import Chip from "@material-ui/core/Chip"; // import { DateTime, Duration } from "luxon"; // // import debugjs from "debug"; // import { ytheme } from "../ytheme"; // import { EditableValue } from "../../models/edited"; // import { ValueRenderMode } from "../ValueContext"; // import { aggDuration, durationEngStrToDurationObj, durationObjToEngStr } from "Ystd"; // // const debugRender = debugjs("render"); // type SignChar = "+" | "-"; // // const useStyles = makeStyles((theme: Theme) => // createStyles({ // task: { // padding: ytheme.padding4, // margin: ytheme.margin3, // display: "flex", // flexDirection: "column", // }, // typography: { // margin: ytheme.margin4, // }, // textField: { // //margin: ytheme.margin3, // padding: "0px", // }, // rating: { // margin: ytheme.margin3, // fontSize: "4rem", // alignSelf: "center", // }, // checkBox: { // margin: ytheme.margin3, // fontSize: "4rem", // alignSelf: "center", // }, // inputRoot: { // color: "inherit", // }, // inputInput: { // //padding: "inherit", // padding: "2px 0px 3px 0px", // // // vertical padding + font size from searchIcon // // paddingLeft: `calc(1em + ${theme.spacing(4)}px)`, // // transition: theme.transitions.create("width"), // // width: "100%", // // [theme.breakpoints.up("md")]: { // // width: "20ch", // // }, // }, // }) // ); // // export interface ValueProps { // m: EditableValue; // editor?: boolean; // disabled?: boolean; // textOnly?: boolean; // [key: string]: any; // } // // export const Value: React.FC<{ // m: EditableValue; // mode?: ValueRenderMode; // editor?: boolean; // disabled?: boolean; // textOnly?: boolean; // }> = ({ m, mode, editor, disabled, textOnly, ...otherProps }) => { // const editorRef = useRef(null); // const state = useLocalStore(() => ({ // editing: false, // focusedOnce: false, // toggleEditing() { // state.editing = !state.editing; // }, // turnOffEditing() { // state.editing = false; // }, // turnOnEditing() { // state.editing = true; // state.focusedOnce = false; // }, // // prettier-ignore // sign: "+" as SignChar, // setSignToPlus() { // state.sign = "+"; // }, // setSignToMinus() { // state.sign = "-"; // }, // getDuration() { // return durationObjToEngStr(Duration.fromISO(m), 0); // }, // setDuration(eventOrValue: any) { // if (m.et !== "duration") { // const error = new Error( // `CODE00000126 Incompartible type: expected 'duration' got '${m.et}'.` // ); // console.error(error); // throw error; // } // const v1 = (eventOrValue.target ? eventOrValue.target.value : eventOrValue) || ""; // const v2 = durationEngStrToDurationObj(v1); // m.set(Duration.fromObject(v2).toISO()); // }, // durPlus5m() { // if (m.et !== "duration") { // const error = new Error( // `CODE00000127 Incompartible type: expected 'duration' got '${m.et}'.` // ); // console.error(error); // throw error; // } // const sgn = state.sign === "+" ? 1 : -1; // const vv = Duration.fromISO(m); // vv.minutes += sgn * 5; // const avv = Duration.fromObject(aggDuration(vv)); // m.set(avv.toISO()); // }, // durPlus1h() { // if (m.et !== "duration") { // const error = new Error( // `CODE00000128 Incompartible type: expected 'duration' got '${m.et}'.` // ); // console.error(error); // throw error; // } // const sgn = state.sign === "+" ? 1 : -1; // const vv = Duration.fromISO(m); // vv.hours += sgn * 1; // const avv = Duration.fromObject(aggDuration(vv)); // m.set(avv.toISO()); // }, // durPlus1d() { // if (m.et !== "duration") { // const error = new Error( // `CODE00000129 Incompartible type: expected 'duration' got '${m.et}'.` // ); // console.error(error); // throw error; // } // const sgn = state.sign === "+" ? 1 : -1; // const vv = Duration.fromISO(m); // vv.days += sgn * 1; // const avv = Duration.fromObject(aggDuration(vv)); // m.set(avv.toISO()); // }, // datePlus5m() { // if (m.et !== "date") { // const error = new Error(`CODE00000130 Incompartible type: expected 'date' got '${m.et}'.`); // console.error(error); // throw error; // } // const sgn = state.sign === "+" ? 1 : -1; // const vv = DateTime.fromJSDate(m || new Date()); // const vv2 = vv.plus(sgn * 5 * 60 * 1000); // const avv = vv2.toJSDate(); // m.set(avv); // }, // datePlus1h() { // if (m.et !== "date") { // const error = new Error(`CODE00000001 Incompartible type: expected 'date' got '${m.et}'.`); // console.error(error); // throw error; // } // const sgn = state.sign === "+" ? 1 : -1; // const vv = DateTime.fromJSDate(m || new Date()); // const vv2 = vv.plus(sgn * 60 * 60 * 1000); // const avv = vv2.toJSDate(); // m.set(avv); // }, // datePlus1d() { // if (m.et !== "date") { // const error = new Error(`CODE00000002 Incompartible type: expected 'date' got '${m.et}'.`); // console.error(error); // throw error; // } // const sgn = state.sign === "+" ? 1 : -1; // const vv = DateTime.fromJSDate(m || new Date()); // const vv2 = vv.plus(Duration.fromObject({ days: 1 })); // const avv = vv2.toJSDate(); // m.set(avv); // }, // })); // // return useObserver(() => { // debugRender("OLD_Value_Component"); // const classes = useStyles(); // // // @ts-ignore // if (!m) return <div>CODE00000003 No value supplied!</div>; // // // const xx = ( // // <FormControl disabled> // // <InputLabel>Name</InputLabel> // // <Input value={name} onChange={handleChange} /> // // {/*<FormHelperText>Disabled</FormHelperText>*/} // // </FormControl> // // ); // const mode2: ValueRenderMode = (mode === "textInlineEditor" ? "text" : mode) || "form"; // const onClickToggleEditing = mode === "textInlineEditor" ? state.toggleEditing : undefined; // // switch (m.et) { // case "string": { // switch (mode2) { // case "form": // return ( // <> // <InputLabel>{m.prop}</InputLabel> // <Input // className={classes.textField} // value={m[prop]} // onChange={m.set} // disabled={disabled} // {...otherProps} // /> // </> // ); // case "text": // if (!state.editing) // return ( // <Typography onClick={onClickToggleEditing} {...otherProps}> // {m} // </Typography> // ); // else // return ( // <Typography component={"span"} {...otherProps}> // <InputBase // ref={editorRef} // className={classes.textField} // value={m[prop]} // onChange={m.set} // onBlur={state.turnOffEditing} // autoFocus // classes={{ // root: classes.inputRoot, // input: classes.inputInput, // }} // /> // </Typography> // ); // } // } // case "boolean": { // return ( // <FormControlLabel // control={ // <Checkbox // className={classes.textField} // checked={!!m} // onChange={m.set} // disabled={disabled} // {...otherProps} // /> // } // label={m.prop} // /> // ); // } // case "date": { // return ( // <div> // <KeyboardDateTimePicker // label={m.prop} // // value={DateTime.fromISO("2010-01-01")} // value={m || ""} // onChange={m.set} // onError={console.log} // ampm={false} // // format="yyyy-MM-dd HH:mm" // format="dd.MM.yyyy HH:mm" // disablePast // showTodayButton // disabled={disabled} // {...otherProps} // /> // <IconButton onClick={state.datePlus5m}> // <Avatar>{state.sign}5m</Avatar> // </IconButton> // <IconButton onClick={state.datePlus1h}> // <Avatar>{state.sign}h</Avatar> // </IconButton> // <IconButton onClick={state.datePlus1d}> // <Avatar>{state.sign}d</Avatar> // </IconButton> // </div> // ); // } // case "duration": { // return ( // <> // <InputLabel>{m.prop}</InputLabel> // <Input // className={classes.textField} // value={state.getDuration} // onChange={state.setDuration} // disabled={disabled} // endAdornment={ // <InputAdornment position="end"> // <IconButton onClick={state.durPlus5m}> // <Avatar>{state.sign}5m</Avatar> // </IconButton> // <IconButton onClick={state.durPlus1h}> // <Avatar>{state.sign}h</Avatar> // </IconButton> // <IconButton onClick={state.durPlus1d}> // <Avatar>{state.sign}d</Avatar> // </IconButton> // </InputAdornment> // } // {...otherProps} // /> // </> // ); // } // case "enum": { // return ( // <Autocomplete // id="combo-box-demo" // options={m.opts.values} // getOptionLabel={(option) => option} // style={{ width: 300 }} // renderInput={(params) => ( // <TextField // {...params} // className={classes.textField} // label={m.prop} // value={m[prop]} // onChange={m.set} // disabled={disabled} // {...otherProps} // /> // )} // /> // ); // } // case "labels": { // return ( // <Autocomplete // multiple // id="size-small-standard-multi" // size="small" // options={m.opts.getAutocompleteItemsSync()} // getOptionLabel={(option) => option} // value={m[prop]} // onChange={m.set} // renderInput={(params) => ( // <TextField // {...params} // variant="standard" // className={classes.textField} // label={m.prop} // disabled={disabled} // {...otherProps} // /> // )} // /> // ); // } // case "link": { // return ( // <Autocomplete // multiple // id="size-small-standard-multi" // size="small" // options={m.opts.getAutocompleteItemsSync()} // getOptionLabel={m.opts.getTitle} // value={m[prop]} // onChange={m.set} // renderInput={(params) => ( // <TextField // {...params} // variant="standard" // className={classes.textField} // label={m.prop} // disabled={disabled} // {...otherProps} // /> // )} // /> // ); // } // case "multiLink": { // return ( // <Autocomplete // multiple // id="size-small-standard-multi" // size="small" // options={m.opts.getAutocompleteItemsSync()} // getOptionLabel={m.opts.getTitle} // value={m[prop]} // onChange={m.set} // renderInput={(params) => ( // <TextField // {...params} // variant="standard" // className={classes.textField} // label={m.prop} // disabled={disabled} // {...otherProps} // /> // )} // renderTags={(value, getTagProps) => // value.map((option, index) => ( // <Chip // variant="outlined" // label={m.opts.getTitle} // size="small" // {...getTagProps({ index })} // /> // )) // } // /> // ); // } // default: // return ( // <div>CODE00000004 Unsupported value m.et={(m as any).et || "undefined"}</div> // ); // } // }); // }; // // if ((module as any).hot) { // (module as any).hot.accept(); // }
$('#logoutButton').click(function(e){ console.log('logoutButton'); });
function onLoginClick() { window.location.href = "/login"; } function onRegisterClick() { window.location.href = "/register"; } function onAboutClick() { window.location.href = "/about"; } function onContactClick() { window.location.href = "/contact"; }
import React, { Suspense } from 'react'; import PropTypes from 'prop-types'; import { renderClientsRoutes } from '../../utils/routing.utils'; const UserRoutes = ({ initialized, modules, pages }) => ( <Suspense fallback={<div />}>{initialized && renderClientsRoutes({ pages, modules })}</Suspense> ); UserRoutes.propTypes = { initialized: PropTypes.bool.isRequired, modules: PropTypes.shape({}).isRequired, pages: PropTypes.shape({}).isRequired, }; export default UserRoutes;
export const LOAD_DETAILS = 'my-project/details/LOAD_DETAILS'; export const LOAD_DETAILS_SUCCESS = 'my-project/details/LOAD_DETAILS_SUCCESS'; export const LOAD_DETAILS_FAILURE = 'my-project/details/LOAD_DETAILS_FAILURE'; export const LOAD_REVIEWS = 'my-project/details/LOAD_REVIEWS'; export const LOAD_REVIEWS_SUCCESS = 'my-project/details/LOAD_REVIEWS_SUCCESS'; export const LOAD_REVIEWS_FAILURE = 'my-project/details/LOAD_REVIEWS_FAILURE'; export const LOAD_SIMILAR_VENDORS = 'my-project/details/LOAD_SIMILAR_VENDORS'; export const LOAD_SIMILAR_VENDORS_SUCCESS = 'my-project/details/LOAD_SIMILAR_VENDORS_SUCCESS'; export const LOAD_SIMILAR_VENDORS_FAILURE = 'my-project/details/LOAD_SIMILAR_VENDORS_FAILURE'; export const LOAD_AMINITIES = 'my-project/details/LOAD_AMINITIES'; export const LOAD_AMINITIES_SUCCESS = 'my-project/details/LOAD_AMINITIES_SUCCESS'; export const LOAD_AMINITIES_FAILURE = 'my-project/details/LOAD_AMINITIES_FAILURE'; export const LOAD_POLICIES = 'my-project/details/LOAD_POLICIES'; export const LOAD_POLICIES_SUCCESS = 'my-project/details/LOAD_POLICIES_SUCCESS'; export const LOAD_POLICIES_FAILURE = 'my-project/details/LOAD_POLICIES_FAILURE'; export const LOAD_AVAILABLE_AREAS = 'my-project/details/LOAD_AVAILABLE_AREAS'; export const LOAD_AVAILABLE_AREAS_SUCCESS = 'my-project/details/LOAD_AVAILABLE_AREAS_SUCCESS'; export const LOAD_AVAILABLE_AREAS_FAILURE = 'my-project/details/LOAD_AVAILABLE_AREAS_FAILURE'; export const LOAD_GALLERY = 'my-project/details/LOAD_GALLERY'; export const LOAD_GALLERY_SUCCESS = 'my-project/details/LOAD_GALLERY_SUCCESS'; export const LOAD_GALLERY_FAILURE = 'my-project/details/LOAD_GALLERY_FAILURE'; export const LOAD_NOTES = 'my-project/details/LOAD_NOTES'; export const LOAD_NOTES_SUCCESS = 'my-project/details/LOAD_NOTES_SUCCESS'; export const LOAD_NOTES_FAILURE = 'my-project/details/LOAD_NOTES_FAILURE'; export const CLEAR_DATA = 'my-project/details/CLEAR_DATA';
import React, { Component } from 'react'; import Helmet from 'react-helmet'; import { Well } from 'react-bootstrap'; import { SignalBar, LocationBar, WifiBar, OrientationBar } from '../../components'; export default class SocketMe extends Component { state = { }; render() { const styles = require('./SocketMe.scss'); return ( <div className={styles.about}> <div className="container"> <Well> <h1>SocketMe</h1> <Helmet title="SocketMe" /> <LocationBar /> <WifiBar /> <SignalBar /> <OrientationBar /> </Well> </div> </div> ); } }
const fName = document.querySelector('#fName'); const lName = document.querySelector('#lName'); const uName = document.querySelector('#uName'); const mail = document.querySelector('#mail'); const pWord = document.querySelector('#pWord'); const sex = document.querySelector('#sex'); const age = document.querySelector('#age'); const login = document.querySelector('#login') const sForm = document.querySelector('#sForm'); sForm.addEventListener('submit', signUp); let savedData = JSON.parse(localStorage.getItem('details')); function signUp(e) { e.preventDefault() let pDetails = { 'first Name': fName.value, 'last Name': lName.value, 'user Name': uName.value, email: mail.value, password: pWord.value, sex: sex.value, age: age.value } let detailsArr; if (fName.value == '' || lName.value == '' || uName.value == '' || mail.value == '' || pWord.value == '' || sex.value == '' || age.value == '') { alert('Please fill in all the details') } else if (localStorage.getItem('details') == null) { detailsArr = []; detailsArr.push(pDetails); localStorage.setItem('details', JSON.stringify(detailsArr)); location.replace('login.html'); } else if (localStorage.getItem('details')) { detailsArr = JSON.parse(localStorage.getItem('details')); let filterArr = detailsArr.filter((item) => { return item['user Name'] === uName.value }); if (filterArr.length > 0) { alert('User name is already in use. Please choose another user name') } else { detailsArr.push(pDetails); localStorage.setItem('details', JSON.stringify(detailsArr)); location.replace('login.html'); } } } login.addEventListener('click', logIn); function logIn() { location.replace('login.html') }
import moment from 'moment'; import * as requestApi from '../config/requestApi'; import applicationService from '../services/application'; export default { namespace: 'home', state: { monthIn: { RECOMMEND: '', 'SOURCE_AWARD': '', 'SALES': '', 'LIVE_EARNINGS': '', }, userPrizeInfo: { // 中奖信息 bigPrizeInfo: [''], cashPrizeInfo: [''], reaPackageWiners: [''], prizeCount: 0, }, problemList: [], }, reducers: { save(state, action) { return { ...state, ...action.payload, }; }, }, effects: { * fetchHomeData({ payload }, { select, put, call }) { yield put({ type: 'fetchBannerList' }); yield put({ type: 'unionIndexPieEarningsStatistics' }); yield put({ type: 'jprizeUserPrize' }); yield put({ type: 'getNotMerchantRole' }); }, * fetchBannerList(_, { select, put, call }) { try { let { regionCode, userLocations } = yield select(state => state.application); if (!regionCode) { regionCode = yield call(applicationService.getReginCode, userLocations); } const bannerLists = yield call(requestApi.requestSOMBannerList, { regionCode, bannerModule: 'ALLIANCE', }); yield put({ type: 'shop/save', payload: { bannerLists: bannerLists || [] } }); } catch (error) { console.log(error); } }, * unionIndexPieEarningsStatistics({ payload }, { select, put, call }) { const merchantId = yield select(state => state.user.user.merchantId); if (!merchantId) return; try { const monthIn = yield call(requestApi.unionIndexPieEarningsStatistics, { startTime: moment().startOf('month').format('X'), endTime: moment().endOf('month').format('X'), merchantId, }); yield put({ type: 'save', payload: { monthIn } }); } catch (error) { console.log(error); } }, * jprizeUserPrize({ payload }, { select, put, call }) { try { // 获取中奖信息 const userPrizeInfo = yield call(requestApi.jprizeUserPrize); yield put({ type: 'save', payload: { userPrizeInfo } }); } catch (error) { console.log(error); } }, * getNotMerchantRole({ payload }, { select, put, call }) { try { // 如果不是商户,获取非商户的默认权限,如果分号不是归属于主账号的商户身份,获取非商户的权限 const userInfo = yield select(state => state.user.user); const identityStatuses = userInfo.identityStatuses; let isMerchant = false; if (identityStatuses && identityStatuses.length > 0) { isMerchant = identityStatuses.find(item => (item.auditStatus === 'active' && item.merchantType === 'shops')); } if (!isMerchant) { console.log(`非商户身份${userInfo.isAdmin ? '(主账号)' : '(分号)'}登陆获取权限`); yield put({ type: 'user/mUserPermission' }); } else { // 如果是商户,判断是否有店铺,如果有店铺,chooseShop会选择默认店铺登陆,并获取全县 // 这里处理,身份是商户,但是没有店铺的情况 if (!(yield select(state => state.user.merchantData)).shops) { console.log(`${userInfo.isAdmin ? '(主账号)' : '(分号)'}无店铺登陆获取权限`); yield put({ type: 'user/mUserPermission' }); } } } catch (error) { console.log(error); } }, * fetchProblemList({ payload }, { select, put, call }) { try { const { params } = payload; const response = yield call(requestApi.getCommonQuestion, params); yield put({ type: 'save', payload: { problemList: response || [] } }); console.log('problemLis', response); } catch (error) { console.log('fetchProblemList Error', error); } }, }, };
$(function () { num() allTopic('') $('.head').load("top.html") }) //头部数字统计 var num=function () { $.getJSON('http://127.0.0.1:9999/topic/num',function (response) { if(response.responseCode=='1000'){ $('.num1').text(response.content.today) $('.num2').text(response.content.yesterday) $('.num3').text(response.content.total) } }) } //发帖的接口 $('.topic').on('click',function () { var xh=localStorage.getItem("xh"); if(xh!=null){ var ftnr = $('.area').val(); var user_xh= localStorage.getItem("xh"); if(ftnr !=null && ftnr !=''){ $.ajax({ method:'GET', data:{ ftnr:ftnr, user_xh:user_xh }, url : 'http://127.0.0.1:9999/topic/startTopic', success:function () { num(); allTopic(''); } }) $('.area').val('') } }else{ alert("亲,您还没登陆呢"); } }) //回帖的接口 $('.ht').on('click',function () { var htnr=$('.htnr').val(); var user_xh=localStorage.getItem("xh"); var topic_xh=$('.ycxh').text(); if(htnr !=null && htnr !=''){ $.ajax({ method:'GET', data:{ htnr:htnr, user_xh:user_xh, topic_xh:topic_xh }, url : 'http://127.0.0.1:9999/topic/reply', success:function () { $('.htk').slideUp(); num(); allTopic(''); } }) $('.htnr').val('') } }) //弹出回帖框 function ht(data) { var xh=localStorage.getItem("xh"); if(xh!=null){ $('.htk').slideDown(); $('.ycxh').text($(data).children().text()); }else{ //alert("亲,请先登录!!!!") } } //删除回帖框 $('.del').on('click',function () { $('.htk').slideUp(); }) $('.searchReply').on('click',function () { var key= $('.topicKey').val(); allTopic(key,1,15); }) //全部主题帖的接口 var allTopic=function (key,pageIndex,pageSize) { pageSize=15; $('.list').empty(); var data = { key : key, pageIndex : pageIndex, pageSize :pageSize, }; $.ajax({ method: 'GET', data: data, url: 'http://127.0.0.1:9999/topic/allTopic', success:function (response) { if(response.responseCode == '1000') { $('.num').text(response.content.total) if (response.content.list.length > 0) { for(var i = 0;i < response.content.list.length;i++){ var newTr = '<tr>' + '<td>' + response.content.list[i].rowId +'</td>' + '<td>' + response.content.list[i].ftnr + '</td>' + '<td>' + response.content.list[i].name + '</td>' + '<td>' + response.content.list[i].htl + '</td>' + '<td>' + response.content.list[i].zhhtr + '</td>' + '<td class="reply" onclick="ht(this)"><span class="topic_xh" style="display: none">'+response.content.list[i].xh +'</span>回帖</td>' + '</tr>' $('.list').append(newTr) } } $("#page").paging({ pageNo: response.content.pageNum, totalPage: response.content.pages, totalSize: response.content.total, callback: function(num) { var key= $('.topicKey').val(); allTopic(key,num,7) } }) } } }) num() }
/** * Copyright (c) 2014, 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ /* * Your dashboard ViewModel code goes here */ define(['ojs/ojcore', 'knockout', 'jquery', 'appController'], function (oj, ko, $, app, data) { function DashboardViewModel() { var self = this; self.headerConfig = {'viewName': 'header', 'viewModelFactory': app.getHeaderModel()}; self.footerConfig = {'viewName': 'footer', 'viewModelFactory': app.getFooterModel()}; self.dbList = ["invStatus", "parts", "schedule", "binPallet"]; } return new DashboardViewModel(); } );
import React, { useEffect, useState } from 'react'; import './index.css'; import SearchField from 'react-search-field'; import Header from '../Header'; import ApiService from '../../services'; import Loader from '../Loader'; import View from '../View'; // Search bar, making an api call based on keyword entered. const Search = () => { //Using react hooks here to persist the state and make the api call const [state, setState] = useState({ keyword: '', data: {}, isLoading: false }); useEffect(() => { state.keyword && ApiService.getSearchKeyword(state.keyword).then(({ data }) => { setState({ data, isLoading: false, keyword: state.keyword }); }); }, [state.keyword]); //updating the dom on when ever change to the keyword const onClick = (keyword) => { setState({ keyword, isLoading: true, }); }; //have loader in place until the data is returned from api if (state.isLoading) { return ( <Loader loading /> ); } console.log('state:::', state.data.articles); const { data: { articles = [] }, keyword = '' } = state; return ( <div> <Header /> <div style={{paddingTop:"40px"}}> <SearchField classNames="search" placeholder="Search with the keyword..." onSearchClick={onClick} /> </div> {/* View component is reuseable */} {articles && <View keyword={keyword} articles={articles} />} </div> ); }; export default Search;
function suma(a, b){ return a + b; } module.exports = { suma: function (a, b) { return a+b; }, resta: function (a, b){ return a-b; }, division: function (a, b){ return a / b; }, multiplicacion: function (a, b){ return a * b; }, par: function (a){ if(a % 2 == 0){ return true; }else { return false; } }, elevado: function(a, b){ return a ** b; } }
module.exports = { name: 'test', description: 'TestCommand', execute(message, args) { message.channel.send('Rats are being experimented on'); }, };
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's // vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. JavaScript code in this file should be added after the last require_* statement. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery /* global $, zenscroll */ class Preview { constructor() { console.log('Init Preview.js') // eslint-disable-line no-console this.selectedId = null window.addEventListener('message', event => this.onIframeMessage(event), false) this.disableInteractions() //this.observeScroll() } onIframeMessage(event) { if (event.origin !== window.location.origin) return if (event.data.action == 'highlight') { this.highlightBlock(event.data.id, 'message') } else { this.setApproval(event.data.id, event.data.approved) } } observeScroll() { this.observer = new IntersectionObserver(entries => this.onObserverChange(entries), { rootMargin: '-49% 0px -49% 0px', }) $('.review-block').each((index, element) => { this.observer.observe(element) }) } onObserverChange(entries) { if (this.disableObserver) return entries.forEach(entry => { if (entry.isIntersecting) { this.highlightBlock(entry.target.dataset.id, 'block') return } }) } disableInteractions() { $('a[href], button, input, select').on('click', function(event) { event.preventDefault() event.stopPropagation() return false }).on('focus', function(event) { event.target.blur() event.preventDefault() event.stopPropagation() return false }).css('cursor', 'not-allowed') } highlightBlock(id, source) { if (this.selectedId) { $(`.review-block[data-id="${this.selectedId}"]`).removeClass('active') $(`.review-button[data-id="${this.selectedId}"]`).removeClass('active') } this.selectedId = id const $blocks = $(`.review-block[data-id="${id}"]`).addClass('active') // const $buttons = $(`.review-button[data-id="${id}"]`).addClass('active') if (source == 'message') { this.disableObserver = true zenscroll.center($blocks[0], 1000, 0, () => { this.disableObserver = false }) } } setApproval(id, approved) { $(`.review-block[data-id="${id}"]`).toggleClass('approved', approved) } } $(document).on('ready', () => { new Preview() })
var simd = {"4RL":["15.02","f"]}; loaded();
// 系统繁忙 export function systemBusy() { } // 发送错误 export function systemPutError() { wx.showModal({ title: '出错啦', content: '填写信息有误', showCancel: false }) } // 获取错误 export function systemGetError() { wx.showModal({ title: '出错啦', content: '找不到该条记录', showCancel: false }) } // 根据非200的状态码返回对应的信息 export function errorStatus(result) { const status = result.status // 逻辑错误 if(status == 401) { wx.showModal({ title: '出错啦', content: result.message, showCancel: false }) } // 没有登录或权限 if(status == 403) { wx.showModal({ title: '请先登录', content: '您还没有登录', success(res) { if(res.confirm) { wx.redirectTo({ url: '/pages/login/login', }) } } }) } // 系统繁忙 if(status == 500) { wx.showModal({ title: '系统异常', content: '系统繁忙请稍后再试', showCancel: false }) } }
window.addEventListener("load", function (event) { var url_string = window.location.href; var url = new URL(url_string); var projectId = url.searchParams.get("project-id"); if (projectId != null) { $('#project option[value=' + projectId + ']').prop('selected', true); loadBillData(); } }); $("#project").change(function () { loadBillData(); }); var ajax = webix.ajax().headers({ 'Content-type': 'application/json' }) function loadBillData() { ajax.get("http://localhost:8080/async-controller?command=load-tasks-information", {"project-id": $("#project").val()}) .then((response) => response.json()) .then((data) => { var text = ''; var amountDue = 0; for (let i = 0; i < data.length; i++) { var workerSalary = data[i].hours * data[i].salary; text += data[i].name + ' - ' + workerSalary + ', '; amountDue += workerSalary; } $("#amount").val(amountDue); $("#information").val(text); }) } var billCreationInputs; var billCreationPatterns; window.addEventListener("load", function (event) { const amountRegex = new RegExp(document.getElementById('regex-amount').textContent); const informationRegex = new RegExp(document.getElementById('regex-information').textContent); billCreationInputs = document.querySelectorAll('.form-control'); billCreationPatterns = { amount: amountRegex, information: informationRegex }; billCreationInputs.forEach((input) => { input.addEventListener('keyup', (e) => { validate(e.target, billCreationPatterns[e.target.attributes.id.value]); }); }); }); function validateBillForm() { return validateInputs(billCreationInputs, billCreationPatterns); }
/** * Created by Cjy on 2017/08/05. */ Ext.define('Admin.store.photoArborescence.PhotoArborescence', { extend: 'Ext.data.TreeStore', requires: [ 'Common.Config' ], storeId: 'photoArborescence.PhotoArborescence', root: { id: 0, text: '百胜' }, proxy: { type: 'ajax', api: { read: Common.Config.requestPath('Photo', 'queryPhotoArborescence') }, reader: { type: 'json', rootProperty: 'data' } } });
/** * Created by iraklitbz on 18/04/16. */ /** * Home controller * * @param $rootScope * @param $scope * @constructor */ function PublishCtrl ($rootScope, $scope, $window) { } app .controller('PublishCtrl', [ '$rootScope', '$scope', '$window', PublishCtrl ]);
/** * FuentesService.js * * @description :: Servicio de revision de fuentes, activa y desactiva fuentes segun sea necesario. * @docs :: TODO */ var colors = require('colors'), later = require('later'); module.exports.start = function(){ console.log("info: ".green + "Fuentes check background service starting..."); RevisarFuentes(); var sched = later.parse.text('every 30 seconds'), timer = later.setInterval( RevisarFuentes, sched ); function RevisarFuentes(){ console.log("info: ".green + "Checking Fuentes on all active Tableros"); // Traemos los tableros activos y revisamos las fuentes de cada uno Tablero.find().where({ active: true }).exec( function( err, tableros){ if( err ){ console.log( err ); }else{ for (var i = 0; i < tableros.length; i++) { console.log(" "); console.log( "========".grey ); console.log(" "); console.log("Tablero Active: ".cyan + tableros[i].name + " id: " + tableros[i].id); console.log(" "); Fuente.find({ entablero: tableros[i].id }).exec( function( err, fuentes ){ if( err ){ console.log( err ); }else{ for (var i = 0; i < fuentes.length; i++) { ActivarDesactivarFuente( fuentes[i] ); } console.log( "========".grey ); console.log(" "); } }); } } }); // Traemos los tableros activos y apagamos sus fuentes sin importar el estado Tablero.find().where({ active: false }).exec( function( err, tableros){ if( err ){ console.log( err ); }else{ for (var i = 0; i < tableros.length; i++) { console.log(" "); console.log( "========".grey ); console.log(" "); console.log("Tablero Inactive: ".red + tableros[i].name ); console.log(" "); Fuente.find({ entablero: tableros[i].id }).exec( function( err, fuentes ){ if( err ){ console.log( err ); }else{ for (var i = 0; i < fuentes.length; i++) { if( fuentes[i].active === false ){ console.log( colors.red( " Fuente " + fuentes[i].id + " inactive" ) ); }else{ console.log( colors.green( " Fuente " + fuentes[i].id + " active" ) ); } InfoFuente( fuentes[i] ); DesactivarFuente( fuentes[i].id, fuentes[i].network, fuentes[i].query ); } console.log( "========".grey ); console.log(" "); } }); } } }); } function ActivarDesactivarFuente( fuente ){ if( fuente.active === false ){ console.log( colors.red( " Fuente " + fuente.id + " inactive" ) ); InfoFuente( fuente ); DesactivarFuente( fuente.id, fuente.network, fuente.query ); }else{ console.log( colors.green( " Fuente " + fuente.id + " active" ) ); InfoFuente( fuente ); ActivarFuente( fuente.id, fuente.network, fuente.query, fuente.entablero ); } } function ActivarFuente( id, network, query, tablero ){ if( network === "twitter" ){ var activar = TwitterStream.requestStream( id, 'statuses/filter', 'tweet' , { track: query }, tablero ); } if( network === "instagram" ){ var activar = InstagramService.RequestRecentFromTag( id, query, tablero ); } if( network === "facebook" ){ console.log(" Network: ".red + "No se activar facebook" ); } if( network === "youtube" ){ var activar = YoutubeService.requestSearch( id, query, tablero ); } } function DesactivarFuente( id, network, query ){ if( network === "twitter" ){ var desactivar = TwitterStream.closeStream( id ); } if ( network === "instagram" ){ var desactivar = InstagramService.StopRecentFromTag( id ); } if( network === "facebook" ){ console.log(" Network: ".red + "No se desactivar facebook" ); } if( network === "youtube" ){ var desactivar = YoutubeService.stopSearch( id ); } } function InfoFuente( fuente ){ console.log(" Network: ".magenta + fuente.network ); console.log(" Query: ".magenta + fuente.query ); console.log(" "); } } module.exports.checkActive = function( id, callback, done ){ Fuente.find().where({ id: id }).limit(1).exec( function( err, fuente ){ if( err ){ return console.log( err ); }else{ if( typeof fuente[0] != 'undefined' ){ if( fuente[0].active ){ console.log("info: ".green + "La fuente está activa: " + fuente[0].active); Tablero.find().where({ id: fuente[0].entablero }).limit(1).exec( function( err, tablero ){ if( err ){ return console.log( err ); }else{ if( typeof tablero[0] != 'undefined' ){ console.log("info: ".green + "El tablero está activo: " + tablero[0].active); if( tablero[0].active ){ callback(); }else{ console.log("info: ".green + "El tablero ya no está activo" ); done(); } }else{ console.log("info: ".green + "El tablero ya no existe" ); done(); } } }); }else{ done(); } }else{ console.log("info: ".green + "La fuente ya no existe" ); done(); } } }); }
/// <reference path="../include.d.ts" /> var rp = require('request-promise'); var Promise = require('bluebird'); var cheerio = require('cheerio'); var ew = require('node-xlsx'); var fs = require('fs'); var savePic = require('../imageProcessor').savePic; var columns = ['Product Name','Product Category', 'Product image name', 'Product descriptions', 'Product specifications']; var sheet = {name: 'result', data: []}; sheet.data.push(columns); var rows = sheet.data; var timeout = 1500; // rp = rp.defaults({proxy : 'http://test2.qypac.net:25001', timeout: 30000}); /** compose url by yourself */ var urls = fs.readFileSync('links.txt').toString().split('\r\n'); // urls = urls.slice(0, 10); /** function to print excel */ var printToExcel = function () { var buffer = ew.build([sheet]); fs.writeFileSync('dewalt.xlsx', buffer); console.log('Excel Printed'); } Promise.map(urls, singleRequest, {concurrency: 3}).then(printToExcel); /** Single Req */ function singleRequest(url) { var options = { method: 'GET', uri: url, gzip: true }; return rp(options) .then(function (body) { var $ = cheerio.load(body); var row = []; var category = []; $('.breadcrumb-trail li').each(function(index, element) { var cate = $(this).text().trim(); category.push(cate); }); var categoryString = category.join(' > '); var name = $('.pdp-details__name-wrapper').text().trim(); var description = $('.pdp-details__description').text().trim(); var specs = []; $('.pdp-specs__specifications li').each(function(index, element) { var key = $(this).find('strong').text().trim(); var value = $(this).find('span').text().trim(); specs.push(key + ' = ' + value); }); var imageUrl = 'http://www.dewalt.com' + $('.pdp-imagery__image--zoom').attr('src').replace('&showdefaultimage=true', ''); // var imageName = $('.pdp-details__sku').text().trim() + '.jpg'; var imageName = url.split('/')[url.split('/').length - 1] + '.jpg'; row = [name, categoryString, imageName, description].concat(specs); rows.push(row); if (fs.existsSync('images/' + imageName)) { console.log('Image already fetched, pass'); return new Promise(function (res, rej) { setTimeout(function () { res(url); }, timeout); }); } else { console.log('Processing ' + imageUrl); return savePic(imageUrl, 'images/' + imageName); } }).then(function (url) { console.log(url + ' was done'); }).catch(function (err) { //handle errors console.log(err); }); }
var sql = require('./BaseModel'); // const Config = require('../globals/Config'); var timeController = require('../controllers/TimeController'); // const _config = new Config(); var Task = function (task) { this.task = task.task; this.status = task.status; this.created_at = new Date(); }; Task.getBookingBy = function getBookingBy(data) { return new Promise(function (resolve, reject) { var str = "SELECT * FROM tb_booking WHERE deleted = 0 AND about_code = '" + data.about_code + "'"; console.log(str); sql.query(str, function (err, res) { if (err) { console.log("error: ", err); const require = { data: [], error: err, query_result: false, server_result: true }; resolve(require); } else { const require = { data: res, error: [], query_result: true, server_result: true }; resolve(require); } }); }); } Task.getBookingByCustomer = function getBookingByCustomer(data) { return new Promise(function (resolve, reject) { var str = "SELECT * FROM tb_booking " + " LEFT JOIN tb_about ON tb_about.about_code = tb_booking.about_code " + " WHERE tb_booking.deleted = '0' " + " AND tb_booking.about_code = '" + data.about_code + "'" + " AND tb_booking.customer_code = '" + data.customer_code + "'"; console.log(str); sql.query(str, function (err, res) { if (err) { console.log("error: ", err); const require = { data: [], error: err, query_result: false, server_result: true }; resolve(require); } else { const require = { data: res, error: [], query_result: true, server_result: true }; resolve(require); } }); }); } Task.getBookingByCode = function getBookingByCode(data) { return new Promise(function (resolve, reject) {//user list var str = "SELECT * FROM tb_booking " + " WHERE booking_code = '" + data.booking_code + "' "; console.log('checkLogin : ', str); sql.query(str, function (err, res) { if (err) { console.log("error: ", err); const require = { data: [], error: err, query_result: false, server_result: true }; resolve(require); } else { const require = { data: res[0], error: [], query_result: true, server_result: true }; resolve(require); } }); }); }; Task.insertBooking = function insertBooking(data) { return new Promise(function (resolve, reject) { var str = "INSERT INTO `tb_booking` (" + "`booking_code`," + "`table_code`," + "`about_code`," + "`customer_code`," + "`booking_firstname`," + "`booking_lastname`," + "`booking_tel`, " + "`booking_email`, " + "`booking_date`, " + "`booking_time`, " + "`booking_amount` " + ") VALUES (" + " '" + data.booking_code + "', " + " '" + data.table_code + "', " + " '" + data.about_code + "', " + " '" + data.customer_code + "', " + " '" + data.booking_firstname + "', " + " '" + data.booking_lastname + "', " + " '" + data.booking_tel + "', " + " '" + data.booking_email + "', " + " '" + timeController.reformatTo(data.booking_date) + "', " + " '" + data.booking_time + "', " + " '" + data.booking_amount + "' " + " ) " // console.log('checkLogin : ', str); sql.query(str, function (err, res) { if (err) { console.log("error: ", err); const require = { data: false, error: err, query_result: false, server_result: true }; resolve(require); } else { const require = { data: true, error: [], query_result: true, server_result: true }; resolve(require); } }); }); }; Task.getBookingMaxCode = function getBookingMaxCode(data) { return new Promise(function (resolve, reject) { var str = "SELECT IFNULL(LPAD( SUBSTRING(max(booking_code),3 ,7)+1,6, '0'),'000001') AS booking_max FROM `tb_booking` " console.log('checkLogin565664646 : ', str); sql.query(str, function (err, res) { if (err) { console.log("error: ", err); const require = { data: [], error: err, query_result: false, server_result: true }; resolve(require); } else { const require = { data: res[0], error: [], query_result: true, server_result: true }; resolve(require); } }); }); }; Task.checkBook = function checkBook(data) { return new Promise(function (resolve, reject) { var str = "SELECT * FROM `tb_table` " + " LEFT JOIN tb_booking ON `tb_table`.`table_code` = tb_booking.table_code " + " WHERE table_amount = '" + data.table_amount + "'" + " AND tb_booking.booking_date = '" + timeController.reformatTo(data.booking_date) + "'" + " AND tb_booking.about_code = '" + data.about_code + "'" console.log('checkLogin565664646 : ', str); sql.query(str, function (err, res) { if (err) { console.log("error: ", err); const require = { data: [], error: err, query_result: false, server_result: true }; resolve(require); } else { const require = { data: res, error: [], query_result: true, server_result: true }; resolve(require); } }); }); }; Task.checkTable = function checkTable(data) { return new Promise(function (resolve, reject) { var str = "SELECT * FROM `tb_table` " + " WHERE table_amount = '" + data.table_amount + "'" + " AND about_code = '" + data.about_code + "'" console.log('checkLogin565664646 : ', str); sql.query(str, function (err, res) { if (err) { console.log("error: ", err); const require = { data: [], error: err, query_result: false, server_result: true }; resolve(require); } else { const require = { data: res, error: [], query_result: true, server_result: true }; resolve(require); } }); }); }; Task.deleteBooking = function deleteBooking(data) { return new Promise(function (resolve, reject) { var str = "UPDATE `tb_booking` SET" // + "`order_list_code`= '" + data.order_list_code + "'," + "`deleted`= '1'" + "WHERE tb_booking.booking_code = '" + data.booking_code + "'"; console.log("data:", data); sql.query(str, function (err, res) { if (err) { console.log("error: ", err); const require = { data: false, error: err, query_result: false, server_result: true }; resolve(require); } else { const require = { data: true, error: [], query_result: true, server_result: true }; resolve(require); } }); }); } module.exports = Task;
import { Template } from 'meteor/templating'; import { ReactiveVar } from 'meteor/reactive-var'; //import { dashboard } from '../imports/api/tasks.js'; // import './main.html'; // list all task // Template.body.onCreated(function bodyOnCreated() { // // this.state = new ReactiveDict(); // Meteor.subscribe('dashboards'); // dashboard = new Meteor.Collection('dashboards'); // }); Template.manageSubscriptions.onRendered(function onRendered(){ // alert('hello'); document.body.style.backgroundColor = '#fff'; }); Template.manageSubscriptions.onCreated(function helloOnCreated() { // counter starts at 0 this.counter = new ReactiveVar(0); }); Template.manageSubscriptions.helpers({ isAdmin: function() { var user = Meteor.user(); if (user.username == 'admin') { //console.log(user); return true; } else { sweetAlert("Warning!","You are not authorised person."); Router.go('/'); } }, listSubscriber: function() { Meteor.call('getSubscriberList', function(error, result){ var SubscriberList = result.data; Session.set('SubscriberList', SubscriberList); }); return Session.get('SubscriberList'); }, }); Template.manageSubscriptions.events({ // add form into collection // using form class method 'click .delete'() { var id = this._id; Meteor.call('getSubscribeEmail', id ,function(error, result){ var subscriberData = result.data; var subscribe_id = subscriberData.email; Meteor.call('checkSubscriberAsUser', subscribe_id,function(err, res){ var checkSubscriberIDExist = res.data; if (checkSubscriberIDExist==true) { //console.log('exist.........'); sweetAlert("Warning!","You can't delete this subscription. This subscriber exist as a user in database."); } else { console.log('confirmed.........'); var test = new Confirmation({ message: "Are you sure delete this subscription?", title: "Somigo", cancelText: "Cancel", okText: "Delete", success: true, // whether the button should be green or red focus: "cancel" // which button to autofocus, "cancel" (default) or "ok", or "none" }, function (ok) { // ok is true if the user clicked on "ok", false otherwise if(ok){ //console.log('i m here for id'); //console.log(id); Meteor.call('deleteSubscriber',id); Router.go('/manageSubscriptions'); } }); } }); }); } });
import React from 'react' import PropTypes from 'prop-types' import { Link } from 'gatsby' import { Button, Flex, Box } from 'theme-ui' import { FaChevronLeft, FaChevronRight } from 'react-icons/fa' const pagingParam = 'page' const styles = { wrapper: { justifyContent: `space-between`, alignItems: `center`, textAlign: `center`, borderRadius: `full`, bg: `white`, maxWidth: [`none`, 500], mx: `auto`, p: 1 }, item: { width: `1/3` }, number: { py: 2 }, button: { minWidth: `full` } } const Pagination = ({ currentPage, pageCount, hasPreviousPage, hasNextPage, slug = '' }) => { if (!hasNextPage && !hasPreviousPage) return '' let basePath = slug + '/' + pagingParam + '/' const prevLink = currentPage >= 3 ? `${basePath}${currentPage - 1}` : slug const nextLink = `${basePath}${currentPage + 1}` return ( <Flex sx={styles.wrapper}> <Box sx={styles.item}> {hasPreviousPage && ( <Button variant='mute' as={Link} to={prevLink} sx={styles.button}> <FaChevronLeft /> Previous </Button> )} </Box> <Box sx={{ ...styles.item, ...styles.number }}> Page <strong>{currentPage}</strong> of <strong>{pageCount}</strong> </Box> <Box sx={styles.item}> {hasNextPage && ( <Button variant='dark' as={Link} to={nextLink} sx={styles.button}> Next <FaChevronRight /> </Button> )} </Box> </Flex> ) } export default Pagination Pagination.propTypes = { currentPage: PropTypes.number, pageCount: PropTypes.number, hasPreviousPage: PropTypes.bool, hasNextPage: PropTypes.bool, slug: PropTypes.string, pagingParam: PropTypes.string }
module.exports = function(module, callback) { var npm = require("npm"); var npmconf = require("npmconf"); var configDefs = npmconf.defs; var shorthands = configDefs.shorthands; var types = configDefs.types; var nopt = require("nopt"); var conf = nopt(types, shorthands); var dataToResult = function(data) { var result = {}; result.module_and_version = data[0]; result.module = data[0].split("@")[0]; result.version = data[0].split("@")[1]; result.location = data[1]; result.parent = data[2]; result.parentLocation = data[3]; result.origin = data[4]; result.children = {}; return result; } conf.production = true; npm.load(conf, function(er) { if (er) { console.log("LOAD ERR", er); } else { npm.commands["install"]([module], function(err, data) { if (err) { callback(err); } else if (data.length == 0) { callback("no data"); } else { var error = null; var result = dataToResult(data[data.length - 1]); callback(error, result); } }); } }); }
(function() { // 这些变量和函数的说明,请参考 rdk/app/example/web/scripts/main.js 的注释 var imports = [ 'rd.controls.Graph', 'css!base/css/custom','css!rd.styles.IconFonts' ]; var extraModules = [ ]; var controllerDefination = ['$scope', 'EventService', main]; function main(scope, EventService) { function setSize(){ var containerHeight=16+22*7;//公式16+26*n 其中n为data数据对象中的header的个数(data.header.length) //var containerWidth=jQuery('#graph').parent().width()-108;//其中108 为左侧元素的宽度+margin值 jQuery('#graph').css('height',containerHeight+"px");//根据数据的长度设置柱状图的自适应高度 }; setSize(); EventService.register('dsGraph', 'result', function(event, data) { scope.titles=data.header; $('.selector > .selector_symbol').first().addClass('iconfont iconfont-e8b3 selector_symbol_color'); }); scope.check_items=function($event){//勾选事件 var target=jQuery($event.target); var portData; if(target.hasClass('iconfont iconfont-e8b3 selector_symbol_color')){ target.removeClass('iconfont iconfont-e8b3 selector_symbol_color'); target.parent().siblings().children('i').removeClass('iconfont iconfont-e8b3 selector_symbol_color') var portData=target.next().html(); alert(false) }else{ target.addClass('iconfont iconfont-e8b3 selector_symbol_color') target.parent().siblings().children('i').removeClass('iconfont iconfont-e8b3 selector_symbol_color') portData=target.next().html(); alert(portData); } } } var controllerName = 'DemoController'; //========================================================================== // 从这里开始的代码、注释请不要随意修改 //========================================================================== define(/*fix-from*/application.import(imports)/*fix-to*/, start); function start() { application.initImports(imports, arguments); rdk.$injectDependency(application.getComponents(extraModules, imports)); rdk.$ngModule.controller(controllerName, controllerDefination); } })();
const vfilter = { stringfilter(val) { if (val == "" || val == undefined || val == null) { return null; } else { return val; } }, //金额处理函数保留小数点后面两位小数 disposenumber(val) { if (val.indexOf(".") != -1) { let listnumber = val.split("."); if (listnumber[1][2]) { if (listnumber[1][2] != 0) { console.log("dddd") let dianhounumber = listnumber[1].slice(0, 2); if(parseInt(dianhounumber)+1>=10){ return listnumber[0]+"."+(parseInt(dianhounumber)+1) }else{ console.log(parseInt(dianhounumber)+1) return listnumber[0]+".0"+(parseInt(dianhounumber)+1) } }else{ return listnumber[0]+"."+listnumber[1].slice(0, 2); } }else{ return val; } }else{ return val+".00"; } }, timefilter(val) {//事件过滤器 var dateTime = new Date(val); var year = dateTime.getFullYear(); var month = dateTime.getMonth() + 1; var day = dateTime.getDate(); var hour = dateTime.getHours(); var minute = dateTime.getMinutes(); var second = dateTime.getSeconds(); var now = new Date(); var now_new = new Date().getTime(); //typescript转换写法 var milliseconds = 0; var timeSpanStr; milliseconds = now_new - val; if (milliseconds <= 1000 * 60 * 1) { timeSpanStr = '刚刚'; } else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) { timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前'; } else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) { timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前'; } else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) { timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前'; } else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year == now.getFullYear()) { timeSpanStr = month + '-' + day + ' ' + hour + ':' + minute; } else { timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute; } return timeSpanStr; }, } export default vfilter;
import { StyleSheet, Dimensions, Platform } from 'react-native'; import * as FontSizes from '../utils/fontsSizes'; const deviceHeight = Dimensions.get("window").height; const deviceWidth = Dimensions.get("window").width; import Globals from '../constants/Globals'; export default channelListStyle = StyleSheet.create({ contentView: { flex: 1, flexDirection: 'column', backgroundColor: 'black', paddingTop: 15 }, contentContainer: { paddingVertical: 20 }, categoryName: { color: '#d51a92', fontSize: FontSizes.large, paddingLeft: 15 }, favoriteSwitchText: { color: 'white', fontSize: FontSizes.large }, imageThmbnail: { width: '47%', height: Globals.DeviceType === 'Phone' ? deviceHeight / 6 : deviceHeight / 5, backgroundColor: '#fff', marginBottom: 30, marginLeft: 7, //marginRight: 5, flexDirection: 'row', alignItems: 'stretch' }, videoTitle: { color: 'white', textAlign: 'left', paddingLeft: 5, flex: 1, fontSize: FontSizes.medium }, videoTitleView: { flex: 1, flexDirection: 'row', justifyContent: 'space-around', alignItems: 'flex-end', paddingBottom: 2, //backgroundColor: 'red' }, tvFavoriteView: { height: Globals.DeviceType === 'Phone' ? 25 : 35, width: Globals.DeviceType === 'Phone' ? 25 : 35, borderRadius: 25, backgroundColor: '#00000090', marginTop: 4, justifyContent: 'center', alignItems: 'center', }, tvFavoriteBg: { height: 40, width: 40, alignSelf: 'flex-end', backgroundColor: 'transparent', justifyContent: 'center', alignItems: 'center', }, videoDuration: { fontSize: FontSizes.small, color: 'white', paddingRight: 3, marginLeft: 3, //marginTop: 1 }, videoDurationView: { flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', //backgroundColor: 'red', marginBottom: 4 }, imageBackground: { width: '100%', height: '100%', resizeMode: 'contain' }, liveNow: { flex: 1, flexDirection: 'row', //alignItems: 'center', paddingBottom: '1%' } });
import React, { Component } from "react"; import { Link } from "react-router-dom"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { getDogs } from "../../actions/dogActions"; import isEmpty from "../../validation/is-empty"; import DogItem from "./DogItem"; export class Dogs extends Component { state = { dogs: {} }; componentWillMount() { this.props.getDogs(); } render() { const { dogs } = this.props; let dogList; if (isEmpty(dogs)) { dogList = ( <div className="col s12 center"> <h1>คุณยังไม่มีรายชื่อสุนัข</h1> </div> ); } else { dogList = dogs.map(dog => <DogItem key={dog._id} dog={dog} />); } return ( <React.Fragment> <div className="row">{dogList}</div> <div className="fixed-action-btn direction-top"> <Link to="/newdog" className="btn-floating btn-large waves-effect waves-light pink"> <i className="material-icons">add</i> </Link> </div> </React.Fragment> ); } } Dogs.propTypes = { dogs: PropTypes.object, getDogs: PropTypes.func.isRequired }; const stateToProps = state => ({ dogs: state.dog.dogs }); export default connect( stateToProps, { getDogs } )(Dogs);
import {db} from '../firestore' const GOT_USER = 'GOT_USER' const LOGOUT = 'LOGOUT' const CHOOSE_VIEW = 'CHOOSE_VIEW' const TOGGLE_FORM = 'TOGGLE_FORM' const initialState = { fullName: '', email: '', isLoggedIn: false, allTodos: true, formVisible: false } export const gotUser = user => ({ type: GOT_USER, user }) export const logout = () => ({ type: LOGOUT }) export const chooseView = bool => ({ type: CHOOSE_VIEW, bool }) export const toggleForm = () => ({ type: TOGGLE_FORM }) export const getUser = uid => async dispatch => { console.log('attempting to get user') try { const doc = await db.collection('users').doc(uid).get() dispatch(gotUser(doc.data())) } catch (err) { console.log('Error fetching user!' + err) } } const reducer = (state = initialState, action) => { switch(action.type) { case GOT_USER: return {...state, fullName: action.user.fullName, email: action.user.email, isLoggedIn: true} case LOGOUT: return { ...state, fullName: '', email: '', isLoggedIn: false, allTodos: true, formVisible: false } case CHOOSE_VIEW: return {...state, allTodos: action.bool} case TOGGLE_FORM: return {...state, formVisible: !state.formVisible} default: return state } } export default reducer
angular.module('PoisRUs').service('searchService', [ '$http', '$resource', 'BaseRoutes', 'ApiRoutes', function($http, $resource, BaseRoutes, ApiRoutes) { var Poi = $resource(BaseRoutes.apiRoot + ApiRoutes.SEARCH_POIS); var User = $resource(BaseRoutes.apiRoot + ApiRoutes.SEARCH_USERS); function searchPOIs(poiData, callback) { return Poi.get({data : poiData}, function(value, headers) { if (callback) callback(null, value.message); }, function (value, headers) { if (callback) callback(value.data); }); } function searchUsers(userData, callback) { return User.get({data : userData}, function(value, headers) { if (callback) callback(null, value.message); }, function (value, headers) { if (callback) callback(value.data); }); } // Service API return { searchPOIs: searchPOIs, searchUsers: searchUsers, } }]);
/** Copyright 2021 fernando.reyes@du.edu Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; const DB = require('../config/db')(); /** * Saves menu item to database * @param req * @param callback */ exports.save = function (req, callback) { if (req.body === undefined) { callback({ status: 400, data: { message: 'Bad Request' } }); } let api_key = req.query.api_key; let Menu = req.body; if (Array.isArray(api_key)) { api_key = api_key.pop(); } Menu.api_key = api_key; DB('menus') .insert(Menu) .then(function (data) { console.log(data); }) .catch(function (error) { throw 'ERROR: unable to save menu ' + error; }); callback({ status: 201, data: { message: 'Menu saved' } }); }; exports.read = function (req, callback) { let api_key = req.query.api_key; let id = req.query.id; let whereObj = {}; if (Array.isArray(api_key)) { api_key = api_key.pop(); } if (Array.isArray(id)) { id = id.pop(); } whereObj.api_key = api_key; if (id !== undefined) { whereObj.id = id; } DB('menus') .where(whereObj) .select('id', 'item', 'description', 'price') .then(function (data) { callback({ status: 200, data: { menu: data } }); }) .catch(function (error) { throw 'ERROR: unable to get menu ' + error; }); }; exports.update = function (req, callback) { if (req.body.id === undefined) { callback({ status: 400, data: { message: 'Bad Request' } }); } let api_key = req.query.api_key; let Menu = req.body; if (Array.isArray(api_key)) { api_key = api_key.pop(); } if (Array.isArray(api_key)) { api_key = api_key.pop(); } let id = Menu.id; delete Menu.id; DB('menus') .where({ api_key: api_key, id: id }) .update(Menu) .then(function (data) { callback({ status: 204 }); }) .catch(function (error) { throw 'ERROR: unable to update record ' + error; }); }; exports.delete = function (req, callback) { if (req.query.id === undefined) { callback({ status: 400, data: { message: 'Bad Request' } }); } let api_key = req.query.api_key; let id = req.query.id; if (Array.isArray(api_key)) { api_key = api_key.pop(); } if (Array.isArray(id)) { id = id.pop(); } DB('menus') .where({ api_key: api_key, id: id }) .del() .then(function () { callback({ status: 204 }); }) .catch(function (error) { throw error; }); };
var sdb = require('simpledb'); var uuid = require('node-uuid'); module.exports = function(config) { this.config = config; this.config.before_create = this.config.before_create || function(args, done) { done(args.data); } this.config.after_create = this.config.after_create || function(args, done) { } this.config.permissions = this.config.permissions || { default_write: 'null', default_read: '*', } this.sdb = this.config.db || new sdb.SimpleDB({ keyid: config.keyid, secret: config.secret }); var self = this; function arrayify(st) { try { if (typeof(st) == 'string') { if ((st.charAt(0) == '(') && (st.charAt(st.length - 1) == ')')) { return JSON.parse('[' + st.substr(1, st.length - 2) + ']'); } return [st] } return st } catch (e) { return [] } } this.sync = function(req, res, next) { return self._sync(req, res, next) } this._sync = function(req, res, next, done, originalUrl, body) { //if done is passed, the function will not use res to return/close the http connection. //done is used by other internal functions that want to talk to the sync engine without //making an http call (it's effectively an rpc call) if ((req.method == 'POST') || (req.method == 'PUT')) { var params = (body || req.body); } else { var params = req.query; } function can_update(d, i, if_so) { //this function runs if_so if the current user can access and update (i) within the (d) domain. self.sdb.getItem(d, i, function(error, result) { if (error) { if (done) { done(error, result); } else { res.json({ type: 'error', msg: error.Message || 'bad query' }) } return } if (!result) { if (done) { done({ Message: 'requested item does not exist.' }, result); } else { res.json({ type: 'error', msg: 'requested item does not exist.' }) } return } //check if the user who is asking for it actually has permission to read this. if ((result.write_access == '*') || (result.owner == req.user._id) || (result.write_access.indexOf(req.user._id) != -1)) { if_so(result); } else { if (done) { done({ Message: 'permission denied.' }, result); } else { res.json({ type: 'error', msg: 'permission denied.' }) } } }); } if (req.route.path.indexOf('*') != req.route.path.length - 1) { throw new Error('sdb-bb requires a dedicated path that is defined by something/*'); } var path = (originalUrl || req.originalUrl).split(req.route.path.split('*')[0])[1]; //check if collection_name includes "/". This is useful for hierarchical data. //The format is: // 1- something/collection_name // 2- somehing/parent_collection_name/sub_collection_name var collection_name = path.split('/')[0].split('?')[0]; var rest_of_url = (originalUrl || req.originalUrl).split(collection_name)[1]; var requested_id = rest_of_url.substr(0, 1) == '/' ? rest_of_url.split('/')[1].split('?')[0] : null; if (requested_id && !(new RegExp('^([abcdef]|[0-9]){8}-([abcdef]|[0-9]){4}-([abcdef]|[0-9]){4}-([abcdef]|[0-9]){4}-([abcdef]|[0-9]){12}$')).test(requested_id)) { if (done) { done({ Message: 'the id is not valid.' }, result); } else { res.json({ type: 'error', msg: 'the id is not valid.' }); } return } if (requested_id) { var parent_collection_name = collection_name; collection_name = collection_name + '/' + requested_id; } else { var parent_collection_name = null; } var domain = null; var parent_domain = null; for (var i in self.config.domains) { if ((new RegExp(i)).test(collection_name)) { domain = self.config.domains[i]; break } } if (parent_collection_name) { //only meaningful for objects that have parents. for (var i in self.config.domains) { if ((new RegExp(i)).test(parent_collection_name)) { parent_domain = self.config.domains[i]; break } } } if (!domain) { throw new Error('the backbone collection ' + collection_name + ' is not defined as a valid collection in config.domains.'); } if (parent_collection_name && !parent_domain) { throw new Error('the backbone collection ' + parent_collection_name + ' is not defined as a valid collection in config.domains.'); } if (req.method == "POST") { //this should create a new model //created_at, collection_name, updated_at, owner, read_access, write_access, children // parameters are treated differently and are reserved words. //parameter "id" should not be passed but if it does, it'll be ignored. //parent_* fields will be used to update the parent (they'll be applied if the parent is passed) //parent_arrayappend_n_* will be used to update the parent - as an array with size n //retry = 1: says this is a retry. make sure we have not already saved this var is_retry = params.retry; if (isNaN(is_retry)) { is_retry = 0 } else { is_retry = parseInt(is_retry); } delete params['retry']; var now = (new Date()).getTime(); function create_object(parent) { if (params['child']) { //if the object is to be created along with its parent var child = JSON.parse(params['child']); delete params['child']; } else { var child = null; } if (params['parent']) { // var parent = JSON.parse(params['parent']); delete params['parent']; var child = params; params = parent; } var parent_fields = {} for (var i in params) { if (i.indexOf('parent_') == 0) { parent_fields[i.split('parent_')[1]] = params[i]; delete params[i]; } } params['owner'] = req.user._id; params['write_access'] = arrayify(params['write_access'] || self.config.permissions.default_write); params['read_access'] = arrayify(params['read_access'] || self.config.permissions.default_read); params['created_at'] = now; params['updated_at'] = now; params['collection_name'] = collection_name; delete params['id']; delete params['children']; if (child) { params['children'] = 1; } var id = uuid.v4(); self.config.before_create({ collection_name: collection_name, data: params, domain: domain, id: id, req: req, sdb: self.sdb }, function(data) { var process_put = function(err) { if (err) { if (done) { done(err, result); } else { res.json({ type: 'error', msg: err.Message || 'bad query' }); } return } if (child) { collection_name = collection_name + '/' + id; for (var i in self.config.domains) { if ((new RegExp(i)).test(collection_name)) { domain = self.config.domains[i]; break } } params = child; create_object(); } else { data['id'] = id; //delete params['collection_name']; self.config.after_create({ collection_name: collection_name, data: data, domain: domain, id: id, req: req, sdb: self.sdb }); delete data['write_access']; delete data['read_access']; delete data['child']; if (done) { done(null, data); } else { res.json(data); } //if the object is a child of another object, update the parent. //this is called after the function is returned (the user does not need to wait for this) if (parent) { var Data = { updated_at: (new Date()).getTime(), children: parent.children ? (parseInt(parent.children) + 1) : 1 } var j = 0; var override = { 'Expected.1.Name': 'updated_at', 'Expected.1.Value': parent.updated_at } var num_of_attr = 2; for (var i in parent_fields) { num_of_attr = num_of_attr + 1; if (i.indexOf('arrayappend_') == 0) { try { var size = parseInt(i.split('arrayappend_')[1].split('_')[0]); var key = i.split('arrayappend_' + size + '_')[1]; var value = parent_fields[i]; if (parent[key]) { var cur = parent[key]=='0'? [] : JSON.parse(parent[key]); cur.push(value); (cur.length > size) && cur.splice(0, 1); Data[key] = JSON.stringify(cur); } else { Data[key] = JSON.stringify([value]); } } catch (e) { } } else { Data[i] = parent_fields[i]; } } var update_with_lock = function() { j = j + 1; self.sdb.putItem(parent_domain, requested_id, Data, override, function(err) { if (err && (j < 5)) { var reread_the_item = function() { self.sdb.getItem(parent_domain, requested_id, function(err, result) { if (err) { reread_the_item(); return } parent = result; update_with_lock(); }) } reread_the_item(); return } }); } update_with_lock(); } } }; //check if this item already exists (to prevent re-creating the same objects because of network issues) if (is_retry) { var check_rep_data = ""; for (var i in data) { if ((i != 'created_at') && (i != 'updated_at') && (i != 'write_access') && (i != 'read_access') && (typeof(data[i]) == 'string')) { check_rep_data = check_rep_data + (check_rep_data == "" ? "" : " and ") + ("`" + i + "`='" + data[i] + "'"); } } check_rep_data = check_rep_data + " and `created_at`>'" + (now - is_retry) + "'"; var q = "select ItemName() from `" + domain + "` where " + check_rep_data; self.sdb.select(q, function(err, result) { if (err) { if (done) { done(err, result); } else { res.json({ type: 'error', msg: err.Message || 'bad query' }); } return } if (result && (result.length > 0)) { //you don't need to write it again id = result[0]['$ItemName'] process_put() } else { self.sdb.putItem(domain, id, data, process_put) } }); return } self.sdb.putItem(domain, id, data, process_put) }) } if (parent_domain) { //if the object is to be created as a child of another object. can_update(parent_domain, requested_id, create_object) } else { create_object(); } } if (req.method == "GET") { //this should return models (or model) if (params.id) { //the client is asking for only one model (not the whole collection) self.sdb.getItem(domain, params.id, function(error, result) { if (error) { res.json({ type: 'error', msg: error.Message || 'bad query' }) return } if (!result) { res.json({}); return } //check if the user who is asking for it actually has permission to read this. if ((result.read_access == '*') || (result.owner == req.user._id) || (result.read_access.indexOf(req.user._id) != -1)) { result.id = result['$ItemName']; delete result['$ItemName']; delete result.read_access; delete result.collection_name; delete result.write_access; res.json(result); return } else { res.json({ type: 'error', msg: 'permission denied.' }) } }) } else { //only getting the items that are in the requested domain/collection and the user has read-access to. var query = "select * from `" + domain + "` where `updated_at` is not null and collection_name='" + collection_name + "' and (read_access in ('*', '" + req.user._id + "') or owner='" + req.user._id + "')"; var where = null; if (params.where) { try { var where = JSON.parse(params.where) } catch (e) { var where = null; } } if (where) { //query = query + ' and '; for (var i in where) { query = query + " and `" + i + "`" + where[i] } } query = query + ' order by `updated_at` DESC limit 20'; self.sdb.select(query, function(error, result) { if (error) { res.json({ type: 'error', msg: error.Message || 'bad query' }) return } for (var i = 0; i < result.length; i++) { result[i].id = result[i]['$ItemName']; delete result[i]['$ItemName']; delete result[i].read_access; delete result[i].collection_name; delete result[i].write_access; } res.json(result) }); } } if (req.method == "PUT") { //this should modify a specific model if (!params.id) { res.json({ type: 'error', msg: 'the item does not have an id field.' }); return } var parent = false; var now = (new Date()).getTime(); var parent_fields = {} for (var i in params) { if (i.indexOf('parent_') == 0) { parent = true; parent_fields[i.split('parent_')[1]] = params[i]; delete params[i]; } } function update_object(Domain, Params, silence) { can_update(Domain, Params.id, function(result) { //check if the user who is asking for it actually has permission to read this. var id = result['$ItemName']; if (parent) { parent = false; parent_fields.id = result['collection_name'].split(parent_collection_name + '/')[1]; update_object(parent_domain, parent_fields, true); } var updated_at = Params['updated_at']; delete result['$ItemName']; result['updated_at'] = now; delete Params['owner']; delete Params['id']; delete Params['children']; delete Params['updated_at']; delete Params['created_at']; delete Params['collection_name']; for (var i in Params) { result[i] = Params[i]; } result['write_access'] = arrayify(result['write_access']); result['read_access'] = arrayify(result['read_access']); for (var i in Params) { if (i.indexOf('arrayremove_') == 0) { try { var key = i.split('arrayremove_')[1]; var item = Params[i]; if (result[key]) { var cur = parent[key]=='0'? [] : JSON.parse(parent[key]); var index = cur.indexOf(item); if (index != -1) { cur.splice(index, 1); if (cur.length){ result[key] = JSON.stringify(cur); }else{ result[key] = '0'; } } } delete result[i]; } catch (e) { } } } var j = 0; var update_with_lock = function() { j = j + 1; self.sdb.putItem(Domain, id, result, { 'Expected.1.Name': 'updated_at', 'Expected.1.Value': updated_at }, function(err) { if ((err) && (err.Code == 'ConditionalCheckFailed') && (j < 5)) { updated_at = err.Message.split('value is (')[1].split(')')[0]; result['updated_at'] = (new Date()).getTime(); update_with_lock(); return } if (err) { (!silence) && res.json({ type: 'error', msg: err.Message || 'bad query' }); return } result['id'] = id; delete result.read_access; delete result.collection_name; delete result.write_access; (!silence) && res.json(result); }); } update_with_lock(); }); } update_object(domain, params); } if (req.method == "DELETE") { //this should delete a specific model - id is passed through url if (!params.id) { res.json({ type: 'error', msg: 'what id should be deleted?' }); return } can_update(domain, params.id, function(result) { self.sdb.deleteItem(domain, params.id, function(err) { if (err) { res.json({ type: 'error', msg: err.Message || 'bad query' }); return } res.json({}); }); }) } } return this }
import { useState, useEffect } from "react"; import axios from "axios"; axios.defaults.headers.common["Authorization"] = "Bearer " + sessionStorage.getItem("token"); const useNetworkRequest = category => { let url = `https://personal-website--backend.herokuapp.com/${category}`; const [loading, setLoading] = useState(true); const [error, setError] = useState(""); const [currentData, setcurrentData] = useState([]); const [status, setStatus] = useState("loading"); useEffect(() => { (async () => { setStatus("loading"); setLoading(true); try { let { data } = await axios.get(url); setcurrentData(data.data); setStatus("data"); } catch (error) { setStatus("error"); setError(error); } setLoading(false); })(); }, [category]); const fxn = async (type, requestData, _id) => { setStatus("loading"); setLoading(true); let token = window.sessionStorage.getItem("token"); switch (type) { case "ADD": { try { let { data } = await axios.post(url, requestData); let newData = [...currentData, data.data]; setcurrentData(newData); setStatus("data"); } catch (error) { setStatus("error"); setError(error); } setLoading(false); break; } case "DELETE": { let deleted = await axios.delete(url, { data: { _id } }); try { if (deleted.statusText === "deleted") { const newDataArray = currentData.filter(data => data._id !== _id); setcurrentData(newDataArray); } setStatus("data"); } catch (error) { setStatus("error"); setError(error); } setLoading(false); break; } case "UPDATE": { let { data } = await axios.put(url, requestData); try { let newData = [...currentData, data.data]; setcurrentData(newData); setStatus("data"); } catch (error) { setStatus("error"); setError(error); } setLoading(false); break; } } }; return { fxn, status, loading, error, currentData }; }; export default useNetworkRequest;
// TODO: improve/refactor import { useEffect } from 'react'; const DEFAULT_POLLING_INTERVAL = 60; // in seconds function usePolling(callback = () => {}, seconds = DEFAULT_POLLING_INTERVAL) { useEffect(() => { callback(); const interval = setInterval(() => { callback(); }, seconds * 1000); return () => { clearInterval(interval); }; }, [callback, seconds]); } export default usePolling;
function init(slideID) { const speechGuessContainer = d3.select(slideID).select('.checkbox-container'); const allBtns = speechGuessContainer.selectAll('.checkbox-btn'); const cowbellVid = document.getElementById('speech-5-video'); d3.selectAll('.checkbox-btn').classed('checked-correct', false); d3.selectAll('.checkbox-btn').classed('checked-wrong', false); allBtns.on('click', function () { const btn = d3.select(this); const node = btn.nodes()[0]; const btnValue = (d3.select(node).attr('data-value')=='true'); if(btnValue){ d3.select(node).classed('checked-correct', true); // d3.select(slideID).select('.btn--div').classed('active', true); } else { d3.select(node).classed('checked-wrong', true); } }); d3.select('#speech-5__btn-0').on('click', ()=>{ setTimeout(()=>{ d3.select('#speech-5__btn-1').classed('active', true); }, 5000); d3.select('#speech-5').select('.hero__img').classed('hide', true); d3.select('#speech-5').select('.videoElem').classed('show', true); cowbellVid.play() }); } export default { init }
"use strict"; var enzyme_1 = require('enzyme'); var React = require('react'); var index_1 = require('./index'); describe('Alert Component', function () { it('should create an alert with the default classes', function () { var alert = enzyme_1.shallow(<index_1["default"]>Loading...</index_1["default"]>); expect(alert).not.toBeNull(); expect(alert.text()).toEqual('Loading...'); expect(alert.hasClass('p2')).toBe(true); expect(alert.hasClass('bg-blue white')).toBe(true); expect(alert.hasClass('hide')).toBe(true); expect(alert.hasClass('block')).toBe(false); }); it('should create an alert with the correct class for the isVisible value', function () { var alert = enzyme_1.shallow(<index_1["default"] isVisible>Loading...</index_1["default"]>); expect(alert.hasClass('hide')).toBe(false); expect(alert.hasClass('block')).toBe(true); }); it('should create an alert with the correct class for the given status value', function () { var alert = enzyme_1.shallow(<index_1["default"] status={'error'}>Error</index_1["default"]>); expect(alert.hasClass('bg-red white')).toBe(true); }); it('should create an alert with the given id value', function () { var alert = enzyme_1.shallow(<index_1["default"] id={'This id'}>Loading...</index_1["default"]>); expect(alert.prop('id')).toEqual('This id'); }); });
import React from "react"; import styled from "styled-components"; import { lightBlueBackground } from "../themes"; const Div = styled.div` height: 9px; ${lightBlueBackground} `; export default function CustomHr() { return <Div />; }
const fs = require("fs") const S = require('string'); fs.readdir('./pdf', (err, data) => { if (err) throw err; for (let i = 0; i < data.length; i++) { if (S(data[i]).contains("-1")) { //se tiene que leer el archivo let files = "./pdf/" + data[i] fs.readFile(files, (err, data) => { if (err) throw err; console.log(files,data); fs.writeFile(S(files).replaceAll("-1","").s, data, (err) => { if (err) throw err; console.log("Create File"); }); fs.writeFile(S(files).replaceAll("-1","_fb").s, data, (err) => { if (err) throw err; console.log("Create File"); }); fs.writeFile(S(files).replaceAll("-1","_mini").s, data, (err) => { if (err) throw err; console.log("Create File"); fs.unlink(files, (err) => { if (err) throw err; console.log(`delete ${files}`); }); }); }); } } });
import React from 'react'; import { FaFacebook, FaPinterest, FaTwitter, FaInstagram, } from 'react-icons/fa'; // Styles import './footer.scss'; // Components import Form from '../Forms/Form'; import H2 from '../HtmlTags/H2'; import H3 from '../HtmlTags/H3'; import Button from '../Buttons/Button'; const Footer = () => { return ( <footer> <div className='footer'> <span> <div className='footer_help'> <H2 title='HELP' /> <H3 title='help@sweath.com' tagClass='footer_help_first' /> <H3 title='refunds & complaints' /> <H3 title='frequently asked questions' /> <H3 title='contact us' /> </div> <div className='footer_info'> <H2 title='INFORMTAION' /> <H3 title='Address: 4150 Washington Avenue' tagClass='footer_info_first' /> <H3 title='Phone: 422 255 1805' /> <H3 title='Email: sweath@gmail.com' /> </div> <div className='footer_newsletter'> <H2 title='NEWSLETTER' /> <div className='footer_newsletter_form'> <Form formType='text' formName='newsletterUserEmail' formPlaceholder='Email Address...' /> <Button buttonTitle='SUBSCRIBE' noArrow={true} /> </div> </div> </span> <div className='footer_end'> <H3 title='&copy; 2021 Sweath. All rights reserved - Font awsome' /> <div className='footer_socials'> <FaFacebook className='fb_icon' size={window.innerWidth > 1025 ? 27 : '5.1%'} /> <FaPinterest className='linkedin_icon' size={window.innerWidth > 1025 ? 27 : '5.1%'} /> <FaTwitter className='twitter_icon' size={window.innerWidth > 1025 ? 27 : '5.1%'} /> <FaInstagram className='ig_icon' size={window.innerWidth > 1025 ? 27 : '5.1%'} /> </div> </div> </div> </footer> ); }; export default Footer;
let Secretnumber = getRandomInt(1, 5); let attempts = 3; //комментируя вызов увидим когда работает функция function getRandomInt(min, max){ //console.log(min); //console.log(max); return Math.floor(Math.random()*(max - min + 1)) + min; } document.querySelector(".check").onclick = function(){ let Usernumber = document.querySelector(".number").value; attempts = attempts - 1; //console.log(attempts); document.querySelector(".attempts").innerHTML = attempts; if (attempts == 0) { document.querySelector(".check").disabled = true; document.querySelector(".number").disabled = true; } document.querySelector(".start").onclick = function(){ Secretnumber = getRandomInt(1, 5); attempts = 3; document.querySelector(".attempts").innerHTML = attempts; document.querySelector(".check").disabled = false; document.querySelector(".number").disabled = false; document.querySelector(".number").value = ""; document.querySelector(".number").focus(); document.querySelector(".hint"). innerHTML = "Я буду подсказывать" } if (Usernumber == Secretnumber) { //console.log("Вы угадали!!") document.querySelector(".hint").innerHTML = "Вы угадали!!"; alert("Вам на счёт зачислен $1000000!!!") document.querySelector(".number").disabled = true; document.querySelector(".check").disabled = true; } if (Usernumber < Secretnumber) { //console.log("Секретное число больше") document.querySelector(".hint").innerHTML = "Cекретное число больше"; } if (Usernumber > Secretnumber) { //console.log("Секретное число меньше") document.querySelector(".hint").innerHTML = "Секретное число меньше"; } }
import React from 'react'; // Import Style // import styles from '../../App/App.css'; export function AboutUs() { return ( <div id="main-container" > <div className="index-content "> <div className="container"> <div className="row"> <div id="home-content" className="column col-md-10 col-md-push-1 col-md-pull-1 col-xs-12 col-sm-12"> <h1>AALAM VILUTHUGAL ASSOCIATION (AVA) </h1> <p>AVA is a non profit association and the primary mission is to Reconnect the alumni of Arasan Ganesan Polytechinc college (AGPC) with their fellow alumni, institute, and students on the campus. It is a Government-aided Polytechnic , founded in 1981 byArasan A.M.S.Ganesan, a famous philanthropist of Sivakasi. It is situated 9 km. from Sivakasi town on Sivakasi -Virudhunagar main road.</p> <p>The association is started by alumni of various batches and groups spread across the world and the registred office in Choolaimedu ,Chennai. The aim of the association is to give basic education support, conducting chapter programs, Meetings, Conferences, Workshops, Family Meeting and educational programs..</p> <p><b> Office Address </b></p> <p>No. 73, Gurulakshmi Castle,Vallalar Street, </p> <p>Choolaimedu, Chennai – 600094. </p> <p>Phone : 9444709933 ; Email: aalamviluthu18@gmail.com</p> </div> </div> </div> </div> </div> ); } export default AboutUs;
/* eslint-disable no-undef */ /* * Socket集成 * @Author: Jiang * @Date: 2019-08-27 18:00:15 * @Last Modified by: Jiang * @Last Modified time: 2020-03-22 10:58:54 */ let SOCKET = ''; // 服务器断开链接 const serverDisconnect = () => { if(!SOCKET) { return; } SOCKET.on('disconnect'); }; // 断开链接 const disconnect = () => { if(!SOCKET) { return; } SOCKET.disconnect(); }; const offConnect = () => { if(!SOCKET) { return; } SOCKET.off('connect'); }; const onConnect = () => { if(!SOCKET) { return; } SOCKET.on('connect', () => { }); }; // 移出所有监听 const removeAllListeners = () => { if(!SOCKET) { return; } SOCKET.removeAllListeners(); }; // 关闭socket const close = () => { agentOffline(); offConnect(); disconnect(); removeAllListeners(); }; export { disconnect, serverDisconnect, offConnect, onConnect, removeAllListeners, close };
/** * CI server * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. * */ import DefaultApi from './generated/api/DefaultApi.js'; import ApiClient from './generated/ApiClient.js'; const client = new ApiClient(); client.basePath = '/api'; /** * The DefaultApi service constructor. * @property {module:api/DefaultApi} */ export const api = new DefaultApi(client);
import React from 'react' import ReactDOM from 'react-dom' import Web3 from 'web3'; import {SHA256} from 'crypto-js'; import Documents from '../build/contracts/Documents.sol.js' let web3 if (typeof web3 !== 'undefined') { web3 = new Web3(web3.currentProvider); } else { web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); } Documents.setProvider(web3.currentProvider) let acc = web3.eth.accounts[0] let docs = Documents.deployed() class Form extends React.Component { constructor(props) { super(props) this.state = {value: ""} this.handleUpload = this.handleUpload.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } handleSubmit(e) { this.props.onSubmit(e) } handleUpload(e) { this.setState({ value: e.target.value }) } render() { return ( <form onSubmit={this.handleSubmit}> <input type="file" id="doc-field" value={this.state.value} onChange={this.handleUpload}/> <input type="submit" value="Submit"/> </form> ) } } function Status(props) { if (props.existed === null) { return null } let message if (props.existed) { message = <span>The document has already existed</span> } else { message = <span>The document was successfully saved</span> } return ( <div> {message} <br/> <span> Timestamp: {props.timestamp} </span> <br/> <span> Document hash: {props.hash} </span> </div> ) } class Container extends React.Component { constructor(props) { super(props) this.state = { hash: null, timestamp: null, // True if the document has been saved before existed: null } this.onSubmit = this.onSubmit.bind(this) } onSubmit(e) { e.preventDefault() const reader = new FileReader() reader.onload = (e => { const hash = SHA256(e.target.result).toString() this.checkDocument(hash) }).bind(this) reader.onerror = e => { console.error("Error loading file") } reader.readAsText(document.getElementById("doc-field").files[0]) } // Checks whether the documents exists and updates state accordingly checkDocument(hash) { docs.documents.call(hash, {from: acc}).then(timestamp => { let newState = { hash: hash, existed: timestamp != 0 } if (!newState.existed) { const timeOfAddition = docs.addDocument(hash, {from: acc}).then(() => docs.documents.call(hash, {from: acc})) timeOfAddition.then((time) => { newState.timestamp = time.toString() this.setState(newState) }) } else { newState.timestamp = timestamp.toString() this.setState(newState) } }) } render() { return ( <div> <Form onSubmit={this.onSubmit} /> <Status hash={this.state.hash} timestamp={this.state.timestamp} existed={this.state.existed} /> </div> ) } } ReactDOM.render(<Container/>, document.getElementById('root'));
import React, { useState } from "react"; import { View, Image, Dimensions, StyleSheet } from "react-native"; import { Button, Headline, HelperText, TextInput, Modal, Portal, Provider, Text, } from "react-native-paper"; export default function LoginPage({ navigation }) { const [visible, setVisible] = useState(false); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const showModal = () => setVisible(true); const hideModal = () => setVisible(false); const hasErrors = () => { return email.length > 2 && !email.includes("@"); }; return ( <> <View style={styles.container}> <Image source={require("../../assets/icon.png")} style={styles.icon} /> <View style={styles.loginContainer}> <Text style={styles.title}>Login to Runator</Text> <Button icon="google" mode="contained" uppercase={false} onPress={() => alert("Google OAuth")} style={{ marginBottom: 10, width: 300, alignSelf: "center", backgroundColor: "#42464E", }} labelStyle={{ fontFamily: "Jost", fontSize: 18 }} > Sign in with Google </Button> <Button icon="email" mode="contained" uppercase={false} onPress={() => navigation.navigate("Register")} style={{ marginBottom: 10, width: 300, alignSelf: "center", backgroundColor: "#42464E", }} labelStyle={{ fontFamily: "Jost", fontSize: 18 }} > Sign up with Email </Button> <View> <Text style={{ alignSelf: "center", paddingBottom: 10, paddingTop: 15, fontFamily: "Jost", color: "#2F3238", fontSize: 16, }} > {" "} already a member ? </Text> <Button mode="contained" onPress={showModal} uppercase={false} style={{ marginBottom: 10, width: 300, alignSelf: "center", backgroundColor: "#42464E", }} labelStyle={{ fontFamily: "Jost", fontSize: 18 }} > Sign In </Button> </View> </View> <Portal> <Modal visible={visible} onDismiss={hideModal} contentContainerStyle={styles.modal} animationType={"fade"} transparent={true} > <Headline style={styles.headline}>Sign In</Headline> <TextInput label="Email" value={email} onChangeText={(email) => setEmail(email)} mode="flat" selectionColor="#FA8135" underlineColor="#FA8135" style={styles.formField} theme={{ colors: { placeholder: "white", text: "white", primary: "orange", background: "#242424", }, }} /> <HelperText type="error" visible={hasErrors()}> Email address is invalid! </HelperText> <TextInput label="Password" value={password} onChangeText={(password) => setPassword(password)} mode="outlined" selectionColor="#FA8135" underlineColor="#FA8135" style={styles.formField} secureTextEntry={true} theme={{ colors: { placeholder: "orange", text: "white", primary: "orange", background: "#242424", }, }} /> <Button style={styles.signInButton} color="#FA8135" uppercase={false} dark={true} mode="contained" onPress={() => { hideModal(); console.log(email, password); navigation.navigate("Runator"); setEmail(""); setPassword(""); }} labelStyle={{ fontFamily: "Jost", fontSize: 18 }} > Sign In </Button> </Modal> </Portal> </View> </> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "flex-start", alignItems: "center", backgroundColor: "#42464e", }, icon: { width: 250, height: 250, margin: 15, }, title: { alignSelf: "center", fontSize: 30, fontFamily: "Jost", marginBottom: 15, padding: 10, color: "#2F3238", }, loginContainer: { backgroundColor: "#FA8135", width: Dimensions.get("window").width, height: "70%", }, modal: { backgroundColor: "#242424", padding: 20, }, headline: { marginBottom: 30, fontFamily: "Jost", color: "white", textAlign: "center", }, formField: { width: Dimensions.get("window").width - 75, margin: 5, alignSelf: "center", }, signInButton: { marginTop: 50, width: 300, height: 40, alignSelf: "center", backgroundColor: "#FA8135", }, });
import React, { Component } from 'react'; import { Nav, NavItem } from 'react-bootstrap'; import { LinkContainer } from 'react-router-bootstrap'; /* |-------------------------------------------------------------------------- | Global View |-------------------------------------------------------------------------- */ export default class Settings extends Component { static propTypes = { config: React.PropTypes.object, library: React.PropTypes.object, children: React.PropTypes.object, } constructor(props) { super(props); } render() { const config = this.props.config; return ( <div className='view view-settings'> <div className='settings-switcher'> <Nav bsStyle="pills" activeKey={ 1 } onSelect={ undefined }> <LinkContainer to='/settings/library'> <NavItem eventKey={ 1 }>Library</NavItem> </LinkContainer> <LinkContainer to='/settings/audio'> <NavItem eventKey={ 2 }>Audio</NavItem> </LinkContainer> <LinkContainer to='/settings/interface'> <NavItem eventKey={ 3 }>Interface</NavItem> </LinkContainer> <LinkContainer to='/settings/advanced'> <NavItem eventKey={ 4 }>Advanced</NavItem> </LinkContainer> <LinkContainer to='/settings/about'> <NavItem eventKey={ 5 }>About</NavItem> </LinkContainer> </Nav> <div className="tab-content"> { React.cloneElement( this.props.children, { config, library: this.props.library, }) } </div> </div> </div> ); } }
import React from 'react'; import {makeStyles} from '@material-ui/core/styles'; import './Footer.scss'; import Card from '@material-ui/core/Card'; import Grid from '@material-ui/core/Grid'; import Typography from '@material-ui/core/Typography'; import clsx from 'clsx'; import Container from "@material-ui/core/Container"; import Button from '@material-ui/core/Button'; import CopyrightIcon from '@material-ui/icons/Copyright'; import GitHubIcon from '@material-ui/icons/GitHub'; import DeveloperModeIcon from '@material-ui/icons/DeveloperMode'; import GroupIcon from '@material-ui/icons/Group'; const useStyles = makeStyles(theme => ({ footer: { maxWidth: "100%", paddingTop: theme.spacing(3), paddingBottom: theme.spacing(3), backgroundColor: theme.palette.primary.transparent30, }, brightCard: { textAlign: "center", padding: theme.spacing(1), color: "white", backgroundColor: theme.palette.primary.transparent30, marginLeft: theme.spacing(1), marginRight: theme.spacing(1), }, link: { textDecoration: "none", display: "block", color: "white", fontWeight: "500", }, gridItem: { marginLeft: theme.spacing(2), marginRight: theme.spacing(2), display: "flex", alignItems: "center", justifyContent: "center", }, button: { color: "white", textTransform: "capitalize", }, startIcon: { marginLeft: 8, marginRight: 4, }, })); export const Footer = () => { const classes = useStyles(); function linkButton (link, Icon, text) { return ( <Grid item className={classes.gridItem}> <a href={link} rel="noopener noreferrer" target="_blank"> <Button className={classes.button} size="large" startIcon={<Icon className={classes.startIcon}/>}> {text} </Button> </a> </Grid> ); } return ( <div className={clsx(classes.footer, "Footer")}> <Container maxWidth="md"> <Grid container justify="center" spacing={2}> {linkButton( "https://github.com/dostuffthatmatters", CopyrightIcon, "Moritz Makowski" )} {linkButton( "https://github.com/helperline", GitHubIcon, "Open Source" )} {linkButton( "https://github.com/orgs/HelperLine/projects/1", DeveloperModeIcon, "Progress" )} {linkButton( "https://helperline.github.io/project/", GroupIcon, "About" )} </Grid> </Container> </div> ); };
import $ from '$'; import _ from 'lodash'; import d3 from 'd3'; import TableFootnotes from './TableFootnotes'; // General object for creating any table class BaseTable { constructor() { this.tbl = $('<table class="table table-condensed table-striped">'); this.thead = $('<thead>'); this.colgroup = $('<colgroup>'); this.tbody = $('<tbody>'); this.tfoot = $('<tfoot>'); this.footnotes = new TableFootnotes(); this.tbl.append(this.colgroup, this.thead, this.tfoot, this.tbody); } getTbl() { this._set_footnotes(); return this.tbl; } numCols(cols) { if (cols) { this._numCols = cols; } else if (this._numCols === undefined) { this._numCols = d3.sum( _.map( this.thead .first() .children() .first() .children(), function(d) { return parseInt($(d).attr('colspan')) || 1; } ) ); } return this._numCols; } addHeaderRow(val) { this.addRow(val, true); } addRow(val, isHeader) { var tr, tagName = isHeader ? '<th>' : '<td>'; if (val instanceof Array) { tr = $('<tr>'); val.forEach(function(v) { tr.append($(tagName).html(v)); }); } else if (val instanceof $ && val.first().prop('tagName') === 'TR') { tr = val; } else { console.log('unknown input type'); } if (isHeader) { this.thead.append(tr); } else { this.tbody.append(tr); } return tr; } setColGroup(percents) { this.colgroup.html( percents.map(function(v) { return '<col style="width: {0}%;">'.printf(v); }) ); } _set_footnotes() { var txt = this.footnotes.html_list().join('<br>'), colspan = this.numCols(); if (txt.length > 0) this.tfoot.html('<tr><td colspan="{0}">{1}</td></tr>'.printf(colspan, txt)); } } export default BaseTable;
import { fetchCommonPasswords } from './api.js'; import { ERRORS, SUCCESS } from './constants.js'; /** * Retrieve the list of common passwords from the express sever */ export const getCommonPasswords = async () => { const response = await fetchCommonPasswords(); const passwords = await response.text(); console.log('common passwords received and parsed') return passwords.split('\n'); }; /** * Check whether the length of characters is between the 8 & 64 range * * @param str string to validate */ export const validateLength = (str) => { return str.length >= 8 && str.length <= 64 ? SUCCESS : ERRORS.LENGTH; }; /** * Check if the string is composed of ASCII characters * * @param str string to validate */ export const validateCharacters = (str) => { for(let i = 0; i < str.length; i++) { if(str.charCodeAt(i) > 127) return ERRORS.CHARACTER; } return SUCCESS; }; /** * Check if the the password exists in the commonPasswords array * * @param str password passed in from form * @param array common passwords to check from */ export const validateStrength = (str, array) => { for(let i = 0; i < array.length; i++) { if(array[i] === str) return ERRORS.COMMON; } return SUCCESS; }; export const passwordValidator = (pwd, passwords) => { let messages = []; const length = validateLength(pwd); const characters = validateCharacters(pwd); const strength = validateStrength(pwd, passwords); const { LENGTH, CHARACTER, COMMON } = ERRORS; // return all messages if no password is entered if(!pwd) return [LENGTH, CHARACTER, COMMON]; if(length !== 'Success') messages.push(length); if(characters !== 'Success') messages.push(characters); if(strength !== 'Success') messages.push(strength); return messages; };
export class InterfaceService { static getRooms() {} }
import React from 'react'; import PropTypes from 'prop-types'; const Hamburger = props => ( <button aria-label="toggle-nav" className={!props.ariaHidden ? 'hamburger is-active' : 'hamburger'} onClick={() => props.toggleSideNav(true)} > <span className="line"></span> <span className="line"></span> <span className="line"></span> </button> ) Hamburger.propTypes = { toggleSideNav: PropTypes.func.isRequired, ariaHidden: PropTypes.bool.isRequired } export default Hamburger;
import React, {Component} from 'react'; import { Input, Table, Icon, Divider,Modal,Button, Tabs, Menu,message } from 'antd'; import {Link} from 'react-router'; import PerForm from './PerForm'; import './css/supervision.css'; const Search = Input.Search; class ToProcessed extends Component{ constructor(props){ super(props); this.state={ dataSource:null, visible:false, //新增/编辑modal框初始化变量 editData:null, //编辑数据绑定初始 editSubDtate:null, //编辑modal子table初始值 randomNumber:0, total:0, current:null, page:1, users:'zcg', department:'zcg', visibles:false, } this.handleSearch=this.handleSearch.bind(this) this.dataTable = ''; this.searchName = ''; this.pdata = ''; } perform =(record)=>{ console.log(1); // this.setState({visibles:!this.state.visibles}) // window.location.href='#PerForm?steps='+2+"&lead="+10; } sortData =(lists)=>{ for(var n=1;n<lists.length;n++){ for(var k=0;k<lists.length-1;k++){ var max=lists[k].score; var nextCount=lists[k+1].score; if(nextCount>max){ var preData=lists[k]; lists[k]=lists[k+1]; lists[k+1]=preData; } } } console.log(lists); } //分页查询数据 onChangePage = (page)=>{ console.log(page) this.setState({page:page}); this.dataTables({page:page,rows:10,concept_field:this.pdata}); } // 分页器初始化 handlePage = ()=>{ return( { current:this.state.page, defaultCurrent:1, defaultPageSize:10, showQuickJumper:true, onChange: (pageNumber) => this.onChangePage(pageNumber), total:this.state.total, } ) } showModal =()=>{ // this.setState({visible:!this.state.visible}) window.location.href='#AddSupervisionPlanNew'; } handleSearch = (value) =>{ console.log(0); console.log(value); //this.dataTables({concept_field:value.trim(),state:"UnDealt"}) this.dataTables({concept_field:value.trim(),page:1,rows:10}); this.pdata = value.trim(); } //初始化加载 componentDidMount(){ // var result=require('./toProcess.json'); // console.log(result.rows); // this.setState({dataSource:result.rows}); this.dataTables({concept_field:"",page:1,rows:10}); const that = this; // 获取当前登录用户的信息 ajax({ url:'/txieasyui?taskFramePN=system&command=system.getLoginUserInfo&colname=json_ajax&colname1={%27dataform%27:%27eui_form_data%27,%27tablename%27:%27detail0%27}', type:"GET", success:function(res){ if(res.EAF_ERROR){ message.error(res.EAF_ERROR); return; } that.setState({deptId:res.deptId}); }, error:function(res){ message.error(res.EAF_ERROR) } }) } handleClick = (obj,text) =>{ window.localStorage.obj = JSON.stringify(obj); window.location.href=`#${text}` } dataTables=(data={})=>{ const that = this; this.setState({dataSource:null}) data.status="UnDealt"; // data.concept_field=""; ajax({ url:"/txieasyui?taskFramePN=supplierInspactionDao&command=supplierInspactionDao.getInspactionGroupList&colname=json&refresh=eval(Math.random())&colname1={'dataform':'eui_form_data'}", data:{queryparams:JSON.stringify(data)}, success:function(res){ console.log(res); console.log(res.jresult.rows.length); that.setState({total:Number(res.jresult.total)}); if(res){ const columns = [{ title: '供应商', dataIndex: 'SUP_NAME', key: 'SUP_NAME', // render: text => <a href="javascript:;">{text}</a>, }, { title: '地址', dataIndex:'ADDRESS', key: 'ADDRESS', width:'20%' }, { title: '督察范围', dataIndex: 'INSPECTION_SCOPE', key: 'INSPECTION_SCOPE', }, { title: '督察时间', dataIndex: 'INSPECTION_START_TIME', key: 'INSPECTION_START_TIME', }, { title: '督察目的', dataIndex:'SUPERVISION_PURPOSE', key: 'SUPERVISION_PURPOSE', }, { title: '当前环节', dataIndex:'Act_Name', key: 'Act_Name', width:'11%', }, { title: '操作', dataIndex:'operation', key: 'operation', // render: text => <a href="javascript:;">{text}</a>, render: (text, record,index) => { // console.log(1); console.log(record); let obj={}; Object.keys(record).map((item,index)=>{ if(typeof record[item]=='string'&&record[item]!==''){ obj[item]=record[item]; } }) obj.ActURL=''; console.log(Object.keys(obj),Object.values(obj)) // window.localStorage.obj = JSON.stringify(obj); if(text==="执行(合作部领导审核)"){ return( <span> {/*<div><Link to={{pathname:"PerForm"}}>{text}</Link></div>*/} <div><a href="javascript:;" onClick={()=>that.handleClick(obj,'PerForm')}>{text}</a></div> <div style={{marginTop:'10px'}}><a target="_blank" href={`/diagram/MonitorViewer5.jsp?piid=${record.Pro_ID}`}>流程图</a></div> </span> ) }else if(text==="执行(查看)"){ return( <span> <div><a href="javascript:;" onClick={()=>that.handleClick(obj,'Perform_look')}>{text}</a></div> <div style={{marginTop:'10px'}}><a target="_blank" href={`/diagram/MonitorViewer5.jsp?piid=${record.Pro_ID}`}>流程图</a></div> </span> ) }else if(text==="执行(查看回执)" || obj.EAF_ID=="0CAC9FE9F2F74BE0B888FEC14C2E3F09"){ return( <span> <div><a href="javascript:;" onClick={()=>that.handleClick(obj,'Perform_lookReturn')}>{text}</a></div> <div style={{marginTop:'10px'}}><a target="_blank" href={`/diagram/MonitorViewer5.jsp?piid=${record.Pro_ID}`}>流程图</a></div> </span> ) }else if(text==="执行(各部门上传)"){ return( <span> <div><a href="javascript:;" onClick={()=>that.handleClick(obj,'Perform_lookUpload')}>{text}</a></div> <div style={{marginTop:'10px'}}><a target="_blank" href={`/diagram/MonitorViewer5.jsp?piid=${record.Pro_ID}`}>流程图</a></div> </span> ) }else if(text==="执行(通知供应商)"){ return( <span> <div><a href="javascript:;" onClick={()=>that.handleClick(obj,'Perform_notifySupplier')}>{text}</a></div> <div style={{marginTop:'10px'}}><a target="_blank" href={`/diagram/MonitorViewer5.jsp?piid=${record.Pro_ID}`}>流程图</a></div> </span> ) }else if(text==="执行(查看供应商上传)"){ return( <span> <div><a href="javascript:;" onClick={()=>that.handleClick(obj,'Check2')}>{text}</a></div> <div style={{marginTop:'10px'}}><a target="_blank" href={`/diagram/MonitorViewer5.jsp?piid=${record.Pro_ID}`}>流程图</a></div> </span> ) }else if(text==="执行(确认整改情况)"){ return( <span> <div><a href="javascript:;" onClick={()=>that.handleClick(obj,'Check2')}>{text}</a></div> <div style={{marginTop:'10px'}}><a target="_blank" href={`/diagram/MonitorViewer5.jsp?piid=${record.Pro_ID}`}>流程图</a></div> </span> ) }else if(text==="执行(归档)"){ return( <span> <div><a href="javascript:;" onClick={()=>that.handleClick(obj,'Check')}>{text}</a></div> <div style={{marginTop:'10px'}}><a target="_blank" href={`/diagram/MonitorViewer5.jsp?piid=${record.Pro_ID}`}>流程图</a></div> </span> ) }else if(text==="执行(编制)"){ return( <span> <div><a href="javascript:;" onClick={()=>that.handleClick(obj,'PerForm_compile')}>{text}</a></div> <div style={{marginTop:'10px'}}><a target="_blank" href={`/diagram/MonitorViewer5.jsp?piid=${record.Pro_ID}`}>流程图</a></div> </span> ) }else if(text==="执行(查看)"){ return( <span> <div><a href="javascript:;" onClick={()=>that.handleClick(obj,'Check')}>{text}</a></div> <div style={{marginTop:'10px'}}><a target="_blank" href={`/diagram/MonitorViewer5.jsp?piid=${record.Pro_ID}`}>流程图</a></div> </span> ) } }, }]; const dataSource = res.jresult.rows?res.jresult.rows:''; that.setState({dataSource:dataSource,columns:columns}); } }, error:function(res){ message.error(check(res).EAF_ERROR) } }); } render(){ return ( <div id="alignCen"> <Search placeholder="请输入供应商名称/地址/范围/目的" onSearch={this.handleSearch} enterButton style={{width:'30%'}}/> {this.state.deptId=='CCE0A8E1903BBC50D1052FF417B8D70B'?<Button type="primary" onClick={this.showModal} className="fr">新增监督计划</Button>:''} <Table pagination={this.handlePage()} loading={!this.state.dataSource} bordered={true} columns={this.state.columns} dataSource={this.state.dataSource} id="processTab"/> {/* <PerForm visible={this.state.visibles} showModal={this.perform}/> */} </div> ) } } export default ToProcessed;
import {StyleSheet} from 'react-native'; export default StyleSheet.create({ container: { flex: 1, backgroundColor: '#455a64', alignItems: 'center', justifyContent: 'center', }, inputContainer: { width: '80%', backgroundColor: 'rgba(255,255,255,0.3)', borderColor: 'gray', borderWidth: 1, borderRadius: 25, paddingHorizontal: 16, fontSize: 16, color: '#ffffff', marginVertical: 10, }, buttonContainer: { backgroundColor: '#1c313a', borderRadius: 25, width: '80%', marginVertical: 10, paddingVertical: 13, }, buttonText: { fontSize: 16, fontWeight: '500', color: '#ffffff', textAlign: 'center', }, textContainer: { fontSize: 20, color: 'white', }, progressBar: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, justifyContent: 'center', alignItems: 'center', }, });
import React from "react" import styled from "styled-components" import FooterLink from "./FooterLink" const FooterLinkGroup1 = () => { const links = [ { id: 1, title: "Home", slug: "/" }, { id: 2, title: "About", slug: "/about" }, { id: 3, title: "Classes", slug: "/classes" }, { id: 4, title: "Case Studies", slug: "/case-studies" }, { id: 5, title: "Schedule", slug: "/schedule" }, ] const linkGroup = links.map(link => { const id = link.id const title = link.title const slug = link.slug return <FooterLink key={id} title={title} slug={slug} /> }) return <GroupContainer>{linkGroup}</GroupContainer> } export default FooterLinkGroup1 const GroupContainer = styled.div` display: grid; grid-template-columns: 1fr; grid-template-rows: auto; gap: 8px; `
/** * Created by hui.sun on 15/11/13. */ 'use strict'; define(['../app'], function(app) { app.directive('pl4Select', function() { return { restrict: 'EA', replace: true, template: '<div class="select-direvtive">'+ '<div class="form-group">'+ '<label>{{selectSetting.firstName}}:</label>'+ '<select class="form-control" ng-model="your.province"ng-options="v.province for v in chinaCities" ng-change="selectedFirstValue(your.province)">'+ '</select>'+ '</div>'+ '<div class="form-group">'+ '<select class="form-control" ng-model="your.city" ng-options="v for v in your.province.cities">'+ '</select></div></div>', link: function($scope, el, attr) { // console.log($scope) $scope.your = { province: '', city: '' }; $scope.your.province = $scope.chinaCities[0]; $scope.your.city = $scope.chinaCities[0].cities[0]; $scope.selectedFirstValue = function(province) { $scope.your.city = province ? province.cities[0] : ''; }; } } }); });
/** * Created by Ramon on 11-9-2017. */ const loggingLevels = { silly: "silly", debug: "debug", verbose:"verbose", info:"info", warn:"warn", error:"error" }; // ports below the 1024 range require root access; run npm with root privileges var config = { portHttp: 8080, portHttps: 443, host: '127.0.0.1', certKey: './storage/ssl/ssl.key', certKeyPhrase: 'icspt7b', certFile: './storage/ssl/ssl.crt', logging: { logToFile: true, loggingDir: "./logs", loggingLevel: loggingLevels.debug }, /** * setup requests rate limit vars globally and login page */ rateLimiter:{ global: { windowMs: 60*1000, // How long is the timespan? delayAfter: 0, //begin slowing down responses after the first request delayMs: 0, //slow down subsequent responses by 3 seconds per request max: 5000, //start blocking after 5 requests message:"Too many request, try again in {minutes} minutes", headers:true//show header stats with attemts remaining }, login:{ windowMs: 15*60*1000,//15*60*1000, // How long is the timespan? delayAfter: 3, //begin slowing down responses after the first request delayMs: 3*1000, //slow down subsequent responses by 3 seconds per request max: 5, //start blocking after 5 requests message:"Too many request, try again in {minutes} minutes", headers:true//show header stats with attemts remaining } }, sessionTimeout: 20, }; module.exports = config;
'use strict'; var path = require('path'); var _ = require('lodash'); /** * Przygotowanie konfiguracji przez złączenie obiektu konfiguracji bazowej z konfiguracją dla środowiska wykonawczego */ function prepareConfig(env) { var mergedConf = {}; try { var envConf = require('./' + env + '.js'); mergedConf = _.merge( baseConf, envConf ); } catch (err) { // Nie udało się znaleźć lub wczytać pliku z konfiguracją! Przyjmujemy domyślną konfigurację ... mergedConf = baseConf; }; return mergedConf; } // Bazowa konfiguracja, która zostanie rozszerzona i/lub przykryta przez konfigurację dla środowiska wykonawczego var baseConf = { env: process.env.NODE_ENV, // Ścieżka do roota serwera root: path.normalize(__dirname + '/../../..'), // Domyślna nazwa hosta hostname: 'localhost', // Domyślny port port: process.env.PORT || 9000, // Plik logu logPath: './logs/log.log', // Konfiguracja MongoDB mongo: { uri: 'mongodb://localhost/playground-dev' }, seedDB: true, api: { jwt: { expiresInMinutes: 10, secretKey: 'siałababamak' } } }; // Opublikuj konfigurację zależną od środowiska wykonawczego module.exports = prepareConfig(process.env.NODE_ENV);
import React from "react"; import "../../css/leftpanel.css"; import Header from "./header"; import ChgMain from "./chgForms/chgMain"; const LeftPanel = () => { return ( <div className="col-md-7 panel-one"> <Header /> <ChgMain /> </div> ); }; export default LeftPanel;
//Filename: views/users/UserView.js define([ 'jquery', 'underscore', 'backbone', 'collections/instagram', 'models/location', 'text!templates/projects/projectTemplate.html' ], function($, _, Backbone, InstagramCollection, Locations, videoTemplate){ var VideoView = Backbone.View.extend({ el: $('.content'), initialize: function() { this.isLoading = false; this.instagramCollection = new InstagramCollection(); this.locations = new Locations(); }, events : { 'click #refreshVid': 'loadVidResults', 'hover video' : 'playVid', 'mouseleave video' : 'stopVid' }, render: function(){ var that = this; this.loadVidResults(); }, loadVidResults: function(){ var that = this; this.isLoading = true; if (this.isLoading == true) { $(that.el).html('<h4 class="loading"><img src="img/small-loading.gif"></h4>'); } that = this; this.instagramCollection.fetch({ success: function(videos) { console.log('This is the videos object ', videos.models); $(that.el).html(_.template(videoTemplate, {videos: videos.models, _:_ , country: 'hullo'})); } }); }, playVid: function(e) { var target = e.target; $target = $(e.target); $(target).parent().find('.count').addClass('active'); target.play(); }, stopVid: function(e) { var target = e.target; $(target).parent().find('.count').removeClass('active'); target.pause(); } }); return VideoView; });
const arr = ['🍊', '🍊', '🍊', '🍊'] // a função findIndex irá retornar o índice do primeiro elemento que // satisfazer a condição que for declarada. // OBS: Se o elemento não existir, será retornado -1 const indiceDaPrimeiraLaranja = arr.findIndex(elemento => { return elemento === '🍊' }) const indiceDaPrimeiraUva = arr.findIndex(elemento => { return elemento === '🍇' }) console.log(indiceDaPrimeiraLaranja) // 0 console.log(indiceDaPrimeiraUva) // -1
//Written by Nabanita Maji and Cliff Shaffer, Spring 2015 /*global ODSA */ $(document).ready(function () { "use strict"; var av_name = "threeSATtoHCCON"; $(".avcontainer").on("jsav-message" , function() { // invoke MathJax to do conversion again MathJax.Hub.Queue(["Typeset" , MathJax.Hub]); }); $(".avcontainer").on("jsav-updatecounter" , function(){ // invoke MathJax to do conversion again MathJax.Hub.Queue(["Typeset" , MathJax.Hub]); }); var jsav = new JSAV(av_name); /* Description for some global variables used : * g: The graph that is constructed for the reduction. Any pair of * nodes in any path P_i in G has 2 edges (say forward for left-to-right * and reverse for right-to-left) between them. However display of such * pair of edges is not yet supported in jsav. So only forward edges are * included as a part of graph g. * * g1 : For the problem described above, as a workaround we have g1, * a second graph which contains a copy of all nodes in g that requires * both reverse and forward edges. These nodes of g1 are not visible and * are placed 5 units beneath the corresponding nodes in g. These nodes * are used to draw the reverse edges on the canvas. * * source : the source node * target : the target node * * P: The array in which the ith row holds the nodes in the paths P_i * in the graph g. * P1: The array in which the ith row holds all the invisible nodes * corresponding to path P_i in graph g1. * * PE: The array in which the [i,j,0]'th item holds the forward edge * for jth node of path P_i (from g) and [i,j,1]'th item holds the * reverse edge (from g1). * * PE1: The array holds all the edges connecting the source and target to * the rest of the graph. * * PE2: The array holds all the interconnecting edges that connects two * paths P_i and P_j. * * PE3: The array contains the edges that connect clause-nodes to the * nodes in a path. * * C: The array that holds the clause nodes of the graph. */ var x= 200 , y1 = 10 , r = 15; var label1, label2, label3, label4, label5, label6,label7,label8,label9,label10,label11, g, g1, source, target, line1, line2, varlabel, exprlabel, literalLabels = new Array(4), clauses = new Array(3), P = new Array(4), C = new Array(3), P1 = new Array(4), color = new Array(3), PLabel = new Array(4), PE = new Array(4), PE1 = new Array(5), PE2 = new Array(4), PE3 = new Array(3); var input=[["$x_1$", "$x_2$", "$\\overline{x_3}$"], ["$\\overline{x_2}$", "$x_3$", "$x_4$"], ["$x_1$", "$\\overline{x_2}$", "$x_4$"]]; function hideGraph(){ exprlabel.hide(); for(var i=0;i<5;i++) PE1[i].hide(); for(var i=0;i<4;i++){ if(i > 0) { for(var j=0;j<4;j++) PE2[i-1][j].hide(); } PLabel[i].hide(); for(var j=0;j<6;j++){ if(j>0){ PE[i][j][0].hide(); PE[i][j][1].hide(); } P[i][j].hide(); } } source.hide(); target.hide(); for(var i=0;i<3;i++) { C[i].hide(); for(var j=0;j<8;j++) clauses[i][j].hide(); for(var j=0;j<3;j++){ PE3[i][j][0].hide(); PE3[i][j][1].hide(); } } line1.hide(); line2.hide(); } //color array for clauses color = ["#669966" , "SlateBlue" , "IndianRed"]; g1 = jsav.ds.graph({width: 800, height: 550, left: 100, top: 50, layout: "manual", directed: true}); g = jsav.ds.graph({width: 800, height: 550, left: 100, top: 50, layout: "manual" , directed: true}); var y=15; // Slide 1 jsav.umsg("<br><b>Reduction of 3-SAT to Hamiltonian Cycle Problem</b>"); label1=jsav.label("This slideshow explains the reduction of 3CNF"+ " Satisfiability to Hamiltonian Cycle in polynomial time",{top:y}); jsav.displayInit(); jsav.step(); // Slide 2 label1.hide(); jsav.umsg("<br><b>3-SAT and HAMILTONIAN CYCLE.</b>"); label1=jsav.label("For a 3-SAT expression containing $n$ variables," + " there are $2^n$ possible assignments.", {left:0,top:y-30}); label2=jsav.label("We model these $2^n$ possible truth assignments using a graph with" +" $2^n$ different Hamiltonian cycles <br>by the following method." , {left:0,top:y}); jsav.step(); // Slide 3 label1.hide(); label2.hide(); jsav.umsg("<br><b>Step1: Construction of paths</b>"); label1=jsav.label("Construct $n$ paths $P_1$, $P_2$, ..., $P_n$ corresponding to the" +" $n$ variables." , {left:0,top:y-30}); label2=jsav.label("Each path $P_i$ should consist of $2k$ nodes ($v_{i,1}$, $v_{i,2}$" +", ..., $v_{i,2k}$) where $k$ is the number of clauses <br>in the "+ "expression." , {left:0,top:y}); jsav.step(); // Slide 4 label4=jsav.label("For example, consider the following boolean expression with 4 variables: ", {left:0,top:y+60}); label5=jsav.label("$x_1$, $x_2$, $x_3$, $x_4$" , {left:0,top:y+90}); label6=jsav.label("Expression: $(x_1 + x_2 + \\overline{x_3}).(\\overline{x_2} + x_3 + x_4).(x_1 + \\overline{x_2} + x_4)$", {left:0,top:y+120}); label7=jsav.label("We construct 4 paths with 6 nodes each", {left:0,top:y+150}); label8=jsav.label("$P_1$ with nodes $v_{1,1}, v_{1,2}, v_{1,3}, v_{1,4}, v_{1,5}, v_{1,6}$", {left:0,top:y+180}); label9=jsav.label("$P_2$ with nodes $v_{2,1}, v_{2,2}, v_{2,3}, v_{2,4}, v_{2,5}, v_{2,6}$", {left:0,top:y+210}); label10=jsav.label("$P_3$ with nodes $v_{3,1}, v_{3,2}, v_{3,3}, v_{3,4}, v_{3,5}, v_{3,6}$", {left:0,top:y+240}); label11=jsav.label("$P_4$ with nodes $v_{4,1}, v_{4,2}, v_{4,3}, v_{4,4}, v_{4,5}, v_{4,6}$", {left:0,top:y+270}); jsav.step(); // Slide 5, 6, 7, 8 // display the boolean variables label1.hide(), label2.hide(); label4.hide(), label5.hide(); label6.hide(); label7.hide(), label8.hide(); label9.hide(); label10.hide(), label11.hide(); jsav.umsg("<br><b>Step 1a: Adding nodes for the paths</b>"); varlabel = jsav.label("Variables:" , {left:10 , top:y-30}); x = 100; for(var i=0;i<6;i=i+2) { literalLabels[i]=jsav.label("$x_"+(i/2+1)+"$" , {left:x , top:y-30}); literalLabels[i+1]=jsav.label("," , {left:x+30 , top:y-30}); x=x+45; } literalLabels[i]=jsav.label("$x_"+(i/2+1)+"$" , {left:x , top:y-30}); y1=60; for(var i=0;i<4;i++) { x=10; P[i]=new Array(6); P1[i]=new Array(6); PE[i]=new Array(6); PLabel[i]=jsav.label("$P_"+(i+1)+"$" , {"left":x+70 , "top":y1+55}); if(i>0) { literalLabels[2*(i-1)].removeClass("zoomlabel"); for(var j=0;j<6;j++) { P[i-1][j].addClass("blur"); } } for(var j=0;j<6;j++) { // Add nodes corresponding to the paths to g and g1 // Display the nodes one by one P1[i][j] = g1.addNode(" " , {"top":y1+5 , "left":x}) .addClass("variablenode").addClass("invisible"); P[i][j] = g.addNode(" "+(j+1) , {"top":y1 , "left":x}) .addClass("variablenode"); if(j>0) { // Add the forward edges between the nodes to g and reverse edges to g1 PE[i][j]=new Array(2); PE[i][j][0]=g.addEdge(P[i][j-1] , P[i][j]) .addClass("edgetrue"); PE[i][j][0].hide(); PE[i][j][1]=g1.addEdge(P1[i][j] , P1[i][j-1]) .addClass("edgefalse"); PE[i][j][1].hide(); } x = x+85; } // Add the interconnecting edges between the paths to g if(i>0){ PE2[i-1]=new Array(4); PE2[i-1][0]=g.addEdge(P[i-1][0] , P[i][0]) .addClass("edgeconnect"); PE2[i-1][1]=g.addEdge(P[i-1][0] , P[i][j-1]) .addClass("edgeconnect"); PE2[i-1][2]=g.addEdge(P[i-1][j-1] , P[i][0]) .addClass("edgeconnect"); PE2[i-1][3]=g.addEdge(P[i-1][j-1] , P[i][j-1]) .addClass("edgeconnect"); for(j=0;j<4;j++) PE2[i-1][j].hide(); } y1 = y1+60; g.layout(); g1.layout(); literalLabels[2*i].addClass("zoomlabel"); jsav.step(); } // Slide for(var j=0;j<6;j++){ P[i-1][j].addClass("blur"); } literalLabels[2*(i-1)].removeClass("zoomlabel"); varlabel.hide(); for( var i=0;i<7;i++) literalLabels[i].hide(); //display forward edges jsav.umsg("<br><b>Step 1b: Adding edges to the paths</b>"); label1=jsav.label("Add edges from $v_{i,j-1}$ to $v_{i,j}$ (i.e. left to right) on" +" $P_i$ to correspond to the assignment $x_i = True$" , {left:0,top:y-30} ); for(var i=0;i<4;i++){ for(var j=0;j<6;j++){ if(j>0) PE[i][j][0].show(); } } jsav.step(); // Slide 10 // Display reverse edges label1.hide(); jsav.umsg("<br><b>Step 1b: Adding edges to the paths</b>"); label1=jsav.label("Add edges from $v_{i,j}$ to $v_{i,j-1}$ (i.e. right to left) on"+ " $P_i$ to correspond to the assignment $x_i = False$" , {left:0,top:y-30} ); for(var i=0;i<4;i++){ for(var j=0;j<6;j++){ if(j>0) PE[i][j][1].show(); } } jsav.step(); // Slide 11 // Display interconnecting edges label1.hide(); jsav.umsg("<br><b>Step 2: Inter-connecting the paths</b>"); label1=jsav.label("Add edges from $v_{i,1}$ and $v_{i,6}$ to $v_{i+1,1}$ and " +"$v_{i+1,6}$" , {left:0,top:y-30} ); for(var i=1;i<4;i++){ for(var j=0;j<4;j++) PE2[i-1][j].show(); } jsav.step(); // Slide 12 jsav.umsg("<br><b>Step 3: Adding source and target nodes</b>"); label1.hide(); y1 = 65; //add source and target nodes to g and display. source = g.addNode("<b>s</b>" , {"top":-5 , "left":220}) .addClass("extranode"); target = g.addNode("<b>t</b>" , {"top":y1+250 , "left":220}) .addClass("extranode"); var tmpnode = g.addNode(" " , {"top":-5 , "left":-200}) .addClass("extranode").addClass("invisible"); //add edges for souce and target to g. PE1[0] = g.addEdge(source , P[0][0]) .addClass("edgeconnect"); PE1[1] = g.addEdge(source , P[0][5]) .addClass("edgeconnect"); PE1[2] = g.addEdge(P[3][0] , target) .addClass("edgeconnect"); PE1[3] = g.addEdge(P[3][5] , target) .addClass("edgeconnect"); PE1[4]=g.addEdge(tmpnode , source) .addClass("edgeconnect"); for(i=0;i<5;i++) PE1[i].hide(); line1 = jsav.g.line(100 , 80 , 100 , 405); line1.addClass("edgeconnect"); line2 = jsav.g.line(100 , 405 , 320 , 405); line2.addClass("edgeconnect"); line1.hide(); line2.hide(); g.layout(); jsav.step(); // Slide 13 // display the edges connecting source and target to path nodes in g. label1.hide(); jsav.umsg("<br><b>Step 4: Connecting source and target nodes to the " +"paths</b>"); label1=jsav.label("Add edges from '$s$' to $v_{1,1}$ and $v_{1,6}$ and from "+ "$v_{4,1}$ and $v_{4,6}$ to '$t$'" , {left:0,top:y-30} ); for(var i=0;i<4;i++) PE1[i].show(); jsav.step(); // Slide 14 //display he edge from target to source. label1.hide(); jsav.umsg("<br><b>Step 5: Adding a backpath from target to source"); label1=jsav.label("Being the only path from target to source, this path will " + "always be present in any Hamiltonian Cycle <br>of the graph.", {left:0,top:y-30} ); line2.show(); line1.show(); PE1[4].show(); jsav.step(); // Slide 15 label1.hide(); jsav.umsg("<br><b>Step 6: Adding nodes corresponding to clauses</b>"); x=150; y1=-10; //display the CNF expression with each clause in different color. exprlabel = jsav.label("3-CNF expression: " , {"top":y1 , "left":10}); for(var i=0;i<3;i++){ clauses[i] = new Array(8); x=x+15; clauses[i][0]=jsav.label("(", {left:x , top:y1}).css({"color":color[i]}); x=x+15; for(var j=1;j<5;j=j+2) { clauses[i][j] = jsav.label(input[i][(j-1)/2], {left:x, top:y1}).css({"color":color[i]}); x=x+25; clauses[i][j+1] = jsav.label("+", {left:x, top:y1}).css({"color":color[i]}); x=x+15; } clauses[i][j] = jsav.label(input[i][(j-1)/2], {left:x, top:y1}).css({"color":color[i]}); x=x+25; clauses[i][6] = jsav.label(")", {left:x+5, top:y1}).css({"color":color[i]}); x=x+15; clauses[i][7]=jsav.label(".", {left:x+5, top:y1}); } // Add the caluse nodes to g and display. C[0] = g.addNode("<b>C1</b>" , {"top":-15 , "left":430}) .addClass("clausenode").css({"background-color":color[0]}); C[1] = g.addNode("<b>C2</b>" , {"top":305 , "left":380}) .addClass("clausenode").css({"background-color":color[1]}); C[2] = g.addNode("<b>C3</b>" , {"top":300 , "left":580}) .addClass("clausenode").css({"background-color":color[2]}); for(var i=0;i<3;i++){ PE3[i] = new Array(3); for(var j=0;j<3;j++) PE3[i][j] = new Array(2); } // add the edges connecting clause nodes to path nodes in g PE3[0][0][0] = g.addEdge(P[0][0], C[0]).addClass("clauseedge"); PE3[0][0][1] = g.addEdge(C[0], P[0][1]).addClass("clauseedge"); PE3[0][1][0] = g.addEdge(P[1][0], C[0]).addClass("clauseedge"); PE3[0][1][1] = g.addEdge(C[0], P[1][1]).addClass("clauseedge"); PE3[0][2][0] = g.addEdge(C[0], P[2][0]).addClass("clauseedge"); PE3[0][2][1] = g.addEdge(P[2][1], C[0]).addClass("clauseedge"); PE3[1][0][0]=g.addEdge(P[1][3] , C[1]).addClass("clauseedge"); PE3[1][0][1]=g.addEdge(C[1] , P[1][2]).addClass("clauseedge"); PE3[1][1][0]=g.addEdge(P[2][2] , C[1]).addClass("clauseedge"); PE3[1][1][1]=g.addEdge(C[1] , P[2][3]).addClass("clauseedge"); PE3[1][2][0]=g.addEdge(P[3][2] , C[1]).addClass("clauseedge"); PE3[1][2][1]=g.addEdge(C[1] , P[3][3]).addClass("clauseedge"); PE3[2][0][0]=g.addEdge(C[2] , P[0][5]).addClass("clauseedge"); PE3[2][0][1]=g.addEdge(P[0][4] , C[2]).addClass("clauseedge"); PE3[2][1][0]=g.addEdge(C[2] , P[1][4]).addClass("clauseedge"); PE3[2][1][1]=g.addEdge(P[1][5] , C[2]).addClass("clauseedge"); PE3[2][2][0]=g.addEdge(P[3][4] , C[2]).addClass("clauseedge"); PE3[2][2][1]=g.addEdge(C[2] , P[3][5]).addClass("clauseedge"); for(var i=0;i<3;i++){ for(var j=0;j<3;j++){ PE3[i][j][0].hide(); PE3[i][j][1].hide(); } } g.layout(); jsav.step(); // Slide 16 hideGraph(); jsav.umsg("<br><b>Step 7: Connecting clauses to the paths</b>"); label1=jsav.label("If a clause $C_j$ contains the variable $x_i$,", {left:0,top:y-30} ); label2=jsav.label("&nbsp;&nbsp;&nbsp;1.Connect $C_j$ to $v_{i,2j-1}$ and "+ "$v_{i,2j}$" , {left:0,top:y+0} ); label3=jsav.label("&nbsp;&nbsp;&nbsp;2.The direction of the path connecting $C_j$"+ ",$v_{i,2j-1}$ and $v_{i,2j}$ should be:" , {left:0,top:y+30} ); jsav.step(); // Slide 17 label4 = jsav.label("a. left to right if $C_j$ contains $x_i$" , {"left":40 , "top":75} ); label5 = jsav.label("For example : $C_1 =$ ($x_1$ + $x_2$ + $\\overline{x_3}$)" +" contains $x_1$. So $C_1$ should be connected as:" , {"left":40 , "top":100} ); var g2 = jsav.ds.graph({width: 200 , height: 100 , left: 100 , top: y+120 , layout: "manual" , directed: true}); var tmpnode1, tmpnode2, tmpnode3; label6 = jsav.label("$P_1$" , {"left":100 , "top":215}); tmpnode1 = g2.addNode("1" , {"top":70 , "left":30}).addClass("variablenode").addClass("blur"); tmpnode2 = g2.addNode("2" , {"top":70, "left":130}).addClass("variablenode").addClass("blur"); tmpnode3 = g2.addNode("C1" , {"top":6, "left":90}).addClass("democlausenode"); g2.addEdge(tmpnode1 , tmpnode3); g2.addEdge(tmpnode3 , tmpnode2); g2.layout(); jsav.step(); // Slide 18 y1=250; label7 = jsav.label("b. right to left if $C_j$ contains $\\overline{x_i}$", {"left":40 , "top":y1} ); label8 = jsav.label("For example : $C_2 = $ ($\\overline{x_2}$ + $x_3$ + $x_4$) " +"contains $\\overline{x_2}$. So $C_2$ should be connected" +" as:" , {"left":40 , "top":y1+25} ); var g3 = jsav.ds.graph({width: 200 , height: 100 , left: 100 , top: y1+45 , layout: "manual" , directed: true}); label9 = jsav.label("$P_2$" , {"left":100 , "top":y1+125}); tmpnode1 = g3.addNode("3" , {"top":75 , "left":30}).addClass("variablenode").addClass("blur"); tmpnode2 = g3.addNode("4" , {"top":75, "left":130}).addClass("variablenode").addClass("blur"); tmpnode3 = g3.addNode("C2" , {"top":10 , "left":90}).addClass("democlausenode"); g3.addEdge(tmpnode3 , tmpnode1); g3.addEdge(tmpnode2 , tmpnode3); g3.layout(); jsav.step(); // Slide 19 jsav.umsg("<br><b>Step7: Connecting clauses to the paths</b>"); //display the graph on canvas g2.hide(); g3.hide(); label1.hide(); label2.hide(); label3.hide(); label4.hide(); label5.hide(); label6.hide(); label7.hide(); label8.hide(); label9.hide(); line2.show(); line1.show(); for(var i=0;i<5;i++) PE1[i].show(); for(var i=0;i<4;i++){ if(i>0){ for(var j=0;j<4;j++) PE2[i-1][j].show(); } PLabel[i].show(); for(var j=0;j<6;j++){ if(j>0){ PE[i][j][0].show(); PE[i][j][1].show(); } P[i][j].show(); } } source.show(); target.show(); exprlabel.show(); for(var i=0;i<3;i++) for(var j=0;j<8;j++) clauses[i][j].show(); C[0].show(); C[1].show(); C[2].show(); jsav.step(); // Slide 20 , side 21 , slide 22 , slide 23 , slide 24 , slide 25 , slide 26 // Slide 27 , slide 28 . Slide 29 // these slides show animation for displaying all the edges for each clause one // by one for(var i=0;i<3;i++){ if(i>0){ clauses[i-1][5].removeClass("zoomlabel"); PE3[i-1][2][0].removeClass("boldedge"); PE3[i-1][2][1].removeClass("boldedge"); } for(var j=0;j<3;j++){ if(j>0){ clauses[i][2*j-1].removeClass("zoomlabel"); PE3[i][j-1][0].removeClass("boldedge"); PE3[i][j-1][1].removeClass("boldedge"); } clauses[i][2*j+1].addClass("zoomlabel"); PE3[i][j][0].addClass("boldedge"); PE3[i][j][1].addClass("boldedge"); PE3[i][j][0].show(); PE3[i][j][1].show(); jsav.step(); } } clauses[2][5].removeClass("zoomlabel"); PE3[2][2][0].removeClass("boldedge"); PE3[2][2][1].removeClass("boldedge"); jsav.step(); // Slide 30 line1.hide(); line2.hide(); exprlabel.hide(); g.hide(); g1.hide(); for(var i=0;i<4;i++) PLabel[i].hide(); for(var i=0;i<3;i++) for(j=0;j<8;j++) clauses[i][j].hide(); jsav.umsg("<br><b>Insights about the constructed graph</b><br><br><br>"); label1=jsav.label("1. Any Hamiltonian Cycle in the constructed graph ($G$) traverses" +" $P_i$ either from right-to-left or left-to-right.<br>" +"This is because any path entering a node $v_{i,j}$ has to exit "+ "from $v_{i,j+1}$ either immediately or via one <br> clause-node"+ " in between, in order to maintain Hamiltonian property<br>"+ "Similarly all paths entering at $v_{i,j-1}$ has to exit from "+ "$v_{i,j}$.<br><br>"+ "2. Since each path $P_i$ can be traversed in $2$ possible ways "+ "and we have $n$ paths mapping to $n$ variables, <br>there can be $2^n$" +" Hamiltonian cycles in the graph $G$ - {$C_1$, $C_2$ $\\cdots$ " +"$C_k$}.<br>"+ "Each one of this $2^n$ Hamiltonian cycles corresponds to a particular" +" assignment for variables $x_1$, $x_2$ $\\cdots$ $x_n$.<br>" +"<br><br>3. <b>This graph can be constructed in polynomial time.</b>" ,{left:0,top:y -30} ); jsav.step(); // Slide 31 label1.hide(); jsav.umsg("<br><b>3-SAT and Hamiltonian Cycle</b>"); label1=jsav.label("1. <b>If there exists a Hamiltonian cycle $H$ in the graph $G$," +"</b><br>" + "If $H$ traverses $P_i$ from left to right, assign $x_i = True$<br>"+ "If $H$ traverses $P_i$ from right to left, assign $x_i = False$"+ "<br><br>"+ "Since H visits each clause node $C_j$, at least one of $P_i$ was" +" traversed in the right direction relative <br>to the node $C_j$"+ "<br>"+ "<b>The assignment obtained here satisfies the given 3 CNF.</b>"+ "<br><br>",{left:0,top:y-20}); jsav.step(); // Slide 32 label2=jsav.label("2. <b>If there exists a satisfying assignment for the 3 CNF</b>," +"<br>"+ "Select the path that traverses $P_i$ from left-to-right if $x_i" +" = True$ or right-to-left if $x_i = False$<br>"+ "Include the clauses in the path wherever possible.<br>"+ "Connect the source to $P_1$, $P_n$ to target and $P_i$ to "+ "$P_{i+1}$ appropriately so as to maintain the continuity <br>of "+ "the path <br>"+ "Connect the target to source to complete the cycle<br><br>" +"Since the assignment is such that every clause is satisfied, all " +"the clause-nodes are included in the path.<br>The $P_i$ nodes and " +"source and target are all included and since the path traverses "+ "unidirectional, <br>no node is repeated twice <br>"+ "<b> The path obtained is a Hamiltonian Cycle</b><br><br>",{left:0,top:y+160}); jsav.step(); // Slide 33 label1.hide(); label2.hide(); line1.show(); line2.show(); g.show(); g1.show(); for(var i=0;i<3;i++) for(j=0;j<8;j++) clauses[i][j].show(); for(var i=0;i<4;i++) PLabel[i].show(); for(var i=0;i<PE1.length;i++) PE1[i].addClass("blur"); for(var i=0;i<4;i++){ for(j=1;j<6;j++){ PE[i][j][0].addClass("blur"); PE[i][j][1].addClass("blur"); } } for(var i=0;i<3;i++){ for(var j=0;j<4;j++) PE2[i][j].addClass("blur"); } for(var i=0;i<3;i++){ for(var j=0;j<3;j++){ PE3[i][j][0].addClass("blur"); PE3[i][j][1].addClass("blur"); } } jsav.umsg("<br><b>Hamiltonian Cycle in the constructed graph</b><br><br><br>"); label1 = jsav.label("The graph $G$ has a Hamiltonian cycle<br>" , {left:0,top:y-30}); for(var i=0;i<3;i++) for(j=0;j<8;j++) clauses[i][j].hide(); // highlight the hamiltonian cycle on the graph in blue. line1.addClass("highlightedge"); line2.addClass("highlightedge"); PE1[0].addClass("highlightedge"); PE1[2].addClass("highlightedge"); PE1[4].addClass("highlightedge"); PE3[0][0][0].addClass("highlightedge"); PE3[0][0][1].addClass("highlightedge"); for(var i=2;i<=4;i++) PE[0][i][0].addClass("highlightedge"); PE2[0][3].addClass("highlightedge"); for(var i=1;i<=5;i++) PE[1][i][1].addClass("highlightedge"); PE2[1][0].addClass("highlightedge"); for(var i=1;i<=5;i++) if(i!=3) PE[2][i][0].addClass("highlightedge"); PE2[2][3].addClass("highlightedge"); for(var i=1;i<=5;i++) PE[3][i][1].addClass("highlightedge"); PE3[1][1][0].addClass("highlightedge"); PE3[1][1][1].addClass("highlightedge"); PE3[2][0][0].addClass("highlightedge"); PE3[2][0][1].addClass("highlightedge"); jsav.step(); // Slide 34 label1.hide(); jsav.umsg("<br><b>Assignment for 3-SAT</b><br><br><br>"); label1=jsav.label("From the Hamiltonian cycle below the assignment is : <br>" +"<b>$x_1 = True$ , $x_2 = False$ , $x_3 = True$ , $x_4 = False$</b><br><br>", {left:0,top:y-30}); exprlabel.hide(); for(var i=0;i<3;i++) for(j=0;j<8;j++) clauses[i][j].hide(); jsav.step(); // Slide 35 label1.hide(); jsav.umsg("<br><b>Satisfiability of 3-CNF</b><br><br><br>"); hideGraph(); jsav.umsg("From the Hamiltonian cycle below the assignment is : <br><br>", {'preserve':true}); label1=jsav.label("<b>$x_1 = True$, $x_2 = False$, $x_3 = True$, $x_4 = False$</b><br><br>"+ "The above assignment satisfies the 3CNF ($x_1$ + $x_2$ + "+ "$\\overline{x_3}$).($\\overline{x_2}$ + $x_3$ + $x_4$).($x_1$ + " +"$\\overline{x_2}$ + $x_4$)<br>" , {left:0,top:y+0}); jsav.recorded(); });
/** * Created by ZG on 2016/3/11. */ // 存储当前时间数字 var curtime = []; // 获取每个页面的数字 function gettimeNum(time){ var LeftTimeNum = Math.floor(time / 10); var RightTimeNum = time % 10 ; curtime.push(LeftTimeNum); curtime.push(RightTimeNum); } function rotatePage(i,curPageNum){ var curPageNode = document.getElementById("time-" + i + "-" +curPageNum) // 必须先确认curPageNode存在!! if (curPageNode){ var prevPageNode = curPageNode.previousElementSibling; if (!prevPageNode) { prevPageNode = curPageNode.parentNode.lastElementChild; } var nextPageNode = curPageNode.nextElementSibling; if (!nextPageNode){ nextPageNode = curPageNode.parentNode.firstElementChild; } prevPageNode.style.visibility = "visible"; prevPageNode.style.webkitTransform = "rotateX(-90deg)"; curPageNode.style.visibility = "visible"; curPageNode.style.webkitTransform = "rotateX(0deg)"; nextPageNode.style.visibility = "hidden"; nextPageNode.style.webkitTransform = "rotateX(90deg)"; } } function draw(){ var curdate = new Date(); // 获得当前时间数组 gettimeNum(curdate.getHours()); gettimeNum(curdate.getMinutes()); gettimeNum(curdate.getSeconds()); for (var i = 0; i < 16; i++){ rotatePage( i, curtime[i]); } // 过去的时间置为空!! curtime = []; } //反复调用draw setInterval(function(){ draw(); }, 1000);
export { default } from '@upfluence/ember-upf-utils/meta-er-extractor/service';
` hello git `
getLocation('8c800a69caf013').then((location) => { console.log( `City: ${location.city}` ) console.log( `Region: ${location.region}` ) console.log( `Country: ${location.country}` ) }).catch((err) => { console.log( `Error: ${err}` ) })
function def() { var j = 10; for(var i=0; i<a; i++) { if(j%2) j+3; } }
'use strict' class ProjectController { async create({ auth, request }) { const Database = use('Database') try { await auth.check() } catch (error) { response.status(401); return { ok: false, error: { msj: 'Token no proveido o invalido' } } } let error; const Project = use('App/Models/Project') const project = new Project(); const { name, description } = request.all(); const user = await auth.getUser(); project.name = name; project.description = description; project.user_id = user.id; try { await project.save(); await Database .table('user_projects') .insert({ user_id: user.id, project_id: project.id }) } catch (e) { error = e; } if (error) { response.status(401); return { ok: false, error: error.detail } } return { ok: true, data: { project } } } async getProjects({ auth, request }) { const Database = use('Database') var projects =await Database.select('*').from('projects') return { ok: true, projects } } async getAllProjects({ auth, request }) { const user = await auth.getUser(); const Project = use('App/Models/Project') const UserProject = use('App/Models/UserProject') const userProject = await UserProject.query().where('user_id', '=', user.id).fetch() return { ok: true, userProject } } async getOneProject({ auth, request, params }) { let error; try { await auth.check() } catch (error) { response.status(401); return { ok: false, error: { msj: 'Token no proveido o invalido' } } } const project_id = params.project; const Task = use('App/Models/Task') const task = await Task.query().where('project_id', '=', project_id).fetch() const Project = use('App/Models/Project') let project = await Project.findBy('id', project_id); return { ok: true, project, task } } async addUser({ auth, request, response}) { const Database = use('Database') let error; try { await auth.check() } catch (error) { response.status(401); return { ok: false, error: { msj: 'Token no proveido o invalido' } } } const { project_id } = request.all(); const user = await auth.getUser(); try { await Database .table('user_projects') .insert({ user_id: user.id, project_id }) } catch (e) { error = e; } if (error) { response.status(401); return { ok: false, error: error.detail } } return { ok: true, } } async removeUser({ auth, response, params }) { let error; try { await auth.check() } catch (error) { response.status(401); return { ok: false, error: { msj: 'Token no proveido o invalido' } } } const Database = use('Database') const project_id = params.id; const user = await auth.getUser(); try { await Database .table('user_projects') .where({ user_id: user.id, project_id }).delete(); } catch (e) { error = e; } if (error) { response.status(401); return { ok: false, error: error.detail } } return { ok: true, } } } module.exports = ProjectController
/*jslint node: true */ 'use strict'; var logger = require('../utils/logger'); var constants = require('../lib/constants'); // for the required JSON parsing error message var async = require('async'); // enables faster responses for large payloads var request = require('./request.js'); var plt = require('pagelt'); var pageLoadTimer = (function () { return { /** * Returns the loading times for the given URLs * @param req * @param callback */ get: function (req, callback) { var pageLoadTimes = []; function measureSinglePageLoad(targetURL, done) { logger.info('Timing Pageload ' + targetURL); plt(targetURL, function (err, latency) { if (err) { if (err.message.indexOf('ENOTFOUND') !== -1) { done(constants.notFoundErrorMsg + targetURL, null); } else { done(err.message, null); } } else { pageLoadTimes.push({url: targetURL, latency_ms: latency.ms}); done(); } }); } if (request.isValid(JSON.stringify(req))) { // Loop through all URLs async.forEach(req.payload, measureSinglePageLoad, function (err) { if (err) { logger.error('Exception (pageLoadTimer.get): ', err); callback(err, null); } else { callback(null, pageLoadTimes); // success } }); } else { callback(constants.parseErrorMsg, null); // the required error message } } }; }()); exports = module.exports = pageLoadTimer;
define(['jquery'], function ($) { 'use strict'; /** * jQuery extensions */ var $win = $(window); $.fn.place_tt = (function () { var defaults = { offset: 5, css: { position : 'absolute', top : -1000, left : 0, color : "#c8c8c8", padding : '10px', 'font-size': '11pt', 'font-weight' : 200, 'background-color': '#1f1f1f', 'border-radius': '5px', 'z-index': 9999 } }; return function (x, y, opts) { opts = $.extend(true, {}, defaults, opts); return this.each(function () { var $tooltip = $(this), width, height; $tooltip.css(opts.css); if (!$.contains(document.body, $tooltip[0])) { $tooltip.appendTo(document.body); } width = $tooltip.outerWidth(true); height = $tooltip.outerHeight(true); $tooltip.css('left', x + opts.offset + width > $win.width() ? x - opts.offset - width : x + opts.offset); $tooltip.css('top', y + opts.offset + height > $win.height() ? y - opts.offset - height : y + opts.offset); }); }; })(); return $; });
const config = require('../config.json') const commands = require('../util/commandList.json') module.exports = function (bot, message, command) { let msg = 'Available commands are: \n\n' for (var cmd in commands) { if (commands[cmd].description) msg += `\`${config.botSettings.prefix}${cmd}\`\n${commands[cmd].description}\n\n` } message.channel.send(msg + 'Support can be found at https://discord.gg/WPWRyxK') .catch(err => console.log(`Commands Warning: (${message.guild.id}, ${message.guild.name}) => Could not send help menu. (${err})`)) }
const { assert } = require("chai"); const { expectRevert } = require('@openzeppelin/test-helpers'); const ERC5496Demo = artifacts.require("ERC5496Demo"); contract("ERC5496", async accounts => { const Alice = accounts[0]; const Bob = accounts[1]; const Tom = accounts[2]; let demoContract; before(async function() { const instance = await ERC5496Demo.deployed("ERC5496Demo", "EPD"); demoContract = instance; await demoContract.mint(1, Alice); await demoContract.mint(2, Alice); await demoContract.mint(3, Alice); await demoContract.increasePrivileges(false); await demoContract.increasePrivileges(false); }) it("Should set privilege 0 to Bob", async () => { let expires = Math.floor(new Date().getTime()/1000) + 5000; await demoContract.setPrivilege(1, 0, Bob, BigInt(expires)); let user_hasP0 = await demoContract.hasPrivilege(1, 0, Bob); assert.equal( user_hasP0, true, "Privilege 0 of NFT 1 should be Bob" ); }); it("Privilege should belong to the owner by default", async () => { let owner_1 = await demoContract.ownerOf(1); assert.equal( owner_1, Alice , "Owner of NFT 1 should be Alice" ); let user_hasP1 = await demoContract.hasPrivilege(1, 1, Alice); assert.equal( user_hasP1, true, "Privilege 1 of NFT 1 should be Alice" ); }); it("The privilege holder is allowed to transfer the privilege to others", async () => { let expires = Math.floor(new Date().getTime()/1000) + 5000; await demoContract.setPrivilege(2, 0, Bob, BigInt(expires)); let user_hasP0 = await demoContract.hasPrivilege(2, 0, Bob); assert.equal( user_hasP0, true, "Privilege 0 of NFT 2 should be Bob" ); await demoContract.setPrivilege(2, 0, Tom, BigInt(expires + 100), { from: Bob }) user_hasP0 = await demoContract.hasPrivilege(2, 0, Tom); assert.equal( user_hasP0, true, "Privilege 0 of NFT 2 should be Tom" ); let privilege_info = await demoContract.getPrivilegeInfo(2, 0); assert.equal( privilege_info.expiresAt, expires, "Only owner can set the expiresAt" ) }); it("User is allowed to transfer NFT while privileges on renting", async () => { await demoContract.transferFrom(Alice, Bob, 1); let owner_1 = await demoContract.ownerOf(1); assert.equal( owner_1, Bob, "Owner of NFT 1 should be Bob" ); let expires = Math.floor(new Date().getTime()/1000) + 1000; await demoContract.setPrivilege(1, 1, Tom, BigInt(expires), { from: Bob }); let user_hasP1 = await demoContract.hasPrivilege(1, 1, Tom); assert.equal( user_hasP1, true, "Bob should be allowed to set the unassigned privilege to Tom" ); }); it("NFT owner may change the privileges total for each tokenId", async () => { await demoContract.increasePrivileges(false); let owner_1 = await demoContract.ownerOf(1); let user_hasP2 = await demoContract.hasPrivilege(1, 2, owner_1); assert.equal( user_hasP2, true, "privilege 2 available after NFT owner update the privilege total" ); }); it("NFT owner should not change the privilege if it has been assigned", async () => { let expires = Math.floor(new Date().getTime()/1000) + 5000; await demoContract.setPrivilege(3, 0, Bob, BigInt(expires)); await expectRevert( demoContract.setPrivilege(3, 0, Tom, BigInt(expires)), "ERC721: transfer caller is not owner nor approved", ); }); it("NFT should support interface IERC5496", async () => { const interfaceIds = { IERC165: "0x01ffc9a7", IERC721: "0x80ac58cd", IERC5496: "0x076e1bbb", } for(let interfaceName in interfaceIds) { let isSupport = await demoContract.supportsInterface(interfaceIds[interfaceName]); assert.equal(isSupport, true, "NFT should support interface "+interfaceName); } }) });
// 15. Функцийн Statement болон Expression бичиглэл /* javascript хэлийг гайхалтай болгосон төрлүүд: 1. first class function хэл. 2. Prototype удамшилийг хэрэгжүүлдэг хэл. Энэ нь self хэлнээс гаралтай. Удамшилийг 2 янзаар хэрэгжүүлдэг. 1. Сонгодог удамшилыг хэрэгжүүлдэг жн: java class зарлах байдлаар 2. Prototype удамшилыг хэрэгжүүлдэг жн: javascript 3. javascript хэл бол indetater хэл дээрээсээ доошоо ажиллаж байдаг. Prototype үндэслэсэн удамшил нь тухайн объектыг газар дээр нь өөрчлөх боломжтой. Prototype шууд өөрчилж функцыг залгаснаар ирээдүйд бусад объектуудаа бол нөлөө үзүүлдэгүй гэж Тэгвэл expression бичиглэлийн хэлбэр тэр объектыг өөрчлөх боломжийг олгодог.*/ /* Expression бичиглэлийн хэлбэр: Хувьсагч байдлаар зарладаг. Энэ бичиглэл javascript-ыг маш алдартай болгосон. Ягаад вэ гэвэл функц кодтойгоо өгөгдөл шиг дамжигдаж явах боломжийг javascript хэлэнд энэ бичиглэл олгодог. obj дотор өөр функцууд байсан боловч нэмээд newFunc функцтай болгож чаддаг гэсэн үг. Өөрөөр хэл газар дээр объектыг өргөтгөх боломжийг function expression олгодог. obj.newFunc = function (number) { console.log("Expression function Ажиллааа...." + number); };*/ // Expression бичиглэлийн хэлбэр var module = function (number) { console.log("Expression function Ажиллааа...." + number); }; module(-1000); // Дээрээс дуудаж ажилуулж болохгүй Доороос нь болно. // statement бичиглэлийн хэлбэр: function mod(number) { console.log("statement function Ажиллааа...." + number); } mod(1000); // Дээрээс доороосдуудаж ажилуулж болохгүй // Тооны модуль хэлдэг функц // |-15| = 15, |23| = 23 // ---------------Модул олох: 1 -------------- var module = function (number) { var mod; if (number < 0) mod = -number; else mod = number; console.log(number + "тооны модул нь " + mod); }; module(-115); //Тооны модулыг бусад операторууддаа дамжуулдаг өөр тооцоололд оролцоход нь тусалдаг байвал яах вэ. энэ тохиолдолд функцаас оператораас функцаас утга буцаах буюу return гэдэг түлхүүр үгийг ажиллаж үзий. Ямарч программын хэлэнд операторууд нь функцууд нь зарим утга буцаадаг зарим нь утга буцаааггүй. // return - Заримдаа утга дамжуулна гэж хэлж болонлдоо // ---------------Модул олох: 2 -------------- var module = function (too) { var mod; if (too < 0) mod = -too; else mod = too; return mod; // mod буцааж байна. }; var x = module(-155); // module аас буцаж ирсэн утгыг x хадгалчихна. module(-115); console.log(-155 + "тооны модул нь " + x); // буцаж ирсэн утгыг хадгалж аваад хэвлэж байна. // ---------------Модул олох: 3 -------------- var module = function (too) { var mod; if (too < 0) mod = -too; else mod = too; return mod; }; var x = module(-155); module(-115); console.log(module(-25) + module(12) + module(-100)); // --------- |3| + |-15| + |-55| module ол------------ // Гурван тооны нийлбэр олдог функц var moduleFind = function (too) { var mod; if (too < 0) mod = -too; else mod = too; return mod; }; var addModules = function (x, y, z) { var niilber = moduleFind(x) + moduleFind(y) + moduleFind(z); return niilber; }; var sum = addModules(-1, -2, -3); console.log(sum);
// pages/myInf/myInf.js //获取应用实例 const app = getApp() Page({ /** * 页面的初始数据 */ data: { userInfo:{}, userListInfo: [ { icon: '../../icons/public.png', text: '我的信息', url: '../identityInfo/identityInfo' }, { icon: '../../icons/public.png', text: '我发布的任务', url: '../pTaskInfo/pTaskInfo' }, { icon: '../../icons/public.png', text: '我接受的任务', url: '../cTaskInfo/cTaskInfo' }, { icon: '../../icons/public.png', text: '投诉热线', url: '../kefu/kefu' }] }, //事件处理函数 bindViewTap: function() { wx.navigateTo({ url: '../identityInfo/identityInfo' }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { let that = this that.setData({ userInfo: app.globalData.userInfo }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
import React from 'react' import { withRouter } from 'react-router-dom' const CreatePet = () => { return ( <div>Cadastrar pet</div> ) } export default withRouter(CreatePet)