<commit_before>/* @flow */
import React from 'react';
import { render } from 'react-dom';
import { addLocaleData } from 'react-intl';
import enLocaleData from 'react-intl/locale-data/en';
import deLocaleData from 'react-intl/locale-data/de';
import frLocaleData from 'react-intl/locale-data/fr';
import esLocaleData from 'react-intl/locale-data/es';

import configureStore from './state';
import { camelizeKeys } from './util/util';
import ComponentWrapper from './ComponentWrapper';
import FundraiserView from './containers/FundraiserView/FundraiserView';
import CallToolView   from './containers/CallToolView/CallToolView';

import type { Store } from 'redux';
import type { AppState } from './state/reducers';

import './components.css';

addLocaleData([
  ...enLocaleData,
  ...deLocaleData,
  ...frLocaleData,
  ...esLocaleData,
]);

const store: Store<AppState, *> = configureStore({});

window.mountFundraiser = (root: string, initialState?: any = {})  => {
  store.dispatch({ type: 'initialize_page', payload: window.champaign.page });
  store.dispatch({ type: 'parse_champaign_data', payload: initialState });

  render(
    <ComponentWrapper store={store} locale={initialState['locale']}>
      <FundraiserView />
    </ComponentWrapper>,
    document.getElementById(root)
  );

  if (process.env.NODE_ENV === 'development' && module.hot) {
    module.hot.accept('./containers/FundraiserView/FundraiserView', () => {
      const UpdatedFundraiserView = require('./containers/FundraiserView/FundraiserView').default;
      render(
        <ComponentWrapper store={store} locale={initialState['locale']}>
          <UpdatedFundraiserView />
        </ComponentWrapper>,
        document.getElementById(root)
      );
    });
  }
};

type callToolProps = {
  locale: string;
  title?: string;
  targets: any[];
  targetCountries: any[];
  countriesPhoneCodes: any[];
  pageId: string | number;
  targetByCountryEnabled: boolean;
};

window.mountCallTool = (root: string, props: callToolProps) => {
  props = camelizeKeys(props);

  render(
    <ComponentWrapper locale={props.locale}>
      <CallToolView
        title={props.title}
        targets={props.targets}
        countries={props.countries}
        pageId={props.pageId}
        onSuccess={props.onSuccess}
        countriesPhoneCodes={props.countriesPhoneCodes}
        countryCode={props.countryCode} />
        targetByCountryEnabled={props.targetByCountryEnabled}
    </ComponentWrapper>,
    document.getElementById(root)
  );
};
<commit_msg>Small style improvement to components.js<commit_after>/* @flow */
import React from 'react';
import { render } from 'react-dom';
import { addLocaleData } from 'react-intl';
import enLocaleData from 'react-intl/locale-data/en';
import deLocaleData from 'react-intl/locale-data/de';
import frLocaleData from 'react-intl/locale-data/fr';
import esLocaleData from 'react-intl/locale-data/es';

import configureStore from './state';
import { camelizeKeys } from './util/util';
import ComponentWrapper from './ComponentWrapper';
import FundraiserView from './containers/FundraiserView/FundraiserView';
import CallToolView   from './containers/CallToolView/CallToolView';

import type { Store } from 'redux';
import type { AppState } from './state/reducers';

import './components.css';

addLocaleData([
  ...enLocaleData,
  ...deLocaleData,
  ...frLocaleData,
  ...esLocaleData,
]);

const store: Store<AppState, *> = configureStore({});

window.mountFundraiser = (root: string, initialState?: any = {})  => {
  store.dispatch({ type: 'initialize_page', payload: window.champaign.page });
  store.dispatch({ type: 'parse_champaign_data', payload: initialState });

  render(
    <ComponentWrapper store={store} locale={initialState['locale']}>
      <FundraiserView />
    </ComponentWrapper>,
    document.getElementById(root)
  );

  if (process.env.NODE_ENV === 'development' && module.hot) {
    module.hot.accept('./containers/FundraiserView/FundraiserView', () => {
      const UpdatedFundraiserView = require('./containers/FundraiserView/FundraiserView').default;
      render(
        <ComponentWrapper store={store} locale={initialState['locale']}>
          <UpdatedFundraiserView />
        </ComponentWrapper>,
        document.getElementById(root)
      );
    });
  }
};

type callToolProps = {
  locale: string;
  title?: string;
  targets: any[];
  targetCountries: any[];
  countriesPhoneCodes: any[];
  pageId: string | number;
  targetByCountryEnabled: boolean;
};

window.mountCallTool = (root: string, props: callToolProps) => {
  props = camelizeKeys(props);

  render(
    <ComponentWrapper locale={props.locale}>
      <CallToolView {...props} />
    </ComponentWrapper>,
    document.getElementById(root)
  );
};
<|endoftext|>


<commit_before>import Vue from 'vue';
import Router from 'vue-router';
import Resource from 'vue-resource';

import accountIndex from '@/components/account/index.vue';
import login from '@/components/account/login.vue';
import regist from '@/components/account/regist.vue';
import forgetPwdFirstStep from '@/components/account/forgetpwd-firststep.vue';
import forgetPwdSecondStep from '@/components/account/forgetpwd-secondstep.vue';

import personal from '@/components/personal/index.vue';

import globalCouponIndex from '@/components/global-coupon/index.vue';
import globalCouponList from '@/components/global-coupon-list/index.vue';

Vue.use(Router);
Vue.use(Resource);

export default new Router({
	routes: [
		{
			path: '/',
			redirect: '/globalCouponIndex'
		},

		{
			path: '/globalCouponIndex',
			name: 'GlobalCouponIndex',
			component: globalCouponIndex
		},

		{
			path: '/globalCouponList',
			name: 'GlobalCouponList',
			component: globalCouponList
		},

		{
			path: '/accountIndex',
			name: 'AccountIndex',
			component: accountIndex,
			children: [
				{
					path: '/login',
					name: 'Login',
					component: login
				},
				{
					path: '/regist',
					name: 'Regist',
					component: regist
				}
			]
		},

		{
			path: '/forgetPwdFirstStep',
			name: 'ForgetPwdFirstStep',
			component: forgetPwdFirstStep
		 },
		 {
			path: '/forgetPwdSecondStep',
			name: 'ForgetPwdSecondStep',
			component: forgetPwdSecondStep
		 },

		{
			path: '/personal',
			name: 'Personal',
			component: personal
		}
	]
})
<commit_msg>组件按需懒加载<commit_after>import Vue from 'vue';
import Router from 'vue-router';
import Resource from 'vue-resource';

// 登录、注册、找回密码等
const accountIndex = () => import('@/components/account/index.vue');
const login = () => import('@/components/account/login.vue');
const regist = () => import('@/components/account/regist.vue');
const forgetPwdFirstStep = () => import('@/components/account/forgetpwd-firststep.vue');
const forgetPwdSecondStep = () => import('@/components/account/forgetpwd-secondstep.vue');

// 个人中心
const personal = () => import('@/components/personal/index.vue');

// 首页
const globalCouponIndex = () => import('@/components/global-coupon/index.vue');

//全球优惠券列表页
const globalCouponList = () => import('@/components/global-coupon-list/index.vue');

Vue.use(Router);
Vue.use(Resource);

export default new Router({
	routes: [
		{
			path: '/',
			redirect: '/globalCouponIndex'
		},

		{
			path: '/globalCouponIndex',
			name: 'GlobalCouponIndex',
			component: globalCouponIndex
		},

		{
			path: '/globalCouponList',
			name: 'GlobalCouponList',
			component: globalCouponList
		},

		{
			path: '/accountIndex',
			name: 'AccountIndex',
			component: accountIndex,
			children: [
				{
					path: '/login',
					name: 'Login',
					component: login
				},
				{
					path: '/regist',
					name: 'Regist',
					component: regist
				}
			]
		},

		{
			path: '/forgetPwdFirstStep',
			name: 'ForgetPwdFirstStep',
			component: forgetPwdFirstStep
		 },
		 {
			path: '/forgetPwdSecondStep',
			name: 'ForgetPwdSecondStep',
			component: forgetPwdSecondStep
		 },

		{
			path: '/personal',
			name: 'Personal',
			component: personal
		}
	]
})
<|endoftext|>


<commit_before>import Vue        from 'vue'
import Router     from 'vue-router'
import menuModule from '../store/modules/menu'

Vue.use(Router)

const router =  new Router({
  mode: 'history',
  routes: [
    ...generateRoutesFromMenu(menuModule.state.items)
  ]
})

function generateRoutesFromMenu (menu = [], routes = []) {
  for (let i = 0, l = menu.length; i < l; i++) {
    let item = menu[i]
    if (item.path) {
      routes.push(item)
    }
  }
  return routes
}

export default router
<commit_msg>Add news reader to router rules.<commit_after>import Vue        from 'vue'
import Router     from 'vue-router'
import menuModule from '../store/modules/menu'

Vue.use(Router)

const router =  new Router({
  mode: 'history',
  routes: [
    ...generateRoutesFromMenu(menuModule.state.items),
    {
      name: 'News',
      path: '/culture/news/:id',
      component: (resolve) => { require(['@/components/layout/Reader.vue'], resolve) }
    }
  ]
})

function generateRoutesFromMenu (menu = [], routes = []) {
  for (let i = 0, l = menu.length; i < l; i++) {
    let item = menu[i]
    if (item.path) {
      routes.push(item)
    }
  }
  return routes
}

export default router
<|endoftext|>


<commit_before>import Vue from "vue"
import Router from "vue-router"
import Profile from "@/components/profile/Profile"
import Body from "@/components/profile/body-sections/Body"
import Portfolio from "@/components/profile/body-sections/portfolio/Portfolio"
import Skills from "@/components/profile/body-sections/Skills"

Vue.use(Router)

export default new Router({
	routes: [
		{
			path: "/",
			component: Profile,
			children: [
				{
					path: "/",
					component: Body
				},
				{
					path: "/portfolio",
					component: Portfolio
				},
				{
					path: "/skills",
					component: Skills
				}
			]
		}
	]
})
<commit_msg>Adjusted router settings<commit_after>import Vue from "vue"
import Router from "vue-router"
import Profile from "@/components/profile/Profile"
import Body from "@/components/profile/body-sections/Body"
import Portfolio from "@/components/profile/body-sections/portfolio/Portfolio"
import Skills from "@/components/profile/body-sections/Skills"

