text:
import os
import copy
import dmr.input
import dmr.config
from unittest import TestCase

# path to base test directory
testdir = os.path.abspath(os.path.join(os.path.dirname(__file__)))

class TestEndToEnd(TestCase):
    """ Perform end-to-end test(s), from input to output.  Currently,
    this only uses the JSON and plaintext output formats, because the
    other formats may depend on the version of docutils and how it
    renders output. Other formats can be added easily.

    To regenerate the expected output, run this module directly as a
    script.
    """

    # base options for all output formats
    options = dict(footer=dmr.config._get_footer())

    # per-output format options
    fmt_options = dict(
        json=dict(pretty=True),
        latex=dict(template_path=os.path.abspath(os.path.join(testdir, '..',
                                                              "templates")),
                   template="latex.genshi"),
        text=dict(template_path=os.path.abspath(os.path.join(testdir, '..',
                                                             "templates")),
                  template="text.genshi"))

    original_config = copy.deepcopy(dmr.config.config)

    def get_expected(self, fmt):
        return open(os.path.join(testdir, "end_to_end.%s" % fmt)).read()

    def get_actual(self, fmt):
        fmt_opts = copy.deepcopy(self.options)
        fmt_opts.update(self.fmt_options.get(fmt, dict()))
        config = dmr.config._get_default_config(fmt, opts=fmt_opts)
        return config.output_class(dmr.input.parse(open(
                    os.path.join(testdir, "end_to_end.rst")))).output()

    def _test_format(self, fmt):
        self.assertEqual(self.get_expected(fmt),
                         self.get_actual(fmt))

    def test_json(self):
        """ End-to-end test with JSON output """
        self._test_format("json")

    def test_text(self):
        """ End-to-end test with JSON output """
        self._test_format("text")

if __name__ == "__main__":
    # update expected test output
    tester = TestEndToEnd("test_json")
    for fmt in ["json", "text"]:
        outfile = os.path.join(testdir, "end_to_end.%s" % fmt)
        print("Writing %s" % outfile)
        open(outfile, "w").write(tester.get_actual(fmt))


text:
import paho.mqtt.client as mqtt
from threading import Thread
import time
import datetime

global current_temperature

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("POOL/temp")

def on_message(client, userdata, msg):
    global current_temperature
    print(msg.topic+" "+str(msg.payload)+"\n")
    if msg.topic == "POOL/temp":
         print "\treceived temperature update "
	 current_temperature = float(str(msg.payload))
	 print current_temperature

def poolPumpScheduler(mqttClient):
    while True:
        print "checking to run pump"
        time.sleep(1)

        now = datetime.datetime.now().strftime('%H:%M')
        print now

def main():
    mqttClient = mqtt.Client()
    mqttClient.on_connect = on_connect
    mqttClient.on_message = on_message

    mqttClient.connect("localhost")

    PoolPumpSchedulerThread = Thread(target=poolPumpScheduler, args=(mqttClient,))
    PoolPumpSchedulerThread.start()

    mqttClient.loop_forever()

if __name__ == '__main__':
    main()

redpajama_set_name: RedPajamaGithub


text:
<?php

################################################################################
#                                                                              #
#		Filename:	test.php				       #
#		Author:		Martin Settle				       #
#               Created:	17 October 2007				       #
#		Description:	conceptual test page			       #
#		Calls:		config.php				       #
#		Called by:	login.php				       #
#									       #
################################################################################

if(empty($CoopName))
{
	session_start();

	$Secure = 1;
	include '../config.php';
	}

//don't cache this page4
header('Expires: Wed 23 Dec 1980 00:30:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');

header('Content-Type: text/xml');

$_GET = quote_smart($_GET);

$membertest = mysql_query("SELECT count(member_id) FROM member WHERE member_email = {$_GET['email']}");
$membercount = mysql_result($membertest,0);
if($membercount == 1) $test = 'member';
else $test = 'new';
/*$dom = new DOMDocument();
$member = $dom->createElement('member');
$dom->appendChild($member);
$responseText = $dom->createTextNode($test);
$member->appendChild($responseText);
$xmlString = $dom->saveXML();
*/
$xmlString = "<?xml version=\"1.0\"?>
<member>{$test}</member>";

echo $xmlString;

//error_log("\nReturned {$xmlString}\n",3,'testing_log');

?>


text:
'use strict';

/**
 * Mock spec runner.
 */
function MockSpecRunner() {}
MockSpecRunner.prototype.run = function(spec, specDone) {
  spec.before.call(this);
  spec.body.call(this);
  spec.after.call(this);
  specDone();
};

MockSpecRunner.prototype.addFuture = function(name, fn, line) {
  return {name: name, fn: fn, line: line};
};

