<commit_before>// Import React
import React from "react";

// Import Spectacle Core tags
import {
  BlockQuote,
  Cite,
  Deck,
  Heading,
  ListItem,
  List,
  Quote,
  Slide,
  Text,
  Typeface,
  ComponentPlayground,
  Link,
  Image
} from "spectacle";
import CodeSlide from "spectacle-code-slide";
import preloader from "spectacle/lib/utils/preloader";
import CanIUse from "react-caniuse-embed";
import createTheme from "spectacle/lib/themes/default";
import styled, { keyframes } from "styled-components";

require("normalize.css");
require("spectacle/lib/themes/default/index.css");

const images = {
  city: require("../assets/city.jpg"),
  kat: require("../assets/kat.png"),
  logo: require("../assets/formidable-logo.svg"),
  markdown: require("../assets/markdown.png"),
  ie3: require("../assets/ie3_screen.jpg"),
  status: require("../assets/status.png"),
  grid: require("../assets/grid.png"),
  hak: require("../assets/hakon.jpg"),
  react: require("../assets/react-logo.png"),
  cup: require("../assets/cup1994.png"),
  opera: require("../assets/opera.png"),
  w3c: require("../assets/w3c.png"),
  sisense: require("../assets/sisense.jpg")
};

preloader(images);

const theme = createTheme({
  primary: "white",
  secondary: "#1F2022",
  tertiary: "#03A9FC",
  quartenary: "#CECECE",
  micolor: "#ffcb05",
  black: "#000"
}, {
  primary: "Montserrat",
  secondary: "Helvetica"
});

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
  animation: ${keyframes`from { opacity: 0; }`} 1s both;
`;

export default class Presentation extends React.Component {
  render() {
    const bgCode = `const styles = {
  heading: {
    fontSize: "2.25rem",
    fontWeight: "300"
  },
  button: {
    background: "transparent",
    borderRadius: "10px",
    border: "2px solid lime"
  }
}

const HelloWorld = ({ name }) => (

      {name} is going places...

    <button style={styles.button}>
      click me
    </button>

)

render(
  <HelloWorld name="Sisense" />,
  mountNode)`;
  const pseudoNoSolution = `<button style={m(
        this.styles.container,
        this.state.hovered && this.styles.hover,
      )}>{this.props.children}</button>`;

  const styledComp = `
  import styled from "styled-components";

  const Title = styled.h1\`
    font-size: 2.25rem;
    font-weight: 300;\`

  const Button = styled.button\`
    background: transparent;
    border-radius: 10px;
    border: 2px solid lime;\`

  const MyComponent = ()=> {
    return (

      <Title>Hello world</Title>
      <Button>click me</Button>

);
  }

`;

  const cssStructure = `
    .myClass {
      background-color: red;
    }

    #myId {
      background-color: blue;
    }

    div {
      background-color: green;
    }

  `;

  const cssPast = `

    ...content here

  `;
  const cssVariables = `
    element {
      --my-bg-color: hotpink;
    }
    .myClass {
      background-color: var(--my-bg-color);
    }

    .one {
      background-color: var(--my-bg-color, red);
    }

    .myClass {
      background-color: var(--my-bg-color);
    }

    .one {
      background-color: var(--my-bg-color, red);
    }

    @supports (-css: variables){
      .one {
        background-color: var(--css);
      }
    }
  `;
    return (
      <Deck transition={["zoom", "slide"]} transitionDuration={500} theme={theme} progress="bar">
        <Slide transition={["zoom"]} bgColor="micolor">
          <Heading size={1} fit caps lineHeight={1} textColor="#000">
            Past Present and Future of CSS
          </Heading>
          <Text margin="10px 0 0" textColor="tertiary" size={1} fit>
            how to survived in a component world
          </Text>
          <Text margin="10px 0 0" textColor="#000" size={3} fit bold>
            twitter: @leofle,            github: leofle,
            medium: leofle,            npm: fleo
          </Text>
        </Slide>
        <Slide transition={["fade"]} bgColor="primary">
          <Heading size={2} textColor="black"> Sr UX Engineer </Heading>
          <Text textColor="primary">blah blah</Text>
          <Image src={images.sisense} width={500} />
        </Slide>
        <Slide transition={["fade"]} bgColor="lime">
          <Heading size={2} textColor="secondary"> I make cool stuff!</Heading>
          <Text textColor="lime">blah blah</Text>
          <Heading size={3} textColor="secondary">🤘</Heading>
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
          <Heading size={2} textColor="secondary"> 1994 </Heading>
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
          <Image src={images.cup} width={500} />
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
        <Heading size={2} textColor="secondary">Håkon Wium Lie</Heading>
          <Image src={images.hak} width={300} />
        </Slide>
        <Slide>
          <Image src={images.opera} width={400} />
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
        <Heading size={2} textColor="secondary">CSS</Heading>
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
          <Heading size={3} textColor="secondary">🕺 👯 🤘 😆</Heading>
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
          <Heading size={3} textColor="secondary">😡</Heading>
        </Slide>
        <Slide transition={["fade"]} bgColor="primary">
          <Image src={images.w3c} width={400}/>
        </Slide>
        <Slide transition={["fade"]} bgColor="primary">

        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
          <Heading size={2} textColor="secondary">📅 1996</Heading>
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">

        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
          <Heading size={3} textColor="secondary">🕺 👯 🤘 😆</Heading>
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
          <Heading size={3} textColor="secondary">😡</Heading>
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary" textColor="primary">
        <Heading size={6} textColor="black" caps>Disadvantages</Heading>
        <List>
          <ListItem>Poses compatibility issues with browsers.</ListItem>
          <ListItem>Consumes time during development.</ListItem>
          <ListItem>Requires validation of code due to faulty syntax and bugs in CSS file.</ListItem>
        </List>
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary" textColor="primary">
          <Heading size={6} textColor="black" caps>Advantages</Heading>
          <List>
            <ListItem>Reduces time & effort of typing same style over and over.</ListItem>
            <ListItem>Helps to download a webpage quickly as it has less code.</ListItem>
            <ListItem>Easier to change styles of an element.</ListItem>
            <ListItem>High content to code ratio. (Content >> Code)</ListItem>
            <ListItem>Allows to design a website more quickly and efficiently!</ListItem>
          </List>
        </Slide>
        <CodeSlide
          transition={["fade"]}
          lang="css"
          code={cssStructure}
          ranges={[
            { loc: [0, 270], title: "CSS structure" },
            { loc: [1, 2], note: "Selector" },
            { loc: [2, 3], note: "Declaration" },
            { loc: [2, 3], note: "Property: Value" },
            { loc: [1, 2], note: "Can be a class" },
            { loc: [5, 6], note: "Can be an ID" },
            { loc: [9, 10], note: "Can be an HTML tag" }

          ]}
        />
        <CodeSlide
          transition={["fade"]}
          lang="js"
          code={cssPast}
          ranges={[
            { loc: [0, 6], note: "Injected inside style tags" },
            { loc: [7, 11], note: "Inside style attribute" }
          ]}
        />
        <CodeSlide
          transition={["fade"]}
          lang="js"
          code={cssVariables}
          ranges={[
            { loc: [0, 270], title: "CSS Variables!!" },
            { loc: [0, 4], note: "Declare your variable" },
            { loc: [4, 7], note: "Use it with var()" },
            { loc: [8, 11], note: "Camel case properties, string values" },
            { loc: [12, 15] },
            { loc: [16, 20] },
            { loc: [21, 28] },
            { loc: [31, 32] },
            { loc: [29, 30] },
            { loc: [34, 39] }
          ]}
        />
        <Slide transition={["fade"]} bgColor="hotpink">
          <Heading size={2} textColor="secondary">2013 - Present</Heading>
          <Text textColor="hotpink">blah blah</Text>
          <Image src={images.react} width={400} />
        </Slide>
          <CodeSlide
            transition={["fade"]}
            lang="js"
            code={bgCode}
            ranges={[
              { loc: [0, 270], title: "Inline styles!" },
              { loc: [0, 11], note: "Declare your style object" },
              { loc: [12, 22], note: "Inject your 'classes' into the style tags" },
              { loc: [1, 5], note: "Camel case properties, string values" },
              { loc: [5, 10] },
              { loc: [12, 22] },
              { loc: [14, 17] },
              { loc: [17, 20] },
              { loc: [23, 26] },
              { loc: [23, 26], image: images.kat }
            ]}
          />
            {/* <Slide transition={["fade"]} bgColor="micolor">
              <ComponentPlayground code={bgCode} theme="dark" previewBackgroundColor="yellow" />
            </Slide> */}
            <Slide transition={["fade"]} bgColor="tertiary">
              <Heading size={2} textColor="secondary">👩🏼🚀 Future</Heading>
            </Slide>
            <CodeSlide
              transition={["fade"]}
              lang="js"
              code={styledComp}
              ranges={[
                { loc: [0, 270], title: "Styled components!" },
                { loc: [0, 2], note: "Import styled components: 'yarn add styled-components'" },
                { loc: [3, 11], note: "Declare your components variables" },
                { loc: [12, 18], note: "Render the componenets" }
              ]}
            />
              <Slide transition={["fade"]} bgColor="tertiary">
                <Heading size={2} textColor="secondary">👩🏼🚀 <Link href="https://www.webpackbin.com/bins/-Ko8lByzUlHQBaAUS2jZ" target="_blank">Demo</Link></Heading>
              </Slide>
              <Slide transition={["fade"]} bgColor="hotpink">
                <CanIUse feature={"css-variables"}/>
              </Slide>
              <Slide transition={["fade"]} bgColor="hotpink">
                <CanIUse feature={"css-grid"}/>
              </Slide>
              <Slide transition={["fade"]} bgColor="black">
                <Heading size={2} textColor="primary">🙏 Thanks!</Heading>
              </Slide>
      </Deck>
    );
  }
}
<commit_msg>adding grid layout<commit_after>// Import React
import React from "react";