Vue.use(Router)

export default new Router({
	mode: "history",
	routes: [
		{
			path: "/",
			component: Profile,
			children: [
				{
					path: "/",
					component: Body
				},
				{
					path: "/portfolio",
					component: Portfolio
				},
				{
					path: "/skills",
					component: Skills
				}
			]
		}
	]
})
<|endoftext|>


<commit_before>import {Route, IndexRoute} from 'react-router'
import React from 'react'
import App from './App'
import AppOld from './App_old'
import Home from './Home'
import Error from './Error'
import ContactUs from './ContactUs'
import legal from './Legal'
import OpenSource from './OpenSource'
import Ambassadors from './Ambassadors'
import HmqExplorer from './Hmq'
import Wiki from './Wiki'

// import Form from './Form'
// import Partners from './Partners'
// import Cases from './Cases'
// import About from './About'

const getRoutes = (store) => {
  return (
    <Route
      path="/"
      prepareData={App.prepareData}
    >
      <Route
        component={App}
      >
        <IndexRoute
          component={Home}
          prepareData={Home.prepareData}
        />
        {legal}
        {HmqExplorer(store)}
        <Route path="open-source"
               prepareData={OpenSource.prepareData}
               component={OpenSource}
        />
        <Route path="ambassadors"
               prepareData={Ambassadors.prepareData}
               component={Ambassadors}
        />
        <Route path="contact-us"
               component={ContactUs}
               prepareData={ContactUs.prepareData}

        />
        <Route
          path="/error/:err"
          prepareData={Error.prepareData}
          component={Error}
        />
      </Route>

      <Route
        component={AppOld}
      >
        {/*<Route path="use-cases"*/}
               {/*component={Cases}*/}
        {/*/>*/}

        {/*<Route path="partners"*/}
               {/*prepareData={Partners.prepareData}*/}
               {/*component={Partners}*/}
        {/*/>*/}
        {/*{Form}*/}
        {Wiki(store)}

        {/*<Route path="about"*/}
               {/*component={About}*/}
        {/*/>*/}

      </Route>

      <Route
        component={App}
      >
        <Route
          path="*"
          prepareData={Error.prepareData}
          component={Error}
        />
      </Route>

    </Route >
  )
}

export default getRoutes<commit_msg>[update] add redirect<commit_after>import {Route, IndexRoute, Redirect} from 'react-router'
import React from 'react'
import App from './App'
import AppOld from './App_old'
import Home from './Home'
import Error from './Error'
import ContactUs from './ContactUs'
import legal from './Legal'
import OpenSource from './OpenSource'
import Ambassadors from './Ambassadors'
import HmqExplorer from './Hmq'
import Wiki from './Wiki'

// import Form from './Form'
// import Partners from './Partners'
// import Cases from './Cases'
// import About from './About'

const getRoutes = (store) => {
  return (
    <Route
      path="/"
      prepareData={App.prepareData}
    >
      <Route
        component={App}
      >
        <IndexRoute
          component={Home}
          prepareData={Home.prepareData}
        />
        {legal}
        {HmqExplorer(store)}
        <Route path="open-source"
               prepareData={OpenSource.prepareData}
               component={OpenSource}
        />
        <Route path="ambassadors"
               prepareData={Ambassadors.prepareData}
               component={Ambassadors}
        />
        <Route path="contact-us"
               component={ContactUs}
               prepareData={ContactUs.prepareData}

        />
        <Route
          path="/error/:err"
          prepareData={Error.prepareData}
          component={Error}
        />

        <Redirect from='about' to='/' />

      </Route>

      <Route
        component={AppOld}
      >
        {/*<Route path="use-cases"*/}
               {/*component={Cases}*/}
        {/*/>*/}

        {/*<Route path="partners"*/}
               {/*prepareData={Partners.prepareData}*/}
               {/*component={Partners}*/}
        {/*/>*/}
        {/*{Form}*/}
        {Wiki(store)}

        {/*<Route path="about"*/}
               {/*component={About}*/}
        {/*/>*/}

      </Route>

      <Route
        component={App}
      >
        <Route
          path="*"
          prepareData={Error.prepareData}
          component={Error}
        />
      </Route>

    </Route >
  )
}

export default getRoutes<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
const fs = require('fs');
const ejs = require('ejs');
const pool = require('../config/db_pool');
// var aws = require('aws-sdk');
// aws.config.loadFromPath('./config/aws_config.json');

/* GET home page. */
// router.get('/', function(req, res, next) {
//     res.render('index');
// });

router.get('/', function(req, res, next) {
  fs.readFile('./views/index.ejs', 'utf-8', function(err, result) {
    if (err)
    console.log('reading ejs error : ', err);
    else
    res.status(200).send(ejs.render(result));
  });
});

router.post('/classConfirm', function(req, res) {

  function myRandom(max, min) {
    return Math.floor(Math.random()*(max-min)) + min;
  }
  var rand = myRandom(1000,9999);

  console.log('연결');
  req.session.className = req.body.className + rand;
  className=req.session.className;
  likeMinimum = req.body.likeMinimum;
  if (likeMinimum.length <= 0)
  likeMinimum = 0;

  console.log(className);
  console.log(likeMinimum);

  pool.getConnection(function(error, connection){
    console.log('들어왔어요');
    if (error)
    {
      console.log("getConnection Error" + error);
      res.sendStatus(503);
    }

    else {
      connection.query('select count(*) as exist from class where className = ?', [className], function(error, row)
      {
        if(error)
        {
          console.log("getConnection Error" + error);
          res.sendStatus(503);
        }
        else
        {
          if(row[0].exist != 0)
          {
            console.log('현존하는 강의가 존재합니다.');
            res.render('index');
          }

          else
          {
            connection.query('insert into class values(null,?,?,?)', [rand, className, likeMinimum], function(error, comments)
            {
              console.log(comments);
              if(error) console.log('selecting query err: ', error);
              else{
                res.render('className', {className : req.session.className});
                connection.release();
              }
            });
          }
        }
      });
    }
  });
});

router.get('/questionList/:className', function(req, res){
  pool.getConnection(function(error, connection){
    console.log('들어왔어요');
    if (error)
    {
      console.log("getConnection Error" + error);
      res.sendStatus(503);
      //connection.release();
    } else {
      connection.query('select id from class where className =?', req.session.className, function(error, row)
      {
        if(error) console.log("selecting Error" + error);
        else {
          console.log(row[0].id);
          req.session.classID = row[0].id;
          connection.query('select id, classID, userID, content, time, commentCnt, likeCnt from question where classID = ?', [row[0].id] , function(error, result) {
            if(error) console.log("selecting Error" + error);
            else
            {
              if(result.length == 0){
                console.log('텅텅 비었어요');
                res.render('realclass', {className : req.session.className, question : null});
              }
              else{
                console.log(result);
                res.render('realClass', {className : req.session.className, question : result});
              }
              connection.release();
            }
          });
        }

      });
    }
  });
});

router.get('/classDetail/:questionID', function(req, res){
  questionID = req.params.questionID;
  className = req.session.className;
  classId = req.session.classID;
  console.log(questionID);
  console.log(classId);
  pool.getConnection(function(error, connection){
    console.log('들어왔어요');
    if (error)
    {
      console.log("getConnection Error" + error);
      res.sendStatus(503);
      //connection.release();
    }

    else {
      connection.query('select * from question where question.id=?', [questionID], function(error, questionData)
      {
        if(error) console.log("selecting Error" + error);
        else {
          console.log('넘어갑니다.');

          connection.query('select * from comment where comment.questionID=?', [questionID], function(error, comments) {
            console.log(questionData);
            console.log(comments);
            res.render('classDetail', {className : req.session.className, questionInfo : questionData, commentsInfo : comments});
          })
        }
      });
    }
    connection.release();
  });
});

router.post('/end', function(req, res){
  req.session.destroy(function(err){
    if(err) console.error('err', err);
    res.redirect('/');
  });
});

/* restful api */
router.post('/api/join', function(req, res){
  console.log(req.body.id);
  console.log(req.body.pw);
  console.log(req.body.email);
  if (req.body.id == null || req.body.pw == null || req.body.email == null) {
    res.json({success:false});
  } else {
    pool.getConnection(function(error, connection){
      if (error)
      {
        console.log("getConnection Error" + error);
        res.sendStatus(503);
      } else {
        connection.query('insert into user values(null, ?, ?, ?)', [req.body.id, req.body.pw, req.body.email], function(err, result) {
          console.log(result);
          if (err != null) {
            console.log('selecting query err: ', err);
            res.json({success:false, message:"중복된 정보가 존재합니다."});
          } else {
            res.json({success:true});
          }
        });
      }
      connection.release();
    });
  }
});

router.post('/api/login', function(req,res){
  console.log(req.body.id);
  console.log(req.body.pw);
  if(req.body.id ==null || req.body.pw==null){
    res.json({sucess:false});
  } else {
    pool.getConnection(function(error, connection){
      if (error)
      {
        console.log("getConnection Error"+ error);
        res.sendStatus(503);
      } else {
        connection.query('select * from user where userID=?',[req.body.id], function(error, result){
          if (error != null) {
            res.json({success:false, message:"Internal Error"});
          } else {
            console.log(result);
            if (result.length <= 0) {
              res.json({success:false, message:"입력하신 ID가 없습니다."});
            } else {
              if (result[0].userPW == req.body.pw) {
                req.session.userID = result[0].id;
                req.session.userName = req.body.id;
                res.json({success:true, message :"로그인 성공", userID:result[0].id});
              } else {
                res.json({success:false, message:"비밀번호가 일치하지 않습니다."});
              }
            }
          }
          connection.release();
        });
      }
    });
  }
});

router.post('/api/logout',function(req, res){
  req.session.destroy(function(){
    req.session;
  });
  res.json({success:true});
});

router.get('/api/classList', function(req, res) {
  console.log('API: get classlist');
  pool.getConnection(function(error, connection) {
    if (error) {
      console.log('db connection failed: ' + error);
      res.sendStatus(503);
    } else {
      connection.query('select * from class', function(err, result) {
        console.log(result);
        if (err == null) {
          res.json({
            success:true,
            count:result.length,
            classinfos:result
          });
        } else {
          res.json({success:false});
        }
      });
      connection.release();
    }
  });
});