describe('angular.scenario.Runner', function() {
  var $window;
  var runner;

  beforeEach(function() {
    // Trick to get the scope out of a DSL statement
    angular.scenario.dsl('dslAddFuture', function() {
      return function() {
        return this.addFuture('future name', angular.noop);
      };
    });
    // Trick to get the scope out of a DSL statement
    angular.scenario.dsl('dslScope', function() {
      var scope = this;
      return function() { return scope; };
    });
    // Trick to get the scope out of a DSL statement
    angular.scenario.dsl('dslChain', function() {
      return function() {
        this.chained = 0;
        this.chain = function() { this.chained++; return this; };
        return this;
      };
    });
    $window = {
      location: {}
    };
    runner = new angular.scenario.Runner($window);
    runner.on('SpecError', angular.mock.rethrow);
    runner.on('StepError', angular.mock.rethrow);
  });

  afterEach(function() {
    delete angular.scenario.dsl.dslScope;
    delete angular.scenario.dsl.dslChain;
  });

  it('should publish the functions in the public API', function() {
    angular.forEach(runner.api, function(fn, name) {
      var func;
      if (name in $window) {
        func = $window[name];
      }
      expect(angular.isFunction(func)).toBeTruthy();
    });
  });

  it('should construct valid describe trees with public API', function() {
    var before = [];
    var after = [];
    $window.describe('A', function() {
      $window.beforeEach(function() { before.push('A'); });
      $window.afterEach(function() { after.push('A'); });
      $window.it('1', angular.noop);
      $window.describe('B', function() {
        $window.beforeEach(function() { before.push('B'); });
          $window.afterEach(function() { after.push('B'); });
        $window.it('2', angular.noop);
        $window.describe('C', function() {
          $window.beforeEach(function() { before.push('C'); });
          $window.afterEach(function() { after.push('C'); });
          $window.it('3', angular.noop);
        });
      });
    });
    var specs = runner.rootDescribe.getSpecs();
    specs[0].before();
    specs[0].body();
    specs[0].after();
    expect(before).toEqual(['A', 'B', 'C']);
    expect(after).toEqual(['C', 'B', 'A']);
    expect(specs[2].definition.parent).toEqual(runner.rootDescribe);
    expect(specs[0].definition.parent).toEqual(specs[2].definition.children[0]);
  });

  it('should publish the DSL statements to the $window', function() {
    $window.describe('describe', function() {
      $window.it('1', function() {
        expect($window.dslScope).toBeDefined();
      });
    });
    runner.run(null/*application*/);
  });

  it('should create a new scope for each DSL chain', function() {
    $window.describe('describe', function() {
      $window.it('1', function() {
        var scope = $window.dslScope();
        scope.test = "foo";
        expect($window.dslScope().test).toBeUndefined();
      });
      $window.it('2', function() {
        var scope = $window.dslChain().chain().chain();
        expect(scope.chained).toEqual(2);
      });
    });
    runner.run(null/*application*/);
  });
});


text:
import java.util.LinkedList;
import java.util.List;

public class GeneralizedAbbreviation {
    static public List<String> generateAbbreviations(String word) {
        char [] chars = word.toCharArray();
        List<String> res = new LinkedList<>();

        bc(chars, 0, 0, res, new StringBuilder());

        return res;
    }

    static public void bc(char [] chars, int curIdx, int num,List<String> res, StringBuilder sb) {
        int oriLen = sb.length();

        if (curIdx == chars.length) {
            if (num != 0) {
                sb.append(num);
            }

            res.add(sb.toString());
        } else {
            bc(chars, curIdx+1, num+1, res, sb);

            if (num != 0) {
                sb.append(num);
            }

            bc(chars, curIdx+1, 0, res, sb.append(chars[curIdx]));
        }

        sb.setLength(oriLen);
    }

    public static void main(String [ ] args) {
        for (String s : generateAbbreviations("word")) {
            System.out.println(s);
        }
    }
}


text:
package nl.jft.logic.util.builder;

import nl.jft.logic.statistic.impl.TitleStatistic;

/**
 * @author Lesley
 */
public final class TitleStatisticBuilder {

    public TitleStatistic build() {
        return new TitleStatistic();
    }

}


text:
import { connect } from 'react-redux'
import axios from 'axios'
import firebase from './firebaseConfig'
import functions from 'firebase-functions'
import admin from 'firebase-admin'
import moment from 'moment'
import React, { Component } from 'react';

import { userData } from '../actions/userAction'
import { todoToStore } from '../actions/todoAction'

import {
  Avatar,
  Button,
  Card,
  Checkbox,
  Col,
  Collapse,
  Form,
  Icon,
  Input,
  Layout,
  Modal,
  Popconfirm,
  Progress,
  Row,
  Select,
  Tag
} from 'antd'
// import { BrowserRouter, Link } from 'react-router-dom'
import {Scrollbars} from 'react-custom-scrollbars';

import './dashboard.css'

admin.initializeApp(functions.config().firebase)

const { TextArea } = Input
const FormItem = Form.Item;
const Panel = Collapse.Panel

class Dashboard extends Component {
  constructor() {
    super()
    this.state = {
      email: '',
      newTask: '',
      photoURL: '',
      review: {
        visibleModal: false,
        item: {
          topic: {
            text: ''
          },
          todo: {},
          notes: {
            0: {
              data: {}
            }
          },
          report: {
            userParticipationRate: {
              0: {}
            },
            userContributionRate: {
              0: {}
            },
            userFocusness: {
              0: {}
            }
          }
        }
      },
      roomList: [],
      summaryList: '',
      todoList: {
        backlog: [],
        done: [],
        onProgress: [],
        todo: []
      },
      topicTitle: '',
      userId: '',
      username: '',
      users: {},
      visible: false,
      validate: '',
      helMessage: ''
    }
  }

  addNewTask() {
    console.log('addNewTask')
    const key = firebase.database().ref(`/kanban`).push().key
    firebase.database().ref(`/kanban/${key}`).set({
      status: 'backlog',
      task: this.state.newTask,
      taskId: key,
      user: {
        name: this.state.username,
        userId: this.state.userId
      }
    })
    this.setState({ newTask: '' })
  }

  addNewTaskChange(e) {
    this.setState({newTask: e.target.value})
  }

  addHandleCancel() {
    this.setState({
      visible: false
    })
  }

  addHandleOk(e) {
    e.preventDefault()
    this.setState({
      visible: false
    })
    this.addNewTask()
  }

  pushNotification() {
    if(window.Notification && Notification.permission !== 'granted') {
      Notification.requestPermission()
    }
    if(window.Notification && Notification.permission == 'granted') {
      // firebase.database().ref(`/rooms/-KwiGXOqgIGPycPIMPJC/chat/`).onCreate('value', snapshot => {
      //   console.log(snapshot.val())
      // })
      functions.database.ref(`/rooms/{roomsId}/chat/`).onCreate(event => {
        console.log(event.data.val())
      })
    }

  }

  addTaskModal(item) {
    this.setState({
      visible: true
    })
  }