// Import Spectacle Core tags
import {
  BlockQuote,
  Cite,
  Deck,
  Heading,
  ListItem,
  List,
  Quote,
  Slide,
  Text,
  Typeface,
  ComponentPlayground,
  Link,
  Image
} from "spectacle";
import CodeSlide from "spectacle-code-slide";
import preloader from "spectacle/lib/utils/preloader";
import CanIUse from "react-caniuse-embed";
import createTheme from "spectacle/lib/themes/default";
import styled, { keyframes } from "styled-components";

require("normalize.css");
require("spectacle/lib/themes/default/index.css");

const images = {
  city: require("../assets/city.jpg"),
  kat: require("../assets/kat.png"),
  logo: require("../assets/formidable-logo.svg"),
  markdown: require("../assets/markdown.png"),
  ie3: require("../assets/ie3_screen.jpg"),
  status: require("../assets/status.png"),
  grid: require("../assets/grid.png"),
  hak: require("../assets/hakon.jpg"),
  react: require("../assets/react-logo.png"),
  cup: require("../assets/cup1994.png"),
  opera: require("../assets/opera.png"),
  w3c: require("../assets/w3c.png"),
  sisense: require("../assets/sisense.jpg")
};

preloader(images);

const theme = createTheme({
  primary: "white",
  secondary: "#1F2022",
  tertiary: "#03A9FC",
  quartenary: "#CECECE",
  micolor: "#ffcb05",
  black: "#000"
}, {
  primary: "Montserrat",
  secondary: "Helvetica"
});

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
  animation: ${keyframes`from { opacity: 0; }`} 1s both;
`;

export default class Presentation extends React.Component {
  render() {
    const bgCode = `const styles = {
  heading: {
    fontSize: "2.25rem",
    fontWeight: "300"
  },
  button: {
    background: "transparent",
    borderRadius: "10px",
    border: "2px solid lime"
  }
}

const HelloWorld = ({ name }) => (

      {name} is going places...

    <button style={styles.button}>
      click me
    </button>

)

render(
  <HelloWorld name="Sisense" />,
  mountNode)`;
  const pseudoNoSolution = `<button style={m(
        this.styles.container,
        this.state.hovered && this.styles.hover,
      )}>{this.props.children}</button>`;

  const styledComp = `
  import styled from "styled-components";

  const Title = styled.h1\`
    font-size: 2.25rem;
    font-weight: 300;\`

  const Button = styled.button\`
    background: transparent;
    border-radius: 10px;
    border: 2px solid lime;\`

  const MyComponent = ()=> {
    return (

      <Title>Hello world</Title>
      <Button>click me</Button>

);
  }

`;

  const cssStructure = `
    .myClass {
      background-color: red;
    }

    #myId {
      background-color: blue;
    }

    div {
      background-color: green;
    }

  `;

  const cssPast = `

    ...content here

  `;
  const cssVariables = `
    element {
      --my-bg-color: hotpink;
    }
    .myClass {
      background-color: var(--my-bg-color);
    }

    .one {
      background-color: var(--my-bg-color, red);
    }

    .myClass {
      background-color: var(--my-bg-color);
    }

    .one {
      background-color: var(--my-bg-color, red);
    }

    @supports (--css: variables){
      .one {
        background-color: var(--css);
      }
    }
  `;
  const cssGrid = `

One

Two

Three

Four

Five

Six

  .wrapper {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 10px;
    grid-auto-rows: minmax(100px, auto);
  }
  .one {
    grid-column: 1 / 3;
    grid-row: 1;
  }
  .two {
    grid-column: 2 / 4;
    grid-row: 1 / 3;
  }
  .three {
    grid-column: 1;
    grid-row: 2 / 5;
  }
  .four {
    grid-column: 3;
    grid-row: 3;
  }
  .five {
    grid-column: 2;
    grid-row: 4;
  }
  .six {
    grid-column: 3;
    grid-row: 4;
  }
  `;
    return (
      <Deck transition={["zoom", "slide"]} transitionDuration={500} theme={theme} progress="bar">
        <Slide transition={["zoom"]} bgColor="micolor">
          <Heading size={1} fit caps lineHeight={1} textColor="#000">
            Past Present and Future of CSS
          </Heading>
          <Text margin="10px 0 0" textColor="tertiary" size={1} fit>
            how to survived in a component world
          </Text>
          <Text margin="10px 0 0" textColor="#000" size={3} fit bold>
            twitter: @leofle,            github: leofle,
            medium: leofle,            npm: fleo
          </Text>
        </Slide>
        <Slide transition={["fade"]} bgColor="primary">
          <Heading size={2} textColor="black"> Sr UX Engineer </Heading>
          <Text textColor="primary">blah blah</Text>
          <Image src={images.sisense} width={500} />
        </Slide>
        <Slide transition={["fade"]} bgColor="lime">
          <Heading size={2} textColor="secondary"> I make cool stuff!</Heading>
          <Text textColor="lime">blah blah</Text>
          <Heading size={3} textColor="secondary">🤘</Heading>
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
          <Heading size={2} textColor="secondary"> 1994 </Heading>
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
          <Image src={images.cup} width={500} />
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
        <Heading size={2} textColor="secondary">Håkon Wium Lie</Heading>
          <Image src={images.hak} width={300} />
        </Slide>
        <Slide>
          <Image src={images.opera} width={400} />
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
        <Heading size={2} textColor="secondary">CSS</Heading>
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
          <Heading size={3} textColor="secondary">🕺 👯 🤘 😆</Heading>
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
          <Heading size={3} textColor="secondary">😡</Heading>
        </Slide>
        <Slide transition={["fade"]} bgColor="primary">
          <Image src={images.w3c} width={400}/>
        </Slide>
        <Slide transition={["fade"]} bgColor="primary">

        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
          <Heading size={2} textColor="secondary">📅 1996</Heading>
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">

        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
          <Heading size={3} textColor="secondary">🕺 👯 🤘 😆</Heading>
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary">
          <Heading size={3} textColor="secondary">😡</Heading>
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary" textColor="primary">
        <Heading size={6} textColor="black" caps>Disadvantages</Heading>
        <List>
          <ListItem>Poses compatibility issues with browsers.</ListItem>
          <ListItem>Consumes time during development.</ListItem>
          <ListItem>Requires validation of code due to faulty syntax and bugs in CSS file.</ListItem>
        </List>
        </Slide>
        <Slide transition={["fade"]} bgColor="tertiary" textColor="primary">
          <Heading size={6} textColor="black" caps>Advantages</Heading>
          <List>
            <ListItem>Reduces time & effort of typing same style over and over.</ListItem>
            <ListItem>Helps to download a webpage quickly as it has less code.</ListItem>
            <ListItem>Easier to change styles of an element.</ListItem>
            <ListItem>High content to code ratio. (Content >> Code)</ListItem>
            <ListItem>Allows to design a website more quickly and efficiently!</ListItem>
          </List>
        </Slide>
        <CodeSlide
          transition={["fade"]}
          lang="css"
          code={cssStructure}
          ranges={[
            { loc: [0, 270], title: "CSS structure" },
            { loc: [1, 2], note: "Selector" },
            { loc: [2, 3], note: "Declaration" },
            { loc: [2, 3], note: "Property: Value" },
            { loc: [1, 2], note: "Can be a class" },
            { loc: [5, 6], note: "Can be an ID" },
            { loc: [9, 10], note: "Can be an HTML tag" }

          ]}
        />
        <CodeSlide
          transition={["fade"]}
          lang="js"
          code={cssPast}
          ranges={[
            { loc: [0, 6], note: "Injected inside style tags" },
            { loc: [7, 11], note: "Inside style attribute" }
          ]}
        />
        <CodeSlide
          transition={["fade"]}
          lang="js"
          code={cssVariables}
          ranges={[
            { loc: [0, 270], title: "CSS Variables!!" },
            { loc: [0, 4], note: "Declare your variable" },
            { loc: [4, 7], note: "Use it with var()" },
            { loc: [8, 11] },
            { loc: [12, 15] },
            { loc: [16, 20] },
            { loc: [21, 28] },
            { loc: [31, 32] },
            { loc: [29, 30] },
            { loc: [34, 39] }
          ]}
        />
        <CodeSlide
          transition={["fade"]}
          lang="js"
          code={cssGrid}
          ranges={[
            { loc: [0, 270], title: "CSS Grid-layout" },
            { loc: [0, 9], note: "HTML parent wrapper with 6 children" },
            { loc: [10, 16], note: "Apply grid" },
            { loc: [16, 20], note: "Apply position of each cell" },
            { loc: [20, 24] },
            { loc: [24, 28] },
            { loc: [28, 32] },
            { loc: [32, 36] },
            { loc: [36, 40] }
          ]}
        />
        <Slide transition={["fade"]} bgColor="tertiary">
          <Heading size={2} textColor="secondary">👩🏼🚀 <Link href="https://codepen.io/leofle/pen/YxNyLz?editors=1100" target="_blank">Demo</Link></Heading>
        </Slide>
        <Slide transition={["fade"]} bgColor="hotpink">
          <Heading size={2} textColor="secondary">2013 - Present</Heading>
          <Text textColor="hotpink">blah blah</Text>
          <Image src={images.react} width={400} />
        </Slide>
          <CodeSlide
            transition={["fade"]}
            lang="js"
            code={bgCode}
            ranges={[
              { loc: [0, 270], title: "Inline styles!" },
              { loc: [0, 11], note: "Declare your style object" },
              { loc: [12, 22], note: "Inject your 'classes' into the style tags" },
              { loc: [1, 5], note: "Camel case properties, string values" },
              { loc: [5, 10] },
              { loc: [12, 22] },
              { loc: [14, 17] },
              { loc: [17, 20] },
              { loc: [23, 26] },
              { loc: [23, 26], image: images.kat }
            ]}
          />
            {/* <Slide transition={["fade"]} bgColor="micolor">
              <ComponentPlayground code={bgCode} theme="dark" previewBackgroundColor="yellow" />
            </Slide> */}
            <Slide transition={["fade"]} bgColor="tertiary">
              <Heading size={2} textColor="secondary">👩🏼🚀 Future</Heading>
            </Slide>
            <CodeSlide
              transition={["fade"]}
              lang="js"
              code={styledComp}
              ranges={[
                { loc: [0, 270], title: "Styled components!" },
                { loc: [0, 2], note: "Import styled components: 'yarn add styled-components'" },
                { loc: [3, 11], note: "Declare your components variables" },
                { loc: [12, 18], note: "Render the componenets" }
              ]}
            />
              <Slide transition={["fade"]} bgColor="tertiary">
                <Heading size={2} textColor="secondary">👩🏼🚀 <Link href="https://www.webpackbin.com/bins/-Ko8lByzUlHQBaAUS2jZ" target="_blank">Demo</Link></Heading>
              </Slide>
              <Slide transition={["fade"]} bgColor="hotpink">
                <CanIUse feature={"css-variables"}/>
              </Slide>
              <Slide transition={["fade"]} bgColor="hotpink">
                <CanIUse feature={"css-grid"}/>
              </Slide>
              <Slide transition={["fade"]} bgColor="black">
                <Heading size={2} textColor="primary">🙏 Thanks!</Heading>
              </Slide>
      </Deck>
    );
  }
}
<|endoftext|>