router.post('/api/makeQuestion', function(req, res) {
  console.log('API: post makeQuestion');
  console.log(req.body.classID);
  console.log(req.body.userID);
  console.log(req.body.content);
  pool.getConnection(function(error, connection) {
    if (error) {
      console.log('db connection failed: ' + error);
      res.sendStatus(503);
    } else {
      connection.query('insert into question (classID, userID, content) values (?, ?, ?)', [req.body.classID, req.body.userID, req.body.content], function(err, result) {
        console.log(result);
        if (err != null) {
          console.log('insert query err: ', err);
          res.json({success:false});
        } else {
          res.json({success:true});
        }
      });
      connection.release();
    }
  });
});

router.get('/api/questionList/:classID', function(req, res) {
  console.log('API: get questinoList');
  console.log(req.params.classID);
  pool.getConnection(function(error, connection) {
    if (error) {
      console.log('db connection failed: ' + error);
      res.sendStatus(503);
    } else {
      connection.query('select * from question where classID=?', [req.params.classID], function(err, result) {
        console.log(result);
        if (err == null) {
          res.json({
            success:true,
            count:result.length,
            questionInfos:result
          });
        } else {
          res.json({success:false});
        }
      });
      connection.release();
    }
  });
});

router.get('/api/questionDetail/:questionID', function(req, res) {
  console.log('API: get question detail');
  pool.getConnection(function(error, connection) {
    if (error) {
      console.log('db connection failed: ' + error);
      res.sendStatus(503);
    } else {
      connection.query('select * from question where id=?', [req.params.questionID], function(err, result) {
        if (err == null) {
          console.log(result);
          console.log(req.params.questionID);
          console.log(req.session.userID);
          connection.query('select * from heart where (questionID=? AND userID=?)', [req.params.questionID, req.session.userID], function(err2, result2) {
            if (err2 == null) {
              console.log(result2);
              res.json({
                success:true,
                info:result,
                didLike: (result2.length!=0)
              });
            } else {
              res.json({success:false, message:err2});
            }
          });
          connection.release();
        } else {
          res.json({success:false, message:err});
        }
      });
    }
  });
});

router.put('/api/addLike', function(req, res) {
  console.log('API: put addLike');
  console.log(req.body.questionID);
  console.log(req.body.userID);
  pool.getConnection(function(error, connection) {
    if(error){
      console.log('db connection failed: ' + error);
      res.sendStatus(503);
    } else {
      connection.query('insert into heart(questionID, userID) values(?,?)',[req.body.questionID, req.body.userID], function(error, result) {
        console.log(result);
        if(error !=null){
          console.log('insert query err: ', error);
          res.json({success:false});
        } else{
          res.json({success: true});
        }
      });
      connection.release();
    }
  });
});

router.delete('/api/removeLike', function(req, res){
  console.log('API : delete remove like');
  console.log(req.body.questionID);
  console.log(req.body.userID);
  pool.getConnection(function(error, connection) {
    if(error){
      console.log('db connection failed: ' + error);
      res.sendStatus(503);
    } else {
      connection.query('delete from heart where (questionID=? and userID=?)',[req.body.questionID, req.body.userID], function(error, result) {
        console.log(result);
        if(error !=null){
          console.log('insert query err: ', error);
          res.json({success:false});
        } else{
          res.json({success: true});
        }
      });
      connection.release();
    }
  });
});

router.post('/api/makeComment', function(req, res){
  console.log('API : post makeComment');
  console.log(req.body.questionID);
  console.log(req.body.userID);
  console.log(req.body.content);
  pool.getConnection(function(error, connection) {
    if(error){
      console.log('db connection failed: ' + error);
      res.sendStatus(503);
    } else {
      connection.query('insert into comment(questionID, userID, content) values(?,?,?)',[req.body.questionID, req.body.userID, req.body.content], function(error, result) {
        console.log(result);
        if(error !=null){
          console.log('insert query err: ', error);
          res.json({success:false});
        } else{
          res.json({success: true});
        }
      });
      connection.release();
    }
  });
});

router.get('/api/commentList/:questionID', function(req,res){
  console.log('API: get commentList');
  console.log(req.params.questionID);
  pool.getConnection(function(error, connection){
    if(error){
      console.log('db connection failed: '+error);
      res.sendStatus(503);
    } else {
      connection.query('select * from comment where questionID=?', [req.params.questionID], function(error, result){
        console.log(result);
        if(error == null){
          res.json({
            success : true,
            count : result.length,
            infos : result
          });
        } else {
          res.json({success:false});
        }
      });
      connection.release();
    }
  });
});

module.exports = router;
<commit_msg>Volley 결함에 대하여 서버 바이너리 대응<commit_after>var express = require('express');
var router = express.Router();
const fs = require('fs');
const ejs = require('ejs');
const pool = require('../config/db_pool');
// var aws = require('aws-sdk');
// aws.config.loadFromPath('./config/aws_config.json');

/* GET home page. */
// router.get('/', function(req, res, next) {
//     res.render('index');
// });

router.get('/', function(req, res, next) {
  fs.readFile('./views/index.ejs', 'utf-8', function(err, result) {
    if (err)
    console.log('reading ejs error : ', err);
    else
    res.status(200).send(ejs.render(result));
  });
});

router.post('/classConfirm', function(req, res) {

  function myRandom(max, min) {
    return Math.floor(Math.random()*(max-min)) + min;
  }
  var rand = myRandom(1000,9999);

  console.log('연결');
  req.session.className = req.body.className + rand;
  className=req.session.className;
  likeMinimum = req.body.likeMinimum;
  if (likeMinimum.length <= 0)
  likeMinimum = 0;

  console.log(className);
  console.log(likeMinimum);

  pool.getConnection(function(error, connection){
    console.log('들어왔어요');
    if (error)
    {
      console.log("getConnection Error" + error);
      res.sendStatus(503);
    }

    else {
      connection.query('select count(*) as exist from class where className = ?', [className], function(error, row)
      {
        if(error)
        {
          console.log("getConnection Error" + error);
          res.sendStatus(503);
        }
        else
        {
          if(row[0].exist != 0)
          {
            console.log('현존하는 강의가 존재합니다.');
            res.render('index');
          }

          else
          {
            connection.query('insert into class values(null,?,?,?)', [rand, className, likeMinimum], function(error, comments)
            {
              console.log(comments);
              if(error) console.log('selecting query err: ', error);
              else{
                res.render('className', {className : req.session.className});
                connection.release();
              }
            });
          }
        }
      });
    }
  });
});

router.get('/questionList/:className', function(req, res){
  pool.getConnection(function(error, connection){
    console.log('들어왔어요');
    if (error)
    {
      console.log("getConnection Error" + error);
      res.sendStatus(503);
      //connection.release();
    } else {
      connection.query('select id from class where className =?', req.session.className, function(error, row)
      {
        if(error) console.log("selecting Error" + error);
        else {
          console.log(row[0].id);
          req.session.classID = row[0].id;
          connection.query('select id, classID, userID, content, time, commentCnt, likeCnt from question where classID = ?', [row[0].id] , function(error, result) {
            if(error) console.log("selecting Error" + error);
            else
            {
              if(result.length == 0){
                console.log('텅텅 비었어요');
                res.render('realclass', {className : req.session.className, question : null});
              }
              else{
                console.log(result);
                res.render('realClass', {className : req.session.className, question : result});
              }
              connection.release();
            }
          });
        }

      });
    }
  });
});

router.get('/classDetail/:questionID', function(req, res){
  questionID = req.params.questionID;
  className = req.session.className;
  classId = req.session.classID;
  console.log(questionID);
  console.log(classId);
  pool.getConnection(function(error, connection){
    console.log('들어왔어요');
    if (error)
    {
      console.log("getConnection Error" + error);
      res.sendStatus(503);
      //connection.release();
    }

    else {
      connection.query('select * from question where question.id=?', [questionID], function(error, questionData)
      {
        if(error) console.log("selecting Error" + error);
        else {
          console.log('넘어갑니다.');

          connection.query('select * from comment where comment.questionID=?', [questionID], function(error, comments) {
            console.log(questionData);
            console.log(comments);
            res.render('classDetail', {className : req.session.className, questionInfo : questionData, commentsInfo : comments});
          })
        }
      });
    }
    connection.release();
  });
});

router.post('/end', function(req, res){
  req.session.destroy(function(err){
    if(err) console.error('err', err);
    res.redirect('/');
  });
});

/* restful api */
router.post('/api/join', function(req, res){
  console.log(req.body.id);
  console.log(req.body.pw);
  console.log(req.body.email);
  if (req.body.id == null || req.body.pw == null || req.body.email == null) {
    res.json({success:false});
  } else {
    pool.getConnection(function(error, connection){
      if (error)
      {
        console.log("getConnection Error" + error);
        res.sendStatus(503);
      } else {
        connection.query('insert into user values(null, ?, ?, ?)', [req.body.id, req.body.pw, req.body.email], function(err, result) {
          console.log(result);
          if (err != null) {
            console.log('selecting query err: ', err);
            res.json({success:false, message:"중복된 정보가 존재합니다."});
          } else {
            res.json({success:true});
          }
        });
      }
      connection.release();
    });
  }
});

router.post('/api/login', function(req,res){
  console.log(req.body.id);
  console.log(req.body.pw);
  if(req.body.id ==null || req.body.pw==null){
    res.json({sucess:false});
  } else {
    pool.getConnection(function(error, connection){
      if (error)
      {
        console.log("getConnection Error"+ error);
        res.sendStatus(503);
      } else {
        connection.query('select * from user where userID=?',[req.body.id], function(error, result){
          if (error != null) {
            res.json({success:false, message:"Internal Error"});
          } else {
            console.log(result);
            if (result.length <= 0) {
              res.json({success:false, message:"입력하신 ID가 없습니다."});
            } else {
              if (result[0].userPW == req.body.pw) {
                req.session.userID = result[0].id;
                req.session.userName = req.body.id;
                res.json({success:true, message :"로그인 성공", userID:result[0].id});
              } else {
                res.json({success:false, message:"비밀번호가 일치하지 않습니다."});
              }
            }
          }
          connection.release();
        });
      }
    });
  }
});