  createRoom(e) {
    e.preventDefault();
    this.setState({validate: 'validating'})
    axios.get(`https://us-central1-minutes-vart.cloudfunctions.net/watsonNLU?text=${this.state.topicTitle}`)
    .then(({ data }) => {
      console.log(data)
      if (data.error) {
        this.setState({validate: 'error', helpMessage: 'Room\'s name should be descriptive and written in English'})
      } else {
        let ref = firebase.database().ref(`/rooms/`)
        let roomData = {
          status: true,
          topic: {
            categories: data.categories || 'fcuk',
            text: this.state.topicTitle
          },
          timestamp: Date.now()
        }
        ref.push().set(roomData)
        this.setState({ topicTitle: '', validate: ''})
      }
    })
  }

  deleteTask(task) {
    console.log('deleteTask')
    if (task.user.userId !== this.state.userId) {
      alert('You are not authorized to edit this task')
    } else {
      firebase.database().ref(`/kanban/${task.taskId}`).remove()
    }
  }

  getAllRooms() {
    let ref = firebase.database().ref('/rooms')
    ref.on('value', snapshot => {
      let temp = []
      let list = Object.entries(snapshot.val() || {})
      list.forEach(li => {
        let participant = li[1].participant ? Object.entries(li[1].participant) : []
        let participants = []
        participant.forEach(ind => {
          participants.push(ind[1].name)
        })
        temp.push({
          participants: participants,
          roomId: li[0],
          topic: li[1].topic.text.toUpperCase() || undefined
        })
      })
      this.setState({ roomList: temp.reverse() })
    })
  }

  getAllSummary() {
    let sum = firebase.database().ref('/history')
    sum.on('value', snapshot => {
      if (snapshot.val() !== null) {
        let summary = []
        let listSummary = Object.entries(snapshot.val())
        listSummary.forEach(summ => {
          summ[1].key = summ[0]
          summary.push(summ[1])
        })
        this.setState({ summaryList: summary })
      }
    })
  }

  getAllTodo() {
    let ref = firebase.database().ref('/kanban')
    ref.on('value', snapshot => {
      if (snapshot.val() !== null) {
        let list = Object.entries(snapshot.val())
        let todoList = {
          backlog: [],
          done: [],
          onProgress: [],
          todo: []
        }
        list.forEach(li => {
          if (li[1].status === 'done') {
            let done = li[1]
            done.taskId = li[0]
            todoList.done.push(done)
          } else if (li[1].status === 'onProgress') {
            let progress = li[1]
            progress.taskId = li[0]
            todoList.onProgress.push(progress)
          } else if (li[1].status === 'todo') {
            let todo = li[1]
            todo.taskId = li[0]
            todoList.todo.push(todo)
          } else if (li[1].status === 'backlog') {
            let backlog = li[1]
            backlog.taskId = li[0]
            todoList.backlog.push(backlog)
          }
        })
        todoList.backlog.reverse()
        todoList.done.reverse()
        todoList.todo.reverse()
        todoList.onProgress.reverse()
        let payload = {
          userId: this.state.userId,
          todoList: list
        }
        this.props.todoToStore(payload)
        this.setState({ todoList: todoList })
      }
    })
  }

  getAllUsers() {
    firebase.database().ref('users').once('value')
      .then(snapshot => {
        this.setState({
          users: snapshot.val()
        })
      })
  }

  judulHistory(title) {
    return `Topic : ${title.toUpperCase()}`
  }

  logout() {
    console.log('Logout')
    firebase.auth().signOut()
    .then(() => {
      console.log('signed out')
    })
  }

  modalHandleCancel() {
    this.setState({
      review: {
        ...this.state.review,
        visibleModal: false
      }
    })
  }

  modalHandleOk() {
    axios.post(`https://us-central1-minutes-vart.cloudfunctions.net/submitReview`, {
      historyId: this.state.review.item.key,
      todo: this.state.review.item.todo
    })
      .then(() => {
        this.setState({
          review: {
            ...this.state.review,
            visibleModal: false
          }
        })
      })
  }

  paketJoin(roomId, topic) {
    console.log('Join room: ', topic)
    let ref = firebase.database().ref(`/rooms/${roomId}/participant/${this.state.userId}`)
    ref.set({
      name: this.state.username,
      id: this.state.userId
    })
    // this.props.history.push(`/chatroom/${roomId}`)
    this.props.history.push({
      pathname: `/chatroom/${roomId}`,
      state: { topic: topic }
    })
  }

  reviewModal(item) {
    this.setState({
      review: {
        visibleModal: true,
        item
      }
    })
  }