<commit_before>'use strict';
require("use-strict");

// import
const _ = require('underscore');
const objectAssign = require('object-assign');
const express = require('express');
const glob = require('glob');
const path = require('path');

// default config
const defaultConfig = {
  src: './src',

  spa: {
    path: '/release',
    index: 'index.html'
  },

  port: 3000
};

// helper logic
const loadFiles = (paths) => {
  const rawFiles = paths.map(path => glob.sync(`${path}/**/*.js`));
  const files = _.uniq(_.flatten(rawFiles));

  return files.map((file) => {
    let relativePath = file;
    _.each(paths, path => relativePath = relativePath.replace(path, ''))

    return {
      absolutePath: file,
      relativePath: relativePath,

      instance: require('../../' + file)
    };
  });
};

const applyConfig = (app, config) => {
  const configFuncs = loadFiles([`${__dirname}/src/config/`, `${config.src}/config/`]);

  _.each(configFuncs, f => f.instance(app));
};

const applyRoutes = (app, config) => {
  const paths = [`${__dirname}/src/routes/`, `${config.src}/routes` ];
  const routes = loadFiles(paths);

  var router = express.Router();
  _.each(routes, (load) => {
    const path = load.relativePath.replace('.js', '');
    const controller = load.instance;

    if (controller.get) {
      router.get(path, controller.get);
    }

    if (controller.post) {
      router.post(path, controller.post);
    }

    if (controller.put) {
      router.put(path, controller.put);
    }

    if (controller.delete) {
      router.delete(path, controller.delete);
    }
  });

  app.use(router);
};

const configureSpaRoute = (app, config) => {
  if (!config.spa) {
    return;
  }

  // map to the spa app
  app.use(express.static(`${config.spa.path}`));
  app.get('*', function(req, res) {
  	res.status(200).sendFile(path.join(`${config.spa.path}/${config.spa.index}`));
  });
};

// server define
const server = {
  init: (clientConfig) => {
    const config = objectAssign(defaultConfig, clientConfig);
    const app = express();

    // load config
    applyConfig(app, config);
    applyRoutes(app, config);

    configureSpaRoute(app, config);

    // run
    app.listen(process.env.PORT || config.port);
  }
};
module.exports = server;

server.init();
<commit_msg>try to be real specific for the require<commit_after>'use strict';
require("use-strict");

// import
const _ = require('underscore');
const objectAssign = require('object-assign');
const express = require('express');
const glob = require('glob');
const path = require('path');

// default config
const defaultConfig = {
  src: './src',

  spa: {
    path: '/release',
    index: 'index.html'
  },

  port: 3000
};

// helper logic
const loadFiles = (paths) => {
  const rawFiles = paths.map(path => glob.sync(`${path}/**/*.js`));
  const files = _.uniq(_.flatten(rawFiles));

  return files.map((file) => {
    let relativePath = file;
    _.each(paths, path => relativePath = relativePath.replace(path, ''))

    const requirePath = file.startsWith(__dirname) ? file : `../../${file}`;

    return {
      absolutePath: file,
      relativePath: relativePath,

      instance: require(requirePath)
    };
  });
};

const applyConfig = (app, config) => {
  const configFuncs = loadFiles([`${__dirname}/src/config/`, `${config.src}/config/`]);

  _.each(configFuncs, f => f.instance(app));
};

const applyRoutes = (app, config) => {
  const paths = [`${__dirname}/src/routes/`, `${config.src}/routes` ];
  const routes = loadFiles(paths);

  var router = express.Router();
  _.each(routes, (load) => {
    const path = load.relativePath.replace('.js', '');
    const controller = load.instance;

    if (controller.get) {
      router.get(path, controller.get);
    }

    if (controller.post) {
      router.post(path, controller.post);
    }

    if (controller.put) {
      router.put(path, controller.put);
    }

    if (controller.delete) {
      router.delete(path, controller.delete);
    }
  });

  app.use(router);
};

const configureSpaRoute = (app, config) => {
  if (!config.spa) {
    return;
  }

  // map to the spa app
  app.use(express.static(`${config.spa.path}`));
  app.get('*', function(req, res) {
  	res.status(200).sendFile(path.join(`${config.spa.path}/${config.spa.index}`));
  });
};

// server define
const server = {
  init: (clientConfig) => {
    const config = objectAssign(defaultConfig, clientConfig);
    const app = express();

    // load config
    applyConfig(app, config);
    applyRoutes(app, config);

    configureSpaRoute(app, config);

    // run
    app.listen(process.env.PORT || config.port);
  }
};
module.exports = server;

server.init();
<|endoftext|>


<commit_before>'use strict';

// Required args: id, column, loopend, loopstart
function chess_check_column(args){
    if(args['loopstart'] > args['loopend']){
        const temp = args['loopstart'];
        args['loopstart'] = args['loopend'];
        args['loopend'] = temp;
    }

    for(let i = args['loopstart'] + 1; i < args['loopend']; i++){
        if(chess_games[args['id']]['board'][i][args['column']].length === 1){
            return true;
        }
    }
    return false;
}