router.post('/api/logout',function(req, res){
  req.session.destroy(function(){
    req.session;
  });
  res.json({success:true});
});

router.get('/api/classList', function(req, res) {
  console.log('API: get classlist');
  pool.getConnection(function(error, connection) {
    if (error) {
      console.log('db connection failed: ' + error);
      res.sendStatus(503);
    } else {
      connection.query('select * from class', function(err, result) {
        console.log(result);
        if (err == null) {
          res.json({
            success:true,
            count:result.length,
            classinfos:result
          });
        } else {
          res.json({success:false});
        }
      });
      connection.release();
    }
  });
});

router.post('/api/makeQuestion', function(req, res) {
  console.log('API: post makeQuestion');
  console.log(req.body.classID);
  console.log(req.body.userID);
  console.log(req.body.content);
  pool.getConnection(function(error, connection) {
    if (error) {
      console.log('db connection failed: ' + error);
      res.sendStatus(503);
    } else {
      connection.query('insert into question (classID, userID, content) values (?, ?, ?)', [req.body.classID, req.body.userID, req.body.content], function(err, result) {
        console.log(result);
        if (err != null) {
          console.log('insert query err: ', err);
          res.json({success:false});
        } else {
          res.json({success:true});
        }
      });
      connection.release();
    }
  });
});

router.get('/api/questionList/:classID', function(req, res) {
  console.log('API: get questinoList');
  console.log(req.params.classID);
  pool.getConnection(function(error, connection) {
    if (error) {
      console.log('db connection failed: ' + error);
      res.sendStatus(503);
    } else {
      connection.query('select * from question where classID=?', [req.params.classID], function(err, result) {
        console.log(result);
        if (err == null) {
          res.json({
            success:true,
            count:result.length,
            questionInfos:result
          });
        } else {
          res.json({success:false});
        }
      });
      connection.release();
    }
  });
});

router.get('/api/questionDetail/:questionID', function(req, res) {
  console.log('API: get question detail');
  pool.getConnection(function(error, connection) {
    if (error) {
      console.log('db connection failed: ' + error);
      res.sendStatus(503);
    } else {
      connection.query('select * from question where id=?', [req.params.questionID], function(err, result) {
        if (err == null) {
          console.log(result);
          console.log(req.params.questionID);
          console.log(req.session.userID);
          connection.query('select * from heart where (questionID=? AND userID=?)', [req.params.questionID, req.session.userID], function(err2, result2) {
            if (err2 == null) {
              console.log(result2);
              res.json({
                success:true,
                info:result,
                didLike: (result2.length!=0)
              });
            } else {
              res.json({success:false, message:err2});
            }
          });
          connection.release();
        } else {
          res.json({success:false, message:err});
        }
      });
    }
  });
});

router.put('/api/addLike', function(req, res) {
  console.log('API: put addLike');
  console.log(req.body.questionID);
  console.log(req.body.userID);
  pool.getConnection(function(error, connection) {
    if(error){
      console.log('db connection failed: ' + error);
      res.sendStatus(503);
    } else {
      connection.query('insert into heart(questionID, userID) values(?,?)',[req.body.questionID, req.body.userID], function(error, result) {
        console.log(result);
        if(error !=null){
          console.log('insert query err: ', error);
          res.json({success:false});
        } else{
          res.json({success: true});
        }
      });
      connection.release();
    }
  });
});

router.put('/api/removeLike', function(req, res){
  console.log('API : delete remove like');
  console.log(req.body.questionID);
  console.log(req.body.userID);
  pool.getConnection(function(error, connection) {
    if(error){
      console.log('db connection failed: ' + error);
      res.sendStatus(503);
    } else {
      connection.query('delete from heart where (questionID=? and userID=?)',[req.body.questionID, req.body.userID], function(error, result) {
        console.log(result);
        if(error !=null){
          console.log('insert query err: ', error);
          res.json({success:false});
        } else{
          res.json({success: true});
        }
      });
      connection.release();
    }
  });
});

router.post('/api/makeComment', function(req, res){
  console.log('API : post makeComment');
  console.log(req.body.questionID);
  console.log(req.body.userID);
  console.log(req.body.content);
  pool.getConnection(function(error, connection) {
    if(error){
      console.log('db connection failed: ' + error);
      res.sendStatus(503);
    } else {
      connection.query('insert into comment(questionID, userID, content) values(?,?,?)',[req.body.questionID, req.body.userID, req.body.content], function(error, result) {
        console.log(result);
        if(error !=null){
          console.log('insert query err: ', error);
          res.json({success:false});
        } else{
          res.json({success: true});
        }
      });
      connection.release();
    }
  });
});

router.get('/api/commentList/:questionID', function(req,res){
  console.log('API: get commentList');
  console.log(req.params.questionID);
  pool.getConnection(function(error, connection){
    if(error){
      console.log('db connection failed: '+error);
      res.sendStatus(503);
    } else {
      connection.query('select * from comment where questionID=?', [req.params.questionID], function(error, result){
        console.log(result);
        if(error == null){
          res.json({
            success : true,
            count : result.length,
            infos : result
          });
        } else {
          res.json({success:false});
        }
      });
      connection.release();
    }
  });
});

module.exports = router;
<|endoftext|>


<commit_before>import { Router } from 'express'
import oauth2 from '../config/oauth2orize'
import { auth } from '../middlewares'
import { user, client, token, main } from '../controllers'

const router = Router()

  .get('/oauth2/authorize', oauth2.authorization)
  .post('/oauth2/authorize', oauth2.decision)
  .post('/oauth2/token', oauth2.token)
  .get('/oauth2/token/info', token.info)
  .get('/oauth2/token/revoke', token.revoke)

  .get('/oauth2/users', auth.isTrustedClient(), user.index)
  .post('/oauth2/users', auth.isTrustedClient(), user.create)
  .get('/oauth2/users/:id', auth.isTrustedClient(), user.show)
  .put('/oauth2/users/:id', auth.isTrustedClient(), user.update)
  .delete('/oauth2/users/:id', auth.isTrustedClient(), user.destroy)

  .get('/oauth2/clients', auth.isTrustedClient(), client.index)
  .post('/oauth2/clients', auth.isTrustedClient(), client.create)
  .get('/oauth2/clients/:id', auth.isTrustedClient(), client.show)
  .put('/oauth2/clients/:id', auth.isTrustedClient(), client.update)
  .delete('/oauth2/clients/:id', auth.isTrustedClient(), client.destroy)

  .get('/', main.index)
  .get('/signup', main.showSignup)
  .post('/signup', main.doSignup)
  .get('/login', main.showLogin)
  .post('/login', main.doLogin)
  .get('/logout', main.doLogout)
  .get('/password/forgot', main.showForgot)
  .post('/password/forgot', main.doForgot)
  .get('/password/reset/:token', main.showReset)
  .post('/password/reset/:token', main.doReset)
  // .get('/*', main.notFound)

export default () => router
<commit_msg>refactor: routes<commit_after>import { Router } from 'express'
import oauth2 from '../config/oauth2orize'
import { auth } from '../middlewares'
import { account, user, client, token } from '../controllers'

const router = Router()

  .get('/oauth2/authorize', oauth2.authorization)
  .post('/oauth2/authorize', oauth2.decision)
  .post('/oauth2/token', oauth2.token)
  .get('/oauth2/token/info', token.info)
  .get('/oauth2/token/revoke', token.revoke)

  .get('/oauth2/users', auth.isTrustedClient(), user.index)
  .post('/oauth2/users', auth.isTrustedClient(), user.create)
  .get('/oauth2/users/:id', auth.isTrustedClient(), user.show)
  .put('/oauth2/users/:id', auth.isTrustedClient(), user.update)
  .delete('/oauth2/users/:id', auth.isTrustedClient(), user.destroy)

  .get('/oauth2/clients', auth.isTrustedClient(), client.index)
  .post('/oauth2/clients', auth.isTrustedClient(), client.create)
  .get('/oauth2/clients/:id', auth.isTrustedClient(), client.show)
  .put('/oauth2/clients/:id', auth.isTrustedClient(), client.update)
  .delete('/oauth2/clients/:id', auth.isTrustedClient(), client.destroy)

  .get('/', account.index)
  .get('/signup', account.showSignup)
  .post('/signup', account.doSignup)
  .get('/login', account.showLogin)
  .post('/login', account.doLogin)
  .get('/logout', account.doLogout)
  .get('/password/forgot', account.showForgot)
  .post('/password/forgot', account.doForgot)
  .get('/password/reset/:token', account.showReset)
  .post('/password/reset/:token', account.doReset)
  .get('/*', (req, res) => res.render(req.url))

export default () => router
<|endoftext|>


<commit_before>var _ = require('lodash'),
	ffmpeg = require('fluent-ffmpeg');