  stateChangeListener() {
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        console.log('Authenticated User: ', user)
        let ref = firebase.database().ref('/users')
        ref.once('value', snap => {
          let regist = snap.hasChild(user.uid)
          if (!regist) {
            console.log('Not Registered. Register first.')
            // this.logout()
            this.props.history.push('/')
          } else {
            console.log('Registered');
          }
        })
        this.setState({
          username: user.displayName,
          email: user.email,
          photoURL: user.photoURL,
          userId: user.uid
        })
      } else {
        this.props.history.push('/')
      }
    })
  }

  toBackLog(task) {
    console.log('toBackLog')
    if (task.user.userId === this.state.userId) {
      task.status = 'backlog'
      firebase.database().ref(`/kanban/${task.taskId}`).set(task)
    } else {
      alert('You are not authorized to edit this task')
    }
  }

  toTodo(task) {
    console.log('toTodo')
    if (task.user.userId === this.state.userId) {
      task.status = 'todo'
      firebase.database().ref(`/kanban/${task.taskId}`).set(task)
    } else {
      alert('You are not authorized to edit this task')
    }
  }

  toOnProgress(task) {
    console.log('toOnProgress')
    if (task.user.userId === this.state.userId) {
      task.status = 'onProgress'
      firebase.database().ref(`/kanban/${task.taskId}`).set(task)
    } else {
      alert('You are not authorized to edit this task')
    }
  }

  toDone(task) {
    console.log('toDone')
    if (task.user.userId === this.state.userId) {
      task.status = 'done'
      firebase.database().ref(`/kanban/${task.taskId}`).set(task)
    } else {
      alert('You are not authorized to edit this task')
    }
  }

  topicTitleChange(e) {
    this.setState({ topicTitle: e.target.value })
  }

  // --------------------------------------------------------------------------

  componentDidMount() {
    this.getAllTodo()
    this.getAllRooms()
    this.getAllSummary()
    this.getAllUsers()
    this.pushNotification()
  }

  componentWillMount() {
    this.stateChangeListener()
  }

  render() {
    return (
      <Layout>
        <Layout className='App'>

M I N U T E S - A P P

                <Button
                  hidden
                  onClick={() => this.addTaskModal()}
                  icon="plus"
                  size='large'>
                  NEW TASK
                </Button>
                <Modal
                  title="ADD NEW TASK"
                  visible={this.state.visible}
                  onOk={(e) => this.addHandleOk(e)}
                  onCancel={() => this.addHandleCancel()}
                  cancelText="Cancel"
                  okText="Add Task"
                >
                  <Form onSubmit={(e) => this.addHandleOk(e)} >
                    <TextArea rows={4}
                      onChange={(e) => this.addNewTaskChange(e)}
                      prefix={<Icon type="calendar" style={{ fontSize: 13 }} />} type="text" placeholder="New Task ..."
                      value={this.state.newTask}
                    />
                  </Form>
                </Modal>

          <Scrollbars autoHide >

                <Row gutter={5}>
                  <Col span={6}>
                    <Card title="BACK LOG" bordered={false} style={{backgroundColor: 'rgba(255,0,0, 0.5)', boxShadow: '0px 0px 10px red'}}>
                      {
                        this.state.todoList.backlog.map((back, idx) => {
                          return (

                              <Card style={{}}>

{back.task}

Assign to: {back.user.name}

                                {
                                  this.state.userId === back.user.userId ? (

                                      <Popconfirm placement="bottomRight" okType="danger" title='Are you sure delete this task?' onConfirm={() => this.deleteTask(back)} okText="Yes" cancelText="No">
                                        <Button
                                          type="danger"
                                          shape="circle"
                                          icon="delete">
                                        </Button>
                                      </Popconfirm>
                                      <Button
                                        onClick={() => this.toTodo(back)}
                                        type="dashed"
                                        shape="circle"
                                        icon="right-circle">
                                      </Button>

                                  ) :
                                  null
                                }
                              </Card>

                          )
                        })
                      }
                    </Card>
                  </Col>
                  <Col span={6}>
                    <Card title="TO-DO" bordered={false} style={{backgroundColor: 'rgba(255,165,0, 0.5)', boxShadow: '0px 0px 10px orange'}}>
                      {
                        this.state.todoList.todo.map((td, idx) => {
                          return (

                              <Card>

{td.task}

Assign to: {td.user.name}

                                {
                                  this.state.userId === td.user.userId ? (

                                      <Button
                                        onClick={() => this.toBackLog(td)}
                                        type="dashed" shape="circle"
                                        icon="left-circle">
                                      </Button>
                                      <Popconfirm placement="bottomRight" okType="danger" title='Are you sure delete this task?' onConfirm={() => this.deleteTask(td)} okText="Yes" cancelText="No">
                                        <Button
                                          type="danger"
                                          shape="circle"
                                          icon="delete">
                                        </Button>
                                      </Popconfirm>
                                      <Button
                                        onClick={() => this.toOnProgress(td)}
                                        type="dashed" shape="circle"
                                        icon="right-circle">
                                      </Button>

                                  ) :
                                  null
                                }
                              </Card>

                          )
                        })
                      }
                    </Card>
                  </Col>
                  <Col span={6}>
                    <Card title="ON PROGRESS" bordered={false} style={{backgroundColor: 'rgba(0,0,255, 0.5)', boxShadow: '0px 0px 10px blue'}}>
                      {
                        this.state.todoList.onProgress.map((prog, idx) => {
                          return (

                              <Card>

{prog.task}

Assign to: {prog.user.name}

                                {
                                  this.state.userId === prog.user.userId ? (

                                      <Button
                                        onClick={() => this.toTodo(prog)}
                                        type="dashed"
                                        shape="circle"
                                        icon="left-circle">
                                      </Button>
                                      <Popconfirm placement="bottomRight" okType="danger" title="Are you sure delete this task?" onConfirm={() => this.deleteTask(prog)} okText="Yes" cancelText="No">
                                        <Button
                                          type="danger"
                                          shape="circle"
                                          icon="delete">
                                        </Button>
                                      </Popconfirm>
                                      <Button
                                        onClick={() => this.toDone(prog)}
                                        type="dashed"
                                        shape="circle"
                                        icon="right-circle">
                                      </Button>

                                  ) :
                                  null
                                }
                              </Card>

                          )
                        })
                      }
                    </Card>
                  </Col>
                  <Col span={6}>
                    <Card title="DONE" bordered={false} style={{backgroundColor: 'rgba(0,128,0, 0.5)', boxShadow: '0px 0px 10px green'}}>
                      {
                        this.state.todoList.done.map((dn, idx) => {
                          return (

                              <Card>

{dn.task}

Assign to: {dn.user.name}

                                {
                                  this.state.userId === dn.user.userId ? (

                                      <Button
                                        onClick={() => this.toOnProgress(dn)}
                                        type="dashed"
                                        shape="circle"
                                        icon="left-circle">
                                      </Button>
                                      <Popconfirm placement="bottomRight" okType="danger" title="Are you sure delete this task?" onConfirm={() => this.deleteTask(dn)} okText="Yes" cancelText="No">
                                        <Button
                                          type="danger"
                                          shape="circle"
                                          icon="delete">
                                        </Button>
                                      </Popconfirm>

                                  ) :
                                  null
                                }
                              </Card>

                          )
                        })
                      }
                    </Card>
                  </Col>
                </Row>

              </Scrollbars>

                <Avatar size="large" src={this.state.photoURL} />

                  {this.state.username}

                <Button
                  type="primary"
                  onClick={this.logout}
                  style={{
                    background: '#13314D'
                  }}>Logout</Button>

          <Scrollbars autoHide >

Discussion List

                <Form onSubmit={(e) => this.createRoom(e)} layout='inline'>
                      <FormItem
                      hasFeedback
                      validateStatus = {this.state.validate}
                      help = {this.state.helpMessage}
                    >
                  <Input
                    size='large'
                    value={this.state.topicTitle}
                    onChange={e => this.topicTitleChange(e)}
                    placeholder="Add Room Name..."/>
                    </FormItem>
                    <FormItem>
                    <Button icon="plus" htmlType='submit'>Add Discussion</Button>
                    </FormItem>
                </Form>

                {
                  this.state.roomList.map((room, idx) => {
                    return (
                      <Card
                        key={idx}
                        title={room.topic}
                        extra={ this.paketJoin(room.roomId, room.topic)}> Join }
                        style={{
                          marginBottom: '10px',
                          marginRight: '10px',
                          background: '#2D587B'
                        }}>
                        {
                          room.participants.map((orang, i) => {
                            return (
                              <Tag key={i}>
                                {orang}
                              </Tag>
                            )
                          })
                        }
                      </Card>
                    )
                  })
                }

              </Scrollbars>

          <Scrollbars autoHide >

Discussion History List

              <Collapse bordered={false} className='collapse'>
                {this.state.summaryList ? this.state.summaryList.map(item => {
                  return (
                    <Panel
                      header={this.judulHistory(item.topic.text)}
                      style={customPanelStyle}
                      key={item.key}
                    >

                        {moment.unix(item.timestamp / 1000).locale('id').format('LLL')}

                        {
                          Object.keys(item.participant).forEach((key, i) => {
                            /* eslint-disable no-unused-expressions */
                            <Tag key={i}>{item.participant[key].name}</Tag>
                          })
                        }

                        {!item.status ? <Button type="primary" onClick={() => this.reviewModal(item)}>Review</Button> : ''}

                    </Panel>
                  )
                }) : null}
              </Collapse>
              <Modal
                title={this.state.review.item.topic.text.toUpperCase()}
                visible={this.state.review.visibleModal}
                onOk={() => this.modalHandleOk()}
                onCancel={() => this.modalHandleCancel()}
                okText="Submit"
                cancelText="Cancel"
              >
                Tasks
                {
                  this.state.review.item.todo ?
                  Object.keys(this.state.review.item.todo).map((key, idx) => {
                  const todo = this.state.review.item.todo[key]
                    return (
                      <Col key="idx">
                        <Row gutter={4}>
                          <Col span={23}>
                            <Input.Group compact>
                              <Select
                                labelInValue
                                style={{ width: '30%' }}
                                defaultValue={{key: todo.userId}}
                                onChange={(e) => {
                                  // eslint-disable-next-line
                                  this.state.review.item.todo[key].userId = e.key
                                  // eslint-disable-next-line
                                  this.state.review.item.todo[key].userName = e.label
                                  this.forceUpdate()
                                }}
                              >
                                {Object.keys(this.state.users).map((id, i) => (
                                  <Select.Option value={id} key={i}>{this.state.users[id].name}</Select.Option>
                                ))}
                              </Select>
                              <Input style={{ width: '70%' }} defaultValue={todo.task} />
                            </Input.Group>
                          </Col>
                          <Col span={1}>
                            <Checkbox
                              checked={todo.status}
                              onChange={(e) => {
                                // eslint-disable-next-line
                                this.state.review.item.todo[key].status = e.target.checked
                                this.forceUpdate()
                              }}
                            />
                          </Col>
                        </Row>
                      </Col>
                    )
                  }) : null
                }

                <Collapse accordion>
                  {
                    this.state.review.item.notes ? (
                      <Panel header='Noted Chat' key="1">

                          {
                            Object.keys(this.state.review.item.notes).map((key, idx) => {
                              const note = this.state.review.item.notes[key]
                              return (

{ note.data.text }

                              )
                            })
                          }

                      </Panel>
                    ) : (
                        <Panel header="Noted Chat" disabled></Panel>
                      )
                  }
                  {
                    this.state.review.item.report.relevantChat ? (
                      <Panel header="Relevant Chat" key="2">

                          {
                            Object.keys(this.state.review.item.report.relevantChat).map((key, idx) => {
                              const chat = this.state.review.item.report.relevantChat[key]
                              return (

{ chat.data.text }

                              )
                            })
                          }

                      </Panel>
                    ) : (
                      <Panel header="Relevant Chat" disabled></Panel>
                    )
                  }
                </Collapse>
                Duration: {this.state.review.item.report.duration}

                Meeting Date: { moment.unix(this.state.review.item.timestamp / 1000).locale('id').format('LLL') }

                <Row style={{position: 'relative', left: 50}}>
                  <Col span={12}>
                    Discussion Productivity
                    <Progress type="dashboard" percent={Math.floor(this.state.review.item.report.discussionProductivity * 100)} />
                  </Col>
                </Row>

                User Participation Rate
                {Object.keys(this.state.review.item.report.userParticipationRate).map((key, idx) => {
                  const user = this.state.review.item.report.userParticipationRate[key]
                  return (
                    <Row key={idx}>
                      <Col span={4}>
                        {user.name}
                      </Col>
                      <Col span={20}>
                        <Progress percent={Math.floor(user.score * 100)} strokeWidth={5}/>
                      </Col>
                    </Row>
                  )
                })}

                User Contribution Rate
                {Object.keys(this.state.review.item.report.userContributionRate).map((key, idx) => {
                  const user = this.state.review.item.report.userContributionRate[key]
                  return (
                    <Row key={idx}>
                      <Col span={4}>
                        {user.name}
                      </Col>
                      <Col span={20}>
                        <Progress percent={Math.floor(user.score * 100)} strokeWidth={5}/>
                      </Col>
                    </Row>
                  )
                })}

                User Focusness
                {Object.keys(this.state.review.item.report.userFocusness).map((key, idx) => {
                  const user = this.state.review.item.report.userFocusness[key]
                  return (
                    <Row key={idx}>
                      <Col span={4}>
                        {user.name}
                      </Col>
                      <Col span={20}>
                        <Progress percent={Math.floor(user.score * 100)} strokeWidth={5}/>
                      </Col>
                    </Row>
                  )
                })}
              </Modal>
              </Scrollbars>

        </Layout>
      </Layout>
    )
  }
}