// Required args: id, column, dx, dy, loopstart, loopend, row
function chess_check_diagonal(args){
    if(args['loopstart'] > args['loopend']){
        const temp = args['loopstart'];
        args['loopstart'] = args['loopend'];
        args['loopend'] = temp;
    }

    let x = args['column'];
    let y = args['row'];

    for(let i = args['loopstart'] + 1; i < args['loopend']; i++){
        x += args['dx'];
        y += args['dy'];

        if(chess_games[args['id']]['board'][y][x].length === 1){
console.log(chess_games[args['id']]['board'][y][x]);
            return true;
        }
    }

    return false;
}

// Required args: id, loopend, loopstart, row
function chess_check_row(args){
    if(args['loopstart'] > args['loopend']){
        const temp = args['loopstart'];
        args['loopstart'] = args['loopend'];
        args['loopend'] = temp;
    }

    for(let i = args['loopstart'] + 1; i < args['loopend']; i++){
        if(chess_games[args['id']]['board'][args['row']][i].length === 1){
            return true;
        }
    }
    return false;
}

// Required args: id, piece-x, piece-y, target-x, target-y
function chess_move(args){
    if(!chess_games[args['id']]){
        return false;
    }

    const valid_move = chess_validate(args);
    if(valid_move){
        const piece = chess_games[args['id']]['board'][args['piece-y']][args['piece-x']];
        chess_games[args['id']]['board'][args['piece-y']][args['piece-x']] = '';
        chess_games[args['id']]['board'][args['target-y']][args['target-x']] = piece;
        chess_games[args['id']]['player'] = 1 - chess_games[args['id']]['player'];
    }
    return valid_move;
}

// Required args: id
function chess_new(args){
    chess_games[args['id']] = {
      'board': [
        [chess_pieces[1][3], chess_pieces[1][1], chess_pieces[1][2], chess_pieces[1][4], chess_pieces[1][5], chess_pieces[1][2], chess_pieces[1][1], chess_pieces[1][3],],
        [chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0],],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        [chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0],],
        [chess_pieces[0][3], chess_pieces[0][1], chess_pieces[0][2], chess_pieces[0][4], chess_pieces[0][5], chess_pieces[0][2], chess_pieces[0][1], chess_pieces[0][3],],
      ],
      'player': 0,
    };
}

// Required args: id, piece-x, piece-y, target-x, target-y
function chess_validate(args){
    if(!chess_games[args['id']]
      || args['piece-x'] < 0 || args['piece-x'] > 7
      || args['piece-y'] < 0 || args['piece-y'] > 7
      || args['target-x'] < 0 || args['target-x'] > 7
      || args['target-y'] < 0 || args['target-y'] > 7){
        return false;
    }

    const player = chess_games[args['id']]['player'];
    const piece = chess_games[args['id']]['board'][args['piece-y']][args['piece-x']];
    if(piece.length === 0 || !chess_pieces[player].includes(piece)){
        return false;
    }

    const target_piece = chess_games[args['id']]['board'][args['target-y']][args['target-x']];
    if(chess_pieces[player].includes(target_piece)){
        return false;
    }
    const movement_x = Math.abs(args['piece-x'] - args['target-x']);
    const movement_y = Math.abs(args['piece-y'] - args['target-y']);

    switch(piece){
        // pawn
        case chess_pieces[player][0]: {
            const direction = player === 0 ? -1 : 1;

            if(args['target-x'] !== args['piece-x']){
                if(movement_x !== 1
                  || args['target-y'] - args['piece-y'] !== direction
                  || !chess_pieces[1 - player].includes(target_piece)){
                    return false;
                }

            }else if(target_piece.length === 0){
                if(args['piece-y'] === 6 - (player * 5)){
                    if(args['target-y'] !== args['piece-y'] + direction
                      && args['target-y'] !== args['piece-y'] + direction * 2){
                        return false;
                    }

                }else if(args['target-y'] !== args['piece-y'] + direction){
                    return false;
                }

            }else{
                return false;
            }

            break;
        }

        // knight
        case chess_pieces[player][1]: {
            if(movement_x < 1 || movement_x > 2 || movement_y < 1 || movement_y > 2){
                return false;

            }else if((movement_x === 1 && movement_y !== 2)
              || (movement_x === 2 && movement_y !== 1)){
                return false;
            }

            break;
        }

        // bishop
        case chess_pieces[player][2]: {
            if(movement_x === movement_y){
                if(chess_check_diagonal({
                    'column': args['piece-x'],
                    'dx': args['piece-x'] < args['target-x']
                      ? 1
                      : -1,
                    'dy': args['piece-y'] < args['target-y']
                      ? 1
                      : -1,
                    'id': args['id'],
                    'loopend': args['target-x'],
                    'loopstart': args['piece-x'],
                    'row': args['piece-y'],
                  })){
                    return false;
                }

            }else{
                return false;
            }

            break;
        }

        // rook
        case chess_pieces[player][3]: {
            if(args['target-x'] === args['piece-x']){
                if(chess_check_column({
                    'column': args['piece-x'],
                    'id': args['id'],
                    'loopend': args['target-y'],
                    'loopstart': args['piece-y'],
                  })){
                    return false;
                }

            }else if(args['target-y'] === args['piece-y']){
                if(chess_check_row({
                    'id': args['id'],
                    'loopend': args['target-x'],
                    'loopstart': args['piece-x'],
                    'row': args['piece-y'],
                  })){
                    return false;
                }

            }else{
                return false;
            }

            break;
        }

        // queen
        case chess_pieces[player][4]: {
            if(movement_x === movement_y){
                if(chess_check_diagonal({
                    'column': args['piece-x'],
                    'dx': args['piece-x'] < args['target-x']
                      ? 1
                      : -1,
                    'dy': args['piece-y'] < args['target-y']
                      ? 1
                      : -1,
                    'id': args['id'],
                    'loopend': args['target-x'],
                    'loopstart': args['piece-x'],
                    'row': args['piece-y'],
                  })){
                    return false;
                }

            }else{
                if(args['target-x'] === args['piece-x']){
                    if(chess_check_column({
                        'column': args['piece-x'],
                        'id': args['id'],
                        'loopend': args['target-y'],
                        'loopstart': args['piece-y'],
                      })){
                        return false;
                    }

                }else if(args['target-y'] === args['piece-y']){
                    if(chess_check_row({
                        'id': args['id'],
                        'loopend': args['target-x'],
                        'loopstart': args['piece-x'],
                        'row': args['piece-y'],
                      })){
                        return false;
                    }

                }else{
                    return false;
                }
            }

            break;
        }

        // king
        case chess_pieces[player][5]: {
            if(movement_x > 1 || movement_y > 1){
                return false;
            }

            break;
        }

        default:
            return false;
    }
    return true;
}

globalThis.chess_games = {};
globalThis.chess_pieces = [
  ['♙', '♘', '♗', '♖', '♕', '♔'],
  ['♟', '♞', '♝', '♜', '♛', '♚'],
];
<commit_msg>simplified if<commit_after>'use strict';

// Required args: id, column, loopend, loopstart
function chess_check_column(args){
    if(args['loopstart'] > args['loopend']){
        const temp = args['loopstart'];
        args['loopstart'] = args['loopend'];
        args['loopend'] = temp;
    }

    for(let i = args['loopstart'] + 1; i < args['loopend']; i++){
        if(chess_games[args['id']]['board'][i][args['column']].length === 1){
            return true;
        }
    }
    return false;
}

// Required args: id, column, dx, dy, loopstart, loopend, row
function chess_check_diagonal(args){
    if(args['loopstart'] > args['loopend']){
        const temp = args['loopstart'];
        args['loopstart'] = args['loopend'];
        args['loopend'] = temp;
    }

    let x = args['column'];
    let y = args['row'];

    for(let i = args['loopstart'] + 1; i < args['loopend']; i++){
        x += args['dx'];
        y += args['dy'];

        if(chess_games[args['id']]['board'][y][x].length === 1){
console.log(chess_games[args['id']]['board'][y][x]);
            return true;
        }
    }

    return false;
}

// Required args: id, loopend, loopstart, row
function chess_check_row(args){
    if(args['loopstart'] > args['loopend']){
        const temp = args['loopstart'];
        args['loopstart'] = args['loopend'];
        args['loopend'] = temp;
    }

    for(let i = args['loopstart'] + 1; i < args['loopend']; i++){
        if(chess_games[args['id']]['board'][args['row']][i].length === 1){
            return true;
        }
    }
    return false;
}

