text
stringlengths
7
3.69M
$(function(){ function handleAddElementsClick(){ if($('#txtLabel').val().length > 0) { var row = $('<div/>', { 'class': 'row' }); var label = $('<p/>', { 'class': 'col-xs-3' }).html($('#txtLabel').val()); var textbox = $('<input/>', { 'type': 'text', 'class': 'col-xs-8' }); var minusDiv = $('<div/>', { 'class': 'col-xs-1' }); var minusButton = $('<span/>', { 'class': 'glyphicon glyphicon-minus-sign', 'style': 'font-size: 2em;cursor:pointer;' }); minusButton.click(function(){ minusButton.closest('div[class=row]').remove(); }); minusDiv.append(minusButton); row.append(label); row.append(textbox); row.append(minusDiv); $('#elements').append(row); $('#txtLabel').val(''); listenerAdded = false; } } $('#addElements').on('click', handleAddElementsClick); });
var anumhotel = 1; var savedanumhotel = 1; var afirstClick = 0; var ahotelToReplica; var vApto1; var nDiarias1; var nAptos1; var somaHotel1 = 0; var vApto2; var nDiarias2; var nAptos2; var somaHotel2 = 0; var vApto3; var nDiarias3; var nAptos3; var somaHotel3 = 0; $("#add-hotel").click(function() { if (afirstClick == 0) { ahotelToReplica = parseInt(document.getElementById(`get1`).value); afirstClick++; console.log(ahotelToReplica); savedanumhotel = ahotelToReplica; anumhotel = savedanumhotel; } else { savedanumhotel++; anumhotel = savedanumhotel; } }); $('#prev_hotel').on('click', function() { if (afirstClick == 0) { ahotelToReplica = parseInt(document.getElementById(`get1`).value); afirstClick++; savedanumhotel = ahotelToReplica-1; } if (anumhotel > 1) { anumhotel--; } }); $('#nxt_hotel').on('click', function() { if (afirstClick == 0) { ahotelToReplica = parseInt(document.getElementById(`get1`).value); afirstClick++; savedanumhotel = ahotelToReplica-1; } if (anumhotel < savedanumhotel) { anumhotel++; } }); function calcHotel(){ vApto1 = document.getElementById(`vApto1${anumhotel}`).value; nDiarias1 = document.getElementById(`nDiarias1${anumhotel}`).value; nAptos1 = document.getElementById(`nAptos1${anumhotel}`).value; somaHotel1 = vApto1 * nDiarias1 * nAptos1; document.getElementById(`vTotal1${anumhotel}`).value = somaHotel1; vApto2 = document.getElementById(`vApto2${anumhotel}`).value; nDiarias2 = document.getElementById(`nDiarias2${anumhotel}`).value; nAptos2 = document.getElementById(`nAptos2${anumhotel}`).value; somaHotel2 = vApto2 * nDiarias2 * nAptos2; document.getElementById(`vTotal2${anumhotel}`).value = somaHotel2; vApto3 = document.getElementById(`vApto3${anumhotel}`).value; nDiarias3 = document.getElementById(`nDiarias3${anumhotel}`).value; nAptos3 = document.getElementById(`nAptos3${anumhotel}`).value; somaHotel3 = vApto3 * nDiarias3 * nAptos3; document.getElementById(`vTotal3${anumhotel}`).value = somaHotel3; }
import React from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux' import * as questsActions from '../actions/questsActions' import * as userActions from '../actions/userActions' import QuestItem from './QuestItem' import {List} from 'react-toolbox/lib/list' import CurrentQuest from "./CurrentQuest"; import $ from 'jquery' class Quests extends React.Component { constructor(props) { super(props); const {getQuestsList, checkActiveQuest} = props.questActions; const {getUserInfo} = props.userActions; getQuestsList(); if (!!$.cookie('access_token')) { checkActiveQuest($.cookie("access_token")); getUserInfo($.cookie("access_token")); } } tick = () => { console.log("started"); let sec = parseInt($(".time .sec").text()); console.log(sec); if (sec === 0) { let min = parseInt($(".time .min").text()); if (min === 0) { this.setState({active: false}); this.props.userActions.getUserInfo($.cookie("access_token")); this.props.questActions.endQuest(); return; } min--; $(".time .min").text(min); $(".time .sec").text("59"); return; } sec--; $(".time .sec").text(sec); }; componentDidMount() { this.interval = setInterval(this.tick, 1000); } componentWillUnmount() { clearInterval(this.interval); } render() { const items = []; console.log("render quest"); debugger; this.props.questsList.forEach((quest) => { if (this.props.user.quest !== undefined && this.props.user.quest !== null) { if (this.props.user.quest.id === quest.id) { items.push( <div className="questItem"> <CurrentQuest {...quest}/> </div> ); } else { items.push( <div className="questItem"> <QuestItem {...quest}/> </div> ) } } else { items.push( <div className="questItem"> <QuestItem {...quest}/> </div> ) } }); return ( <div className="buyList"> <List selectable ripple> {items} </List> </div> ) } } function mapStateToProps(state) { console.log("mapStateToProps"); debugger; return { questsList: state.getQuestsList.questsList, activeQuest: state.getQuestsList.activeQuest, user: state.user.user } } function mapDispatchToProps(dispatch) { return { questActions: bindActionCreators(questsActions, dispatch), userActions: bindActionCreators(userActions, dispatch) } } export default connect(mapStateToProps, mapDispatchToProps)(Quests)
import React from 'react'; import { mount } from 'enzyme'; import chai, { expect } from 'chai'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; import { RefChipList } from './refChipList'; chai.use(sinonChai); describe('<RefChipList />', () => { let requiredProps; const testRefs = [ { process: 'a', linkHash: 'b' }, { process: 'c', linkHash: 'd' } ]; beforeEach(() => { requiredProps = { openDialog: sinon.spy(), deleteRef: sinon.spy(), deleteAllRefs: sinon.spy(), refs: [], classes: { row: '', chip: '' } }; }); it('renders text propt when no refs are present', () => { const chipList = mount(<RefChipList {...requiredProps} />); expect(chipList.find('Typography')).to.have.length(1); expect(chipList.find('Typography').text()).to.equal( 'Add segments as refs...' ); }); it('renders 2 refs', () => { requiredProps.refs = testRefs; const chipList = mount(<RefChipList {...requiredProps} />); expect(chipList.find('Typography')).to.have.length(0); expect(chipList.find('Chip')).to.have.length(2); }); it('it deletes the ref of the clicked x', () => { requiredProps.refs = testRefs; const chipList = mount(<RefChipList {...requiredProps} />); chipList.find('Chip').forEach((chip, idx) => { const deleteButton = chip.find('Cancel'); deleteButton.simulate('click'); expect(requiredProps.deleteRef.callCount).to.equal(idx + 1); expect(requiredProps.deleteRef.getCall(idx).args[0]).to.deep.equal( testRefs[idx] ); }); }); it('brings up ref selector screen when the plus button is pushed', () => { const chipList = mount(<RefChipList {...requiredProps} />); const addButton = chipList.find('Add'); expect(addButton).to.have.length(1); addButton.simulate('click'); expect(requiredProps.openDialog.callCount).to.equal(1); }); it('hides the plus button when withOpenButton is false', () => { const chipList = mount( <RefChipList {...requiredProps} withOpenButton={false} /> ); expect(chipList.find('Add')).to.have.length(0); expect(chipList.find('IconButton')).to.have.length(1); }); it('clears the chip list when the trash button is pressed', () => { const chipList = mount(<RefChipList {...requiredProps} />); const trashButton = chipList.find('Delete'); trashButton.simulate('click'); expect(requiredProps.deleteAllRefs.callCount).to.equal(1); }); });
const listData = require('../Data/lists.json'); const problem2 = require('../callback2'); function cb(id) { return listData[id] } problem2(cb,"mcu453ed").then((res) =>{ console.log(res); });
class Observer { constructor(state) { this.state = state; this.subscribers = []; } get() { return this.state; } set(state) { this.state = state; this.broadcast(state); } subscribeMany(fnArray = []) { return fnArray.map(fn => this.subscribe(fn)); } subscribe(fn) { if (Array.isArray(fn)) { return this.subscribeMany(fn); } this.subscribers.push(fn); return () => (this.subscribers = this.subscribers.filter( subscriber => subscriber !== fn )); } broadcast(data) { this.subscribers.forEach(subscriber => subscriber(data)); return data; } } export default Observer;
import React from "react"; import styled from "styled-components"; import PropTypes from "prop-types"; import { whiteBackground } from "../themes"; const Container = styled.div` padding: 14px 9px; color: rgb(224, 36, 94); transition-property: background-color; transition-duration: 0.2s; cursor: pointer; text-align: center; &:hover { background-color: rgba(224, 36, 94, 0.1); } ${whiteBackground} `; function DeleteButton({ children }) { return <Container>{children}</Container>; } DeleteButton.propTypes = { children: PropTypes.node.isRequired }; export default DeleteButton;
describe("My whatCanIDrink function", function() { // A test suite begins with a call to the global Jasmine function describe with two parameters: a string and a function. beforeEach(function() { drink = new whatCanIDrink(); }); describe("Check age", function() { it("should exist", function() { expect(whatCanIDrink).toBeDefined(); }); it("should be unabl to return drink when called as whatCanIDrink(-2)", function() { var result = whatCanIDrink(-2) expect(result).toBe("Sorry. I can’t tell what drink because that age is incorrect!"); }); it("should return drink toddy when called as whatCanIDrink(13)", function() { var result = whatCanIDrink(13) expect(result).toBe("Drink Toddy"); }); it("should return drink coke when called as whatCanIDrink(17)", function() { var result = whatCanIDrink(17) expect(result).toBe("Drink Coke"); }); it("should return drink beer when called as whatCanIDrink(18)", function() { var result = whatCanIDrink(18) expect(result).toBe("Drink Beer"); }); it("should return drink beer when called as whatCanIDrink(20)", function() { var result = whatCanIDrink(20) expect(result).toBe("Drink Beer"); }); it("should return drink whisky when called as whatCanIDrink(31)", function() { var result = whatCanIDrink(31) expect(result).toBe("Drink Whisky"); }); it("should return drink whisky when called as whatCanIDrink(99)", function() { var result = whatCanIDrink(99) expect(result).toBe("Drink Whisky"); }); it("should bw unable to return what to drink when called as whatCanIDrink(140)", function() { var result = whatCanIDrink(140) expect(result).toBe("Sorry. I can’t tell what drink because that age is incorrect!"); }); }) });
import Upload from './container/Upload' export default Upload
'use strict'; import uniqueId from 'lodash.uniqueid'; export default { uniqueName(name) { return uniqueId(`${name}_capacitor_`); }, create(name, fn) { fn.toString = function () { return name; }; return fn; } }
import React from 'react'; class Filter extends React.Component { constructor(props) { super(props); this.state = { activeFilterIndex: 0, }; this.navItems = [ 'all', 'video', 'website', 'overig', ]; } onClickFilter(index) { this.props.changeFilterIndex(index); this.setState({ activeFilterIndex: index, }); } render() { const { activeFilterIndex } = this.state; let activeClass = ''; const nav = this.navItems.map((label, index) => { if (index === activeFilterIndex) { activeClass = 'active'; } else { activeClass = ''; } return <button key={label} onClick={() => this.onClickFilter(index)} className={`filter__${label}Button ${activeClass}`} > {label} </button>; }); return ( <nav> {nav} </nav> ); } } export default Filter;
function returnOddArray(){ newArray = []; for (var i = 0; i < 256; i++) { if (i % 2 == 1){ newArray.push(i); } } console.log(newArray); return newArray; } returnOddArray();
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const {CleanWebpackPlugin} = require('clean-webpack-plugin'); const {HotModuleReplacementPlugin, NamedModulesPlugin} = require('webpack'); module.exports = { // 入口 可以直接是一个String entry: './src/index.js', 等价于对象的写法 entry: { main: './src/index.js' // 如果是多页应用的引入 切记需要在输出与此对应 // pageOne: './src/views/pageOne.js', // pageTwo: './src/views/pageTwo.js', // pageThree: './src/views/pageThree.js' }, // 出口 output: { // 打包后的名字 // filename: './dist.js', // 如果是单一入口这样写是可以的 filename: '[name].js', // 如果是多入口 // __dirname是个变量,指的就是和当前目录路径 path: path.resolve(__dirname, 'dist') // 配置公共的cdn路径 会自动加到前缀 // publicPath: 'http://cdn.com' }, module: { // loader的执行顺序 从下到上 从右到左 eg:先转scss->sass-loader,然后css-loader,最后style-loader。 rules: [ // 图片 { test: /\.(jpeg|png|jpg|gif)$/, use: { // url-loader 能有 file-loader功能 区别是它转换成base64 直接放入到了js文件 而不会创建像file-loader一样的图片文件 // url-loader 优势就是直接放在js里面了 js加载完了图片就出来了 不会发起http请求 // url-loader 劣势就是直接放在js里面了 js是图片可能大 那么js文件就大 // 选择方式 根据图片的大小来决定 图片大file-loader;图片小url-loader // limit 是url-loader中options的独有属性,类似下面例子 小于200kb才执行 否则执行file-loader // 字体使用file-loader loader: 'url-loader', options: { // name就是原来的名字 hash是对应的hash ext是后缀 name: '[name]_[hash].[ext]', // 输出到指定的文件夹 outputPath: 'images/', // 小于200kb才执行 limit: 204800 } } }, // 字体 { test: /\.(eot|ttf|svg|woff)$/, use: { loader: 'file-loader' } }, // 样式 { test: /\.(scss)$/, // npm install --save-dev css-loader // 处理css 一般都会将 css-loader style-loader混合使用 // css-loader的作用是处理css之间的关系 比如在css文件中引入某css:@import './index.css' // style-loader 作用是将css-loader处理的文件挂载到head里面的style // sass-loader npm install sass-loader node-sass --save-dev // postcss-loader npm i -D postcss-loader // 解决的是类似处理-webkit-兼容的问题 自动加上 // 在使用postcss-loader时候需要在与webpack.config.js同目录下 新建postcss.config.js // module.exports = { // plugins: [require('autoprefixer')] 需要cnpm i autoprefixer --D // } // 如果要在每个loader中加上配置 可以在数组中写成对象的形式 use: [ 'style-loader', { loader: 'css-loader', options: { importLoaders: 2, // css模块化打包开启 需要注意引入css的语法 modules: true } }, 'sass-loader', 'postcss-loader' ] }, // babel处理es6 // npm install babel-loader babel-core babel-preset-env // babel-loader只是打开了es6与webpack的通道,转义是babel-core babel-preset-env // 这样处理还不能兼容一些函数,对象在低版本下的兼容 需要在index.js中引入 import '@babel/polyfill' (所有的) 所以参见presets的配置 { test: /\.js$/, // 除开什么目录的 exclude: /(node_modules)/, loader: 'babel-loader', options: { // 这样配置只会打包所用到的es6语法 不会所有的都打包,降低文件大小 presets: [['@babel/preset-env',{ useBuiltIns:'usage' }]] } } // 新建.babelrc也可以配置 ] }, // 插件 plugin 可以在webpack运行到某个时刻的时候 帮你做一些事 类似生命周期函数 plugins: [ // npm install --save-dev html-webpack-plugin 注意引入与实例 // 会自动在dist下生存index.html与引入bundle.js(dist.js) // 可以接收一个参数template 表示需要生存的模版 比如生成一个有div id='root'的节点 (自动生成的没有任何节点) new HtmlWebpackPlugin( { template: './src/index.html' } ), // npm install --save-dev clean-webpack-plugin // 每次打包的时候 会自动删除原来的dist new CleanWebpackPlugin(), // HMR插件 new HotModuleReplacementPlugin(), new NamedModulesPlugin() ], // 如果模式 development 不会压缩代码 一般根据 process.env.NODE_ENV 来动态处理 webpack --mode=production || development mode: 'development', // 开关sourceMap 在production默认是关闭none的,开启是 source-map。生产环境需要关闭,开发环境可以开启。 // sourceMap简单说,Source map就是一个信息文件,里面储存着位置信息。也就是说,转换后的代码的每一个位置,所对应的转换前的位置。有了它,出错的时候,除错工具将直接显示原始代码,而不是转换后的代码。这无疑给开发者带来了很大方便 // 在开发环境 建议使用 cheap-module-eval-source-map // 在生产环境 建议使用 none devtool: 'none', // 开发中的服务 // npm i webpack-dev-server -D 还需要安装 webpack-cli devServer: { // 作用的具体路径 contentBase: './dist', // 是否自动打开浏览器 open: true, // 设置端口 port: 8001, // 代理 将/api开头替换成http://localhost:3000 proxy: { '/api': { target: 'http://localhost:3000', pathRewrite: {'^/api': ''} } }, // HMR:模块热替换,比如解决只是改变样式,不刷新整个页面。 // 需要引入webpack的内置插件 注意引入的方式(解构体现) hot: true } };
import React, { Component } from 'react'; import styled from 'styled-components'; import PropTypes from 'prop-types'; import LoginForm from '../components/LoginForm'; import logo from '../logoPositivo.svg'; class Login extends Component { render() { const { history } = this.props; return ( <LoginDiv> <div data-testid="page-login"> <img src={ logo } alt="Logo do TrybeTunes" /> <LoginForm history={ history } /> </div> </LoginDiv> ); } } Login.propTypes = { history: PropTypes.objectOf(PropTypes.any).isRequired, }; const LoginDiv = styled.div` height: 100vh; div { display: flex; flex-direction: column; align-items: center; justify-content: center; } img { width: 15%; margin-bottom: 6.5rem; } `; export default Login;
/** * API interface for interacting with the Canvas to add, remove, and destroy entities */ /*global define */ define( ['models/entity', 'models/storage'], function (modelEntity, storage) { 'use strict'; var game = { createEntity: function (name, x, y) { // Setup entity var newEntity = new modelEntity[name](); newEntity.name = name; // Slice arguments to pass proper data to init if (arguments.length > 1 && newEntity.init) { // Remove name argument var args = [].slice.call(arguments, 1); // Fire the init with proper arguments newEntity.init.apply(newEntity, args); } else if (newEntity.init) { newEntity.init(); } // Store it storage.entities.push(newEntity); return newEntity; }, getTag: function (tag) { var stack = []; for (var i = 0; i < storage.entities.length; i++) { if (storage.entities[i].tag === tag) { stack.push(storage.entities[i]); } } return stack; } }; return game; });
export const getUser = (uid)=>{ return async(dispatch, getState, { getFirestore, getFirebase }) => { const firestore = getFirestore () await firestore.collection('users').doc(uid).onSnapshot((snapshot)=>{ let user = snapshot.data() dispatch({ type:'User', user:{ ...user, uid } }) }) } } export const getUsers = () => { return async(dispatch, getState, { getFirestore, getFirebase }) => { const firestore = getFirestore () await firestore.collection('users').onSnapshot((snapshot)=>{ let users = snapshot.docs.map((doc)=>{ return { ...doc.data(), uid:doc.id, } }) dispatch({ type:'AllUsers', users }) }) } } export const follow = (follower, following) => { return ( (dispatch, getState, {getFirestore})=>{ const firestore = getFirestore() firestore .collection("users") .doc(following) .update({ followers:firestore.FieldValue.arrayUnion(follower) }) .then(()=>{ firestore .collection("users") .doc(follower) .update({ following:firestore.FieldValue.arrayUnion(following) }) .then(()=>{ dispatch({ type:"ConnectionSuccess" }) }) .catch(err=>{ dispatch({ type:"ConnectionErr", err:err.message }) }) }) .catch(err=>{ dispatch({ type:"ConnectionErr", err:err.message }) }) } ) } export const unfollow = (unfollower, unfollowing) => { return( (dispatch, getState, {getFirestore})=>{ const firestore = getFirestore() firestore .collection("users") .doc(unfollowing) .update({ followers:firestore.FieldValue.arrayRemove(unfollower) }) .then(()=>{ firestore .collection("users") .doc(unfollower) .update({ following:firestore.FieldValue.arrayRemove(unfollowing) }) .then(()=>{ dispatch({ type:"ConnectionSuccess" }) }) .catch(err=>{ dispatch({ type:"ConnectionErr", err:err.message }) }) }) .catch(err=>{ dispatch({ type:"ConnectionErr", err:err.message }) }) } ) }
var scrollerBtn = document.getElementById("scroller-btn"); scrollerBtn.onclick = function() { // code let current = window.scrollY; let scrollInterval = setInterval(function(){ if(window.scrollY > 10){ window.scroll(0, current); current -= 60; } else{ clearInterval(scrollInterval); } }, 10); } $(function(){ $('.carousel').carousel({ interval: 3800 }) }) var scrollAnimationElements = document.getElementsByClassName("scroll-animation"); function hasScrolledIntoView(el){ var elTop = el.offsetTop; var elBottom = el.offsetHeight + elTop; var winTop = window.scrollY; var winBottom = window.innerHeight + winTop; return (winTop < elTop && elBottom < winBottom); } window.addEventListener("scroll", function(){ if(window.scrollY > 500){ scrollerBtn.style.transform = "scale(1)"; } else{ scrollerBtn.style.transform = "scale(0)"; } for(i=0; i<scrollAnimationElements.length; i++){ var temp; if(hasScrolledIntoView(temp = scrollAnimationElements[i])){ scrollAnimationElements[i].style.animationDuration = "1.5s"; if(temp.hasAttribute("data-animation")){ temp.classList.add("animated", temp.getAttribute("data-animation")); } else{ temp.classList.add("animated", "bounceInRight"); } temp.style.visibility = "visible"; } } }, false);
const daftarvip = (prefix) => { return ` *SE QUER SER VIP ENTRE EM CONTATO:* *Proprietários do BOT :* _wa.me/553181003881 _wa.me/5528999995062 ` } exports.daftarvip = daftarvip
import React, { Component } from 'react'; import axios from 'axios'; import { Empty, Result, Select } from 'antd'; import './committees.css'; const { Option } = Select; class Committees extends Component { constructor(props) { super(props); this.state = { committees: [], error: {}, loading: true, }; this.fetchCommittees = this.fetchCommittees.bind(this); this.handleChange = this.handleChange.bind(this); } componentDidMount() { this.fetchCommittees(); } fetchCommittees() { axios .get('/api/committees') .then(response => { this.setState({ committees: response.data, loading: false, selected: 0, error: {}, }); }) .catch(err => { this.setState({ error: { message: err.response.data.error, code: err.response.status }, loading: false, }); }); } handleChange(value) { this.setState({ selected: value, }); } renderBody = () => { if (this.state.selected === 0) { return ( <div className="aligner-item"> <Empty /> </div> ); } if (Object.keys(this.state.error).length !== 0) { return ( <div className="aligner-item"> <Result status="500" title={this.state.error.code} subTitle={this.state.error.message} /> </div> ); } return ( <div> {JSON.stringify( this.state.committees.find( committee => committee.committee_id === this.state.selected ) )} </div> ); }; render() { const options = this.state.committees.map(committee => ( <Option key={committee.committee_id} value={committee.committee_id}> {committee.name} </Option> )); return ( <div className="aligner"> <div> <Select className="aligner-item aligner-item--top-left select" showSearch placeholder="Select a committee" optionFilterProp="children" onChange={this.handleChange} filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 } dropdownMatchSelectWidth={false} size="large" loading={this.state.loading} > {options} </Select> </div> {this.renderBody()} </div> ); } } export default Committees;
'use strict' class TaskController { async create({ auth, request, response }) { try { await auth.check() } catch (error) { response.status(401); return { ok: false, error: { msj: 'Token no proveido o invalido' } } } const { title, description, project_id } = request.all(); const Task = use('App/Models/Task') const task = new Task(); task.title = title; task.description = description; task.project_id = project_id; try { await task.save(); return { ok: true, task } } catch (e) { response.status(401); error = e; return { ok: false, error } } } async done({ auth, request,response }) { try { await auth.check() } catch (error) { response.status(401); return { ok: false, error: { msj: 'Token no proveido o invalido' } } } const { id } = request.all(); const Task = use('App/Models/Task') await Task .query() .where('id', id) .update({ done: true }) return { ok: true } } async delete({ auth, params,response }) { try { await auth.check() } catch (error) { response.status(401); return { ok: false, error: { msj: 'Token no proveido o invalido' } } } try { const Task = use('App/Models/Task') const id = params.id; const task = await Task.findBy('id',id); if(!task){ return { ok: true,} } await task.delete(); return {ok:true} } catch (error) { response.status(401); return {ok:false, error} } } } module.exports = TaskController
import React from 'react' import {Route,Switch} from 'react-router-dom' import Landing from './Components/Landing/Landing' import Guide from './Components/Guide/Guide' import Build from './Components/Build/Build' import List from './Components/List/List' import Comp_case from './Components/PC_components/Comp_Case/Comp_case' import Case_Fan from './Components/PC_components/Case_Fan/Case_Fan' import Computer_Speakers from './Components/PC_components/Computer_Speakers/Computer_Speakers' import Cpu from './Components/PC_components/Cpu/Cpu' import CpuCooler from './Components/PC_components/CpuCooler/CpuCooler' import External_Storage from './Components/PC_components/External_Storage/External_Storage' import Fan_Controller from './Components/PC_components/Fan_Controller/Fan_Controller' import Headphones from './Components/PC_components/Headphones/Headphones' import Keyboard from './Components/PC_components/Keyboard/Keyboard' import Memory from './Components/PC_components/Memory/Memory' import Monitor from './Components/PC_components/Monitor/Monitor' import MotherBoard from './Components/PC_components/MotherBoard/MotherBoard' import Mouse from './Components/PC_components/Mouse/Mouse' import Operating_System from './Components/PC_components/Operating_System/Operating_System' import Optical_Drive from './Components/PC_components/Optical_Drive/Optical_Drive' import Power_Supply from './Components/PC_components/Power_Supply/Power_Supply' import Software from './Components/PC_components/Software/Software' import Sound_Card from './Components/PC_components/Sound_Card/Sound_Card' import PCStorage from './Components/PC_components/PCStorage/PCStorage' import Thermal_Compound from './Components/PC_components/Thermal_Compound/Thermal_Compund' import UPS from './Components/PC_components/UPS/UPS' import Video_Card from './Components/PC_components/Video_Card/Video_Card' import Wired_NetWork_Card from './Components/PC_components/Wired_NetWork_Card/Wired_NetWork_Card' import Wireless_Network_Card from './Components/PC_components/Wireless_Network_Card/Wireless_Network_Card' import CpuPage from './Components/PC_components/Cpu/CpuPage' import CpuCoolerPage from './Components/PC_components/CpuCooler/CpuCoolerPage' import MotherboardPage from './Components/PC_components/MotherBoard/MotherboardPage' import IndvidualParts from './Components/IndividualParts/IndividualParts' export default( <Switch> <Route exact path='/' component={Landing}/> <Route path='/list' component={List}/> <Route path='/guide' component={Guide}/> <Route path='/build' component={Build}/> <Route path='/indvidual-parts' component={IndvidualParts}/> <Route path='/comp-case' component={Comp_case}/> <Route path='/case-fan' component={Case_Fan}/> <Route path='/speakers' component={Computer_Speakers}/> <Route exact path='/cpu' component={Cpu}/> <Route exact path='/cpu-cooler' component={CpuCooler}/> <Route path='/external-storage' component={External_Storage}/> <Route path='/fan-controller' component={Fan_Controller}/> <Route path='/headphones' component={Headphones}/> <Route path='/Keyboard' component={Keyboard}/> <Route path='/memory' component={Memory}/> <Route path='/monitor' component={Monitor}/> <Route exact path='/motherboard' component={MotherBoard}/> <Route path='/mouse' component={Mouse}/> <Route path='/os' component={Operating_System}/> <Route path='/optical' component={Optical_Drive}/> <Route path='/power-supply' component={Power_Supply}/> <Route path='/software' component={Software}/> <Route path='/sound-card' component={Sound_Card}/> <Route path='/internal-storage' component={PCStorage}/> <Route path='/thermal-compound' component={Thermal_Compound}/> <Route path='/ups' component={UPS}/> <Route path='/video-card' component={Video_Card}/> <Route path='/wired-network-card' component={Wired_NetWork_Card}/> <Route path='/wireless-network-card' component={Wireless_Network_Card}/> <Route path='/cpu/:id' component={CpuPage}/> <Route path='/cpu-cooler/:id' component={CpuCoolerPage}/> <Route path='/motherboard/:id' component={MotherboardPage}/> </Switch> )
/** * @module monitoring api */ var EventEmitter = require('events').EventEmitter; var _ = require('lodash'); var application = require('./application'); var properties = require('./properties'); var logger = require('./logger')('hubiquitus:core:monitoring'); var actors = require('./actors'); var cache = require('./cache'); var discovery = require('./discovery'); var adapters = { inproc: require('./adapters/inproc'), remote: require('./adapters/remote') }; var toobusy = require('toobusy'); exports.__proto__ = new EventEmitter(); exports.setMaxListeners(0); /* * Listeners setup */ actors.on('actor added', function (aid) { exports.emit('actor added', aid); }); actors.on('actor removed', function (aid) { exports.emit('actor removed', aid); }); cache.on('actor added', function (aid, cid) { exports.emit('cache actor added', aid, cid); }); cache.on('actor removed', function (aid, cid) { exports.emit('cache actor removed', aid, cid); }); cache.on('cleared', function () { exports.emit('cache cleared'); }); discovery.on('discovery started', function (aid) { exports.emit('discovery started', aid); }); discovery.on('discovery stopped', function (aid) { exports.emit('discovery stopped', aid); }); discovery.on('discovery', function (aid) { exports.emit('discovery', aid); }); _.forEach(adapters, function (adapter) { adapter.on('req sent', function (req) { exports.emit('req sent', req); }); adapter.on('req received', function (req) { exports.emit('req received', req); }); adapter.on('res sent', function (res) { exports.emit('res sent', res); }); adapter.on('res received', function (res) { exports.emit('res received', res); }); }); /** * Returns actors * @returns {Array} actors */ exports.actors = function () { return actors.all(); }; /** * Returns cache * @return {Object} cache */ exports.cache = { actors: cache.actors, containers: cache.containers }; /** * Returns current discoveries with the last research date for each of them * @returns {Object} discoveries */ exports.discoveries = function () { return discovery.discoveries(); }; /* * Ping management */ application.addActor(properties.container.id + '_ping', function (req) { logger.makeLog('trace', 'hub-51', 'ping', {req: req}); req.reply(); }); /** * Ping a container * @param cid {String} target container id * @param cb {Function} callback */ exports.pingContainer = function (cid, cb) { application.send(properties.container.id, cid + '_ping', 'PING', properties.containerPingTimeout, function (err) { cb(err); }); }; /** * Container event loop round in ms * @returns {Number} */ exports.lag = function () { return toobusy.lag(); }; /** * check if event loop load is over threshold * @returns {Boolean} */ exports.toobusy = function () { return toobusy(); };
var koa = require('koa'); var app = new koa(); var convert = require('koa-convert'); app.use(convert(function*() { this.body = '<h1>헬로 월드!~</h1>'; })); app.listen(3000, function() { console.log('서버 로드 ! port : 3000'); });
(function(){ // 图片 var imgs = ["img/1.jpg","img/2.jpg","img/3.jpg","img/4.jpg"]; //z-index的值 var z = 999999; //显示第几张图片 var index = 0; var boxx = document.getElementById('boxx') boom(10,5) //l 传进来几行;t传进来几列; function boom(l,t) { //创建一个新的div var oParentNode = document.createElement("div"); //设置z-index的值 oParentNode.style.zIndex = z; z--; boxx.appendChild(oParentNode); var x = l,y = t; for(var i = 0; i < y;i++){ for(var j = 0;j<x;j++){ //创建碎片 var oDiv = document.createElement("div"); //添加背景图片 oDiv.style.background = "url("+imgs[index]+")"; oDiv.style.width = boxx.clientWidth / x + 'px'; oDiv.style.height = boxx.clientHeight / y + 'px'; oDiv.style.left = (boxx.clientWidth / x) * j +'px'; oDiv.style.top = (boxx.clientHeight / y) * i +'px'; oDiv.style.backgroundPositionX = (boxx.clientWidth/ x)* -j + 'px'; oDiv.style.backgroundPositionY= (boxx.clientHeight/y)* -i + 'px'; oDiv.style.transition = (Math.random()*1+0.5)+"s"; oParentNode.appendChild(oDiv); } }; var allDiv = oParentNode.children; setTimeout(()=>{ index++; index == imgs.length && (index = 0); boom(l,t); for(var i= 0;i<allDiv.length;i++){ allDiv[i].style.transform = 'perspective(800px) rotateX('+ (Math.random()*500-250)+'deg) rotateY('+(Math.random()*500-250)+'deg) translateX('+(Math.random()*500-250)+'px) translateY('+(Math.random()*500-250)+'px) translateZ('+(Math.random()*1000-500)+'px)' allDiv[i].style.opacity = 0; }; },4000); setTimeout(function(){ oParentNode.remove(); },5500) } })()
import React from 'react'; import PropTypes from 'prop-types'; import LoadingView from './loading_view'; import ModalView from './modal_view'; /** * @return {component} The component of shopcart */ class ShopCart extends React.Component { /** * 結帳事件,尚未實作 */ handleCheckout() { alert('It\'s just a demo project!'); } /** * 處理刪除事件的程式碼,會先跳出Modal來讓使用者確認是否需要刪除 * @param {int} id * @param {int} index */ handleDelete(id, index) { this.setState({id: id, index: index, show_delete_check: true}); } /** * 處理刪除事件的回傳程式碼 * @param {bool} result */ handleDeleteCallback(result) { this.setState({show_delete_check: false}); if (result) { this.props.actions.deleteFromShopcart(this.state.id, this.state.index); } } /** * 跳出提示視窗詢問是否要刪除 * @return {null} */ showDeleteModal() { if (this.state && this.state.show_delete_check == true) { return ( <ModalView title="確認" content="是否要刪除此項目?" callback={(result) => this.handleDeleteCallback(result)} /> ); } } /** * @return {component} * @param {int} index * @param {object} product * @param {int} amount * @param {int} total */ itemDetail(index, product, amount, total) { return ( <tr key={index}> <td>{index + 1}</td> <td>{product.title}</td> <td> <select value={amount.toString()} className="form-control" onChange={(e) => this.props.actions.updateAmountToShopcart(index, parseInt(e.target.value))}> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </td> <td>{product.price - product.discount}</td> <td>{total}</td> <td> <button className="btn btn-danger" onClick={()=> this.handleDelete(product.id, index)}> <i className="fa fa-times" aria-hidden="true"></i> 刪除 </button> </td> </tr> ); } /** * @return {component} */ render() { let shopcartList = this.props.shopcart_list .map((item, index) => this.itemDetail(index, item.product, item.amount, item.total)); let renderChild = null; if (this.props.is_loading) { renderChild= <LoadingView/>; } else { renderChild = ( <table className="table"> <thead> <tr> <th>#</th> <th>品項</th> <th>數量</th> <th>價錢</th> <th>小計</th> <th>動作</th> </tr> </thead> <tfoot> <tr> <td></td> <td></td> <td></td> <td><b>總計</b></td> <td>{this.props.sum}</td> <td> <button className="btn btn-success" onClick={() => this.handleCheckout()}> <i className="fa fa-shopping-cart" aria-hidden="true"></i> 結帳 </button> </td> </tr> </tfoot> <tbody> {shopcartList} </tbody> </table> ); } return ( <div> <h2>購物車</h2> {this.showDeleteModal()} {renderChild} </div> ); } } ShopCart.propTypes = { actions: PropTypes.object.isRequired, sum: PropTypes.number.isRequired, shopcart_list: PropTypes.array.isRequired, is_loading: PropTypes.bool.isRequired, }; export default ShopCart;
import React from 'react' import {Link} from 'react-router-dom' import {API_ROOT, GET_HEADERS, GET_REQ} from '../constants/index' export default class joinPage extends React.Component{ //state for component class state = { event: {}, errors: [] } //fetches information about event componentDidMount(){ fetch(`${API_ROOT}/events/${this.props.match.params.id}`, GET_REQ()) .then(resp => resp.json()) .then(event => this.setState({event})) } //submits information about new joinee for event submitForm = e => { e.preventDefault() const {first_name, last_name, email, ideas} = e.target const reqObj = { method: 'POST', headers: GET_HEADERS(), body: JSON.stringify({users: {first_name: first_name.value, last_name: last_name.value, email: email.value, ideas: ideas.value, event_id: this.state.event.id}}) } fetch(`${API_ROOT}/users`, reqObj) .then(resp => resp.json()) .then(data => { if (!data.errors) { alert(`Thank you, ${data.first_name}. Your information has been received and you will be sent an email with the name of the person you are to give a gift to once the admin closes the sign-up.`) this.props.history.push('/') } else { this.setState({errors: data.errors}) } }) } //renders form based on whether or not the eventees have already been matched renderForm = () => { if (this.state.event['users']) { if (this.state.event.users.length === 0) { return ( <> <form onKeyDown={(e) => { if (e.key === 13 && e.target.type !== 'textarea') {e.preventDefault()}}} onSubmit={this.submitForm}> <h2>Please Fill Out Information* to Join Event</h2> <p>{this.state.errors}</p> <input type="text" name="first_name" placeholder="First Name" /> <input type="text" name="last_name" placeholder="Last Name" /><br></br> <input type="email" name="email" placeholder="Email" /><br></br> <textarea rows={7} name="ideas" placeholder={"Gift Ideas"}></textarea><br></br> <button type="submit">Submit</button> </form> </> ) } else if (this.state.event.users[0] && !this.state.event.users[0].match) { return( <> <form onKeyDown={(e) => { if (e.key === 13 && e.target.type !== 'textarea') {e.preventDefault()}}} onSubmit={this.submitForm}> <h2>Please Fill Out Information* to Join Event</h2> <p>{this.state.errors}</p> <input type="text" name="first_name" placeholder="First Name" /> <input type="text" name="last_name" placeholder="Last Name" /><br></br> <input type="email" name="email" placeholder="Email" /><br></br> <textarea rows={7} name="ideas" placeholder={"Gift Ideas"}></textarea><br></br> <button type="submit">Submit</button> </form> </> ) } else { return (<p>We're sorry, the signups for this event has been closed by the admin.</p>) } } } //renders page render(){ const {code, start, end, max_price, notes} = this.state.event return( <div className="screen"> <div className="snowfall"> <div className="pageBody"> <div className="welcome"> <h2>Welcome to</h2> <Link to="/"><h1 className="ss">❄❄❄ Secret Santa ❄❄❄</h1></Link> </div> <div className="options eventPage"> <div className="event-code"> <h2>Event Code: {code}</h2> </div> <div className="dates"> {start ? <div> <h4>Start Date</h4> <p>{start}</p> </div> : null} {end ? <div> <h4>End Date</h4> <p>{end}</p> </div> : null} </div> {max_price ? <> <h4>Max Price: ${max_price}</h4> </> : null} {notes ? <> <h4>Additional Notes</h4> <p>{notes}</p> </> : null} </div> {this.renderForm()} </div> </div> </div> ) } }
import React, { Component } from 'react' import Symbols from './symbol' import promise from './promise' export default class componentName extends Component { render() { // function foo({ x, y = 5 } = {}) { // console.log(x, y); // }; function foo({ x = 4, y = 5 } = {}) { console.log(x, y); } foo(); function fetch(url, { body = '', method = 'GET', headers = {} } = {}) { console.log(body); console.log(method); console.log(headers); } fetch('http://example.com'); return ( <div> {/* <Symbols /> */} <Promise /> </div> ) } }
const invariant = require("invariant"); const glViewMethods = require("./glViewMethods"); module.exports = function (React) { class GLComponent extends React.Component { constructor (props, context) { super(props, context); glViewMethods.forEach(methodname => { if (!this[methodname]) this[methodname] = () => invariant(true, "'%s' method is not available in deprecated GL.Component. Use GL.createComponent(props => glView) instead"); }); if (process.env.NODE_ENV !== "production") console.error("GL.Component class is deprecated. Use GL.createComponent(props => glView) function instead"); // eslint-disable-line no-console } } GLComponent.isGLComponent = true; return GLComponent; };
import { defineMatrixLength, cachedValueOf } from './operator'; import { multiplyMat3Mat3, multiplyMat3Vec } from './utils/math'; const AXES = Symbol('data'); class AMat3 { constructor (...columns) { this[AXES] = columns; } get [0] () { return this[AXES][0]; } set [0] (_) { throw new Error('set [0] not implemented'); } get [1] () { return this[AXES][1]; } set [1] (_) { throw new Error('set [1] not implemented'); } get [2] () { return this[AXES][2]; } set [2] (_) { throw new Error('set [2] not implemented'); } multiplyMat (other) { return multiplyMat3Mat3(this, other); } multiplyVec (other) { return multiplyMat3Vec(this, other); } multiply (other) { if (other instanceof AMat3) { return this.multiplyMat(other); } const { x, y, z } = other; if (x === undefined || y === undefined || z === undefined) { throw new Error(`multiply only works with mat3 and vec3, not supported ${other}`); } return this.multiplyVec(other); } [Symbol.iterator] () { return this[AXES].values(); } } cachedValueOf(AMat3); defineMatrixLength(AMat3); export class IMat3 extends AMat3 { }
(function () { 'use strict'; define(["./sprite-base", "./vector-maths"], function (SpriteBase, vectorMaths) { Ball.prototype = new SpriteBase(); Ball.prototype.constructor = Ball; function Ball() { this.position = { x: 400, y: 200 }; this.velocity = { x: 0, y: 0 }; this.radius = 25; this.sceneSpeed = { x: 0, y: 0 }; } Ball.prototype._draw = function draw(context) { context.beginPath(); context.arc(0, 0, 25, 0, 2 * Math.PI, false); context.closePath(); // shadow //context.shadowColor = '#BBB'; //context.shadowBlur = 20; //context.shadowOffsetX = 15; //context.shadowOffsetY = 15; // fill // create radial gradient var grd = context.createRadialGradient(10, -10, 10, 10, -10, 30); // light grd.addColorStop(0, '#FFFFFF'); // dark grd.addColorStop(1, '#A0A0A0'); context.fillStyle = grd; context.fill(); // line context.lineWidth = 2; context.strokeStyle = '#404040'; context.stroke(); }; var gravity = 3000; var resistance = 100; Ball.prototype.animate = function (sElapsed) { // Affect of gravity this.velocity.y += sElapsed * gravity; // Affect of air resistance this.velocity.x -= this.velocity.x / resistance; this.velocity.y -= this.velocity.y / resistance; this.position.x += sElapsed * (this.velocity.x - this.sceneSpeed.x); this.position.y += sElapsed * (this.velocity.y - this.sceneSpeed.y); }; Ball.prototype.struck = function (vector, overshot) { this.velocity.x += vector.x; this.velocity.y += vector.y; var vectorLen = vectorMaths.lineLength(vector); // Correct the overshoot this.position.x += overshot * vector.x / vectorLen; this.position.y += overshot * vector.y / vectorLen; // Vibrate and sound volume var volume = vectorLen / 3000; if (volume > 1) volume = 1; setTimeout(function () { vibrate(volume); playSound(volume); }, 1); }; var vibrate = function vibrate() { if (navigator && navigator.vibrate) navigator.vibrate(10); }; var ballSoundSrc = 'sound/pingpong_ball_once.mp3'; var ballSoundLoaded = false; var ballBoundSound = window.Media ? new Media('/android_asset/www/' + ballSoundSrc, function () { ballSoundLoaded = true; }, function (err) { console.log("playAudio():Audio Error: " + err); }) : new Audio(ballSoundSrc); var playSound = function playSound(volume) { if (ballBoundSound.setVolume) ballBoundSound.setVolume(volume); else ballBoundSound.volume = volume; ballBoundSound.play(); }; return Ball; }); })();
const request = require('request') const weather = (url, callback)=>{ request({url : url,json : true},(error, response)=>{ if(error) { callback("Unable to connect weather service!", undefined) } else if(response.body.message) { callback("City not found", undefined) } else { callback(undefined,{ temp : response.body.main.temp, humidity : response.body.main.humidity, name : response.body.name }) } }) } module.exports = weather
import UIkit from 'uikit'; import Icons from 'uikit/dist/js/uikit-icons'; // loads the Icon plugin UIkit.use(Icons); import Vue from 'vue'; import App from './app.vue'; import router from './router'; const app = new Vue({ el: '#root', template: `<app></app>`, components: {App}, router });
import React, { Component } from "react"; import Paper from "@material-ui/core/Paper"; import "./style.css"; class SingleRecipe extends Component { constructor(props) { super(props); this.state = {}; } render() { return ( <Paper elevation={1} className="dashboardRecepe"> {this.props.meal.label ? ( <div> <div className="bg-header"> <img className="card-img" src={this.props.meal.image} alt={this.props.meal.label} /> <h1> <a href={this.props.meal.url} target="_blank"> <i class="fas fa-external-link-square-alt" />{" "} <span>Meal: {this.props.meal.label}</span> </a> </h1> </div> <div className="bodyCard"> <div> <h5> <i class="fas fa-utensils" /> Calories: <p className="bold"> {" "} {Math.round(this.props.meal.calories)} cal </p> </h5> </div> <div> <h5> {" "} <i class="fas fa-info-bold" /> Nutrition information: </h5> <ul> <li> Fat: <span className="bold"> {Math.round(this.props.meal.fat)} g </span> </li> <li> Carbohydrate: <span className="bold"> {Math.round(this.props.meal.carb)} g </span> </li> <li> Protein: <span className="bold"> {Math.round(this.props.meal.protein)} g </span> </li> </ul> </div> <div> <h5> <i class="far fa-list-alt" /> Ingredients: </h5> <ul> {this.props.meal.ingredients.map((item, i) => { return ( <li key={i}> <i class="fas fa-chevron-right" /> {item} </li> ); })} </ul> </div> <div> <h5> <i class="far fa-clock" /> Prep time: <span className="bold"> {this.props.meal.time} min</span> </h5> </div> </div> </div> ) : ( "" )} </Paper> ); } } export default SingleRecipe;
var http = require('http'); var fs = require('fs'); var server = http.createServer(); var port = 3000; server.listen(port, function(){ console.log("WebServer Starting : %d", port); }); // client connection Event processing server.on('connection', function(socket){ var addr = socket.address(); console.log('Access the client : %s %d', addr.address, addr.port); }); // Event Processing client request server.on('request',function(req,res){ console.log('클라이언트 요청이 들어옴'); var filename = 'house.png'; var infile = fs.createReadStream(filename, {flags:'r'}); // 스트림객체로 파일읽음, 'r'은 파일 읽음을 나타냄 var filelength = 0; var curlength = 0; fs.stat(filename, function(err,stats) { filelength = stats.size; //// Q-0. stats??? }); // write Head res.writeHead(200, {"Content-Type":"image/png"}); // 파일 내용을 스트림에서 읽어 본문 쓰기 infile.on('readable', function(){ var chunk; while (null !== (chunk = infile.read())) { console.log('읽어 들인 데이터 크기 : %d 바이트', chunk.length); curlength += chunk.length; res.write(chunk,'utf-8', function(err) { // 이 콜백함수는 쓰기 완료 시점을 확인하기 위한 용도이다 console.log('파일 부분 쓰기 완료 : %d, 파일 크기 : %d', curlength, filelength ); if(curlength >= filelength) { // 응답객체에 쓰는 작업이 모두완료되었다면! // 응답 전송하기 res.end(); // end메소드를 호출하는 시점은 write()메소드가 종료된 시점이므로 write()메소드에 콜백함수를 전달하여 쓰기가 완료된 시점을 확인 }; }); }; }); }); server.on('close', function(){ console.log('Termination the server'); });
function getPatientFromForm(form) { const patient = { name: form.name.value, weight: form.weight.value, height: form.height.value, fat: form.fat.value, bmi: calculatesBmi(form.weight.value, form.height.value) } return patient; } function buildsTd(data, className) { const td = document.createElement("td"); td.classList.add(className); td.textContent = data; return td; } function buildTr(patient) { const patientTr = document.createElement("tr"); patientTr.classList.add("patient"); patientTr.appendChild(buildsTd(patient.nome, "info-name")); patientTr.appendChild(buildsTd(patient.peso, "info-weight")); patientTr.appendChild(buildsTd(patient.altura, "info-height")); patientTr.appendChild(buildsTd(patient.gordura, "info-fat")); patientTr.appendChild(buildsTd(patient.imc, "info-bmi")); return patientTr; } function validatesPatient(patient) { const errors = []; if (patient.name.length == 0) { errors.push("The name cannot be blank"); } if (patient.weight.length == 0) { errors.push("The weight cannot be blank"); } if (patient.height.length == 0) { errors.push("The height cannot be blank"); } if (patient.fat.length == 0) { errors.push("The fat cannot be blank"); } if (!isValidWeight(patient.weight)) { errors.push("Invalid weight"); } if (!isValidHeight(patient.height)) { errors.push("Invalid height"); } return errors; } function showErrorsMessage(errors) { const ul = document.querySelector("#errors-message"); ul.innerHTML = ""; errors.forEach(function (error) { const li = document.createElement("li"); li.textContent = error; ul.appendChild(li); }); } function addPatient(patient) { const patientTr = buildTr(patient); const table = document.querySelector("#table-patients"); table.appendChild(patientTr); } const addButton = document.querySelector("#add-patient"); addButton.addEventListener("click", function (event) { event.preventDefault(); const form = document.querySelector("#form-add"); const patient = getPatientFromForm(form); const errors = validatesPatient(patient); if (errors.length > 0) { showErrorsMessage(errors); return } addPatient(patient); form.reset(); const errorsMessage = document.querySelector("#errors-message"); errorsMessage.innerHTML = ""; });
'use strict'; const _serializeSingleReservation = (reservation) => { return { 'id': reservation.id, 'clientId': reservation.clientId, 'movies': reservation.movies, 'date': reservation.date, 'status': reservation.status, 'subtotal': reservation.subtotal, 'deliveryDate': reservation.deliveryDate, 'created_at': reservation.created_at, 'updated_at': reservation.updated_at }; }; module.exports = class { serialize(data) { if (!data) { throw new Error('Expect data to be not undefined nor null'); } if (Array.isArray(data)) { return data.map(_serializeSingleReservation); } return _serializeSingleReservation(data); } };
'use strict'; // Any object which doesn't have property that we will try to access. var myObject = { foo: 'foo' }; // Overwrite default action, which gets objects property. myObject = new Proxy(myObject, { // Overwrite default getter. get: function (o, name) { // Check if target object contains passed property if (!Object.prototype.hasOwnProperty.call(o, name)) { // If not, the error will be thrown throw new ReferenceError(`Object property '${name}' is not defined (try to define the new one using null value)`); } // In default mode, we return existing property. return o[name]; } }); // Print existing property (finished successfully). console.log(myObject.foo); // "foo" // Try to print non-existing property. // Once the Proxy is not used, the `undefined` value will be printed. // After overwrite the default behaviour of getting property values, the ReferenceError will be thrown. console.log(myObject.bar);
import shared from 'shared/utils/helpers'; var helpers = Object.assign({}, shared, { getObjectUrl(base, id){ return `${base}${id}/`; }, getTestUrl(host, route){ return `${host}${route}`; }, getEndpointsUrl(config, study_id=[], effect=[]){ let effects = effect.join(','), study_ids = study_id.join(','); return `${config.host}${config.endpoint_filter_url}&study_id[]=${study_ids}&effect[]=${effects}`; }, errorDict: { endpoints: 'Filtering results contain more than 100 endpoints. Increase the quality threshold or include fewer effects.', effects: 'At least one effect must be chosen.', empty: 'No endpoints were returned. Decrease the quality threshold or include more effects.', }, formatErrors(error){ error = error.substr(-9); return helpers.errorDict[error]; }, }); export default helpers;
(function() { const quotes = [{ quote: ' Tô fazendo amor com a favela toda.', author: 'Mc Jessica' }, { quote: ' Não acho que quem ganhar ou quem perder, nem quem ganhar nem perder, vai ganhar ou perder. Vai todo mundo perder.', author: 'Dilma Rousseff' }, { quote: ' BRASIIIIIIIIIILLLLLLL', author: 'Gil do Vigor' }, { quote: ' O verde é esperança, né? O amarelo, sei lá, desespero. O azul não sei.', author: 'Benedita da Conceição' }, { quote: ' Uuuuuuuuuuuuuuur. Ahhhhhhhhhrrrrrrr Uhrrrr. Ahhhhrrrrrr. Aaaarhg.', author: 'Chewbacca' }, { quote: ' Qualquer coisa me bota no paredawn.', author: 'Karol Conká' }, { quote: ' À esquerda, à esquerda.', author: 'Beyoncé' }, { quote: ' Quando o grave bater eu vou quicar.', author: 'Pabllo Vittar' }, { quote: ' Olha aqui menino, quantos anos você tem? Sei que cê tá lindo e merece parabéns.', author: 'Pabllo Vittar' }, { quote: ' Soy el fuego que.', author: 'Alok', }, ]; const btn = document.getElementById("generate-btn"); btn.addEventListener("click", function() { const random = Math.floor(Math.random() * quotes.length); console.log(random); document.getElementById("quote").textContent = quotes[random].quote; document.querySelector(".author").textContent = quotes[random].author; }); })();
window.esdocSearchIndex = [ [ "unpleasant/src/basicperlin.js~basicperlin", "function/index.html#static-function-basicPerlin", "<span>basicPerlin</span> <span class=\"search-result-import-path\">unpleasant/src/basicPerlin.js</span>", "function" ], [ "unpleasant/src/cellular2d.js~cellular2d", "function/index.html#static-function-cellular2D", "<span>cellular2D</span> <span class=\"search-result-import-path\">unpleasant/src/cellular2D.js</span>", "function" ], [ "unpleasant/src/classicperlin2d.js~classicperlin2d", "function/index.html#static-function-classicPerlin2D", "<span>classicPerlin2D</span> <span class=\"search-result-import-path\">unpleasant/src/classicPerlin2D.js</span>", "function" ], [ "unpleasant/src/generic11d.js~generic11d", "function/index.html#static-function-generic11D", "<span>generic11D</span> <span class=\"search-result-import-path\">unpleasant/src/generic11D.js</span>", "function" ], [ "unpleasant/src/generic12d.js~generic12d", "function/index.html#static-function-generic12D", "<span>generic12D</span> <span class=\"search-result-import-path\">unpleasant/src/generic12D.js</span>", "function" ], [ "unpleasant/src/generic2.js~generic2", "function/index.html#static-function-generic2", "<span>generic2</span> <span class=\"search-result-import-path\">unpleasant/src/generic2.js</span>", "function" ], [ "unpleasant/src/generic3.js~generic3", "function/index.html#static-function-generic3", "<span>generic3</span> <span class=\"search-result-import-path\">unpleasant/src/generic3.js</span>", "function" ], [ "unpleasant/src/simplex2d.js~simplex2d", "function/index.html#static-function-simplex2D", "<span>simplex2D</span> <span class=\"search-result-import-path\">unpleasant/src/simplex2D.js</span>", "function" ], [ "src/.external-ecmascript.js~array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array", "src/.external-ecmascript.js~Array", "external" ], [ "src/.external-ecmascript.js~arraybuffer", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer", "src/.external-ecmascript.js~ArrayBuffer", "external" ], [ "src/.external-ecmascript.js~boolean", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean", "src/.external-ecmascript.js~Boolean", "external" ], [ "src/.external-ecmascript.js~dataview", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView", "src/.external-ecmascript.js~DataView", "external" ], [ "src/.external-ecmascript.js~date", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date", "src/.external-ecmascript.js~Date", "external" ], [ "src/.external-ecmascript.js~error", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error", "src/.external-ecmascript.js~Error", "external" ], [ "src/.external-ecmascript.js~evalerror", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError", "src/.external-ecmascript.js~EvalError", "external" ], [ "src/.external-ecmascript.js~float32array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array", "src/.external-ecmascript.js~Float32Array", "external" ], [ "src/.external-ecmascript.js~float64array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array", "src/.external-ecmascript.js~Float64Array", "external" ], [ "src/.external-ecmascript.js~function", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function", "src/.external-ecmascript.js~Function", "external" ], [ "src/.external-ecmascript.js~generator", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator", "src/.external-ecmascript.js~Generator", "external" ], [ "src/.external-ecmascript.js~generatorfunction", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction", "src/.external-ecmascript.js~GeneratorFunction", "external" ], [ "src/.external-ecmascript.js~infinity", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity", "src/.external-ecmascript.js~Infinity", "external" ], [ "src/.external-ecmascript.js~int16array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array", "src/.external-ecmascript.js~Int16Array", "external" ], [ "src/.external-ecmascript.js~int32array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array", "src/.external-ecmascript.js~Int32Array", "external" ], [ "src/.external-ecmascript.js~int8array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array", "src/.external-ecmascript.js~Int8Array", "external" ], [ "src/.external-ecmascript.js~internalerror", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/InternalError", "src/.external-ecmascript.js~InternalError", "external" ], [ "src/.external-ecmascript.js~json", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON", "src/.external-ecmascript.js~JSON", "external" ], [ "src/.external-ecmascript.js~map", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map", "src/.external-ecmascript.js~Map", "external" ], [ "src/.external-ecmascript.js~nan", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN", "src/.external-ecmascript.js~NaN", "external" ], [ "src/.external-ecmascript.js~number", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number", "src/.external-ecmascript.js~Number", "external" ], [ "src/.external-ecmascript.js~object", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object", "src/.external-ecmascript.js~Object", "external" ], [ "src/.external-ecmascript.js~promise", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise", "src/.external-ecmascript.js~Promise", "external" ], [ "src/.external-ecmascript.js~proxy", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy", "src/.external-ecmascript.js~Proxy", "external" ], [ "src/.external-ecmascript.js~rangeerror", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError", "src/.external-ecmascript.js~RangeError", "external" ], [ "src/.external-ecmascript.js~referenceerror", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError", "src/.external-ecmascript.js~ReferenceError", "external" ], [ "src/.external-ecmascript.js~reflect", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect", "src/.external-ecmascript.js~Reflect", "external" ], [ "src/.external-ecmascript.js~regexp", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp", "src/.external-ecmascript.js~RegExp", "external" ], [ "src/.external-ecmascript.js~set", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set", "src/.external-ecmascript.js~Set", "external" ], [ "src/.external-ecmascript.js~string", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String", "src/.external-ecmascript.js~String", "external" ], [ "src/.external-ecmascript.js~symbol", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol", "src/.external-ecmascript.js~Symbol", "external" ], [ "src/.external-ecmascript.js~syntaxerror", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError", "src/.external-ecmascript.js~SyntaxError", "external" ], [ "src/.external-ecmascript.js~typeerror", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError", "src/.external-ecmascript.js~TypeError", "external" ], [ "src/.external-ecmascript.js~urierror", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError", "src/.external-ecmascript.js~URIError", "external" ], [ "src/.external-ecmascript.js~uint16array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array", "src/.external-ecmascript.js~Uint16Array", "external" ], [ "src/.external-ecmascript.js~uint32array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array", "src/.external-ecmascript.js~Uint32Array", "external" ], [ "src/.external-ecmascript.js~uint8array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array", "src/.external-ecmascript.js~Uint8Array", "external" ], [ "src/.external-ecmascript.js~uint8clampedarray", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray", "src/.external-ecmascript.js~Uint8ClampedArray", "external" ], [ "src/.external-ecmascript.js~weakmap", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap", "src/.external-ecmascript.js~WeakMap", "external" ], [ "src/.external-ecmascript.js~weakset", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet", "src/.external-ecmascript.js~WeakSet", "external" ], [ "src/.external-ecmascript.js~boolean", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean", "src/.external-ecmascript.js~boolean", "external" ], [ "src/.external-ecmascript.js~function", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function", "src/.external-ecmascript.js~function", "external" ], [ "src/.external-ecmascript.js~null", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null", "src/.external-ecmascript.js~null", "external" ], [ "src/.external-ecmascript.js~number", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number", "src/.external-ecmascript.js~number", "external" ], [ "src/.external-ecmascript.js~object", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object", "src/.external-ecmascript.js~object", "external" ], [ "src/.external-ecmascript.js~string", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String", "src/.external-ecmascript.js~string", "external" ], [ "src/.external-ecmascript.js~undefined", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined", "src/.external-ecmascript.js~undefined", "external" ], [ "src/basicperlin.js", "file/src/basicPerlin.js.html", "src/basicPerlin.js", "file" ], [ "src/cellular2d.js", "file/src/cellular2D.js.html", "src/cellular2D.js", "file" ], [ "src/classicperlin2d.js", "file/src/classicPerlin2D.js.html", "src/classicPerlin2D.js", "file" ], [ "src/generic11d.js", "file/src/generic11D.js.html", "src/generic11D.js", "file" ], [ "src/generic12d.js", "file/src/generic12D.js.html", "src/generic12D.js", "file" ], [ "src/generic2.js", "file/src/generic2.js.html", "src/generic2.js", "file" ], [ "src/generic3.js", "file/src/generic3.js.html", "src/generic3.js", "file" ], [ "src/index.js", "file/src/index.js.html", "src/index.js", "file" ], [ "src/simplex2d.js", "file/src/simplex2D.js.html", "src/simplex2D.js", "file" ], [ "src/utils.js", "file/src/utils.js.html", "src/utils.js", "file" ], [ "test/test.js", "test-file/test/test.js.html", "test/test.js", "testFile" ], [ "unpleasant unpleasant,unpleasant", "test-file/test/test.js.html#lineNumber12", "unpleasant", "test" ], [ "unpleasant#basicperlinnoise unpleasant#basicperlinnoise,unpleasant#basicperlinnoise", "test-file/test/test.js.html#lineNumber58", "unpleasant .basicPerlinNoise", "test" ], [ "", "test-file/test/test.js.html#lineNumber59", "unpleasant .basicPerlinNoise should return a number", "test" ], [ "unpleasant#cellular2dnoise unpleasant#cellular2dnoise,unpleasant#cellular2dnoise", "test-file/test/test.js.html#lineNumber88", "unpleasant .cellular2DNoise", "test" ], [ "", "test-file/test/test.js.html#lineNumber89", "unpleasant .cellular2DNoise should return an array of 2 numbers", "test" ], [ "unpleasant#classicperlin2dnoise unpleasant#classicperlin2dnoise,unpleasant#classicperlin2dnoise", "test-file/test/test.js.html#lineNumber68", "unpleasant .classicPerlin2DNoise", "test" ], [ "", "test-file/test/test.js.html#lineNumber69", "unpleasant .classicPerlin2DNoise should return a number", "test" ], [ "unpleasant#generic1noise1d unpleasant#generic1noise1d,unpleasant#generic1noise1d", "test-file/test/test.js.html#lineNumber16", "unpleasant .generic1Noise1D", "test" ], [ "", "test-file/test/test.js.html#lineNumber17", "unpleasant .generic1Noise1D should return a number", "test" ], [ "unpleasant#generic1noise2d unpleasant#generic1noise2d,unpleasant#generic1noise2d", "test-file/test/test.js.html#lineNumber26", "unpleasant .generic1Noise2D", "test" ], [ "", "test-file/test/test.js.html#lineNumber27", "unpleasant .generic1Noise2D should return a number", "test" ], [ "unpleasant#generic2noise unpleasant#generic2noise,unpleasant#generic2noise", "test-file/test/test.js.html#lineNumber36", "unpleasant .generic2Noise", "test" ], [ "", "test-file/test/test.js.html#lineNumber37", "unpleasant .generic2Noise should return a number", "test" ], [ "unpleasant#generic3noise unpleasant#generic3noise,unpleasant#generic3noise", "test-file/test/test.js.html#lineNumber46", "unpleasant .generic3Noise", "test" ], [ "", "test-file/test/test.js.html#lineNumber47", "unpleasant .generic3Noise should return a number", "test" ], [ "unpleasant#simplex2dnoise unpleasant#simplex2dnoise,unpleasant#simplex2dnoise", "test-file/test/test.js.html#lineNumber78", "unpleasant .simplex2DNoise", "test" ], [ "", "test-file/test/test.js.html#lineNumber79", "unpleasant .simplex2DNoise should return a number", "test" ] ]
var Utilities = { color: { red:0xFF0000, green:0x00FF00, blue:0x0000FF } }
// ================================================================================ // // Copyright: M.Nelson - technische Informatik // Die Software darf unter den Bedingungen // der APGL ( Affero Gnu Public Licence ) genutzt werden // // weblet: allg/filesystem/folder/edit // ================================================================================ { var i; var str = ""; var w; var ivalues = { styleName : 'style.css', diraddaction : '/file/mkdir.xml', dirdelaction : '/file/rmdir.xml', fileaddaction : '/file/mkfile.html', filedelaction : '/file/rmfile.xml', mvaction : '/file/mv.xml', view : 'viewdir', popupadd : 'fileadd', popuprename : 'filerename', noleaf : false }; var svalues = { }; weblet.initDefaults(ivalues, svalues); weblet.initpar.view = weblet.initpar.view + (( weblet.initpar.noleaf ) ? "_noleaf" : ""); MneAjax.prototype.load.call(weblet, weblet.path + "/" + weblet.initpar.view + ".html"); weblet.frame = weblet.origframe; weblet.frame.innerHTML = weblet.req.responseText; var attr = { hinput : weblet.initpar.hinput == true, }; weblet.findIO(attr); weblet.btnrequest['diradd'] = weblet.initpar.diraddaction; weblet.btnrequest['dirdel'] = weblet.initpar.dirdelaction; weblet.btnrequest['fileadd'] = weblet.initpar.fileaddaction; weblet.btnrequest['filedel'] = weblet.initpar.filedelaction; weblet.btnrequest['rename'] = weblet.initpar.mvaction; weblet.titleString.add = weblet.txtGetText("#mne_lang#hinzufügen"); weblet.titleString.mod = weblet.txtGetText("#mne_lang#bearbeiten"); weblet.titleString.del = weblet.txtGetText("#mne_lang#Ordner/Datei <$1> wirklich löschen ?"); weblet.titleString.delid = 'name'; weblet.showValue = function(weblet) { this.obj.pweblet = weblet; if ( typeof weblet != 'undefined' && weblet != null ) this.act_values = weblet.act_values; else this.act_values = {}; this.closepopups(); this.okaction = ''; this.reload = 0; if ( this.act_values.action == 'submenu' ) { this.obj.delaction = "dirdel"; if ( this.initpar.view.substr(0,7) != 'viewdir') { this.reload = 1; this.initpar.view = "viewdir"; } } else if ( this.act_values.action == 'root' ) { if ( this.initpar.view.substr(0,8) != 'viewroot' ) { this.initpar.view = "viewroot"; this.reload = 1; } } else if ( this.act_values.action != 'submenu' ) { this.obj.delaction = "filedel"; if ( this.initpar.view.substr(0,8) != 'viewfile' ) { this.initpar.view = "viewfile"; this.reload = 1; } } if ( this.reload ) { this.obj.inputs = {}; this.load(this.id); this.popup.root.style.width = "10px"; this.popup.root.style.height = "10px"; var w = this; window.setTimeout(function() { w.popup.resize(true,false); }, 100 ); return this.showValue(weblet); } this.clearModify(); }; weblet.addfile = function() { this.openpopup(this.initpar.popupadd, this.popup.root, { adddir : false}); this.popup.hidden(); return false; }; weblet.adddir = function() { this.openpopup(this.initpar.popuprename, this.popup.root, { adddir : true }); this.popup.hidden(); this.obj.refreshmenuid = this.act_values.dir; this.parent.subweblets[this.initpar.popuprename].okaction = 'adddir'; t this.parent.subweblets[this.initpar.popuprename].showInput("filename", "neu", null, false ); this.parent.subweblets[this.initpar.popuprename].obj.inputs.filename.select(); this.parent.subweblets[this.initpar.popuprename].obj.inputs.filename.focus(); return false; }; weblet.rename = function() { if ( this.act_values.action == 'root') return false; this.openpopup(this.initpar.popuprename, this.popup.root); this.popup.hidden(); this.obj.refreshmenuid = ( this.act_values.leaf == "" ) ? this.act_values.parentdir : this.act_values.dir; this.parent.subweblets[this.initpar.popuprename].okaction = 'rename'; this.parent.subweblets[this.initpar.popuprename].showInput("filename", this.act_values.name, null, false ); this.parent.subweblets[this.initpar.popuprename].obj.inputs.filename.select(); this.parent.subweblets[this.initpar.popuprename].obj.inputs.filename.focus(); return false; }; weblet.del = function(setdepend) { var p = {}; if ( this.confirm(this.txtSprintf(this.titleString.del, this.txtFormat.call(this, this.act_values[this.titleString.delid], this.typs[this.ids[this.titleString.delid]]) ) ) != true ) return false; p = this.addParam(p, 'rootInput.old', this.initpar.root); p = this.addParam(p, 'dirInput.old', this.act_values.dir); if ( this.act_values.filename != null ) p = this.addParam(p, 'filenameInput.old', this.act_values.filename); if ( MneAjaxWeblet.prototype.write.call(this, this.btnrequest[this.obj.delaction], p ) == 'ok' ) { this.popup.hidden(); if ( typeof this.act_values.rootaction != 'undefined' ) this.act_values.menu.refresh(this.act_values.rootaction.menuid, true); else this.act_values.menu.refresh('', true); if ( setdepend != false ) this.setDepends("del"); return false; } return true; }; weblet.onbtnclick = function(id, button) { if ( id == 'dataready') { this.act_values.menu.refresh(this.act_values.menuid, true); } else if ( id == 'ok' && button.weblet.oid == this.initpar.popuprename ) { this.act_values.menu.refresh(this.obj.refreshmenuid, true); this.act_values.name = button.weblet.act_values.name; if ( this.act_values.leaf == "") { this.act_values.menuid = this.act_values.dir = this.act_values.parentdir + '/' + this.act_values.name; this.act_values.path = this.act_values.parentpath + "->" + this.act_values.name; } else { this.act_values.filename = this.act_values.name; this.act_values.menuid = this.act_values.dir + '/' + this.act_values.name; this.act_values.path = this.act_values.parentpath + "->" + this.act_values.name; } this.setDepends('rename'); } }; }
import * as React from 'react'; import { ListItem } from 'material-ui/List'; class ProvinceListItem extends React.Component { drillProvince() { this.props.drillProvince({ provinceListItem: this }); } render() { return ( <React.Fragment> <ListItem primaryText={this.props.primaryText} onClick={this.drillProvince.bind(this)} innerDivStyle={{padding:'3px 10px 3px 20px'}}/> </React.Fragment> ); } } export default ProvinceListItem;
import React, { Component } from 'react' import { Button, Card, HoverCard, Checkbox, FlipCard, Image, Nav, Carousel } from 'project-clio' import { H1, H2, H3, B, R, S } from 'project-clio' import { COLOR, SIZE } from 'project-clio' import './App.module.css'; import printer from './printer.png' import plants from './plants.jpg' export default class App extends Component { render () { return ( <div> <Nav> <Nav.Item href="#"> Home </Nav.Item> <Nav.Item href="#"> About </Nav.Item> <Nav.Item href="#"> Product </Nav.Item> <Nav.Item href="#"> Contact </Nav.Item> </Nav> <p> </p> <H1> Heading One </H1> <H2> Heading Two </H2> <H3> Heading Three </H3> <B> Bold </B> <S> Small </S> <R> Regular </R> {/* <Checkbox label="This is a Checkbox."/> */} <Button content="Button" color={COLOR.BLUE} size={SIZE.MD} type="border" /> <p> </p> <Button content="Large" color={COLOR.LIGHT} size={SIZE.LG} type="expand" /> <p> </p> <Button content="Button" color={COLOR.DARK} size={SIZE.MD} type="border" /> <p> </p> <Card> <H3> Card Title </H3> <R> Lorem ipsum dolor sit amet consectetur adipisicing elit. Sed natus, minus obcaecati, velit magni praesentium voluptatem facilis dolorem facere veniam ipsa in. Assumenda, eum? Quam blanditiis mollitia eveniet sapiente alias! </R> <Button content="Button" color={COLOR.DARK} size={SIZE.MD} /> </Card> <p> </p> <div className="flex-container"> <Card> <H3> Card Title </H3> <Image src={printer} alt="" width="150px"/> <Button content="Button" size={SIZE.MD} /> </Card> <Card> <H3> Card Title </H3> <Image src={printer} alt="" width="150px"/> <Button content="Button" size={SIZE.MD} /> </Card> <Card> <H3> Card Title </H3> <Image src={printer} alt="" width="150px"/> <Button content="Button" size={SIZE.MD} /> </Card> </div> <p> </p> <HoverCard> <HoverCard.Front> <Image src={printer} alt="" width="150px"/> </HoverCard.Front> <HoverCard.Back> <R> lorem lorem hover card. lorem lorem hover card. lorem lorem hover card. </R> </HoverCard.Back> </HoverCard> {/* <Carousel> <Carousel.Slide> <H3> Slide Title 1 </H3> <Image src={printer} alt="" width="150px"/> <Button content="Button" size={SIZE.MD} /> </Carousel.Slide> <Carousel.Slide> <H3> Slide Title 2 </H3> <Image src={printer} alt="" width="150px"/> <Button content="Button" size={SIZE.MD} /> </Carousel.Slide> </Carousel> */} {/* <Image src={plants} width="80%"> <H1> HERE IS A TITLE </H1> <Button content="Button" size={SIZE.MD}/> </Image> */} {/* Photo by eberhard grossgasteiger on Unsplash */} {/* <FlipCard> <FlipCard.Front> <H3> Hover Here </H3> <img src={printer} alt="" style={{width: 150+"px"}}/> </FlipCard.Front> <FlipCard.Back> <H3> Card Title Two </H3> <R> Lovident non voluptates commodi similique, beatae ipsum delectus exercitationem! Lorem ipsum dolor sit amet consectetur adipisicing elit. Sed natus, minus obcaecati, velit magni praesentium voluptatem facilis dolorem facere veniam ipsa in. Assumenda, eum? Quam blanditiis mollitia eveniet sapiente alias! </R> <Button content="Button" size={SIZE.MD} type="border" /> </FlipCard.Back> </FlipCard> */} {/* <div>Icons made by <a href="https://www.freepik.com/" title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a></div> */} <p> </p> </div> ) } }
var mongoose = require('mongoose'); var bcrypt = require('bcrypt'); var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; // var UserSchema = new mongoose.Schema({ // username: {type: String, unique: true}, // password: String, // email: String, // firstname: String, // lastname: String, // gender: String, // roles: [String] // }); var UserSchema = new mongoose.Schema({ username: { type: String, require: true, unique: true }, firstname: { type: String, required: true }, lastname: { type: String, required: true }, gender: { type: String, required: true, enum: ['Male','Female'] }, email: { type: String, required: true }, password: { type: String, required: true }, location: { type: String, default: '' }, joined: { type: Date, default: Date.now }, birth: { type: Date, default: '' }, picture: { type: String, default: 'http://www.lcfc.com/images/common/bg_player_profile_default_big.png' }, roles: [String] }); UserSchema.methods.generateHash = function(password){ return bcrypt.hashSync(password,bcrypt.genSaltSync(8), null); }; UserSchema.methods.isValidPassword = function(password){ return bcrypt.compareSync(password, this.password); }; var UserModel = mongoose.model('UserModel', UserSchema); passport.use('local-login', new LocalStrategy({ usernameField: 'username', passwordField: 'password', passReqToCallback: true }, function(req, username, password, done){ process.nextTick(function(){ UserModel.findOne({ username: username}, function(err, user){ if(err) return done(err); if(!user) return done(null, false, req.flash('loginMessage', 'No User found')); if(!user.isValidPassword(password)){ return done(null, false, req.flash('loginMessage', 'invalid password')); } return done(null, user); }); }); } )); passport.use('register', new LocalStrategy( { usernamefield: 'username', passwordfield: 'password', passReqToCallback: true }, function(req,username, password,done){ process.nextTick(function(){ UserModel.findOne({username: req.body.username}, function(err,user){ if(err){ return done(err); } if(user){ return done(null, false, req.flash('signupMessage', 'That email is already taken')); } else { var user = new UserModel(); user.roles = ['admin']; user.username = req.body.username; user.password = user.generateHash(req.body.password); user.email = req.body.email; user.firstname = req.body.firstname; user.lastname = req.body.lastname; user.gender = req.body.gender; user.location = req.body.location; user.birth = req.body.birth; user.picture = req.body.picture; user.save(function(err){ if(err) throw err; return done(null,user); }); } }); }); } )); passport.serializeUser(function(user,done){ done(null,user); }); passport.deserializeUser(function(user,done){ done(null,user); }); module.exports = UserModel;
function initializeUserContext(userContext, $rootScope, AccountService, HabitsService, GoalService, AudioService, PayService, NotificationService, Environment) { AccountService.setAccountUser(userContext.accountUser); AccountService.setUserPreferences(userContext.userPreferences); AccountService.setActivityContext(userContext.activityContext); HabitsService.setHabitContext(userContext.habitContext); HabitsService.setPotentialAccountHabits(userContext.potentialHabits); GoalService.setGoalContext(userContext.goalContext); AudioService.setAudioContext(userContext.thoughtContext); $rootScope.$broadcast('event:userContextInitialized'); } if (!String.prototype.endsWith) { String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; } if (!String.prototype.startsWith) { String.prototype.startsWith = function(prefix) { return this.indexOf(prefix) == 0; }; } if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); }; } // IE8... if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) { 'use strict'; if (this == null) { throw new TypeError(); } var n, k, t = Object(this), len = t.length >>> 0; if (len === 0) { return -1; } n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n != n) { // shortcut for verifying if it's NaN n = 0; } else if (n != 0 && n != Infinity && n != -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } for (k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } function isAlphaNumeric(str) { var regex = /^[a-z0-9]+$/i; return regex.test(str); } function isNumeric(str) { var regex = /^[0-9]+$/i; return regex.test(str); } function getQueryStringParam(name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } function capitaliseFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } function generateGUID() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } var months = { 0: 'Jan', 1: 'Feb', 2: 'Mar', 3: 'Apr', 4: 'May', 5: 'Jun', 6: 'Jul', 7: 'Aug', 8: 'Sep', 9: 'Oct', 10: 'Nov', 11: 'Dec' } function getMonthAbbrev(index) { return months[index]; } function dayDiff(first, second) { return (second-first)/(1000*60*60*24); } Date.prototype.addDays = function(days) { var dat = new Date(this.valueOf()); dat.setDate(dat.getDate() + days); return dat; } function openModal(modal) { if (window.StatusBar) StatusBar.styleDefault(); modal.show(); }; function closeModal(modal) { if (window.StatusBar) StatusBar.styleLightContent(); modal.hide(); }
var should = require("should"); var utils = require("../../app/utils/geometryUtils"); describe("GeometryUtils", function() { describe("#degToRad", function() { it("should return pi/2 for 90 degrees", function() { utils.degToRad(90).should.equal(Math.PI / 2); }); it("should return 0 for 0 degrees", function() { utils.degToRad(0).should.equal(0); }); it("should return pi for 180 degrees", function() { utils.degToRad(180).should.equal(Math.PI); }); it("should return pi/6 for 30 degrees", function() { utils.degToRad(30).should.equal(Math.PI / 6); }); it("should return pi/3 for 60 degrees", function() { utils.degToRad(60).should.equal(Math.PI / 3); }); }); describe("#radToDeg", function() { it("should return 180 for pi", function() { utils.radToDeg(Math.PI).should.equal(180); }); it("should return 90 for pi/2", function() { utils.radToDeg(Math.PI / 2).should.equal(90); }); it("should return 360 for pi*2", function() { utils.radToDeg(Math.PI * 2).should.equal(360); }); }); describe("#computeAngleFrompoints", function() { it("should return 45 degrees for [-1,0], [0,1]", function() { utils.computeAngleFromPoints([-1, 0], [0, 1]).should.equal(45); }); it("should return -225 degrees for [0,1], [-1,0]", function() { utils.computeAngleFromPoints([0, 1], [-1, 0]).should.equal(-135); }); it("should return 90 degrees for [0,0], [0,1]", function() { utils.computeAngleFromPoints([0, 0], [0, 1]).should.equal(90); }); it("should return -90 degrees for [0,1], [0,0]", function() { utils.computeAngleFromPoints([0, 1], [0, 0]).should.equal(-90); }); }); describe("#computeAngle", function() { it("should return 0 degrees for (1,0)", function() { utils.computeAngle(1, 0).should.equal(0); }); it("should return 180 degrees for (-1,0)", function() { utils.computeAngle(-1, 0).should.equal(180); }); it("should return 90 degrees for (0,1)", function() { utils.computeAngle(0, 1).should.equal(90); }); it("should return -90 degrees for (0,-1)", function() { utils.computeAngle(0, -1).should.equal(-90); }); it("should return 45 degrees for (1,1)", function() { utils.computeAngle(1, 1).should.equal(45); }); }); describe("#computeDistance", function() { it("should return 1 for (1,0)", function() { utils.computeDistance(1, 0).should.equal(1); }); it("should return 0 for (0,0)", function() { utils.computeDistance(0, 0).should.equal(0); }); it("should return 1 for (-1,0)", function() { utils.computeDistance(-1, 0).should.equal(1); }); it("should return 1 for (0,1)", function() { utils.computeDistance(0, 1).should.equal(1); }); it("should return 1 for (0,-1)", function() { utils.computeDistance(0, -1).should.equal(1); }); it("should return 3 for (0,3)", function() { utils.computeDistance(0, 3).should.equal(3); }); it("should return 5 for (3,4)", function() { utils.computeDistance(3, 4).should.equal(5); }); it("should return 5 for (-3,-4", function() { utils.computeDistance(-3, -4).should.equal(5); }); it("should return 5 for (3,-4)", function() { utils.computeDistance(3, -4).should.equal(5); }); it("should return 5 for (-3,4)", function() { utils.computeDistance(-3, 4).should.equal(5); }); }); describe("#computeDistanceBetweenPoints", function() { it("should return 1 for [0,0], [0,1]", function() { utils.computeDistanceBetweenPoints([0, 0], [0, 1]).should.equal(1); }); it("should return 1 for [0,1], [0,0]", function() { utils.computeDistanceBetweenPoints([0, 1], [0, 0]).should.equal(1); }); it("should return 2 for [1,0], [-1,0]", function() { utils.computeDistanceBetweenPoints([1, 0], [-1, 0]).should.equal(2); }); it("should return 2 for [-1,0], [1,0]", function() { utils.computeDistanceBetweenPoints([-1, 0], [1, 0]).should.equal(2); }); it("should return 5 for [0,0], [3,4]", function() { utils.computeDistanceBetweenPoints([0, 0], [3, 4]).should.equal(5); }); it("should return 5 for [3,4], [0,0]", function() { utils.computeDistanceBetweenPoints([3, 4], [0, 0]).should.equal(5); }); }); describe("#computeEndPoint", function() { it("should return [3,4] for [0,0], 53.13 degrees, 5 length", function() { var end = utils.computeEndPoint([0, 0], 53.13, 5); end[0].should.be.approximately(3, 0.01); end[1].should.be.approximately(4, 0.01); }); it("should return [4,3] for [0,0], 36.86 degrees, 5 length", function() { var end = utils.computeEndPoint([0, 0], 36.86, 5); end[0].should.be.approximately(4, 0.01); end[1].should.be.approximately(3, 0.01); }); it("should return [4,-3] for [0,0], -36.86 degrees, 5 length", function() { var end = utils.computeEndPoint([0, 0], -36.86, 5); end[0].should.be.approximately(4, 0.01); end[1].should.be.approximately(-3, 0.01); }); it("should return [-3,-4] for [0,0], 126.86 degrees, 5 length", function() { var end = utils.computeEndPoint([0, 0], -126.86, 5); end[0].should.be.approximately(-3, 0.01); end[1].should.be.approximately(-4, 0.01); }); it("should return [1,1] for [0,0], 45 degrees, 1.41421 length", function() { var end = utils.computeEndPoint([0, 0], 45, 1.41421); end[0].should.be.approximately(1, 0.01); end[1].should.be.approximately(1, 0.01); }); it("should return [2,2] for [1,1], 45 degrees, 1.41421 length", function() { var end = utils.computeEndPoint([1, 1], 45, 1.41421); end[0].should.be.approximately(2, 0.01); end[1].should.be.approximately(2, 0.01); }); }); });
import React from 'react'; import {StyleSheet, Text, TouchableOpacity, View} from 'react-native'; import {IcBack} from '../../../assets'; const Header = props => { const {title, subTtitle, container, back} = styles; return ( <View style={container}> {props.onBack && ( <TouchableOpacity activeOpacity={0.7} onPress={props.onBack}> <View style={back}> <IcBack /> </View> </TouchableOpacity> )} <View> <Text style={title}>{props.title}</Text> <Text style={subTtitle}>{props.subTitle}</Text> </View> </View> ); }; export default Header; const styles = StyleSheet.create({ container: { backgroundColor: 'white', paddingHorizontal: 24, paddingTop: 30, paddingBottom: 24, flexDirection: 'row', alignItems: 'center', }, title: { fontSize: 22, fontFamily: 'Poppins-Medium', color: '#020202', }, subTtitle: { fontSize: 14, fontFamily: 'Poppins-Light', color: '#8D92A3', }, back: { padding: 16, marginRight: 16, marginLeft: -10, }, });
import React, { Component } from 'react'; import ProverbView from './ProverbView.js'; import ProverbProvider from './ProverbProvider.js'; import logo from './colberthead.png'; import easter_logo from './fallonhead.png'; import './App.css'; class App extends Component { constructor(props) { super(props); this.state = { header_image: logo, header_text: "Live on tape from the Ed Sullivan Theater in New York City, it's Stephen Colbert !" }; this.proverb_provider = new ProverbProvider(); } /** * Exécuté lorsqu'un nouveau proverbe est généré. * Actuellement, 1 chance sur 10 que Stephen Colbert laisse la place à Jimmy Fallon, parce que. */ onNewProverb(e) { if (Math.random() < 0.9) { this.setState({ header_image: logo, header_text: "Live on tape from the Ed Sullivan Theater in New York City, it's Stephen Colbert !" }); } else { this.setState({ header_image: easter_logo, header_text: "FROM STUDIO 6B IN ROCKEFELLER CENTER IN THE HEART OF NEW YORK CITY, IT'S THE TONIGHT SHOW STARRING JIMMY FALLON" }); } } render() { // component ProverbView has to call my (App) method 'onNewProverb', and when it does, i want 'this' to be me (App) // So, I have to use .bind(this) on it. return ( <div className="App"> <header className="App-header"> <img src={this.state.header_image} className="App-logo" alt="logo" title={this.state.header_text} /> <h1 className="App-title">Alternative Proverb Generator</h1> <h2 className="App-desc">A GIF-intensive application made with love, greasy pizza and React</h2> </header> <ProverbView proverb_provider={this.proverb_provider} onNewProverb={this.onNewProverb.bind(this)} /> </div> ); } } export default App;
var rootUrl = 'http://localhost:8080/calc' var populateListURL = 'http://localhost:8080/calc/operations' function calculate() { $("#response").html(""); $(".alert").alert('close') var num1 = $("#numOneTf").val(); var num2 = $("#numTwoTf").val(); var operation = $("#operationType").find("option:selected").text(); if ($("#numOneTf").val() == "" || $("#numTwoTf").val() == "") { $("#response").animate({}, 300); $('<div class="alert alert-danger" style="width:800px;" ><b>error : </b>' + "please input a roman numeral." + '</div>').hide().appendTo('#response').fadeIn(1000); } else { $.ajax({ type: 'GET', url: rootUrl + "?num1=" + num1 + "&num2=" + num2 + "&operationType=" + encodeURIComponent(operation), contentType: "application/json", dataType: "text", success: function(response) { $(".alert").alert('close') $("#response").animate({}, 300); $('<div class="alert alert-success" style="width:800px;" ><b>Result : </b>' + response + '</div>').hide().appendTo('#response').fadeIn(1000); }, error: function(response) { $("#response").animate({}, 300); var jsonValue = jQuery.parseJSON(response.responseText); $('<div class="alert alert-danger" style="width:800px;" >' + jsonValue.message + '</div>').hide().appendTo('#response').fadeIn(1000); } }); } } $(document).on('click', '#calcBtn', function() { calculate(); return false; }); $(document).ready(function() {});
const CustomError = require('../CustomError'); /** @typedef {'BAD_REQUEST'} BadRequestCode Error code */ /** @typedef {import('../CustomError').ErrorMessage} BadRequestMessage Error message */ /** * @typedef {import('../CustomError')} BadRequest * @param {BadRequestCode} code Bad request code * @param {BadRequestMessage} message Bad request error message * @param {import('../CustomError').ErrorDetails} details Error details */ class BadRequest extends CustomError { /** * Creates a Bad Request Error * @param {import('../CustomError').ErrorMessage} message * @param {import('../CustomError').ErrorDetails} details * @returns {BadRequest} */ constructor(message, details = null) { super('BAD_REQUEST', message, details); } } module.exports = BadRequest;
import React, {Component} from 'react'; import {StyleSheet} from 'react-native'; import { Router, Scene, Stack } from 'react-native-router-flux'; import Home from './src/screens/Home'; import Color from './src/screens/Color'; import Chart from './src/screens/Chart'; // const instructions = Platform.select({ // ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu', // android: // 'Double tap R on your keyboard to reload,\n' + // 'Shake or press menu button for dev menu', // }); export default class App extends Component { render() { return ( <Router navigationBarStyle={{ backgroundColor: '#333' }} titleStyle={{color: '#fff'}} > <Stack key="root"> <Scene key="home" component={Home} hideNavBar={true} initial /> <Scene key="color" component={Color} title="Iluminação" headerTintColor="#fff"/> <Scene key="chart" component={Chart} title="Resumo" headerTintColor="#fff"/> </Stack> </Router> ); } }
const Koa = require('koa') const app = module.exports = new Koa() app.use(async context => { const { request, response, cookies } = context const field = request.path.replace(/^\//, '') context.assert(field, 400) if (request.header['origin']) { response.set('Access-Control-Allow-Origin', request.header['origin']) response.set('Access-Control-Allow-Credentials', 'true') } if (request.header['access-control-request-method']) { response.set('Access-Control-Allow-Methods', request.header['access-control-request-method']) } switch (request.method) { case 'GET': response.body = cookies.get(field) break case 'POST': cookies.set(field, request.body) response.status = 205 break case 'DELETE': cookies.set(field) response.status = 205 break case 'OPTIONS': response.status = 204 response.set('Allow', 'OPTIONS') break default: context.throw(405) } })
/* import posts from 'components/posts.json' */ /* export default function getPost(id, posts) { for (var p of posts) { if (p.id === id) return p; } return null; } */ import firebase from "firebase"; import "firebase/firestore"; export default async function getPost(post) { let return_post = null; const db = firebase.firestore(); await db .collection("posts") .doc(post) .get() .then((doc) => { if (doc.exists) { let post_ = doc.data(); post_.id = doc.id; post_.time = post_.time.toDate(); return_post = post_; } else { console.log("no existe el usuario"); return_post = null; } }) .catch((e) => { console.log(e); return_post = null; }); return return_post; }
$(document).ready(function(e){ $('.editTareaEquipoClasificacion').click(function(e){ e.preventDefault(); $("#popup").css("display","table"); $("#popup .content-popup").css("width","700px"); var height = $(window).height() - 60; $("#popup .content-popup .html").css("height",height); $("#popup .content-popup .html").html("<div class='loader2'></div>"); var href = $(this).attr('href'); $.post(href,function(data){ $("#popup .content-popup .html").html(data); }); }); $(".popup_equipos_tares_default").live('click',function(e){ e.preventDefault(); var id = $(this).attr('href').split('#'); var idgrupo = id[1]; var html = "<form action='/tareas/updategroup/' method='post' accept-charset='utf-8' enctype='multipart/form-data'>"; var checked = ''; $('#popup').css('display','table'); $('#popup .html').html("<div class='loader2'></div>"); $('#popup .content-popup').width(250); $.post('/tareas/getequiposgrupos/id/' + idgrupo,function(info){ for(x in info.equipos){ if(typeof info.equiposGrupos[info.equipos[x].Equipo_de_Vlo] == 'undefined'){ html = html + "<p><input type='checkbox' class='checkbox' name='equipos[]' value='" + info.equipos[x].Equipo_de_Vlo + "'/> "+ info.equipos[x].Equipo_de_Vlo +"</p>"; }else if(info.equiposGrupos[info.equipos[x].Equipo_de_Vlo] == idgrupo){ html = html + "<p><input type='checkbox' checked='checked' class='checkbox' name='equipos[]' value='" + info.equipos[x].Equipo_de_Vlo + "'/> "+ info.equipos[x].Equipo_de_Vlo +"</p>"; } } html = html + "<p><input type='hidden' name='idgrupo' id='idgrupo_equipos_tares_default' value='" + idgrupo + "'/></p>"; html = html + "<p><input type='submit' class='submit' name='guardar' value='Guardar' class='save_equipos_tares_default'/></p>"; html = html + '</form>'; $('#popup .html').html(html); },'json'); }); });
import React from "react"; import {Form} from "semantic-ui-react"; function EditRestaurant({restaurant, onSubmit}) { const handleSubmit = ({target}) => { const formData = new FormData(target); const newRestaurant = {id: restaurant?.id ?? 0}; for (const pair of formData.entries()) { newRestaurant[pair[0]] = pair[1]; } console.log(newRestaurant); if (onSubmit) { onSubmit(newRestaurant); } } return ( <Form onSubmit={handleSubmit}> <Form.Field> <input name={"name"} placeholder={"Restoran Adı"} value={restaurant?.name}/> </Form.Field> <Form.Field> <input type={"number"} name={"tableCount"} placeholder={"Masa Sayısı"} value={restaurant?.tableCount}/> </Form.Field> <Form.Button type={'submit'}>Onayla</Form.Button> </Form> ) } export default EditRestaurant;
/* jshint indent: 2 */ module.exports = function(sequelize, DataTypes) { return sequelize.define('profiles_fields', { id: { type: DataTypes.INTEGER(10), allowNull: false, primaryKey: true, autoIncrement: true }, varname: { type: DataTypes.STRING(50), allowNull: false }, title: { type: DataTypes.STRING(255), allowNull: false }, field_type: { type: DataTypes.STRING(50), allowNull: false }, field_size: { type: DataTypes.INTEGER(3), allowNull: false, defaultValue: '0' }, field_size_min: { type: DataTypes.INTEGER(3), allowNull: false, defaultValue: '0' }, required: { type: DataTypes.INTEGER(1), allowNull: false, defaultValue: '0' }, match: { type: DataTypes.STRING(255), allowNull: false, defaultValue: '' }, range: { type: DataTypes.STRING(255), allowNull: false, defaultValue: '' }, error_message: { type: DataTypes.STRING(255), allowNull: false, defaultValue: '' }, other_validator: { type: DataTypes.STRING(5000), allowNull: false, defaultValue: '' }, default: { type: DataTypes.STRING(255), allowNull: false, defaultValue: '' }, widget: { type: DataTypes.STRING(255), allowNull: false, defaultValue: '' }, widgetparams: { type: DataTypes.STRING(5000), allowNull: false, defaultValue: '' }, position: { type: DataTypes.INTEGER(3), allowNull: false, defaultValue: '0' }, visible: { type: DataTypes.INTEGER(1), allowNull: false, defaultValue: '0' } }, { tableName: 'profiles_fields' }); };
import React, {useState} from 'react'; import { googleTranslate } from '../utils/googleTranslate'; const Translation = (props) => { const [transText, setTransText] = useState(''); let text = props.data.join(' '); let lang = props.lang; googleTranslate.translate(text, lang, function(err, translation) { setTransText(translation.translatedText); }); return ( <h1>{transText}</h1> ) } export default Translation;
#pragma strict var lejek:AudioClip; function Start () { } function Update () { } function OnCollisionEnter (collision:Collision){ audio.PlayOneShot(lejek); }
angular.module('mappler.controllers.blog.blogListController', []) .controller('BlogListCtrl', [ '$scope', '$rootScope', '$state', '$ionicLoading', '$ionicModal', '$ionicPopup', '$timeout', '$stateParams', '$ionicHistory', '$ionicScrollDelegate', '$filter', '$cordovaNetwork', '$cordovaKeyboard', '$mapplerLocalStorage', 'Constants', 'RestHttpService', 'AppService', 'BlogService', function($scope, $rootScope, $state, $ionicLoading, $ionicModal, $ionicPopup, $timeout, $stateParams, $ionicHistory, $ionicScrollDelegate, $filter, $cordovaNetwork, $cordovaKeyboard, $mapplerLocalStorage, Constants, RestHttpService, AppService, BlogService) { var offset = 0; var limit = 10; $scope.noMoreItemsAvailable = false; // 블로그 목록 $scope.appBlogInfoList = AppService.getAppBlogInfoList(); $scope.loginUserBlogList = AppService.getLoginUserBlogList(); $scope.addrId = $stateParams.addrId; $scope.appBlogInfo = $filter('filter')($scope.appBlogInfoList, function (d) {return d.addrId === $scope.addrId;})[0]; if(angular.isUndefined($scope.appBlogInfo) || angular.equals({}, $scope.appBlogInfo)){ $scope.appBlogInfo = $filter('filter')($scope.loginUserBlogList, function (d) {return d.addrId === $scope.addrId;})[0]; } //console.log("$scope.loginUserBlogList", $scope.loginUserBlogList); $scope.blogTitle = $scope.appBlogInfo.blogName; $scope.isSubHeaderView = false; // 네트워크 연결 유무 $scope.isNetworkOnline = true; // 서버로부터 데이터를 조회가 완료되었는지 유무 $scope.isDataSearchFinished = false; // 데이터에 대한 권한 $scope.blogAuthInfo = {}; // 데이터 입력에 대한 버튼 활성화 유무 $scope.isAddDataButtonEnable = false; // 데이터 정렬 종류 $scope.appBlogListSortType = AppService.getAppBlogListSortType(); $scope.dataTotalCount; $scope.fieldInfo = {}; $scope.blogList = []; // 검색에 대한 활성화 유무 $scope.isSearchBlogListBar = false; // 검색 키워드 $scope.searchData = {}; $scope.searchData["mydata"] = false; $scope.searchData["keywords"] = ""; $scope.nameSearchValue = ""; if($rootScope.isDeviceReady){ // Google Analytics if (typeof analytics !== 'undefined'){ analytics.startTrackerWithId(Constants.GOOGLE_ANALYTICS_KEY); analytics.trackView('list'); } } var blogSiteUrl = $scope.appBlogInfo.siteUrl; var blogId = $scope.appBlogInfo.blogId; var currentLocationLat, currentLocationLng; /*var date = new Date(); var nowDate = $filter('date')(date, "yyyy-MM-dd HH:mm:ss"); console.log("nowDate", nowDate); var utcDate = $filter('date')(date, "yyyy-MM-dd HH:mm:ss", "UTC"); console.log("utcDate", utcDate);*/ // 기존에 저장되어 있는 값이 있는지 확인(상세보기에서 뒤로가기 했을 경우) var blogListInfo = $mapplerLocalStorage.getItem('blogListInfo'); if(angular.isDefined(blogListInfo) && blogListInfo != null && blogListInfo != ""){ $scope.dataTotalCount = 0; $scope.blogList = []; $ionicLoading.show({ template: $filter('translate')('blog_loading_blog_data') }); blogListInfo = JSON.parse(blogListInfo); // 저장되어 있는 현재 위치 값 가져오기 if($scope.appBlogListSortType == "closest"){ currentLocationLat = blogListInfo['blogListCurrentLocationLat']; currentLocationLng = blogListInfo['blogListCurrentLocationLng']; } offset = blogListInfo['blogListOffset']; // 검색에 관련된 설정 $scope.isSearchBlogListBar = blogListInfo['isSearchBlogListBar']; $scope.searchData.keywords = blogListInfo['searchDataKeywords']; var blogListScrollPosition = blogListInfo['blogListScrollPosition']; $scope.blogList = blogListInfo['blogListData']; // 목록에서 위치 이동 $timeout(function() { $ionicScrollDelegate.$getByHandle('blogListScroll').scrollTo(blogListScrollPosition.left, blogListScrollPosition.top, true); $ionicLoading.hide(); }, 500); $scope.isDataSearchFinished = true; // 저장되어 있는 값 삭제 $mapplerLocalStorage.removeItem('blogListInfo'); }else{ if($scope.appBlogListSortType == "closest"){ getMyCurrentLocation(); }else{ getBlogDataList(); } } // 데이터 가져오기 function getBlogDataList(){ var dataError = function(error, status){ $ionicLoading.hide(); $scope.error = error; if(error.error == "timeout"){ $rootScope.$broadcast('event:app-networkRequired', {"isAppExit":false,"isHistoryBack":true}); }else{ $ionicPopup.alert({ title: $filter('translate')('site_error_alert_popup_title'), template: $filter('translate')('site_error_alert_msg') }); } } var dataSuccess = function(response, status){ $ionicLoading.hide(); $scope.dataTotalCount = response.dataTotalCount; $scope.fieldInfo = response.fieldInfo; var tempBlogList = $scope.setLoadingDataReSetting(response.dataList); $scope.blogList = tempBlogList; //console.log("$scope.blogList", $scope.blogList); // 디바이스에서 검색이후 화면 키보드 입력창 닫기 if($rootScope.isDeviceReady){ if($cordovaKeyboard.isVisible()){ $cordovaKeyboard.close(); } } $scope.isDataSearchFinished = true; } $ionicLoading.show({ template: $filter('translate')('blog_loading_blog_data') }); var isSiteSslUse = "N"; if(angular.isDefined($scope.appBlogInfo.isSiteSslUse)){ isSiteSslUse = $scope.appBlogInfo.isSiteSslUse; } BlogService.getBlogDataList(isSiteSslUse, blogSiteUrl, blogId, offset, limit, currentLocationLat, currentLocationLng, $scope.nameSearchValue, $scope.isBlogUserGroupAllowYN, $scope.userGroupId).then(dataSuccess, dataError); } // 현재 위치 정보 가져오기 function getMyCurrentLocation(){ offset = 0; currentLocationLat = ""; currentLocationLng = ""; if(navigator.geolocation){ $ionicLoading.show({ template: $filter('translate')('data_current_location_loading_msg') }); var options = { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }; navigator.geolocation.getCurrentPosition(function(position) { currentLocationLat = parseFloat(position.coords.latitude); currentLocationLng = parseFloat(position.coords.longitude); $ionicLoading.hide(); // 데이터 가져오기 getBlogDataList(); }, function(error) { $ionicLoading.hide(); var tempErrorMsg = error.message; if (error.code == 1) { tempErrorMsg = $filter('translate')('geo_location_permission_denied_error_msg'); } else if (error.code == 2) { tempErrorMsg = $filter('translate')('geo_location_position_unavailable_error_msg'); } else if (error.code == 3) { tempErrorMsg = $filter('translate')('gps_timeout_error_msg'); } $ionicPopup.alert({ title: $filter('translate')('site_error_alert_popup_title'), template: tempErrorMsg }).then(function(res) { getBlogDataList(); }); }, options); }else{ $ionicPopup.alert({ title: $filter('translate')('site_error_alert_popup_title'), template: "Sorry, browser does not support geolocation!" }); } } // 썸네일 이미지 가져오기 $scope.getThumbnail = function(item){ var retBindHtml = ""; if(item.images === null){ retBindHtml = "img/no-image.png"; }else{ if(angular.isUndefined(item.images[0]) == false){ //retBindHtml = item.images[0].imgThumUrl; retBindHtml = item.images[0].imgOrgUrl; }else{ retBindHtml = "img/no-image.png"; } } return retBindHtml; } // 새로운 데이터 가져오기 $scope.refreshLoadData = function(){ document.addEventListener("deviceready", function () { // 1.네트워크에 연결되어 있는지 확인 후 실제 데이터 업로드 if(!$cordovaNetwork.isOnline()){ $rootScope.$broadcast('event:app-networkRequired', {"isAppExit":false,"isHistoryBack":false}); $scope.isNetworkOnline = false; }else{ $scope.isNetworkOnline = true; } }, false); if($scope.isNetworkOnline){ offset = 0; $scope.noMoreItemsAvailable = false; var isSiteSslUse = "N"; if(angular.isDefined($scope.appBlogInfo.isSiteSslUse)){ isSiteSslUse = $scope.appBlogInfo.isSiteSslUse; } BlogService.getBlogDataList(isSiteSslUse, blogSiteUrl, blogId, offset, limit, currentLocationLat, currentLocationLng, $scope.nameSearchValue, $scope.isBlogUserGroupAllowYN, $scope.userGroupId).then(function(items) { if(items.dataList.length > 0){ var tempBlogList = $scope.setLoadingDataReSetting(items.dataList); $scope.blogList = tempBlogList; } // Stop the ion-refresher from spinning $scope.$broadcast('scroll.refreshComplete'); }); } } // 예전 데이터 가져오기 $scope.loadBlogListMore = function(){ document.addEventListener("deviceready", function () { // 1.네트워크에 연결되어 있는지 확인 후 실제 데이터 업로드 if(!$cordovaNetwork.isOnline()){ $rootScope.$broadcast('event:app-networkRequired', {"isAppExit":false,"isHistoryBack":false}); $scope.isNetworkOnline = false; }else{ $scope.isNetworkOnline = true; } }, false); if($scope.isNetworkOnline){ if($scope.isDataSearchFinished === true && $scope.noMoreItemsAvailable === false){ $scope.isDataSearchFinished = false; offset = offset + limit; var isSiteSslUse = "N"; if(angular.isDefined($scope.appBlogInfo.isSiteSslUse)){ isSiteSslUse = $scope.appBlogInfo.isSiteSslUse; } BlogService.getBlogDataList(isSiteSslUse, blogSiteUrl, blogId, offset, limit, currentLocationLat, currentLocationLng, $scope.nameSearchValue, $scope.isBlogUserGroupAllowYN, $scope.userGroupId).then(function(items) { if(items.dataList.length > 0){ var tempBlogList = $scope.setLoadingDataReSetting(items.dataList); $scope.blogList = $scope.blogList.concat(tempBlogList); }else{ $scope.noMoreItemsAvailable = true; } $scope.isDataSearchFinished = true; $scope.$broadcast('scroll.infiniteScrollComplete'); $ionicScrollDelegate.resize(); }); } } } $scope.setLoadingDataReSetting = function(dataList){ var tempBlogList = []; angular.forEach(dataList, function (item, index) { // 등록되어 있는 날짜가 세계 표준시 (UTC, GMT+0)로 되어 있어서 그 기준점으로 설정한다. item.edit_datetime = $filter('datetmUTC')(item.edit_datetime); if(angular.isUndefined(item.distance) || item.distance == ""){ item.distance = ""; }else{ var tempDistance = (item.distance * 1000).toFixed(0); var tempUnit = "m"; if(tempDistance > 1000){ tempDistance = (tempDistance / 1000).toFixed(1); tempUnit = "km"; } if($scope.appLocaleLanguage != "ko"){ if(tempUnit == "m"){ tempUnit = "ft"; tempDistance = (tempDistance * 3.2808).toFixed(0); }else{ tempUnit = "mi"; tempDistance = tempDistance * 0.62137; } } if(tempUnit == "m" || tempUnit == "ft"){ item.distance = $filter('number')(tempDistance, 0) + tempUnit; }else{ item.distance = $filter('number')(tempDistance, 1) + tempUnit; } } tempBlogList.push(item); }); return tempBlogList; } $scope.moreDataCanBeLoaded = function(){ if($scope.isDataSearchFinished && !$scope.noMoreItemsAvailable){ return true; }else{ return false; } } // 상세보기 $scope.goDataView = function(oid){ // 기존 데이터 및 목록에서의 위치 값을 저장 var tempBlogListInfo = {}; tempBlogListInfo['blogListScrollPosition'] = $ionicScrollDelegate.$getByHandle('blogListScroll').getScrollPosition(); tempBlogListInfo['blogListData'] = $scope.blogList; tempBlogListInfo['blogListOffset'] = offset; tempBlogListInfo['isSearchBlogListBar'] = $scope.isSearchBlogListBar; tempBlogListInfo['searchDataKeywords'] =$scope.searchData.keywords; if($scope.appBlogListSortType == "closest"){ tempBlogListInfo['blogListCurrentLocationLat'] = currentLocationLat; tempBlogListInfo['blogListCurrentLocationLng'] = currentLocationLng; } $mapplerLocalStorage.setItem('blogListInfo', JSON.stringify(tempBlogListInfo)); $state.go('app.blogView', {"addrId":$scope.addrId,"oId":oid, "selectedTabType":"list"}, {reload: true, inherit: false}); } // 검색 $scope.searchBlogList = function(){ offset = 0; $scope.dataTotalCount = 0; $scope.blogList = []; if($scope.isLoggedIn){ if($scope.searchData.mydata){ if($scope.nameSearchValue == ""){ $scope.nameSearchValue = "search=uid eq " + $scope.userInfo.userId + " and login_route_type eq " + $scope.userInfo.signupRouteType; }else{ $scope.nameSearchValue = $scope.nameSearchValue + " and uid eq " + $scope.userInfo.userId + " and login_route_type eq " + $scope.userInfo.signupRouteType; } }else{ $scope.nameSearchValue = "search=name like " + $scope.searchData.keywords; } } $timeout(function() { //$scope.isSearchBlogListBar = false; getBlogDataList(); }, 500); } $scope.backButton = function() { offset = 0; $scope.dataTotalCount = 0; $scope.blogList = []; if($scope.isLoggedIn){ if($scope.searchData.mydata){ $scope.searchData = false; } } $scope.searchData.keywords = ""; $timeout(function() { getBlogDataList(); }, 500); } // 단어 검색의 값을 인식하기 위한 핸들러 $scope.$watch('searchData.keywords', function(newList, oldList) { if(angular.isDefined(newList) && newList != null && newList != ""){ $scope.nameSearchValue = "search=name like " + $scope.searchData.keywords; }else{ $scope.nameSearchValue = ""; } },true); // 검색을 위한 화면 보이기 설정 변경에 따른 이벤트 핸들러 $scope.$on('event:searchBlogListBarChanged', function(event) { $scope.isSearchBlogListBar = !$scope.isSearchBlogListBar; }); // 목록에 대한 sort 설정 변경에 따른 이벤트 핸들러 $scope.$on('event:setAppBlogListSortTypeEvent', function(event, appBlogListSortType) { $scope.appBlogListSortType = appBlogListSortType; currentLocationLat = ""; currentLocationLng = ""; $scope.blogList = []; // 스크롤을 최상단으로 이동 $ionicScrollDelegate.scrollTop(); if(appBlogListSortType == "closest"){ getMyCurrentLocation(); }else{ $scope.refreshLoadData(); } }); // 로그인에 대한 이벤트 핸들러 $scope.$on('event:loginSuccess', function(event, loginUser) { $scope.isLoggedIn = true; $scope.userInfo = loginUser; $scope.loginUserBlogList = loginUser.blogAuthInfoList; // 데이터 대한 권한 가져오기 $scope.blogAuthInfo = $filter('filter')($scope.loginUserBlogList, function (d) {return d.addrId === $scope.appBlogInfo.addrId;})[0]; if($scope.blogAuthInfo.dataAddAuth == 'Y'){ $scope.isAddDataButtonEnable = true; } }); // 로그아웃에 대한 이벤트 핸들러 $scope.$on('event:logoutSuccess', function(event, loginUser) { $scope.isLoggedIn = false; $scope.userInfo = {}; $scope.isAddDataButtonEnable = false; }); } ]) .controller('BlogCoreDataListCtrl', [ '$scope', '$rootScope', '$state', '$ionicLoading', '$ionicModal', '$ionicPopup', '$timeout', '$stateParams', '$ionicHistory', '$ionicScrollDelegate', '$filter', '$cordovaNetwork', '$cordovaSQLite', '$mapplerLocalStorage', 'Constants', 'RestHttpService', 'LocalDBService', 'AppService', 'BlogService', function($scope, $rootScope, $state, $ionicLoading, $ionicModal, $ionicPopup, $timeout, $stateParams, $ionicHistory, $ionicScrollDelegate, $filter, $cordovaNetwork, $cordovaSQLite, $mapplerLocalStorage, Constants, RestHttpService, LocalDBService, AppService, BlogService) { // 블로그 목록 $scope.loginUserBlogList = AppService.getLoginUserBlogList(); $scope.addrId = $stateParams.addrId; $scope.appBlogInfo = {}; if(angular.isUndefined($scope.appBlogInfo) || angular.equals({}, $scope.appBlogInfo)){ $scope.appBlogInfo = $filter('filter')($scope.loginUserBlogList, function (d) {return d.addrId === $scope.addrId;})[0]; } $scope.blogTitle = $scope.appBlogInfo.blogName; $scope.dataTotalCount = 0; $scope.blogList = []; $scope.imgIndex = 0; var blogSiteUrl = $scope.appBlogInfo.siteUrl; var blogId = $scope.appBlogInfo.blogId; // 기존에 저장되어 있는 값이 있는지 확인 $scope.getCoreDataList = function(){ $scope.imgIndex = 0; LocalDBService.getTmpAddDataInfoListToCoreData().then(function(res) { angular.forEach(res, function (item, index) { var tempData = JSON.parse(item.tmp_data); tempData["data_seq"] = item.data_seq; tempData["addr_id"] = item.addr_id; tempData["img_data"] = "img/no-image.png"; $scope.blogList.push(tempData); }); $scope.dataTotalCount = res.length; $timeout(function() { $scope.getImageFromCoreData(); }, 100); }, function (err) { console.error(err); }); } // Core Data에서 이미지 가져오기 $scope.getImageFromCoreData = function(){ if($scope.dataTotalCount != $scope.imgIndex){ var dataSeq = $scope.blogList[$scope.imgIndex].data_seq; LocalDBService.getTmpImageInfoListToCoreData(dataSeq).then(function(res) { var tempImgListLength = res.length; if(tempImgListLength > 0){ $scope.blogList[$scope.imgIndex].img_data = res[0].img; } $scope.imgIndex = $scope.imgIndex + 1; $timeout(function() { $scope.getImageFromCoreData(); }, 100); }, function (err) { console.error(err); }); } } document.addEventListener("deviceready", function () { $scope.getCoreDataList(); }, false); // 상세보기 $scope.goDataView = function(dataSeq, addrId){ $state.go('app.blogCoreDataView', {"addrId":addrId, "dataSeq":dataSeq}, {reload: true, inherit: false}); } // data sync 완료에 대한 이벤트 핸들러 $scope.$on('event:dataUploadSyncProcessFinished', function(event) { $scope.dataTotalCount = 0; $scope.blogList = []; $timeout(function() { $scope.getCoreDataList(); }, 100); }); // 로그아웃에 대한 이벤트 핸들러 $scope.$on('event:logoutSuccess', function(event, loginUser) { $scope.isLoggedIn = false; $scope.userInfo = {}; $scope.isAddDataButtonEnable = false; }); } ]);
(function() { 'use strict'; angular .module('BlackSwanGitHub') .controller('IssuesCtrl', IssuesCtrl); IssuesCtrl.$inject = ['$scope', 'githubFactory', '$log', '$routeParams','$location']; function IssuesCtrl($scope, githubFactory, $log, $routeParams, $location) { var vm = this; $log.info("routeParams:" + $routeParams.repo + $routeParams.user); $scope.repo = $routeParams.repo; $scope.repoUser = $routeParams.user; $scope.per_page = 10; $scope.page = 1; $scope.chartData = { options : { scales: { yAxes: [ { id: 'y-axis-1', type: 'linear', display: true, position: 'left' }, { id: 'y-axis-2', type: 'linear', display: true, position: 'right' } ] } } } ; $scope.chartData.datasetOverride = [{ yAxisID: 'y-axis-1' }, { yAxisID: 'y-axis-2' }]; $scope.chartData.labels = ["Forks Count","Network Count", "Open Issues Count", "Stargazers Count", "Subscribers Count", "Watchers Count"]; $scope.chartData.series = [$scope.repo]; vm.listIssues = function listIssues(username, reponame, perPage, page) { githubFactory.getRepoIssues({ user: username, repo:reponame, per_page: perPage, page : page, }).then(function(_data){ $scope.totalIssues = _data.data.total_count; $scope.issues = _data.data.items; $scope.pageCount = (_data.data.total_count / perPage ); console.log(_data) //on success }).catch(function (_data) { }); } vm.repoDetails = function repoDetails(username, reponame) { githubFactory.getRepoDetails({ user: username, repo:reponame, }).then(function(_data){ $scope.chartData.data = [_data.data.forks_count, _data.data.network_count, _data.data.open_issues_count , _data.data.stargazers_count, _data.data.subscribers_count , _data.data.watchers_count]; console.log(_data.data) //on success }).catch(function (_data) { }); } vm.repoDetails($scope.repoUser, $scope.repo); vm.listIssues($scope.repoUser, $scope.repo, $scope.per_page, $scope.page); $scope.nextPage = function nextPage (page) { vm.listIssues($scope.repoUser, $scope.repo, $scope.per_page, page); } $scope.rowsToShow = function rowsToShow (rows) { $scope.per_page = rows; vm.listIssues($scope.repoUser, $scope.repo, rows, $scope.page); } $scope.sort = function sort (sort) { vm.listIssues($scope.repo, sort, $scope.repoOrder, $scope.perPage, $scope.Page); } } })();
angular.module('quizz-admin').controller('MultiChoiceAnswersReportController', ['$scope', '$rootScope', '$routeParams', '$location', 'reportService', function ($scope, $rootScope, $routeParams, $location, reportService) { $scope.quizID = $routeParams.quizId; $scope.$watch('quizID', function(newValue, oldValue) { if (newValue && newValue != '') { $scope.load(newValue); $location.search('quizId', newValue); $routeParams.quizId = newValue; } else { $scope.reportData = []; $location.search('quizId', null); $routeParams.quizId = null; } }); $scope.loadQuizes = function() { reportService.listQuizes( function(response) { $scope.quizes = response.items; $scope.readyToShow = true; }, function(error) { }); }; $scope.loadQuizes(); $scope.load = function(quizID) { reportService.loadAnswersReport($scope.quizID, function(response) { $scope.$apply(function() { $scope.answersKind = $scope.getAnswersKind(response.items); $scope.reportData = response.items; }); }, function(error) { }); }; $scope.getAnswersKind = function(items) { var result = ''; angular.forEach(items, function(item) { if (item.answers && item.answers.length > 0) { var kind = item.answers[0].kind; if (kind == 'GOLD' || kind == 'INCORRECT' || kind == 'SILVER') { result = 'SELECTABLE'; } else { result = 'INPUT'; } return; } }); return result; }; }]);
function createElement(type, props, ...children) { //返回虚拟dom props.children = children; delete props.__self; delete props.__source; //能区分组件类型: //vtype:1-原生标签;2-函数组件;3-类组件 let vtype; if (typeof type === 'string') { //原生标签 vtype=1; } else { if(type.isReactComponent) { //类组件 vtype=3; }else { //函数组件 vtype=2; } } return {vtype,type, props}; } export class Component { static isReactComponent=true; constructor(props) { this.props = props; this.state = {}; } setState() { } forceUpdate() { } } export default {createElement}
module.exports = function () { temp = './temp/'; var config = { src : './source/', dest : './assets/', styles : { src : 'styles/*.styl', dest : 'styles/' }, scripts : { src : 'scripts/*.js', dest : 'scripts/' }, optimized : { style : { name :'app.css', vendor : 'lib.css' }, script : { name : 'app.js', vendor : 'lib.js' } }, alljs : [ './source/**/*.js', './*.js' ], temp : temp }; return config; };
import {pageSize, pageSizeType, paginationConfig, searchConfig} from '../../globalConfig'; import name from '../../dictionary/name'; const containerTypeOptions = [{value:1, title:'1'}, {value:2, title:'2'}]; const tableCols = [ {key: 'carMode', title: '车型'}, {key: 'length', title: '长' }, {key: 'width', title: '宽'}, {key: 'height', title: '高' }, {key: 'maxWeight', title: '最大装载重量' }, {key: 'maxVolume', title: '最大装载体积' }, {key: 'containerRate', title: '标准柜比例', options: containerTypeOptions }, {key: 'isContainer', title: '是否柜车', from:'dictionary', position: name.YES_OR_NO }, {key: 'containerType', title: '柜车类型', from:'dictionary', position: name.CONTAINER_TYPE }, {key: 'containerCode', title: '柜型标准代码' }, {key: 'remark', title: '备注'}, {key: 'active', title: '状态', from:'dictionary', position: name.ACTIVE} ]; const filters = [ {key: 'carMode', title: '车型', type: 'text'}, {key: 'maxWeight', title: '最大装载重量', type: 'number', remark2: true}, {key: 'maxVolume', title: '最大装载体积', type: 'number', remark2: true} ]; const buttons = [ {key: 'add', title: '新增', bsStyle: 'primary', sign: 'car_type_new'}, {key: 'edit', title: '编辑', sign: 'car_type_edit'}, {key: 'del', title: '删除', sign: 'car_type_delete'}, {key: 'active', title: '激活', sign: 'car_type_active'}, //{key: 'input', title: '导入'}, //{key: 'output', title: '导出'} ]; const controls = [ {key: 'carMode', title: '车型', type:'text', required: true }, {key: 'length', title: '长',type:'number', props: {real: true, precision: 2}}, {key: 'width', title: '宽',type:'number', props: {real: true, precision: 2}}, {key: 'height', title: '高',type:'number', props: {real: true, precision: 2}}, {key: 'maxWeight', title: '最大装载重量',type:'number', props: {real: true, precision: 2}}, {key: 'maxVolume', title: '最大装载体积',type:'number', props: {real: true, precision: 2}}, {key: 'containerRate', title: '标准柜比例',type:'select', options: containerTypeOptions }, {key: 'isContainer', title: '是否柜车', type:'radioGroup', from:'dictionary', position: name.YES_OR_NO }, {key: 'containerType', title: '柜车类型',type:'select', from:'dictionary', position: name.CONTAINER_TYPE }, {key: 'containerCode', title: '柜型标准代码',type:'text'}, {key: 'remark', title: '备注', type:'text' }, {key: 'active', title: '状态', type: 'readonly', from:'dictionary', position: name.ACTIVE} ]; const index = { filters, buttons, tableCols, pageSize, pageSizeType, paginationConfig, searchConfig }; const edit = { controls, edit: '编辑', add: '新增', config: {ok: '确定', cancel: '取消'} }; const config = { index, edit }; export default config;
import firebase from 'firebase/app' import 'firebase/functions' import 'firebase/firestore' import 'firebase/auth' const firebaseConfig = { apiKey: process.env.VUE_APP_FIREBASE_API_KEY, authDomain: process.env.VUE_APP_FIREBASE_AUTH_DOMAIN, projectId: process.env.VUE_APP_FIREBASE_PROJECT_ID, storageBucket: process.env.VUE_APP_FIREBASE_STORAGE_BUCKET, messagingSenderId: process.env.VUE_APP_FIREBASE_MESSAGING_SENDER_ID, appId: process.env.VUE_APP_FIREBASE_APP_ID, measurementId: process.env.VUE_APP_FIREBASE_MEASUREMENT_ID, clientId: process.env.VUE_APP_FIREBASE_WEB_CLIENT_ID, clientSecret: process.env.VUE_APP_FIREBASE_WEB_CLIENT_SECRET, scopes: ['email', 'profile', 'https://www.googleapis.com/auth/calendar'] } // Initialize Firebase const app = firebase.initializeApp(firebaseConfig) const server = '127.0.0.1' firebase.firestore().useEmulator(server, 8080) firebase.functions().useEmulator(server, 5001) firebase.auth().onAuthStateChanged(async (user) => { let result = await firebase.auth().getRedirectResult() if (result.credential) { await firebase.firestore().collection('settings').doc('google').set({ user: JSON.parse(JSON.stringify(user)), refreshToken: user.refreshToken, updated: Date.now() }) } }) export default app
var lock="free"; var counter="0"; const maxCounter=10000; var vid1 = "<video width=\"320\" height=\"240\" autoplay><source src=\""; var vid2 = "\" type=\"video/mp4\"></video>"; var img1="<img src=\""; var img2="\" class=\"thumb\">"; function counterplus() { var acc = document.getElementById("counter"); counter++; acc.style.display = "block"; acc.innerHTML= "Jobs en cours : " + counter ; } function countermoins() { var acc = document.getElementById("counter"); counter--; if (counter === 0) { acc.style.display = "none"; } else { acc.innerHTML= "Jobs en cours : " + counter ; acc.style.display = "block"; } acc.innerHTML= "Jobs en cours : " + counter ; } function InitAccord() { var acc = document.getElementsByClassName("accordion"); var i; var panel; for (i = 0; i < acc.length; i++) { acc[i].addEventListener("click", function () { this.classList.toggle("active"); panel = this.nextElementSibling; if (panel.style.display === "block") { panel.style.display = "none"; } else { panel.style.display = "block"; } }); } } function closePanels() { var acc = document.getElementsByClassName("accordion"); var i; var panel; for (i = 0; i < acc.length; i++) { panel = acc[i].nextElementSibling; panel.style.display = "none"; } } function openAllPanels() { var acc = document.getElementsByClassName("accordion"); var i; var panel; for (i = 0; i < acc.length; i++) { panel = acc[i].nextElementSibling; panel.style.display = "block"; } } function openThisPanel(repere) { var panel; panel=document.getElementById("panel"+repere+"F"); panel.style.display = "block"; panel=document.getElementById("panel"+repere+"H"); panel.style.display = "block"; panel=document.getElementById("panel"+repere+"C"); panel.style.display = "block"; panel=document.getElementById("panel"+repere+"T"); panel.style.display = "block"; } function closeThisPanel(repere) { var panel; panel=document.getElementById("panel"+repere+"details"); panel.style.display = "none"; } function loadXMLDoc(filename) { if (window.ActiveXObject) { xhttp = new ActiveXObject("Msxml2.XMLHTTP"); } else { xhttp = new XMLHttpRequest(); } xhttp.open("GET", filename, false); xhttp.send(""); return xhttp.responseXML; } function playSound(s) { var e=document.createElement('audio'); e.setAttribute('src',s); e.play(); } class contexte { constructor(doc , ref, duree) { this.doc = doc; this.ref = ref; this.duree = duree; this.newurl = "Qxref.php" + "?doc=" + this.doc + "&ref="+ this.ref +"&duree="+ this.duree ; } send(){ var xhttp = new XMLHttpRequest(); document.getElementById(this.doc + this.ref).innerHTML = '<div class="tooltip">Running <span class="tooltiptext">(' + counter +')</span></div>'; var self = this; // Set up something that survives into the closure xhttp.onreadystatechange = function(){ if (xhttp.readyState == 4) { countermoins(); if (xhttp.status == 200) { playSound("coq.mp3"); document.getElementById(self.doc + self.ref).innerHTML = xhttp.responseText; } else { playSound("bang.mp3"); var stringError= "<p>Err " + xhttp.status + "</p>" ; document.getElementById(self.doc + self.ref).innerHTML = xhttp.responseText; } } } // alert ( "GET sur l'URL: " + this.newurl ); xhttp.open("GET", this.newurl, true); xhttp.send(""); } } function displayXref(doc,ref,duree) { if (lock !="free") { playSound("bang.mp3"); alert(" travail en cours, réessaie!") } else { if (counter > maxCounter) { alert(" trops de jobs en cours, réessaie!") } else { lock="busy"; counterplus(); var ctxt=new contexte(doc,ref,duree); ctxt.send(self.doc + self.ref); playSound("ting.mp3"); lock="free"; } } } function displayAllXref(doc,duree,...listrefs) { listrefs.forEach(function(ref){ displayXref(doc,ref,duree); }); } class contextedelete { constructor(doc , ref, duree) { this.doc = doc; this.ref = ref; this.newurl = "delObjRef.php" + "?doc=" + this.doc + "&ref="+ this.ref ; } send(){ var xhttp = new XMLHttpRequest(); document.getElementById(this.doc + this.ref).innerHTML = '<div class="tooltip">Deleting <span class="tooltiptext">(' + counter +')</span></div>'; var self = this; // Set up something that survives into the closure xhttp.onreadystatechange = function(){ if (xhttp.readyState == 4) { countermoins(); if (xhttp.status == 200) { playSound("coq.mp3"); document.getElementById(self.doc + self.ref).innerHTML = "<small>" + xhttp.responseText + "</small>"; } else { playSound("bang.mp3"); var stringError= "<p>Err " + xhttp.status + "</p>" ; document.getElementById(self.doc + self.ref).innerHTML = xhttp.responseText; } } } // alert ( "GET sur l'URL: " + this.newurl ); xhttp.open("GET", this.newurl, true); xhttp.send(""); } } function delRef(doc,ref,target) { r = confirm("Tu veux vraiment supprimer " + ref + " dans le theme " + target + " de " + doc + "?"); if (r == true) { if (lock !="free") { playSound("bang.mp3"); alert(" travail en cours, réessaie!") } else { if (counter > maxCounter) { alert(" trops de jobs en cours, réessaie!") } else { lock="busy"; counterplus(); var ctxt=new contextedelete(doc,ref); ctxt.send(); playSound("ting.mp3"); lock="free"; } } } } function viewThumbVideo(id,target) { document.getElementById(id).innerHTML = vid1 + target + vid2; } function viewThumbImg(id,target) { document.getElementById(id).innerHTML = img1 + target + img2; } function setGenre(id,path) { // http://fritz-home/m/MySetTag.php?file=essai%2Faudio%2FSonnette%2FSambre_et_meuse.mp3&artist=Arm%C3%A9e+Fran%C3%A7aise&title=Sambre+et+Meuse&album=On+les+aura&year=2001 var btn = document.getElementById("setGenre" + id); var url = "/BD/MySetGenre.php"; url += "?id=" + id; url += "&path=" + path; var mygenre = document.getElementById("genre" + id); var selectedIndex=mygenre.selectedIndex; var mygenretext = mygenre.options[mygenre.selectedIndex].text; var genre = mygenre.options[mygenre.selectedIndex].value; url += "&genre=" + mygenretext; if (window.ActiveXObject) { xhttp = new ActiveXObject("Msxml2.XMLHTTP"); } else { xhttp = new XMLHttpRequest(); } xhttp.onreadystatechange = function () { //Call a function when the state changes. if (xhttp.readyState == 4) { if (xhttp.status == 200) { // playSound("/m/coq.mp3"); document.getElementById("genre" + id).selectedIndex = selectedIndex; makeAlbum(id,path); } else { playSound("/m/bang.mp3"); alert(xhttp.responseText + " Retour xhttp.status = " + xhttp.status); } } } // alert ( "GET sur l'URL: " + url ); xhttp.open("GET", url, true); xhttp.send(""); } function makeAlbum(id,path) { // http://fritz-home/m/MySetTag.php?file=essai%2Faudio%2FSonnette%2FSambre_et_meuse.mp3&artist=Arm%C3%A9e+Fran%C3%A7aise&title=Sambre+et+Meuse&album=On+les+aura&year=2001 var btn = document.getElementById("setGenre" + id); var url = "/BD/makeAlbum.php"; url += "?id=" + id; url += "&path=" + path; if (window.ActiveXObject) { xhttp = new ActiveXObject("Msxml2.XMLHTTP"); } else { xhttp = new XMLHttpRequest(); } xhttp.onreadystatechange = function () { //Call a function when the state changes. if (xhttp.readyState == 4) { if (xhttp.status == 200) { // playSound("/m/coq.mp3"); alert(xhttp.responseText + " Retour xhttp.status = " + xhttp.status); } else { playSound("/m/bang.mp3"); alert(xhttp.responseText + " Retour xhttp.status = " + xhttp.status); } } } // alert ( "GET sur l'URL: " + url ); xhttp.open("GET", url, true); xhttp.send(""); }
import React, { useState } from "react"; function Additem(props){ const [note,setNote] = useState(""); function onchangefunc(e){ setNote(e.target.value); } function addnotefunc(e){ if(note!=="" && e.type==="click"){ props.addToList(note); setNote(""); } else if(note!=="" && e.key==="Enter"){ props.addToList(note); setNote(""); } } return <div className="additem"> <input type="text" placeholder="Enter the item here" onChange={onchangefunc} onKeyDown={addnotefunc} value={note}></input> <button onClick={addnotefunc}>➕</button> </div> } export default Additem;
/** * Initialize your data structure here. */ var TrieNode = function() { this.nodes = []; this.endFlag = false; } var Trie = function() { this.root = new TrieNode(); this.root.endFlag = true; }; /** * Inserts a word into the trie. * @param {string} word * @return {void} */ Trie.prototype.insert = function(word) { var node = this.root; for(var i = 0; i< word.length; i++) { var item = word.charCodeAt(i)-97; if(!node.nodes[item]) { node.nodes[item] = new TrieNode(); } node = node.nodes[item]; } node.endFlag = true; }; /** * Returns if the word is in the trie. * @param {string} word * @return {boolean} */ Trie.prototype.search = function(word) { var node = this.root; for (var i = 0; i< word.length; i++) { var item = word.charCodeAt(i)-97; if(node.nodes[item]) { node = node.nodes[item]; } else { return false; } } return node.endFlag; }; /** * Returns if there is any word in the trie that starts with the given prefix. * @param {string} prefix * @return {boolean} */ Trie.prototype.startsWith = function(prefix) { var node = this.root; for (var i = 0; i <prefix.length; i++) { var item = prefix.charCodeAt(i)-97; if(node.nodes[item]) { node = node.nodes[item]; } else { return false; } } return true; }; /** * Your Trie object will be instantiated and called as such: * var obj = Object.create(Trie).createNew() * obj.insert(word) * var param_2 = obj.search(word) * var param_3 = obj.startsWith(prefix) */
const mongoose = require('mongoose'); const passport = require('passport'); const router = require('express').Router(); const auth = require('../auth'); const User = mongoose.model('User'); const Message = mongoose.model('Message'); const Channel = mongoose.model('Channel'); const Validator = require('validator'); const config = require('../../config/main'); const bodyParser = require('body-parser'); router.get('/', auth.optional, (req, res) => { console.log('GET /channels: Request received.'); console.time('getChannels'); Channel.find({alive: true, public: true}).then((channelList) => { console.timeEnd('getChannels'); res.json(channelList); }); }); router.get('/:channelId', auth.optional, (req, res) => { console.log('GET /channels/:channelId: Request received.'); Channel.findById(req.params.channelId).then((channel) => { if (channel.alive && channel.public) { console.log('GET channels/:channelId: Channel info sent.'); res.json(channel); } else { console.log('GET channels/:channelId/: Channel not found.'); res.status(400).send('SERVER: Channel not found.'); } }); }); // { // "name":"string", // "description":"string", // "public":"boolean" // } router.post('/', auth.required, async (req, res) => { console.log('POST /channels: Request received.'); const {payload: {id}} = req; User.findById(id).then((owner) => { if (owner) { if (validateChannelName(req.body.name)) { if (validateChannelDescription(req.body.description)) { var newChannel = new Channel({ owner: owner, time: Date.now(), name: req.body.name, description: req.body.description, avatar: config.DEFAULT_AVATAR_URL, public: req.body.public, members: [owner], alive: true }); newChannel.save().then(() => { owner.channels.push(newChannel._id); owner.save().then(() => { console.log('POST /channels: Channel created.'); res.sendStatus(201); }); }); } else { console.log('POST /channels: Invalid channel description.'); res.status(400).send('SERVER: Invalid channel description.'); } } else { console.log('POST /channels: Invalid channel name.'); res.status(404).send('SERVER: Invalid channel name.'); } } else { console.log('POST /channels: User not found.'); res.status(404).send('SERVER: User not found.'); } }); }); router.post('/:channelId/membership', auth.required, async (req, res) => { console.log('POST /channels/:channelId/membership: Request received.'); const {payload: {id}} = req; User.findById(id).then((user) => { if (user) { Channel.findById(req.params.channelId).then((channel) => { if (channel) { if (channel.alive === true) { if (user.channels.indexOf(channel._id) === -1) { user.channels.push(channel._id); if (channel.members.indexOf(user._id) === -1) { channel.members.push(user._id); user.save().then(() => { channel.save().then(() => { console.log('POST /channels/:channelId/membership:', user.username, 'joined ', channel.name); res.sendStatus(200); }); }); } } else { console.log('POST /channels/:channelId/membership: User already in channel.'); res.status(400).send('SERVER: User already in channel.'); } } else { console.log('POST /channels/:channelId/membership: Channel has been deleted.'); res.status(404).send('SERVER: Channel has been deleted.'); } } else { console.log('POST /channels/:channelId/membership: Channel not found.'); res.status(404).send('SERVER: Channel not found.'); } }); } else { console.log('POST /channels/:channelId/membership: User not found.'); res.status(404).send('SERVER: User not found.'); } }); }); router.delete('/:channelId/membership', auth.required, async (req, res) => { console.log('DELETE /channels/:channelId/membership: Request received.'); const {payload: {id}} = req; User.findById(id).then((user) => { if (user) { Channel.findById(req.params.channelId).then((channel) => { if (channel) { if (channel.owner.toString() !== id) { //replace this with better code using update() var membersIndex = channel.members.indexOf(user._id); if (membersIndex !== -1) { channel.members.splice(membersIndex, 1); } var channelsIndex = user.channels.indexOf(channel._id); if (channelsIndex !== -1) { user.channels.splice(channelsIndex, 1); } user.save().then(() => { channel.save().then(() => { console.log('DELETE /channels/:channelId/membership:', user.username, 'left channel', channel.name,'.'); res.sendStatus(200); }); }); } else { console.log('DELETE /channels/:channelId/membership: The owner cannot leave their channel.'); res.status(400).send('SERVER: The owner cannot leave their channel.'); } } else { console.log('DELETE /channels/:channelId/membership: Channel not found.'); res.status(404).send('SERVER: Channel not found.'); } }); } else { console.log('DELETE /channels/:channelId/membership: The owner cannot leave their channel: User not found.'); res.status(404).send('SERVER: User not found.'); } }); }); //use a socket to tell member sthey're baleeted before kicking them. router.delete('/:channelId', auth.required, (req, res) => { console.log('DELETE /channels/:channelId: Request received.'); const {payload: {id}} = req; User.findById(id).then((user) => { if (user) { Channel.findById(req.params.channelId).then((channel) => { if (channel) { for (key in channel.members) { User.findById(channel.members[key]).then((member) => { //replace this with better code using update() var channelsIndex = member.channels.indexOf(channel._id); if (channelsIndex !== -1) { member.channels.splice(channelsIndex, 1); member.save(); } }); } if (channel.owner.toString() === id) { channel.alive = false; channel.save().then(() => { res.sendStatus(200); }); } else { console.log('DELETE /channels/:channelId: User is not the owner of this channel.'); res.status(401).send('SERVER: User is not the owner of this channel.'); } } else { console.log('DELETE /channels/:channelId: Channel not found.'); res.status(404).send('SERVER: Channel not found.'); } }); } else { console.log('DELETE /channels/:channelId: User not found.'); res.status(404).send('SERVER: User not found.'); } }); }); router.patch('/:channelId/transferOwnership/:userId', auth.required, async (req, res) => { console.log('PATCH /channels/:channelId/transferOwnership: Request received.'); const {payload: {id}} = req; User.findById(id).then((user) => { if (user) { Channel.findById(req.params.channelId).then ((channel) => { if (channel) { if (channel.owner.toString() === id) { User.findById(req.params.userId).then ((newOwner) => { if (newOwner) { channel.owner = newOwner; channel.save().then(() => { console.log('PATCH /channels/:channelId/transferOwnership: New owner is', channel.owner.username,'.'); res.sendStatus(200); }); } else { console.log('PATCH /channels/:channelId/transferOwnership: New owner not found.'); res.status(404).send('SERVER: New owner not found.'); } }) } else { console.log('PATCH /channels/:channelId/transferOwnership: User is not the owner of this channel.'); res.status(401).send('SERVER: User is not the owner of this channel.'); } } else { console.log('PATCH /channels/:channelId/transferOwnership: Channel not found.'); res.status(404).send('SERVER: Channel not found.'); } }); } else { console.log('PATCH /channels/:channelId/transferOwnership: User not found.'); res.status(404).send('SERVER: User not found.'); } }); }); // { // "name":"string", // "description":"string", // "avatar":"string", // "public":"boolean" // } router.patch('/:channelId', auth.required, async (req, res) => { console.log('PATCH /channels/:channelId: Request received.'); const {payload: {id}} = req; User.findById(id).then((user) => { if (user) { Channel.findById(req.params.channelId).then((channel) => { if (channel) { if (channel.owner.toString() === id) { if (validateChannelName(req.body.name)) { channel.name = req.body.name; } else { console.log('PATCH /channels/:channelId: Name not found or failed validation.'); } if (validateChannelDescription(req.body.description)) { channel.description = req.body.description; } else { console.log('PATCH /channels/:channelId: Description not found or failed validation.'); } if (validateChannelAvatar(req.body.avatar)) { channel.avatar = req.body.avatar; } else { console.log('PATCH /channels/:channelId: Avatar not found or failed validation.'); } if (req.body.public) { channel.public = req.body.public; } console.log(channel); channel.save().then(() => { console.log('PATCH /channels/:channelId: Settings saved.'); res.sendStatus(200); }); } else { console.log('PATCH /channels/:channelId: User is not the owner of this channel.'); res.status(401).send('SERVER: User is not the owner of this channel.'); } } else { console.log('PATCH /channels/:channelId: Channel not found.'); res.status(404).send('SERVER: Channel not found.'); } }); } else { console.log('PATCH /channels/:channelId: User not found.'); res.status(404).send('SERVER: User not found.'); } }); }); // { // "messageText":"string" // } router.post('/:channelId/message', auth.required, async (req, res) => { console.log('POST /channels/:channelId/message: Request received.'); const {payload: {id}} = req; if (validateMessage(req.body.messageText)) { User.findById(id).then((user) => { if (user) { Channel.findById(req.params.channelId).then((channel) => { if (channel) { var MessageModel = mongoose.model('Message', Message.schema, req.params.channelId); MessageData = new MessageModel({ user: user, time: Date.now(), channel: req.params.channelId, messageText: req.body.messageText, edited: false, alive: true }); MessageData.save().then(() => { console.log('POST /channels/:channelId/message: Post made.'); res.sendStatus(201); }); } else { console.log('POST /channels/:channelId/message: Channel not found.'); res.status(404).send('SERVER: Channel not found.'); } }); } else { console.log('POST /channels/:channelId/message: User not found.'); res.status(404).send('SERVER: User not found.'); } }); } }); // router.get('/:channelId/:messageId', auth.optional, async (req, res) => { // Channel.findById(req.params.channelId).then((channel) => { // if (channel) { // getMessageModel(req.params.channelId).find({alive: true}).sort({'time':1}).limit() // } // }) // }); //change this to do 50 at a time later router.get('/:channelId/message', auth.optional, async (req, res) => { console.log('GET /channels/:channelId/message: Request received.'); Channel.findById(req.params.channelId).then((channel) => { if (channel) { getMessageModel(req.params.channelId).find({alive: true}).sort({'time':1}).limit(50).populate('user').then((data) => { console.log('GET /channels/:channelId/message: Sending messages.') res.json(data); }); } else { console.log('GET /channels/:channelId/message: Channel not found.'); res.status(404).send('SERVER: Channel not found.'); } }); }); router.delete('/:channelId/message/:messageId', auth.required, async (req, res) => { console.log('DELETE /channels/:channelId/message/:messageId: Request received.'); const {payload: {id}} = req; //kick everyone out before deleting channel Channel.findById(req.params.channelId).then((channel) => { if (channel) { getMessageModel(req.params.channelId).findById(req.params.messageId).then((message) => { if (message) { if (message.user.toString() === id || channel.officers.includes(message.user) || message.user === channel.owner) { message.alive = false; message.save(); console.log('DELETE /channels/:channelId/message/:messageId: Deleted message.'); res.sendStatus(200); } else { console.log('DELETE /channels/:channelId/message/:messageId: Insufficient permissions.'); res.status(401).send('SERVER: Insufficient permissions.'); } } else { console.log('DELETE /channels/:channelId/message/:messageId: Message not found.'); res.status(404).send('SERVER: Message not found.'); } }); } else { console.log('DELETE /channels/:channelId/message/:messageId: Channel not found.'); res.status(404).send('SERVER: Channel not found.'); } }); }); router.patch('/:channelId/message/:messageId', auth.required, async (req, res) => { console.log('PATCH /channels/:channelId/message/:messageId: Request received.'); const {payload: {id}} = req; if (messageTextValidation(req.body.messageText)) { Channel.findById(req.params.channelId).then((channel) => { if (channel) { getMessageModel(req.params.channelId).findById(req.params.messageId).then((message) => { if (message.alive) { if (message.user.toString() === id) { message.edited = true; message.messageText = req.body.messageText; message.save().then(() => { console.log('PATCH /channels/:channelId/message/:messageId: Message edited.'); res.sendStatus(200); }); } else { console.log('PATCH /channels/:channelId/message/:messageId: Insufficient permissions.'); res.status(401).send('SERVER: Insufficient permissions.'); } } else { console.log('PATCH /channels/:channelId/message/:messageId: Message not found.'); res.status(404).send('SERVER: Message not found.'); } }); } else { console.log('PATCH /channels/:channelId/message/:messageId: Channel not found.'); res.status(404).send('SERVER: Channel not found.'); } }) } else { console.log('PATCH /channels/:channelId/message/:messageId: Invalid message text.'); res.status(400).send('SERVER: Invalid message text.'); } }); function getMessageModel(channelId) { return mongoose.model('Message', Message.schema, channelId); } function validateChannelName(channelName) { if (Validator.isLength(channelName, config.MIN_CHANNEL_NAME_LENGTH, config.MAX_CHANNEL_NAME_LENGTH)) { if (Validator.isAlphanumeric(channelName)) { return true; } } return false; } function validateChannelDescription(channelDescription) { if (Validator.isLength(channelDescription, config.MIN_CHANNEL_DESCRIPTION_LENGTH, config.MAX_CHANNEL_DESCRIPTION_LENGTH)) { return true; } return false; } function validateChannelAvatar(avatar) { if (Validator.isURL(avatar)) { return true; } return false; } function validateMessage(messageText) { if (Validator.isLength(messageText, 0, config.MAX_MESSAGE_LENGTH)) { return true; } return false; } module.exports = router;
import { uid, isServer, isDocumentVisible, Console } from './utils' export function makeQueryInstance(query, onStateUpdate) { const instance = { id: uid(), onStateUpdate, } instance.clearInterval = () => { clearInterval(instance.refetchIntervalId) delete instance.refetchIntervalId } instance.updateConfig = config => { const oldConfig = instance.config // Update the config instance.config = config if (!isServer) { if (oldConfig?.refetchInterval === config.refetchInterval) { return } query.clearIntervals() const minInterval = Math.min( ...query.instances.map(d => d.config.refetchInterval || Infinity) ) if ( !instance.refetchIntervalId && minInterval > 0 && minInterval < Infinity ) { instance.refetchIntervalId = setInterval(() => { if ( query.instances.some(instance => instance.config.enabled) && (isDocumentVisible() || query.instances.some( instance => instance.config.refetchIntervalInBackground )) ) { query.fetch() } }, minInterval) } } } instance.run = async () => { try { // Perform the refetch for this query if necessary if ( query.config.enabled && // Don't auto refetch if disabled !query.wasSuspended && // Don't double refetch for suspense query.state.isStale && // Only refetch if stale (query.config.refetchOnMount || query.instances.length === 1) ) { await query.fetch() } query.wasSuspended = false } catch (error) { Console.error(error) } } instance.unsubscribe = () => { query.instances = query.instances.filter(d => d.id !== instance.id) if (!query.instances.length) { query.clearIntervals() query.cancel() if (!isServer) { // Schedule garbage collection query.scheduleGarbageCollection() } } } return instance }
/* * CnbiSoft JavaScript Library jQuery Plugin Copyright CnbiSoft * Technologies LLP License Information at <http://www.CnbiSoft.com/license> * * @author CnbiSoft Technologies LLP * * @version CnbiSoft/3.2.3-sr2.6105 */ (function() { var j = CnbiSoft(["private", "extensions.jQueryPlugin"]); if (j !== void 0) { var b = window.jQuery, i, k, l; b.CnbiSoft = j.core; i = function(a, d) { var c, e, g, h; e = d instanceof Array || d instanceof b ? Math.min(a.length, d.length) : a.length; for (c = 0; c < e; c += 1) if (g = d instanceof Array || d instanceof b ? d[c] : d, a[c].parentNode) j.core.render(b.extend({}, g, { renderAt : a[c] })); else { g = new CnbiSoft(b.extend({}, g, { renderAt : a[c] })); if (!b.CnbiSoft.delayedRender) b.CnbiSoft.delayedRender = {}; b.CnbiSoft.delayedRender[g.id] = a[c]; h = document.createElement("script"); h.setAttribute("type", "text/javascript"); h.appendChild(document .createTextNode("CnbiSoft.items['" + g.id + "'].render();")); a[c].appendChild(h) } return a }; j.addEventListener("*", function(a, d) { var c; b.extend(a, b.Event("CnbiSoft" + a.eventType)); a.sender && a.sender.options && a.sender.options.containerElementId ? (c = a.sender.options.containerElementId, typeof c === "object" ? b(c).trigger(a, d) : b("#" + c).length ? b("#" + c).trigger(a, d) : b(document).trigger(a, d)) : b(document).trigger(a, d) }); k = function(a) { return a.filter(":CnbiSoft").add(a.find(":CnbiSoft")) }; l = function(a, d, c) { typeof d === "object" && a.each(function() { this.configureLink(d, c) }) }; b.fn.insertCnbiSoft = function(a) { return i(this, a) }; b.fn.appendCnbiSoft = function(a) { a.insertMode = "append"; return i(this, a) }; b.fn.prependCnbiSoft = function(a) { a.insertMode = "prepend"; return i(this, a) }; b.fn.attrCnbiSoft = function(a, d) { var c = [], b = k(this); if (d !== void 0) return b.each(function() { this.CnbiSoft.setChartAttribute(a, d) }), this; if (typeof a === "object") return b.each(function() { this.CnbiSoft.setChartAttribute(a) }), this; b.each(function() { c.push(this.CnbiSoft.getChartAttribute(a)) }); return c }; b.fn.updateCnbiSoft = function(a) { var b, c, e, g, h, f = {}, j = k(this), i = [["swfUrl", !1], ["height", !1], ["width", !1], ["bgColor", !0], ["renderer", !0], ["dataFormat", !1], ["dataSource", !1], ["detectFlashVersion", !0], ["autoInstallRedirect", !0], ["lang", !0], ["scaleMode", !0], ["debugMode", !0]]; b = 0; for (c = i.length; b < c; b += 1) h = i[b][0], a[h] && (i[b][1] && (g = !0), f[h] = a[h]); j.each(function() { e = this.CnbiSoft; if (g) e.clone(f).render(); else { if (f.dataSource !== void 0 || f.dataFormat !== void 0) f.dataSource === void 0 ? e.setChartData(e.args.dataSource, f.dataFormat) : f.dataFormat === void 0 ? e .setChartData(f.dataSource, e.args.dataFormat) : e .setChartData(f.dataSource, f.dataFormat); (f.width !== void 0 || f.height !== void 0) && e.resizeTo(f.width, f.height); if (f.swfUrl) e.src = f.swfUrl, e.render() } }); return this }; b.fn.cloneCnbiSoft = function(a, d) { var c, e; typeof a !== "function" && typeof d === "function" && (e = a, a = d, d = e); c = []; k(this).each(function() { c.push(this.CnbiSoft.clone(d, {}, !0)) }); a.call(b(c), c); return this }; b.fn.disposeCnbiSoft = function() { k(this).each(function() { this.CnbiSoft.dispose(); delete this.CnbiSoft; this._fcDrillDownLevel === 0 && delete this._fcDrillDownLevel }); return this }; b.fn.convertToCnbiSoft = function(a, d) { var c = []; if (typeof a.dataConfiguration === "undefined") a.dataConfiguration = {}; b.extend(!0, a.dataConfiguration, d); this.each(function() { c.push(b("<div></div>").insertBefore(this) .insertCnbiSoft(a).get(0)) }); return b(c) }; b.fn.drillDownCnbiSoftTo = function() { var a, b, c, e, g, h = k(this); if (typeof this._fcDrillDownLevel === "undefined") this._fcDrillDownLevel = 0; a = 0; for (b = arguments.length; a < b; a += 1) if (g = arguments[a], g instanceof Array) { c = 0; for (e = g.length; c < e; c += 1) l(h, g[c], this._fcDrillDownLevel), this._fcDrillDownLevel += 1 } else l(h, g, this._fcDrillDownLevel), this._fcDrillDownLevel += 1; return this }; b.extend(b.expr[":"], { CnbiSoft : function(a) { return a.CnbiSoft instanceof j.core } }) } })();
import React from "react"; import { connect } from "react-redux"; import { Link } from "react-router-dom"; import { logout } from "../../../core/actions/auth.js"; function Nav({ logout, isAuthenticated }) { return ( <nav className="navbar navbar-expand-sm navbar-dark bg-dark" style={{ justifyContent: "center" }} > {/* <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample08" aria-controls="navbarsExample08" aria-expanded="false" aria-label="Toggle navigation" > <span className="navbar-toggler-icon"></span> </button> */} <div style={{ justifyContent: "center" }} className=" navbar-expand justify-content-md-center" id="navbarsExample08" > <ul className="navbar-nav"> <li className="nav-item active"> <a className="nav-link" href="/"> Social Platform </a> </li> {isAuthenticated ? ( <React.Fragment> <li className="nav-item ml-auto"> <Link to="/profile" className="nav-link"> Profile </Link> </li> <li className="nav-item ml-auto"> <div onClick={(e) => { e.preventDefault(); logout(); }} className="nav-link" style={{ cursor: "pointer" }} > Logout </div> </li> </React.Fragment> ) : ( <React.Fragment> <li className="nav-item"> <Link to="/login" className="nav-link"> Login </Link> </li> <li className="nav-item"> <Link to="/register" className="nav-link"> Register </Link> </li> </React.Fragment> )} </ul> </div> </nav> ); } const mapStateToProps = (state) => ({ isAuthenticated: state?.authReducer?.isAuthenticated, }); export default connect(mapStateToProps, { logout })(Nav);
app.factory('getResults', ['$http', function ($http) { return $http.get('app.json') .success(function (data) { return data; }) .error(function (err) { return err; }); }]); app.factory('applyFilters', ['getResults', function (getResults) { var results = { homes: [], minPrice: 0, maxPrice: 10000000000, bathrooms: 0, bedrooms: 0, squareFeet: 0, type: 0, rating: 0, roomType: 0, searchWords: "", searchedCity: { key: "No results found" }, currentHome: { currentHome: {} } }; return { change: function (key, val) { switch (key) { case "Min Price": if (val !== "Min Price") { results.minPrice = parseFloat(val); } else { results.minPrice = 0; } break; case "Max Price": if (val !== "Max Price") { results.maxPrice = parseFloat(val); } else { results.maxPrice = 10000000000; } break; case "Bathrooms": if (val !== "Bathrooms") { results.bathrooms = parseFloat(val); } else { results.bathrooms = 0; } break; case "Bedrooms": if (val !== "Bedrooms") { results.bedrooms = parseFloat(val); } else { results.bedrooms = 0; } break; case "Square feet": if (val !== "Square feet") { results.squareFeet = parseFloat(val); } else { results.squareFeet = 0; } break; case "Home type": if (val !== "Home type") { results.type = val; } else { results.type = 0; } break; case "Star rating": if (val !== "Star rating") { results.rating = parseFloat(val); } else { results.rating = 0; } break; case "Room type": if (val !== "Room type") { results.roomType = val; } else { results.roomType = 0; } break; default: alert("idk"); } }, initResults2: function (homes) { results.homes = []; for (var i = 0; i < homes.length; i++) { (function () { if (i === 0) { var cityLat = 0; var cityLong = 0; for (var a = 0; a < homes.length; a++) { cityLat += parseInt(homes[a].lat); cityLong += parseInt(homes[a].long); } cityLat = cityLat / a; cityLong = cityLong / a; map = new google.maps.Map(document.getElementById('map'), { center: { lat: cityLat, lng: cityLong }, zoom: 7 }); } var marker = []; var infowindow = []; var dataBeds = parseFloat(homes[i].beds); var dataBaths = parseFloat(homes[i].baths); var dataPrice = parseFloat(homes[i].price); var dataSqft = parseFloat(homes[i].sqft); var lat = homes[i].lat; var long = homes[i].long; var address = homes[i].address; var myLatLng = { lat: parseInt(homes[i].lat), lng: parseInt(homes[i].long) }; var dataHomeType = homes[i].type; var dataRating = parseFloat(homes[i].rating); var dataRoomType = homes[i].roomType; if ((dataBaths >= results.bathrooms) && (dataBeds >= results.bedrooms) && (results.minPrice <= dataPrice) && (dataPrice <= results.maxPrice) && (dataSqft >= results.squareFeet) && (results.type == 0 || dataHomeType == results.type) && (results.roomType == 0 || dataRoomType == results.roomType) && (results.rating <= dataRating)) { marker[i] = new google.maps.Marker({ position: myLatLng, map: map, title: homes[i].address }); results.homes.push(homes[i]); infowindow[i] = new google.maps.InfoWindow({ content: '<div class=" info-window container-fluid">' + '<div class="row">' + '<div class="col-xs-6">' + '<img src="' + homes[i].picture + '"/>' + '</div>' + '<div class="col-xs-6">' + '<p>' + '<span>' + '$' + homes[i].price + '</span>' + '<br />' + homes[i].beds + ' bd, ' + homes[i].baths + ' ba' + '<br />' + homes[i].sqft + ' sqft' + '</p>' + '</div >' + '</div>' + '</div>', maxWidth: 150, position: myLatLng }); var thisHome = homes[i]; var newWindow = infowindow[i]; marker[i].addListener('mouseover', function () { newWindow.open(map, this); }); marker[i].addListener('mouseout', function () { newWindow.close(); }); marker[i].addListener('click', function () { $("#resultsModal").modal("show"); results.currentHome = { currentHome: thisHome }; }); } }()); } }, fixResults: function () { return results; }, results: results, search: function () { results.searchWords = $("#search-bar").val(); }, searchedCity: function (x) { results.searchedCity = x; }, resetFilters: function () { results.minPrice = 0; results.maxPrice = 10000000000; results.bathrooms = 0; results.bedrooms = 0; results.squareFeet = 0; results.type = 0; results.rating = 0; results.roomType = 0; } } }]); app.factory('liveSearch', ['getResults', function (getResults) { var thisCity = { city: [] }; return { suggestions: function (page) { var searchBar = thisCity.city[0].key; var regex = new RegExp("^" + searchBar, "i"); getResults.success(function (data) { thisCity.city = []; angular.forEach(data[page], function (val, key) { if (key.search(regex) != -1) { thisCity.city.push({ key: key, val: val }); } }); }); }, suggestions2: function (page) { var searchBar = $("#search-bar").val(); var regex = new RegExp("^" + searchBar, "i"); getResults.success(function (data) { thisCity.city = []; angular.forEach(data[page], function (val, key) { if (key.search(regex) != -1) { thisCity.city.push({ key: key, val: val }); } }); }); }, thisCity: thisCity } }]);
import React from 'react' import LayoutComponent from '../../components/LayoutComponent' import DashboardComponent from '../../components/DashboardComponent' import './index.scss'; export default class Dashboard extends React.PureComponent { render() { return ( <LayoutComponent> <DashboardComponent /> </LayoutComponent> ) } }
'use strict'; import Base from '../base.js'; export default class extends Base { /** * index action * @return {Promise} [] */ async limitAction() { let page = this.get('page'); let size = this.get('size'); let _class = this.model('class'); let data = await _class.showClass({show:1},page,size); return this.success(data); } async indexAction() { let _class = this.model('class'); let data = await _class.showAllClass({show:1}); return this.success(data); } }
/* * Copyright ©️ 2020 GaltProject Society Construction and Terraforming Company * (Founded by [Nikolai Popeka](https://github.com/npopeka) * * Copyright ©️ 2020 Galt•Core Blockchain Company * (Founded by [Nikolai Popeka](https://github.com/npopeka) by * [Basic Agreement](ipfs/QmaCiXUmSrP16Gz8Jdzq6AJESY1EAANmmwha15uR3c1bsS)). */ const JsIpfsServiceNode = require('./JsIpfsServiceNode'); module.exports = function (node, pass) { class JsIpfsServiceNodePass extends JsIpfsServiceNode { constructor(node) { super(node); } getAccountPublicKey(accountKey) { return super.getAccountPublicKey(accountKey, pass); } getAccountPeerId(accountKey) { return super.getAccountPeerId(accountKey, pass); } keyLookup(accountKey) { return super.keyLookup(accountKey, pass); } } return new JsIpfsServiceNodePass(node); };
var searchData= [ ['ec_5fbad_5fgain_5flevel',['EC_BAD_GAIN_LEVEL',['../group___error_codes.html#ga152836fba63cffc721c652f2afd90166',1,'HMC5883L.h']]], ['ec_5finvalid_5fbias_5fmode',['EC_INVALID_BIAS_MODE',['../group___error_codes.html#ga8d614b9fb1abde4870f56e0d284e5c43',1,'HMC5883L.h']]], ['ec_5finvalid_5fmeasurement_5fmode',['EC_INVALID_MEASUREMENT_MODE',['../group___error_codes.html#gad42b93e29ae1feb1886cd6fed34f029d',1,'HMC5883L.h']]], ['ec_5finvalid_5fnavg',['EC_INVALID_NAVG',['../group___error_codes.html#ga42b9f7389394451cee6febb3dcd8b0a6',1,'HMC5883L.h']]], ['ec_5finvalid_5foutrate',['EC_INVALID_OUTRATE',['../group___error_codes.html#gaf34062d8ff8ae1fa0a057c01dceba5b5',1,'HMC5883L.h']]], ['ec_5finvalid_5fufloat',['EC_INVALID_UFLOAT',['../group___error_codes.html#ga419d094458d892d7439a052bf287932d',1,'HMC5883L.h']]], ['errors_20and_20warnings',['Errors and warnings',['../group___error_codes.html',1,'']]] ];
export const STATES=Object.freeze({ loading:'loading', unvalid:'unvalid', valid:'valid', none:'none' }); export const ErrorCodeMessage=Object.freeze({ none:'waiting for scan', linkUnvalid:'Qr code link is not Arianee link', notFromBrand:'Passport is not from this Brand', tooOld:'Proof is too old', unknown:'unknown' });
HRworksReceipt.settings = function (params) { var viewModel = { dellReceipts: function() { HRworksReceipt.localStoreReceipts.clear(); }, exampleReceipts: function() { for(var i= 0; i < 100; i++) { HRworksReceipt.localStoreReceipts.insert({ text : 'Receipt' + i, amount : 111, date : '20120304', receiptKind : '1', kindOfPayment : '1', currency : 'EUR', timestamp : Date() }); } }, serverSource : [{ name : "Produktiver Server" }, { name : "Testserver Demo" }, { name : "Testserver Area51" } ] }; return viewModel; };
import React, {Component} from 'react'; import Errors from './Errors/Errors'; import './InputRequired.css'; class InputRequired extends Component { state = { email: '', password: '', errors: {email: '', password: ''}, emailValid: true, passwordValid: true, formValid: true } userInputHandler = (event) => { const name = event.target.name; const value = event.target.value; this.setState({[name]: value}, () => { this.fieldValidateHandler(name, value) }); } fieldValidateHandler = (fieldName, value) => { let fieldValidationErrors = this.state.errors; let emailValid = this.state.emailValid; let passwordValid = this.state.passwordValid; switch(fieldName) { case 'email': emailValid = value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i); if (value.length === 0) emailValid=1; fieldValidationErrors.email = emailValid ? '' : ' Invalid email address'; break; case 'password': passwordValid = value.length >= 2; if (value.length === 0) passwordValid=1; fieldValidationErrors.password = passwordValid ? '': ' Invalid password'; break; default: break; } this.setState({ errors: fieldValidationErrors, emailValid: emailValid, passwordValid: passwordValid}, this.validateForm); } validateForm() { this.setState({formValid: this.state.emailValid && this.state.passwordValid}); } errorClass(error) { return(error.length === 0 ? '' : 'has-error'); } render() { const emailIsValid = this.state.emailValid; const passwordIsValid = this.state.passwordValid; let emailInputClass = emailIsValid ? "requirement emailInputPositive" : "requirement emailInputNegative"; let passwordInputClass = passwordIsValid ? "requirement passwordInputPositive" : "requirement passwordInputNegative"; let emailLabelClass = emailIsValid ? "inputLabel emailLabelPositive" : "inputLabel emailLabelNegative"; let passwordLabelClass = passwordIsValid ? "inputLabel passwordLabelPositive" : "inputLabel passwordLabelNegative"; return( <div> <div className='formDefault'> <Errors errors={this.state.errors}/> </div> <div className={`email form-group ${this.errorClass(this.state.errors.email)}`}> <label className={emailLabelClass}>EMAIL ADDRESS</label> <div className={emailInputClass}> <input type='email' required className='form-control' name='email' placeholder='Enter your email address' value={this.state.email} onChange={this.userInputHandler}/> <div className='tooltip'> <p>*</p> <span className='tooltipContent'>required</span> </div> </div> </div> <div className={`form-group ${this.errorClass(this.state.errors.password)}`}> <label className={passwordLabelClass}>PASSWORD</label> <div className={passwordInputClass}> <input type='password' className='form-control' name='password' placeholder='Enter your password' value={this.state.password} onChange={this.userInputHandler}/> <div className='tooltip'> <p>*</p> <span className='tooltipContent'>required</span> </div> </div> </div> </div> ) } } export default InputRequired;
import styled from "styled-components"; import Icon from "react-icons-kit"; import { mail, lock, info } from "react-icons-kit/feather"; import firebase from "./../config/firebase"; import { getUser, updateUser } from './../config/localstorage' import Router from 'next/router' class Login extends React.Component { constructor() { super(); this.state = { email: "", password: "", error: false, logging: false }; this.FireLogin = this.FireLogin.bind(this); this.onInputChange = this.onInputChange.bind(this); } componentDidMount() { const { user } = getUser(); if (user.uid !== '') { Router.push('/home') } } FireLogin = e => { e.preventDefault(); this.setState({ logging: true }) firebase .login(this.state.email, this.state.password) .then(( user ) => { localStorage.setItem("uid", user.uid); localStorage.setItem("onboard", false); localStorage.setItem('theme','tomorrow_night') this.setState({ error: false }); Router.push('/') }) .catch(e => { this.setState({ error: e.message }); this.setState({ logging: false }) }); }; onInputChange(e) { const { target } = e; const { name, value } = target; this.setState({ [name]: value }); } render() { // this.state.logging ? <div>loading</div> : return( <Wrapper> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" > <path fillRule="evenodd" clipRule="evenodd" d="M-9.61651e-07 2L0.000116366 1.97811L5 7.20876L5 19L16.271 19L21.0505 24L2 24C0.89543 24 -3.91403e-08 23.1046 -8.74225e-08 22L-9.61651e-07 2ZM19 6.82127L19 17.5269L23.8933 22.6461C23.9625 22.4434 24 22.2261 24 22L24 2C24 1.94223 23.9975 1.88504 23.9928 1.82852L19 6.82127ZM16.5786 5L21.5786 -9.43232e-07L2.24633 -9.81903e-08L7.02574 5L16.5786 5Z" fill="currentColor" /> </svg> <p style={{ fontSize: 24 }}>Snipcode</p> <FormWrapper onSubmit={this.FireLogin}> <Tab>Login</Tab> <Input type="email" name="email" required placeholder="Email" onChange={this.onInputChange} value={this.state.email} error={this.state.error} /> <Input type="password" name="password" value={this.state.password} onChange={this.onInputChange} required placeholder="Password" error={this.state.error} /> <input type="submit" style={{ display: "inline-block", padding: 10, margin: 10, background: "#5d9e6b" }} /> </FormWrapper> {this.state.error ? ( <span style={{ color: "red", padding: 10 }}>{this.state.error}</span> ) : null} <span>Don’t have an account ? Sign up </span> <span style={{ position: "absolute", bottom: 0, fontSize: 12, padding: 5 }}> You accept our terms of service and privacy </span> </Wrapper> ); } } export default Login; const Wrapper = styled.div` display: flex; flex-direction: column; justify-content: center; align-items: center; width: 100%; height: 100%; background: ${props => props.theme.primary}; color: ${props => props.theme.color}; `; const FormWrapper = styled.form` display: flex; flex-direction: column; width: 345px; margin: 0 auto; `; const Tab = styled.span` font-size: 16px; padding: 10px 0px; &:after { content: ""; position: relative; display: block; border-radius: 25px; left: 20px; top: 5px; height: 5px; width: 5px; background:#5d9e6b; } `; const InputWrapper = styled.div` display: flex; background:${props=>props.theme.secondary}; margin: 10px; border-radius: 5px; max-width: 400px; `; const IconWrapper = styled.span` padding: 10px; `; const InputWidget = styled.input` border: none; padding: 0px 10px; outline: none; background: transparent; color: inherit; flex: 1; &::placeholder { color: #aaa; } `; const Input = props => ( <InputWrapper> <IconWrapper> <Icon icon={props.name === "email" ? mail : lock} /> </IconWrapper> <InputWidget {...props} /> <IconWrapper> {props.error ? <Icon icon={info} style={{ color: "red" }} /> : null} </IconWrapper> </InputWrapper> );
import React from 'react'; import { upVoteTrack, downVoteTrack } from '../actions'; import { connect } from 'react-redux'; import { FaArrowCircleDown, FaArrowCircleUp } from 'react-icons/lib/fa'; import style from '../style.css'; const styleDown = `${style.button_vote} ${style.button_down}`; class Track extends React.Component { constructor() { super(); this.upVote = this.upVote.bind(this); this.downVote = this.downVote.bind(this); } upVote() { const { trackIndex, dispatchUpVote } = this.props; dispatchUpVote(trackIndex); } downVote() { const { trackIndex, dispatchDownVote } = this.props; dispatchDownVote(trackIndex); } render() { const { title, artist, cover, isPlaying } = this.props; const trackStatus = isPlaying ? { opacity: 1 } : { opacity: 0.3 }; return ( <li > <img src={cover} role="presentation" style={trackStatus} /> <span className={style.title}>{title}</span> <span className={style.artist}>{artist}</span> <FaArrowCircleUp onClick={this.upVote} className={style.button_vote} /> <FaArrowCircleDown onClick={this.downVote} className={styleDown} /> </li> ); } } Track.propTypes = { isPlaying: React.PropTypes.bool, cover: React.PropTypes.string, artist: React.PropTypes.string, title: React.PropTypes.string, handleClick: React.PropTypes.func, key: React.PropTypes.number, trackIndex: React.PropTypes.number, dispatchDownVote: React.PropTypes.func, dispatchUpVote: React.PropTypes.func, }; const mapDispatchToProps = dispatch => ({ dispatchUpVote: trackIndex => dispatch(upVoteTrack(trackIndex)), dispatchDownVote: trackIndex => dispatch(downVoteTrack(trackIndex)), }); export default connect( null, mapDispatchToProps )(Track);
import * as React from 'react'; import {View, TouchableOpacity, Image, StatusBar} from 'react-native'; import {colors, fontName, fontScale, images, routeName} from '../utils'; import {TextComponent} from './TextComponent'; export const Header = ({navigation, ...props}) => { console.log('pprops', props); return ( <View {...props} style={{ flexDirection: 'row', backgroundColor: colors.primary, width: '100%', justifyContent: 'center', paddingTop: StatusBar.currentHeight, }}> <View style={{ flexDirection: 'row', width: '100%', height: 80, justifyContent: 'center', alignItems: 'flex-end', paddingBottom: '4%', }}> { <TouchableOpacity onPress={() => { props.address ? navigation.navigate(routeName.LOGIN) : props.noClick == true ? console.log('HELP') : navigation.goBack(); }} style={{ alignItems: 'center', justifyContent: 'center', left: 0, bottom: '7%', position: 'absolute', height: 40, width: 40, }}> <Image style={{ height: 17, width: 10, }} source={images.backIcon} /> </TouchableOpacity> } <TextComponent style={[ { color: colors.secondary, fontSize: fontScale(20), fontFamily: fontName.PRIMARY_BOLD, }, ]}> {props.name} </TextComponent> </View> </View> ); };
if(typeof window === "undefined" || window.noConfig !== true) { courier.config({ paths: { "courier/*" : "../*.js", "@traceur": "../bower_components/traceur/traceur.js", "less": "../less-1.7.0.js", "pathed/pathed": "basics/pathed.js" }, map: { "mapd/mapd": "map/mapped" } }); } else { throw "fake loading error"; }
import React, { useState } from "react"; import styled from "styled-components"; import Infos from "../../../components/molecules/Infos"; const ConcordeContainer = styled.div` height: 100vh; perspective: 50vw; perspective-origin: 30vw 50vh; img{ filter: grayscale(1); margin: 20vh; height: 60vh; transform: rotateX(20deg); transition: all 1s ease-in-out, filter 0.3s ease-in-out; border-radius: 5px; } .animate{ filter: grayscale(0); margin: 20px; height: calc(100vh - 102px); transform: rotateX(0deg); } `; const Concorde = () => { const [ hovered, setHovered ] = useState(0) const isHovered = function(bool) { setHovered(bool) } return ( <ConcordeContainer> <Infos setIsAnimated={isHovered} title="Le Concorde" content="Lorem ipsum dolor" top="50" left="30" leftCard="250" bottomCard="200" /> <img className={hovered ? "animate" : null} src="../assets/img/chap_2/part_2/concorde.png" alt=""/> </ConcordeContainer> ); }; export default Concorde;
import React, { useState, useEffect} from 'react'; import axios from 'axios'; // MYCOMPONENTS import ProductList from './ProductList.js'; import FilterFurniture from './FilterFurniture.js'; import FilterDelivery from './FilterDelivery.js'; // MYFUNCTIONS import querySearch from '../functions/querySearch.js'; import queryFilterStyle from '../functions/queryFilterStyle.js'; import queryFilterDelivery from '../functions/queryFilterDelivery.js'; function Content() { const [data, setData] = useState({}); const [furnitures, setFurnitures] = useState({}); const [products, setProducts] = useState({}); const [search, setSearch] = useState(''); const [filterStyle, setFilterStyle] = useState([]); const [filterDelivery, setFilterDelivery] = useState([]); const delivery = [ { value: "1", label: "1 week" }, { value: "2", label: "2 weeks" }, { value: "3", label: "1 month" }, { value: "4", label: "more" }, ]; // GET API DATA KETIKA RENDER PERTAMA useEffect(() => { async function getData() { const result = await axios("https://www.mocky.io/v2/5c9105cb330000112b649af8"); setData(result.data); // FOR MASTER DATA setFurnitures(result.data.furniture_styles); // FOR SEARCH & FILTER DATA setProducts(result.data.products); // FOR SEARCH & FILTER DATA } getData(); }, []) // HANDLER SEARCH INPUT & FILTER FURNITURE STYLE & FILTER DELIVERY useEffect(() => { if (Object.keys(data).length > 0) { // FILTER STEP 1 => BY SEARCH const dataSearch = querySearch(data.products, search); // FILTER STEP 2 => BY FURNITURE STYLE const dataFilterFurniture = queryFilterStyle(dataSearch, filterStyle); // FILTER STEP 3 => BY DELIVERY TIME const dataFilterDelivery = queryFilterDelivery(dataFilterFurniture, filterDelivery); setProducts(dataFilterDelivery); } }, [search, filterStyle, filterDelivery]) return ( <> <header> <form> <div className="row"> <div className="col50"> <div className="filter"> <input className="search" type="text" placeholder="Search Furniture" value={search} onChange={event => setSearch(event.target.value.toLowerCase())} /> </div> </div> </div> <div className="row"> <div className="col50"> <div className="filter"> <FilterFurniture options={furnitures} value={filterStyle} onChangeCallback={response => setFilterStyle(response)} /> </div> </div> <div className="col50"> <div className="filter"> <FilterDelivery options={delivery} value={filterDelivery} onChangeCallback={response => setFilterDelivery(response)} /> </div> </div> </div> </form> </header> <div className="content"> <ProductList data={products} /> </div> </> ) } export default Content;
window.onload = function() { // only first doughnut chart initiation code is commented, as the code is the same for each one (apart from chart variable names) // retrieve data $.get("/totals/daily.csv", function(fileContent) { // define chart window.global_daily_total = Morris.Donut(getTotalsOptions(fileContent, 'global_daily_total')); // define variable for currently selected segment (a number) window.global_daily_total_currentSegment = { value: 0 }; // select iteam that will automatically be selected when chart is refreshed, if no other segments have been // hovered over yet, to avoid unexpected segment selection alteration when chart refreshes for first time window.global_daily_total.select(0); }); $.get("/totals/weekly.csv", function(fileContent) { window.global_weekly_total = Morris.Donut(getTotalsOptions(fileContent, 'global_weekly_total')); window.global_weekly_total_currentSegment = { value: 0 }; window.global_weekly_total.select(0); }); $.get("/totals/monthly.csv", function(fileContent) { window.global_monthly_total = Morris.Donut(getTotalsOptions(fileContent, 'global_monthly_total')); window.global_monthly_total_currentSegment = { value: 0 }; window.global_monthly_total.select(0); }); // only first line chart initiation code is commented, as the code is the same for each one (apart from chart variable names) // retrieve data $.get("/rates/daily/global.csv", function(fileContent) { // define chart window.global_daily_rate = Morris.Line(getRatesOptions(fileContent, 'global_daily_rate')); }); $.get("/rates/weekly/global.csv", function(fileContent) { window.global_weekly_rate = Morris.Line(getRatesOptions(fileContent, 'global_weekly_rate')); }); $.get("/rates/monthly/global.csv", function(fileContent) { window.global_monthly_rate = Morris.Line(getRatesOptions(fileContent, 'global_monthly_rate')); }); function forceTotalsUpdates() { updateTotals(window.global_daily_total, window.global_daily_total_currentSegment, "/totals/daily.csv", true); updateTotals(window.global_weekly_total, window.global_weekly_total_currentSegment, "/totals/weekly.csv", true); updateTotals(window.global_monthly_total, window.global_monthly_total_currentSegment, "/totals/monthly.csv", true); } // add the data to the charts, and update them to make sure they're the correct size run = true while (run) { try { forceTotalsUpdates(); run = false; } finally { setTimeout(function () { $(".chart svg").height($(".chart svg").width()); forceTotalsUpdates(); }, 500); } } // auto-update charts when data changes setInterval(function() { updateTotals(window.global_daily_total, window.global_daily_total_currentSegment, "/totals/daily.csv", false); updateTotals(window.global_weekly_total, window.global_weekly_total_currentSegment, "/totals/weekly.csv", false); updateTotals(window.global_monthly_total, window.global_monthly_total_currentSegment, "/totals/monthly.csv", false); updateRates(window.global_daily_rate, "/rates/daily/global.csv", false); updateRates(window.global_weekly_rate, "/rates/weekly/global.csv", false); updateRates(window.global_monthly_rate, "/rates/monthly/global.csv", false); $(".chart svg").height($(".chart svg").width()); }, 1000); // auto-update charts when screen resolution changes window.addEventListener("resize", function () { forceTotalsUpdates(); updateRates(window.global_daily_rate, "/rates/daily/global.csv", true); updateRates(window.global_weekly_rate, "/rates/weekly/global.csv", true); updateRates(window.global_monthly_rate, "/rates/monthly/global.csv", true); $(".chart svg").height($(".chart svg").width()); }); window.addEventListener("orientationchange", function () { forceTotalsUpdates(); updateRates(window.global_daily_rate, "/rates/daily/global.csv", true); updateRates(window.global_weekly_rate, "/rates/weekly/global.csv", true); updateRates(window.global_monthly_rate, "/rates/monthly/global.csv", true); $(".chart svg").height($(".chart svg").width()); }); }
import React, { useEffect, useRef, useState } from 'react'; import styled from 'styled-components'; import gsap from 'gsap'; import { connect } from 'react-redux'; import CloseButton from '../../atoms/CloseButton/CloseButton'; import { ReactComponent as ErrorIcon } from '../../../assets/icons/error.svg'; import { ReactComponent as SuccessIcon } from '../../../assets/icons/success.svg'; import { setInformationObject } from '../../../actions/toggleActions'; const StyledWrapper = styled.div` position: fixed; bottom: 1rem; right: 1rem; z-index: 1000; height: 80px; width: 400px; display: flex; justify-content: space-between; align-items: center; background-color: ${({ theme }) => theme.color.roomsPanel}; color: #fff; padding: 0 2rem; `; const StyledParagraph = styled.p` letter-spacing: 1px; font-size: 15px; position: absolute; top: 50%; left: 74px; transform: translateY(-50%); `; const StyledErrorIcon = styled(ErrorIcon)` width: 40px; height: 40px; `; const StyledSuccessIcon = styled(SuccessIcon)` width: 40px; height: 40px; `; //* informationObject -> {type: enum['error', 'success'], message: String} const InformationBox = ({ informationObject, setInformationObject }) => { const wrapperRef = useRef(null); const [shouldBoxOpen, setBoxOpen] = useState(false); const [isSuccess, setSuccess] = useState(true); const [tl] = useState(gsap.timeline({ defaults: { ease: 'power3.inOut' } })); useEffect(() => { if (informationObject) { setBoxOpen(true); informationObject.type === 'success' ? setSuccess(true) : setSuccess(false); setTimeout(() => { setBoxOpen(false); setInformationObject(null); }, 3000); } }, [informationObject]); useEffect(() => { const wrapperBox = wrapperRef.current; tl.fromTo(wrapperBox, { autoAlpha: 0, y: '+=30' }, { autoAlpha: 1, y: '0', duration: 0.5 }); }, []); useEffect(() => { shouldBoxOpen ? tl.play() : tl.reverse(); }, [shouldBoxOpen]); return ( <StyledWrapper ref={wrapperRef}> <CloseButton setBoxState={setBoxOpen} isSmall={true} theme={'dark'} /> {isSuccess ? <StyledSuccessIcon /> : <StyledErrorIcon />} <StyledParagraph>{informationObject && informationObject.message}</StyledParagraph> </StyledWrapper> ); }; const mapStateToProps = ({ toggleReducer: { informationObject } }) => { return { informationObject }; }; const mapDispatchToProps = dispatch => { return { setInformationObject: informationObject => dispatch(setInformationObject(informationObject)) }; }; export default connect(mapStateToProps, mapDispatchToProps)(InformationBox);
import React, { Component } from 'react'; import { Table, Modal } from 'antd'; import ScreenList from './screenList'; import { emptyTableLocale } from '../common/constants'; import { sortFilterByProps, getCustomerName } from '../common/utils'; import { fromNow } from '../common/momentUtils'; export default class CustomerTable extends Component { handleScreenList = (e, record) => { e.preventDefault(); Modal.info({ title: getCustomerName(record.cid) + ' screen list', width: '600px', content: <ScreenList uuid={ record.uuid }/>, maskClosable: true, onOk() { } }); }; render() { let { dataSource, pagination, loading, onChange, sorter } = this.props; let screenListRender = (uuid, record) => { return (<a onClick={ (e) => this.handleScreenList(e, record) }> <img className="user-avatar" src={ require('../../../static/images/chat_selected.png') } alt="chat list" title="chat list"/> </a>); }; const columns = [ { title: 'customer', dataIndex: 'cid', key: 'cid', render: getCustomerName, sorter: true, sortOrder: sorter.columnKey === 'cid' && sorter.order }, { title: 'screen list', dataIndex: 'uuid', key: 'uuid', render: screenListRender }, { title: 'first screen', dataIndex: 'firstTime', key: 'firstTime', sorter: (a, b) => sortFilterByProps(a, b, 'firstTime'), sortOrder: sorter.columnKey === 'firstTime' && sorter.order, render: fromNow }, { title: 'last screen', dataIndex: 'lastTime', key: 'lastTime', sorter: (a, b) => sortFilterByProps(a, b, 'lastTime'), sortOrder: sorter.columnKey === 'lastTime' && sorter.order, render: fromNow }, { title: 'country', dataIndex: 'country', key: 'country', sorter: true, sortOrder: sorter.columnKey === 'country' && sorter.order } ]; return ( <Table locale={ emptyTableLocale } columns={ columns } dataSource={ dataSource } pagination={ pagination } loading={ loading } onChange={ onChange }/> ); } }
import React from 'react'; export const Input = ({ ...props }) => { const { onChange, className, icon, errors, ...rest } = props; return ( <div className="field"> <div className="ui left icon input"> <i className={`${icon} icon`} /> <input {...rest} className={className} onChange={onChange} required /> </div> {errors && ( <div className="ui pointing red basic label"> {errors} </div> ) } </div> ); }; export default Input;
function all_read(obj){ var c = document.getElementsByClassName("col-md-1 glyphicon glyphicon-envelope"); for(var i = 0 ; i < c.length; i++){ if(c[i].style.color == "darkkhaki"){ $(c[i]).parent().siblings("input").prop("checked", true); //console.log($(c[i]).siblings("input")); //$(c[i]).siblings("input").get()[0].checked = true; //c[i].previousSibling.checked = true; }else{ $(c[i]).parent().siblings("input").prop("checked", false); } } } function all_noread(obj){ var c = document.getElementsByClassName("col-md-1 glyphicon glyphicon-envelope"); for(var i = 0 ; i < c.length; i++){ if(c[i].style.color == "darkkhaki"){ console.log($(c[i]).parent().siblings("input")); $(c[i]).parent().siblings("input").prop("checked", false); //console.log($(c[i]).siblings("input")); //$(c[i]).siblings("input").get()[0].checked = true; //c[i].previousSibling.checked = true; }else{ console.log($(c[i]).parent().siblings("input")); $(c[i]).parent().siblings("input").prop("checked", true); } } } function all_no(obj){ var c = document.getElementsByClassName("col-md-1"); for(var i = 0 ; i < c.length; i++){ c[i].checked = false; } } function all_check(obj){ var c = document.getElementsByClassName("col-md-1"); for(var i = 0 ; i < c.length; i++){ c[i].checked = true; } } function change_mail(obj){ $(obj).children().css("color","darkkhaki"); } var i = 1; function change_star(obj){ if(i == 0){ $(obj).css("color","black"); i = 1; }else{ $(obj).css("color","#FAD04D"); i = 0; } } function change_color(obj){ var s1 = $(obj).parent(); var s2 = $(obj).is(":checked"); if(s2 == true){ s1.css("background-color","#528BCB"); }else{ s1.css("background-color","white"); } }
import * as types from './constants'; const initialState = { wishListData: null, sharedWishListData: null, currentWishListData:null, loading: false, noteloading: false, current:{ wishlist_id: 0, shared: false } }; const WishListReducer = (state = initialState, action) => { //let result = []; switch (action.type) { case types.LOAD_MY_WISHLIST: return { ...state, error:null, loading: true }; case types.LOAD_MY_WISHLIST_SUCCESS: return { ...state, wishListData: action.result.data.data, current:{wishlist_id: action.result.data.data.wishlist_id, shared: false }, loading: false }; case types.LOAD_MY_WISHLIST_FAILURE: return { ...state, error: action.error.message, loading: false }; case types.LOAD_SHARED_WISHLIST: return { ...state, error:null, loading: true }; case types.LOAD_SHARED_WISHLIST_SUCCESS: return { ...state, sharedWishListData: action.result.data.data, current:{wishlist_id: action.result.data.data.wishlist_id, shared: true }, loading: false }; case types.LOAD_SHARED_WISHLIST_FAILURE: return { ...state, error: action.error.message, loading: false }; case types.LOAD_ADD_TO_WISHLIST: return { ...state, loading:true, apiStatus:null, error:null, }; case types.LOAD_ADD_TO_WISHLIST_SUCCESS: return { ...state, loading:false, apiStatus:true }; case types.LOAD_ADD_TO_WISHLIST_FAILURE: return { ...state, loading:false, apiStatus:false, error: action.error.message, }; case types.LOAD_REMOVE_FROM_WISHLIST: return { ...state, apiStatus:null, error:null, }; case types.LOAD_REMOVE_FROM_WISHLIST_SUCCESS: return { ...state, wishListData: handleRemoveFromWishList(action.payload, state.wishListData), apiStatus:true }; case types.LOAD_REMOVE_FROM_WISHLIST_FAILURE: return { ...state, apiStatus:false, wishListData: handleRemoveFromWishList(action.payload, state.wishListData), error: action.error.message, }; //notes case types.LOAD_NOTES: return { ...state, noteloading: true }; case types.LOAD_NOTES_SUCCESS: return { ...state, wishListData: !state.current.shared ? appendNotesToVendor(action.payload, state.wishListData, action.result.data.data.results) : state.wishListData, sharedWishListData: state.current.shared ? appendNotesToVendor(action.payload, state.sharedWishListData, action.result.data.data.results) : state.sharedWishListData, noteloading: false, error: null }; case types.LOAD_NOTES_FAILURE: return { ...state, error: action.error.message, noteloading: false }; case types.LOAD_ADD_COLLABORATOR: return { ...state, error:null }; case types.LOAD_ADD_COLLABORATOR_SUCCESS: return { ...state, wishListData: handleAddCollaborator(action.result.data.data, state.wishListData), }; case types.LOAD_ADD_COLLABORATOR_FAILURE: return { ...state, error: action.error.message, }; case types.LOAD_REMOVE_COLLABORATOR: return { ...state, error:null }; case types.LOAD_REMOVE_COLLABORATOR_SUCCESS: return { ...state, wishListData: handleRemoveCollaborator(action.payload, state.wishListData) }; case types.LOAD_REMOVE_COLLABORATOR_FAILURE: return { ...state, error: action.error.message }; case types.TOGGLE_SHARED_WISHLIST: return { ...state, current: {wishlist_id: action.payload.wishlist_id, shared: action.payload.shared} } default: return state; } }; //append notes to wishlistdata on loading notes for a vendor function appendNotesToVendor(details, wishListData, notes) { let wishListDataCopy = JSON.parse(JSON.stringify(wishListData)); wishListDataCopy.wishlistitems.slice().find( item => item.category_id == details.category_id ).vendors.find(item => item.vendor_id == details.vendor_id)['notes'] = notes; return wishListDataCopy; } //remove a vendor from wishlist function handleRemoveFromWishList(details, wishListData) { let wishListDataCopy = JSON.parse(JSON.stringify(wishListData)); wishListDataCopy.wishlistitems.slice().find( item => item.category_id == details.category_id ).vendors = wishListDataCopy.wishlistitems.slice().find( item => item.category_id == details.category_id ).vendors.filter(item => item.vendor_id != details.vendor_id); return wishListDataCopy; } // remove a collaborator from wishlist function handleRemoveCollaborator(collaborator, wishListData) { let wishListDataCopy = JSON.parse(JSON.stringify(wishListData)); wishListDataCopy.collaborators = wishListDataCopy.collaborators.filter(user => user.collaborator_id !== collaborator); return wishListDataCopy; } // add a collaborator to wishlist function handleAddCollaborator(collaborator, wishListData) { if (!wishListData.collaborators) { wishListData.collaborators = []; } let wishListDataCopy = JSON.parse(JSON.stringify(wishListData)); wishListDataCopy.collaborators.push(collaborator); return wishListDataCopy; } export default WishListReducer;
function pad(v, l) { v = v || ''; while(v.length < l) v += ' '; return v; } module.exports = { pad: pad };
// Topics array for buttons var topics = ['vortex', 'spiral', 'illusion', 'spin', 'trippy', 'art', '3D', 'shiny', 'glow', 'neon', 'uv']; var newTopic = ''; var x = ''; function populate() { // Clear out buttonArea $('#buttonArea').empty(); // Loop through topics and create a button for each one for (var i = 0; i < topics.length; i++) { $('#buttonArea').append( "<button class='btn btn-default default-color-dark z-depth-2 topics animated zoomIn' data-topic='" + topics[i] + "'>" + topics[i] + '</button>' ); } } // When the search button is clicked... $('#submit').on('click', function(event) { // Prevent the default action of clicking the button event.preventDefault(); // Place the user input into a variable newTopic = $('input#search').val(); // Add the new topic to the topics array topics.push(newTopic); // Create a button for the new topic $('#buttonArea').append( "<button class='btn btn-default topics' data-topic='" + newTopic + "'>" + newTopic + '</button>' ); populate(); gifSearch(); }); function gifSearch() { // When a topic button is clicked $('.topics').on('click', function(event) { // Place the data attribute 'topic' into a variable x = $(this).data('topic'); // Use the 'x' variable to search for the given topic var queryURL = 'https://api.giphy.com/v1/gifs/search?q=' + x + '&api_key=dc6zaTOxFJmzC&limit=10'; // Make an AJAX request to the queryURLs $.ajax({ url: queryURL, method: 'GET' }).done(function(response) { // Clear out anything that is in the gifarea $('#gifarea').empty(); // For every item returned in the search... for (var i = 0; i < response.data.length; i++) { // Create variables with elements to contain the incoming response var gifDiv = $('<div>'); var p = $('<p>').text('Rating: ' + response.data[i].rating); // set resultgif to an <img> tag var resultgif = $('<img class="img-fluid img-thumbnail animated fadeIn">'); // give the <img> tag a 'src' attribute which is equal to the url resultgif.attr('src', response.data[i].images.fixed_height.url); // Append the resultgif and rating to the gifDiv gifDiv.append(resultgif); gifDiv.append(p); // Append the gifDiv to the gifArea $('#gifarea').append(gifDiv); } }); }); } populate(); gifSearch();
const path = require('path'); module.exports = { "stories": [ "../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)" ], "addons": [ '@storybook/addon-knobs', '@storybook/addon-actions', "@storybook/preset-create-react-app" ], webpackFinal: async config => { config.resolve.extensions.push('.ts', '.tsx'); config.resolve.alias['@'] = path.resolve(__dirname, '../src'); config.resolve.alias['@Icon'] = path.resolve(__dirname, '../src/icon'); config.resolve.alias['helpers'] = path.resolve(__dirname, '../src/helpers'); return config; }, }
/** * userActions * @params getState() 读取redux的store */ import * as actionTypes from "./actionTypes"; import * as requestApi from "../config/requestApi"; import * as nativeApi from "../config/nativeApi"; import NavigatorService from '../common/NavigatorService'; // 注册 export function fetchRegister(params = {}, callback = () => { }) { return (dispatch, getState) => { requestApi .requestRegister(params) .then(data => { requestApi.storageLogin("save", data); global.loginInfo = {...data, phone: params.phone, userId: data.id} dispatch({type: actionTypes.FETCH_REGISTER, data: global.loginInfo}); callback(); }) .catch(error => { // }); }; } // 登录 export function fetchLogin(params = {}, callback = () => { }, fail = () => { }) { return (dispatch, getState) => { requestApi .requestLogin(params) .then(data => { let loginInfo = { // 后端更改接口返回数据,去掉user字段 userId: data.id, params, ...data, phone: params.phone }; const nextFun=()=>{ requestApi.storagePhone("save", params); requestApi.storageLogin("save", data); global.loginInfo = loginInfo; dispatch({type: actionTypes.FETCH_LOGIN, data: {...data}}); callback(data); } nextFun() }) .catch(error => { console.log(error) fail(); }); }; } // 更新登录信息 export function updateUser(user = {}) { return (dispatch, getState) => { dispatch({ type: "user/updateUser", payload: { user }}) } } // 获取商户信息 export function getMerchantHome(successCallback=()=>{},failCallback=()=>{},user={}){ return (dispatch, getState) => { app._store.dispatch({ type: "user/getMerchantHome", payload: { successCallback, failCallback, user }}) } } // 选择登录店铺 export function chooseShop(data, callback = () => { }) { return (dispatch, getState) => { app._store.dispatch({ type: 'user/chooseShop', payload: data }) }; } //单纯修改一些状态 export function changeState(params) { return (dispatch, getState) => { dispatch({type: actionTypes.CHANGE_STATE, data: params}); }; } // 非商户身份获取权限 export function mUserPermission() { return (dispatch, getState) => { app._store.dispatch({ type: 'user/mUserPermission' }); }; }
import React from "react"; import { Col, Container, Image, Row } from "react-bootstrap"; import sign from "../../../images/Banners/sign-aboutus.webp"; import "./AboutUsInfo.css"; const AboutUsInfo = () => { return ( <Container fluid> <Row className="aboutus-info"> <Col xs="6" className="info-left"> <p className="sub-info-title">History Since 2010</p> <h2>Welcome To Michelie Shop Amazing Fashion.</h2> <span> Maecenas sed diam eget risus varius blandit sit amet non magna. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. </span> </Col> <Col xs="6" className="info-right"> <p className="info-right-desc info-right-desc1"> Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Cras mattis consectetur purus sit amet fermentum. Sed posuere consectetur est at lobortis. Nullam id dolor id nibh ultricies vehicula ut id elit. </p> <p className="info-right-desc info-right-desc2"> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium. </p> <div className="sign"> <Image src={sign} alt="Signature" /> </div> <p className="about-author text-uppercase"> <span>pr. Megan</span> -ceo Eurotas </p> </Col> </Row> </Container> ); }; export default AboutUsInfo;
module.exports = ` ############################################ ## Article ############################################ type ContentfulArticle implements Node & Article { title: String slug: String @makeSlug date: Date @dateformat featured: Boolean author: ArticleAuthor @link(from: "author___NODE") category: ArticleCategory @link(from: "category___NODE") tags: [ArticleTag] @link(by: "name") keywords: [String] link: String body: String @mdx(from: "body___NODE") excerpt(pruneLength: Int = 100): String @mdx(from: "body___NODE") timeToRead: Int @mdx(from: "body___NODE") thumbnailText: String thumbnail: ContentfulAsset @link(from: "heroImage___NODE") private: Boolean } ############################################ ## Category ############################################ type ContentfulCategory implements Node & ArticleCategory { name: String slug: String @makeSlug description: String color: String icon: ContentfulAsset @link(from: "icon___NODE") } ############################################ ## Author ############################################ type ContentfulAuthor implements Node & ArticleAuthor { name: String slug: String @makeSlug description: String title: String social: [SocialMedia] @normalizeSocial skills: [String] thumbnail: ContentfulAsset @link(from: "thumbnail___NODE") } `
import Modal from './Modal.component' import ModalController from './Modal.controller' export { Modal, ModalController }