const customPanelStyle = {
  background: 'white',
  borderRadius: 4,
  marginBottom: 24,
  border: 0,
  overflow: 'hidden'
};

// export default Dashboard

const mapStateToProps = state => {
  return {
  }
}

const mapDispatchToProps = dispatch => {
  return {
    userData: payload => dispatch(userData(payload)),
    todoToStore: payload => dispatch(todoToStore(payload))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Dashboard)


text:
/**
 * Autogenerated by Thrift Compiler (0.13.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.sdnplatform.sync.thrift;

@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.13.0)", date = "2020-06-16")
public class ClockEntry implements org.apache.thrift.TBase<ClockEntry, ClockEntry._Fields>, java.io.Serializable, Cloneable, Comparable<ClockEntry> {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ClockEntry");

  private static final org.apache.thrift.protocol.TField NODE_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("nodeId", org.apache.thrift.protocol.TType.I16, (short)1);
  private static final org.apache.thrift.protocol.TField VERSION_FIELD_DESC = new org.apache.thrift.protocol.TField("version", org.apache.thrift.protocol.TType.I64, (short)2);

  private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new ClockEntryStandardSchemeFactory();
  private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new ClockEntryTupleSchemeFactory();

  public short nodeId; // required
  public long version; // required

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    NODE_ID((short)1, "nodeId"),
    VERSION((short)2, "version");

    private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();

    static {
      for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    @org.apache.thrift.annotation.Nullable
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // NODE_ID
          return NODE_ID;
        case 2: // VERSION
          return VERSION;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    @org.apache.thrift.annotation.Nullable
    public static _Fields findByName(java.lang.String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final java.lang.String _fieldName;

    _Fields(short thriftId, java.lang.String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public java.lang.String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  private static final int __NODEID_ISSET_ID = 0;
  private static final int __VERSION_ISSET_ID = 1;
  private byte __isset_bitfield = 0;
  public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.NODE_ID, new org.apache.thrift.meta_data.FieldMetaData("nodeId", org.apache.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16)));
    tmpMap.put(_Fields.VERSION, new org.apache.thrift.meta_data.FieldMetaData("version", org.apache.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
    metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ClockEntry.class, metaDataMap);
  }

  public ClockEntry() {
  }

  public ClockEntry(
    short nodeId,
    long version)
  {
    this();
    this.nodeId = nodeId;
    setNodeIdIsSet(true);
    this.version = version;
    setVersionIsSet(true);
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public ClockEntry(ClockEntry other) {
    __isset_bitfield = other.__isset_bitfield;
    this.nodeId = other.nodeId;
    this.version = other.version;
  }

  public ClockEntry deepCopy() {
    return new ClockEntry(this);
  }

  @Override
  public void clear() {
    setNodeIdIsSet(false);
    this.nodeId = 0;
    setVersionIsSet(false);
    this.version = 0;
  }

  public short getNodeId() {
    return this.nodeId;
  }

  public ClockEntry setNodeId(short nodeId) {
    this.nodeId = nodeId;
    setNodeIdIsSet(true);
    return this;
  }

  public void unsetNodeId() {
    __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __NODEID_ISSET_ID);
  }

  /** Returns true if field nodeId is set (has been assigned a value) and false otherwise */
  public boolean isSetNodeId() {
    return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __NODEID_ISSET_ID);
  }

  public void setNodeIdIsSet(boolean value) {
    __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __NODEID_ISSET_ID, value);
  }

  public long getVersion() {
    return this.version;
  }

  public ClockEntry setVersion(long version) {
    this.version = version;
    setVersionIsSet(true);
    return this;
  }

  public void unsetVersion() {
    __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __VERSION_ISSET_ID);
  }

  /** Returns true if field version is set (has been assigned a value) and false otherwise */
  public boolean isSetVersion() {
    return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __VERSION_ISSET_ID);
  }

  public void setVersionIsSet(boolean value) {
    __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __VERSION_ISSET_ID, value);
  }

  public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
    switch (field) {
    case NODE_ID:
      if (value == null) {
        unsetNodeId();
      } else {
        setNodeId((java.lang.Short)value);
      }
      break;

    case VERSION:
      if (value == null) {
        unsetVersion();
      } else {
        setVersion((java.lang.Long)value);
      }
      break;

    }
  }

  @org.apache.thrift.annotation.Nullable
  public java.lang.Object getFieldValue(_Fields field) {
    switch (field) {
    case NODE_ID:
      return getNodeId();

    case VERSION:
      return getVersion();

    }
    throw new java.lang.IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new java.lang.IllegalArgumentException();
    }

    switch (field) {
    case NODE_ID:
      return isSetNodeId();
    case VERSION:
      return isSetVersion();
    }
    throw new java.lang.IllegalStateException();
  }

  @Override
  public boolean equals(java.lang.Object that) {
    if (that == null)
      return false;
    if (that instanceof ClockEntry)
      return this.equals((ClockEntry)that);
    return false;
  }

  public boolean equals(ClockEntry that) {
    if (that == null)
      return false;
    if (this == that)
      return true;

    boolean this_present_nodeId = true;
    boolean that_present_nodeId = true;
    if (this_present_nodeId || that_present_nodeId) {
      if (!(this_present_nodeId && that_present_nodeId))
        return false;
      if (this.nodeId != that.nodeId)
        return false;
    }

    boolean this_present_version = true;
    boolean that_present_version = true;
    if (this_present_version || that_present_version) {
      if (!(this_present_version && that_present_version))
        return false;
      if (this.version != that.version)
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    int hashCode = 1;

    hashCode = hashCode * 8191 + nodeId;

    hashCode = hashCode * 8191 + org.apache.thrift.TBaseHelper.hashCode(version);

    return hashCode;
  }

  @Override
  public int compareTo(ClockEntry other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;

    lastComparison = java.lang.Boolean.valueOf(isSetNodeId()).compareTo(other.isSetNodeId());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetNodeId()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.nodeId, other.nodeId);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = java.lang.Boolean.valueOf(isSetVersion()).compareTo(other.isSetVersion());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetVersion()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.version, other.version);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  @org.apache.thrift.annotation.Nullable
  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
    scheme(iprot).read(iprot, this);
  }

  public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
    scheme(oprot).write(oprot, this);
  }

  @Override
  public java.lang.String toString() {
    java.lang.StringBuilder sb = new java.lang.StringBuilder("ClockEntry(");
    boolean first = true;

    sb.append("nodeId:");
    sb.append(this.nodeId);
    first = false;
    if (!first) sb.append(", ");
    sb.append("version:");
    sb.append(this.version);
    first = false;
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws org.apache.thrift.TException {
    // check for required fields
    // alas, we cannot check 'nodeId' because it's a primitive and you chose the non-beans generator.
    // alas, we cannot check 'version' because it's a primitive and you chose the non-beans generator.
    // check for sub-struct validity
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
    try {
      // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
      __isset_bitfield = 0;
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private static class ClockEntryStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
    public ClockEntryStandardScheme getScheme() {
      return new ClockEntryStandardScheme();
    }
  }

  private static class ClockEntryStandardScheme extends org.apache.thrift.scheme.StandardScheme<ClockEntry> {

    public void read(org.apache.thrift.protocol.TProtocol iprot, ClockEntry struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TField schemeField;
      iprot.readStructBegin();
      while (true)
      {
        schemeField = iprot.readFieldBegin();
        if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
          break;
        }
        switch (schemeField.id) {
          case 1: // NODE_ID
            if (schemeField.type == org.apache.thrift.protocol.TType.I16) {
              struct.nodeId = iprot.readI16();
              struct.setNodeIdIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 2: // VERSION
            if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
              struct.version = iprot.readI64();
              struct.setVersionIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          default:
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
        }
        iprot.readFieldEnd();
      }
      iprot.readStructEnd();

      // check for required fields of primitive type, which can't be checked in the validate method
      if (!struct.isSetNodeId()) {
        throw new org.apache.thrift.protocol.TProtocolException("Required field 'nodeId' was not found in serialized data! Struct: " + toString());
      }
      if (!struct.isSetVersion()) {
        throw new org.apache.thrift.protocol.TProtocolException("Required field 'version' was not found in serialized data! Struct: " + toString());
      }
      struct.validate();
    }

    public void write(org.apache.thrift.protocol.TProtocol oprot, ClockEntry struct) throws org.apache.thrift.TException {
      struct.validate();

      oprot.writeStructBegin(STRUCT_DESC);
      oprot.writeFieldBegin(NODE_ID_FIELD_DESC);
      oprot.writeI16(struct.nodeId);
      oprot.writeFieldEnd();
      oprot.writeFieldBegin(VERSION_FIELD_DESC);
      oprot.writeI64(struct.version);
      oprot.writeFieldEnd();
      oprot.writeFieldStop();
      oprot.writeStructEnd();
    }

  }

  private static class ClockEntryTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
    public ClockEntryTupleScheme getScheme() {
      return new ClockEntryTupleScheme();
    }
  }

  private static class ClockEntryTupleScheme extends org.apache.thrift.scheme.TupleScheme<ClockEntry> {

    @Override
    public void write(org.apache.thrift.protocol.TProtocol prot, ClockEntry struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
      oprot.writeI16(struct.nodeId);
      oprot.writeI64(struct.version);
    }

    @Override
    public void read(org.apache.thrift.protocol.TProtocol prot, ClockEntry struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
      struct.nodeId = iprot.readI16();
      struct.setNodeIdIsSet(true);
      struct.version = iprot.readI64();
      struct.setVersionIsSet(true);
    }
  }

  private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
    return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
  }
}