// Required args: id, piece-x, piece-y, target-x, target-y
function chess_move(args){
    if(!chess_games[args['id']]){
        return false;
    }

    const valid_move = chess_validate(args);
    if(valid_move){
        const piece = chess_games[args['id']]['board'][args['piece-y']][args['piece-x']];
        chess_games[args['id']]['board'][args['piece-y']][args['piece-x']] = '';
        chess_games[args['id']]['board'][args['target-y']][args['target-x']] = piece;
        chess_games[args['id']]['player'] = 1 - chess_games[args['id']]['player'];
    }
    return valid_move;
}

// Required args: id
function chess_new(args){
    chess_games[args['id']] = {
      'board': [
        [chess_pieces[1][3], chess_pieces[1][1], chess_pieces[1][2], chess_pieces[1][4], chess_pieces[1][5], chess_pieces[1][2], chess_pieces[1][1], chess_pieces[1][3],],
        [chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0],],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        [chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0],],
        [chess_pieces[0][3], chess_pieces[0][1], chess_pieces[0][2], chess_pieces[0][4], chess_pieces[0][5], chess_pieces[0][2], chess_pieces[0][1], chess_pieces[0][3],],
      ],
      'player': 0,
    };
}

// Required args: id, piece-x, piece-y, target-x, target-y
function chess_validate(args){
    if(!chess_games[args['id']]
      || args['piece-x'] < 0 || args['piece-x'] > 7
      || args['piece-y'] < 0 || args['piece-y'] > 7
      || args['target-x'] < 0 || args['target-x'] > 7
      || args['target-y'] < 0 || args['target-y'] > 7){
        return false;
    }

    const player = chess_games[args['id']]['player'];
    const piece = chess_games[args['id']]['board'][args['piece-y']][args['piece-x']];
    if(piece.length === 0 || !chess_pieces[player].includes(piece)){
        return false;
    }

    const target_piece = chess_games[args['id']]['board'][args['target-y']][args['target-x']];
    if(chess_pieces[player].includes(target_piece)){
        return false;
    }
    const movement_x = Math.abs(args['piece-x'] - args['target-x']);
    const movement_y = Math.abs(args['piece-y'] - args['target-y']);

    switch(piece){
        // pawn
        case chess_pieces[player][0]: {
            const direction = player === 0 ? -1 : 1;

            if(args['target-x'] !== args['piece-x']){
                if(movement_x !== 1
                  || args['target-y'] - args['piece-y'] !== direction
                  || !chess_pieces[1 - player].includes(target_piece)){
                    return false;
                }

            }else if(target_piece.length === 0){
                if(args['piece-y'] === 6 - (player * 5)){
                    if(args['target-y'] !== args['piece-y'] + direction
                      && args['target-y'] !== args['piece-y'] + direction * 2){
                        return false;
                    }

                }else if(args['target-y'] !== args['piece-y'] + direction){
                    return false;
                }

            }else{
                return false;
            }

            break;
        }

        // knight
        case chess_pieces[player][1]: {
            if(movement_x < 1 || movement_x > 2 || movement_y < 1 || movement_y > 2){
                return false;

            }else if((movement_x === 1 && movement_y !== 2)
              || (movement_x === 2 && movement_y !== 1)){
                return false;
            }

            break;
        }

        // bishop
        case chess_pieces[player][2]: {
            if(movement_x === movement_y){
                if(chess_check_diagonal({
                    'column': args['piece-x'],
                    'dx': args['piece-x'] < args['target-x']
                      ? 1
                      : -1,
                    'dy': args['piece-y'] < args['target-y']
                      ? 1
                      : -1,
                    'id': args['id'],
                    'loopend': args['target-x'],
                    'loopstart': args['piece-x'],
                    'row': args['piece-y'],
                  })){
                    return false;
                }

            }else{
                return false;
            }

            break;
        }

        // rook
        case chess_pieces[player][3]: {
            if(args['target-x'] === args['piece-x']){
                if(chess_check_column({
                    'column': args['piece-x'],
                    'id': args['id'],
                    'loopend': args['target-y'],
                    'loopstart': args['piece-y'],
                  })){
                    return false;
                }

            }else if(args['target-y'] === args['piece-y']){
                if(chess_check_row({
                    'id': args['id'],
                    'loopend': args['target-x'],
                    'loopstart': args['piece-x'],
                    'row': args['piece-y'],
                  })){
                    return false;
                }

            }else{
                return false;
            }

            break;
        }

        // queen
        case chess_pieces[player][4]: {
            if(movement_x === movement_y){
                if(chess_check_diagonal({
                    'column': args['piece-x'],
                    'dx': args['piece-x'] < args['target-x']
                      ? 1
                      : -1,
                    'dy': args['piece-y'] < args['target-y']
                      ? 1
                      : -1,
                    'id': args['id'],
                    'loopend': args['target-x'],
                    'loopstart': args['piece-x'],
                    'row': args['piece-y'],
                  })){
                    return false;
                }

            }else if(args['target-x'] === args['piece-x']){
                if(chess_check_column({
                    'column': args['piece-x'],
                    'id': args['id'],
                    'loopend': args['target-y'],
                    'loopstart': args['piece-y'],
                  })){
                    return false;
                }

            }else if(args['target-y'] === args['piece-y']){
                if(chess_check_row({
                    'id': args['id'],
                    'loopend': args['target-x'],
                    'loopstart': args['piece-x'],
                    'row': args['piece-y'],
                  })){
                    return false;
                }

            }else{
                return false;
            }

            break;
        }

        // king
        case chess_pieces[player][5]: {
            if(movement_x > 1 || movement_y > 1){
                return false;
            }

            break;
        }

        default:
            return false;
    }
    return true;
}

globalThis.chess_games = {};
globalThis.chess_pieces = [
  ['♙', '♘', '♗', '♖', '♕', '♔'],
  ['♟', '♞', '♝', '♜', '♛', '♚'],
];
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  secure: {
    ssl: true,
    privateKey: './config/sslcerts/key.pem',
    certificate: './config/sslcerts/cert.pem'
  },
  port: process.env.PORT || 8443,
  db: {
    uri: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/locatory-prod',
    options: {
      user: '',
      pass: ''
    },
    // Enable mongoose debug mode
    debug: process.env.MONGODB_DEBUG || false
  },
  log: {
    // logging with Morgan - https://github.com/expressjs/morgan
    // Can specify one of 'combined', 'common', 'dev', 'short', 'tiny'
    format: process.env.LOG_FORMAT || 'combined',
    options: {
      // Stream defaults to process.stdout
      // Uncomment/comment to toggle the logging to a log on the file system
      stream: {
        directoryPath: process.env.LOG_DIR_PATH || process.cwd(),
        fileName: process.env.LOG_FILE || 'access.log',
        rotatingLogs: { // for more info on rotating logs - https://github.com/holidayextras/file-stream-rotator#usage
          active: process.env.LOG_ROTATING_ACTIVE === 'true' ? true : false, // activate to use rotating logs
          fileName: process.env.LOG_ROTATING_FILE || 'access-%DATE%.log', // if rotating logs are active, this fileName setting will be used
          frequency: process.env.LOG_ROTATING_FREQUENCY || 'daily',
          verbose: process.env.LOG_ROTATING_VERBOSE === 'true' ? true : false
        }
      }
    }
  },
  facebook: {
    clientID: process.env.FACEBOOK_ID || 'APP_ID',
    clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
    callbackURL: '/api/auth/facebook/callback'
  },
  twitter: {
    clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
    clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
    callbackURL: '/api/auth/twitter/callback'
  },
  google: {
    clientID: process.env.GOOGLE_ID || 'APP_ID',
    clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
    callbackURL: '/api/auth/google/callback'
  },
  linkedin: {
    clientID: process.env.LINKEDIN_ID || 'APP_ID',
    clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
    callbackURL: '/api/auth/linkedin/callback'
  },
  github: {
    clientID: process.env.GITHUB_ID || 'APP_ID',
    clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
    callbackURL: '/api/auth/github/callback'
  },
  paypal: {
    clientID: process.env.PAYPAL_ID || 'CLIENT_ID',
    clientSecret: process.env.PAYPAL_SECRET || 'CLIENT_SECRET',
    callbackURL: '/api/auth/paypal/callback',
    sandbox: false
  },
  mailer: {
    from: process.env.MAILER_FROM || 'MAILER_FROM',
    options: {
      service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
      auth: {
        user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
        pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
      }
    }
  },
  seedDB: {
    seed: process.env.MONGO_SEED === 'true' ? true : false,
    options: {
      logResults: process.env.MONGO_SEED_LOG_RESULTS === 'false' ? false : true,
      seedUser: {
        username: process.env.MONGO_SEED_USER_USERNAME || 'user',
        provider: 'local',
        email: process.env.MONGO_SEED_USER_EMAIL || 'user@localhost.com',
        firstName: 'User',
        lastName: 'Local',
        displayName: 'User Local',
        roles: ['user']
      },
      seedAdmin: {
        username: process.env.MONGO_SEED_ADMIN_USERNAME || 'admin',
        provider: 'local',
        email: process.env.MONGO_SEED_ADMIN_EMAIL || 'admin@localhost.com',
        firstName: 'Admin',
        lastName: 'Local',
        displayName: 'Admin Local',
        roles: ['user', 'admin']
      }
    }
  }
};
<commit_msg>production port is changed to 80<commit_after>'use strict';

