text
stringlengths
7
3.69M
var agent = require("superagent").agent(); var assert = require("chai").assert; var app = require('../app'); var port = Math.floor(1000 + 10000*Math.random()); var HOST = "http://localhost:" + port; if (typeof(suite) === "undefined") suite = describe; if (typeof(test) === "undefined") test = it; suite('Integration Tests', function() { test('startServer', function(done) { app.startServer(port, function(error) { throw error; }, done); }); test('isServerUp', function(done) { agent.get(HOST + "/") .end(function(err, res) { assert.equal(res.statusCode, 200); done(); }); }); test('testSignup', function(done) { agent .post(HOST + "/user/signup/testuser") .send({ password: "ssnoc", createdAt: "2015-11-04T02:15:34.515Z" }) .end(function(err, res) { assert.equal(res.statusCode, 201); done(); }); }); test('signupFailsWithSameUsername', function(done) { agent .post(HOST + "/user/signup/testuser") .send({ password: "testpassword", createdAt: "2015-11-04T02:15:34.515Z" }) .end(function(err, res) { assert.equal(res.statusCode, 401); done(); }); }); test('testLogout1', function(done) { var redirects = []; agent .post(HOST + "/user/logout") .send({ logoutTime: "2015-11-05T03:15:34.515Z" }) .on('redirect', function(res){ redirects.push(res.headers.location); }) .end(function(err, res) { assert.equal(redirects[0], "/"); done(); }); }); test('testUpdateUserWithoutLogin', function(done) { agent .put(HOST + "/user/testuser") .send({ firstname: "Ming-Yuan", lastname: "Jian", updatedAt: "2015-11-05T02:15:34.515Z" }) .end(function(err, res) { assert.equal(res.statusCode, 403); done(); }); }); test('testLogin', function(done) { agent .post(HOST + "/user/login/testuser") .send({ password: "ssnoc", lastLoginAt: "2015-11-05T02:15:34.515Z" }) .end(function(err, res) { assert.equal(res.statusCode, 200); done(); }); }); test('testUpdateUser', function(done) { agent .put(HOST + "/user/testuser") .send({ firstname: "Ming-Yuan", lastname: "Jian", location: "CMU-SV B23", coordinate: "37.412353, -122.058460", updatedAt: "2015-11-05T02:15:34.515Z" }) .end(function(err, res) { assert.equal(res.statusCode, 200); done(); }); }); test('testGetUsers', function(done) { agent .get(HOST + "/users") .end(function(err, res) { assert.equal(res.statusCode, 200); assert.equal(res.body[0].username, "SSNAdmin"); done(); }); }); test('testLogout2', function(done) { var redirects = []; agent .post(HOST + "/user/logout") .send({ logoutTime: "2015-11-05T03:15:34.515Z" }) .on('redirect', function(res){ redirects.push(res.headers.location); }) .end(function(err, res) { assert.equal(redirects[0], "/"); done(); }); }); test('testDeleteUser', function(done) { agent .del(HOST + "/user/testuser") .end(function(err, res) { assert.equal(res.statusCode, 200); done(); }); }); /*test('testShareStatus', function(done) { agent .post(HOST + "/status/testuser") .send({ updatedAt: "2015-11-05T02:15:34.515Z", statusType: "OK" }) .expect("Content-type", /json/) .end(function(err, res) { res.status.should.equal(200); res.body.desc.should.equal("add status successfully."); done(); }); }); test('testGetAllSharedStatus', function(done) { agent .get(HOST + "/status/all/testuser") .expect("Content-type", /json/) .end(function(err, res) { res.status.should.equal(200); res.body.length.should.aboveOrEqual(1); done(); }); }); test('testGetAnnouncements', function(done) { agent .get(HOST + "/announcements") .expect("Content-type", /json/) .end(function(err, res) { res.status.should.equal(200); res.body.length.should.aboveOrEqual(0); done(); }); }); test('testPostPublicMessage', function(done) { agent .post(HOST + "/messages/wall") .expect("Content-type", /json/) .send({ content: "HELLO", messageType: "Public", postedAt: "2015-11-07T02:15:34.515Z" }) .end(function(err, res) { res.status.should.equal(201); done(); }); }); test('testGetPublicMessages', function(done) { agent .get(HOST + "/messages/wall") .expect("Content-type", /json/) .end(function(err, res) { res.status.should.equal(200); res.body.length.should.aboveOrEqual(1); done(); }); }); test('testSearchUsers', function(done) { agent .get(HOST + "/search/users?username=t") .expect("Content-type", /json/) .end(function(err, res) { res.status.should.equal(200); res.body[0].username.should.equal("testuser"); done(); }); }); var base64Image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADIAQMAAACXljzdAAAABlBMVEX///8JHfL2zBfdAAABL0lEQVRYw+2XMQ6DMAxFP2LIyBE4Sm4W6M04So6QMQOK+50UWrWdG1fiSyDBW4xjfxvg0qXfSlTbKAIX4fShmCE7r2kDvL4gBIIdMsk+tailuLhItEZ4H/JslWzMaLBG6mmPsqGSjzroSVqXaNQuhi/905M0jQmlhvyhnkQS2CLMqOR5BZZsiNSQPTM6iNzyzIyudkhzl+TrsSssdgj8Dk8OMOQ45LNL+hO6y1gbhWR1ms5/IFqdSa2n8Hu0TOfVDklofl1nicizDgwQGiI87/WFjrpghyS1bEbNAl1EXpyxPzmdsXVOsETanBM59oP8NoN7krYfsI9RzznAEjn20UNnRu0QrcRB/frsYCsEjx8MGvPbptqVtNPmqNN/DF347JBnl+g++jqD+5NLl/rrDicsvrgw3HVeAAAAAElFTkSuQmCC"; test('testPictureUpload', function(done) { server .post("/user/picture/testuser") .send({ image: base64Image }) .expect("Content-type", /json/) .end(function(err, res) { res.status.should.equal(200); done(); }); }); test('getUploadedPicture', function(done) { server .get("/user/picture/testuser") .send() .expect("Content-type", /html/) .end(function(err, res) { res.status.should.equal(200); done(); }); }); test('testLogout', function(done) { server .post("/user/logout") .send({ logoutTime: "2015-11-05T03:15:34.515Z" }) .expect("Content-type", /json/) .end(function(err, res) { res.status.should.equal(302); done(); }); });*/ });
import React from "react"; import Number from "./Number"; import {NumbersPadUI} from "../../consts/NumbersPadUI"; import {ButtonsUIConst} from "../../consts/ButtonsUIConst" function Numbers({addNumber}) { return( <div className="numbers_pad"> {NumbersPadUI.map((element)=> (<Number clickHandler={addNumber} key={element} num={ButtonsUIConst[element]}/>) )} </div> ) } export default Numbers
import Resource from 'ember-api-store/models/resource'; import { denormalizeId} from 'ember-api-store/utils/denormalize'; var Backup = Resource.extend({ type: 'backup', volume: denormalizeId('volumeId'), actions: { restoreFromBackup() { this.get('volume').doAction('restorefrombackup', { backupId: this.get('id'), }); }, }, availableActions: function() { let a = this.get('actionLinks'); var volA = this.get('volume.actionLinks'); let created = this.get('state') === 'created'; return [ { label: 'action.remove', icon: 'icon icon-trash', action: 'promptDelete', enabled: !!a.remove, altAction: 'delete' }, { label: 'action.restoreFromBackup', icon: 'icon icon-history', action: 'restoreFromBackup', enabled: created && volA && !!volA.restorefrombackup }, { divider: true }, { label: 'action.viewInApi', icon: 'icon icon-external-link',action: 'goToApi', enabled: true }, ]; }.property('actionLinks.remove','volume.actionLinks.restorefrombackup','state','volume.state'), }); export default Backup;
///<reference types = "cypress"/> import * as objViagem from "../payload/cadastroViagem.js" //const objViagem = require("../payload/cadastroViagem.js") -- usado qnd obj eh um .json let obj = objViagem.obj() //console.log(obj) function cadastrarViagem(tokenAdmin) { return cy.request({ url: '/v1/viagens', method: 'POST', headers: { Authorization: `Bearer ${tokenAdmin}`, /***/ "Content-type": "application/json" }, body: obj }) } export { cadastrarViagem } export { obj };
module.exports = { Box: { clientID: 'Your Box Client Id', clientSecret: 'Your Box Client Secret', publicKeyId: 'Your Box Public Key Id', privateKeyPath: './private_key.pem', privateKeyPassphrase: 'Your Private Key Passphrase', enterpriseId: 'Your Box Enterprise Id', photosFolder: 'The folder ID of your photos folder', metadataTemplate: { templateName: 'Your Metadata Template Name', tagsAttrName: 'Your metadata tags attribute name', recognitionVersionAttrName: 'Your metadata image rec version attribute name' } }, Clarifai: { clientID: 'Your Clarifai Client Id', clientSecret: 'Your Clarifai Client Secret' } };
App.GameLoop = (function(app){ var clock = new THREE.Clock(); function animate(){ requestAnimationFrame( animate ); app.Engine.render(); update(); } function update() { var delta = clock.getDelta(); app.Engine.editMode(); App.Player.Mesh.move(delta); app.Engine.controls.update(); app.Engine.stats.update(); } animate(); return { }; })(App);
import React from "react"; import styled from "styled-components"; import PropTypes from "prop-types"; import MakeHoverUserInfo from "../middleComponents/MakeHoverUserInfo"; import { userType } from "../propTypes"; const StyledImg = styled.img` border-radius: 50%; width: ${props => { if (props.xsmall) return "24px"; if (props.small) return "28px"; if (props.middle) return "33px"; if (props.large) return "95px"; return "46px"; }}; height: ${props => { if (props.xsmall) return "24px"; if (props.small) return "28px"; if (props.middle) return "33px"; if (props.large) return "95px"; return "46px"; }}; `; export default function Avatar({ onClick, xsmall, small, middle, large, user, hoverable }) { const Content = () => ( <StyledImg src={user && user.avatarSrc} alt={user && user.nickName} onClick={onClick} xsmall={xsmall} small={small} middle={middle} large={large} /> ); return hoverable ? ( <MakeHoverUserInfo user={user}> <Content /> </MakeHoverUserInfo> ) : ( <Content /> ); } Avatar.propTypes = { user: userType, hoverable: PropTypes.bool, onClick: PropTypes.func, xsmall: PropTypes.bool, small: PropTypes.bool, middle: PropTypes.bool, large: PropTypes.bool }; Avatar.defaultProps = { user: null, hoverable: false, onClick: null, xsmall: false, small: false, middle: false, large: false };
module.exports = function (sequelize, DataTypes) { var m = sequelize.define('department_user_access', { id: { type: DataTypes.INTEGER(11), allowNull: false, primaryKey: true, autoIncrement: true }, departmentId: { type: DataTypes.INTEGER(11), allowNull: false, references: { model: 'department', key: 'id' } }, userId: { type: DataTypes.INTEGER(11), allowNull: false, references: { model: 'user', key: 'id' } } }, { tableName: 'department_user_access', timestamps: false, }); m.associate = function(models) { m.belongsTo(models.department, {foreignKey: 'departmentId'}); m.belongsTo(models.user, {foreignKey: 'userId'}); } return m; };
import './page.styl'; import ProductListItem from "../../components/ProductListItem"; import Slider from "../../components/Slider"; const initProduct = () => { const listItems = document.querySelectorAll('.product-item'); listItems.forEach(item => { new ProductListItem(item); }); }; const initSlider = () => { const slider = document.querySelector('.slider'); new Slider(slider); }; document.addEventListener('DOMContentLoaded', () => { initProduct(); initSlider(); });
'use strict'; module.exports = function (Ctrl, userRoles, generateAccessFilter) { return [ { checkAuthorizationToken : false, accessControl : 'public', routes : [ { verb : 'get', url : '/roles', func : Ctrl.getRoles }, { verb : 'post', url : '/signin', func : Ctrl.signin } ] }, { checkAuthorizationToken : true, accessControl : generateAccessFilter([ userRoles.user ]), routes : [ // { verb : 'get', url : '/signout', func : Ctrl.signout }, { verb : 'get', url : '/whoami', func : Ctrl.whoami } ] }, { checkAuthorizationToken : true, accessControl : generateAccessFilter([ userRoles.admin ]), routes : [ { verb : 'get', url : '/', func : Ctrl.getAll }, { verb : 'get', url : '/count', func : Ctrl.count }, { verb : 'get', url : '/:nbPerPage/:currentPage', func : Ctrl.getPage }, { verb : 'get', url : '/:id', func : Ctrl.getById }, { verb : 'post', url : '/', func : Ctrl.create }, { verb : 'put', url : '/:id', func : Ctrl.update }, { verb : 'delete', url : '/:id', func : Ctrl.delete } ] } ]; };
var navtreeindex2____8js__8js_8js = [ [ "navtreeindex2__8js_8js", "navtreeindex2____8js__8js_8js.html#a8faf7fdd50ae861ef7ae26079bdc0972", null ] ];
import Ember from 'ember'; import Sortable from 'ui/mixins/sortable'; import C from 'ui/utils/constants'; import { tagsToArray } from 'ui/models/stack'; export default Ember.Controller.extend(Sortable, { stacksController: Ember.inject.controller('stacks'), projects: Ember.inject.service(), prefs: Ember.inject.service(), intl: Ember.inject.service(), infraTemplates: Ember.computed.alias('stacksController.infraTemplates'), which: Ember.computed.alias('stacksController.which'), tags: Ember.computed.alias('stacksController.tags'), showAddtlInfo: false, selectedService: null, actions: { showAddtlInfo(service) { this.set('selectedService', service); this.set('showAddtlInfo', true); }, dismiss() { this.set('showAddtlInfo', false); this.set('selectedService', null); }, sortResults(name) { this.get('prefs').set(C.PREFS.SORT_STACKS_BY, name); this.send('setSort', name); }, }, filteredStacks: function() { var which = this.get('which'); var needTags = tagsToArray(this.get('tags')); var out = this.get('model.stacks'); if ( which === C.EXTERNAL_ID.KIND_NOT_ORCHESTRATION ) { out = out.filter(function(obj) { return C.EXTERNAL_ID.KIND_ORCHESTRATION.indexOf(obj.get('grouping')) === -1; }); } else if ( which !== C.EXTERNAL_ID.KIND_ALL ) { out = out.filterBy('grouping', which); } if ( needTags.length ) { out = out.filter((obj) => obj.hasTags(needTags)); } out = out.filter((obj) => obj.get('type').toLowerCase() !== 'kubernetesstack'); return out; // state isn't really a dependency here, but sortable won't recompute when it changes otherwise }.property('model.stacks.[]','model.stacks.@each.{state,grouping}','which','tags'), sortableContent: Ember.computed.alias('filteredStacks'), sortBy: 'name', sorts: { state: ['stateSort','name','id'], name: ['name','id'] }, pageHeader: function() { let which = this.get('which'); let tags = this.get('tags'); if ( tags && tags.length ) { return 'stacksPage.header.tags'; } else if ( which === C.EXTERNAL_ID.KIND_ALL ) { return 'stacksPage.header.all'; } else if ( C.EXTERNAL_ID.SHOW_AS_SYSTEM.indexOf(which) >= 0 ) { return 'stacksPage.header.infra'; } else if ( which.toLowerCase() === 'user') { return 'stacksPage.header.user'; } else { return 'stacksPage.header.custom'; } }.property('which','tags'), });
import { createStore, combineReducers, applyMiddleware } from 'redux'; import thunkMiddleware from "redux-thunk"; import { createLogger } from 'redux-logger'; import { reducer as formReducer } from 'redux-form'; import auth from './Reducers/auth/reducer'; const loggerMiddleware = createLogger(); const RootReducer = combineReducers({ auth, formReducer }) const AppStore = createStore( RootReducer, applyMiddleware( thunkMiddleware, loggerMiddleware ) ); export default AppStore;
import React from "react"; import {Card, Carousel} from "antd"; const FadeIn = () => { return ( <Card className="gx-card" title="Fade In"> <Carousel effect="fade"> <div><h3>1</h3></div> <div><h3>2</h3></div> <div><h3>3</h3></div> <div><h3>4</h3></div> </Carousel> </Card> ); }; export default FadeIn;
//import liraries import React, { Component } from 'react'; import { View, Text, StyleSheet } from 'react-native'; import Logo from './Logo' import EmailAndPassword from './Email&PasswordScreen'; // create a component const LoginScreen = () => { return ( <View style={styles.container}> <View style={styles.logocontainer}> <Logo /> </View> <View style={styles.emailAndPassword}> <EmailAndPassword /> </View> </View> ); }; // define your styles const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', }, logocontainer:{ flex:1, justifyContent:'center', alignContent:'center' }, emailAndPassword:{ flex:2 } }); //make this component available to the app export default LoginScreen;
const crypto = require('crypto'); const {device} = require("./../db/models/device"); module.exports = { authenticate: (retrievedSignature, ownSignature, data) => { const computedSignature = crypto.createHmac("sha256", Buffer.from(ownSignature, 'hex')) .update(Buffer.from("data", 'utf-8')) .digest("hex"); return computedSignature === retrievedSignature; }, };
import {createStore, applyMiddleware} from 'redux' import thunk from 'redux-thunk' import nock from 'nock' import {fetchPlot} from "../../actions"; import {apiUrl, pathFetchPlot} from "../../api"; import plotReducer from "../../reducers/plot"; const middlewares = [thunk]; let store; beforeEach(() => { store = createStore(plotReducer, applyMiddleware(thunk)) }); test('initial state has to have the plot data object as an empty string', () => { const plotState = {image: '', updateNeeded: false}; expect(store.getState()).toEqual(plotState); }); test('fetchPlot action should populate the plot string', () => { const rand = 0; const plotResponse = {plot: 'plotdata'}; const plotState = {image: 'plotdata', updateNeeded: false}; const params = {weights:[], biases:[]}; const data = []; nock(`${apiUrl}`) .post(`${pathFetchPlot}`, {params: params, data: data}) .reply(200, plotResponse); expect.assertions(1); const action = fetchPlot(params, data); return store.dispatch(action) .then(() => { expect(store.getState()).toEqual(plotState); }); });
import * as actionTypes from '../actionTypes'; const INITIAL_STATE = { cart: [], checkout: { transaction_code: '', id_address: '', seller_id: '', item: [], }, }; const cartReducer = (state = INITIAL_STATE, action) => { let newCart = [...state.cart]; switch (action.type) { case actionTypes.ADD_TO_CART: // return { // ...state, // cart: [...state.cart, action.payload], // }; // console.log('ANJING', action.payload); const item = action.payload; const inCart = state.cart.find((item) => item.id === action.payload.id ? true : false, ); return { ...state, cart: inCart ? state.cart.map((item) => item.id === action.payload.id ? {...item, qty: item.qty + 1} : item, ) : [...state.cart, {...item, qty: 1}], }; case actionTypes.DELETE_FROM_CART: return { ...state, cart: state.cart.filter((item) => item.id !== action.payload.id), }; case actionTypes.QUANTITY_INCREASED: const indexQtyInc = state.cart.findIndex((item) => { return action.payload.id === item.id; }); newCart[indexQtyInc] = { ...newCart[indexQtyInc], qty: state.cart[indexQtyInc].qty + 1, }; return { ...state, cart: newCart, }; case actionTypes.QUANTITY_DECREASED: const indexQtyDec = state.cart.findIndex((item) => { return action.payload.id === item.id; }); newCart[indexQtyDec] = { ...newCart[indexQtyDec], qty: state.cart[indexQtyDec].qty - 1, }; if (newCart[indexQtyDec].qty === 0) { state.cart.splice(indexQtyDec, 1); return { ...state, cart: state.cart, }; } else { return { ...state, cart: newCart, }; } case actionTypes.ADD_TO_CHECKOUT: return { ...state, checkout: { ...state.checkout, transaction_code: action.payload.transaction_code, id_address: action.payload.id_address, seller_id: action.payload.seller_id, item: action.payload.item, }, }; case actionTypes.PICK_CART: return { ...state, cart: state.cart.map((item) => item.id === action.payload.id ? {...item, pick: !item.pick} : item, ), }; case actionTypes.CLEAR_CART: return { ...state, cart: state.cart.filter((item) => { item.pick === true; }), }; case actionTypes.CLEAR_CHECKOUT: return { ...state, checkout: { transaction_code: '', id_address: '', seller_id: '', item: [], }, }; default: return state; } }; export default cartReducer;
// variables to store information for the game var computerChoices = ["s", "n", "a", "p", "e"]; var userGuess = ""; var numGuesses = 9; var lettersGuessed = []; var wins = 0; var losses = 0; // variable to determine computer choice from provided array var computerGuess = computerChoices[Math.floor(Math.random() * computerChoices.length)]; // update guesses left function countNumGuesses() { document.querySelector("#number-text").innerHTML = numGuesses; } // countNumGuesses(); // resets the game function resetGame() { numGuesses = 9; lettersGuessed = []; // Randomly picks letter for computer computerGuess = computerChoices[Math.floor(Math.random() * computerChoices.length)]; } // This function runs whenever the user presses document.onkeyup = function (event) { // Makes the user guess is lower case var userGuess = event.key.toLowerCase(); //This logic determines the outcome of the game if (userGuess !== computerGuess) { numGuesses--; lettersGuessed.push(userGuess); document.querySelector("#number-text").innerHTML = numGuesses; } if (userGuess === computerGuess) { wins++; numGuesses = 9 document.querySelector("#wins-text").innerHTML = wins; resetGame() } if (numGuesses === 0) { losses++; lettersGuessed = []; numGuesses = 9; document.querySelector("#losses-text").innerHTML = losses; resetGame(); } // calls on HTML id's to update game document.getElementById("number-text").textContent = "Guesses Left:" + numGuesses; document.getElementById("letters-text").textContent = "Letters you have Guessed:" + lettersGuessed; document.getElementById("wins-text").textContent = "Wins: " + wins; document.getElementById("losses-text").textContent = "Losses: " + losses; };
import React, {useState, useEffect} from 'react'; // import {Link} from 'react-router-dom'; import {connect} from 'react-redux'; import {getCategory} from '../redux/reducer'; import {getTransactions} from '../redux/reducer'; import Categories from './Categories'; import axios from 'axios'; const Budget = (props) => { const[showMore, toggleShowMore] = useState(false); const [catPenny, setCatPenny] = useState(false); const [edit, toggleEdit] = useState(true); // const [allocated, filterAllocated] = useState(true); // const [category, filterCategory] = useState(true); // const [balance, filterBalance] = useState(true); // let today = new Date(); // let month = (today.getMonth()+1); // let day = (today.getDate()); // console.log(today); // console.log(month); // console.log(day); useEffect(() => { getCategory(); getTransactions()}, []) const getCategory = () => { axios .get('/api/category') .then((res) => { props.getCategory(res.data) }) .catch(() => console.log('did not get categories')) } const getTransactions = () => { axios .get('/api/transaction') .then((res) => { props.getTransactions(res.data) }) } const remove = id => { axios .delete(`/api/category/${id}`) .then(() => { getCategory() }) .catch(() => console.log('cannot delete')) } let total = props.category && props.category.map(element => element.category_balance ) .reduce((acc, curr)=> acc+curr, 0); let dollarBalance = props.category && props.category.filter(element => element.category_type === "$") .map(element => element.category_balance) .reduce((acc, curr)=> acc+curr, 0); let percentageBalance = props.category && props.category.filter(element => element.category_type === "%") .map(element => element.category_balance ) .reduce((acc, curr)=> acc+curr, 0); let percentageTotal = props.category && props.category .filter(element => element.category_type === '%') .map(element => element.category_allocated) .reduce((acc, curr) => acc + curr, 0); let dollarTotal = props.category && props.category .filter(element => element.category_type === '$') .map(element => element.category_allocated) .reduce((acc, curr) => acc + curr, 0); return( <div className='main'> <div className='totals' onClick={()=>toggleShowMore(showMore ? false : true)}> <div className='total-cat'> <span>${showMore ? dollarBalance.toFixed(2) : Math.trunc(dollarBalance)}</span> <div className='line'/> <span>${showMore ? dollarTotal.toFixed(2) : Math.trunc(dollarTotal)}</span> </div> <div className='circle'>${showMore ? total.toFixed(2) : Math.trunc(total)}</div> <div className='total-cat'> <span>${showMore ? percentageBalance.toFixed(2) : Math.trunc(percentageBalance)}</span> <div className='line'/> <span>%{percentageTotal}</span> </div> </div> <div className='header'>Categories</div> <div className='white-space'> <span className='column-left' >Allocated</span> <span className='column'>Name</span> <span className='column-right'>Balance</span> </div> <div className='list'> {props.category .filter(element => element.category_type === '$') .map((element, index) =>{ return( <Categories key = {index} category_id = {element.category_id} category_name = {element.category_name} category_allocated = {element.category_allocated} category_type = {element.category_type} category_balance = {element.category_balance} catPenny = {catPenny} setCatPennyFN = {setCatPenny} removeFN = {remove}/> ) })} {props.category .filter(element => element.category_type === '%') .map((element, index) =>{ return( <Categories key = {index} category_id = {element.category_id} category_name = {element.category_name} category_allocated = {element.category_allocated} category_type = {element.category_type} category_balance = {element.category_balance} catPenny = {catPenny} setCatPennyFN = {setCatPenny} removeFN = {remove}/> ) })} </div> </div> ) } const mapStateToProps = (reduxState) => { return reduxState } export default connect(mapStateToProps, {getCategory, getTransactions})(Budget);
module.exports = function (app) { function runStep() { console.log("Adding dummy persons"); app.dataSources.MongoDB.automigrate("Person", function (err) { if (err) { throw err; } app.models.Person.create([ { "firstName": "Joseph", "lastName": "K. Neumann", "departmentId": "995d9a16-377c-4df0-aad7-3e58242558f3", "title": "Direct Mobility Specialist", "phone": "202-555-0128", "email": "jkn@company.com", "id": "58d052ca972aa51354ef6ded" }, { "firstName": "Ivan", "lastName": "K. McCartney", "departmentId": "995d9a16-377c-4df0-aad7-3e58242558f3", "title": "Human Branding Producer", "phone": "202-555-0181", "email": "ikm@company.com", "id": "58d052ca972aa51354ef6dee" }, { "firstName": "Lean", "lastName": "J. Goodwin", "departmentId": "995d9a16-377c-4df0-aad7-3e58242558f3", "title": "District Interactions Analyst", "phone": "202-555-0180", "email": "ljg@company.com", "id": "58d052ca972aa51354ef6def" }, { "firstName": "David", "lastName": "V. Llanos", "departmentId": "995d9a16-377c-4df0-aad7-3e58242558f3", "title": "Customer Program Manager", "phone": "202-555-0181", "email": "dvl@company.com", "id": "58d052ca972aa51354ef6df0" }, { "firstName": "Jerry", "lastName": "E. Perreira", "departmentId": "995d9a16-377c-4df0-aad7-3e58242558f3", "title": "Chief Directives Administrator", "phone": "202-555-0126", "email": "jep@company.com", "id": "58d052ca972aa51354ef6df1" }, { "firstName": "Trisha", "lastName": "T. Nicholes", "departmentId": "995d9a16-377c-4df0-aad7-3e58242558f3", "title": "Corporate Identity Specialist", "phone": "202-555-0192", "email": "ttn@company.com", "id": "58d052ca972aa51354ef6df2" }, { "firstName": "Carol", "lastName": "T. White", "departmentId": "995d9a16-377c-4df0-aad7-3e58242558f3", "title": "Forward Group Engineer", "phone": "202-555-0177", "email": "ctw@company.com", "id": "58d052ca972aa51354ef6df3" }, { "firstName": "Doris", "lastName": "R. Nicholson", "departmentId": "995d9a16-377c-4df0-aad7-3e58242558f3", "title": "Product Solutions Associate", "phone": "202-555-0156", "email": "drn@company.com", "id": "58d052ca972aa51354ef6df4" }, { "firstName": "Marie", "lastName": "S. Ortiz", "departmentId": "995d9a16-377c-4df0-aad7-3e58242558f3", "title": "Product Quality Analyst", "phone": "202-555-0114", "email": "mso@company.com", "id": "58d052ca972aa51354ef6df5" }, { "firstName": "Allen", "lastName": "J. Wiggins", "departmentId": "995d9a16-377c-4df0-aad7-3e58242558f3", "title": "Global Data Administrator", "phone": "202-555-0108", "email": "ajw@company.com", "id": "58d052ca972aa51354ef6df6" }, { "firstName": "Nikolai", "lastName": "Kristiansen", "departmentId": "2b4594b2-9719-4e3e-aea4-1fba941e5cb7", "title": "District Applications Technician", "phone": "202-555-0142", "email": "nk@company.com", "id": "58d052ca972aa51354ef6df7" }, { "firstName": "William", "lastName": "Rognli", "departmentId": "2b4594b2-9719-4e3e-aea4-1fba941e5cb7", "title": "International Configuration Consultant", "phone": "202-555-0178", "email": "wr@company.com", "id": "58d052ca972aa51354ef6df8" }, { "firstName": "Daniel", "lastName": "Arnesen", "departmentId": "2b4594b2-9719-4e3e-aea4-1fba941e5cb7", "title": "Principal Brand Designer", "phone": "202-555-0165", "email": "da@company.com", "id": "58d052ca972aa51354ef6df9" }, { "firstName": "Tomas", "lastName": "Ekeland", "departmentId": "2b4594b2-9719-4e3e-aea4-1fba941e5cb7", "title": "Regional Branding Engineer", "phone": "202-555-0144", "email": "te@company.com", "id": "58d052ca972aa51354ef6dfa" }, { "firstName": "Adrian", "lastName": "Nordli", "departmentId": "2b4594b2-9719-4e3e-aea4-1fba941e5cb7", "title": "Customer Infrastructure Associate", "phone": "202-555-0126", "email": "an@company.com", "id": "58d052ca972aa51354ef6dfb" }, { "firstName": "David", "lastName": "R. Jensen", "departmentId": "2b4594b2-9719-4e3e-aea4-1fba941e5cb7", "title": "International Accountability Liason", "phone": "202-555-0165", "email": "drj@company.com", "id": "58d052ca972aa51354ef6dfc" }, { "firstName": "Kasper", "lastName": "L. Pedersen", "departmentId": "2b4594b2-9719-4e3e-aea4-1fba941e5cb7", "title": "Investor Branding Developer", "phone": "202-555-0126", "email": "klp@company.com", "id": "58d052ca972aa51354ef6dfd" }, { "firstName": "Mette", "lastName": "H. Jeppesen", "departmentId": "2b4594b2-9719-4e3e-aea4-1fba941e5cb7", "title": "Chief Solutions Strategist", "phone": "202-555-0190", "email": "mhj@company.com", "id": "58d052ca972aa51354ef6dfe" }, { "firstName": "Natasja", "lastName": "M. Lorenzen", "departmentId": "2b4594b2-9719-4e3e-aea4-1fba941e5cb7", "title": "Investor Mobility Administrator", "phone": "202-555-0123", "email": "nml@company.com", "id": "58d052ca972aa51354ef6dff" }, { "firstName": "Nicklas", "lastName": "M. Hermansen", "departmentId": "2b4594b2-9719-4e3e-aea4-1fba941e5cb7", "title": "Global Security Manager", "phone": "202-555-0111", "email": "nmh@company.com", "id": "58d052ca972aa51354ef6e00" }, { "firstName": "Mimir", "lastName": "S. Mathiasen", "departmentId": "2b4594b2-9719-4e3e-aea4-1fba941e5cb7", "title": "Senior Interactions Designer", "phone": "202-555-0140", "email": "msm@company.com", "id": "58d052ca972aa51354ef6e01" }], function (err, persons) { if (err) { throw err; } }); }); } app.migrationScripts.push({ stepId: 2, callback: function () { app.testMigration(2, runStep); } }); };
'use strict'; const gen = require('../util/gen'); const forEach = require('../util/for-each'); const toArray = require('../util/to-array'); const CLASS_OVERLAY = 'so-overlay'; const INPUTS_DISABLED = 'input:not([disabled]),select:not([disabled]),textarea:not([disabled]),button:not([disabled]),a:not([disabled])'; const INPUTS_ENABLED = '.modal input,.modal select,.modal textarea,.modal button,.modal a'; const CLASS_PREVENT_SCROLL = 'so-prevent-scroll'; const CLASS_WRAPPER = 'so-wrapper'; const DATA_KEY_SCROLL = 'soScrollBy'; const DATA_KEY_DISABLED = 'soInputDisabled'; const DISABLED = 'disabled'; const body = document.body; const wrapper = document.querySelector('.so-wrapper'); const state = { overlays: {}, overlay: null }; function removeNode(node) { if (node.removeNode) { node.removeNode(); } else { node.remove(); } } function disableInputs() { let include = toArray(document.querySelectorAll(INPUTS_DISABLED)); let exclude = toArray(document.querySelectorAll(INPUTS_ENABLED)); state.disabled = include.filter(el => exclude.indexOf(el) === -1).map(el => { el.dataset[DATA_KEY_DISABLED] = 'true'; return el; }); } function enableInputs() { state.disabled.forEach(el => { el.removeAttribute(DISABLED); }); } function show() { // store page scroll let top = window.scrollY || window.pageYOffset; body.dataset[DATA_KEY_SCROLL] = top; body.classList.add(CLASS_PREVENT_SCROLL); disableInputs(); // show state.overlay state.overlay = document.createElement('div'); state.overlay.classList.add(CLASS_OVERLAY); body.appendChild(state.overlay); wrapper.style.top = Math.round(-top) + 'px'; } function hide() { if (state.overlay) { // recapture page scroll let top = body.dataset[DATA_KEY_SCROLL]; delete body.dataset[DATA_KEY_SCROLL]; wrapper.style.top = ''; // re-enable page inputs enableInputs(); // release scroll last body.classList.remove(CLASS_PREVENT_SCROLL); window.scrollTo(0, top); removeNode(state.overlay); state.overlay = null; } } function addOverlay() { let id = gen.uuidV4(); if (!state.overlay) { show(); } state.overlays[id] = true; return id; } function removeOverlay(id) { delete state.overlays[id]; if (!Object.keys(state.overlays).length) { hide(); } } function removeAll() { for (let id in state.overlays) { delete state.overlays[id]; } hide(); } const api = { add: addOverlay, remove: removeOverlay, clear: removeAll }; window.overlay = api; module.exports = api;
({ doInit: function(component, event, helper) { if(component.get("v.parentfield")=='Group'){ var getTaskChptrAction = component.get("c.getNotes"); getTaskChptrAction.setParams({ "GroupId": component.get("v.GroupId") }); // Add Asynch Callback For Class Action getTaskChptrAction .setCallback( this, function(response) { var state = response.getState(); if ( state == "SUCCESS") { component.set("v.Notes",response.getReturnValue()); } else { // Replace With Error Handler f/w once available console.log("Failed with state: " + state); } }); // Enqueue Class Action $A.enqueueAction(getTaskChptrAction); } }, Strike: function(component,event,helper){ component.set("v.Rowdata1",event.getParam('data1')); // component.set("v.Rowdata1",event.getParam('data1')); var notelist; for(var i=0;i<component.get("v.MemberNoteslist").length;i=i+1){ //alert('@@@'+ component.get("v.AttachmentList")[i].MemberId); //alert('#####'+event.getParam('data1').Id); if(component.get("v.MemberNoteslist")[i].MemberId==event.getParam('data1').Id){ notelist = component.get("v.MemberNoteslist")[i].Notes; } } component.set("v.Notes",notelist); //alert('Notes'+JSON.stringify(notelist)); }, Showmodal: function(component, event, helper) { component.set("v.modalIsOpen", true) }, closeModel: function(component, event, helper) { component.set("v.modalIsOpen", false) }, setAttributeValue: function(component, event, helper) { var eventValue = event.getParam("closeMdl"); var eventValue1 = event.getParam("Notesnw"); var eventValue2 = event.getParam("Type"); component.set("v.modalIsOpen", eventValue); /* component.set("v.Notes", { Title: eventValue2, Body: eventValue1 });*/ var notelst=component.get("v.Notes"); if(notelst==undefined){ notelst=[]; } notelst.push(eventValue1); // alert(JSON.stringify(eventValue1)); component.set("v.Notes",notelst); component.set("v.NewNotes",eventValue1); var notelist=component.get("v.MemberNoteslist"); var NotesObj={ 'MemberId' : component.get("v.Rowdata1").Id, 'Notes' : notelst } notelist.push(NotesObj); component.set("v.MemberNoteslist",notelist); }, Save: function(component, event, helper) { var Value = component.get("v.Notes[0].Title"); var Value1 = component.get("v.Notes[0].Body"); console.log(Value); var action2 = component.get("c.CreateNote"); // set the parameters to method action2.setParams({ "Title": Value, "Notes": Value1, "GroupId": "0017F000008bbfDQAQ" }); console.log(JSON.stringify((action2.getParams()))); // set a call back action2.setCallback(this, function(a) { // store the response return value (wrapper class insatance) console.log(a.getReturnValue()); }); // enqueue the action $A.enqueueAction(action2); } })
import React, { useState } from "react"; import { NavLink } from "react-router-dom"; import { slide as Menu } from "react-burger-menu"; import { useAuthState } from "../../auth/auth-context"; import IconWave from "../../assets/icon-wave.svg"; import IconGlobe from "../../assets/icon-globe.svg"; import IconSat from "../../assets/icon-satellite.svg"; import IconUser from "../../assets/icon-user.svg"; import IconQuestion from "../../assets/icon-question.svg"; export default function BurgerMenu() { const [menuOpen, setMenuOpen] = useState(false); const { userAddress } = useAuthState(); const handleStateChange = state => { setMenuOpen(state.isOpen); }; const closeMenu = () => { setMenuOpen(false); }; return ( <Menu isOpen={menuOpen} onStateChange={state => handleStateChange(state)} closeMenu={closeMenu} > {userAddress === "none" ? ( <NavLink onClick={() => closeMenu()} to={"/join"} className="app__nav-link--mobile-join" > JOIN </NavLink> ) : null} {userAddress === "none" ? ( <NavLink onClick={() => closeMenu()} to={"/login"}> LOG IN </NavLink> ) : null} <br></br> <NavLink onClick={() => closeMenu()} to={"/"}> <img className="app__nav__icon" src={IconWave} alt="icon"></img> WELCOME </NavLink> <NavLink onClick={() => closeMenu()} to={"/catalog/priorities"}> <img className="app__nav__icon" src={IconSat} alt="icon"></img> CATALOG </NavLink> <div> <img className="app__nav__icon" src={IconQuestion} alt="icon"></img> <a className="app__nav-link nav-bar__link--lowlight--welcome" href="https://learn.trusat.org" target="_blank" rel="noopener noreferrer" > LEARNING HUB </a> </div> {userAddress !== "none" ? ( <NavLink onClick={() => closeMenu()} to={`/profile/${userAddress}`}> <img className="app__nav__icon" src={IconUser} alt="icon"></img> MY PROFILE </NavLink> ) : null} <div> <img className="app__nav__icon" src={IconQuestion} alt="icon"></img> <a className="app__nav-link nav-bar__link--lowlight--welcome" href="https://discuss.trusat.org" target="_blank" rel="noopener noreferrer" > FORUM </a> </div> <NavLink onClick={() => closeMenu()} to={"/about"}> <img className="app__nav__icon" src={IconGlobe} alt="icon"></img> ABOUT </NavLink> </Menu> ); }
const Router = FlowRouter; export default Router;
const express = require('express') const Task = require("../models/task.js") const auth = require('../middleware/auth') const { findOne } = require('../models/task.js') const router = new express.Router() //GET /tasks?completed=true //GET /tasks?limit=10&skip=3 //GET /tasks?sortBy=createdAt:desc router.get("/tasks", auth, async (request, response) => { try { //const task = await Task.find({owner : request.user._id}) //or //await request.user.populate('tasks').execPopulate() const match = {} const sort = {} //if(request.query.completed) match.completed = request.query.completed === 'true' ? true : false if (request.query.completed) match.completed = request.query.completed === 'true' if (request.query.sortBy) { const parts = request.query.sortBy.split(':') sort[parts[0]] = parts[1] === 'desc' ? -1 : 1 } await request.user.populate({ path: 'tasks', match, options: { limit: parseInt(request.query.limit), skip: parseInt(request.query.skip), sort } }).execPopulate() const task = request.user.tasks response.status(200).send(task) } catch (error) { response.status(400).send(error) } }) router.post("/tasks", auth, async (request, response) => { //const taskData = new Task(request.body) const taskData = new Task({ ...request.body, owner: request.user._id }) try { const task = await taskData.save() response.status(201).send(task) } catch (error) { response.status(400).send(error) } }) router.get("/tasks/:id", auth, async (request, response) => { const _id = request.params.id try { //const task = await Task.findById(_id) const task = await Task.findOne({ _id, owner: request.user._id }) if (!task) return response.status(404).send() response.status(201).send(task) } catch (error) { response.status(400).send({ error }) } }) router.patch("/tasks/:id", auth, async (request, response) => { const updates = Object.keys(request.body) const allowedUpdates = ['description', 'completed'] const isValidOperation = updates.every((update) => allowedUpdates.includes(update)) if (!isValidOperation) response.status(400).send({ error: "Invalid data" }) try { //const task = await Task.findById(_id) const task = await Task.findOne({ _id: request.params.id, owner: request.user._id }) if (!task) return response.status(404).send() updates.forEach((update) => task[update] = request.body[update]) await task.save() //const task = await Task.findByIdAndUpdate(_id, request.body, { new : true, runValidators: true}) response.status(200).send(task) } catch (error) { response.status(400).send(error) } }) router.delete("/tasks/:id", auth, async (request, response) => { const _id = request.params.id try { //const task = await Task.findByIdAndDelete(_id) const task = await Task.findOneAndDelete({ _id: request.params.id, owner: request.user._id }) if (!task) return response.status(404).send() response.status(200).send(task) } catch (error) { response.status(400).send(error) } }) module.exports = router
import calcLayout from "./calcLayout.mjs"; export default class UI { constructor(ship, /*input*/) { this.ship = ship ; this.getComponent = this.ship.getComponent.bind(this.ship); ////this.input = input ; this.uiElements = []; this.el = div("div","ui","full"); document.body.appendChild(this.el); ////{ //// let radar = new UI_MetaRadar("0",this.ship); //// this.uiElements .push( radar ); //// radar.getEl().classList.add("ui-full"); //// document.body.appendChild(radar.getEl()); //// //// ////let button = new UI_Button("1",this.ship, "Click ME!"); //// ////this.uiElements .push( button ); //// ////button.getEl().classList.add("ui-bottomLeft"); //// ////document.body.appendChild(button.getEl()); //// //// let slider = new UI_Slider("1",this.ship,0,1,0.01); //// this.uiElements .push( slider ); //// slider.getEl().classList.add("ui-bottomLeft"); //// document.body.appendChild(slider.getEl()); //// slider.addEventListener("input",(e)=>{ //// ship.setSpeed(e.target.value) //// }); ////} } init() { this.create(); } update() { for (var uiEl of this.uiElements) { uiEl.update(); } } create() { let rd = calcLayout( ` styles = \` .bl { position : fixed ; bottom : 0 ; left : 0 ; display : inline-flex ; } .bl > * + * { margin-;left : 5px ; } \`; body = [ div( "div", "full", "stacked", metaRadar(), div("div","bl", ////Div.style(\` //// top : 0 ; //// left : 0 ; //// display : flex ; //// flex-direction : row ; ////\`), slider() .attach("metaMove:0.forward") .max(0.5) .min(-0.5) .step(0.01) , slider() .attach("metaMove:0.forward") .max(1) .min(-1) .step(0.01) , div("div",button("hi!"),), ) ), ]; `, this.getComponent, "0" ) let frame = div("iframe"); this.el.appendChild(frame); setTimeout((()=>{ frame.contentDocument.head.appendChild(div("link",Div.attributes({rel:"stylesheet",type:"text/css",href:"styles/ui.css"}))); frame.contentDocument.head.appendChild(div("link",Div.attributes({rel:"stylesheet",type:"text/css",href:"styles/slider.css"}))); for (let style of rd.styles) { frame.contentDocument.head.appendChild(div("style",Div.child(style))); } for (let el of rd.domEls) { frame.contentDocument.body.appendChild(el); } this.uiElements.push(...rd.uiEls); }).bind(this),0); } }
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export default new Router({ mode: 'history', routes: [ { path: '/', component: resolve => require(['@/components/index'], resolve)//首页 }, { path: '/text/detail/:id', component: resolve => require(['@/pages/text/detail'], resolve)//文本详情页 }, { path: '/textEdit', name:"textEdit", component: resolve => require(['@/pages/text/edit'], resolve)//文本编辑页 }, { path: '/login', component: resolve => require(['@/pages/login/login'], resolve)//登录页面 }, { path: '/imgEdit', name:"imgEdit", component: resolve => require(['@/pages/imgEdit/imgEdit'], resolve)//上传图片页面 }, { path: '/all/text', component: resolve => require(['@/pages/more/text'], resolve) //全部文字笔记 }, { path: '/all/pic', component: resolve => require(['@/pages/more/pic'], resolve) //全部图文笔记 }, { path: '/user/recycle', component: resolve => require(['@/pages/user/recycle'], resolve) //回收站 }, {//推荐 path: '/Tj/pic', component: resolve => require(['@/pages/Tj/pic'], resolve) //推荐 图片 }, {//推荐 path: '/Tj/text', name:"text", component: resolve => require(['@/pages/Tj/text'], resolve) //推荐 文本 }, ] })
import React, {Component} from 'react' import {connect} from "react-redux"; import Header from '../../components/header/header' import {Link} from 'react-router-dom' import {Grid, Row, Col} from 'react-styled-flexboxgrid'; import MyLoader from '../../components/skeleton/skeleton' import SearchForm from '../../components/searchForm/SearchForm' import removeDuplicates from 'removeduplicates' import * as actionCreators from "../../redux/actions/index"; import {bindActionCreators} from "redux"; import HotelCard from '../../components/hotelCard/hotelCard' import {Star} from 'material-ui-icons'; class SearchResults extends Component { constructor(props) { super(props) this.state = {} } componentDidMount() { this.props.restoreRedirect() } componentDidUpdate() { this.props.restoreRedirect() } submit = (values) => { let cbds = null if (values.childBirthDates != null) { cbds = values.childBirthDates.map(cbd => { var cbdt = {name: cbd.birth} return (`childBirthDates[]=${cbdt.name}&`) }) } else if (values.childBirthDates == null) { cbds = '' } let name = null if (values.hotelName != null) { name = values.hotelName } else if (values.hotelName == null) { name = '' } // Do something with the form values this.props.availHotelsForm(cbds, values.end, name, values.adultNumber, values.childNumber, values.start); } render() { if (this.props.availHotel && !Array.isArray(this.props.availHotel)) { let i = 0; var ratingsa = [] for (i; i < this.props.availHotel.Rating; i++) { ratingsa.push(<Star/>) } } let availables = removeDuplicates(this.props.availHotel, 'Description') console.log(availables) return ( <div> <Header/> <div className="jumbotron"> <Grid> <Row> <Col md={12}> <SearchForm onSubmit={this.submit} className="search-form"/> </Col> </Row> </Grid> </div> <Grid> <Row> <Col md={12}> <h2>Arama Sonuçları</h2> {this.props.availHotel !== null ? <div>{this.props.availHotel.length > 0 && this.props.availHotel !== null && this.props.loading === false && availables ? availables.map(avail => { let i = 0; var ratings = [] for (i; i < avail.Rating; i++) { ratings.push(<Star/>) } if (Array.isArray(avail.RoomTypes.apiHotelRoomTypeInfo) && avail.RoomTypes.apiHotelRoomTypeInfo[0].Pricings.apiHotelPricingInfo.StopDates === null) { return ( <Col className="hotelcard" md={4}> <Link to={`hotels/${avail.Description}`}> <HotelCard hotelImage={avail.ImageURL["string"][0] + '.jpg'} hotelName={avail.Description} hotelRating={ratings} hotelPlace={avail.Place} minPrice={Array.isArray(avail.RoomTypes.apiHotelRoomTypeInfo) ? avail.RoomTypes.apiHotelRoomTypeInfo[0].Pricings.apiHotelPricingInfo.TotalPrice.Net : !Array.isArray(avail.RoomTypes.apiHotelRoomTypeInfo) ? avail.RoomTypes.apiHotelRoomTypeInfo.Pricings.apiHotelPricingInfo.TotalPrice.Net : ''} /> </Link> </Col> ) } else if (!Array.isArray(avail.RoomTypes.apiHotelRoomTypeInfo) && avail.RoomTypes.apiHotelRoomTypeInfo.Pricings.apiHotelPricingInfo.StopDates === null) { return( <Col className="hotelcard" md={4}> <Link to={`hotels/${avail.Description}`}> <HotelCard hotelImage={avail.ImageURL["string"][0] + '.jpg'} hotelName={avail.Description} hotelRating={ratings} hotelPlace={avail.Place} minPrice={avail.RoomTypes.apiHotelRoomTypeInfo.Pricings.apiHotelPricingInfo.TotalPrice.Net} /> </Link> </Col> ) } else if (Array.isArray(avail.RoomTypes.apiHotelRoomTypeInfo) && avail.RoomTypes.apiHotelRoomTypeInfo[0].Pricings.apiHotelPricingInfo.StopDates !== null) { return ("") } }) : this.props.availHotel !== null && this.props.availHotel.Description && !Array.isArray(availables) ? <div> {Array.isArray(this.props.availHotel.RoomTypes.apiHotelRoomTypeInfo)? this.props.availHotel.RoomTypes.apiHotelRoomTypeInfo[0].Pricings.apiHotelPricingInfo.StopDates === null ? <Col className="hotelcard" md={4}> <Link to={`hotels/${this.props.availHotel.Description}`}> <HotelCard hotelImage={this.props.availHotel.ImageURL["string"][0] + '.jpg'} hotelName={this.props.availHotel.Description} hotelRating={ratingsa} hotelPlace={this.props.availHotel.Place} minPrice={Array.isArray(this.props.availHotel.RoomTypes.apiHotelRoomTypeInfo) ? this.props.availHotel.RoomTypes.apiHotelRoomTypeInfo[0].Pricings.apiHotelPricingInfo.TotalPrice.Net : !Array.isArray(this.props.availHotel.RoomTypes.apiHotelRoomTypeInfo) ? this.props.availHotel.RoomTypes.apiHotelRoomTypeInfo.Pricings.apiHotelPricingInfo.TotalPrice.Net : ''} /> </Link> </Col> :<div>Seçtiğiniz tarih aralıklarında uygun otelimiz bulunmamaktadır</div> : !Array.isArray(this.props.availHotel.RoomTypes.apiHotelRoomTypeInfo)? this.props.availHotel.RoomTypes.apiHotelRoomTypeInfo.Pricings.apiHotelPricingInfo.StopDates === null ? <Col className="hotelcard" md={4}> <Link to={`hotels/${this.props.availHotel.Description}`}> <HotelCard hotelImage={this.props.availHotel.ImageURL["string"][0] + '.jpg'} hotelName={this.props.availHotel.Description} hotelRating={ratingsa} hotelPlace={this.props.availHotel.Place} minPrice={this.props.availHotel.RoomTypes.apiHotelRoomTypeInfo.Pricings.apiHotelPricingInfo.TotalPrice.Net} /> </Link> </Col> :<div>Seçtiğiniz tarih aralıklarında uygun otelimiz bulunmamaktadır</div> : <div>Seçtiğiniz tarih aralıklarında uygun otelimiz bulunmamaktadır</div> } </div> : this.props.loading === true && !this.props.availHotel.length > 0 || !availables.Description ? <Row><Col md={4}><MyLoader/></Col><Col md={4}><MyLoader/></Col> <Col md={4}><MyLoader/></Col></Row> : this.props.loading === false && !this.props.availHotel.length > 0 || !availables.Description ? <div>Seçtiğiniz tarih aralıklarında uygun otelimiz bulunmamaktadır</div> : <div>Seçtiğiniz tarih aralıklarında uygun otelimiz bulunmamaktadır</div> }</div> : <div>Seçtiğiniz tarih aralıklarında uygun otelimiz bulunmamaktadır</div>} </Col> </Row> </Grid> </div> ) } } function mapStateToProps(state) { return { hotels: state.hotel.hotels, availHotel: state.availHotel.availHotel, loading: state.availHotel.loading, redirect: state.availHotel.redirect } } function mapDispatchToProps(dispatch) { return bindActionCreators(actionCreators, dispatch) } export default connect( mapStateToProps, mapDispatchToProps )(SearchResults);
class AnimationController { constructor(solution,interpolationType ="linear"){ this.solution = solution; console.log(this.solution); this.solution.animationController = this; this.reset(); switch(interpolationType){ case "linear": this.interpolationFn = function(t,totalTime,a,b){ return t; } break; case "bounce": this.interpolationFn = function(t,totalTime,a,b){ let accelPeriod = 0.0; let const_bounce = 0.3; let dist = Math.abs(a.x-b.x) + Math.abs(a.y-b.y); let bouncePeriod = (1./dist)*const_bounce*2; let bounceStart = 1. - bouncePeriod; let bounceEnd = 1.-bouncePeriod*0.5; let linearPeriod = bounceStart-accelPeriod; let y = (1 -Math.sqrt(1.-2*accelPeriod*(linearPeriod)))*0.5 if(t<accelPeriod){ return (t*t)/(accelPeriod*accelPeriod)*y; } if(t<bounceStart){ return y+ (t-accelPeriod)/(linearPeriod)*(1-y); } if(t<bounceEnd){ return 1.0 + (t-bounceStart)*const_bounce; } return 1.0 + (bounceEnd-bounceStart)*const_bounce - (t-bounceEnd)*const_bounce; //return t; } break; default: error("Unknown interpolation mode") } } seek(time){ //do binary search /*if(time <= this.solution.times[0]){ this.time = this.solution.times[0]; this.idx = 0; return; } if(time >= this.solution.times[this.solution.times.length-1]){ this.time = this.solution.times[this.solution.times.length-1]; this.idx = this.solution.times.length-2; return; }*/ let tmp_idx = Math.floor((this.solution.times.length-1)/2); this.time = time; if(this.time<=this.solution.times[0]){ this.time =this.solution.times[0]; this.idx = 0; } else if(this.time>=this.solution.times[this.solution.times.length-1]){ this.time =this.solution.times[this.solution.times.length-1]; this.idx = Math.max(this.solution.times.length-2,0); } else while(true){ if(time<=this.solution.times[tmp_idx+1] && time>=this.solution.times[tmp_idx]){ break; } if(time > this.solution.times[tmp_idx+1]){ tmp_idx = Math.floor((this.solution.times.length-1 + tmp_idx)/2); } else /*time < this.solution.times[tmps_idx]*/{ tmp_idx = Math.floor(tmp_idx/2); } } this.step(0); } replaceData(solution){ /* Make sure time isn't overflowing */ this.solution = solution; this.solution.animationController = this; console.log("seeking: ", this.time); this.seek(this.time); //TODO ???? maybe done? } step(delta){ this.time +=delta; if(this.solution.times.length <2){ this.idx = 0; this.time = this.solution.times[0]; } //else while(this.time > this.solution.times[this.idx+1]){ this.idx++; //console.log(this.idx); if(this.idx>this.solution.times.length-2){; this.idx = Math.max(0,this.solution.times.length-2); this.time = this.solution.times[this.solution.times.length-1]; break; } } //else while(this.time < this.solution.times[this.idx]){ console.log("hmmm?"); this.idx--; if(this.idx<0){ this.idx = 0; this.time = this.solution.times[0]; break; } } for(let i in scene.robots){ let tmp = makePos(this.solution.keyframes[this.idx][i].x,this.solution.keyframes[this.idx][i].y); scene.robots[i].x = tmp.x; scene.robots[i].y = tmp.y; } if(this.solution.moves.length>0){ //console.log("steping by ",delta); //console.log("this.idx = ", this.idx," and this.time = ", this.time); let color = this.solution.moves[this.idx].color; let prev_pos = this.solution.keyframes[this.idx][color]; let next_pos = this.solution.keyframes[this.idx+1][color]; let t = (this.time-this.solution.times[this.idx])/(this.solution.times[this.idx+1] -this.solution.times[this.idx]); t = this.interpolationFn(t,(this.solution.times[this.idx+1] -this.solution.times[this.idx]),prev_pos,next_pos); let tmp = addPos( scalePos(prev_pos,1-t), scalePos(next_pos,t)); scene.robots[color].x = tmp.x; scene.robots[color].y = tmp.y; } } reset(){ for(let i in scene.robots){ scene.robots[i].x = this.solution.keyframes[0][i].x; scene.robots[i].y = this.solution.keyframes[0][i].y; } this.time = this.solution.times[0]; this.idx = 0; } }
import express from "express" import cookieParser from "cookie-parser" import logger from "morgan" import http from "http" import cors from "cors" import * as gameController from "./games.controller.mjs" const defaultLogger = logger("dev", { skip: () => process.env.NODE_ENV === "test" }) /** * Function used to create an Express application with 3 endpoints: * - `GET /`: just to check if the API si started * - `GET /games`: to get the games from the database * - `POST /games`: to create new games in the database * @param database an instance of a MongoDB database * @returns Express application */ function createApp(database) { const app = express() app.use(defaultLogger) app.use(express.json()) app.use(express.urlencoded({ extended: false })) app.use(cookieParser()) app.use(cors()) app.get("/", (request, response) => { response.json("OK") }) app.post("/games", gameController.post(database)) app.get("/games", gameController.get(database)) return http.createServer(app) } export { createApp }
import axios from 'axios'; import apiKeys from '../../helpers/apiKeys'; const clientId = apiKeys.githubApi.client_id; // The client_id is exactly the key in apiKeys in gitHub. const clientSecret = apiKeys.githubApi.client_secret; //The client_secret is exactly the key in apiKeys in gitHub. const getUser = gitHubUserName => new Promise((resolve, reject) => { axios .get(`https://api.github.com/users/${gitHubUserName}?client_id=${clientId}&client_secret=${clientSecret}`) .then((result) => { console.log(result); resolve(result.data); }) .catch(err => reject(err)); }); const getCommits = gitHubUserName => new Promise((resolve, reject) => { axios .get(`https://api.github.com/users/${gitHubUserName}/events/public`) .then((result) => { let commitsCount = 0; const commitsArray = result.data.filter(event => event.type === 'PushEvent'); commitsArray.forEach((commit) => { commitsCount += commit.payload.commits.length; }); resolve(commitsCount); }) .catch(err => reject(err)); }); export default { getUser, getCommits };
module.exports = { typeof(e){ let re = '' switch(typeof(e)){ case 'number' : if(parseInt(e) == e){ re = 'int' }else{ re = 'float' } break default : re = typeof(e) break } return re }, inArr(search,array){ for(var i in array){ if(array[i]==search){ return true; } } return false; }, shallowCopy(e){ // console.log(91,e) // console.log(93,typeof(e)) if(typeof(e) != "object"){ return e } let re = {} for(let key in e){ let item = this.shallowCopy(e[key]) // console.log(94,key,item) re[key] = item } return re }, }
import Vue from 'vue' import { Toast } from 'vant' import Axios from 'axios' Vue.use(Toast) export function request (config) { const instance = Axios.create({ baseURL: 'http://123.207.32.32:8000', timeout: 1000 * 5 }) // 请求拦截 instance.interceptors.request.use(config => { Toast.loading({ forbidClick: true, message: '加载中...' }) return config }, err => Promise.reject(err)) // 相应拦截 instance.interceptors.response.use(res => { setTimeout(() => { Toast.clear() }, 500) return res.data }, err => Promise.reject(err)) return instance(config) }
// 排行榜接口 // 注册排行榜接口 // 获取签名方法 const getSecuritySign = require('../sign') // 请求相关函数 const { get } = require('../request') // utils const { getRandomVal, handleSongList } = require('../utils') // 响应成功code const CODE_OK = 0 function registerTopList (app) { app.get('/api/getTopList', (req, res) => { const url = 'https://u.y.qq.com/cgi-bin/musics.fcg' const data = JSON.stringify({ comm: { ct: 24 }, toplist: { module: 'musicToplist.ToplistInfoServer', method: 'GetAll', param: {} } }) const randomKey = getRandomVal('recom') const sign = getSecuritySign(data) get(url, { sign, '-': randomKey, data }).then((response) => { const data = response.data if (data.code === CODE_OK) { const topList = [] const group = data.toplist.data.group group.forEach((item) => { item.toplist.forEach((listItem) => { topList.push({ id: listItem.topId, pic: listItem.frontPicUrl, name: listItem.title, period: listItem.period, songList: listItem.song.map((songItem) => { return { id: songItem.songId, singerName: songItem.singerName, songName: songItem.title } }) }) }) }) res.json({ code: CODE_OK, result: { topList } }) } else { res.json(data) } }) }) } // 注册排行榜详情接口 function registerTopDetail (app) { app.get('/api/getTopDetail', (req, res) => { const url = 'https://u.y.qq.com/cgi-bin/musics.fcg' const { id, period } = req.query const data = JSON.stringify({ detail: { module: 'musicToplist.ToplistInfoServer', method: 'GetDetail', param: { topId: Number(id), offset: 0, num: 100, period } }, comm: { ct: 24, cv: 0 } }) const randomKey = getRandomVal('getUCGI') const sign = getSecuritySign(data) get(url, { sign, '-': randomKey, data }).then((response) => { const data = response.data if (data.code === CODE_OK) { const list = data.detail.data.songInfoList const songList = handleSongList(list) res.json({ code: CODE_OK, result: { songs: songList } }) } else { res.json(data) } }) }) } module.exports = { registerTopDetail, registerTopList }
/* See license.txt for terms of usage */ define([ "firebug/lib/trace", "firebug/lib/domplate", "firebug/lib/object", "firebug/lib/string", "firebug/lib/dom", "firebug/lib/events", "firebug/lib/css", "firebug/lib/locale", "firebug/lib/system", "fbtest/testResultTabView", ], function(FBTrace, Domplate, Obj, Str, Dom, Events, Css, Locale, System, TestResultTabView) { with (Domplate) { // ********************************************************************************************* // // Constants var Cc = Components.classes; var Ci = Components.interfaces; var Cu = Components.utils; Cu["import"]("resource://fbtest/FBTestIntegrate.js"); // ********************************************************************************************* // // TestResultRep Implementation /** * This template represents a "test-result" that is beening displayed within * Trace Console window. Expandable and collapsible logic associated with each * result is also implemented by this object. * * @domplate */ var TestResultRep = domplate( /** @lends FBTestApp.TestResultRep */ { tableTag: TABLE({"class": "testResultTable", cellpadding: 0, cellspacing: 0, onclick: "$onClick"}, TBODY() ), resultTag: FOR("result", "$results", TR({"class": "testResultRow", _repObject: "$result", $testError: "$result|isError", $testOK: "$result|isOK"}, TD({"class": "testResultCol", width: "100%"}, DIV({"class": "testResultMessage testResultLabel"}, "$result|getMessage" ), DIV({"class": "testResultFullMessage testResultMessage testResultLabel"}, "$result.msg" ) ), TD({"class": "testResultCol"}, DIV({"class": "testResultFileName testResultLabel"}, "$result|getFileName" ) ) ) ), resultInfoTag: TR({"class": "testResultInfoRow", _repObject: "$result", $testError: "$result|isError"}, TD({"class": "testResultInfoCol", colspan: 2}) ), getMessage: function(result) { return Str.cropString(result.msg, 200); }, getFileName: function(result) { // xxxHonza: the file name is always content of the wrapAJSFile.html file. return ""; //unescape(result.fileName); }, isError: function(result) { return !result.pass; }, isOK: function(result) { return result.pass; }, summaryPassed: function(summary) { return !summary.failing; }, onClick: function(event) { if (Events.isLeftClick(event)) { var row = Dom.getAncestorByClass(event.target, "testResultRow"); if (row) { this.toggleResultRow(row); Events.cancelEvent(event); } } }, toggleResultRow: function(row) { var result = row.repObject; Css.toggleClass(row, "opened"); if (Css.hasClass(row, "opened")) { var infoBodyRow = this.resultInfoTag.insertRows({result: result}, row)[0]; infoBodyRow.repObject = result; this.initInfoBody(infoBodyRow); } else { var infoBodyRow = row.nextSibling; var netInfoBox = Dom.getElementByClass(infoBodyRow, "testResultInfoBody"); row.parentNode.removeChild(infoBodyRow); } }, initInfoBody: function(infoBodyRow) { var result = infoBodyRow.repObject; var tabViewNode = TestResultTabView.viewTag.replace({result: result}, infoBodyRow.firstChild, TestResultTabView); // Select default tab. TestResultTabView.selectTabByName(tabViewNode, "Stack"); }, // Firebug rep support supportsObject: function(testResult) { return testResult instanceof FBTestApp.TestResult; }, browseObject: function(testResult, context) { return false; }, getRealObject: function(testResult, context) { return testResult; }, getContextMenuItems: function(testResult, target, context) { // xxxHonza: The "copy" command shouldn't be there for now. var popup = Firebug.chrome.$("fbContextMenu"); Dom.eraseNode(popup); var items = []; if (testResult.stack) { items.push({ label: Locale.$STR("fbtest.item.Copy"), nol10n: true, command: Obj.bindFixed(this.onCopy, this, testResult) }); items.push({ label: Locale.$STR("fbtest.item.Copy_All"), nol10n: true, command: Obj.bindFixed(this.onCopyAll, this, testResult) }); items.push("-"); items.push({ label: Locale.$STR("fbtest.item.View_Source"), nol10n: true, command: Obj.bindFixed(this.onViewSource, this, testResult) }); } return items; }, // Context menu commands onViewSource: function(testResult) { var stackFrame = testResult.stack[0]; var winType = "FBTraceConsole-SourceView"; var lineNumber = stackFrame.lineNumber; openDialog("chrome://global/content/viewSource.xul", winType, "all,dialog=no", stackFrame.fileName, null, null, lineNumber, false); }, onCopy: function(testResult) { System.copyToClipboard(testResult.msg); }, onCopyAll: function(testResult) { var tbody = Dom.getAncestorByClass(testResult.row, "testTable").firstChild; var passLabel = Locale.$STR("fbtest.label.Pass"); var failLabel = Locale.$STR("fbtest.label.Fail"); var text = ""; for (var row = tbody.firstChild; row; row = row.nextSibling) { if (Css.hasClass(row, "testResultRow") && row.repObject) { text += (Css.hasClass(row, "testError") ? failLabel : passLabel); text += ": " + row.repObject.msg; text += ", " + row.repObject.fileName + "\n"; } } var summary = Dom.getElementByClass(tbody, "testResultSummaryRow"); if (summary) { summary = summary.firstChild; text += summary.childNodes[0].textContent + ", " + summary.childNodes[1].textContent; } System.copyToClipboard(text); }, }); // ********************************************************************************************* // // Registration Firebug.registerRep(TestResultRep); return TestResultRep; // ********************************************************************************************* // }});
(function(){ $(function(){ $('.btnCheck').on('click',function(){ var dataInfo = $(this).attr('data-info') $.ajax({ url:'/movieMessage', type:'GET', data:'dataInfo='+dataInfo, success:function(data,status,xhr){ var checkInfo = $('.checkInfo') checkInfo.html('') for(var p in data){ if(p==='_id'||p==='__v'||p==='title')continue if((typeof data[p])==='object'){ for(var j in data[p]){ $('<p><strong>'+j+'</strong>:'+data[p][j]+'</p>').appendTo(checkInfo) } }else{$('<p><strong>'+p+'</strong>:'+data[p]+'</p>').appendTo(checkInfo)} } } }) }) var dataInfoG=[''] $('.btnUpdate').on('click',function(){ var dataInfo = $(this).attr('data-info') dataInfoG[0]=dataInfo $.ajax({ url:'/movieMessage', type:'GET', data:'dataInfo='+dataInfo, success:function(data,status,xhr){ var updateInfo = $('.updateInfo') updateInfo.html('') for(var p in data){ if(p==='_id'||p==='__v'||p==='updated_at'||p==='created_at'||p==='movieId'||p==='title')continue if((typeof data[p])==='object'){ for(var j in data[p]){ $('<div style="margin:10px"><strong>'+j+'</strong>:<div contenteditable="true" style="margin-left:20px;padding:5px;display:inline-block;outline:1px #ccc solid" data-name='+p+'-:'+j+'>'+data[p][j]+'</div></div>').appendTo(updateInfo) } }else{$('<div style="margin:10px"><strong>'+p+'</strong>:<div contenteditable="true" style="margin-left:20px;padding:5px;display:inline-block;outline:1px #ccc solid" data-name='+p+'>'+data[p]+'</div></div>').appendTo(updateInfo)} } } }) }) $('.updateConfirm').on('click',function(){ var divs = $('.updateInfo').find($('div[data-name]')) var dataInfo=dataInfoG[0] console.log(dataInfo) var string='movieId='+dataInfo+'&' var innerObj = [] var innerObjCount=[] for(var i=0;i<divs.length;i++){ var ele = $(divs[i]) var dn = ele.attr('data-name') var zzb =/-:/ if(!zzb.test(dn)){ if(i==0){string += dn +'='+ele.text()} else{string += '&'+ dn +'='+ele.text()} }else{ var dns = dn.split('-:') if(innerObj[innerObj.length-1]!==dns[0]){innerObj.push(dns[0])} } } for(var j=0;j<innerObj.length;j++){ innerObjCount.push(0) for(var i=0;i<divs.length;i++){ var ele = $(divs[i]) var dn = ele.attr('data-name') var zzb = /-:/ if(zzb.test(dn)){ var dns = dn.split('-:') if(dns[0]===innerObj[j]){ innerObjCount[j]++ } } } } var comString='' for(var j=0;j<innerObj.length;j++){ var comString_p='' var count = 0 for(var i=0;i<divs.length;i++){ var ele = $(divs[i]) var dn = ele.attr('data-name') var zzb = /-:/ if(zzb.test(dn)){ var dns = dn.split('-:') if(dns[0]===innerObj[j]){ count++ if(count<innerObjCount[j]){comString_p += '"'+dns[1]+'"'+':"'+ele.text()+'",'} else{comString_p += '"'+dns[1]+'"'+':"'+ele.text()+'"'} } } } if(j===innerObj.length-1){ comString+=innerObj[j]+'={'+ comString_p+'}' }else{comString+=innerObj[j]+'={'+ comString_p+'}&'} } string+='&'+comString $.ajax({ url:'/movieUpdate', type:'POST', beforeSend:function(xhr){if(!window.confirm('确定修改?')){xhr.abort()}}, data:string, success:function(data,status,xhr){ console.log(data) } }) }) $('.addmovie').on('click',function(){ $.ajax({ url:'/movieMessage', type:'GET', data:'dataInfo=movie_1', success:function(data,status,xhr){ var addmovieInfo = $('.addmovieInfo') addmovieInfo.html('') for(var p in data){ if(p==='_id'||p==='__v'||p==='updated_at'||p==='created_at'||p==='movieId')continue if((typeof data[p])==='object'){ for(var j in data[p]){ $('<div style="margin:10px"><strong>'+j+'</strong>:<div contenteditable="true" style="margin-left:20px;padding:5px;display:inline-block;outline:1px #ccc solid" data-name='+p+'-:'+j+'> </div></div>').appendTo(addmovieInfo) } }else{$('<div style="margin:10px"><strong>'+p+'</strong>:<div contenteditable="true" style="margin-left:20px;padding:5px;display:inline-block;outline:1px #ccc solid" data-name='+p+'> </div></div>').appendTo(addmovieInfo)} } } }) }) $('.addmovieConfirm').on('click',function(){ var divs = $('.addmovieInfo').find($('div[data-name]')) var innerObj = [] var innerObjCount=[] var string='' for(var i=0;i<divs.length;i++){ var ele = $(divs[i]) var dn = ele.attr('data-name') var zzb =/-:/ if(!zzb.test(dn)){ if(i==0){string += dn +'='+ele.text()} else{string += '&'+ dn +'='+ele.text()} }else{ var dns = dn.split('-:') if(innerObj[innerObj.length-1]!==dns[0]){innerObj.push(dns[0])} } } for(var j=0;j<innerObj.length;j++){ innerObjCount.push(0) for(var i=0;i<divs.length;i++){ var ele = $(divs[i]) var dn = ele.attr('data-name') var zzb = /-:/ if(zzb.test(dn)){ var dns = dn.split('-:') if(dns[0]===innerObj[j]){ innerObjCount[j]++ } } } } var comString='' for(var j=0;j<innerObj.length;j++){ var comString_p='' var count = 0 for(var i=0;i<divs.length;i++){ var ele = $(divs[i]) var dn = ele.attr('data-name') var zzb = /-:/ if(zzb.test(dn)){ var dns = dn.split('-:') if(dns[0]===innerObj[j]){ count++ if(count<innerObjCount[j]){comString_p += '"'+dns[1]+'"'+':"'+ele.text()+'",'} else{comString_p += '"'+dns[1]+'"'+':"'+ele.text()+'"'} } } } if(j===innerObj.length-1){ comString+=innerObj[j]+'={'+ comString_p+'}' }else{comString+=innerObj[j]+'={'+ comString_p+'}&'} } string+='&'+comString console.log(string) $.ajax({ url:'/movieadd', type:'POST', data:string, success:function(data,status,xhr){ alert(data) } }) }) $('.btnDelete').on('click',function(){ var dataInfo = $(this).attr('data-info') if(dataInfo=='movie_1')return $.ajax({ url:'/deleteMovie', type:'GET', data:'dataInfo='+dataInfo, success:function(data,status,xhr){ window.location.reload() console.log(data) } }) }) }) })()
import React, { Component } from 'react'; class Counter extends Component { state = { number: 0, fixedNumber: 0 }; render() { const { number, fixedNumber } = this.state; // state의 값 조회시 this.state로 조회할 수 있음 return ( <div> <h1>{number}</h1> <h2>고정 값 : {fixedNumber}</h2> <button onClick={() => { this.setState({number: number + 1}, () => {console.log(this.state)}); // this.setState를 통해 state의 값 변경가능. callback함수를 통한 state값 확인 }}> +1 </button> </div> ) } } export default Counter;
// export const FOO = "login_foo";
import { makeList } from './setCountries'; import { createUserMap } from '../map/map'; import { activeBtn } from '../map/choseTheMap'; import { changeLegendContent } from '../map/legendInfo'; export function rerenderTextCountry(name) { document.querySelector('#country-name').textContent = name; } export function rerenderSomeStatistic(item, oneMore) { document.querySelectorAll('.case').forEach((el, i) => { el.textContent = item[i][oneMore]; }); } export function chooseCategoryForCountry(parent, item, otherParent) { const ITEMS = document.createElement('div'); ITEMS.classList.add('list_country-cases'); const ARRAY_OF_TITLES = [ 'Total confirmed', 'Total deaths', 'Total recovered', 'New confirmed', 'New deaths', 'New recovered', 'Total confirmed (100K)', 'Total deaths (100K)', 'Total recovered (100K)', 'New confirmed (100K)', 'New deaths (100K)', 'New recovered (100k)' ]; const ARRAY_OF_CASES = [ 'cases', 'deaths', 'recovered', 'todayCases', 'todayDeaths', 'todayRecovered', 'TotalConfirmedOneHundred', 'TotalDeathsOneHundred', 'TotalRecoveredOneHundred', 'NewConfirmedOneHundred', 'NewDeathsedOneHundred', 'NewRecoveredOneHundred' ]; for (let i = 0; i < ARRAY_OF_TITLES.length; i += 1) { const STATISTIC = document.createElement('div'); STATISTIC.classList.add('list_global-statistic', 'pointer-item'); const CATEGORY = document.createElement('div'); CATEGORY.classList.add('list_global-category'); CATEGORY.classList.add('list_global-category-choose'); const ITEM = document.createElement('div'); ITEM.classList.add('list_global-item'); const CATEGORY_NAME = document.createElement('h4'); CATEGORY_NAME.textContent = `${ARRAY_OF_TITLES[i]}`; ITEM.append(CATEGORY_NAME,); CATEGORY.append(ITEM); STATISTIC.append(CATEGORY); ITEMS.appendChild(STATISTIC); STATISTIC.addEventListener('click', (e) => { rerenderTextCountry(ARRAY_OF_TITLES[i]); rerenderSomeStatistic(item, ARRAY_OF_CASES[i]); localStorage.setItem('DANSitNikov-parameter', JSON.stringify(ARRAY_OF_CASES[i])); document.querySelector('.list_country-cases').classList.toggle('display-list'); makeList(item, otherParent); createUserMap(ARRAY_OF_CASES[i], 'white', `map_${i}`, document.querySelector('.map')); activeBtn(document.querySelectorAll('.choose_map-button')[i], document.querySelectorAll('.active-btn-map')); changeLegendContent(i, document.querySelector('.legend')); }); } parent.appendChild(ITEMS); return parent; }
import React from 'react'; import ReactDOM from 'react-dom'; import './styles/main.scss'; // import 'slick-carousel/slick/slick.scss'; // import 'slick-carousel/slick/slick-theme.scss'; import Navigation from './components/Navigation'; import IntroSection from './sections/IntroSection'; import ProfileSection from './sections/ProfileSection'; import AcademicSection from './sections/AcademicSection'; import CoursesSection from './sections/CoursesSection'; import PublicationSection from './sections/PublicationSection'; import ContactSection from './sections/ContactSection'; import QuoteSection from './sections/QuoteSection'; const App = () => ( <div> <Navigation /> <IntroSection /> <ProfileSection /> <AcademicSection /> <CoursesSection /> <PublicationSection /> <ContactSection /> <QuoteSection /> </div> ); ReactDOM.render (<App />, document.getElementById ('root'));
import { renderString, configure, renderPageString } from "../src"; import CtaManager from "../src/lib/cta_manager"; import HubDbManager from "../src/lib/hubdb_manager"; import PageManager from "../src/lib/page_manager"; import pagesJSON from './fixture/pages.json'; const d= new Date(); const hubDBManager = new HubDbManager({ 1: { metadata: { id: 1, name: 'tablename', columns: ['title'], created_at: new Date(), published_at: new Date(), updated_at: new Date(), row_count: 2 }, rows: [ { hs_id: 123, hs_path: null, hs_child_table: '', hs_name: 'title', hs_created_at: d, title: 'TITLE 1', count: 101 }, { hs_id: 124, hs_path: null, hs_child_table: '', hs_name: 'title', hs_created_at: d, column_name: '', title: 'TITLE 2', count: 50 } ] } }); const ctaManager = new CtaManager([ { id: 'ccd39b7c-ae18-4c4e-98ee-547069bfbc5b', button_text: 'READ MORE', portal_id: '1234' } ]); const pageManager = new PageManager(pagesJSON); describe('Hub DB integration works', () => { it('hubdb integration', () => { configure({pageManager, hubDBManager, ctaManager}); const html = renderString(` {% for row in hubdb_table_rows(1, "count__gt=1") %} the value for row {{ row.hs_id }} is {{ row.title }} {% endfor %} `); expect(html).toContain('the value for row 123 is TITLE 1'); expect(html).toContain('the value for row 124 is TITLE 2') }); it('cta renders ', () => { configure({pageManager, hubDBManager, ctaManager}); const html = renderString(`{{ cta('ccd39b7c-ae18-4c4e-98ee-547069bfbc5b') }}`); expect(html).toContain('ccd39b7c-ae18-4c4e-98ee-547069bfbc5b'); }); it('Page is correctly configured', () => { configure({pageManager, hubDBManager, ctaManager}); const html = renderPageString('/', `{{ content.id }}`); expect(html).toContain('1'); }); it('Page is correctly for subpages', () => { configure({pageManager, hubDBManager, ctaManager}); const html = renderPageString('/test', `{{ content.id }}`); expect(html).toContain('2'); }); });
window.onload = function() { switchSpan(); } function switchSpan(){ var el = document.querySelector('span.switch'); var i = 0; var spanWords = ['weird', 'funny', 'random']; var interval = setInterval(function() { let iter = i++ % 3; el.textContent = spanWords[iter]; if (iter > 2) { clearInterval(interval); } }, 3000); }
(function () { 'use strict'; /** * @ngdoc service * @name interestingVideos.factory:InterestingVideos * * @description * */ angular .module('interestingVideos') .factory('InterestingVideos', InterestingVideos); function InterestingVideos($http,consts) { var InterestingVideosBase = {}; InterestingVideosBase.getAll = function() { return $http({ method: "GET", url: consts.serverUrl + "Video/GetVideos", params:{ Videotype:0 } }); }; InterestingVideosBase.getVideo = function(videoId) { return $http({ method: "GET", url: consts.serverUrl + "Video/GetVideo", params: { videoId: videoId } }); }; // InterestingVideosBase.create = function(video) { // // var fd = new FormData(); // fd.append("Name", video.Name); // fd.append("Description", video.Description); // fd.append("ImageFile", video.ImageFile); // fd.append("IsAuthorizedContent", video.IsAuthorizedContent); // video.tags.forEach(function(top, index) { // fd.append("Tags[" + index + "].TagId", tag.TagId); // }); // return $http({ // method: "POST", // url: consts.serverUrl + "InterestingVideos/CreateVideo", // data: fd, // headers: { // 'Content-Type': undefined // }, // transformRequest: angular.identity // }); // }; // InterestingVideosBase.update = function(video) { // var fd = new FormData(); // fd.append("Id", video.Id); // fd.append("Name", video.Name); // fd.append("Description", video.Description); // fd.append("ImageFile", video.ImageFile); // fd.append("IsAuthorizedContent", video.IsAuthorizedContent); // // video.tags.forEach(function(top, index) { // if (top.Id != undefined) fd.append("Tags[" + index + "].Id", tag.TagId); // fd.append("Tags[" + index + "].TagId",tag.TagId); // }); // // return $http({ // method: "POST", // url: consts.serverUrl + "InterestingVideos/UpdateVideo", // data: fd, // headers: { // 'Content-Type': undefined // }, // transformRequest: angular.identity // }); // }; InterestingVideosBase.delete = function(videoId) { return $http({ method: "POST", url: consts.serverUrl + "video/DeleteVideo", data: {videoId:videoId} }); }; return InterestingVideosBase; } }());
import fetch from 'isomorphic-fetch' function search (query, range, dev, cb) { query = encodeURIComponent(query) range = encodeURIComponent(range) return fetch(`/api/query/${query}${range ? '/' : ''}${range}${dev ? '?dev=1' : ''}`, { accept: 'application/json' }).then(checkStatus) .then(parseJSON) .then(cb) .catch(function (err) { cb({ error: true, message: err.message }) }) } function checkStatus (response) { let ctHeader = response.headers.get('content-type') if (ctHeader && ctHeader.indexOf('application/json') !== 0) { throw new Error('Unexpected error occurred') } return response } function parseJSON (response) { return response.json() } const Client = { search } export default Client
function runTest() { FBTest.openNewTab(basePath + "commandLine/api/debug.html", function(win) { FBTest.enablePanels(["console", "script"], function() { var tasks = new FBTest.TaskList(); // Create breakpoint using 'debug(onTextExecute)' method on the cmd line. tasks.push(createBreakpoint); // Execute breakpoint by pressing 'Execute Test' button on the page. tasks.push(executeBreakpoint, win); tasks.run(function() { FBTest.testDone(); }); }); }); } function createBreakpoint(callback) { // Asynchronously wait for result in the Console panel. var config = {tagName: "div", classes: "logRow logRow-command"}; FBTest.waitForDisplayedElement("console", config, function(row) { FBTest.compare(">>> debug(onExecuteTest)", row.textContent, "The command line should display: >>> debug(onExecuteTest)"); callback(); }); // Execute command line expression. FBTest.executeCommand("debug(onExecuteTest)"); } function executeBreakpoint(callback, win) { // Asynchronously wait for break in debugger. FBTest.waitForBreakInDebugger(FW.Firebug.chrome, 30, false, function(row) { FBTest.clickContinueButton(); callback(); }); // Execute test by clicking on the 'Execute Test' button. FBTest.clickContentButton(win, "testButton"); }
var structfield________________________________________________________________info________________8js________8js____8js__8js_8js = [ [ "structfield________________________________info________8js____8js__8js_8js", "structfield________________________________________________________________info________________8js________8js____8js__8js_8js.html#af82d66eebe31d2cb74a2cafc6d3922bc", null ] ];
exports.run = async (bot, msg, args) => { if (args.length < 1) { throw 'Please specify a command'; } let command = bot.commands.get(args[0]); if (!command) { throw 'That command doesn\'t exist!'; } let amount = bot.managers.stats.get(`command.${command.info.name}`) || 0; return (await msg.edit({ embed: bot.utils.embed(command.info.name, `You've used **${command.info.name}** a total of ${amount} times.`) })).delete(6000); }; exports.info = { name: 'commandstat', usage: 'commandstat <command>', description: 'Show usage count for a specific command.', credits: '<@149916494183137280>' // Liam Bagge#0550 };
import { isNull, isTrue, isUndefined, isFalse } from '../true'; describe('Probar resultados Nulos', () => { test('null', () => { expect(isNull()).toBeNull(); }); }); describe('Probar resultador verdaderos', () => { test('verdaderos', () => { expect(isTrue()).toBeTruthy(); }); }); describe('Probar resultador falsos', () => { test('falsos', () => { expect(isFalse()).toBeFalsy(); }); }); describe('Probar resultador undefined', () => { test('undefined', () => { expect(isUndefined()).toBeUndefined(); }); }); describe('Probar resultados no verdaderos', () => { test('verdadero o falso', () => { expect(isFalse()).not.toBeTruthy(); }); });
import React from 'react' import Logo from "../images/logo.svg" import "./Header.css" export const Header = () => { const toggleNav = () => { document.querySelector(".nav-links").classList.toggle("hide") document.querySelector(".main-content").classList.toggle("menu-gradient") } return ( <header className="main-header"> <nav className="main-nav container"> <img src={Logo} alt=""/> <div className="hidden" onClick={toggleNav}></div> <ul className="nav-links small-nav hide"> <li><a href="#about">About</a></li> <li><a href="#about">Discover</a></li> <li><a href="#about">Get started</a></li> </ul> </nav> </header> ) } export default Header
import React from 'react'; import { Text } from 'react-native'; import { Provider } from 'react-redux'; import { useFonts } from 'expo-font'; import configureStore from './redux/store'; import * as firebase from 'firebase'; import ConditionRender from './containers/ConditionRender'; const store = configureStore(); export default function App() { /** * Firebase configuration */ var firebaseConfig = { apiKey: "AIzaSyB8rMsENjRdLYGxRHhTi0YHSEuSLuMi2JQ", authDomain: "exchangestudentschats.firebaseapp.com", databaseURL: "https://exchangestudentschats-default-rtdb.firebaseio.com", projectId: "exchangestudentschats", storageBucket: "exchangestudentschats.appspot.com", messagingSenderId: "485986349293", appId: "1:485986349293:web:10ab319e0c231f69e81ce4" }; if (!firebase.apps.length) { firebase.initializeApp(firebaseConfig); } else { firebase.app(); // if already initialized, use that one } //Loading the fonts const [loaded] = useFonts({ Montserrat: require('./assets/myfonts/Montserrat-Regular.ttf'), MontserratBold: require('./assets/myfonts/Montserrat-Bold.ttf'), }); if (!loaded) { return ( <Text>Loading...</Text> ) } else { return ( <Provider store={store}> <ConditionRender /> </Provider> ) } }
let frutasUno = ["banana","pera","manzana"]; let frutasDos = ["durazno","ciruela","naranja"]; //spread operator let todasLasFrutas = [...frutasUno, ...frutasDos]; console.log(todasLasFrutas);
const ResponseError = require('../../../Enterprise_business_rules/Manage_error/ResponseError'); const { TYPES_ERROR } = require('../../../Enterprise_business_rules/Manage_error/codeError'); module.exports = async (id, { spaceRepositoryMySQL }) => { // Se comprueba que se recibe un nombre if (!id) { throw new ResponseError(TYPES_ERROR.FATAL, 'El id es necesario para realizar el borrado del aula o laboratorio', 'name_empty'); } // Se comprueba que existe un aula o laboatorio con ese nombre const space = await spaceRepositoryMySQL.getSpace(id); if (!space) { throw new ResponseError(TYPES_ERROR.FATAL, 'El aula o laboratorio no está regitrado', 'not_space_exist'); } return spaceRepositoryMySQL.deleteSpace(id); };
/** Stores all player based data. - Stores values (or datums) for all user related data - Modifies said datums - Listens for changes to those values, and triggers certain actions because of that Meant to be expensive in operations. Use sparingly. @author laifrank2002 @date 2019-12-02 */ var StateManager = ( function() { var data = {}; var listeners = []; /** Listens for a certain datum to see if it is changed. If it is, an action is triggered with the new value of the datum as a parameter. @param name - key @param category - datum category @param id - datum key in category @param action - function to be called with new value of datum as parameter @author laifrank2002 @date 2019-12-02 */ function StateListener(name,category,id,action) { this.name = name; this.category = category; this.id = id; this.action = action; } /** Checks if it is the correct datum, then triggers the action with the new changed value. @param category - datum category @param id - datum key in category @param value - the new value for the datum @author laifrank2002 @date 2019-12-02 */ StateListener.prototype.trigger = function(category,id,value) { if(category === this.category && id === this.id) { this.action(value); } } return { get data() {return data}, /** Initializes the module. - Creates all of the data categories - Assigns values to them so that the modules can use them @author laifrank2002 @date 2019-12-02 */ initialize: function() { Engine.log("Initializing StateManager..."); /* takes the categories and initializes them */ data["world"] = { people: {}, }; // temp until saving and loading is figured out StateManager.startNewGame(); }, /** Populates the data with default values in order to start a new game. @author laifrank2002 @date 2019-12-02 */ startNewGame: function() { }, /** Sets the state of a certain datum. @param category - datum category @param id - datum key in category @param value - the new value to be assigned to the datum @author laifrank2002 @date 2019-12-02 */ setState: function(category,id,value) { if(data[category]) { data[category][id] = value; listeners.forEach(listener => listener.trigger(category,id,value)); } else { Engine.log("Set Data: No such category: " + category + " exists."); } }, /** Attempts to add a certain value to non object datums as the new datum. @param category - datum category @param id - datum key in category @param value - the value to be added to the existing datum @author laifrank2002 @date 2019-12-02 */ addState: function(category,id,value) { if(data[category]) { if(typeof data[category][id] !== "object") { StateManager.setState(category,id ,StateManager.getState(category,id) + value); } } else { Engine.log("Add Data: No such category: " + category + " exists."); } }, /** Gets a certain datum by category and id. @param category - datum category @param id - datum key in category @author laifrank2002 @date 2019-12-02 */ getState: function(category,id) { if(data[category]) { return data[category][id]; } else { Engine.log("Get Data: No such category: " + category + " exists."); } }, /** Adds a listener to a certain datum by key. Note, no two listeners should have the same name. @param name - key @param category - datum category @param id - datum key in category @param action - function to be called with new value of datum as parameter @author laifrank2002 @date 2019-12-02 */ addListener: function(name,category,id,action) { listeners.push(new StateListener(name,category,id,action)); }, /** Removes a listener by key. Note, fails silently @param name - key of the listener @return boolean - if a listener was successfully removed @author laifrank2002 @date 2019-12-02 */ removeListener: function(name) { var listenerRemoved = false; listeners = listeners.filter(listener => { if(listener.name === name) listenerRemoved = true; return listener.name !== name }); return listenerRemoved; }, } } )();
sap.ui.controller("com.slb.mobile.view.WOListMaster", { onListItemPress : function (evt) { busyDialog.open(); var context = evt.getSource().getBindingContext(); var nav = oCore.byId('mainview').getController().nav; nav.to("WODetail",context); //this.nav.to("WODetail", context); }, handleListSelect : function (evt) { var context = evt.getParameter("listItem").getBindingContext(); this.nav.to("WODetail", context); }, /** * Called when a controller is instantiated and its View controls (if available) are already created. * Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization. * @memberOf view.WOListMaster */ onInit: function() { //var oModel3 = new sap.ui.model.json.JSONModel("model/WOMockup.json"); // this.getView().setModel(oModel3); var woList=[]; var woModel = new sap.ui.model.json.JSONModel(); var item = {}; var temp1; var sUrl = appContext.applicationEndpointURL + "/WOLIST?sap-client=330&$format=json"; var uri = appContext.applicationEndpointURL; // var sUrl = appContext.applicationEndpointURL +"?sap-client=330&$format=json"; var headers = {"X-SMP-APPCID" : appContext.applicationConnectionId}; var user = appContext.registrationContext.user; var password = appContext.registrationContext.password; //Decalaration of OData Model var oModel = new sap.ui.model.odata.ODataModel(uri, true, user,password, headers); oModel.read("/WOLIST", null, null, true, function fnSuccess(oData,response) { $(oData.results).each(function( i, val ) { woList.push({ "WOId" : val.Orderid, "Plant" : val.OrderType, "WOText" :val.ShortText, "RigId": "R2322", "JobId": "J87799", "StartDate": "23-Nov-2014" }); }); woModel.setData(woList); oCore.setModel(woModel,"mastermodel"); oCore.byId("masterlist").fireEvent("drawmaster"); }, function fnError(response) { alert("eerrr"); } ); /*****************************comment ajax request ******************** var req = $.ajax({ url: sUrl, dataType: 'json', cache: false, beforeSend:function (xhr) { xhr.setRequestHeader('Authorization', "Basic " + Base64.encode(user + ':' + password)); } // type: "GET" }); req.success(function(oData,status, xhr) { // alert("suc"); if(xhr.status==200){ $(oData.d.results).each(function( i, val ) { woList.push({ "WOId" : val.Orderid, "Plant" : val.OrderType, "WOText" :val.ShortText, "RigId": "R2322", "JobId": "J87799", "StartDate": "23-Nov-2014" }); }); woModel.setData(woList); oCore.setModel(woModel,"mastermodel"); oCore.byId("masterlist").fireEvent("drawmaster"); }else{ } }); req.fail(function(xhr){ alert("error"); }); **************/ // woModel.setData(woList); //oCore.setModel(woModel,"mastermodel"); /* var sURL = getDataEndPoint('WorkOrders'); var oHeaders = {}; authStr = "Basic " + btoa(userdata.user + ':' + userdata.pass); oHeaders['Authorization'] = authStr; var request = { headers : oHeaders, requestUri : sURL, method : "GET" }; console.log("read using " + sURL); OData.read(request, readSuccessCallback, errorCallback); */ // oCore.byId("masterlist").fireEvent("drawmaster"); }, getGroupHeader: function (oGroup){ return new sap.m.GroupHeaderListItem( { title: oGroup.key, upperCase: false } ); }, goHome: function(evt) { var context = evt.getSource().getBindingContext(); var nav = oCore.byId('mainview').getController().nav; nav.to("Home",context); } /** * Similar to onAfterRendering, but this hook is invoked before the controller's View is re-rendered * (NOT before the first rendering! onInit() is used for that one!). * @memberOf view.WOListMaster */ // onBeforeRendering: function() { // // }, /** * Called when the View has been rendered (so its HTML is part of the document). Post-rendering manipulations of the HTML could be done here. * This hook is the same one that SAPUI5 controls get after being rendered. * @memberOf view.WOListMaster */ // onAfterRendering: function() { // // }, /** * Called when the Controller is destroyed. Use this one to free resources and finalize activities. * @memberOf view.WOListMaster */ // onExit: function() { // // } }); /* * This method is used for getting the data end points for various calls to backend system . It prepares the backend service call */ function readSuccessCallback(data, response) { alert("success"); } function errorCallback(e) { alert("An error occurred: " + JSON.stringify(e)); // showScreen("MainDiv"); }
module.exports = angular.module('employees', [ 'ui.layout', 'treeControl', 'ui.router']) .config(function($stateProvider) { $stateProvider .state('employees', { url: '/employees', templateUrl: 'templates/employees/index.html', controller: 'EmployeesCtrl as employees', resolve: { employeeGraph: function(EmployeesSvc) { return EmployeesSvc.employeeGraph() } } }) $stateProvider .state('employees.show', { url: '/:id', templateUrl: 'templates/employees/show.html', controller: 'EmployeeCtrl as employee', resolve: { employee: function(EmployeesSvc, $stateParams) { return EmployeesSvc.find($stateParams.id) } } }) }) .controller('EmployeesCtrl', require('./controllers/index')) .controller('EmployeeCtrl', require('./controllers/show')) .service('EmployeesSvc', require('./services/employees'))
Template.spaceBooking.helpers({ spaceBookingModal: function() { return "space-booking-modal-" + this._id }, depositInCents: function() { var p = Mart.Prices.findOne({ unit: Session.get(unitSessionId(this._id)), productId: this._id }) if(p) return p.depositInCents } });
import { extensions } from '../lib/configuration.js' import resolveUrl from './resolveUrl.js' function getDefaultTheme () { return { theme: extensions.studio.options.theme, editorTheme: extensions.studio.options.editorTheme } } function getCurrentTheme () { const defaultTheme = extensions.studio.options.theme const defaultEditorTheme = extensions.studio.options.editorTheme let currentTheme = defaultTheme let currentEditorTheme = defaultEditorTheme let userTheme = window.localStorage.getItem('studioTheme') let userEditorTheme = window.localStorage.getItem('studioEditorTheme') if (userTheme != null && extensions.studio.options.availableThemes[userTheme] != null) { currentTheme = userTheme } if (userEditorTheme != null && extensions.studio.options.availableEditorThemes[userEditorTheme] != null) { currentEditorTheme = userEditorTheme } if (currentEditorTheme == null) { currentEditorTheme = extensions.studio.options.availableThemes[currentTheme].editorTheme } return { theme: currentTheme, editorTheme: currentEditorTheme } } function setCurrentTheme ({ theme, editorTheme }, { onComplete, onError } = {}) { if (theme == null && editorTheme == null) { if (onComplete) { onComplete() } return getCurrentTheme() } if (theme == null && editorTheme != null) { changeEditorTheme(editorTheme) if (onComplete) { onComplete() } return getCurrentTheme() } const themeLinks = Array.prototype.slice.call(document.querySelectorAll('link[data-jsreport-studio-theme]')) const serverStartupHash = document.querySelector('meta[data-jsreport-server-startup-hash]').getAttribute('content') const customCssLink = document.querySelector('link[data-jsreport-studio-custom-css]') const defaultThemeLink = themeLinks.find((l) => l.dataset.defaultJsreportStudioTheme === 'true' || l.dataset.defaultJsreportStudioTheme === true) let targetThemeLink = themeLinks.find((l) => l.dataset.jsreportStudioTheme === theme) if (!defaultThemeLink) { return getCurrentTheme() } let newEditorTheme if (editorTheme != null) { newEditorTheme = editorTheme } else { newEditorTheme = getCurrentTheme().editorTheme } if (!targetThemeLink) { const newThemeLink = document.createElement('link') newThemeLink.rel = 'stylesheet' newThemeLink.href = resolveUrl(`/studio/assets/alternativeTheme.css?${serverStartupHash}&name=${theme}`) newThemeLink.disabled = false newThemeLink.dataset.jsreportStudioTheme = theme newThemeLink.onload = () => { changeTheme(theme) changeEditorTheme(newEditorTheme) if (customCssLink) { changeCustomCss(theme, onComplete, onError) } else { onComplete && onComplete() } } newThemeLink.onerror = () => { if (onError) { onError() } } defaultThemeLink.parentNode.insertBefore(newThemeLink, defaultThemeLink.nextSibling) themeLinks.push(newThemeLink) targetThemeLink = newThemeLink return { theme: theme, editorTheme: newEditorTheme } } else { changeTheme(theme) changeEditorTheme(newEditorTheme) if (customCssLink) { changeCustomCss(theme, onComplete, onError) } else { onComplete && onComplete() } return getCurrentTheme() } function changeTheme (newTheme) { targetThemeLink.disabled = false themeLinks.forEach((l) => { if (l.dataset.jsreportStudioTheme !== newTheme) { l.disabled = true } }) window.localStorage.setItem('studioTheme', newTheme) } function changeEditorTheme (newEditorTheme) { window.localStorage.setItem('studioEditorTheme', newEditorTheme) } function changeCustomCss (newTheme, onLoad, onError) { const clonedLink = customCssLink.cloneNode() clonedLink.href = resolveUrl(`/studio/assets/customCss.css?theme=${newTheme}`) clonedLink.onload = () => { if (onLoad) { onLoad() } } clonedLink.onerror = () => { if (onError) { onError() } } customCssLink.parentNode.insertBefore(clonedLink, customCssLink.nextSibling) customCssLink.remove() } } function setCurrentThemeToDefault (opts = {}) { setCurrentTheme({ theme: extensions.studio.options.theme, editorTheme: extensions.studio.options.editorTheme }, { ...opts, onComplete: () => { window.localStorage.removeItem('studioTheme') window.localStorage.removeItem('studioEditorTheme') if (opts.onComplete) { opts.onComplete() } } }) return { theme: extensions.studio.options.theme, editorTheme: extensions.studio.options.editorTheme } } export { getCurrentTheme } export { getDefaultTheme } export { setCurrentTheme } export { setCurrentThemeToDefault }
module.exports = { maxUsernameLength: 16, };
import React from 'react' import { head, once, tail, reverse, wrap } from 'lodash' import { Main } from 'morpheus/title' import { createSelector } from 'reselect' import { selectors as sceneSelectors, getSceneType } from 'morpheus/scene' import './modules' import { decorate as faderDecorator } from './components/Fader' import Pano from './components/WebGl' import Sound from './components/Sound' import Stage from './components/Stage' function createSceneMapper(map) { return sceneData => map[getSceneType(sceneData)] } export const createLiveSceneSelector = createSceneMapper({ panorama: Pano, special: Stage, title: Main, }) export const createEnteringSceneSelector = createSceneMapper({ panorama: Pano, special: Stage, }) export const createExitingSceneSelector = createSceneMapper({ panorama: Pano, special: Stage, title: Main, }) // wrap...once creates a lazy init selector to break a circular dependency export default wrap( once(() => createSelector( sceneSelectors.currentScenesData, sceneSelectors.isEntering, sceneSelectors.isLive, sceneSelectors.isExiting, sceneSelectors.dissolve, (_currentScenes, _isEntering, _isLive, _isExiting, dissolve) => { const currentScenes = _currentScenes.toJS() let scenes = [] const current = head(currentScenes) const previouses = reverse(tail(currentScenes)) const CurrentScene = createLiveSceneSelector(current) const EnteringScene = createEnteringSceneSelector(current) const CurrentExitingScene = createExitingSceneSelector(current) const PreviousScenes = previouses.map(createExitingSceneSelector) let previousScene if (PreviousScenes.length) { previousScene = PreviousScenes.map((PreviousScene, index) => ( <PreviousScene key={`scene${previouses[index].sceneId}`} scene={previouses[index]} /> )) scenes = scenes.concat(previousScene) } if (_isLive && CurrentScene) { if (previousScene && dissolve) { const Fader = faderDecorator(<CurrentScene scene={current} />) scenes.push(<Fader key={`scene${current.sceneId}`} />) } else { scenes.push( <CurrentScene key={`scene${current.sceneId}`} scene={current} />, ) } } if (_isEntering && EnteringScene) { scenes.push( <EnteringScene key={`scene${current.sceneId}`} scene={current} />, ) } if (_isExiting && CurrentExitingScene) { scenes.push( <CurrentExitingScene key={`scene${current.sceneId}`} scene={current} />, ) } scenes.push(<Sound key="sound" scene={current} />) return scenes }, ), ), (selectorFactory, state) => selectorFactory()(state), )
class Moves { static get ROCK() { return "rock"; } static get PAPER() { return "paper" } static get SCISSORS() { return "scissors"; } } class Winner { static get PLAYER() { return 1; } static get COMPUTER() { return 0; } static get TIE() { return 2; } } function ComputerPlay() { let randomNumber = Math.floor(Math.random() * 3); //returns a number from 0 to 2 switch (randomNumber) { case 0: return Moves.ROCK; case 1: return Moves.PAPER; case 2: return Moves.SCISSORS; } } function CheckWinner(playerSelection, computerSelection) { if (playerSelection && computerSelection) { if ((playerSelection === Moves.ROCK) && (computerSelection === Moves.PAPER)) { return { string: "You Lose! Paper beats Rock", winner: Winner.COMPUTER }; } else if ((playerSelection === Moves.ROCK) && (computerSelection === Moves.SCISSORS)) { return { string: "You Win! Rock beats Scissors", winner: Winner.PLAYER }; } else if ((playerSelection === Moves.ROCK) && (computerSelection === Moves.ROCK)) { return { string: "It's a tie! Rock vs Rock", winner: Winner.TIE }; } else if ((playerSelection === Moves.PAPER) && (computerSelection === Moves.ROCK)) { return { string: "You Win! Paper beats Rock", winner: Winner.PLAYER }; } else if ((playerSelection === Moves.PAPER) && (computerSelection === Moves.PAPER)) { return { string: "it's a tie! Paper vs Paper", winner: Winner.TIE }; } else if ((playerSelection === Moves.PAPER) && (computerSelection === Moves.SCISSORS)) { return { string: "You Lose! Scissors beats Paper", winner: Winner.COMPUTER }; } else if ((playerSelection === Moves.SCISSORS) && (computerSelection === Moves.ROCK)) { return { string: "You Lose! Rock beats Scissors", winner: Winner.COMPUTER }; } else if ((playerSelection === Moves.SCISSORS) && (computerSelection === Moves.PAPER)) { return { string: "You Win! Scissors beats Paper", winner: Winner.PLAYER }; } else if ((playerSelection === Moves.SCISSORS) && (computerSelection === Moves.SCISSORS)) { return { string: "It's a tie! Scissors vs Scissors", winner: Winner.TIE }; } } } function Game() { const TotalRounds = 5; let computerMoves = []; //at the start of our program computer has moves for the whole round let round = 0; let wins = 0; let loses = 0; let ties = 0; GenerateComputerMoves(); GenerateRoundResultsDisplay(); function GenerateComputerMoves() { for (let i = 0; i < TotalRounds; i++) { computerMoves[i] = ComputerPlay(); } }; function GenerateRoundResultsDisplay() { if (round === 0) { const mainElement = document.getElementsByTagName('MAIN')[0]; const newDivRoundResultContainer = document.createElement('div'); newDivRoundResultContainer.style.cssText = "display:flex; justify-content: space-evenly; width: 40%; padding-bottom: 2.5rem; padding-top: 2.5rem;"; newDivRoundResultContainer.setAttribute('id', 'round-result-container'); for (let i = 0; i < TotalRounds; i++) { const newDivRoundResultElement = document.createElement('div'); newDivRoundResultElement.setAttribute("data-entry", `${i}`); newDivRoundResultElement.style.width = "20px"; newDivRoundResultElement.style.height = "20px"; newDivRoundResultElement.style.borderRadius = "100px"; newDivRoundResultElement.style.backgroundColor = "#f7e1aa"; newDivRoundResultContainer.appendChild(newDivRoundResultElement); } mainElement.insertBefore(newDivRoundResultContainer, mainElement.firstElementChild); } } function RoundResult(result) { document.querySelector('#round-result-container').childNodes.forEach(div => { if (div.dataset.entry == round) { switch (result) { case 'win': div.style.backgroundColor = "#41cac8"; //green break; case 'lose': div.style.backgroundColor = "#e596bc"; //pink break; case 'tie': div.style.backgroundColor = "#7fcaf0"; break; } } }) } function reset() { round = 0; firstTimeInitRound = 0; wins = 0; loses = 0; ties = 0; document.querySelector('#round-result-container').childNodes.forEach(div => { div.style.backgroundColor = "#f7e1aa"; }) GenerateComputerMoves(); resetDisplay(); } function resetDisplay() { const roundDisplays = document.getElementsByClassName('round-display'); Array.from(roundDisplays).forEach(roundDisplay => { roundDisplay.lastElementChild.remove(); }) } return { GameRound: function gameRound(playerMove) { const playerRoundElement = document.getElementById("player-round"); const computerRoundElement = document.getElementById("computer-round"); if (round === 0) { playerRoundElement.textContent = "Player 1" playerRoundElement.style.width = "auto"; playerRoundElement.textAlign = "initial"; playerRoundElement.parentElement.style.width = "initial"; computerRoundElement.style.display = "initial"; } console.log(round); const result = CheckWinner(playerMove, computerMoves[round]); switch (result.winner) { case Winner.PLAYER: wins++; RoundResult('win'); break; case Winner.COMPUTER: loses++; RoundResult('lose'); break; case Winner.TIE: ties++; RoundResult('tie'); break; } round++; if (round === TotalRounds) { let displayMessage = ''; if (wins > loses) { displayMessage = "You won the game! Congratulations!"; } else if (wins < loses) { displayMessage = "You lost the game! Try next time!"; } else { displayMessage = "It's a tie! Try again"; } playerRoundElement.textContent = displayMessage; playerRoundElement.style.width = "100%"; playerRoundElement.style.textAlign = "center"; playerRoundElement.parentElement.style.width = "100%"; computerRoundElement.style.display = 'none'; reset(); } }, RoundDisplay: function roundDisplay() { function playerRoundDisplay(buttonPressed) { const roundDisplay = document.getElementById('round-container').firstElementChild; const buttonPressedChildElement = buttonPressed.childNodes[0]; const newButtonElement = document.createElement('button'); newButtonElement.classList.add('round-display-buttons'); newButtonElement.disabled = true; const newButtonIcon = document.createElement('I'); newButtonIcon.setAttribute('class', buttonPressedChildElement.getAttribute('class')); newButtonElement.appendChild(newButtonIcon); roundDisplay.appendChild(newButtonElement); return newButtonElement; } function computerRoundDisplay() { const rockIconFAString = "far fa-hand-rock"; const paperIconFAString = "far fa-hand-paper"; const scissorsIconFAString = "far fa-hand-scissors"; const roundDisplay = document.getElementById('round-container').lastElementChild; const newButtonElement = document.createElement('button'); newButtonElement.classList.add('round-display-buttons'); newButtonElement.disabled = true; const newButtonIcon = document.createElement('I'); switch (computerMoves[round]) { case Moves.ROCK: newButtonIcon.setAttribute('class', rockIconFAString); break; case Moves.PAPER: newButtonIcon.setAttribute('class', paperIconFAString); break; case Moves.SCISSORS: newButtonIcon.setAttribute('class', scissorsIconFAString); break; } newButtonElement.appendChild(newButtonIcon); roundDisplay.appendChild(newButtonElement); } if (round > 0) { resetDisplay(); } playerRoundDisplay(this); computerRoundDisplay(); } }; }; const GameFunctions = Game(); document.getElementById("rock-btn").addEventListener("click", GameFunctions.RoundDisplay); document.getElementById("paper-btn").addEventListener("click", GameFunctions.RoundDisplay); document.getElementById("scissors-btn").addEventListener("click", GameFunctions.RoundDisplay); document.getElementById("rock-btn").addEventListener("click", () => { GameFunctions.GameRound(Moves.ROCK); }); document.getElementById("paper-btn").addEventListener("click", () => { GameFunctions.GameRound(Moves.PAPER); }); document.getElementById("scissors-btn").addEventListener("click", () => { GameFunctions.GameRound(Moves.SCISSORS); });
import FlassMessageComponent from "../components/Utils/FlashMessageComponent"; const flashMessage = ({mensaje, success,}) => { const e = success==='success' ? "success" : "error"; return <> <FlassMessageComponent success={e} message={mensaje} /> </>; }; //este es el que tenemos que importar en el main export default flashMessage;
const config = { apiKey: "AIzaSyBr5RBcisx9REhrM5htQneuaZ3Vjdp6w7w", authDomain: "chegadisso-1570f.firebaseapp.com", databaseURL: "https://chegadisso-1570f.firebaseio.com", projectId: "chegadisso-1570f", storageBucket: "chegadisso-1570f.appspot.com", messagingSenderId: "810528454904" }; export default config;
var email, pas; var user = localStorage.getItem("auth"); function getINFO() { email = document.getElementById("email").value; pas = document.getElementById("passs").value; console.log(email + " \n" + pas); if (email == "" && pas == "") { alert("please enter all the fields .. "); } else { localStorage.setItem("emaill", email); localStorage.setItem("pass", pas); } } function onload() { document.getElementById("signup").style.display = "none"; } function show() { document.getElementById("signup").style.display = "block"; window.location = "#signup"; } function check() { var email2 = document.getElementById("email1").value; var pas2 = document.getElementById("passs1").value; var checkemail = localStorage.getItem("emaill"); var checkpass = localStorage.getItem("pass"); if (email2 == checkemail && pas2 == checkpass) { alert("congrats !!!!@!!!!!"); // window.open("landing.html"); // document.getElementById("land").innerText="WELCOME + "+ email2 ; } else { alert("username or password is not correct !!! "); } } function display() { // alert("hello"); document.getElementById("land1").innerText = "WELCOME " + localStorage.getItem("emaill").toUpperCase(); } function signup() { var checkUSER = false; var usersOBJ = { emailID: document.getElementById("email").value, passW: document.getElementById("passs").value }; if (user === null) { user = []; } else { user = JSON.parse(user); } for (var i = 0; i < user.length; i++) { if (user[i].emailID === document.getElementById("email").value) { checkUSER = true; } } if (checkUSER === true) { alert("user already exist !"); } else { user.push(usersOBJ); user = JSON.stringify(user); localStorage.setItem("auth", user); document.getElementById("email").value = ""; document.getElementById("passs").value = ""; alert(" registerd user !!"); window.location = "index.html"; } } function check2() { if (user === null) { alert("please register yourself first"); } else { user = JSON.parse(user); } for (var i = 0; i < user.length; i++) { if ( user[i].emailID === document.getElementById("email1").value && user[i].passW == document.getElementById("passs1").value ) { alert("congrats !!!!@!!!!!"); // window.location = "homepage.html"; } } }
import { inputFormattedTimestamp, formattedTaskDate, msTimestamp, msToTimer, msToFormattedTime, } from "../date"; describe(inputFormattedTimestamp, () => { it("should return a correctly formatted date and time", () => { expect(inputFormattedTimestamp(1627888212118)).toEqual("2021-08-02 17:10"); }); it("should return only the date when passed true as second argument", () => { expect(inputFormattedTimestamp(1627888212118, true)).toEqual("2021-08-02"); }); }); describe(formattedTaskDate, () => { it("should formate a postgreSQL timestamp to a user friendly format", () => { expect(formattedTaskDate("2021-08-01 09:23:45.609001000 +0000")).toEqual( "SUN 01 AUG" ); }); }); describe(msTimestamp, () => { it("should return a unix UTC timestamp for a date", () => { expect(msTimestamp("2021-08-02 17:10")).toEqual(1627888200000); }); }); describe(msToTimer, () => { it("should return a formatted timer given a millisecond timestamp", () => { expect(msToTimer(3600000)).toEqual("01:00:00"); expect(msToTimer(3600000 - 1000)).toEqual("00:59:59"); }); }); describe(msToFormattedTime, () => { it("should return a formatted time given a millisecond timestamp", () => { expect(msToFormattedTime(3600000)).toEqual("1 hr"); expect(msToFormattedTime(3600000 - 1000)).toEqual("59 mins & 59 secs"); expect(msToFormattedTime(3600000 + 61000)).toEqual("1 hr, 1 min & 1 sec"); expect(msToFormattedTime(3600000 + 62000)).toEqual("1 hr, 1 min & 2 secs"); expect(msToFormattedTime(7200000 + 122000)).toEqual( "2 hrs, 2 mins & 2 secs" ); }); });
#pragma strict var ballSpeed : float = 100; function Start () { yield WaitForSeconds(2); GoBall(); } function Update() { var xVel : float = GetComponent.<Rigidbody2D>().velocity.x; if (xVel < 18 && xVel > -18 && xVel != 0) { if (xVel > 0) { GetComponent.<Rigidbody2D>().velocity.x = 20; } else { GetComponent.<Rigidbody2D>().velocity.x = -20; } } } function OnCollisionEnter2D (colInfo : Collision2D){ if (colInfo.collider.tag == "Player") { GetComponent.<Rigidbody2D>().velocity.y = GetComponent.<Rigidbody2D>().velocity.y + colInfo.collider.GetComponent.<Rigidbody2D>().velocity.y/3; GetComponent.<AudioSource>().pitch = Random.Range(0.8f, 1.2f); GetComponent.<AudioSource>().Play(); } } function ResetBall () { GetComponent.<Rigidbody2D>().velocity.y = 0; GetComponent.<Rigidbody2D>().velocity.x = 0; transform.position.x = 0; transform.position.y = 0; yield WaitForSeconds (0.5); GoBall(); } function GoBall() { var randomNumber = Random.Range(0, 2); if (randomNumber <= 0.5) { GetComponent.<Rigidbody2D>().AddForce (new Vector2 (ballSpeed, 10)); } else { GetComponent.<Rigidbody2D>().AddForce (new Vector2 (-ballSpeed, -10)); } }
import * as Yup from 'yup'; export const LoginSchema = Yup.object().shape({ email: Yup.string() .email('Invalid email') .required('Required'), password: Yup.string() .min(8, 'Password is too short - 8 chars minimum') .required('Password is required') }); export const RegisterSchema = Yup.object().shape({ email: Yup.string() .email('Invalid email') .required('Email is required'), password: Yup.string() .min(8, 'Password is too short - 8 chars minimum') .required('Password is required') .matches(/^(?=.*\d)(?=.*[a-z])[\w~@#$%^&*+=`|{}:;!.?\"()\[\]-]{8,25}$/, 'Password must contain at least 1 number'), name: Yup.string() .strict() .min(2, 'Name too short - 2 chars minimum') .required('Name is required'), lastName: Yup.string() .strict() .min(2, 'Last name too short - 2 chars minimum') .required('Last name is required') }); export const CreateNamespaceSchema = Yup.object().shape({ name: Yup.string() .min(2, 'Namespace name is too short - 2 chars minimum') .required('Namespace name is required'), isPrivate: Yup.bool(), password: Yup.string().min(3, 'Password is too short - 3 chars minimum') }); export const SearchByIDNamespaceSchema = Yup.object().shape({ namespaceID: Yup.string() .min(20, 'Namespace ID is too short - 20 chars minimum') .required('One of this fields is required') }); export const SearchByNameNamespaceSchema = Yup.object().shape({ namespaceName: Yup.string() .min(2, 'Namespace name is too short - 2 chars minimum') .required('One of this fields is required') }); export const CreateRoomSchema = Yup.object().shape({ name: Yup.string() .min(2, 'Room name is too short - 2 chars minimum') .required('Room name is required'), description: Yup.string().required('Room description is required') });
'use strict'; /* Controllers */ // Simulation controller app.controller('SimulationCtrl', ['$scope','$state','$timeout','getHttp', function($scope,$state,$timeout,getHttp) { var now = new Date(); $scope.sim = { hitcard: {cardid:23}, setuptime: now, screenIds:['egm', 'drscreen', 'systeminfo', 'progressive', 'advertisement', 'virtualglass','bigwin'], logOptions: ['info','debug'], loggerOptions: ['debug', 'verbose', 'normal' ] }; $scope.submitData = function(f){ var string = ''; if(f == 'hitcard'){ string = $scope.sim.hitcard.cardid; } if(f == 'startrolldice'){ } if(f == 'rolldiceresult'){ string = $scope.sim.rolldiceresult.numHits; } if(f == 'bigwinhit'){ string = $scope.sim.bigwinhit.amount; } if(f == 'logsmibas'){ string = $scope.settings.logsmibas; } if(f == 'setmastervolume'){ string = $scope.settings.setmastervolume; } if(f == 'setactivestream'){ for (var key in $scope.settings.setactivestream) { if ($scope.settings.setactivestream.hasOwnProperty(key)) { if($scope.settings.setactivestream[key] != ''){ string += $scope.settings.setactivestream[key]+'_'; } } } } var call = f+string.replace(/_(?=[^_]*$)/, ''); if(f == 'logger'){ call = $scope.settings.logger; } getHttp.async(call).then(function(d) { if(d.data.indexOf('ERROR') >= 0){ addAlert("danger",d.data); } else { addAlert("success","Success: " + f); } }); } // managing alerts $scope.alerts = []; function addAlert(type,msg) { $scope.alerts.push({type: type, msg: msg}); $timeout(function() { $scope.alerts.splice($scope.alerts.indexOf(alert), 1); }, 5000); }; $scope.closeAlert = function(index) { $scope.alerts.splice(index, 1); }; }]);
angular .module("iCanHelp", ["ui.bootstrap", 'ngRoute']) .config(['$routeProvider',function ($routeProvider) { return [ $routeProvider.when('/', { templateUrl: 'app/home/index/index.html', controller: 'home.indexController', controllerAs: 'contr' }), $routeProvider.when('/account/login/:email?', { templateUrl: 'app/account/login/login.html', controller: "account.loginController" }), $routeProvider.when('/account/register', { templateUrl: 'app/account/register/register.html', controller: "account.registerController", controllerAs: 'contr' }) ]; }]); 'use strict'; angular.module('iCanHelp') // Declare an http interceptor that will signal the start and end of each request .config(['$httpProvider', function ($httpProvider) { var $http, interceptor = ['$q', '$injector', function ($q, $injector) { var notificationChannel; var response = function(resp) { // get $http via $injector because of circular dependency problem $http = $http || $injector.get('$http'); // don't send notification until all requests are complete if ($http.pendingRequests.length < 1) { // get requestNotificationChannel via $injector because of circular dependency problem notificationChannel = notificationChannel || $injector.get('requestNotificationChannel'); // send a notification requests are complete notificationChannel.requestEnded(); } return resp; }; var responseError = function(resp) { // get $http via $injector because of circular dependency problem $http = $http || $injector.get('$http'); // don't send notification until all requests are complete if ($http.pendingRequests.length < 1) { // get requestNotificationChannel via $injector because of circular dependency problem notificationChannel = notificationChannel || $injector.get('requestNotificationChannel'); // send a notification requests are complete notificationChannel.requestEnded(); } return $q.reject(resp); }; var request = function (resp) { // get requestNotificationChannel via $injector because of circular dependency problem notificationChannel = notificationChannel || $injector.get('requestNotificationChannel'); // send a notification requests are complete notificationChannel.requestStarted(); return resp; }; return { response: response, responseError: responseError, request: request }; }]; $httpProvider.interceptors.push(interceptor); }]) // declare the notification pub/sub channel .factory('requestNotificationChannel', ['$rootScope', function ($rootScope) { // private notification messages var _START_REQUEST_ = '_START_REQUEST_'; var _END_REQUEST_ = '_END_REQUEST_'; // publish start request notification var requestStarted = function () { $rootScope.$broadcast(_START_REQUEST_); }; // publish end request notification var requestEnded = function () { $rootScope.$broadcast(_END_REQUEST_); }; // subscribe to start request notification var onRequestStarted = function ($scope, handler) { $scope.$on(_START_REQUEST_, function (event) { handler(); }); }; // subscribe to end request notification var onRequestEnded = function ($scope, handler) { $scope.$on(_END_REQUEST_, function (event) { handler(); }); }; return { requestStarted: requestStarted, requestEnded: requestEnded, onRequestStarted: onRequestStarted, onRequestEnded: onRequestEnded }; }]) // declare the directive that will show and hide the loading widget .directive('loadingWidget', ['requestNotificationChannel', function (requestNotificationChannel) { return { restrict: "A", link: function (scope, element) { // hide the element initially element.addClass('ng-hide'); var startRequestHandler = function () { // got the request start notification, show the element element.removeClass('ng-hide'); }; var endRequestHandler = function () { // got the request start notification, show the element element.addClass('ng-hide'); }; // register for the request start notification requestNotificationChannel.onRequestStarted(scope, startRequestHandler); // register for the request end notification requestNotificationChannel.onRequestEnded(scope, endRequestHandler); } }; }]); angular.module('iCanHelp') .directive('emailUnique', function () { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attr, ctrl) { ctrl.$parsers.push(function (viewValue) { // set it to true here, otherwise it will not // clear out when previous validators fail. ctrl.$setValidity('uniqueEmail', true); if (ctrl.$valid) { // set it to false here, because if we need to check // the validity of the email, it's invalid until the // AJAX responds. ctrl.$setValidity('checkingEmail', false); // now do your thing, chicken wing. if (viewValue !== "" && typeof viewValue !== "undefined") { $http.get('/api/account/emailUnique/' + viewValue).success(function () { ctrl.$setValidity('uniqueEmail', true); ctrl.$setValidity('checkingEmail', true); }).error(function () { ctrl.$setValidity('uniqueEmail', false); ctrl.$setValidity('checkingEmail', true); }); } else { ctrl.$setValidity('uniqueEmail', false); ctrl.$setValidity('checkingEmail', true); } } return viewValue; }); } } }); angular.module("iCanHelp") .service('initDataProvider', ['$window', function ($window) { function getDataScopeFromWindow(name) { var data = $window[name]; return data; } function copyDataPropertyToObject(sourceName, targetObject, property) { var data = getDataScopeFromWindow(sourceName); for (var prop in data) { if (data.hasOwnProperty(prop) && prop === property) { targetObject[prop] = data[prop]; } } } function copyDataToObject(sourceName, targetObject) { var data = getDataScopeFromWindow(sourceName); for (var prop in data) { if (data.hasOwnProperty(prop)) { targetObject[prop] = data[prop]; } } } return { copyDataToObject: copyDataToObject, getDataScopeFromWindow: getDataScopeFromWindow, copyDataPropertyToObject: copyDataPropertyToObject }; }]) angular.module('iCanHelp') .factory('messageBus', ['$rootScope', function ($rootScope) { var msgBus = {}; msgBus.emitMsg = function (msg, data) { data = data || {}; $rootScope.$emit(msg, data); }; msgBus.onMsg = function (msg, func, scope) { var unbind = $rootScope.$on(msg, func); if (scope) { scope.$on('$destroy', unbind); } }; return msgBus; }]); angular.module('iCanHelp') .controller('userPanelController', [ 'initDataProvider', 'messageBus', '$scope', '$timeout', function (provider, messageBus, $scope, $timeout) { provider.copyDataToObject("userPanelData", $scope); messageBus.onMsg("user.login", function (event, email) { $scope.email = email; $scope.isAuthenticated = true; }); } ]); angular.module('iCanHelp') .service('account.service', ['$http', '$q', '$timeout' , function ($http, $q, $timeout) { this.$http = $http; this.$q = $q; this.register = function (email, password) { var defer = $q.defer(); var model = { email: email, password: password }; $http.post('/api/account/register/', model).success(function () { defer.resolve(); }).error(function (data) { defer.reject(data); }); return defer.promise; }; this.login = function (email, password) { var defer = $q.defer(); $timeout(function() { var model = { email: email, password: password }; $http.post('/api/account/login/', model).success(function(authToken) { defer.resolve(authToken); }).error(function(error) { defer.reject(error); }); }); return defer.promise; }; } ]) angular.module('iCanHelp') .controller('account.loginController', [ '$scope', '$location', '$routeParams', 'messageBus', 'account.service', function ($scope, $location, $routeParams,messageBus, service) { $scope.password = ""; $scope.error = ""; $scope.email = $routeParams.email; $scope.submit = function () { service.login($scope.email, $scope.password) .then($scope.loginSuccess, $scope.loginError); }; $scope.loginSuccess = function (reponse) { var authCookie = "_ncfa=" + reponse.authToken + ";"; document.cookie = authCookie; messageBus.emitMsg("user.login", $scope.email); $location.path("/"); }; $scope.loginError = function (error) { $scope.error = error.message; }; } ]); angular.module('iCanHelp') .controller('account.registerController', [ '$location', '$routeParams', 'account.service', function ($location, $routeParams, service) { this.service = service; this.email = ""; this.password = ""; this.error = ""; this.submit = function () { service.register(email, password).then(registerSuccess, registerError); }; this.registerSuccess = function () { this.error = ""; $location.path("/account/login/" + email); }; this.registerError = function (error) { this.error = error; }; }]); angular.module("iCanHelp") .controller("home.indexController", function() { this.heading = "Fajny nagłówek"; });
var Marketplace = artifacts.require("Marketplace"); var Warehouse = artifacts.require("Warehouse"); module.exports = function(deployer) { deployer.deploy(Warehouse); deployer.link(Warehouse, Marketplace); deployer.deploy(Marketplace); }
const add = require( "../index.js" ).add; QUnit.module( "add", () => { QUnit.test( "two numbers", assert => { assert.equal( add( 1, 2 ), 3 ); } ); } );
var React = require('react') var expect = require('chai').expect var App = require('../../src/components/App.jsx') var enzyme = require('enzyme') var shallow = enzyme.shallow var Adapter = require('enzyme-adapter-react-16') enzyme.configure({ adapter: new Adapter() }) describe('<App />', function() { it('runs successfully', function(done) { var wrapper = shallow(<App />) expect(wrapper.find('span')).to.have.length(1) done() }) })
(function(){ var cop21 = window.cop21 || (window.cop21 = {}); cop21.sankey = function(){ var height = 600, width = 600, delRadius = 6, delPadding = 2, tabRadius = 20, allTablesMap, currentStep, margin = {top: 5, right: 5, bottom: 5, left: 5}, showLabel = true; function sankey(selection){ selection.each(function(data){ var chart; var viz; var legend; var marginLegend = 20; var units = "Delegations"; var formatNumber = d3.format(",.0f"), // zero decimal places format = function(d) { return formatNumber(d) + " " + units; }, color = d3.scale.category20(); var linkG; var currentSteps = [currentStep-1, currentStep]; var chartWidth = width - margin.left - margin.right, chartHeight = height - margin.top - margin.bottom; if (selection.select('svg').empty()){ chart = selection.append('svg') .attr('width', width) .attr('height', height) .append("g") .attr('width', chartWidth) .attr('height', chartHeight) .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); if(currentStep){ legend = chart.append('g') .attr('class', 'legend') legend.append('circle') .attr('r', 8) .attr('fill', 'none') .attr('stroke', 'white') .attr('stroke-width', 1) .attr('cx', 5) .attr('cy', 8) legend.append('circle') .attr('r', 8) .attr('fill', 'none') .attr('stroke', 'white') .attr('stroke-width', 1) .attr('cx', chartWidth-5) .attr('cy', 8) legend.append('line') .attr('x1', 13) .attr('y1', 8) .attr('x2', chartWidth-13) .attr('y2', 8) .attr('stroke', 'white') .attr('stroke-width', 1) legend.append('text') .attr('text-anchor', 'middle') .attr('fill', 'white') .attr('class', 'stepLeft') .attr('x', 5) .attr('y', 8) .attr('dy', '3px') legend.append('text') .attr('text-anchor', 'middle') .attr('fill', 'white') .attr('class', 'stepRight') .attr('x', chartWidth-5) .attr('y', 8) .attr('dy', '3px') } viz = chart.append('g') .attr("transform", "translate(0," + marginLegend +")") .attr('class', 'sanviz') linkG = viz.append('g').attr('class','linkG'); } else { chart = selection.select('svg') .attr('width', width) .attr('height', height) .select("g") .attr('width', chartWidth) .attr('height', chartHeight) .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); legend = chart.select('.legend'); viz = chart.select('.sanviz') linkG = viz.select('.linkG'); } if(currentStep){ var stepLeft = legend.select('.stepLeft').text(currentSteps[0]) var stepRight = legend.select('.stepRight').text(currentSteps[1]) } // Set the sankey diagram properties var sankey = d3.sankey() .nodeWidth(5) .nodePadding(2) .size([chartWidth, chartHeight-marginLegend]); var path = sankey.link(); sankey .nodes(data.nodes) .links(data.links) .layout(32); // add in the links var link = linkG.selectAll(".link") .data(data.links) link.transition().duration(500) .attr("d", path) .attr("stroke-width", function(d) { return Math.max(1, d.dy); }) .sort(function(a, b) { return b.dy - a.dy; }); link.enter().append("path") .attr("class", "link") .attr("d", path) .attr("stroke-width", function(d) { return Math.max(1, d.dy); }) .attr('stroke-opacity',0.5) .sort(function(a, b) { return b.dy - a.dy; }) link.exit().remove() // add in the nodes var node = viz.selectAll(".node") //.data(data.nodes, function(d){return d.name}) .data(data.nodes) node .each(function(d){ $(this).popover('destroy') $(this).popover({ title: allTablesMap[d.name.split('_')[0] + '_' + d.name.split('_')[1]], content:format(d.value), placement:'auto top', container: 'body', trigger: 'hover' }) }) .on('mouseover',function(d){ var name = d.name; var type = d.sourceLinks.length?'source':'target'; link.transition() .attr('stroke-opacity', 0.2) .filter(function(e){ return e[type].name == name; }).transition() .attr('stroke-opacity', 0.9) }) .on('mouseout', function(d){ link.transition() .attr('stroke-opacity', 0.5) }) .transition().duration(500) .attr("height", function(d) { return d.dy; }) .attr('x', function(d){return d.x}) .attr('y', function(d){return d.y}) node.enter().append("rect") .attr("height", function(d) {return d.dy; }) .attr("width", sankey.nodeWidth()) .attr('x', function(d){return d.x}) .attr('y', function(d){return d.y}) .attr('class', 'node') .style("fill", "white") .each(function(d){ $(this).popover('destroy') $(this).popover({ title: allTablesMap[d.name.split('_')[0] + '_' + d.name.split('_')[1]], content:format(d.value), placement:'auto top', container: 'body', trigger: 'hover' }) }) .on('mouseover',function(d){ var name = d.name; var type = d.sourceLinks.length?'source':'target'; link.transition() .attr('stroke-opacity', 0.2) .filter(function(e){ return e[type].name == name; }).transition() .attr('stroke-opacity', 0.9) }) .on('mouseout', function(d){ link.transition() .attr('stroke-opacity', 0.5) }) node.exit().remove() // add in the title for the nodes var labels = viz.selectAll(".tabLabels") //.data(data.nodes, function(d){return d.name}) .data(data.nodes) labels.exit().remove() labels.transition().duration(500) .attr("y", function(d) { return d.y + d.dy / 2; }) .text(function(d) { if(d.value >= 5){return allTablesMap[d.name.split('_')[0] + '_' + d.name.split('_')[1]]} }) .filter(function(d) { return d.x < chartWidth / 2; }) //.text(null) .text(function(d) { if(!currentStep){return allTablesMap[d.name.split('_')[0] + '_' + d.name.split('_')[1]]} else{return null;} }) //.text(function(d) { if(d.value >= 5){return allTablesMap[d.name.split('_')[0] + '_' + d.name.split('_')[1]]} }) labels.enter().append("text") .attr("x",function(d){return chartWidth -6 - sankey.nodeWidth() }) .attr("y", function(d) { return d.y + d.dy / 2; }) .attr("dy", ".35em") .attr('class', 'tabLabels') .attr("text-anchor", "end") .text(function(d) { if(d.value >= 5){return allTablesMap[d.name.split('_')[0] + '_' + d.name.split('_')[1]]} }) .filter(function(d) { return d.x < chartWidth / 2; }) .attr("x", function (d) {return d.x + 6 + sankey.nodeWidth()}) .attr("text-anchor", "start") //.text(null) //.text(function(d) { if(d.value >= 5){return allTablesMap[d.name.split('_')[0] + '_' + d.name.split('_')[1]]} }) .text(function(d) { if(!currentStep){return allTablesMap[d.name.split('_')[0] + '_' + d.name.split('_')[1]]} else{return null;} }) }); //end selection } // end sankey function tText(d){ var source = d.source.name.split("_")[1], target = d.target.name.split("_")[1]; if(source == target){ return d.value + ' delegation(s) stayed at table ' + target }else{ return d.value + ' delegation(s) moved from table ' + source + ' to table ' + target } }; sankey.height = function(x){ if (!arguments.length) return height; height = x; return sankey; } sankey.width = function(x){ if (!arguments.length) return width; width = x; return sankey; } sankey.currentStep = function(x){ if (!arguments.length) return currentStep; currentStep = x; return sankey; } sankey.showLabel = function(x){ if (!arguments.length) return showLabel; showLabel = x; return sankey; } sankey.allTablesMap = function(x){ if (!arguments.length) return allTablesMap; allTablesMap = x; return sankey; } sankey.margin = function(x){ if (!arguments.length) return margin; margin = x; return sankey; } return sankey; } })();
// you can write to stdout for debugging purposes, e.g. // console.log('this is a debug message'); function solution(S) { // write your code in JavaScript (Node.js 8.9.4) const N = S.length; const charOpen = '('; const charClose = ')'; let stack = []; for(let i=0; i<N; i++){ if(S.charAt(i) == charOpen){ stack.push(i); } if(S.charAt(i) == charClose){ if(stack.length > 0){ stack.pop(); } else{ return 0; } } } if(stack.length > 0){ return 0; } else{ return 1; } }
$(function() { $("#activityType").click(function() { $("#configRules").empty(); //var activityType = $("#CreateActivityForm input[name='activityType']").val(); var activityType = $("#activityType").val(); activityType = parseInt(activityType); var itemjs = ""; var activityHtml = null; var activityTotalHtml = null; var tokenStartHtml = "<table class='table table-striped' id='activityconfigbyid'><tbody>"; var tokenEndHtml = "</tbody></table>"; // 消费/首冲数额 var number = ""; // 道具奖励 --- 后期完善 <textarea rows="" cols=""></textarea> /* var itemlistHtml = "<textarea rows=1 cols=1 placeholder='奖励配置,格式:道具Id,数量&道具Id,数量'例:123,50&456,10" + "class='form-control' style='width:25%'" + "id='itemList' name='itemList[]'></textarea>";*/ var itemlistHtml = ""; // 领取次数 var frequency = "<input type='text' " + "class='form-control' name='frequency[]' style='width:15%' placeholder='领取次数'>"; // 排行榜类型 var rankingTypeHtml = "<select name='type[]'>" + "<option value=0>--请选择排行榜类型--</option>" + "<option value=1>通关指定副本一定次数</option>" + "<option value=2>竞技场排名达到多少名</option>" + "<option value=3>指定小游戏参与一定次数</option>" + "<option value=4>石中剑抽取一定次数</option>" + "<option value=5>技能升级一定次数 </option>" + "<option value=6>拥有一定数量好友</option>" + "<option value=7>某个品质装备达到一定星数有一定数量 </option>" + "<option value=8>表情包拥有一定数量 </option>" + "<option value=9>扭蛋机抽取一定次数</option>" + "<option value=10>整蛊玩家一定次数</option></select>"; // 区间 var IntervalHtml = "<input type='text' " + "class='form-control' name='IntervalStart[]' style='width:15%'>&nbsp至 &nbsp" + "<input type='text' class='form-control' " + "name='IntervalEnd[]' style='width:15%'>"; // 描述 var bewriteHtml = "<input type='text'" + "class='form-control' name='NodeBewrite[]' style='width:15%' placeholder='描述'>"; // 小游戏类型 var gameTypeHtml = "<select name='type[]'>" + "<option value=0>--请选择--</option>" + "<option value=1>无下限</option>" + "<option value=2>跳楼侠</option>" + "<option value=3>大战三侠镇</option>" + "</select> " // 任务类型 get ajax 返回获取类型 var taskTypeHtml ="<select name='type[]'>" + "<option value=0>--请选择--</option>" + "<option value=101>等级排行榜</option>" + "<option value=102>杀人排行榜</option>" + "<option value=103>富豪排行榜</option>" + "<option value=104>竞技场排行榜</option>" + "</select>" var trStartHtml = "<tr>" + "<td><div class='control-group'>" + "<label class='control-label'>活动有效期时间/关闭时间</label>" + "<label class='checkbox-inline'><div class='controls'>"; var trEndHtml = "</div></label></div></td><td></td></tr>"; switch(activityType) { case 1: // 首冲 number = "<input type='text' " + "class='form-control' name='number[]' style='width:15%' placeholder='首冲条件数额'>"; activityHtml=number+"&nbsp&nbsp"+bewriteHtml+"&nbsp&nbsp"; activityTotalHtml = setConditionalRules(activityHtml,12,frequency); $("#configRules").append(activityTotalHtml); break; case 2: // 每日单笔充值类 number = "<input type='text' " + "class='form-control' name='number[]' style='width:15%' placeholder='每日单笔充值类数额'>"; activityHtml=number+"&nbsp&nbsp"+bewriteHtml+"&nbsp&nbsp"+ itemlistHtml+"&nbsp;&nbsp;"; activityTotalHtml = setConditionalRules(activityHtml,12,frequency); //alert(activityTotalHtml); $("#configRules").append(activityTotalHtml); break; case 3: // 每日累积充值类 number = "<input type='text' " + "class='form-control' name='number[]' style='width:15%' placeholder='每日累积充值类数额'>"; activityHtml=number+"&nbsp&nbsp"+bewriteHtml+"&nbsp&nbsp"+ itemlistHtml+"&nbsp;&nbsp;"; activityTotalHtml = setConditionalRules(activityHtml,12,frequency); //alert(activityTotalHtml); $("#configRules").append(activityTotalHtml); break; case 4: // 多日累积充值类 number = "<input type='text' " + "class='form-control' name='number[]' style='width:15%' placeholder='多日累积充值类数额'>"; activityHtml=number+"&nbsp&nbsp"+bewriteHtml+"&nbsp&nbsp"+ itemlistHtml+"&nbsp;&nbsp;"; activityTotalHtml = setConditionalRules(activityHtml,12,frequency); //alert(activityTotalHtml); $("#configRules").append(activityTotalHtml); break; case 5: // 每日累积消费类 number = "<input type='text' " + "class='form-control' name='number[]' style='width:15%' placeholder='每日累积消费类数额'>"; activityHtml=number+"&nbsp&nbsp"+bewriteHtml+"&nbsp&nbsp"+ itemlistHtml+"&nbsp;&nbsp;"; activityTotalHtml = setConditionalRules(activityHtml,12,frequency); //alert(activityTotalHtml); $("#configRules").append(activityTotalHtml); break; case 6: // 多日累积消费类 number = "<input type='text' " + "class='form-control' name='number[]' style='width:15%' placeholder='多日累积消费类数额'>"; activityHtml=number+"&nbsp&nbsp"+bewriteHtml+"&nbsp&nbsp"+ itemlistHtml+"&nbsp;&nbsp;"; activityTotalHtml = setConditionalRules(activityHtml,12,frequency); //alert(activityTotalHtml); $("#configRules").append(activityTotalHtml); break; case 7: IntervalHtml = "<input type='text' " + "class='form-control' name='IntervalStart[]' style='width:15%' placeholder='榜单开始区间'>&nbsp至 &nbsp" + "<input type='text' class='form-control' " + "name='IntervalEnd[]' style='width:15%' placeholder='榜单截止区间'>"; // 冲榜类 activityHtml=taskTypeHtml+"&nbsp&nbsp"+bewriteHtml+"&nbsp&nbsp"+IntervalHtml+"&nbsp&nbsp"+ itemlistHtml+"&nbsp;&nbsp;"; activityTotalHtml = setConditionalRules(activityHtml,12,frequency); //alert(activityTotalHtml); $("#configRules").append(activityTotalHtml); break; case 8: // 等级类 number = "<input type='text' " + "class='form-control' name='number[]' style='width:15%' placeholder='所到达等级'>"; activityHtml=number+"&nbsp&nbsp"+bewriteHtml+"&nbsp&nbsp"+ itemlistHtml+"&nbsp;&nbsp;"; activityTotalHtml = setConditionalRules(activityHtml,12,frequency); //alert(activityTotalHtml); $("#configRules").append(activityTotalHtml); break; case 9: // 任务目标类 IntervalHtml = "<input type='text' " + "class='form-control' name='IntervalStart[]' style='width:15%' placeholder='等级开始区间'>&nbsp至 &nbsp" + "<input type='text' class='form-control' " + "name='IntervalEnd[]' style='width:15%' placeholder='等级截止区间'>"; number = "<input type='text' " + "class='form-control' name='number[]' style='width:15%' placeholder='任务目标数额'>"; activityHtml=rankingTypeHtml+"&nbsp&nbsp"+bewriteHtml+"&nbsp&nbsp"+number+"&nbsp&nbsp"+ itemlistHtml+"&nbsp;&nbsp;"; activityTotalHtml = setConditionalRules(activityHtml,12,frequency); //alert(activityTotalHtml); $("#configRules").append(activityTotalHtml); break; case 10: // 小游戏榜单 IntervalHtml = "<input type='text' " + "class='form-control' name='IntervalStart[]' style='width:15%' placeholder='小游戏榜单开始区间'>&nbsp至 &nbsp" + "<input type='text' class='form-control' " + "name='IntervalEnd[]' style='width:15%' placeholder='小游戏榜单截止区间'>"; number = "<input type='text' " + "class='form-control' name='number[]' style='width:15%' placeholder='任务目标数额'>"; activityHtml=gameTypeHtml+"&nbsp&nbsp"+bewriteHtml+"&nbsp&nbsp"+IntervalHtml+"&nbsp&nbsp"+ itemlistHtml+"&nbsp;&nbsp;"; activityTotalHtml = setConditionalRules(activityHtml,12,frequency); //alert(activityTotalHtml); $("#configRules").append(activityTotalHtml); break; case 11: // 日累积整蛊类 IntervalHtml = "<input type='text' " + "class='form-control' name='IntervalStart[]' style='width:15%' placeholder='小游戏榜单开始区间'>&nbsp至 &nbsp" + "<input type='text' class='form-control' " + "name='IntervalEnd[]' style='width:15%' placeholder='小游戏榜单截止区间'>"; number = "<input type='text' " + "class='form-control' name='number[]' style='width:15%' placeholder='任务目标数额'>"; activityHtml=gameTypeHtml+"&nbsp&nbsp"+bewriteHtml+"&nbsp&nbsp"+IntervalHtml+"&nbsp&nbsp"+ itemlistHtml+"&nbsp;&nbsp;"; activityTotalHtml = setConditionalRules(activityHtml,12,frequency); //alert(activityTotalHtml); $("#configRules").append(activityTotalHtml); break; default:break;return false; } $("#activityconfigbyid tr td ").each(function(){ var _this = $(this); _this.find("#edititeminfo").click(function() { var itemTypeVal = $(this).attr("add-data-item-val"); $("#ItemListForm [name=itemOptionBtn]").val(itemTypeVal); $("#addloginNoticeModal").modal({backdrop:"static"}).modal('show'); }); }); }); $("#Globactivitybtn").click(function() { var form = $("#CreateActivityForm").serializeArray(); $.ajax({ type: 'POST', url: "SetActivity", data: form, dataType: 'json', success: function(result) { alert(result.msg); if (result.errcode == 0) { //window.location.href = '/Mail/'; } }, error:function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(errorThrown); alert(textStatus); // paser error; } }); }); $("#activityListTable tr").each(function() { var _this = $(this); // 删除 _this.find(".delactivity").click(function() { var id = $(this).attr('data-value'); var serverId = $(this).attr('data-server-id'); if (confirm("你确定要把活动编号为"+id+"删除么?")) { // var id = '{"id":'+id+'}'; $.ajax({ type:'POST', url:'delActivity', data:'id='+id+'&serverId='+serverId, dataType:'json', success:function(result){ alert(result.msg); if(result.errcode == 0){ window.location.href = window.location.href; } }, error:function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(errorThrown); alert(textStatus); // paser error; } }); } }); // 编辑 _this.find(".editActivityBtn").click(function() { var id = $(this).attr('data-value'); alert(id); var form = $("#activityEditForm").serializeArray(); for(var i=0;i<form.length;i++){ var name = form[i].name; if(name ==null ||name =="") { continue; } $("#activityEditForm [name=activityId]").val(id); } $("#activityEditForm").submit(); }); // 发布 _this.find(".ReleaseActivityBtn").click(function() { var id = $(this).attr('data-value'); var serverId = $(this).attr('data-server-id'); if (confirm("你确定要把活动编号为"+id+"进行发布么?")) { // var id = '{"id":'+id+'}'; $.ajax({ type:'POST', url:'ReleaseActivity', data:'id='+id, dataType:'json', success:function(result){ alert(result.msg); if(result.errcode == 0){ window.location.href = window.location.href; } }, error:function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(errorThrown); alert(textStatus); // paser error; } }); } }); // 请求数据 _this.find(".serverInfo").click(function() { var form = $("#serverInfoForm").serializeArray(); for(var i=0;i<form.length;i++){ var name = form[i].name; if(name ==null ||name =="") { continue; } var value = $(this).parent().parent().find('[data-name='+name+']').text(); $("#serverInfoForm [name=RequestData]").val(value); } $("#serverinfoModal").modal({backdrop:"static"}).modal('show'); }); }); // 批量活动发布 $("#addactivityBtn").click(function(){ var form = $("#ReleaseAvtivityForm").serializeArray(); if (confirm("你确定要发布已选的活动么?")) { $.ajax({ type:'POST', url:'ReleaseActivity', data:form, dataType:'json', success:function(result){ alert(result.msg); if(result.errcode == 0){ window.location.href = window.location.href; } }, error:function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(errorThrown); alert(textStatus); // paser error; } }); } });}); function setConditionalRules(htmlinfo,amount,itemjs) { var trStartHtml = ""; var htmllist = ""; var tokenStartHtml = "<table class='table table-striped' id='activityconfigbyid'><tbody>"; var tokenEndHtml = "</tbody></table>"; var trEndHtml = "</div></label></div></td></tr>"; var html = ""; var termCheckHtml =""; var addItemHtml = ""; for(var i=1;i<=amount;i++) { termCheckHtml = '<input type="checkbox" id="term'+i+'"value="term'+i+'" name="checkbox[]" style="margin:0px;padding:0px"/>&nbsp;'; trStartHtml = "<tr id='activityBytr"+i+"'>" + "<td><div class='control-group' style='margin:0px;padding:0px'>" + "<label class='control-label'>条件"+i+"&nbsp;&nbsp;"+termCheckHtml+"</label>" + "<label class='checkbox-inline'><div class='controls'>"; addItemHtml = "<a class='btn' title='添加道具' " + "id='edititeminfo' add-data-item-val='itemList"+i+"'>添加道具</a>&nbsp;&nbsp;"; var itemlistHtml = "<textarea rows=1 cols=1 " + "placeholder='奖励配置,格式:道具Id,数量&道具Id,数量'例:123,50&456,10" + "class='form-control' style='width:15%'" + "id='itemList"+i+"' name='itemList[]'></textarea>&nbsp;&nbsp;"; html=trStartHtml+htmlinfo+addItemHtml+itemlistHtml+itemjs+trEndHtml; htmllist+=html; } return tokenStartHtml+htmllist+tokenEndHtml; } function optionVerify(byid,name,type){ var count=$("#"+byid+" option").length; var name =name+'[]'; for(var i=0;i<count;i++) { var optionstr = $("#"+byid).find('select[name="'+name+'"]').get(0).options[i].value; optionstr = parseInt(optionstr); if(optionstr == type) { $("#"+byid).find('select[name="'+name+'"]').get(0).options[i].selected = true; break; } } } function optionVerifySet(byid=null,type=null,display=false,serverId=null) { var count=$("#"+byid+" option").length; for(var i=0;i<count;i++) { var optionstr = $("#"+byid).get(0).options[i].value; if(optionstr == type) { $("#"+byid).get(0).options[i].selected = true; break; } } if(byid=='ServerId') { $("#ServerId").prepend("<option value="+type+">"+type+"区</option>"); } }
export function getMargin(routeName) { let screenMargin = 0; if( routeName== 'EmailLogin' || routeName== 'Join' || routeName== 'Login' || routeName== 'PassWord' || routeName== 'PWChange' || routeName== 'BabyPlus' || routeName== 'BabyPlus_my' ) { screenMargin = 40; } else if(routeName== 'BabyAlergy' || routeName== 'Detail' || routeName== 'Review' || routeName== 'Reply' || routeName== 'TalkDetail' || routeName== 'PostDetail' ) { screenMargin = 32; } else if( routeName == 'Main' ) { screenMargin = 14; } return screenMargin; };
const app = getApp(); const util = require('../../utils/util.js') Page({ data: { showTost: false, customer_name: '', credit: '', contact: '', phone: '', address: '', price: '', order_no: [], title: '', isValid: false, popErrorMsg: '', myInvoice: {}, userInfo: {}, token: '', invoice_content: '' }, // 开票说明 toInvoiceIntro: function () { wx.navigateTo({ url: '../invoiceIntro/invoiceIntro', }) }, //提交按钮 drawSub: function () { this.toValidParm(); if (this.data.isValid) { this.setData({ showTost: true, }) } }, // 取消 optCancel: function () { this.setData({ showTost: false }) }, // 提交发票 optBtn: function () { let token = wx.getStorageSync('token'); this.setData({ showTost: false }) let obj = { customer_name: this.data.customer_name, credit: this.data.credit, content: this.data.invoice_content, price: this.data.price, contact: this.data.contact, phone: this.data.phone, address: this.data.address, order_no: this.data.order_no } wx.request({ url: `${util.apiPath}/FE/InvoiceManage/addInvoice`, method: "POST", data: obj, header: { 'session-token': token, }, success: res => { if (res.data.code == 200) { wx.redirectTo({ url: '../invoiceList/invoiceList', }) } else { wx.showToast({ title: '开票失败', mask: true, duration: 2000, success: function () { setTimeout(function () { wx.navigateBack({ delta: 2 }) }, 1500) } }) } } }) }, // 存储信息 orderItemValue: function (e) { let self = this; let name = e.target.dataset.name this.data[name] = e.detail.value; this.setData({ ...self.data }) }, // 获取地址 getLocation: function () { let _this = this wx.chooseLocation({ success: function (e) { _this.setData({ address: e.address }) } }) }, // 验证信息 toValidParm: function () { var _this = this; var title = '' title = !_this.data.customer_name ? '请填写发票抬头' : !_this.data.credit ? '请填写信用代码' : !_this.data.contact ? '请填写收件人' : !_this.data.phone ? '请填写手机号' : (_this.data.phone && !/^[1][3,4,5,7,8][0-9]{9}$/.test(_this.data.phone)) ? '手机号码格式不正确' : !_this.data.address ? '请填写当前位置' : '' _this.setData({ 'isValid': title ? false : true, 'popErrorMsg': title }) if (title) { _this.ohShitfadeOut(); } }, ohShitfadeOut: function () { var fadeOutTimeout = setTimeout(() => { this.setData({ popErrorMsg: '', isValid: true }); clearTimeout(fadeOutTimeout); }, 1200); }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { let self = this; let token = wx.getStorageSync('token'); let order_no = wx.getStorageSync('order_no').split(','); this.setData({ price: options.price, userInfo: app.globalData.userInfo, order_no: order_no, customer_name: app.globalData.customer_name, credit: app.globalData.memeberInfo.credit }) wx.request({ url: `${util.apiPath}/FE/InvoiceManage/invoiceContent`, method: "GET", header: { 'session-token': token, }, success: function (res) { if (res.data.code == 200) { self.setData({ invoice_content: res.data.results }) } } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
//Variable global var globalFEN=[] function initialize(){ $.get("saved_games", function(data){ for (i=0; i<data.length ; i++){ //Agrego los FENs a la variable global globalFEN.push( data[i].fen ) //Agrego las secciones necesarias usando D3 console.log(data[i].fen.split(" ")) var paneles = d3.select("#paneles").append("div").attr("class","panel panel-default") var body = paneles.append("div").attr("class","panel-body") .attr("id","panel-body-"+String(i)+"-"+String(data[i].game_id)) var rows = body.append("div").attr("class","row") //Sección para dibujar la imagen var cols1 = rows.append("div").attr("class","col-xs-5" ) var divs = cols1.append("div").attr("id","svg"+ String(i) ) .attr("class","svg-img") //Convierto a objeto el string del svg img = $(data[i].svg); //Obtengo el div que va a guardar las imagenes svg var svg = document.getElementById("svg"+ String(i)) //Limpio si ya tienen info svg.innerHTML=""; //Agrego imagen SVG svg.appendChild(img[0]); //Modifico el tamaño de la imagen var img_r = d3.selectAll("svg") img_r.attr("height",400) img_r.attr("width",400) //Escribir la info de texto var cols2 = rows.append("div").attr("class","col-xs-4 col-xs-offset-1") //Escribir H var h_text = cols2.append("h2").attr("class","h-paneles") h_text.text("Game Slot #"+ String(i+1) ) var br0 = cols2.append("br").attr("class","p-br") //Escribir Ps var p1 = cols2.append("p").attr("class","p-label").text("FEN del juego:") var li1 = cols2.append("li").attr("class","p-li").text(data[i].fen) var br1 = cols2.append("br").attr("class","p-br") var p3 = cols2.append("p").attr("class","p-label").text("Jugador a mover:") var prox_jugador = data[i].fen.split(" ")[1] var li3 = cols2.append("li").attr("class","p-li").text(prox_jugador); var br3 = cols2.append("br").attr("class","p-br") var p2 = cols2.append("p").attr("class","p-label").text("Turno:") var prox_turno = data[i].fen.split(" ")[ data[i].fen.split(" ").length-1 ] if( prox_jugador=="b" ){ prox_turno = String( (parseInt( prox_turno )*2)-1 ) } else{ prox_turno= String( (parseInt(prox_turno)*2)-2 ) } var li2 = cols2.append("li").attr("class","p-li").text(prox_turno); var br2 = cols2.append("br").attr("class","p-br") var p4 = cols2.append("p").attr("class","p-label").text("Id del juego:") var li3 = cols2.append("li").attr("class","p-li").text(data[i].game_id) var br3 = cols2.append("br").attr("class","p-br") } //Una vez cargada la página obtengo una lista de todos los paneles var list_panels = document.getElementsByClassName("panel-body"); //A todos los paneles les agrego un event listener for (var i = 0; i < list_panels.length; i++) { list_panels[i].addEventListener('click', panelClick, false); } }); } function panelClick(){ //Levantar bandera en servidor para indicar que hay juego cargado //Obtengo el FEN del panel sobre el cual se hizo click fen= globalFEN[ parseInt( this.id.split("-")[2]) ] game_id = this.id.split("-",)[3] console.log(this.id) console.log(game_id) $.get("load_game",{fen:fen,game_id:game_id},function(data){ window.location.href = "/svg_test" }); } initialize();
var LinkedList = require('../linkedlist').SinglyLinkedList; var nthToLast = require('../02_nth_to_last').nthToLast; var expect = require('chai').expect; describe("LinkedList", function() { describe("#nthToLast", function() { var ll; before(function() { ll = new LinkedList(); ll.insert("one"); ll.insert("two"); ll.insert("three"); ll.insert("four"); }); describe("zero-th node to last element", function() { it("should return null", function() { expect(nthToLast(ll.head, 0)).to.be.null; }); }); describe("first node to last element", function() { it("should return last node", function() { expect(nthToLast(ll.head, 1).value).to.equal("four"); }); }); describe("nth node to last element where n = size of LinkedList", function() { it("should return first node to the first element", function() { expect(nthToLast(ll.head, 4).value).to.equal("one"); }); }); describe("(n + 1)th node to the last element where n = size of LinkedList", function() { it("should return SentinelNode head", function() { expect(nthToLast(ll.head, 5).value).to.be.null; }); }); }); });
import React from "react"; import "./App.css"; import { NavLink, Switch, Route } from "react-router-dom"; import GetApi from "./GetApi"; import SkillBar from "react-skillbars"; import styled from "styled-components"; import SimpleLoadingBar from "react-simple-loading-bar"; const skills = [ { type: "css", level: 79 }, { type: "Javascript", level: 75 }, { type: "HTML", level: 80 } ]; const ContentWrap = styled.div` display: flex; flex-direction: column; align-content: center; -webkit-box-align: center; align-items: center; -webkit-box-pack: center; justify-content: center; min-height: calc(100vh - 60px); width: 100%; background: transparent; padding: 40px 0px; animation: fades 2.5s; `; const ProjectContentPic = styled.img` position: relative; min-width: 400px; min-height:400px; width: 40%; overflow: hidden; margin: 5px 6px; border-radius: 10px; `; const ProjectContent = styled.div` display: flex; -webkit-box-align: center; align-items: center; align-content: center; -webkit-box-pack: center; justify-content: center; flex-wrap: wrap; width: 60%; overflow: hidden; padding: 30px 0px; `; const ProfilePicture = styled.img` height: 15rem; width: 15rem; margin: 0 auto; animation: fades 2.5s; transition: 1.5s; border-radius: 30% 30% 30%; z-index: 1; `; const Appskillbars = styled.div` padding-top: 6%; padding-bottom: 1%; margin: 0 auto; height: 10%; width: 100%; animation: fades 1.5s; `; const HomeText = styled.div` width: 100%; display: flex; flex-direction: column; justify-content: center; align-items:center; margin: 0 auto; animation: fades 1.5s; p { text-align:center; width:50%; font-weight:500; font-size:1.5rem; } `; const Ptag = styled.div` font-size: 20px; width: 80%; display: flex; margin: 0 auto; flex-direction: column; line-height: 2rem; border: 1px black; animation: fades 1.5s; `; const SocialMedia = styled.div` display: flex; justify-content: center; animation: fades 1.5s; a { font-size: 4rem; color: black; padding: 1%; } `; const Oldportfolio = styled.div` position: absolute; border: 2px solid black; animation: fades 1.5s; @media (max-width: 768px) { width: 35%; position: relative; margin-top: 5%; margin-left: 33%; } a { color: black; } `; const App = props => ( <div className="app"> <Oldportfolio> {" "} <a href="www.edwardkumerius.com">Checkout my first portfolio! </a> </Oldportfolio> <GetApi height={20} /> <SimpleLoadingBar height={20} /> <Navigation {...props} /> <Main {...props} /> </div> ); const Navigation = ({}) => ( <nav> <ul> <li> <NavLink activeClassName="current" exact to="/"> Home </NavLink> </li> <li> <NavLink activeClassName="current" to="/about"> About </NavLink> </li> <li> <NavLink activeClassName="current" to="/contact"> Contact </NavLink> </li> <li> <NavLink activeClassName="current" to="/projects"> My projects </NavLink> </li> </ul> </nav> ); const Home = props => ( <div className="home"> <HomeText> <ProfilePicture src={require("./assets/cool.jpg")} alt="profile-picture" /> <p> Mitt namn är Edward Kumerius och jag brinner för webbutveckling. Jag studerar till frontend-utvecklare på KYH samtidigt som jag extra jobbar som IT/Webbansvarig på ett litet catering företag. </p> </HomeText> <SocialMedia> <a href="https://www.facebook.com/edward.kumerius"> <i class="fab fa-facebook p-i" /> </a> <a href="https://www.instagram.com/"> <i class="fab fa-instagram p-i" /> </a> <a href="https://github.com/Eddyking1"> <i class="fab fa-git-square p-i" /> </a> </SocialMedia> </div> ); const About = ({ nick }) => ( <div className="about"> <h1>About {nick ? nick : "nobody"}</h1> <Ptag> <p1> {" "} Hello, my name is {nick ? nick : "nobody"} and I'm a 21 year old frontend-developer and i love it! </p1> <p1> {" "} When I was younger I came to the conclusion that I love technology and I wanted to get involved with it. </p1> <p1> {" "} I have always loved to tinker with computers and exploring different functionalities on the largest operating systems as Mac OS, Windows OS and last but not least linux OS. </p1> <p1> {" "} By just tinkering and solving my own computer issues I learned everything I know today. I learnd how to solve the problems I encountered by searching for the solutions instead of just turn it in to a repair shop.{" "} </p1> <p1> {" "} So how did I get into programming? I always thought being a coder is something that I wanted to do as I grew up, along the way I met several people that had experience with programming in "c++" so i learned code by those people. </p1> <p1> {" "} A friend of mine could write code with me on my computer with a program called teamviewer, as he guided me through my first "hello world" projekt and thats how I fell for coding with the endless possibilities that you could do with code.{" "} </p1> <p1> I have a passion for webdesign and javascript functionality. </p1> <p1> {" "} I live in Stockholm with my family. During my freetime I enjoy playing video games, working out and spending time with my girlfriend.{" "} </p1> </Ptag> <Appskillbars> {" "} <SkillBar skills={skills} height={20} />{" "} </Appskillbars> <SocialMedia> <a href="https://www.facebook.com/edward.kumerius"> <i class="fab fa-facebook p-i" /> </a> <a href="https://www.instagram.com/"> <i class="fab fa-instagram p-i" /> </a> <a href="https://github.com/Eddyking1"> <i class="fab fa-git-square p-i" /> </a> </SocialMedia> </div> ); const Contact = props => ( <div className="contact"> <h1>Services Me</h1> <h2>Name Edward Kumerius </h2> <h2>Telefone: 0763370509 </h2> <h2> Email: <strong>{props ? props.email : "edward.kumerius@kyh.se"}</strong> </h2> <SocialMedia> <a href="https://www.facebook.com/edward.kumerius"> <i class="fab fa-facebook p-i" /> </a> <a href="https://www.instagram.com/"> <i class="fab fa-instagram p-i" /> </a> <a href="https://github.com/Eddyking1"> <i class="fab fa-git-square p-i" /> </a> </SocialMedia> </div> ); const Projects = props => ( <ContentWrap> <ProjectContent> <ProjectContentPic src={require("./assets/tokyoC.png")} alt="profile-picture" /> <ProjectContentPic src={require("./assets/originalPortfolio.png")} alt="profile-picture" /> <ProjectContentPic src={require("./assets/Rpage.png")} alt="profile-picture" /> <ProjectContentPic src={require("./assets/matbitenC.png")} alt="profile-picture" /> </ProjectContent> </ContentWrap> ); const Main = props => ( <Switch> <Route exact path="/" render={routeProps => <Home {...routeProps} {...props} />} /> <Route exact path="/about" render={routeProps => <About {...routeProps} {...props} />} /> <Route exact path="/contact" render={routeProps => <Contact {...routeProps} {...props} />} /> <Route exact path="/projects" render={routeProps => <Projects {...routeProps} {...props} />} /> </Switch> ); export default App;
var myApp = angular.module('myApp', []); myApp.controller('myController', ['$scope', '$http', function($scope, $http){ $scope.clicked = false; $scope.scary = false; $scope.notFound = false; $scope.scaryThing = ''; $scope.requestedMovie = ''; $scope.lookUpMovie = function () { $scope.clicked = true; var query = { query: { bool: { must: $scope.requestedMovie.split(/\s+/).map(function (word) { return {term: {title: word.toLowerCase()}}; }) } } }; var searchPath = "http://localhost:9200/movies/movies/_search"; $http.post(searchPath, query). success(function(data, status, headers, config) { if (data.hits.hits.length > 0) { $scope.notFound = false; var re = new RegExp($scope.scaryThing, "gi"); $scope.scary = data.hits.hits[0]._source.keywords.some(function (keyword) { return keyword.search(re) != -1; } ); $scope.returnedMovie = data.hits.hits[0]._source.title; $scope.returnedKeyword = $scope.scaryThing + "s"; } else { $scope.notFound = true; } }). error(function(data, status, headers, config) { // no-op }).finally(function () { // $scope.scaryThing = ''; // $scope.requestedMovie = ''; }); } }]); //clear form after query //fix: false positive if no keyword is selected
import React, { useCallback } from "react"; import Counter from "./Counter"; import { useSelector, useDispatch, useStore } from "react-redux"; const INCREMENT = "counter2/INCREMENT"; const DECREMENT = "counter2/DECREMENT"; const CounterContainer = props => { const counter = useSelector(state => state.counter2); const dispatch = useDispatch(); const decreaseCounter = useCallback(() => { dispatch({ type: DECREMENT }); }, [dispatch]); const increaseCounter = useCallback(() => { dispatch({ type: INCREMENT }); }, [dispatch]); //같은 프로바이더 안에 있는 리덕스 스토어 레퍼런스를 리턴함 //아마 useSelector 위주로 사용하게 될것임. //하지만 가아끔 스토어에 접근해야하는 경우, 리듀서 교체를 해야하는 경우에만 쓰인다. const store = useStore(); // EXAMPLE ONLY! Do not do this in a real app. // The component will not automatically update if the store state changes // 진짜 앱에선 이렇게 쓰지 말기. // 스토어에 변화가 일어나도 컴포넌트가 자동으로 업데이트 안함. console.log("store", store.getState()); console.log("counter", counter); return ( <> <Counter number={counter} //이렇게 하는 방법도 있지만 useCallback를 쓰는 걸 추천한다. 리덕스는 // onDecrease={() => dispatch({ type: DECREMENT })} onDecrease={decreaseCounter} onIncrease={increaseCounter} /> </> ); }; export default CounterContainer;
//@flow import _ from 'lodash'; export function isEveryChildChecked(node: Object, nodes: Object, props: Object) { const { childrenKey } = props; let children = null; if (node[childrenKey]) { children = node[childrenKey].filter( child => nodes[child.refKey] && !nodes[child.refKey].uncheckable ); if (!children.length) { return nodes[node.refKey].check; } return children.every((child: Object) => { if (child[childrenKey] && child[childrenKey].length) { return isEveryChildChecked(child, nodes, props); } return nodes[child.refKey].check; }); } return nodes[node.refKey].check; } export function isSomeChildChecked(node: Object, nodes: Object, props: Object) { const { childrenKey } = props; if (!node[childrenKey]) { return false; } return node[childrenKey].some((child: Object) => { if (nodes[child.refKey] && nodes[child.refKey].check) { return true; } return isSomeChildChecked(child, nodes, props); }); } /** * 判断第一层节点是否存在有children的节点 * @param {*} data */ export function isSomeNodeHasChildren(data: any[], childrenKey: string) { return data.some((node: Object) => node[childrenKey]); } /** * 获取每个节点的最顶层父节点的check值 * @param {*} nodes * @param {*} node */ export function getTopParentNodeCheckState(nodes: Object, node: Object) { if (node.parentNode) { return getTopParentNodeCheckState(nodes, node.parentNode); } return nodes[node.refKey].check; } /** * 获取该节点的兄弟节点是否都为 uncheckable * @param {*} node */ export function getSiblingNodeUncheckable(node: Object, nodes: Object) { const list = []; const parentNodeRefkey = node.parentNode ? node.parentNode.refKey : ''; Object.keys(nodes).forEach((refKey: string) => { const curNode = nodes[refKey]; if (_.isUndefined(node.parentNode) && _.isUndefined(curNode.parentNode)) { list.push(curNode); } else if (curNode.parentNode && curNode.parentNode.refKey === parentNodeRefkey) { list.push(curNode); } }); return list.every(node => node.uncheckable); }
const express = require('express'); const path = require('path'); const parser = require('body-parser'); const server = express(); const urlParser = parser.urlencoded({extended: false}); server.get("/reg", urlParser, (req, res) => { res.sendFile(__dirname + "/pik/index.html"); }); server.post("/reg", urlParser,(req, res) => { res.send(`${req.body.info}`) console.log(req.body); }); server.listen(8000);
import { forwardRef } from "react"; import { TableCell, TableFooter, TableRow } from "@material-ui/core"; import MaterialTable, { MTableBody } from "material-table"; //Material UI table import { AddBox, ArrowDownward, Check, ChevronLeft, ChevronRight, Clear, DeleteOutline, Edit, FilterList, FirstPage, LastPage, Remove, SaveAlt, Search, ViewColumn } from "@material-ui/icons"; const tableIcons = { Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />), Check: forwardRef((props, ref) => <Check {...props} ref={ref} />), Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />), Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />), DetailPanel: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />), Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />), Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />), Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />), FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />), LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />), NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />), PreviousPage: forwardRef((props, ref) => <ChevronLeft {...props} ref={ref} />), ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />), Search: forwardRef((props, ref) => <Search {...props} ref={ref} />), SortArrow: forwardRef((props, ref) => <ArrowDownward {...props} ref={ref} />), ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />), ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />) }; const Table = ({characterDetails, spinner}) => { return ( <div> <MaterialTable icons={tableIcons} isLoading={spinner} columns={[ { title: "Name", field: "name" }, { title: "Gender",field: "gender", lookup: { "male": "M", "female": "F", "n/a": "N/A" } }, { title: "Height", field: "height"} ]} data={characterDetails} title="Star wars characters" components={{ Body: (props) => ( <> <MTableBody {...props} /> <TableFooter> <TableRow> <TableCell colSpan={2}><h5 className="font-weight-bold">Total: {characterDetails?.length}</h5></TableCell> <TableCell colSpan={2}><h5 className="font-weight-bold">Total: {characterDetails?.reduce(function(prev, current) {return prev + +current.height }, 0)}</h5></TableCell> </TableRow> </TableFooter> </> ) }} /> </div> ) } export default Table
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classes from './ProjectCard.module.css'; import Dropdown from '../../Dropdown/Dropdown'; import { languageHelper } from '../../../../../../tool/language-helper'; const translation = [ { name: '名称', begin: '开始日期', end: '结束日期', note: '说明', }, { name: 'Name', begin: 'Begin', end: 'End', note: 'Note', }, ]; const text = translation[languageHelper()]; class projectCard extends Component { constructor(props) { super(props); this.state = { editing: this.props.data ? false : true, // eslint-disable-line proData: this.props.data // eslint-disable-line ? { id: this.props.data.id, // eslint-disable-line name: this.props.data.name, // eslint-disable-line role: this.props.data.role, // eslint-disable-line duration: { begin: this.props.data.duration.begin.substring(0, 10), // eslint-disable-line end: this.props.data.duration.end.substring(0, 10), // eslint-disable-line }, note: this.props.data.note, // eslint-disable-line } : { id: '', name: '', role: '', duration: { begin: '', end: '', }, note: '', }, }; this.nameRef = React.createRef(); this.beginRef = React.createRef(); this.endRef = React.createRef(); this.noteRef = React.createRef(); } // this method only toggle 'editing' editHandler = () => { this.setState({ editing: true }); }; // tell parent the id of the current card deleteHandler = () => { if (this.state.proData.id) { this.props.deleteHandler(this.state.proData.id); // eslint-disable-line } else { this.props.cancel(); } }; saveHandler = () => { this.setState({ ...this.state, editing: false, }); if (this.state.proData.id) { // console.log(`id to delete is ${this.state.proData.id}`); this.props.saveHandler( this.state.proData, this.state.proData.id, 'update' ); // eslint-disable-line } else { this.props.saveHandler(this.state.proData, null, "add"); // eslint-disable-line } }; inputOnChange = () => { this.setState({ ...this.state, proData: { ...this.state.proData, name: this.nameRef.current.value, duration: { begin: this.beginRef.current.value, end: this.endRef.current.value, }, note: this.noteRef.current.value, }, }); }; render() { let toShow = ( <div className={classes.ProjectCard}> <input disabled type="text" value={this.state.proData.name ? this.state.proData.name : ''} /> <div className={classes.twoP}> <p> {this.state.proData.duration.begin} -{' '} {this.state.proData.duration.end} </p> </div> <input style={{ margin: '15px 0px 3px 0px' }} disabled type="text" value={this.state.proData.note ? this.state.proData.note : ''} /> <Dropdown delete={this.deleteHandler} edit={this.editHandler} /> </div> ); if (this.state.editing) { toShow = ( <div className={classes.ProjectCard}> <input type="text" value={this.state.proData.name ? this.state.proData.name : ''} ref={this.nameRef} placeholder={text.name} onChange={this.inputOnChange} /> <input type="text" value={ this.state.proData.duration.begin ? this.state.proData.duration.begin : '' } ref={this.beginRef} placeholder={text.begin} onChange={this.inputOnChange} /> <input type="text" value={ this.state.proData.duration.end ? this.state.proData.duration.end : '' } ref={this.endRef} placeholder={text.end} onChange={this.inputOnChange} /> <input type="text" value={this.state.proData.note ? this.state.proData.note : ''} ref={this.noteRef} placeholder={text.note} onChange={this.inputOnChange} /> <Dropdown delete={this.deleteHandler} edit={this.editHandler} editing save={this.saveHandler} /> </div> ); } return toShow; } } projectCard.propTypes = { cancel: PropTypes.func, data: PropTypes.object.isRequired, saveHandler: PropTypes.func.isRequired, }; export default projectCard;
"use strict"; const questionList = [ { letter: "a", answer: ["antivirus", "actualizar", "amazon"], status: 0, question: [ "Programas que permiten analizar la memoria, las unidades de disco y otros elementos de un ordenador, en busca de virus.", "En un entrono virtual, reemplazar información por considerarse antigua o no válida", "Compañía creada por Jeff Bezos en 1994", ], }, { letter: "b", answer: ["bit", "blog", "backup"], status: 0, question: [ "Unidad mínima de información empleada en la informática y en las telecomunicaciones", "Sitio web similiar a un diario personal online, cuyas entradas o artículos publicados se denominan post", "Hacer copia de seguridad.", ], }, { letter: "c", answer: ["conexion", "comprimir", "cracker"], status: 0, question: [ "Enlace que se establece entre el emisor y el receptor a través del que se envía el mensaje", "Reducir el peso de un archivo para que ocupe menos espacio sin perder la información original", "Es una persona interesada en saltarse la seguridad de un sistema informático.", ], }, { letter: "d", answer: ["directorio", "digital", "dom"], status: 0, question: [ "Tipo de buscador", "Contrario a analógico", "Estructura de objetos que genera el navegador cuando se carga un documento y se puede alterar mediante Javascript para cambiar dinámicamente los contenidos y aspecto de la página.", ], }, { letter: "e", answer: ["ebay", "encriptar", "extension"], status: 0, question: [ "Sitio de subastas por internet más popular en el mundo.", "Proteger archivos expresando su contenido en un lenguaje cifrado", "Cadena de caracteres anexado al nombre de un archivo usualmente precedido de un punto", ], }, { letter: "f", answer: ["facebook", "fakenews", "firewall"], status: 0, question: [ "Red social creada por Mark Zuckerberg en 2006", "Bulos o noticias falsas en la red", "Su traducción literal es muro de fuego, también conocido a nivel técnico como cortafuegos.", ], }, { letter: "g", answer: ["gift", "gigaherzt", "gusano"], status: 0, question: [ "Formato de imagen digital usado para crear animaciones cortas que se reproducen en bucle", "1000 megahertz", "Es un programa similar a un virus que, a diferencia de éste, solamente realiza copias de sí mismo, o de partes de él. En ingles Worm.", ], }, { letter: "h", answer: ["hacker", "hardware", "harmonyos"], status: 0, question: [ "Pirata informático", "Componentes físicos de un PC.", "Nombre del sistema operativo de Huawei", ], }, { letter: "i", answer: ["internet", "intel", "ip"], status: 0, question: [ "Red informática de nivel mundial que utiliza la línea telefónica para transmitir la información", "Primera empresa de procesadores.", "Direccion única e irrepetible que se asigna a un dispositivo que trata de comunicarse con otro en Internet", ], }, { letter: "j", answer: ["jpg", "joke", "javascript"], status: 0, question: [ "Formato de imagen más popular con gran grado de compresión.", "No es un virus, sino bromas de mal gusto que tienen por objeto hacer pensar a los usuarios que han sido afectados por un virus.", "Lenguaje de programación interpretado, dialecto del estándar ECMAScript. Se define como orientado a objetos, ​ basado en prototipos, imperativo, débilmente tipado y dinámico.", ], }, { letter: "k", answer: ["kindle", "keylogger", "key"], status: 0, question: [ "Tableta diseñada por Amazon.com como la versión multimedia del lector de libros electrónicos", "Programa que recoge y guarda una lista de todas las teclas pulsadas por un usuario. Dicho programa puede hacer pública la lista, permitiendo que terceras personas conozcan los datos escritos por el usuario afectado", "Tecla, en su uso más general, o bien, por extensión, el teclado.", ], }, { letter: "l", answer: ["link", "linux", "lcd"], status: 0, question: [ "Elemento de un documento electrónico que permite acceder automáticamente a otro documento o a otra parte del mismo.", "Sistema operativo gratuito para PC derivado de Unix", "Monitor de Cristal Líquido.", ], }, { letter: "m", answer: ["microsoft", "malware", "meme"], status: 0, question: [ "Fundada en 1975 por Bill Gates, entre otros.", "Cualquier programa, documento o mensaje, susceptible de causar perjuicios a los usuarios de sistemas informáticos. MALicious softWARE.", "Imagen, video o texto, por lo general distorsionado con fines caricaturescos que se difunde principalmente a través de Internet", ], }, { letter: "n", answer: ["navegador", "netiqueta", "nuke"], status: 0, question: [ "Software informático que permite acceder a internet", "Norma o regla que tengo que cumplir para no generar conflictos cuando me comunico en la red", "Caída o pérdida de la conexión de red, provocada de forma intencionada por alguna persona.", ], }, { letter: "o", answer: ["open source", "offline", "ocr"], status: 0, question: [ "Expresión de la lengua inglesa que pertenece al ámbito de la informática. Aunque puede traducirse como fuente abierta o código abierto", "Modo en el que trabajo cuando no tengo Internet", "Reconocimiento óptico de caracteres.", ], }, { letter: "p", answer: ["perfil", "programar", "podcast"], status: 0, question: [ "He de crearme uno para acceder por primera vez a mi red social favorita", "Dar instrucciones a un dispositivo digital para que realice una tarea en un momento determinado", "Emisión de radio o de televisión que un usuario puede descargar de internet mediante una suscripción previa y escucharla tanto en una computadora como en un reproductor portátil.", ], }, { letter: "q", answer: ["qr", "quicktime", "quick access"], status: 0, question: [ "Código de barras de 2D compuesto por módulos negros en forma de cuadrado con fondo blanco", "Formato de video creado por Apple.", "Acceso rápido en ingles.", ], }, { letter: "r", answer: ["recomendar", "ram", "robo de identidad"], status: 0, question: [ "En LinkedIn, dar un like", "Memoria de acceso aleatorio.", "Obtención de información confidencial del usuario, como contraseñas de acceso a diferentes servicios, con el fin de que personas no autorizadas puedan utilizarla para suplantar al usuario afectado.", ], }, { letter: "s", answer: ["serie", "selfie", "servidor"], status: 0, question: [ "Cuando los componentes de un circuito están dispuestos en una línea, uno tras otro, se dice que hay una conexión en...", "Autofoto", "Ordenador conectado a la red que presta asistencia a otros usuarios", ], }, { letter: "t", answer: ["tutor", "teclado", "troyano"], status: 0, question: [ "Persona que resuelve mis dudas sobre el curso online que estoy haciendo", "Dispositivo principal de entrada en PC.", "Programa que llega al ordenador de manera encubierta, aparentando ser inofensivo, se instala y realiza determinadas acciones que afectan a la confidencialidad del usuario afectado.", ], }, { letter: "u", answer: ["ubicacion", "ubuntu", "url"], status: 0, question: [ "La comparto cuando quiero decir dónde estoy", "Distribución de Linux más famosa basada en Debian.", "Dirección a través de la cual se accede a las páginas Web en Internet", ], }, { letter: "v", answer: ["viral", "visical", "virus"], status: 0, question: [ "Acepción referida a un mensaje o contenido que se difunde con gran rápidez a través de las redes sociales", "Primera hoja de cálculo", "Programas que se pueden introducir en los ordenadores y sistemas informáticos de formas muy diversas, produciendo efectos molestos, nocivos e incluso destructivos e irreparables.", ], }, { letter: "w", answer: ["wallapop", "webinar", "wav"], status: 0, question: [ "Empresa española fundada en el año 2013, que ofrece una plataforma dedicada a la compra venta de productos de segunda mano entre usuarios a través de Internet", "Conferencia o seminario en formato online que se transmite en directo a través de una herramienta especializada", "Extensión de tipo de formato de sonido con muy poca o nula compresión.", ], }, { letter: "x", answer: ["xeon", "xml", "xxi"], status: 0, question: [ "Familia de microprocesadores Intel para servidores PC y Macintosh", "Lenguaje de Marcado Extensible o Lenguaje de Marcas Extensible, metalenguaje que permite definir lenguajes de marcas", "Siglo actual dónde la computadora parece que estuvo toda la vida y ahora nos parece imposible vivir sin tecnología", ], }, { letter: "y", answer: ["youtuber", "yahoo", "yosemite"], status: 0, question: [ "Profesion de moda entre los más pequeños que consiste en grabar videos y subirlos su canal en una plataforma online, para conseguir el mayor numero de visitas posible", "Empresa global de medios con sede en Estados Unidos que posee un portal de Internet, un directorio web y una serie de servicios tales como el popular correo electrónico", "Undécima versión de OS X, el sistema operativo de Apple para los ordenadores Macintosh.", ], }, { letter: "z", answer: ["zoom", "zettabyte", "zombie"], status: 0, question: [ "Aplicación que utilizo cuando teletrabajo para reunirme con mis compañeros de equipo", "Unidad de almacenamiento de información equivale a 1021 bytes, cuyo prefijo fue adoptado en 1991, viene del latín septem, que significa siete", "Ordenador conectado a la red que ha sido comprometido por un hacker, un virus informático o un troyano. Puede ser utilizado para realizar distintas tareas maliciosas de forma remota", ], }, ]; const menuSection = document.getElementById("menu-section"); const menuSectionOption = document.querySelectorAll("#menu-section ul li"); const playSection = document.getElementById("play-section"); const ruleSection = document.getElementById("rule-section"); const rankingSection = document.getElementById("ranking-section"); const startPlaying = document.querySelector(".startBtn"); const letters = document.querySelectorAll("[data-letter]"); const exitGame = document.getElementById("exit"); const letter = [] menuSectionOption.forEach((button) => { button.addEventListener("click", function (x) { const option = x.target.textContent if (option === "JUGAR") { menuSection.style.display = "none"; startPlaying.style.display = "flex"; } if (option === "¿COMO JUGAR?") { menuSection.style.display = "none"; ruleSection.style.display = "flex"; } if (option === "RANKINGS") { } }) }); startPlaying.addEventListener("click", () => { startPlaying.style.display = "none"; document.querySelector(".playing").style.display = "flex" startGame() countdownTime() }) function startGame() { for (let x = 0; x < letters.length; x++) { letter.push(letters[x].textContent) } } function countdownTime() { let secondsRemaining = document.querySelector(".countdown").textContent; let countdown = setInterval(() => { secondsRemaining--; document.querySelector(".countdown").textContent = secondsRemaining; if (secondsRemaining < 15) { document.querySelector(".countdown").style.color = "red"; } if (secondsRemaining <= 0) { clearInterval(countdown); } }, 1000); }
import React from "react"; import clsx from "clsx"; import { createStyles, makeStyles } from "@material-ui/core/styles"; import UserIcon from "../../assets/svgJs/UserIcon"; import Typography from "@material-ui/core/Typography"; import useIsTrackSwitchedOff from "../Hooks/useIsTrackSwitchedOff"; import usePublications from "../Hooks/usePublications"; import useTrack from "../Hooks/useTrack"; import useParticipantIsReconnecting from "../Hooks/useParticipantIsReconnecting"; const useStyles = makeStyles((theme) => createStyles({ container: { position: "relative", display: "flex", alignItems: "center", height: "100%", overflow: "hidden", "& video": { filter: "none", objectFit: "cover !important", }, borderRadius: "8px", background: "black", }, innerContainer: { position: "absolute", top: 0, left: 0, width: "100%", height: "100%", }, infoContainer: { position: "absolute", zIndex: 2, display: "flex", flexDirection: "column", justifyContent: "space-between", height: "100%", width: "100%", background: "transparent", top: 0, }, avatarContainer: { display: "flex", alignItems: "center", justifyContent: "center", background: "black", position: "absolute", top: 0, right: 0, bottom: 0, left: 0, zIndex: 1, [theme.breakpoints.down("sm")]: { "& svg": { transform: "scale(0.7)", }, }, }, reconnectingContainer: { position: "absolute", top: 0, right: 0, bottom: 0, left: 0, display: "flex", alignItems: "center", justifyContent: "center", background: "rgba(40, 42, 43, 0.75)", zIndex: 1, }, screenShareIconContainer: { background: "rgba(0, 0, 0, 0.5)", padding: "0.18em 0.3em", marginRight: "0.3em", display: "flex", "& path": { fill: "white", }, }, identity: { background: "rgba(0, 0, 0, 0.5)", color: "white", padding: "0.18em 0.3em", margin: 0, display: "flex", alignItems: "center", }, infoRowBottom: { display: "flex", justifyContent: "space-between", position: "absolute", bottom: 0, left: 0, }, typeography: { color: "white", [theme.breakpoints.down("sm")]: { fontSize: "0.75rem", }, }, hideParticipant: { display: "block", }, cursorPointer: { cursor: "pointer", }, }) ); export default function ParticipantInfo({ participant, onClick, isSelected, children, isLocalParticipant, hideParticipant, }) { const publications = usePublications(participant); const videoPublication = publications.find((p) => p.trackName.includes("camera") ); const isVideoEnabled = Boolean(videoPublication); const videoTrack = useTrack(videoPublication); const isVideoSwitchedOff = useIsTrackSwitchedOff(videoTrack); const isParticipantReconnecting = useParticipantIsReconnecting(participant); const classes = useStyles(); return ( <div className={clsx(classes.container, { [classes.hideParticipant]: hideParticipant, [classes.cursorPointer]: Boolean(onClick), })} onClick={onClick} data-cy-participant={participant.identity} > <div className={classes.innerContainer}> {(!isVideoEnabled || isVideoSwitchedOff) && ( <div className={classes.avatarContainer}> <div style={{ display: "flex", color: "white", flexDirection: "column", }} > <UserIcon width={30} height={30} fill="#fff" /> <p>{participant.identity}</p> </div> </div> )} {isParticipantReconnecting && ( <div className={classes.reconnectingContainer}> <Typography variant="body1" className={classes.typeography}> Reconnecting... </Typography> </div> )} {children} </div> </div> ); }
import React, { Component } from 'react' import { connect } from "react-redux"; import { Col, Row } from 'reactstrap'; import parse from 'html-react-parser'; import Stats from '../Stats' import ProductCard from '../ProductCard' import * as Contants from '../../../../_config/constants' import { selectInventory, selectShip } from 'modules/salesForm' import './SelectProduct.scss' class SelectProduct extends Component { constructor(props) { super(props) this.state = { selectedDirectShipIndex:[], inventoryIndex: [], shipIndex: [] } } componentWillMount = () => { this.setState({ inventoryIndex: this.props.inventory, shipIndex: this.props.ship }) } onSelectProduct = (selectedIndex, counts, clickType) => { const { orderType } = this.props if(orderType===1) { if (clickType === true) { let shipIndex = this.props.ship shipIndex.push(selectedIndex) this.props.onSelectShip(shipIndex) this.setState({shipIndex: shipIndex}) } else { let shipIndex = this.props.ship; var index = shipIndex.indexOf(selectedIndex); if (index !== -1) shipIndex.splice(index, 1); this.props.onSelectShip(shipIndex) this.setState({ shipIndex: shipIndex }) } } else if (orderType === 0) { if (clickType==='plus') { let inventoryIndex = this.props.inventory; inventoryIndex.push(selectedIndex); this.props.onSelectInventory(inventoryIndex) this.setState({ inventoryIndex: inventoryIndex }) } else { let inventoryIndex = this.props.inventory; var index = inventoryIndex.lastIndexOf(selectedIndex); if (index !== -1) inventoryIndex.splice(index, 1); this.props.onSelectInventory(inventoryIndex) this.setState({ inventoryIndex: inventoryIndex }) } } } _renderTopContent = (orderType) => { return ( <> <Row className="align-items-center mt-4"> <Col> <h2 className="font-weight-bold text-black">{Contants.orderType[orderType] && Contants.orderType[orderType].title}</h2> </Col> </Row> <Row className="justify-content-center mt-2"> <Col lg="9" sm="12" > <h5 className="font-weight-normal" > {Contants.orderType[orderType] && parse(Contants.orderType[orderType].detail) } </h5> </Col> </Row> </> ) } _renderProductsContent = (orderType) => { return ( <Row className="justify-content-center mt-3" > <Col sm="12" md="9" > <Row className="mx-auto"> { Contants.products.map((item, index) => { return ( <Col xs="12" sm="6" md="6" lg="4" className="mt-4" key={index}> <ProductCard onSelectProduct={this.onSelectProduct} inventory={this.state.inventoryIndex} ship={this.state.shipIndex} productIndex={item._id} data={item} type={orderType === 0 ? "multiple" : "check"} /> </Col> ) }) } </Row> </Col> </Row> ) } render() { const { orderType } = this.props; return ( <div className="text-center SelectProduct mx-auto " > { this._renderTopContent(orderType) } { this._renderProductsContent(orderType) } <Stats step={2} {...this.props} activeNextStep = { orderType === 1 ? this.state.shipIndex && this.state.shipIndex.length === 0 : orderType === 0 ? this.state.inventoryIndex && this.state.inventoryIndex.length===0: false } /> </div> ) } } const mapStateToProps = ({ salesform }) => { const { orderType, inventory, ship } = salesform; return { orderType, inventory, ship }; } const mapDispatchToProps = (dispatch) => { return { onSelectInventory: (data) => { dispatch(selectInventory(data)); }, onSelectShip: (data) => { dispatch(selectShip(data)) } } } export default connect( mapStateToProps, mapDispatchToProps )(SelectProduct);
import devConfig from './devConfig.json'; const env = process.env.APP_ENV || 'development'; const configs = { development: devConfig }; export default (() => { const config = configs[env]; config.palette = { color10: "#4E2E75", color11: "#988CA6", color12: "#604E75", color13: "#3D0F73", color14: "#200343", color20: "#AC413B", color21: "#F5CECC", color22: "#AD716E", color23: "#AA1109", color24: "#640500", color30: "#266169", color31: "#7D9396", color32: "#44656A", color33: "#075C68", color34: "#01363D", white: "#ffffff", blue0: "#f7fbfd", blue1: "#e7f7f9", blue2: "#82b3bb", blue3: "#0095b3", blue4: "#056679", blue5: "#074851" }; return config; })();
import React from 'react'; class Reactions extends React.Component{ constructor(props) { super(props) this.state = { count: 0 } this.updateReactionCount = this.updateReactionCount.bind(this); } // componentDidMount() { // this.props.fetchReactions(); // } updateReactionCount() { // if (mood === "happy") { // this.setState( prevState => { // return { // "happy": prevState["happy"]+ 1, // "sad": prevState["sad"] // } // }); // } else if (mood === "sad") { // this.setState(prevState => { // return { // "happy": prevState["happy"], // "sad": prevState["sad"] + 1 // } // }); // } this.setState( prevState => { return { count: prevState.count + 1 } }) } render() { return ( <div className="buttons-container"> <ul> <li className="button-component"> {this.state.count} <button onClick={this.updateReactionCount}>😊</button> </li> <li className="button-component"> {this.state.count} <button onClick={this.updateReactionCount}>&#128549;</button> </li> </ul> <div> {this.props.reactions} </div> </div> ); } }; export default Reactions;
import React from "react"; import { BackHandler, StyleSheet, View, Image, ScrollView, ImageBackground, TouchableOpacity, Alert, SafeAreaView, FlatList } from "react-native"; import { Container, Header, StyleProvider, Form, Item, Left, Right, Thumbnail, Title, Input, Label, Content, List, CheckBox, Body, ListItem, Text, Button, CardItem } from "native-base"; import * as COLOR_CONSTS from "../constants/color-consts"; import * as ROUTE_CONSTS from "../constants/route-consts"; import * as APP_CONSTS from "../constants/app-consts"; import * as API_CONSTS from "../constants/api-constants"; import getTheme from "../../native-base-theme/components"; import material from "../../native-base-theme/variables/platform"; import GridView from "react-native-super-grid"; import Loader from "../components/loader"; import { SearchBar } from "react-native-elements"; import AsyncStorage from "@react-native-community/async-storage"; import ImagePicker from "react-native-image-picker"; import { NavigationEvents } from "react-navigation"; import { AppEventEmitter, AppEvent } from "../components/appEventEmitter"; export default class DashboardTabScreen extends React.Component { constructor(props) { super(props); this.state = { loading: false, postTab: true, profileTab: false, contactsTab: false, courseTab: false, performanceTab: false, postTabChild: true, teamTabChild: false, userDataPost: [1, 1, 1, 1, 1, 1, 1, 1, 1], teamData: [1], postData: [], name: "Byron Price", email: "byronprice@gmail.com", occupation: "Student", number: "2 12827 9012", userData: [], usersArr: [], usersContactsArr: [], institute_title:'', thumb: "", image: "", courses: [], postcourses: [], courseId: '', userId:'', refreshCoursesSubscription: null }; this._pickImage = this._pickImage.bind(this); this.postTabSelected = this.postTabSelected.bind(this); this.profileTabSelected = this.profileTabSelected.bind(this); this.contactsTabSelected = this.contactsTabSelected.bind(this); this.performanceTabSelected = this.performanceTabSelected.bind(this); this.teamTabChildSelected = this.teamTabChildSelected.bind(this); this.postTabChildSelected = this.postTabChildSelected.bind(this); this.postDetails = this.postDetails.bind(this); this.logout = this.logout.bind(this); this.logoutApi = this.logoutApi.bind(this); this.updateProfileData = this.updateProfileData.bind(this); this.courseDetails = this.courseDetails.bind(this); this.courseTabSelected = this.courseTabSelected.bind(this); this.addCourses = this.addCourses.bind(this); this.feedCell = this.feedCell.bind(this); } componentDidMount() { this.retrieveData(); this.state.refreshCoursesSubscription = AppEventEmitter.addListener( AppEvent.RefreshDashBoardScreenCourses, () => { this.state.userData.role === 4 ? this.getStudentCourses() : this.getInstrucrorCourses(); }, null ); BackHandler.addEventListener("hardwareBackPress", this.handleBackButton); } componentWillUnmount = () => { let subscription = this.state.refreshCoursesSubscription; if (subscription != null) { AppEventEmitter.removeSubscription(subscription); } BackHandler.removeEventListener("hardwareBackPress", this.handleBackButton); }; handleBackButton() { BackHandler.exitApp(); return true; } getAllUsers(userId) { this.setState({ loading: true }); var self = this; var url = API_CONSTS.API_BASE_URL + API_CONSTS.API_INSTRUCTOR_COURSES_SELECTED + userId; fetch(url, { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: global.token } }) .then(response => { if (response.status === 200) { return response.json(); } else if (response.status === 401) { this.props.navigation.navigate("Home"); return { code: response.status, message: "Plese login again" }; } else { return { code: response.status, message: "Something went wrong " + response.status }; } }) .then(responseJson => { this.setState({ loading: false }); if (responseJson.code == 200) { this.setState({ usersArr: responseJson.body, searchArr: responseJson.body }); } }) .catch(error => { console.error(error); }); } courseDetails = async user => { // console.log("courseDetails", user); if (this.state.userData.role === 4) { await AsyncStorage.setItem(APP_CONSTS.COURSE_ID, "" + user.id); this.props.navigation.navigate("Home", { courseId: user.id }); AppEventEmitter.emit(AppEvent.RefreshHomeScreen); } else if (this.state.userData.role === 3) { await AsyncStorage.setItem(APP_CONSTS.COURSE_ID, "" + user.id); this.props.navigation.navigate("Home", { courseId: user.id }); AppEventEmitter.emit(AppEvent.RefreshHomeScreen); // this.props.navigation.navigate(ROUTE_CONSTS.COURSE_DETAIL_SCREEN,{data:user}) } }; updateSearch = search => { if (search != "") { this.setState({ search }); // console.log(search); var items = []; this.state.usersArr.filter(item => { let val = item.title.toLowerCase(); let val2 = search.toLowerCase(); if (val.indexOf(val2) !== -1) { items.push(item); this.setState({ usersArr: items }); // console.log(item); } else { this.setState({ usersArr: items }); } }); } else { this.setState({ search }); this.setState({ usersArr: this.state.searchArr }); } }; _pickImage = async () => { const options = { quality: 1.0, maxWidth: 500, maxHeight: 500, storageOptions: { skipBackup: true, path: "images", cameraRoll: true, waitUntilSaved: true } }; ImagePicker.showImagePicker(options, response => { console.log("Response = ", response); if (response.didCancel) { console.log("User cancelled photo picker"); } else if (response.error) { console.log("ImagePicker Error: ", response.error); } else if (response.customButton) { console.log("User tapped custom button: ", response.customButton); } else { var source; Platform.OS === "android" ? (source = response.uri) : (source = response.uri.replace("file://", "")); console.log(source); this.uploadeImage(source); this.setState({ avatarSource: source, loading: true }); } }); }; uploadeImage(image) { this.setState({ loading: true }); var self = this; var formData = new FormData(); formData.append("imgFile", { uri: image, name: "image.jpg", type: "image/jpeg" }); var url = API_CONSTS.API_BASE_URL + API_CONSTS.API_UPDATE_IMAGE; fetch(url, { method: "PUT", headers: { Accept: "application/json", Authorization: global.token }, body: formData }) .then(response => { if (response.status === 200) { return response.json(); } else if (response.status === 401) { this.setState({ loading: false }); this.props.navigation.pop(2); return { code: response.status, message: "Plese login again" }; // alert("Server Error! \n Status Code"+response.status) } else { return { code: response.status, message: "Something went wrong " + response.status }; } }) .then(responseJson => { console.log(responseJson); if (responseJson.code == 200) { this.setState( { loading: false, image: responseJson.body.image }, function() { this.forceUpdate(); } ); // alert(JSON.stringify(responseJson)) } else { // Alert.alert('Message',responseJson.message, [ {text: 'OK', onPress: () =>this.setState ({loading:false}, // function(){ // this.forceUpdate() // })} ]) } }) .catch(error => { console.error(error); }); } postDetails(data) { this.props.navigation.navigate(ROUTE_CONSTS.FEED_DETAILS, { data: data, userData: this.state.userData }); } getAllPost(userId = this.state.userId, courseId = this.state.courseId) { this.setState({ loading: true }); var self = this; var url = API_CONSTS.API_BASE_URL + API_CONSTS.API_GET_OWN_POST + `?userId=${userId}&courseId=${courseId}`; console.log('url', url) fetch(url, { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: global.token } }) .then(response => { if (response.status === 200) { return response.json(); } else if (response.status === 401) { this.props.navigation.pop(1); return { code: response.status, message: "Please login again" }; } else { return { code: response.status, message: "Something went wrong " + response.status }; } }) .then(responseJson => { this.setState({ loading: false }); console.log("PostData", responseJson); if (responseJson.code == 200) { console.log("123456789"); this.setState({ postData: responseJson.body }); } if (responseJson.code == 400) { this.setState({ postData: [] }) } }) .catch(error => { console.error(error); }); } retrieveData = async () => { var self = this; try { const userId = await AsyncStorage.getItem(APP_CONSTS.USER_ID); this.setState({userId: userId}) if (userId !== null && userId != undefined) { self.fetchProfileDetails(userId); self.getAllPost(userId); this.getAllUsers(userId); this.getContacts(); } else { alert("No Data"); } } catch (error) { // Error retrieving data alert(error); } }; fetchProfileDetails(userId) { var self = this; var url = API_CONSTS.API_BASE_URL + API_CONSTS.API_GET_USER_BY_ID + userId; fetch(url, { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: global.token } }) .then(response => { if (response.status === 200) { return response.json(); } else if (response.status === 401) { this.props.navigation.pop(1); return { code: response.status, message: "Plese login again" }; } else { return { code: response.status, message: "Something went wrong " + response.status }; } }) .then(responseJson => { console.log("UserInfoo", responseJson.body); if (responseJson.code == 200) { var profileData = responseJson.body; this.setState({ userData: responseJson.body, image: responseJson.body.image, institute_title: responseJson.body.institute.title, thumb: responseJson.body.institute.image, name: responseJson.body.name, email: responseJson.body.email, occupation: responseJson.body.occupation, number: responseJson.body.phoneNumber }); } if (this.state.userData.role === 4) { this.getStudentCourses(); } else if (this.state.userData.role === 3) { this.getInstrucrorCourses(); } }) .catch(error => { console.error(error); }); } updateProfileData() { if ( this.state.email == "" || this.state.name == "" || this.state.number == "" || this.state.occupation == "" ) { alert("All fields are required"); } else { this.updateProfile(); } } updateProfile() { this.setState({ loading: true }); var self = this; var url = API_CONSTS.API_BASE_URL + API_CONSTS.API_UPDATE_PROFILE; fetch(url, { method: "PUT", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: global.token }, body: JSON.stringify({ name: this.state.name, phoneNumber: this.state.number, email: this.state.email, occupation: this.state.occupation }) }) .then(response => { if (response.status === 200) { return response.json(); } else if (response.status === 401) { this.props.navigation.pop(1); return { code: response.status, message: "Plese login again" }; } else { return { code: response.status, message: "Something went wrong " + response.status }; } }) .then(responseJson => { console.log("UserInfo", responseJson.body); if (responseJson.code == 200) { Alert.alert("Message", responseJson.message, [ { text: "OK", onPress: () => this.setState({ loading: false }, function() { // this.forceUpdate() }) } ]); } }) .catch(error => { console.error(error); }); } logout = async () => { try { AsyncStorage.clear(); await AsyncStorage.setItem(APP_CONSTS.LOGGEDIN_FLAG, "false"); // this.props.navigation.navigate(ROUTE_CONSTS.LANDING_SCREEN); this.props.navigation.pop(2); // await AsyncStorage.setItem(APP_CONSTS.EMAIL, this.state.email); // await AsyncStorage.setItem(APP_CONSTS.GENDER, this.state.gender); } catch (error) { // Error saving data alert(error); } }; logoutApi() { this.setState({ loading: true }); var self = this; var url = API_CONSTS.API_BASE_URL + API_CONSTS.API_LOGOUT; fetch(url, { method: "POST", headers: { Authorization: global.token } }) .then(response => { return response; }) .then(responseJson => { this.setState({ loading: false }); if (responseJson.code == 200) { this.logout(); } else { this.logout(); } }) .catch(error => { console.error(error); }); } getContacts() { this.setState({ loading: true }); var self = this; var url = API_CONSTS.API_BASE_URL + API_CONSTS.API_GET_STUDENT_SEARCH; fetch(url, { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: global.token } }) .then(response => { if (response.status === 200) { return response.json(); } else if (response.status === 401) { this.props.navigation.navigate("Home"); return { code: response.status, message: "Plese login again" }; } else { return { code: response.status, message: "Something went wrong " + response.status }; } }) .then(responseJson => { this.setState({ loading: false }); if (responseJson.code == 200) { console.log("studentData", responseJson.body); this.setState({ usersContactsArr: responseJson.body, searchContactsArr: responseJson.body }); } }) .catch(error => { this.setState({ loading: false }); console.error(error); }); } postTabSelected() { this.setState({ postTab: true, profileTab: false, contactsTab: false, performanceTab: false, courseTab: false },() => this.getAllPost()); } profileTabSelected() { this.setState({ postTab: false, profileTab: true, contactsTab: false, performanceTab: false, courseTab: false }); } contactsTabSelected() { this.setState({ postTab: false, profileTab: false, contactsTab: true, performanceTab: false, courseTab: false }); } courseTabSelected() { this.setState({ postTab: false, profileTab: false, contactsTab: false, performanceTab: false, courseTab: true }); } performanceTabSelected() { this.setState({ postTab: false, profileTab: false, contactsTab: false, performanceTab: true, courseTab: false }); } postTabChildSelected() { this.setState({ postTabChild: true, teamTabChild: false }); } teamTabChildSelected() { this.setState({ postTabChild: false, teamTabChild: true }); } renderTabs() { return ( <View style={{ flexDirection: "row", justifyContent: "center", margin: 20 }} > <TouchableOpacity style={{ alignItems: "center" }} onPress={this.postTabSelected} > <Image source={require("../../assets/post.png")} style={{ width: 25, height: 25, marginBottom: 5 }} ></Image> <Text style={{ fontWeight: "400", fontSize: 12 }}>Posts</Text> {this.state.postTab ? ( <View style={{ height: 7, marginTop: 10, backgroundColor: COLOR_CONSTS.APP_GREEN_COLOR, width: 50, borderRadius: 10 }} ></View> ) : ( <View style={{ height: 0, marginTop: 10, backgroundColor: COLOR_CONSTS.APP_GREEN_COLOR, width: 50, borderRadius: 10 }} ></View> )} </TouchableOpacity> <TouchableOpacity style={{ marginLeft: 20, alignItems: "center" }} onPress={this.profileTabSelected} > <Image source={require("../../assets/profile.png")} style={{ width: 26, height: 25, marginBottom: 5 }} ></Image> <Text style={{ fontWeight: "400", fontSize: 12 }}>Profile</Text> {this.state.profileTab ? ( <View style={{ height: 7, marginTop: 10, backgroundColor: COLOR_CONSTS.APP_GREEN_COLOR, width: 50, borderRadius: 10 }} ></View> ) : ( <View style={{ height: 0, marginTop: 10, backgroundColor: COLOR_CONSTS.APP_GREEN_COLOR, width: 50, borderRadius: 10 }} ></View> )} </TouchableOpacity> <TouchableOpacity style={{ marginLeft: 20, alignItems: "center" }} onPress={this.contactsTabSelected} > <Image source={require("../../assets/contacts.png")} style={{ width: 34, height: 25, marginBottom: 5 }} ></Image> <Text style={{ fontWeight: "400", fontSize: 12 }}>Contacts</Text> {this.state.contactsTab ? ( <View style={{ height: 7, marginTop: 10, backgroundColor: COLOR_CONSTS.APP_GREEN_COLOR, width: 55, borderRadius: 10 }} ></View> ) : ( <View style={{ height: 0, marginTop: 10, backgroundColor: COLOR_CONSTS.APP_GREEN_COLOR, width: 55, borderRadius: 10 }} ></View> )} </TouchableOpacity> <TouchableOpacity style={{ marginLeft: 20, alignItems: "center" }} onPress={this.courseTabSelected} > <Image source={require("../../assets/courses.png")} style={{ width: 34, height: 25, marginBottom: 5 }} ></Image> <Text style={{ fontWeight: "400", fontSize: 12 }}> {global.role == 4 ? "Join Courses" : "Courses"} </Text> {this.state.courseTab ? ( <View style={{ height: 7, marginTop: 10, backgroundColor: COLOR_CONSTS.APP_GREEN_COLOR, width: 55, borderRadius: 10 }} ></View> ) : ( <View style={{ height: 0, marginTop: 10, backgroundColor: COLOR_CONSTS.APP_GREEN_COLOR, width: 55, borderRadius: 10 }} ></View> )} </TouchableOpacity> {/* <TouchableOpacity style={{marginLeft:20,alignItems:'center'}} onPress={this.performanceTabSelected}> <Image source={require('../../assets/performance.png')} style={{width:27,height:25,marginBottom:5}}></Image> <Text style={{fontWeight:'400',fontSize:12}}>Performance</Text> {this.state.performanceTab ? <View style={{height:7,marginTop:10,backgroundColor:COLOR_CONSTS.APP_GREEN_COLOR,width:75,borderRadius:10}}></View> : <View style={{height:0,marginTop:10,backgroundColor:COLOR_CONSTS.APP_GREEN_COLOR,width:75,borderRadius:10}}></View>} </TouchableOpacity> */} </View> ); } renderPostCourses() { let organisationComponent = []; this.state.postcourses.forEach((user, index) => { organisationComponent.push( <Text onPress={() => this.showCoursePosts(user, index)} style={{marginHorizontal:10, fontWeight: user.tick ? 'bold': 'normal', textDecorationLine: user.tick ? 'underline' : 'none'}}>{user.title}</Text> ); }); return ( <ScrollView horizontal showsHorizontalScrollIndicator={false} > {organisationComponent} </ScrollView> ); } showCoursePosts(user, index){ const { postcourses } = this.state; for (let i = 0; i < postcourses.length; i++) { if(postcourses[i]['tick'] = true){ postcourses[i]['tick'] = false } } postcourses[index].tick = true this.setState({postcourses, courseId: user.id }, () => this.getAllPost()) } renderPosts() { return ( <FlatList data={this.state.postData} ListEmptyComponent={this._listEmptyComponent} extraData={this.state} initialNumToRender={5} maxToRenderPerBatch={5} windowSize={5} renderItem={this.feedCell} keyExtractor={(item, index) => index.toString()} /> ); } feedCell = ({ item, index }) => ( <View> <ListItem thumbnail noBorder style={{ marginTop: 10 }}> <Left> {item.type == 1 ? ( <TouchableOpacity onPress={() => {}}> {/* <Image source={{uri: item.postMedia[0].thumbnail}} style={{width:'100%',height:200,resizeMode:'cover'}} ></Image> */} <View style={{ width: 120, height: 120, justifyContent: "center", alignItems: "center", borderRadius: 5, resizeMode: "cover", backgroundColor: item.backgroundColor }} > <Text style={{ textAlign: "center", fontSize: 14, color: "white" }} > {item.description} </Text> </View> </TouchableOpacity> ) : null} {item.type == 2 ? ( <View> <Thumbnail large square source={{ uri: item.postMedia[0].media }} style={{ height: 120, width: 120, borderRadius: 5 }} /> {/* <Image source={require('../../assets/vdos.png')} style={{height: 20,width:20,position:'absolute',marginLeft:95,marginTop:5}}></Image> */} </View> ) : null} {item.type == 3 ? ( <View> <Thumbnail large square source={{ uri: item.postMedia[0].thumbnail }} style={{ height: 120, width: 120, borderRadius: 5 }} /> <Image source={require("../../assets/vdos.png")} style={{ height: 20, width: 20, position: "absolute", marginLeft: 95, marginTop: 5 }} ></Image> </View> ) : null} {item.type == 4 ? ( <TouchableOpacity onPress={() => {}}> <View style={{ width: 120, height: 120, borderRadius: 5, backgroundColor: COLOR_CONSTS.APP_QUESTION_COLOR }} > <View style={{ height: 40, justifyContent: "center", alignItems: "center" }} > <Text note style={{ textAlign: "center", fontSize: 12 }}> Question 1 </Text> </View> <View style={{ justifyContent: "center", alignItems: "center", height: 100, marginTop: -25 }} > <Text style={{ textAlign: "center", fontSize: 13, color: "white", padding: 2 }} > {item.postMedia[0].questions} </Text> </View> </View> </TouchableOpacity> ) : null} {item.type == 5 ? ( <View style={{ height: 120, width: 120, justifyContent: "center", alignItems: "center" }} > <Thumbnail large square source={require("../../assets/doc.png")} style={{ height: 80, width: 80 }} /> {/* <Image source={require('../../assets/vdos.png')} style={{height: 20,width:20,position:'absolute',marginLeft:95,marginTop:5}}></Image> */} </View> ) : null} {item.type == 6 ? ( <View style={{ height: 120, width: 120, justifyContent: "flex-start", alignItems: "center" }} > {/* <Thumbnail large square source={{uri:item.postMedia[0].thumbnail}} style={{height:80,width:80,resizeMode: 'center'}}/> */} <Image source={require("../../assets/audio1.png")} style={{ height: 22, width: 20, marginLeft: 95, marginTop: 5, resizeMode: "center" }} ></Image> </View> ) : null} </Left> <Body> <Text>{item.user.institute.title}</Text> <Text style={{ fontSize: 12, marginTop: 5 }} numberOfLines={0}> {item.description} </Text> <Button rounded style={{ width: 100, height: 25, marginTop: 10, justifyContent: "center", backgroundColor: COLOR_CONSTS.APP_GREEN_COLOR }} onPress={() => { this.postDetails(item); }} > <Text style={{ color: "black", fontWeight: "500", fontSize: 12, textAlign: "center" }} > View Post </Text> </Button> </Body> </ListItem> <View style={{ height: 2, marginTop: 5, backgroundColor: COLOR_CONSTS.APP_LIGHT_GREY_COLOR, borderRadius: 10 }} ></View> </View> ); _listEmptyComponent = () => { return ( <View style={{ height: "100%", justifyContent: "center", alignSelf: "center", paddingTop: 30 }} > <Text style={{ textAlign: "center", color: "grey" }}></Text> </View> ); }; renderTabsPerformance() { return ( <View style={{ flexDirection: "row", justifyContent: "center", margin: 20 }} > <TouchableOpacity style={{ alignItems: "center" }} onPress={this.postTabChildSelected} > <Image source={require("../../assets/post.png")} style={{ width: 25, height: 25, marginBottom: 5 }} ></Image> <Text style={{ fontWeight: "400", fontSize: 12 }}>Posts</Text> {this.state.postTabChild ? ( <View style={{ height: 7, marginTop: 5, backgroundColor: COLOR_CONSTS.APP_GREEN_COLOR, width: 50, borderRadius: 10 }} ></View> ) : ( <View style={{ height: 0, marginTop: 5, backgroundColor: COLOR_CONSTS.APP_GREEN_COLOR, width: 50, borderRadius: 10 }} ></View> )} </TouchableOpacity> <TouchableOpacity style={{ marginLeft: 70, alignItems: "center" }} onPress={this.teamTabChildSelected} > <Image source={require("../../assets/o2.png")} style={{ width: 25, height: 25, borderRadius: 12, marginBottom: 5 }} ></Image> <Text style={{ fontWeight: "400", fontSize: 12 }}>Teams</Text> {this.state.teamTabChild ? ( <View style={{ height: 7, marginTop: 5, backgroundColor: COLOR_CONSTS.APP_GREEN_COLOR, width: 50, borderRadius: 10 }} ></View> ) : ( <View style={{ height: 0, marginTop: 5, backgroundColor: COLOR_CONSTS.APP_GREEN_COLOR, width: 50, borderRadius: 10 }} ></View> )} </TouchableOpacity> </View> ); } renderPostPerformance() { return ( <View> <Text style={{ marginTop: 20, margin: 10, fontSize: 18, fontWeight: "500" }} > Recent </Text> <View> <View style={{ justifyCOntent: "center", alignItems: "center" }}> <ImageBackground source={require("../../assets/imageFeed.png")} style={{ width: APP_CONSTS.SCREEN_WIDTH - 20, height: 160 }} > <Image source={require("../../assets/vdos.png")} style={{ height: 20, width: 20, margin: 10, alignSelf: "flex-end" }} ></Image> </ImageBackground> </View> <View style={{ margin: 10 }}> <Text style={{ textAlign: "left" }}>Medgar Evers College</Text> <View style={{ flexDirection: "row", justifyContent: "space-between", marginTop: 10 }} > <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>15k</Text> <Text style={{ fontSize: 12 }}>Views</Text> </View> <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>230</Text> <Text style={{ fontSize: 12 }}>Likes</Text> </View> <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>65</Text> <Text style={{ fontSize: 12 }}>Video</Text> <Text style={{ fontSize: 12 }}>Comments</Text> </View> <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>9</Text> <Text style={{ fontSize: 12 }}>Voice</Text> <Text style={{ fontSize: 12 }}>Memos</Text> </View> <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>35</Text> <Text style={{ fontSize: 12 }}>Comments</Text> </View> </View> </View> </View> <View> <View style={{ justifyCOntent: "center", alignItems: "center" }}> <ImageBackground source={require("../../assets/imageFeed.png")} style={{ width: APP_CONSTS.SCREEN_WIDTH - 20, height: 160 }} > <Image source={require("../../assets/vdos.png")} style={{ height: 20, width: 20, margin: 10, alignSelf: "flex-end" }} ></Image> </ImageBackground> </View> <View style={{ margin: 10 }}> <Text style={{ textAlign: "left" }}>Medgar Evers College</Text> <View style={{ flexDirection: "row", justifyContent: "space-between", marginTop: 10 }} > <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>15k</Text> <Text style={{ fontSize: 12 }}>Views</Text> </View> <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>230</Text> <Text style={{ fontSize: 12 }}>Likes</Text> </View> <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>65</Text> <Text style={{ fontSize: 12 }}>Video</Text> <Text style={{ fontSize: 12 }}>Comments</Text> </View> <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>9</Text> <Text style={{ fontSize: 12 }}>Voice</Text> <Text style={{ fontSize: 12 }}>Memos</Text> </View> <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>35</Text> <Text style={{ fontSize: 12 }}>Comments</Text> </View> </View> </View> </View> </View> ); } renderTeamPerformance() { var cardWidth = APP_CONSTS.SCREEN_WIDTH / 6 - 15; var cardDimension = APP_CONSTS.SCREEN_WIDTH / 6 - 15; if (APP_CONSTS.SCREEN_WIDTH > 375) { cardWidth = APP_CONSTS.SCREEN_WIDTH / 8 - 15; cardDimension = APP_CONSTS.SCREEN_WIDTH / 8 - 15; } return ( <View style={{ marginLeft: 10 }}> <Text style={{ marginTop: 20, margin: 10, fontSize: 18, fontWeight: "500" }} > Popular </Text> <GridView itemDimension={cardDimension} items={this.state.userDataPost} style={styles.gridView} spacing={1} horizontal={false} renderItem={item => ( <TouchableOpacity style={{ marginTop: 10 }}> <View style={{ width: cardWidth, height: 60, backgroundColor: "transparent", borderWidth: 0, alignItems: "center" }} > {/* <Image source={{uri: event.image}} style={{height:100, width:cardWidth-1,resizeMode: 'cover', backgroundColor:"transparent", borderRadius:4}}/> */} <Image source={require("../../assets/lisa.png")} style={styles.eventsCardContainer} /> {/* <View style={{height:1,backgroundColor:'rgba(0,0,0,0.1)'}}></View> */} {/* <Text style={{color:"grey", marginLeft:5, marginBottom:5, fontSize:12}}>{event.venueLocality}</Text> */} <Text style={{ color: "black", textAlign: "center", fontSize: 14, marginTop: 3 }} > Lisa </Text> </View> </TouchableOpacity> )} /> <View style={{ marginTop: 20 }}> <CardItem style={{ backgroundColor: "transparent", marginLeft: -5 }}> <Left> <Thumbnail small source={require("../../assets/lisa.png")} /> <Body> <Text>LISA</Text> <Text note>CHIF HUMAN RESOURCES OFFICER</Text> </Body> </Left> </CardItem> <View style={{ justifyCOntent: "center", alignItems: "center" }}> <ImageBackground source={require("../../assets/imageFeed.png")} style={{ width: APP_CONSTS.SCREEN_WIDTH - 20, height: 160 }} > <Image source={require("../../assets/vdos.png")} style={{ height: 20, width: 20, margin: 10, alignSelf: "flex-end" }} ></Image> </ImageBackground> </View> <View style={{ margin: 10 }}> <Text style={{ textAlign: "left" }}>Medgar Evers College</Text> <View style={{ flexDirection: "row", justifyContent: "space-between", marginTop: 10 }} > <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>15k</Text> <Text style={{ fontSize: 12 }}>Views</Text> </View> <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>230</Text> <Text style={{ fontSize: 12 }}>Likes</Text> </View> <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>65</Text> <Text style={{ fontSize: 12 }}>Video</Text> <Text style={{ fontSize: 12 }}>Comments</Text> </View> <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>9</Text> <Text style={{ fontSize: 12 }}>Voice</Text> <Text style={{ fontSize: 12 }}>Memos</Text> </View> <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>35</Text> <Text style={{ fontSize: 12 }}>Comments</Text> </View> </View> </View> </View> <View style={{ marginTop: 20 }}> <CardItem style={{ backgroundColor: "transparent", marginLeft: -5 }}> <Left> <Thumbnail small source={require("../../assets/lisa.png")} /> <Body> <Text>LISA</Text> <Text note>CHIF HUMAN RESOURCES OFFICER</Text> </Body> </Left> </CardItem> <View style={{ justifyCOntent: "center", alignItems: "center" }}> <ImageBackground source={require("../../assets/imageFeed.png")} style={{ width: APP_CONSTS.SCREEN_WIDTH - 20, height: 160 }} > <Image source={require("../../assets/vdos.png")} style={{ height: 20, width: 20, margin: 10, alignSelf: "flex-end" }} ></Image> </ImageBackground> </View> <View style={{ margin: 10 }}> <Text style={{ textAlign: "left" }}>Medgar Evers College</Text> <View style={{ flexDirection: "row", justifyContent: "space-between", marginTop: 10 }} > <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>15k</Text> <Text style={{ fontSize: 12 }}>Views</Text> </View> <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>230</Text> <Text style={{ fontSize: 12 }}>Likes</Text> </View> <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>65</Text> <Text style={{ fontSize: 12 }}>Video</Text> <Text style={{ fontSize: 12 }}>Comments</Text> </View> <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>9</Text> <Text style={{ fontSize: 12 }}>Voice</Text> <Text style={{ fontSize: 12 }}>Memos</Text> </View> <View style={{ flexDirection: "column", alignItems: "center" }}> <Text style={{ fontWeight: "700", fontSize: 18 }}>35</Text> <Text style={{ fontSize: 12 }}>Comments</Text> </View> </View> </View> </View> </View> ); } renderPerformance() { return ( <View> {this.renderTabsPerformance()} <View style={{ height: 1, marginTop: 5, backgroundColor: COLOR_CONSTS.APP_LIGHT_GREY_COLOR, borderRadius: 10 }} ></View> {this.state.postTabChild ? this.renderPostPerformance() : this.renderTeamPerformance()} </View> ); } renderProfile() { var cardWidth = APP_CONSTS.SCREEN_WIDTH / 4 - 15; var cardDimension = APP_CONSTS.SCREEN_WIDTH / 4 - 15; if (APP_CONSTS.SCREEN_WIDTH > 375) { cardWidth = APP_CONSTS.SCREEN_WIDTH / 6 - 15; cardDimension = APP_CONSTS.SCREEN_WIDTH / 6 - 15; } return ( <View style={{ marginLeft: 10 }}> <Text style={{ marginTop: 20, margin: 10, marginLeft: 0, fontSize: 18, fontWeight: "500", color: COLOR_CONSTS.APP_LIGHT_GREY_COLOR }} > Teams </Text> <GridView itemDimension={cardDimension} items={this.state.teamData} style={styles.gridView} spacing={1} horizontal={false} renderItem={item => ( <TouchableOpacity style={{ marginTop: 10 }}> <View style={{ width: cardWidth, height: 60, backgroundColor: "transparent", borderWidth: 0, alignItems: "center" }} > {/* <Image source={{uri: event.image}} style={{height:100, width:cardWidth-1,resizeMode: 'cover', backgroundColor:"transparent", borderRadius:4}}/> */} <Image source={{ uri: this.state.thumb }} style={styles.eventsCardContainer} /> {/* <View style={{height:1,backgroundColor:'rgba(0,0,0,0.1)'}}></View> */} {/* <Text style={{color:"grey", marginLeft:5, marginBottom:5, fontSize:12}}>{event.venueLocality}</Text> */} <Text style={{ color: "black", textAlign: "center", fontSize: 10, marginTop: 3 }} > {this.state.userData.institute.title} </Text> </View> </TouchableOpacity> )} /> <View> <Item floatingLabel style={{ marginLeft: 5, marginTop: 35 }}> <Label style={{ fontSize: 14 }}>Name</Label> <Input style={{ marginRight: 30 }} value={this.state.name} style={{ color: COLOR_CONSTS.APP_BLACK_COLOR }} onChangeText={name => { this.setState({ name: name }); }} /> </Item> <Item floatingLabel style={{ marginLeft: 5, marginTop: 35 }}> <Label style={{ fontSize: 14 }}>Email</Label> <Input style={{ marginRight: 30 }} value={this.state.email} style={{ color: COLOR_CONSTS.APP_BLACK_COLOR }} onChangeText={email => { this.setState({ email: email }); }} /> </Item> <Item floatingLabel style={{ marginLeft: 5, marginTop: 35 }}> <Label style={{ fontSize: 14 }}>Occupation</Label> <Input editable={false} style={{ marginRight: 30 }} value={this.state.occupation} style={{ color: COLOR_CONSTS.APP_BLACK_COLOR }} // onChangeText={occupation => { // this.setState({ occupation: occupation }); // }} /> </Item> <Item floatingLabel style={{ marginLeft: 5, marginTop: 35 }}> <Label style={{ fontSize: 14 }}>Number</Label> <Input style={{ marginRight: 30 }} value={this.state.number} style={{ color: COLOR_CONSTS.APP_BLACK_COLOR }} onChangeText={number => { this.setState({ number: number }); }} /> </Item> </View> <View style={{ justifyContent: "center", alignItems: "center" }}> <Button rounded style={{ width: 200, height: 40, margin: 20, backgroundColor: COLOR_CONSTS.APP_GREEN_COLOR, justifyContent: "center" }} onPress={this.updateProfileData} > <Text style={{ color: "black", fontWeight: "500", fontSize: 15, textAlign: "center" }} > Update Profile </Text> </Button> </View> <View style={{ justifyContent: "center", alignItems: "center" }}> <Button rounded style={{ width: 200, height: 40, margin: 20, backgroundColor: COLOR_CONSTS.APP_GREEN_COLOR, justifyContent: "center" }} onPress={this.logoutApi} > <Text style={{ color: "black", fontWeight: "500", fontSize: 15, textAlign: "center" }} > Log Out </Text> </Button> </View> </View> ); } renderContacts() { const { search } = this.state; let organisationComponent = []; this.state.usersContactsArr.forEach(user => { organisationComponent.push( user.role != 5 && ( // <ListItem avatar noBorder button onPress={()=>{this.courseDetails(user)}}> <ListItem avatar noBorder button> {/* <Left> <Thumbnail small source={{uri: user.image}} /> </Left> */} <Body style={{ margin: 0 }}> <Text>{user.name}</Text> {user.role == 4 ? ( <Text note>Student</Text> ) : user.role == 5 ? ( <Text note>Course</Text> ) : ( <Text note>Instructor</Text> )} <View style={{ height: 1, marginTop: 2, backgroundColor: COLOR_CONSTS.APP_LIGHT_GREY_COLOR, borderRadius: 1 }} ></View> </Body> <Right>{/* <Text note>3:43 pm</Text> */}</Right> </ListItem> ) ); }); return ( <View style={{ marginTop: 20 }}> {/* <View style={{marginLeft:15,marginRight:15,borderWidth:1,borderColor:'rgba(0,0,0,0.6)',borderRadius:8}}> <SearchBar lightTheme={true} placeholder="Search groups, employees, locations" onChangeText={this.updateSearch} value={search} containerStyle={{backgroundColor:COLOR_CONSTS.APP_WHITE_COLOR,borderRadius:10,height:43}} inputContainerStyle={{backgroundColor:COLOR_CONSTS.APP_WHITE_COLOR,height:30,marginTop:-3}} searchIcon={<Image source={require('../../assets/search.png')} style={{width:18,height:18}}/>} cancelIcon={null} clearIcon={null} /> </View> <View style={{flexDirection:'row',justifyContent:'space-around',marginTop:10,marginLeft:20,marginRight:20}}> <Button rounded style={{width:100,height:35,marginTop:10,backgroundColor:COLOR_CONSTS.APP_GREEN_COLOR,justifyContent:'center'}}> <Text style={{color:'black',fontWeight:'500',fontSize:15,textAlign:'center'}}>Delete</Text> </Button> <Button rounded style={{width:100,height:35,marginTop:10,backgroundColor:COLOR_CONSTS.APP_GREEN_COLOR,justifyContent:'center'}}> <Text style={{color:'black',fontWeight:'500',fontSize:15}}>Add</Text> </Button> </View> */} <ScrollView vertical showsHorizontalScrollIndicator={false} style={styles.cardContainer} > {organisationComponent} </ScrollView> </View> ); } getInstrucrorCourses() { this.setState({ loading: true }); var self = this; var url = API_CONSTS.API_BASE_URL + API_CONSTS.API_INSTRUCTOR_SELECTED_COURSES; fetch(url, { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: global.token } }) .then(response => { if (response.status === 200) { return response.json(); } }) .then(responseJson => { this.setState({ loading: false }); console.log("instructorSelectedCourses", responseJson.body); if (responseJson.code == 200) { this.setState({ courses: responseJson.body, }); for (let i = 0; i < responseJson.body.length; i++) { responseJson.body[i]['tick'] = false; if( i == 0){ this.setState({courseId: responseJson.body[i].id}, () => this.getAllPost()) responseJson.body[i]['tick'] = true; } } this.setState({ postcourses: responseJson.body }); } }) .catch(error => { this.setState({ loading: false }); console.error(error); }); } getStudentCourses() { this.setState({ loading: true }); var self = this; var url = API_CONSTS.API_BASE_URL + API_CONSTS.API_GET_STUDENT_SELECTED_COURSES; fetch(url, { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: global.token } }) .then(response => { if (response.status === 200) { return response.json(); } }) .then(responseJson => { this.setState({ loading: false }); console.log("studentSelectedCourses", responseJson.body); if (responseJson.code == 200) { this.setState({ courses: responseJson.body, }); for (let i = 0; i < responseJson.body.length; i++) { responseJson.body[i]['tick'] = false; if( i == 0){ this.setState({courseId: responseJson.body[i].id}, () => this.getAllPost()) responseJson.body[i]['tick'] = true; } } this.setState({ postcourses: responseJson.body }); } }) .catch(error => { this.setState({ loading: false }); console.error(error); }); } renderCourses() { // if(this.state.courses.length === 0) { return; } let organisationComponent = []; this.state.courses.forEach((user, index) => { organisationComponent.push( <ListItem key={index.toString()} avatar noBorder button onPress={() => { this.courseDetails(user); }} > {/* <Left> <Thumbnail small source={{uri: user.image}} /> </Left> */} <Body style={{ margin: 0 }}> <Text>{user.title}</Text> <Text note></Text> <View style={{ height: 1, marginTop: 2, backgroundColor: COLOR_CONSTS.APP_LIGHT_GREY_COLOR, borderRadius: 1 }} ></View> </Body> <Right>{/* <Text note>3:43 pm</Text> */}</Right> </ListItem> ); }); return ( <View style={{ marginTop: 20 }}> <ScrollView vertical showsHorizontalScrollIndicator={false} style={styles.cardContainer} > {organisationComponent} </ScrollView> <View style={{ justifyContent: "center", alignItems: "center" }}> <Button rounded style={{ width: 200, height: 40, margin: 20, backgroundColor: COLOR_CONSTS.APP_GREEN_COLOR, justifyContent: "center" }} onPress={this.addCourses} > <Text style={{ color: "black", fontWeight: "500", fontSize: 15, textAlign: "center" }} > Add Course </Text> </Button> </View> </View> ); } addCourses() { if (this.state.userData.role === 4) { return this.props.navigation.navigate(ROUTE_CONSTS.SELECT_COURSE_SCREEN, {backScreen: 'dashboard' }); } return this.props.navigation.navigate( ROUTE_CONSTS.SELECT_COURSE_INSTRUCTOR, { institute: [] , backScreen: 'dashboard'} ); } render() { return ( <StyleProvider style={getTheme(material)}> <Container style={styles.container}> <NavigationEvents onWillFocus={() => {}} /> <Loader loading={this.state.loading} /> <Header style={styles.headerStyle}> <Left style={{ flex: 3 }}> <View style={{ padding: 10, marginTop: 1, alignItems: "flex-start" }} > <TouchableOpacity onPress={this.closeButtonTapped}> {/* <Image source={require('../../assets/bck.png')} style={{ width: 20, height: 20, resizeMode: 'contain' }} /> */} </TouchableOpacity> </View> </Left> <Body style={{ flex: 3, alignItems: "center" }}> <Title style={styles.title}>Dashboard</Title> </Body> <Right style={{ flex: 3 }}></Right> </Header> <Content> <View style={{ height: 180, width: APP_CONSTS.SCREEN_WIDTH, justifyContent: "center", alignItems: "center" }} > <Text style={{margin:10}}>{this.state.institute_title}</Text> <TouchableOpacity onPress={this._pickImage}> {/* <Image source={require('../../assets/userDummy.png')} style={{height: 80,width:80}}></Image> */} <Image source={this.state.image ? { uri: this.state.image } : require("../../assets/userDummy.png")} style={{ width: 100, height: 100, borderRadius: 50, resizeMode: "contain" }} /> <Image source={{ uri: this.state.thumb }} style={{ height: 36, width: 36, borderRadius: 18, position: "absolute", marginLeft: 75 }} resizeMode="center" ></Image> </TouchableOpacity> </View> <View style={{ marginTop: -20 }}> <Text style={{ textAlign: "center", fontWeight: "500" }}> {this.state.userData.name} Dashboard </Text> </View> {this.renderTabs()} {this.state.postTab ? this.renderPostCourses() : null} <View style={{ height: 1, marginTop: 5, backgroundColor: COLOR_CONSTS.APP_LIGHT_GREY_COLOR, borderRadius: 10 }} ></View> {this.state.postTab ? this.renderPosts() : null} {this.state.performanceTab ? this.renderPerformance() : null} {this.state.profileTab ? this.renderProfile() : null} {this.state.contactsTab ? this.renderContacts() : null} {this.state.courseTab ? this.renderCourses() : null} </Content> </Container> </StyleProvider> ); } } const styles = StyleSheet.create({ container: { backgroundColor: COLOR_CONSTS.APP_OFF_WHITE_COLOR }, headerStyle: { backgroundColor: COLOR_CONSTS.APP_BLACK_COLOR }, title: { color: COLOR_CONSTS.APP_WHITE_COLOR, fontSize: 18, fontWeight: "bold", textAlign: "center" }, eventsCardContainer: { height: 35, width: 35, resizeMode: "cover", borderRadius: 5 } });
const bsearch=require("ksana-corpus").bsearch; const plist=require("./plist"); const groupStat=function(postings, groups){ return plist.groupStat(postings,groups); } const filterMatch=function(cor,matches,excludegroup){ if (!cor) return []; if (!excludegroup) return matches; var out=matches.slice(); for (var i=0;i<excludegroup.length;i++) { if (!excludegroup[i]) continue; const startend=cor.groupTRange(i); const s=bsearch(out,startend[0],true); const e=bsearch(out,startend[1],true); out.splice(s,e-s); } return out; } module.exports={groupStat:groupStat,filterMatch:filterMatch}
//AKA Message in the database import React from 'react' import PropTypes from 'prop-types' export default class LogMessage extends React.Component { render() { return ( <div className='LogMessage'> {(this.props.gamemaster === this.props.userId) ? <h2>{`Game Master Says:`}</h2> : <h3>{`Player attempts to...`}</h3>} <p>{this.props.text}</p> </div> ) } } LogMessage.propTypes = { text: PropTypes.string.isRequired, gamemaster: PropTypes.string.isRequired, userId: PropTypes.string.isRequired, }
export default function isBuffer(arg) { return arg instanceof Buffer; }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const DataHelper_1 = require("../../../helpers/DataHelper"); const ProductConfig_1 = require("./ProductConfig"); class Product { constructor(model) { if (!model) return; this._id = DataHelper_1.default.handleIdDataModel(model._id); this.code = model.code; this.type = model.type; this.name = model.name; this.logo = DataHelper_1.default.handleFileDataModel(model.logo); this.favicon = DataHelper_1.default.handleFileDataModel(model.favicon); this.config = new ProductConfig_1.default(model.config); } static parseArray(list) { return list && Array.isArray(list) ? list.map(item => new Product(item)) : []; } } Object.seal(Product); exports.default = Product;
import {Api} from "./api"; export {AchievementsApi, Achievement}; class AchievementsApi { static get url() { return `${Api.baseUrl}/achievements`; } static async getAllAchievement(data, controller) { return await Api.get(`${AchievementsApi.url}?` + new URLSearchParams({...data}), true, controller); } static async addAchievement(achievement, controller) { const response = await Api.post(`${AchievementsApi.url}`, true, achievement, controller); response.id = achievement.id; } } class Achievement { constructor(weight, height) { this.date = Date.now(); this.id = null; this.weight = weight; this.height = height; } }
// @flow import axios from 'axios' import type { Dispatch, GetState } from '../../types' import { FETCH_PROGRAMS, FETCH_PROGRAMS_SUCCESS, FETCH_PROGRAMS_FAILURE } from '../actionTypes/' export const filterPrograms = (searchParams: string) => { return (dispatch: Dispatch, getState: GetState) => { const params = `${searchParams.substring(1)}&limit=100` dispatch({ type: FETCH_PROGRAMS, }) axios .get(`https://api.spacexdata.com/v3/launches?${new URLSearchParams(params).toString()}`) .then(({ data }) => { dispatch({ type: FETCH_PROGRAMS_SUCCESS, payload: data, }) }) .catch(e => { console.error(e.message) dispatch({ type: FETCH_PROGRAMS_FAILURE, }) }) } }
const fs = require('fs'); //const csv = require('csv'); const parse = require('csv-parse/lib/sync'); const _ = require('lodash'); //const filename = './data/sample-faqs.tsv'; const filename = './data/faqdata0.tsv'; const jsonname = './json/faqdata.json'; const columns = [ 'no', 'public', 'serviceName', 'category', 'createdBy', 'workflowStatus', 'createDate', 'updateDate', 'title', 'context', 'language', 'countOfView', 'url']; let input = fs.readFileSync(filename,'utf-8'); let records = parse(input,{columns: columns,delimiter:'\t',comment:'###',from :2}); //console.dir(records); const faqs = {}; // _.each(records,(ele,idx,ary)=>{ // //console.log(idx + ' : ' + ele); // zips['No.' + ele.postNum] = ele; // }); faqs.faq = records; const output = JSON.stringify(faqs,null,'\t'); fs.writeFileSync(jsonname,output);
var RdIntegration = (function () { 'use strict'; var $form, $token_rdstation, $identifier, $options, $accountSettings, REJECTED_FIELDS = ['captcha', '_wpcf7', '_wpcf7_version', '_wpcf7_unit_tag', '_wpnonce', '_wpcf7_is_ajax_call', '_wpcf7_locale'], COMMON_EMAIL_FIELDS = ['email', 'e-mail', 'e_mail', 'email_lead', 'your-email'], $, _withjQuery = function (callback) { if (typeof jQuery === "undefined") { _loadScript("https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js", callback); } else { callback(); } }, _integrate = function (token_rdstation, identifier, options) { _withjQuery(function () { $ = jQuery; _setParams(token_rdstation, identifier, options); _overrideSubmitFormMethod(); $(document).ready(_bindSubmitCallback); _initDebugMode(); }); }, _overrideSubmitFormMethod = function () { if (typeof $options.callbackCompleted !== "undefined") { _submitForm = $options.callbackCompleted; } }, _setParams = function (token_rdstation, identifier, options) { $options = options || {}; $token_rdstation = token_rdstation; $identifier = identifier; }, _loadScript = function (scriptSource, callback) { var head = document.getElementsByTagName('head')[0], script = document.createElement('script'); script.type = 'text/javascript'; script.src = scriptSource; // most browsers script.onload = callback; // IE 6 & 7 script.onreadystatechange = function () { if (this.readyState === 'complete') { callback(); } }; head.appendChild(script); }, _bindSubmitCallback = function () { var elementSubmit = _getElementSubmit(); jQuery(elementSubmit).click(_submitClickHandler); }, _getElementSubmit = function () { return $options.elementSubmit ? $options.elementSubmit : ':submit'; }, _submitClickHandler = function (event) { $accountSettings = _getAccountSettings(); $form = _findForm(event.target); if (!$form) { return; } var inputs = _prepareFormData($form); if (!_findEmail(inputs)) { return; } if (typeof $form[0].checkValidity === 'function') { if (!$form[0].checkValidity()) { return; } } _post(inputs, _submitForm); event.preventDefault(); }, _findForm = function (button) { return $(button).closest('form'); }, _prepareFormData = function (form) { var inputs = $(form).find(':input'); inputs = _removeNotAllowedFields(inputs); inputs = inputs.serializeArray(); inputs = _fieldMap(inputs); inputs.push($accountSettings.identifier, $accountSettings.token, $accountSettings.c_utmz, $accountSettings.traffic_source, _getQueryParams()); return inputs; }, _fieldMap = function (inputs) { if ($options.fieldMapping) { inputs = _translateFields(inputs); } return inputs; }, _translateFields = function (inputs) { $.each(inputs, function() { var newName = $options.fieldMapping[this.name]; if (newName) { this.name = newName; } }); return inputs; }, _submitForm = function () { if(_actionIsValid($form) && typeof $options.elementSubmit == 'undefined') { $form.submit(); } else { var elementSubmit = _getElementSubmit(); $form.find(elementSubmit).unbind('click', _submitClickHandler).click(); } }, _actionIsValid = function (form) { var action = form.attr('action'); return typeof action !== "undefined" && action.trim() !== ""; }, _isPassword = function (element) { return $(element).is(":password"); }, _removeNotAllowedFields = function (inputs) { inputs = inputs.map(function () { if (_isAllowedField(this)) { return this; } }); return inputs; }, _isAllowedField = function (element) { return _isEmailField(element) || !(_isPassword(element) || _isRejectedField(element)); }, _isRejectedField = function (element) { var name = $(element).attr('name') || ""; return (name && REJECTED_FIELDS.indexOf(name.toLowerCase()) >= 0); }, _getAccountSettings = function () { return { identifier: { name : 'identificador', value: $identifier }, token: { name: 'token_rdstation', value: $token_rdstation }, c_utmz: { name: 'c_utmz', value: _read_cookie('__utmz') }, traffic_source: { name: 'traffic_source', value: _read_cookie('__trf.src') } }; }, _findEmail = function (fields) { var found = false; $.each(fields, function () { if (_isEmailField(this)) { this.name = 'email'; found = true; return false; } }); return found; }, _isEmailField = function (field) { return COMMON_EMAIL_FIELDS.indexOf(field.name.toLowerCase()) >= 0; }, _read_cookie = function (name) { var cookies = document.cookie.split(';'), d, cookie; name = name + '='; for (d = 0; d < cookies.length; d++) { cookie = cookies[d]; while (cookie.charAt(0) === ' ') { cookie = cookie.substring(1, cookie.length); } if (cookie.indexOf(name) === 0) { return cookie.substring(name.length, cookie.length); } } return null; }, _getQueryParams = function() { return { name: 'query_params', value: location.search.substring(1) }; }, _getCookieId = function () { var leadTrackingCookie = _read_cookie("rdtrk"); if (leadTrackingCookie !== null) { leadTrackingCookie = JSON.parse(unescape(leadTrackingCookie)); return leadTrackingCookie.id; } }, _insertClientId = function(formData){ var client_id = _getCookieId(); if (typeof client_id !== "undefined") { formData.push({name: 'client_id', value: client_id}); } return formData; }, _insertCookieValues = function(formData){ formData.push({name: 'c_utmz', value: _read_cookie('__utmz')}); formData.push({name: 'traffic_source', value: _read_cookie('__trf.src')}); return formData; }, _insertInternalSource = function(formData) { formData.push({ name: '_is', value: 3 }); return formData; }, _post = function (formData, callback) { formData = _insertClientId(formData); formData = _insertCookieValues(formData); formData = _insertInternalSource(formData); _withjQuery(function () { jQuery.ajax({ type: 'POST', url: 'https://www.rdstation.com.br/api/1.3/conversions', data: formData, crossDomain: true, xhrFields: { withCredentials: true }, warn: function (response) { console.log("ERROR - "); console.log(response); }, complete: function(jqXHR, textStatus) { if (callback) { callback(jqXHR, textStatus); } } }); }); }, _initDebugMode = function() { if ($options.debugMode === true) { _analyse(); } }, _analyse = function () { _withjQuery(function () { $ = jQuery; $options = $options || {}; console.info('Iniciando'); var submitButtons = $(_getElementSubmit()), forms = _findForm(submitButtons); if (submitButtons.length === 0) { console.warn('Nenhum botao de submit encontrado'); } else { console.info('Botoes de submit encontrados: ' + submitButtons.length); } if (forms.length === 0) { console.warn('Nenhum formulario encontrado'); } else { console.info('Formularios encontrados: ' + forms.length); } _analyseForms(forms); console.info('Finalizado'); }); }, _analyseForms = function (forms) { $accountSettings = _getAccountSettings(); $.each(forms, function(index, form) { var inputs = _prepareFormData(form), mappedFields = []; console.log(''); console.info(index + 1 + ' formulario'); if (!_findEmail(inputs)) { console.warn('Campo de email nao encontrado'); } else { console.info('Campo de email encontrado'); } $.each(inputs, function(index, input) { mappedFields.push(input.name); }); console.info('Campos mapeados: ' + mappedFields.join(", ")); }); console.log(''); }; return { integrate: _integrate, post: _post, analyse: _analyse }; }()); function RDStationFormIntegration(token_rdstation, identifier, options) { 'use strict'; RdIntegration.integrate(token_rdstation, identifier, options); }