text:
require 'kramdown'

module Grape
  class API
    class << self
      attr_reader :combined_routes

      def add_swagger_documentation(options={})
        documentation_class = create_documentation_class

        documentation_class.setup({:target_class => self}.merge(options))
        mount(documentation_class)

        @combined_routes = {}
        routes.each do |route|
          resource = route.route_path.gsub(/\/api\/:version/, '').match('\/(\w*?)[\.\/\(]').captures.first
          next if resource.empty?
          resource.downcase!
          @combined_routes[resource] ||= []
          @combined_routes[resource] << route
        end

      end

      private

      def create_documentation_class

        Class.new(Grape::API) do
          class << self
            def name
              @@class_name
            end
          end

          def self.setup(options)
            defaults = {
              :target_class => nil,
              :mount_path => '/swagger_doc',
              :base_path => nil,
              :api_version => '0.1',
              :markdown => false,
              :hide_documentation_path => false,
              :hide_format => false
            }
            options = defaults.merge(options)

            @@target_class = options[:target_class]
            @@mount_path = options[:mount_path]
            @@class_name = options[:class_name] || options[:mount_path].gsub('/','')
            @@markdown = options[:markdown]
            @@hide_documentation_path = options[:hide_documentation_path]
            @@hide_format = options[:hide_format]
            @@include_object_fields = options[:display_object_fields]
            api_version = options[:api_version]
            base_path = options[:base_path]

            desc 'Swagger compatible API description'#, {:no_doc=>true}
            get @@mount_path do
              header['Access-Control-Allow-Origin'] = '*'
              header['Access-Control-Request-Method'] = '*'

              # clear the unexisting routes (not sure why this is happenning)
              routes = @@target_class::combined_routes

              if @@hide_documentation_path
                routes.reject!{ |route, value| "#{@@mount_path}/#{route}/".index(parse_path(@@mount_path, nil) << '/') == 0 }
              end

              routes_array = routes.keys.map do |local_route|
                { :path => "#{parse_path(route.route_path.gsub('(.:format)', ''),route.route_version)}/#{local_route}#{@@hide_format ? '' : '.{format}'}" }
              end
              routes_array.delete_if{|r|r.nil?}

              {
                apiVersion: api_version,
                swaggerVersion: "1.1",
                basePath: parse_base_path(base_path, request),
                operations:[],
                apis: routes_array
              }
            end

            desc 'Swagger compatible API description for specific API', :params =>
              {
                "name" => { :desc => "Resource name of mounted API", :type => "string", :required => true },
              }#, :no_doc=>true
            get "#{@@mount_path}/:name" do
              header['Access-Control-Allow-Origin'] = '*'
              header['Access-Control-Request-Method'] = '*'
              routes = @@target_class::combined_routes.select{|key,val| key.to_s == params[:name]}
              routes_array = routes.map do |k,route_classes|
                route_classes.map do |route|
                #routes_array = routes.map do |route|
                  unless route.instance_variable_get("@options")[:no_doc]
                    #notes = route.route_notes && @@markdown ? Kramdown::Document.new(route.route_notes.strip_heredoc).to_html : route.route_notes
                    notes = route.route_notes && @@markdown ? Kramdown::Document.new(strip_heredoc(route.route_notes)).to_html : route.route_notes
                    if @@include_object_fields
                      additional_notes = describe_entity_documentation(route.instance_variable_get("@options")[:object_fields])
                      notes << additional_notes unless additional_notes.blank?
                    end
                    allowed_methods = route.instance_variable_get("@options")[:allowed_methods] ? route.instance_variable_get("@options")[:allowed_methods] : ['GET']
                    http_codes = parse_http_codes route.route_http_codes
                    operations = {
                            :notes => notes,
                            :summary => route.route_description || '',
                            :nickname   => (route.route_method || allowed_methods.join(',')) + route.route_path.gsub(/[\/:\(\)\.]/,'-'),
                            :httpMethod => (route.route_method || allowed_methods.join(',')),
                            :parameters => parse_header_params(route.route_headers) +
                              parse_params(route.route_params, route.route_path, (route.route_method || route.instance_variable_get("@options")[:allowed_methods].join(',')))
                          }

                    operations.merge!({:errorResponses => http_codes}) unless http_codes.empty?
                    {
                      :path => parse_path(route.route_path, api_version),
                      :operations => [operations]
                    }
                  end
                end
              end
              routes_array.flatten!
              routes_array.delete_if{|route| route.nil?} if(routes_array)
              {
                apiVersion: api_version,
                swaggerVersion: "1.1",
                basePath: parse_base_path(base_path, request),
                resourcePath: "",
                apis: routes_array
              }
            end
          end

          helpers do
            def describe_entity_documentation(object_fields, subtitle='Success Response')
              additional_notes = ''
              if(object_fields && object_fields.size > 0)
                fields_hash = {}
                additional_notes = "