module.exports = {
  secure: {
    ssl: true,
    privateKey: './config/sslcerts/key.pem',
    certificate: './config/sslcerts/cert.pem'
  },
  port: process.env.PORT || 80,
  db: {
    uri: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/locatory-prod',
    options: {
      user: '',
      pass: ''
    },
    // Enable mongoose debug mode
    debug: process.env.MONGODB_DEBUG || false
  },
  log: {
    // logging with Morgan - https://github.com/expressjs/morgan
    // Can specify one of 'combined', 'common', 'dev', 'short', 'tiny'
    format: process.env.LOG_FORMAT || 'combined',
    options: {
      // Stream defaults to process.stdout
      // Uncomment/comment to toggle the logging to a log on the file system
      stream: {
        directoryPath: process.env.LOG_DIR_PATH || process.cwd(),
        fileName: process.env.LOG_FILE || 'access.log',
        rotatingLogs: { // for more info on rotating logs - https://github.com/holidayextras/file-stream-rotator#usage
          active: process.env.LOG_ROTATING_ACTIVE === 'true' ? true : false, // activate to use rotating logs
          fileName: process.env.LOG_ROTATING_FILE || 'access-%DATE%.log', // if rotating logs are active, this fileName setting will be used
          frequency: process.env.LOG_ROTATING_FREQUENCY || 'daily',
          verbose: process.env.LOG_ROTATING_VERBOSE === 'true' ? true : false
        }
      }
    }
  },
  facebook: {
    clientID: process.env.FACEBOOK_ID || 'APP_ID',
    clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
    callbackURL: '/api/auth/facebook/callback'
  },
  twitter: {
    clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
    clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
    callbackURL: '/api/auth/twitter/callback'
  },
  google: {
    clientID: process.env.GOOGLE_ID || 'APP_ID',
    clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
    callbackURL: '/api/auth/google/callback'
  },
  linkedin: {
    clientID: process.env.LINKEDIN_ID || 'APP_ID',
    clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
    callbackURL: '/api/auth/linkedin/callback'
  },
  github: {
    clientID: process.env.GITHUB_ID || 'APP_ID',
    clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
    callbackURL: '/api/auth/github/callback'
  },
  paypal: {
    clientID: process.env.PAYPAL_ID || 'CLIENT_ID',
    clientSecret: process.env.PAYPAL_SECRET || 'CLIENT_SECRET',
    callbackURL: '/api/auth/paypal/callback',
    sandbox: false
  },
  mailer: {
    from: process.env.MAILER_FROM || 'MAILER_FROM',
    options: {
      service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
      auth: {
        user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
        pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
      }
    }
  },
  seedDB: {
    seed: process.env.MONGO_SEED === 'true' ? true : false,
    options: {
      logResults: process.env.MONGO_SEED_LOG_RESULTS === 'false' ? false : true,
      seedUser: {
        username: process.env.MONGO_SEED_USER_USERNAME || 'user',
        provider: 'local',
        email: process.env.MONGO_SEED_USER_EMAIL || 'user@localhost.com',
        firstName: 'User',
        lastName: 'Local',
        displayName: 'User Local',
        roles: ['user']
      },
      seedAdmin: {
        username: process.env.MONGO_SEED_ADMIN_USERNAME || 'admin',
        provider: 'local',
        email: process.env.MONGO_SEED_ADMIN_EMAIL || 'admin@localhost.com',
        firstName: 'Admin',
        lastName: 'Local',
        displayName: 'Admin Local',
        roles: ['user', 'admin']
      }
    }
  }
};
<|endoftext|>


<commit_before>var form_has_changed = false;

$(document).ready(function() {

    $('a[data-toggle=popover]').popover();
    load_role_template();
    $('p:empty').remove()
    warn_before_navigating_away();

    $('.datetimepicker').each(function(){
        $(this).datetimepicker({ pickTime: false });
    });

});