var ShowImporter = require('../importers/ShowImporter.js');
var traktConfig = require('../../config/trakt');
var directoriesConfig = require('../../config/directories');
module.exports = function home(app, models){
	app.get('/shows', function(req, res){
		var Show = models.Show;
		if(req.isAuthenticated()){
			Show.find(function(err, shows){
				res.render('shows/index', {
					shows: shows
				});
			});
		}else{
			res.redirect('/auth/login');
		}
	});
	app.get('/show/:show', function(req, res){
		var Show = models.Show,
			Episode = models.Episode;
		if(req.isAuthenticated()){
			Show.findOne({url: req.params.show}, function(err, show){
				if(!show || show.length == 0){
					return res.render('error.html', {
						message: 'Show not found'
					});
				}
				//console.log(show)
				if(show && show.seasons){
					show.seasons = show.seasons.sort(function(a, b){
							if(a.season > b.season){
								return 1;
							}else if(a.season < b.season){
								return -1;
							}
							return 0;
					});
				}
				Episode.find({'show': show._id}, function(err, episodes){
					if(err){
						console.log(err);
					}
					//console.log('lol', episodes)
					var seasons = {};
					_.each(episodes, function (el){
						var s = el.season,
							e = el.episode;
						if(!seasons[s]){
							seasons[s] = {};
							seasons[s].num = s;
						}
						var season = seasons[s];
						if(!season.episodes){
							season.episodes = [];
						}
						if(show && show.seasons){
							if(show.seasons && show.seasons[s] && show.seasons[s].episodes){
								el = _.merge(el, show.seasons[s].episodes[e-1])
								//console.log(show.seasons[s].episodes[e])
							}
						}
						season.episodes.push(el)
					});
					seasons = _.each(seasons, function(season){
						if(season){
							season.episodes = season.episodes.sort(function(a, b){
								if(a.episode > b.episode){
									return 1;
								}else if(a.episode < b.episode){
									return -1;
								}
								return 0;
							});
						}
					});
					res.render('shows/single', {
						show: show,
						seasons: seasons
					});
				})
			});
		}else{
			res.redirect('/auth/login');
		}
	});
	app.get('/watch/:episodeId', function(req, res){
		var dir = directoriesConfig.tv,
			Episode = models.Episode;
		if(req.isAuthenticated()){
			Episode
			.findOne({'_id': req.params.episodeId})
			.populate('show')
			.exec(function(err, ep){
				console.log(ep)
				res.render('shows/episode', {
					show: {},
					ep: ep
				});
			});
		}else{
			res.redirect('/auth/login');
		}
	});
	app.get('/transcode/:episodeId', function(req, res){
		var dir = directoriesConfig.tv,
			Episode = models.Episode;
		if(req.isAuthenticated()){
			Episode
			.findOne({'_id': req.params.episodeId})
			.populate('show')
			.exec(function(err, ep){
				if(ep && ep.file){
					var options = [
						'-threads 0',
						'-coder 0',
						'-flags -loop',
						'-pix_fmt yuv420p',
						'-subq 0',
						'-sc_threshold 0',
						'-keyint_min 150',
						'-deinterlace',
						'-maxrate 10000000',
						'-bufsize 10000000',
						'-strict experimental',
						'-frag_duration 1000',
						'-movflags +frag_keyframe+empty_moov',
						'-profile:v baseline'
					];
					// Force lossless
					options.push('-crf 0');
					res.contentType('video/mp4');
					console.log(ep.file)
					var proc = ffmpeg({source: dir + ep.file})
					.format('mp4')
					.addOptions(options)
					.on('start', function(commandLine) {
						console.log('Spawned Ffmpeg with command: ' + commandLine);
					})
					.on('end', function(){
						console.log('file has been converted succesfully');
					})
					.on('error', function(err){
						console.log('an error happened: ' + err.message);
					})
					.pipe(res, {end:true});

				}
			});
		}else{
			res.redirect('/auth/login');
		}
	});
	app.get('/import', function(req, res){
		var dir = directoriesConfig.tv,
			importer = new ShowImporter(traktConfig.apiKey, models);
		importer.importAll(dir, function(){});
		res.end();
	});
};<commit_msg>Don't force lossless<commit_after>var _ = require('lodash'),
	ffmpeg = require('fluent-ffmpeg');
var ShowImporter = require('../importers/ShowImporter.js');
var traktConfig = require('../../config/trakt');
var directoriesConfig = require('../../config/directories');
module.exports = function home(app, models){
	app.get('/shows', function(req, res){
		var Show = models.Show;
		if(req.isAuthenticated()){
			Show.find(function(err, shows){
				res.render('shows/index', {
					shows: shows
				});
			});
		}else{
			res.redirect('/auth/login');
		}
	});
	app.get('/show/:show', function(req, res){
		var Show = models.Show,
			Episode = models.Episode;
		if(req.isAuthenticated()){
			Show.findOne({url: req.params.show}, function(err, show){
				if(!show || show.length == 0){
					return res.render('error.html', {
						message: 'Show not found'
					});
				}
				//console.log(show)
				if(show && show.seasons){
					show.seasons = show.seasons.sort(function(a, b){
							if(a.season > b.season){
								return 1;
							}else if(a.season < b.season){
								return -1;
							}
							return 0;
					});
				}
				Episode.find({'show': show._id}, function(err, episodes){
					if(err){
						console.log(err);
					}
					//console.log('lol', episodes)
					var seasons = {};
					_.each(episodes, function (el){
						var s = el.season,
							e = el.episode;
						if(!seasons[s]){
							seasons[s] = {};
							seasons[s].num = s;
						}
						var season = seasons[s];
						if(!season.episodes){
							season.episodes = [];
						}
						if(show && show.seasons){
							if(show.seasons && show.seasons[s] && show.seasons[s].episodes){
								el = _.merge(el, show.seasons[s].episodes[e-1])
								//console.log(show.seasons[s].episodes[e])
							}
						}
						season.episodes.push(el)
					});
					seasons = _.each(seasons, function(season){
						if(season){
							season.episodes = season.episodes.sort(function(a, b){
								if(a.episode > b.episode){
									return 1;
								}else if(a.episode < b.episode){
									return -1;
								}
								return 0;
							});
						}
					});
					res.render('shows/single', {
						show: show,
						seasons: seasons
					});
				})
			});
		}else{
			res.redirect('/auth/login');
		}
	});
	app.get('/watch/:episodeId', function(req, res){
		var dir = directoriesConfig.tv,
			Episode = models.Episode;
		if(req.isAuthenticated()){
			Episode
			.findOne({'_id': req.params.episodeId})
			.populate('show')
			.exec(function(err, ep){
				console.log(ep)
				res.render('shows/episode', {
					show: {},
					ep: ep
				});
			});
		}else{
			res.redirect('/auth/login');
		}
	});
	app.get('/transcode/:episodeId', function(req, res){
		var dir = directoriesConfig.tv,
			Episode = models.Episode;
		if(req.isAuthenticated()){
			Episode
			.findOne({'_id': req.params.episodeId})
			.populate('show')
			.exec(function(err, ep){
				if(ep && ep.file){
					var options = [
						'-threads 0',
						'-coder 0',
						'-flags -loop',
						'-pix_fmt yuv420p',
						'-subq 0',
						'-sc_threshold 0',
						'-keyint_min 150',
						'-deinterlace',
						'-maxrate 10000000',
						'-bufsize 10000000',
						'-acodec aac',
						'-strict experimental',
						'-frag_duration 1000',
						'-movflags +frag_keyframe+empty_moov',
						'-profile:v baseline'
					];
					// Force lossless
					//options.push('-crf 0');
					res.contentType('video/mp4');
					console.log(ep.file)
					var proc = ffmpeg({source: dir + ep.file})
					.format('mp4')
					.audioCodec('aac')
					.addOptions(options)
					.on('start', function(commandLine) {
						console.log('Spawned Ffmpeg with command: ' + commandLine);
					})
					.on('end', function(){
						console.log('file has been converted succesfully');
					})
					.on('error', function(err){
						console.log('an error happened: ' + err.message);
					})
					.pipe(res, {end:true});

				}
			});
		}else{
			res.redirect('/auth/login');
		}
	});
	app.get('/import', function(req, res){
		var dir = directoriesConfig.tv,
			importer = new ShowImporter(traktConfig.apiKey, models);
		importer.importAll(dir, function(){});
		res.end();
	});
};<|endoftext|>


<commit_before>/**
 * BMotion Studio for ProB Standalone Module
 *
 */
define(['angularAMD', 'angular', 'prob.graph', 'prob.iframe.template', 'prob.ui', 'bms.manifest', 'prob.modal', 'bms.common', 'angular-route'],
    function (angularAMD, angular) {

        var module = angular.module('prob.online', ['prob.graph', 'prob.iframe.template', 'prob.ui', 'prob.modal', 'bms.manifest', 'bms.common', 'ngRoute'])
            .run(['bmsMainService',
                function (bmsMainService) {
                    bmsMainService.mode = 'ModeOnline';
                }])
            .config(['$routeProvider', '$locationProvider',
                function ($routeProvider) {
                    $routeProvider
                        .when('/', {
                            template: '
'
                            + '
'
                            + '
'
                            + 'BMotion Studio for ProB'
                            + '
'
                            + '
'
                            + '
',
                            controller: 'bmsOnlineHomeCtrl'
                        })
                        .when('/:sessionId/:view', {
                            template: '
'
                            + '

'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + 'BMotion Studio for ProB'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + 'ProB'
                            + '
'
                            + '
'
                            + ' History
'
                            + '
'
                            + ' Events
'
                            + '
'
                            + ' State
'
                            + '
'
                            + ' Animations
'
                            + '
'
                            + ' Console
'
                            + '
'
                            + ' Model Checking
'
                            + '
'
                            + '
'
                            + '
'
                            + 'Diagram '
                            + '
'
                            + '
'
                            + ' Element Projection
'
                            + '
'
                            + ' Trace Diagram
'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + '

'
                            + '
'
                            + '
'
                            + '

'
                            + '
'
                            + '
'
                            + '

'
                            + '
'
                            + '
'
                            + '

'
                            + '
'
                            + '
'
                            + '

'
                            + '
'
                            + '
'
                            + '

'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + '
',
                            controller: 'bmsOnlineVisualizationCtrl'
                        })
                        .otherwise({
                            redirectTo: '/'
                        });
                }])
            .controller('bmsOnlineHomeCtrl', ['$scope', 'initVisualizationService', '$routeParams',
                function ($scope, initVisualizationService, $routeParams) {
                    var path = $routeParams['path'];
                    if (path) {
                        initVisualizationService(path);
                    }
                    /*else {
                     bmsModalService.setMessage("Please provide path to bmotion.json file.
Append \"\?path=[relative path to bmotion.json file]\" to URL.");
                     }*/
                }])
            .controller('bmsOnlineVisualizationCtrl', ['$scope',
                function ($scope) {
                }])
            .controller('bmsVisualizationCtrl', ['$scope', '$routeParams',
                function ($scope, $routeParams) {
                    var self = this;
                    self.view = $routeParams.view;
                    self.sessionId = $routeParams.sessionId;
                }])
            .directive('bmsVisualization', ['initVisualizationService', '$routeParams',
                function (initVisualizationService, $routeParams) {
                    return {
                        replace: true,
                        scope: {},
                        controller: ['$scope', function ($scope) {
                        }],
                        link: function ($scope, element, attrs) {
                            element.attr('class', 'fullWidthHeight');
                            var view = $routeParams.view;
                            var sessionId = $routeParams.sessionId;
                            if (!sessionId && !view) {
                                var path = attrs['bmsVisualization'];
                                if (path) {
                                    initVisualizationService(path);
                                } else {
                                    bmsModalService.setMessage("Please provide path to bmotion.json file.");
                                }
                            }
                        }
                    }
                }])
            .factory('initVisualizationService', ['$location', 'bmsInitSessionService', 'bmsManifestService', 'bmsMainService', 'bmsModalService',
                function ($location, bmsInitSessionService, bmsManifestService, bmsMainService, bmsModalService) {

                    return function (manifestFilePath) {

                        bmsModalService.loading("Initialising visualisation ...");

                        bmsManifestService.validate(manifestFilePath)
                            .then(function (manifestData) {
                                bmsInitSessionService(manifestFilePath, manifestData)
                                    .then(function (sessionId) {
                                        // TODO: Handle multiple views in online mode!
                                        var views = manifestData.views;
                                        var view = views[0];
                                        $location.path('/' + sessionId + '/' + view.id);
                                        bmsModalService.endLoading();
                                    }, function (errors) {
                                        bmsModalService.openErrorDialog(errors);
                                    });
                            }, function (error) {
                                bmsModalService.openErrorDialog(error);
                            });

                    }

                }]);
        return angularAMD.bootstrap(module);

    })