#{subtitle}

{
"
                object_fields.each_pair do |key, val|
                  additional_notes << "  #{key} [#{val[:type].capitalize}]: #{val[:desc]}
"
                end
                additional_notes << "}
"
              end
              additional_notes
            end

            def parse_params(params, path, method)
              if params
                params.map do |param, value|
                  value[:type] = 'file' if value.is_a?(Hash) && value[:type] == 'Rack::Multipart::UploadedFile'

                  dataType = value.is_a?(Hash) ? value[:type]||'String' : 'String'
                  description = value.is_a?(Hash) ? value[:desc] || value[:description] : ''
                  required = value.is_a?(Hash) ? !!value[:required] : false
                  #paramType = path.include?(":#{param}") ? 'path' : (method == 'POST') ? 'form' : 'query'
                  # For now just use query, since that's the only way to make it work for our version of swagger
                  paramType = path.include?(":#{param}") ? 'path' : 'query'
                  name = (value.is_a?(Hash) && value[:full_name]) || param
                  {
                    paramType: paramType,
                    name: name,
                    description: description,
                    dataType: dataType,
                    required: required
                  }
                end
              else
                []
              end
            end

            def parse_header_params(params)
              if params
                params.map do |param, value|
                  dataType = 'String'
                  description = value.is_a?(Hash) ? value[:description] : ''
                  required = value.is_a?(Hash) ? !!value[:required] : false
                  paramType = "header"
                  {
                    paramType: paramType,
                    name: param,
                    description: description,
                    dataType: dataType,
                    required: required
                  }
                end
              else
                []
              end
            end

            def parse_path(path, version)
              # adapt format to swagger format
              parsed_path = path.gsub '(.:format)', ( @@hide_format ? '' : '.{format}')
              # This is attempting to emulate the behavior of
              # Rack::Mount::Strexp. We cannot use Strexp directly because
              # all it does is generate regular expressions for parsing URLs.
              # TODO: Implement a Racc tokenizer to properly generate the
              # parsed path.
              parsed_path = parsed_path.gsub(/:([a-zA-Z_]\w*)/, '{\1}')
              # add the version
              version ? parsed_path.gsub('{version}', version) : parsed_path
            end

            def parse_http_codes codes
              codes ||= {}
              codes.collect do |k, v|
                { code: k, reason: v }
              end
            end

            def try(*a, &b)
              if a.empty? && block_given?
                yield self
              else
                public_send(*a, &b) if respond_to?(a.first)
              end
            end

            def strip_heredoc(string)
              indent = string.scan(/^[ \t]*(?=\S)/).min.try(:size) || 0
              string.gsub(/^[ \t]{#{indent}}/, '')
            end

            def parse_base_path(base_path, request)
              (base_path.is_a?(Proc) ? base_path.call(request) : base_path) || request.base_url
            end
          end
        end
      end
    end
  end
end