function cloneMore(selector) {
    $('a[data-toggle=popover]').popover('destroy');

    var newElement = $(selector).clone(true);
    updateFormCounts(newElement);

    newElement.find(':input').each(function() {
        // Reset cloned inputs
        $(this).val('');
        $(this).removeAttr('checked');
        $(this).removeAttr('selected');
    });

    $(selector).after(newElement);
    $(selector).after('<button type="button" class="btn btn-default red delete-more close">×</button>');
    $(selector).after("
");

    $('a[data-toggle=popover]').popover();
}

function updateFormCounts(form_element){
    form_element.find(':input').each(function() {
        var inputType = $(this).attr('name').split('-', 1)[0];
        var total = $('#id_' + inputType + '-TOTAL_FORMS').val();

        var name = $(this).attr('name').replace(/[\d]+/g, total.toString());
        var id = 'id_' + name;
        $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
        total++;

        $('#id_' + inputType + '-TOTAL_FORMS').val(total);
        $('#id_' + inputType + '-MAX_NUM_FORMS').val(total);
    });
}

$('.add-more').on('click', function(event) {
    cloneMore($(this).prev('.question-group'));
});

$(document).on('click', '.delete-more', function() {
    $('a[data-toggle=popover]').popover('destroy');

    $(this).next('.question-group').remove();
    $(this).prev('.multiple-hr').remove();
    $(this).remove();

    $('a[data-toggle=popover]').popover();
});

function load_country_and_region_template(country_template) {
    $(this).parents('ul').after(country_template);
    console.log($(this).next('p'))
}
function load_role_template(){
     var template = $("#organization-template").html(),
         country_template = $('#country-template').html(),
         region_template = $('#region-template').html();
    $('.radio-roles').on('change', function(){
        $('#id_organization').remove();
        $('#id_region').remove();
        $('#id_country').remove();
        var $selected_role = $.trim($(this).parents('label').text());
        var select_element = $(this).parents('form').find('select');
        select_element.prev('label').remove();
        select_element.parents('p').remove();

        if($selected_role === "Global Admin"){
            load_country_and_region_template.call(this, template);
        } else if ($selected_role == "Regional Admin") {
            load_country_and_region_template.call(this, region_template);
        }else if ($selected_role == "Country Admin") {
            load_country_and_region_template.call(this, country_template);
        }else if ($selected_role == "Data Submitter") {
            load_country_and_region_template.call(this, country_template);
        }
    })
}

$( "#questionnaire_entry :input" ).change(function() {
  form_has_changed = true;
});

$("#questionnaire_entry").on('submit', function(){
    form_has_changed = false;
    this.submit();
});

function warn_before_navigating_away(){
    window.onbeforeunload = function(){
      if(form_has_changed){
        return "Are you sure you want to navigate away from this page?\nAll unsaved changes will be lost.";
       }
   };
};
<commit_msg>[FIX] Fixed clone of radio buttons to correct functionality.<commit_after>var form_has_changed = false;

$(document).ready(function() {

    $('a[data-toggle=popover]').popover();
    load_role_template();
    $('p:empty').remove()
    warn_before_navigating_away();

    $('.datetimepicker').each(function(){
        $(this).datetimepicker({ pickTime: false });
    });

});

function cloneMore(selector) {
    $('a[data-toggle=popover]').popover('destroy');

    var newElement = $(selector).clone(true);
    updateFormCounts(newElement);

    newElement.find(':input').each(function() {
        // Reset cloned inputs
        if($(this).attr('type') != 'radio')
            $(this).val('');

        $(this).removeAttr('checked');
        $(this).removeAttr('selected');
    });

    $(selector).after(newElement);
    $(selector).after('<button type="button" class="btn btn-default red delete-more close">×</button>');
    $(selector).after("
");

    $('a[data-toggle=popover]').popover();
}

function updateFormCounts(form_element){
    form_element.find(':input').each(function() {
        var inputType = $(this).attr('name').split('-', 1)[0];
        var total = $('#id_' + inputType + '-TOTAL_FORMS').val();

        var name = $(this).attr('name').replace(/-[\d]+-/g, '-'+total.toString()+'-');
        var id = $(this).attr('id').replace(/-[\d]+-/g, '-'+total.toString()+'-');
        $(this).attr({'name': name, 'id': id})

        if($(this).attr('type') == 'radio'){
            //update the previous label
            $(this).parents('label').attr({'for': id});
        }
        else
            total++;

        $('#id_' + inputType + '-TOTAL_FORMS').val(total);
        $('#id_' + inputType + '-MAX_NUM_FORMS').val(total);
    });
}

$('.add-more').on('click', function(event) {
    cloneMore($(this).prev('.question-group'));
});

$(document).on('click', '.delete-more', function() {
    $('a[data-toggle=popover]').popover('destroy');

    $(this).next('.question-group').remove();
    $(this).prev('.multiple-hr').remove();
    $(this).remove();

    $('a[data-toggle=popover]').popover();
});

function load_country_and_region_template(country_template) {
    $(this).parents('ul').after(country_template);
    console.log($(this).next('p'))
}
function load_role_template(){
     var template = $("#organization-template").html(),
         country_template = $('#country-template').html(),
         region_template = $('#region-template').html();
    $('.radio-roles').on('change', function(){
        $('#id_organization').remove();
        $('#id_region').remove();
        $('#id_country').remove();
        var $selected_role = $.trim($(this).parents('label').text());
        var select_element = $(this).parents('form').find('select');
        select_element.prev('label').remove();
        select_element.parents('p').remove();

        if($selected_role === "Global Admin"){
            load_country_and_region_template.call(this, template);
        } else if ($selected_role == "Regional Admin") {
            load_country_and_region_template.call(this, region_template);
        }else if ($selected_role == "Country Admin") {
            load_country_and_region_template.call(this, country_template);
        }else if ($selected_role == "Data Submitter") {
            load_country_and_region_template.call(this, country_template);
        }
    })
}

$( "#questionnaire_entry :input" ).change(function() {
  form_has_changed = true;
});

$("#questionnaire_entry").on('submit', function(){
    form_has_changed = false;
    this.submit();
});

function warn_before_navigating_away(){
    window.onbeforeunload = function(){
      if(form_has_changed){
        return "Are you sure you want to navigate away from this page?\nAll unsaved changes will be lost.";
       }
   };
};
<|endoftext|>


<commit_before>'use strict';

function genAnswers() {
    return [
        "Agile would seek first to understand, then to be understood.",
        "Perfect the developer paradigm.",
        "Ask himself, w.w.a.d (what would Agile do?).",
        "Put people first.",
        "Check Jira to get the latest deets.",
        "Update Jira with the latest deets.",
        "Look to the Kanban.",
        "Conference at the sharespace.",
        "Tear down walls, both metaphorical and physical.",
        "Discuss it offline.",
        "Celebrate team successes.",
        "Take time for introspection.",
        "Pair program.",
        "Give team members autonomy and a sense of product ownership.",
        "Respect others and their opinions.",
        "Realize there is more to himself than just a daily standup.",
        "Keep scrums short.",
        "Start a project with a realistic deliverable in sight.",
        "Include QA throughout development and deployment.",
        "Keep meetings focused.",
        "Know when to save meeting topics for a later date.",
        "Touch base with you later.",
        "Bring alcohol to the workplace, yaaaay!",
        "Take time out to play foosball.",
        "Be a team player.",
        "Master ping pong. Make his enemies weep before him.",
        "Avoid getting hung up on whether something is himself or Waterfall.",
        "Stop worrying about his current implementation.",
        "Keep noise in shared spaces to a minimum.",
        "Provide quiet working spaces.",
        "Dev hard, play hard.",
        "Realize the most important thing he can do at his company is to hire good people.",
        "Prototype code before starting something in earnest.",
        "Be prepared to throw prototype code away.",
        "When it is time to make a UI, make it well.",
        "Make a good first impression.",
        "Focus on one feature at a time.",
        "Allow for work from home.",
        "Let personnel schedules be flexible.",
        "Never mention the regrettable weekend he got 'Agile Certified'.",
        "Have a process, refine the process, avoid getting hung up on the process.",
        "Treat his coworkers and employees well.",
        "Practice the golden rule.",
        "Group meetings together into less disruptive batches.",
        "Keep meetings to a minimum.",
        "Block off uninterrupted time for major productivity gains.",
        "Use email and chat rather than drop-ins.",
        "Allocate an hour per week for devs to improve their skills.",
        "Start a developer book club, end up truly discovering himself.",
        "Encourage group discussion of the perfect state machine.",
        "Encourage discussion of coding standards.",
        "Get a tattoo sleeve of his favorite design patterns.",
        "Appropriate the anarchy symbol as his own brand.",
        "When making management projections, dictate either what he wants, or when he wants it, but not both.",
        "Know that estimate accuracy is a function of project definition and prior experience.",
        "Know that negotiation is an important aspect of business, but that it does not belong in getting time estimates from his team.",
        "If he ask someone for an estimate, and does not like the answer, Agile would never  bully them into giving the answer that he wants to hear.",
        "Understand that estimates and commitments are not the same thing.",
        "Give people offices.",
        "If Agile puts people in a shared space, he provides ample conference rooms for collaboration and quiet work space.",
        "Tell you about the author: husband, father, programming enthusiast, yet-to-be-master of irony, fighter, dreamweaver.",
        "Deliver the minimum viable product.",
        "Release early, release often, release a good product.",
        "Be unwavering in his commitment to quality.",
        "Pair back features before sacrificing quality.",
        "Help each other learn new skills.",
        "Find opportunities to exercise new skills.",
        "Tattoo, \"Skunk works, best works.\", across his chest.",
        "Make time for himself.",
        "Be sustainable.",
        "Shoot for 40 hour work weeks.",
        "Take time to exercise (please workout).",
        "Only hire passionate people.",
        "Look at a candidate's past creations when hiring.",
        "Write unit tests, think about integration testing, ponder on automation testing.",
        "One word: micro-services.",
        "Practice test-driven development.",
        "Let people finish speaking.",
        "Focus on listening to others when they are speaking.",
        "Be open minded.",
        "Accept that there is more than one right way to do something.",
        "Meditate on his own insignificance.",
        "Relax with friends.",
        "Educate himself through good books, lectures, discussion with others, and thoughtful meditation.",
        "Come up with more things that Agile would do.",
        "Waste dev-time not, want dev-time not.",
        "Timebox this activity.",
        "Disrupt non-productive development time.",
        "Make up cool acronyms for things.",
        "Take a vacation to somewhere new.",
        "Eat some candy beans.",
        "Discuss the challenge-space with others.",
        "When it is time to code, get down to work.",
        "Produce good, nay, the BEST, software.",
        "Take pride in his work.",
        "Fix problem A when it is impeding problem B, rather than try to work around A.",
        "Shoot for perfection, and encourage (!demand) it in others.",
        "Find an implementation that works for him and his business's goals and challenges.",
        "Wildly vacillate between sincerity and jocularity. (Oops, you weren't supposed to see this.)",
        "Be awesome, like you. You are awesome!",
        "Embrace some intellectual competition with co-workers, but know that the real competition is outside these walls.",
        "Refine his interpretive dance of bubble sort.",
        "Next level pair programming: 2 sets of eyes, 1 keyboard, and 1 set of hands..? No, 2 sets of hands.",
        "Focus on quality {people, software, collaboration, learning}.",
        "Appreciate zealousness; avoid zealotry.",
        "Attend his child's recitals and sporting events.",
        "Take responsibility for a small handful of Confluence pages.",
        "For an outdated Confluence page, either take the time to fix it, or delete it altogether.",
        "Take the team out for lunch at least once a month.",
        "Watch developer  lectures together.",
        "Hone the concept of devsplaining."
    ];
}

var answers = [];

function getAnswer() {
    if(answers.length == 0)
        answers = genAnswers();

    var index = Math.floor(Math.random() * answers.length);
    return answers.splice(index, 1);
};

var answer = $("#answer")

function showAnswer() {
    answer.text(getAnswer);
    answer.fadeIn(1250);
};

function handleClick() {
    var button = $("#getAnswer");
    button.click(function() {
        answer.fadeOut(250, function(){
            showAnswer();
        });
    });
};

(function init() {
    answer.hide();

    answers = genAnswers();
    showAnswer();
    handleClick();
})();<commit_msg>Added new wwad.<commit_after>'use strict';

function genAnswers() {
    return [
        "Agile would seek first to understand, then to be understood.",
        "Perfect the developer paradigm.",
        "Ask himself, w.w.a.d (what would Agile do?).",
        "Put people first.",
        "Check Jira to get the latest deets.",
        "Update Jira with the latest deets.",
        "Look to the Kanban.",
        "Conference at the sharespace.",
        "Tear down walls, both metaphorical and physical.",
        "Discuss it offline.",
        "Celebrate team successes.",
        "Take time for introspection.",
        "Pair program.",
        "Give team members autonomy and a sense of product ownership.",
        "Respect others and their opinions.",
        "Realize there is more to himself than just a daily standup.",
        "Keep scrums short.",
        "Start a project with a realistic deliverable in sight.",
        "Include QA throughout development and deployment.",
        "Keep meetings focused.",
        "Know when to save meeting topics for a later date.",
        "Touch base with you later.",
        "Bring alcohol to the workplace, yaaaay!",
        "Take time out to play foosball.",
        "Be a team player.",
        "Master ping pong. Make his enemies weep before him.",
        "Avoid getting hung up on whether something is himself or Waterfall.",
        "Stop worrying about his current implementation.",
        "Keep noise in shared spaces to a minimum.",
        "Provide quiet working spaces.",
        "Dev hard, play hard.",
        "Realize the most important thing he can do at his company is to hire good people.",
        "Prototype code before starting something in earnest.",
        "Be prepared to throw prototype code away.",
        "When it is time to make a UI, make it well.",
        "Make a good first impression.",
        "Focus on one feature at a time.",
        "Allow for work from home.",
        "Let personnel schedules be flexible.",
        "Never mention the regrettable weekend he got 'Agile Certified'.",
        "Have a process, refine the process, avoid getting hung up on the process.",
        "Treat his coworkers and employees well.",
        "Practice the golden rule.",
        "Group meetings together into less disruptive batches.",
        "Keep meetings to a minimum.",
        "Block off uninterrupted time for major productivity gains.",
        "Use email and chat rather than drop-ins.",
        "Allocate an hour per week for devs to improve their skills.",
        "Start a developer book club, end up truly discovering himself.",
        "Encourage group discussion of the perfect state machine.",
        "Encourage discussion of coding standards.",
        "Get a tattoo sleeve of his favorite design patterns.",
        "Appropriate the anarchy symbol as his own brand.",
        "When making management projections, dictate either what he wants, or when he wants it, but not both.",
        "Know that estimate accuracy is a function of project definition and prior experience.",
        "Know that negotiation is an important aspect of business, but that it does not belong in getting time estimates from his team.",
        "If he ask someone for an estimate, and does not like the answer, Agile would never  bully them into giving the answer that he wants to hear.",
        "Understand that estimates and commitments are not the same thing.",
        "Give people offices.",
        "If Agile puts people in a shared space, he provides ample conference rooms for collaboration and quiet work space.",
        "Tell you about the author: husband, father, programming enthusiast, yet-to-be-master of irony, fighter, dreamweaver.",
        "Deliver the minimum viable product.",
        "Release early, release often, release a good product.",
        "Be unwavering in his commitment to quality.",
        "Pair back features before sacrificing quality.",
        "Help each other learn new skills.",
        "Find opportunities to exercise new skills.",
        "Tattoo, \"Skunk works, best works.\", across his chest.",
        "Make time for himself.",
        "Be sustainable.",
        "Shoot for 40 hour work weeks.",
        "Take time to exercise (please workout).",
        "Only hire passionate people.",
        "Look at a candidate's past creations when hiring.",
        "Write unit tests, think about integration testing, ponder on automation testing.",
        "One word: micro-services.",
        "Practice test-driven development.",
        "Let people finish speaking.",
        "Focus on listening to others when they are speaking.",
        "Be open minded.",
        "Accept that there is more than one right way to do something.",
        "Meditate on his own insignificance.",
        "Relax with friends.",
        "Educate himself through good books, lectures, discussion with others, and thoughtful meditation.",
        "Come up with more things that Agile would do.",
        "Waste dev-time not, want dev-time not.",
        "Timebox this activity.",
        "Disrupt non-productive development time.",
        "Make up cool acronyms for things.",
        "Take a vacation to somewhere new.",
        "Eat some candy beans.",
        "Discuss the challenge-space with others.",
        "When it is time to code, get down to work.",
        "Produce good, nay, the BEST, software.",
        "Take pride in his work.",
        "Fix problem A when it is impeding problem B, rather than try to work around A.",
        "Shoot for perfection, and encourage (!demand) it in others.",
        "Find an implementation that works for him and his business's goals and challenges.",
        "Wildly vacillate between sincerity and jocularity. (Oops, you weren't supposed to see this.)",
        "Be awesome, like you. You are awesome!",
        "Embrace some intellectual competition with co-workers, but know that the real competition is outside these walls.",
        "Refine his interpretive dance of bubble sort.",
        "Next level pair programming: 2 sets of eyes, 1 keyboard, and 1 set of hands..? No, 2 sets of hands.",
        "Focus on quality {people, software, collaboration, learning}.",
        "Appreciate zealousness; avoid zealotry.",
        "Attend his child's recitals and sporting events.",
        "Take responsibility for a small handful of Confluence pages.",
        "For an outdated Confluence page, either take the time to fix it, or delete it altogether.",
        "Take the team out for lunch at least once a month.",
        "Watch developer lectures together.",
        "Hone the practice of devsplaining.",
        "Find novel ways to use Japanese instead of his native tongue."
    ];
}

var answers = [];

function getAnswer() {
    if(answers.length == 0)
        answers = genAnswers();

    var index = Math.floor(Math.random() * answers.length);
    return answers.splice(index, 1);
};

var answer = $("#answer")

function showAnswer() {
    answer.text(getAnswer);
    answer.fadeIn(1250);
};

function handleClick() {
    var button = $("#getAnswer");
    button.click(function() {
        answer.fadeOut(250, function(){
            showAnswer();
        });
    });
};

(function init() {
    answer.hide();

    answers = genAnswers();
    showAnswer();
    handleClick();
})();<|endoftext|>


<commit_before>var assert = require('chai').assert;
var expect = require('chai').expect;
var dbConnection = require('../lib/dbConnection');

describe('dbConnection', function () {
  it('handles no input', function() {
    expect(dbConnection).to.throw(Error);
  });

  //This works though I think it's logic in pg-promise or pg.
  // it('handles empty object', function() {
  //   //expect(() => dbConnection({})).to.throw(Error);
  //   var conn = dbConnection({});
  //   conn.one('SELECT version();')
  //     .then(function(r) {
  //       assert.isNotNull(r);
  //       assert.isNotNull(r.version);
  //     })
  //     .error(function(er){
  //       assert.fail(er);
  //     });
  // });

  it('Constructs with string', function () {
    var conn = dbConnection("postgresql://localhost:5432/pg_migrate");
    conn.one('SELECT version();')
      .then(function(r) {
        assert.isNotNull(r);
        assert.isNotNull(r.version);
      })
      .error(function(er){
        assert.fail(er);
      });
  });

  it('Constructs with object', function () {
    var conObj = {
      user: '',
      password: '',
      host: "localhost",
      port: 5432,
      database: 'pg_migrate',
      max: 2,
      disconnect: function(client, dc) {
        console.log('disconnect');
      }
    };
    var conn = dbConnection(conObj);
    conn.one('SELECT version();')
      .then(function(r) {
        assert.isNotNull(r);
        assert.isNotNull(r.version);
      })
      .error(function(er){
        assert.fail(er);
      });
  });
});<commit_msg>return the promise for mocha's result.<commit_after>var assert = require('chai').assert;
var expect = require('chai').expect;
var dbConnection = require('../lib/dbConnection');

describe('dbConnection', function () {
  it('handles no input', function() {
    expect(dbConnection).to.throw(Error);
  });

  //This works though I think it's logic in pg-promise or pg.
  // it('handles empty object', function() {
  //   //expect(() => dbConnection({})).to.throw(Error);
  //   var conn = dbConnection({});
  //   conn.one('SELECT version();')
  //     .then(function(r) {
  //       assert.isNotNull(r);
  //       assert.isNotNull(r.version);
  //     })
  //     .error(function(er){
  //       assert.fail(er);
  //     });
  // });

  it('Constructs with string', function () {
    var conn = dbConnection("postgresql://localhost:5432/pg_migrate");
    conn.one('SELECT version();')
      .then(function(r) {
        assert.isNotNull(r);
        assert.isNotNull(r.version);
      })
      .error(function(er){
        assert.fail(er);
      });
    return conn;
  });

  it('Constructs with object', function () {
    var conObj = {
      user: '',
      password: '',
      host: "localhost",
      port: 5432,
      database: 'pg_migrate',
      max: 2,
      disconnect: function(client, dc) {
        console.log('disconnect');
      }
    };
    var conn = dbConnection(conObj);
    conn.one('SELECT version();')
      .then(function(r) {
        assert.isNotNull(r);
        assert.isNotNull(r.version);
      })
      .error(function(er){
        assert.fail(er);
      });
    return conn;
  });
});<|endoftext|>