;<commit_msg>check if user specified path to bmotion.json file<commit_after>/**
 * BMotion Studio for ProB Standalone Module
 *
 */
define(['angularAMD', 'angular', 'prob.graph', 'prob.iframe.template', 'prob.ui', 'bms.manifest', 'prob.modal', 'bms.common', 'angular-route'],
    function (angularAMD, angular) {

        var module = angular.module('prob.online', ['prob.graph', 'prob.iframe.template', 'prob.ui', 'prob.modal', 'bms.manifest', 'bms.common', 'ngRoute'])
            .run(['bmsMainService',
                function (bmsMainService) {
                    bmsMainService.mode = 'ModeOnline';
                }])
            .config(['$routeProvider', '$locationProvider',
                function ($routeProvider) {
                    $routeProvider
                        .when('/', {
                            template: '
'
                            + '
'
                            + '
'
                            + 'BMotion Studio for ProB'
                            + '
'
                            + '
'
                            + '
',
                            controller: 'bmsOnlineHomeCtrl'
                        })
                        .when('/:sessionId/:view', {
                            template: '
'
                            + '

'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + 'BMotion Studio for ProB'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + 'ProB'
                            + '
'
                            + '
'
                            + ' History
'
                            + '
'
                            + ' Events
'
                            + '
'
                            + ' State
'
                            + '
'
                            + ' Animations
'
                            + '
'
                            + ' Console
'
                            + '
'
                            + ' Model Checking
'
                            + '
'
                            + '
'
                            + '
'
                            + 'Diagram '
                            + '
'
                            + '
'
                            + ' Element Projection
'
                            + '
'
                            + ' Trace Diagram
'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + '

'
                            + '
'
                            + '
'
                            + '

'
                            + '
'
                            + '
'
                            + '

'
                            + '
'
                            + '
'
                            + '

'
                            + '
'
                            + '
'
                            + '

'
                            + '
'
                            + '
'
                            + '

'
                            + '
'
                            + '
'
                            + '
'
                            + '
'
                            + '
',
                            controller: 'bmsOnlineVisualizationCtrl'
                        })
                        .otherwise({
                            redirectTo: '/'
                        });
                }])
            .controller('bmsOnlineHomeCtrl', ['$scope', 'initVisualizationService', '$routeParams', 'bmsModalService',
                function ($scope, initVisualizationService, $routeParams, bmsModalService) {
                    var path = $routeParams['path'];
                    if (path) {
                        initVisualizationService(path);
                    }
                    else {
                        bmsModalService.setMessage("Please provide path to bmotion.json file.
Append \"\?path=[relative path to bmotion.json file]\" to URL.");
                    }
                }])
            .controller('bmsOnlineVisualizationCtrl', ['$scope',
                function ($scope) {
                }])
            .controller('bmsVisualizationCtrl', ['$scope', '$routeParams',
                function ($scope, $routeParams) {
                    var self = this;
                    self.view = $routeParams.view;
                    self.sessionId = $routeParams.sessionId;
                }])
            .directive('bmsVisualization', ['initVisualizationService', '$routeParams',
                function (initVisualizationService, $routeParams) {
                    return {
                        replace: true,
                        scope: {},
                        controller: ['$scope', function ($scope) {
                        }],
                        link: function ($scope, element, attrs) {
                            element.attr('class', 'fullWidthHeight');
                            var view = $routeParams.view;
                            var sessionId = $routeParams.sessionId;
                            if (!sessionId && !view) {
                                var path = attrs['bmsVisualization'];
                                if (path) {
                                    initVisualizationService(path);
                                } else {
                                    bmsModalService.setMessage("Please provide path to bmotion.json file.");
                                }
                            }
                        }
                    }
                }])
            .factory('initVisualizationService', ['$location', 'bmsInitSessionService', 'bmsManifestService', 'bmsMainService', 'bmsModalService',
                function ($location, bmsInitSessionService, bmsManifestService, bmsMainService, bmsModalService) {

                    return function (manifestFilePath) {

                        bmsModalService.loading("Initialising visualisation ...");

                        bmsManifestService.validate(manifestFilePath)
                            .then(function (manifestData) {
                                bmsInitSessionService(manifestFilePath, manifestData)
                                    .then(function (sessionId) {
                                        // TODO: Handle multiple views in online mode!
                                        var views = manifestData.views;
                                        var view = views[0];
                                        $location.path('/' + sessionId + '/' + view.id);
                                        bmsModalService.endLoading();
                                    }, function (errors) {
                                        bmsModalService.openErrorDialog(errors);
                                    });
                            }, function (error) {
                                bmsModalService.openErrorDialog(error);
                            });

                    }

                }]);
        return angularAMD.bootstrap(module);

    })
;<|endoftext|>


<commit_before>define(
    ['backbone', 'backform', 'bootstrap'],
    function(Backbone, Backform, bootstrap) {

	// options: name, template, model, loading, fields
	var RoomFormView = Backbone.View.extend({
            el: '#simple-form-view',
            events: {
                'click #simple-form-save': 'save'
            },
            initialize: function(options) {
                var self = this;
                console.log('simple-form view init');
		this.options = options;
                self.template = _.template(options.template);
                self.model = options.model;
                self.name = options.name;
                self.loading = options.loading;
                self.saved = false;
                this.listenTo(this.model, 'change',
                              function() {
                                  console.log(name + ' change');
                                  if (self.loading){
                                    self.loading = false;
                                    this.render();
                                }
                              });
		this.initialize_form(options.fields);
            },
            initialize_form: function(fields) {
                this.form = new Backform.Form({
                    model: this.model,
                    fields: fields,
                    events: {
                        'submit': function(e) {
                            console.log(this.name + ' submit backform');
                            e.preventDefault();
                            if (this.model.isValid()) {
                                this.model.save({model: JSON.stringify(this.model)},{
                                    success: function(model, response, option) {
                                        console.log('SAVE SUCCESS', response);
                                        $('span.status').css({'margin': '5px','color': '#409b27'
                                        }).html('Saved!').show().fadeOut( 1000 );
                                    },
                                    error: function(model, response, options) {
                                        console.log('SAVE ERROR', response);
                                    },
                                });
                            }
                            return false;
                        }
                    }
                });
            },
            render: function() {
                var t = this.template({name: this.name,
                                       s: this.model.attributes});
                this.$el.html(t);
                if (this.loading) {
                    this.$('#simple-form-loading').show();
                    this.$('#simple-form-loaded').hide();
                    this.$('#simple-form-backform').hide();
                    this.$('#simple-form-new').hide();
                } else {
                    this.$('#simple-form-loading').hide();
                    this.$('#simple-form-new').hide();
                    if (this.model.has('id')) {
                        this.$('#simple-form-loaded').show();
                        this.$('#simple-form-new').hide();
                    } else {
                        this.$('#simple-form-loaded').hide();
                        this.$('#simple-form-new').show();
                    }
                    this.$('#simple-form-backform').show();
                }
                if (this.form) {
                    this.firstfield = this.getFirstField();
                    this.form.setElement(this.$el.find('#simple-form-backform'));
                    this.form.render();
                    this.$(this.firstfield.control + '[name=' + this.firstfield.name +']').focus();

                    this.$('button').on('mousedown', function() {
                        $(this).css('color', 'white');
                    });
                    this.$('button').on('mouseup', function() {
                        $(this).css('color', 'inherit');
                    });

                }
                return this;
            },
            getFirstField: function() {
                var field_list = _.reject(this.form.fields.models, function(model) { return model.get('disabled'); });
                return field_list[0]._previousAttributes;
            },
            save: function() {
                console.log('saving simple-form');
                this.model.save();
            }
        });
        return RoomFormView;
    }
);
<commit_msg>updated button, removed name reference<commit_after>define(
    ['backbone', 'backform', 'bootstrap'],
    function(Backbone, Backform, bootstrap) {

    // options: name, template, model, loading, fields
    var RoomFormView = Backbone.View.extend({
            el: '#simple-form-view',
            events: {
                'click #simple-form-save': 'save'
            },
            initialize: function(options) {
                var self = this;
                console.log('simple-form view init');
        this.options = options;
                self.template = _.template(options.template);
                self.model = options.model;
                self.name = options.name;
                self.loading = options.loading;
                self.saved = false;
                this.listenTo(this.model, 'change',
                              function() {
                                  console.log(name + ' change');
                                  if (self.loading){
                                    self.loading = false;
                                    this.render();
                                }
                              });
        this.initialize_form(options.fields);
            },
            initialize_form: function(fields) {
                this.form = new Backform.Form({
                    model: this.model,
                    fields: fields,
                    events: {
                        'submit': function(e) {
                            e.preventDefault();
                            // console.log(this.name + ' submit backform');
                            if (this.model.isValid()) {
                                this.model.save({model: JSON.stringify(this.model)},{
                                    success: function(model, response, option) {
                                        // console.log('SAVE SUCCESS', response);
                                        $('span.status').css({'margin': '5px','color': '#409b27'}).html('Saved!').show().fadeOut( 1000 );
                                        self.saved = true;
                                    },
                                    error: function(model, response, options) {
                                        // console.log('SAVE ERROR', response);
                                        self.saved = false;
                                    },
                                });
                                 return false;
                            }
                        }
                    }
                });
            },
            render: function() {
                var t = this.template({name: this.name,
                                       s: this.model.attributes});
                this.$el.html(t);
                if (this.loading) {
                    this.$('#simple-form-loading').show();
                    this.$('#simple-form-loaded').hide();
                    this.$('#simple-form-backform').hide();
                    this.$('#simple-form-new').hide();
                } else {
                    this.$('#simple-form-loading').hide();
                    this.$('#simple-form-new').hide();
                    if (this.model.has('id')) {
                        this.$('#simple-form-loaded').show();
                        this.$('#simple-form-new').hide();
                    } else {
                        this.$('#simple-form-loaded').hide();
                        this.$('#simple-form-new').show();
                    }
                    this.$('#simple-form-backform').show();
                }
                if (this.form) {
                    this.firstfield = this.getFirstField();
                    this.form.setElement(this.$el.find('#simple-form-backform'));
                    this.form.render();
                    this.$(this.firstfield.control + '[name=' + this.firstfield.name +']').focus();

                    this.$('button').on('mousedown', function() {
                        $(this).css('color', 'white');
                    });
                    this.$('button').on('mouseup', function() {
                        $(this).css('color', 'inherit');
                    });

                }
                return this;
            },
            getFirstField: function() {
                var field_list = _.reject(this.form.fields.models, function(model) { return model.get('disabled'); });
                return field_list[0]._previousAttributes;
            },
            save: function() {
                console.log('saving simple-form');
                this.model.save();
            }
        });
        return RoomFormView;
    }
);
<|endoftext|>


<commit_before>/**
 * Settings storage for all Gateway Services
 * General API Settings are stored in api/apiConfig and should be imported here
 */

import {
    rudexAPIs,
    bitsparkAPIs,
    widechainAPIs,
    openledgerAPIs,
    cryptoBridgeAPIs,
    gdex2APIs,
    xbtsxAPIs,
    citadelAPIs,
    deexAPIs
} from "api/apiConfig";
import {allowedGateway} from "branding";

export const availableGateways = {
    OPEN: {
        id: "OPEN",
        name: "OPENLEDGER",
        baseAPI: openledgerAPIs,
        isEnabled: allowedGateway("OPEN"),
        selected: false,
        options: {
            enabled: false,
            selected: false
        }
    },
    RUDEX: {
        id: "RUDEX",
        name: "RUDEX",
        baseAPI: rudexAPIs,
        isEnabled: allowedGateway("RUDEX"),
        isSimple: true,
        selected: false,
        simpleAssetGateway: true,
        fixedMemo: {prepend: "dex:", append: ""},
        addressValidatorMethod: "POST",
        options: {
            enabled: false,
            selected: false
        }
    },
    SPARKDEX: {
        id: "SPARKDEX",
        name: "SPARKDEX",
        baseAPI: bitsparkAPIs,
        isEnabled: allowedGateway("SPARKDEX"),
        selected: false,
        options: {
            enabled: false,
            selected: false
        }
    },
    BRIDGE: {
        id: "BRIDGE",
        name: "CRYPTO-BRIDGE",
        baseAPI: cryptoBridgeAPIs,
        isEnabled: allowedGateway("BRIDGE"),
        selected: false,
        singleWallet: true, // Has no coresponging coinType == backingCoinType specific wallet
        addressValidatorAsset: true, // Address validator requires output_asset parameter
        useFullAssetName: true, // Adds <gateway>.<asset> to memo and address object
        intermediateAccount: "cryptobridge", // Fixed intermediateAccount
        options: {
            enabled: false,
            selected: false
        }
    },
    GDEX: {
        id: "GDEX",
        name: "GDEX",
        baseAPI: gdex2APIs,
        isEnabled: allowedGateway("GDEX"),
        options: {
            enabled: false,
            selected: false
        }
    },
    XBTSX: {
        id: "XBTSX",
        name: "XBTSX",
        baseAPI: xbtsxAPIs,
        isEnabled: allowedGateway("XBTSX"),
        isSimple: true,
        selected: false,
        simpleAssetGateway: false,
        addressValidatorMethod: "POST",
        options: {
            enabled: false,
            selected: false
        }
    },
    CITADEL: {
        id: "CITADEL",
        name: "CITADEL",
        baseAPI: citadelAPIs,
        isEnabled: allowedGateway("CITADEL"),
        selected: false,
        assetWithdrawlAlias: {monero: "xmr"}, // if asset name doesn't equal to memo
        options: {
            enabled: false,
            selected: false
        }
    },
    DEEX: {
        id: "DEEX",
        name: "DEEX",
        baseAPI: deexAPIs,
        isSimple: true,
        simpleAssetGateway: true,
        fixedMemo: {prepend: "dex:", append: ""},
        isEnabled: allowedGateway("DEEX"),
        addressValidatorMethod: "POST",
        options: {
            enabled: false,
            selected: false
        }
    }
};

export const gatewayPrefixes = Object.keys(availableGateways);

export function getPossibleGatewayPrefixes(bases) {
    return gatewayPrefixes.reduce((assets, prefix) => {
        bases.forEach(a => {
            assets.push(`${prefix}.${a}`);
        });
        return assets;
    }, []);
}

export default availableGateways;
<commit_msg>change option gateway<commit_after>/**
 * Settings storage for all Gateway Services
 * General API Settings are stored in api/apiConfig and should be imported here
 */

import {
    rudexAPIs,
    bitsparkAPIs,
    widechainAPIs,
    openledgerAPIs,
    cryptoBridgeAPIs,
    gdex2APIs,
    xbtsxAPIs,
    citadelAPIs,
    deexAPIs
} from "api/apiConfig";
import {allowedGateway} from "branding";

export const availableGateways = {
    OPEN: {
        id: "OPEN",
        name: "OPENLEDGER",
        baseAPI: openledgerAPIs,
        isEnabled: allowedGateway("OPEN"),
        selected: false,
        options: {
            enabled: false,
            selected: false
        }
    },
    RUDEX: {
        id: "RUDEX",
        name: "RUDEX",
        baseAPI: rudexAPIs,
        isEnabled: allowedGateway("RUDEX"),
        isSimple: true,
        selected: false,
        simpleAssetGateway: true,
        fixedMemo: {prepend: "dex:", append: ""},
        addressValidatorMethod: "POST",
        options: {
            enabled: false,
            selected: false
        }
    },
    SPARKDEX: {
        id: "SPARKDEX",
        name: "SPARKDEX",
        baseAPI: bitsparkAPIs,
        isEnabled: allowedGateway("SPARKDEX"),
        selected: false,
        options: {
            enabled: false,
            selected: false
        }
    },
    BRIDGE: {
        id: "BRIDGE",
        name: "CRYPTO-BRIDGE",
        baseAPI: cryptoBridgeAPIs,
        isEnabled: allowedGateway("BRIDGE"),
        selected: false,
        singleWallet: true, // Has no coresponging coinType == backingCoinType specific wallet
        addressValidatorAsset: true, // Address validator requires output_asset parameter
        useFullAssetName: true, // Adds <gateway>.<asset> to memo and address object
        intermediateAccount: "cryptobridge", // Fixed intermediateAccount
        options: {
            enabled: false,
            selected: false
        }
    },
    GDEX: {
        id: "GDEX",
        name: "GDEX",
        baseAPI: gdex2APIs,
        isEnabled: allowedGateway("GDEX"),
        options: {
            enabled: false,
            selected: false
        }
    },
    XBTSX: {
        id: "XBTSX",
        name: "XBTSX",
        baseAPI: xbtsxAPIs,
        isEnabled: allowedGateway("XBTSX"),
        isSimple: true,
        selected: false,
        simpleAssetGateway: false,
        addressValidatorMethod: "POST",
        options: {
            enabled: false,
            selected: false
        }
    },
    CITADEL: {
        id: "CITADEL",
        name: "CITADEL",
        baseAPI: citadelAPIs,
        isEnabled: allowedGateway("CITADEL"),
        selected: false,
        assetWithdrawlAlias: {monero: "xmr"}, // if asset name doesn't equal to memo
        options: {
            enabled: false,
            selected: false
        }
    },
    DEEX: {
        id: "DEEX",
        name: "DEEX",
        baseAPI: deexAPIs,
        isSimple: true,
        simpleAssetGateway: false,
        fixedMemo: {prepend: "dex:", append: ""},
        isEnabled: allowedGateway("DEEX"),
        addressValidatorMethod: "POST",
        options: {
            enabled: false,
            selected: false
        }
    }
};

export const gatewayPrefixes = Object.keys(availableGateways);

export function getPossibleGatewayPrefixes(bases) {
    return gatewayPrefixes.reduce((assets, prefix) => {
        bases.forEach(a => {
            assets.push(`${prefix}.${a}`);
        });
        return assets;
    }, []);
}

export default availableGateways;
<|endoftext|>


<commit_before>'use strict';

const { crashReporter } = require('electron');

const crashHandler = () => {
	crashReporter.start({
		productName: 'zulip-electron',
		companyName: 'Kandra Labs, Inc.',
		submitURL: 'https://zulip-sentry.herokuapp.com/crashreport',
		autoSubmit: true
	});
};

module.exports = {
	crashHandler
};
<commit_msg>crash-reporter: Remove deprecated autoSubmit api.<commit_after>'use strict';

const { crashReporter } = require('electron');

const crashHandler = () => {
	crashReporter.start({
		productName: 'zulip-electron',
		companyName: 'Kandra Labs, Inc.',
		submitURL: 'https://zulip-sentry.herokuapp.com/crashreport',
		uploadToServer: true
	});
};

module.exports = {
	crashHandler
};
<|endoftext|>


<commit_before>require('es6-promise').polyfill()
require('./blog.js')
require('./case-study-carousel.js')
require('./docs.js')
require('./events-carousel.js')
require('./fetch.js')
require('./get-started.js')
require('./install.js')
require('./modal.js')
require('./overlay.js')
require('./quotes-carousel.js')
require('./smooth-scroll.js')
require('./stackdiagram.js')
require('./typer.js')
require('swagger-ui-browserify')

import Wallop from 'wallop';
import Hammer from 'hammerjs';

// globals
const compareVersions = require('compare-versions');
window.compareVersions = compareVersions;

const docPathName = window.location.pathname

// Mobile menu
$('#nav-icon').on('click', function (e) {
  e.preventDefault();
  if($('#nav-icon').hasClass('open')) {
    $('.navigation').removeClass('mobile-menu--open');
    $('.menu-mobile').removeClass('open');
    $('#nav-icon').removeClass('open');
    $('body').removeAttr('style');
    $('html').removeAttr('style');
  } else {
    $('.navigation').addClass('mobile-menu--open');
    $('.menu-mobile').addClass('open');
    $('#nav-icon').addClass('open');
    $('body').attr('style', 'overflow: hidden;');
    $('html').attr('style', 'overflow: hidden;');
  }
})

// Array.find polyfill
if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this === null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

/***********************
  Dropdown
***********************/
$('.dropdown').click(function(){
  $('html').one('click',function() {
    $('.dropdown').removeClass('is-active')
  });

  $(this).toggleClass('is-active')

  event.stopPropagation()
})

/***********************
  Set timeout function
***********************/
function Timer(callback, delay) {
  var timerId, start, remaining = delay;

  this.pause = function() {
    window.clearTimeout(timerId);
    remaining -= new Date() - start;
  };

  this.resume = function() {
    start = new Date();
    window.clearTimeout(timerId);
    timerId = window.setTimeout(callback, remaining);
  };

  this.cancel = function() {
    window.clearTimeout(timerId);
  };

  this.resume();
}

/****************
  Slider
****************/
var wallopEl = document.querySelector('.Wallop');
if(wallopEl){
  var slider = new Wallop(wallopEl);

  // Add auto-play functionality
  var autoPlayMs = 6000;
  var nextTimeout;
  var loadNext = function() {
    var nextIndex = (slider.currentItemIndex + 1) % slider.allItemsArray.length;
    slider.goTo(nextIndex);
  }
  nextTimeout = new Timer(function() { loadNext(); }, autoPlayMs);
  slider.on('change', function() {
    nextTimeout.resume();
  });

  slider.on('mouseenter', function(){
    nextTimeout.cancel();
  })

  slider.on('mouseleave', function(){
    nextTimeout.resume();
  })

  // Enable touch for Wallop
  Hammer(wallopEl, {
    inputClass: Hammer.TouchInput
  }).on('swipeleft', function() {
    slider.next();
  });

  Hammer(wallopEl, {
    inputClass: Hammer.TouchInput
  }).on('swiperight', function() {
    slider.previous();
  });
}

/****************
  Clickable headers
****************/
$('#docs-content h1, #docs-content h2, #docs-content h3, #docs-content h4, #docs-content h5, #docs-content h6').each(function( index ) {
  var hashURL = $(this).attr('id')
  $(this).wrapInner('')
});

/****************
  SwaggerUI
****************/
$(document).ready(function() {
  var yamlFile = $('[data-api]').data('api');

  var swaggerUi = new SwaggerUi({
    url: yamlFile,
    dom_id: 'swagger-ui-container',
    docExpansion: 'list'
  });

  swaggerUi.load();
})

/****************
  Add proper submit feedback link to docs
****************/
const docPageTitle = ($('h1.docs-heading').text()).replace(' ', '+')
const jPid = 10001 // pid
const jIssueType = 10100 // issuetype
const jSummary = `Feedback+for+${docPageTitle}` // summary
const jDescription = `Source: ${window.location.href}` // description
const jLabels = 'documentation'

$('#submit-feedback').attr('href', `https://jira.dcos.io/secure/CreateIssueDetails!init.jspa?pid=${jPid}&issuetype=${jIssueType}&summary=${jSummary}&description=${jDescription}&labels=${jLabels}`)

/****************
  Docs version switch 404 prevention
****************/

const currentUrlPath = window.location.pathname
var pathArray = currentUrlPath.split('/')

$('button.dropdown a.option').click(function(event){
  event.preventDefault()
  pathArray[2] = $(this).attr('data-version')
  var newUrlPath = window.location.origin + pathArray.join('/')

  $.ajax({
      type: "HEAD",
      async: true,
      url: newUrlPath,
      success: function(message){
        location.assign(newUrlPath)
      },
      error: function(message){
        location.assign(`${window.location.origin}/docs/${pathArray[2]}`)
      }
  })

})

/****************
  Open docs images in lightboxes
****************/
$('#docs-content img').each(function(index) {
  var imgUrl = $(this).attr('src')
  $(this).addClass('cursor-pointer')

  $(this).click(function(){
    window.open(imgUrl, '_blank');
  })
})

/****************
  truncate excerpt
****************/
function cut(n) {
  return function textCutter(i, text) {
    var short = text.substr(0, n);
    if (/^\S/.test(text.substr(n)))
      return short.replace(/\s+\S*$/, '…');
    return short;
  };
}

$('.related-pages > div > p').each(function(index) {
  var excerpt = $(this).text();
  if(excerpt.length > 200) {
    $(this).text(cut(200));
  }
})
<commit_msg>Firefox fix<commit_after>require('es6-promise').polyfill()
require('./blog.js')
require('./case-study-carousel.js')
require('./docs.js')
require('./events-carousel.js')
require('./fetch.js')
require('./get-started.js')
require('./install.js')
require('./modal.js')
require('./overlay.js')
require('./quotes-carousel.js')
require('./smooth-scroll.js')
require('./stackdiagram.js')
require('./typer.js')
require('swagger-ui-browserify')

import Wallop from 'wallop';
import Hammer from 'hammerjs';

// globals
const compareVersions = require('compare-versions');
window.compareVersions = compareVersions;

const docPathName = window.location.pathname

// Mobile menu
$('#nav-icon').on('click', function (event) {
  event.preventDefault();
  if($('#nav-icon').hasClass('open')) {
    $('.navigation').removeClass('mobile-menu--open');
    $('.menu-mobile').removeClass('open');
    $('#nav-icon').removeClass('open');
    $('body').removeAttr('style');
    $('html').removeAttr('style');
  } else {
    $('.navigation').addClass('mobile-menu--open');
    $('.menu-mobile').addClass('open');
    $('#nav-icon').addClass('open');
    $('body').attr('style', 'overflow: hidden;');
    $('html').attr('style', 'overflow: hidden;');
  }
})

// Array.find polyfill
if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this === null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

/***********************
  Dropdown
***********************/
$('.dropdown').click(function(event){
  $('html').one('click',function() {
    $('.dropdown').removeClass('is-active')
  });

  $(this).toggleClass('is-active')

  event.stopPropagation()
})

/***********************
  Set timeout function
***********************/
function Timer(callback, delay) {
  var timerId, start, remaining = delay;

  this.pause = function() {
    window.clearTimeout(timerId);
    remaining -= new Date() - start;
  };

  this.resume = function() {
    start = new Date();
    window.clearTimeout(timerId);
    timerId = window.setTimeout(callback, remaining);
  };

  this.cancel = function() {
    window.clearTimeout(timerId);
  };

  this.resume();
}

/****************
  Slider
****************/
var wallopEl = document.querySelector('.Wallop');
if(wallopEl){
  var slider = new Wallop(wallopEl);

  // Add auto-play functionality
  var autoPlayMs = 6000;
  var nextTimeout;
  var loadNext = function() {
    var nextIndex = (slider.currentItemIndex + 1) % slider.allItemsArray.length;
    slider.goTo(nextIndex);
  }
  nextTimeout = new Timer(function() { loadNext(); }, autoPlayMs);
  slider.on('change', function() {
    nextTimeout.resume();
  });

  slider.on('mouseenter', function(){
    nextTimeout.cancel();
  })

  slider.on('mouseleave', function(){
    nextTimeout.resume();
  })

  // Enable touch for Wallop
  Hammer(wallopEl, {
    inputClass: Hammer.TouchInput
  }).on('swipeleft', function() {
    slider.next();
  });

  Hammer(wallopEl, {
    inputClass: Hammer.TouchInput
  }).on('swiperight', function() {
    slider.previous();
  });
}

/****************
  Clickable headers
****************/
$('#docs-content h1, #docs-content h2, #docs-content h3, #docs-content h4, #docs-content h5, #docs-content h6').each(function( index ) {
  var hashURL = $(this).attr('id')
  $(this).wrapInner('')
});

/****************
  SwaggerUI
****************/
$(document).ready(function() {
  var yamlFile = $('[data-api]').data('api');

  var swaggerUi = new SwaggerUi({
    url: yamlFile,
    dom_id: 'swagger-ui-container',
    docExpansion: 'list'
  });

  swaggerUi.load();
})

/****************
  Add proper submit feedback link to docs
****************/
const docPageTitle = ($('h1.docs-heading').text()).replace(' ', '+')
const jPid = 10001 // pid
const jIssueType = 10100 // issuetype
const jSummary = `Feedback+for+${docPageTitle}` // summary
const jDescription = `Source: ${window.location.href}` // description
const jLabels = 'documentation'

$('#submit-feedback').attr('href', `https://jira.dcos.io/secure/CreateIssueDetails!init.jspa?pid=${jPid}&issuetype=${jIssueType}&summary=${jSummary}&description=${jDescription}&labels=${jLabels}`)

/****************
  Docs version switch 404 prevention
****************/

const currentUrlPath = window.location.pathname
var pathArray = currentUrlPath.split('/')

$('button.dropdown a.option').click(function(event){
  event.preventDefault()
  pathArray[2] = $(this).attr('data-version')
  var newUrlPath = window.location.origin + pathArray.join('/')

  $.ajax({
      type: "HEAD",
      async: true,
      url: newUrlPath,
      success: function(message){
        location.assign(newUrlPath)
      },
      error: function(message){
        location.assign(`${window.location.origin}/docs/${pathArray[2]}`)
      }
  })

})

/****************
  Open docs images in lightboxes
****************/
$('#docs-content img').each(function(index) {
  var imgUrl = $(this).attr('src')
  $(this).addClass('cursor-pointer')

  $(this).click(function(){
    window.open(imgUrl, '_blank');
  })
})

/****************
  truncate excerpt
****************/
function cut(n) {
  return function textCutter(i, text) {
    var short = text.substr(0, n);
    if (/^\S/.test(text.substr(n)))
      return short.replace(/\s+\S*$/, '…');
    return short;
  };
}

$('.related-pages > div > p').each(function(index) {
  var excerpt = $(this).text();
  if(excerpt.length > 200) {
    $(this).text(cut(200));
  }
})
<|endoftext|>