<commit_before>import _ from 'lodash';
import { CallModal } from './modal';
import React, { Component } from 'react';
import {
  View,
  Text,
  TextInput,
  Dimensions,
  TouchableWithoutFeedback,
  StyleSheet,
} from 'react-native';

const MODAL_WIDTH = Dimensions.get('window').width / 2;
const MODAL_HEIGHT = Dimensions.get('window').height / 2;
const MODAL_RADIUS = 5;
const FONT_SIZE = 15;
const FONT_COLOR = '#FFF';
const ITEM_HEIGHT = 40;
const ITEM_PADDING = 5;

const OK_TEXT = 'OK';
const CANCEL_TEXT = 'CANCEL';

const defaultContainerRender = (props) => {
  const styles = StyleSheet.create({
    container: {
      flex: 0,
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'stretch',
      width: MODAL_WIDTH,
      borderRadius: MODAL_RADIUS,
      backgroundColor: 'rgba(0, 0, 0, 0.7)',
    },
  });
  return (
    <View style={styles.container}>
      {props.children}
    </View>
  );
}

const defaultItemRender = (props) => {
  const styles = StyleSheet.create({
    container: {
      flex: 0,
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'stretch',
      minHeight: ITEM_HEIGHT,
      borderBottomWidth: 1,
      borderBottomColor: FONT_COLOR,
      padding: ITEM_PADDING,
    },
    last: {
      borderBottomWidth: 0,
    },
    text: {
      color: FONT_COLOR,
      fontSize: FONT_SIZE,
      textAlign: 'center',
    },
  });
  return (
    <TouchableWithoutFeedback onPress={props.onPress}>
      <View style={[styles.container, props.last && styles.last]}>
        <Text
          style={[styles.text, props.textStyle]}
          numberOfLines={props.numberOfLines}
          ellipsizeMode={'middle'}
        >
          {props.text}
        </Text>
      </View>
    </TouchableWithoutFeedback>
  );
}

const defaultTitleRender = (props) => {
  const Item = defaultItemRender;
  const styles = StyleSheet.create({
    text: {
      fontSize: FONT_SIZE * 1.4,
      fontWeight: 'bold',
    },
  });
  return (
    <Item
      numberOfLines={1}
      textStyle={styles.text}
      {...props}
    />
  );
}

const titleYesNoRender = ({ title, message, okText, cancelText, onOk, onCancel, children, Container, Title, Item }) => {
  return (
    <Container>
      {
        !!title && <Title text={title} />
      }
      {
        !!message && <Item text={message} />
      }
      {children}
      {
        !!onOk && <Item
          last={!onCancel}
          onPress={onOk}
          text={okText}
        />
      }
      {
        !!onCancel && <Item
          last
          onPress={onCancel}
          text={cancelText}
        />
      }
    </Container>
  );
}

const defaultArgs = (args) => {
  const result = {
    title: '',
    message: '',
    inputType: 'text',
    okText: OK_TEXT,
    cancelText: CANCEL_TEXT,
    Container: defaultContainerRender,
    Title: defaultTitleRender,
    Item: defaultItemRender,
  };
  if (_.isString(args)) {
    Object.assign(result, {
      message: args,
    });
  } else if (_.isObject(args)) {
    Object.assign(result, args);
  }
  return result;
}

exports.alert = async function(args) {
  const TitleYesNo = titleYesNoRender;
  return await CallModal.show({
    renderFunction: (props) => (
      <TitleYesNo
        {...defaultArgs(args)}
        onOk={props.requestCloseModal}
      />
    )
  });
}

exports.confirm = async function(args) {
  return new Promise((resolve, reject) => {
    const TitleYesNo = titleYesNoRender;
    CallModal.show({
      renderFunction: (props) => (
        <TitleYesNo
          {...defaultArgs(args)}
          onOk={() => {
            props.requestCloseModal();
            resolve(true);
          }}
          onCancel={() => {
            props.requestCloseModal();
            resolve(false);
          }}
        />
      )
    });
  });
}

class TextInputPrompt extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text: props.value || '',
    }
  }
  styles = StyleSheet.create({
    container: {
      flex: 0,
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'stretch',
      minHeight: ITEM_HEIGHT,
      borderBottomWidth: 1,
      borderBottomColor: FONT_COLOR,
      padding: ITEM_PADDING,
    },
    input: {
      minHeight: ITEM_HEIGHT,
      color: FONT_COLOR,
      fontSize: FONT_SIZE,
      textAlign: 'center',
      padding: 0,
    },
  });
  handleChangeText = (text) => {
    this.props.onChangeValue(text);
    this.setState({text});
  }
  render() {
    return (
      <View style={this.styles.container}>
        <TextInput
          style={this.styles.input}
          onChangeText={this.handleChangeText}
          value={this.state.text}
        />
      </View>
    );
  }
}

class CheckBoxPrompt extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectionList: props.value || [],
    }
  }
  render() {
    const Item = defaultItemRender;
    return (
      <View>
        {
          _.map(this.state.selectionList, ({ key, value, selected }, index) => (
            <Item
              key={key}
              last={this.props.autoSubmit && index === this.state.selectionList.length - 1}
              onPress={() => {
                let newSelectionList;
                if (this.props.multiple) {
                  newSelectionList = _.map(this.state.selectionList, (selection) => {
                    let result = Object.assign({}, selection);
                    if (selection.key === key) {
                      Object.assign(result, {
                        selected: !selection.selected,
                      });
                    }
                    return result;
                  });
                  this.setState({
                    selectionList: newSelectionList,
                  });
                  this.props.onChangeValue(newSelectionList);
                } else {
                  newSelectionList = _.map(this.state.selectionList, (selection) => {
                    let result = {
                      key: selection.key,
                      value: selection.value,
                    };
                    if (selection.key === key) {
                      Object.assign(result, {
                        selected: true,
                      });
                    }
                    return result;
                  });
                }
                this.setState({
                  selectionList: newSelectionList,
                });
                this.props.onChangeValue(newSelectionList);
              }}
              text={`${(selected === true)?'V ': ''}${value}`}
            />
          ))
        }
      </View>
    );
  }
}

exports.prompt = async function(args) {
  return new Promise((resolve, reject) => {
    const TitleYesNo = titleYesNoRender;
    const input = defaultArgs(args);
    CallModal.show({
      renderFunction: class extends Component {
        constructor(props) {
          super(props);
          this.state = {
            value: props.value,
          }
        }
        handleValueChange = (value) => {
          this.setState({value});
          if (input.autoSubmit) {
            this.submitValue(value);
          }
        };
        handleSubmit = (value) => {
          this.submitValue(this.state.value);
        };
        handleCancel = () => {
          this.props.requestCloseModal();
          resolve();
        };
        submitValue = (value) => {
          this.props.requestCloseModal();
          let result = value;
          if (!_.isString(result)) {
            result = _.filter(result, ['selected', true]);
            result = _.map(result, 'key').join(',');
          }
          resolve(result);
        };
        render() {
          let content;
          switch(input.inputType){
            case 'text':
              content = (
                <TextInputPrompt
                  value={input.value}
                  onChangeValue={this.handleValueChange}
                />
              );
              break;
            case 'checkbox':
              content = (
                <CheckBoxPrompt
                  multiple
                  value={input.value}
                  onChangeValue={this.handleValueChange}
                />
              );
              break;
            case 'select':
              content = (
                <CheckBoxPrompt
                  autoSubmit={input.autoSubmit}
                  value={input.value}
                  onChangeValue={this.handleValueChange}
                />
              );
              break;
          }
          return (
            <TitleYesNo
              {...input}
              onOk={!input.autoSubmit && this.handleSubmit}
              onCancel={!input.autoSubmit && this.handleCancel}
            >
              {content}
            </TitleYesNo>
          )
        }
      }
    });
  });
}

module.exports = exports;<commit_msg>fix 0.0.5 wrong util file<commit_after>import _ from 'lodash';
import { CallModal } from './modal';
import React, { Component } from 'react';
import {
  View,
  Text,
  TextInput,
  Dimensions,
  TouchableWithoutFeedback,
  StyleSheet,
} from 'react-native';

const MODAL_WIDTH = Dimensions.get('window').width / 2;
const MODAL_HEIGHT = Dimensions.get('window').height / 2;
const MODAL_RADIUS = 5;
const FONT_SIZE = 15;
const FONT_COLOR = '#FFF';
const ITEM_HEIGHT = 40;
const ITEM_PADDING = 5;

const OK_TEXT = 'OK';
const CANCEL_TEXT = 'CANCEL';

const defaultContainerRender = (props) => {
  const styles = StyleSheet.create({
    container: {
      flex: 0,
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'stretch',
      width: MODAL_WIDTH,
      borderRadius: MODAL_RADIUS,
      backgroundColor: 'rgba(0, 0, 0, 0.7)',
    },
  });
  return (
    <View style={styles.container}>
      {props.children}
    </View>
  );
}

const defaultItemRender = (props) => {
  const styles = StyleSheet.create({
    container: {
      flex: 0,
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'stretch',
      minHeight: ITEM_HEIGHT,
      borderBottomWidth: 1,
      borderBottomColor: FONT_COLOR,
      padding: ITEM_PADDING,
    },
    last: {
      borderBottomWidth: 0,
    },
    text: {
      color: FONT_COLOR,
      fontSize: FONT_SIZE,
      textAlign: 'center',
    },
  });
  return (
    <TouchableWithoutFeedback onPress={props.onPress}>
      <View style={[styles.container, props.last && styles.last]}>
        <Text
          style={[styles.text, props.textStyle]}
          numberOfLines={props.numberOfLines}
          ellipsizeMode={'middle'}
        >
          {props.text}
        </Text>
      </View>
    </TouchableWithoutFeedback>
  );
}

const defaultTitleRender = (props) => {
  const Item = defaultItemRender;
  const styles = StyleSheet.create({
    text: {
      fontSize: FONT_SIZE * 1.4,
      fontWeight: 'bold',
    },
  });
  return (
    <Item
      numberOfLines={1}
      textStyle={styles.text}
      {...props}
    />
  );
}

const titleYesNoRender = ({ title, message, okText, cancelText, onOk, onCancel, children, Container, Title, Item }) => {
  return (
    <Container>
      {
        !!title && <Title text={title} />
      }
      {
        !!message && <Item text={message} />
      }
      {children}
      {
        !!onOk && <Item
          last={!onCancel}
          onPress={onOk}
          text={okText}
        />
      }
      {
        !!onCancel && <Item
          last
          onPress={onCancel}
          text={cancelText}
        />
      }
    </Container>
  );
}

const defaultArgs = (args) => {
  const result = {
    title: '',
    message: '',
    inputType: 'text',
    okText: OK_TEXT,
    cancelText: CANCEL_TEXT,
    Container: defaultContainerRender,
    Title: defaultTitleRender,
    Item: defaultItemRender,
  };
  if (_.isString(args)) {
    Object.assign(result, {
      message: args,
    });
  } else if (_.isObject(args)) {
    Object.assign(result, args);
  }
  return result;
}

exports.alert = async function(args) {
  const TitleYesNo = titleYesNoRender;
  return await CallModal.show({
    renderFunction: (props) => (
      <TitleYesNo
        {...defaultArgs(args)}
        onOk={props.requestCloseModal}
      />
    )
  });
}

exports.confirm = async function(args) {
  return new Promise((resolve, reject) => {
    const TitleYesNo = titleYesNoRender;
    CallModal.show({
      renderFunction: (props) => (
        <TitleYesNo
          {...defaultArgs(args)}
          onOk={() => {
            props.requestCloseModal();
            resolve(true);
          }}
          onCancel={() => {
            props.requestCloseModal();
            resolve(false);
          }}
        />
      )
    });
  });
}

class TextInputPrompt extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text: props.value || '',
    }
  }
  styles = StyleSheet.create({
    container: {
      flex: 0,
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'stretch',
      minHeight: ITEM_HEIGHT,
      borderBottomWidth: 1,
      borderBottomColor: FONT_COLOR,
      padding: ITEM_PADDING,
    },
    input: {
      minHeight: ITEM_HEIGHT,
      color: FONT_COLOR,
      fontSize: FONT_SIZE,
      textAlign: 'center',
      padding: 0,
    },
  });
  handleChangeText = (text) => {
    this.props.onChangeValue(text);
    this.setState({text});
  }
  render() {
    return (
      <View style={this.styles.container}>
        <TextInput
          style={this.styles.input}
          onChangeText={this.handleChangeText}
          value={this.state.text}
        />
      </View>
    );
  }
}

class CheckBoxPrompt extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectionList: props.value || [],
    }
  }
  render() {
    const Item = defaultItemRender;
    return (
      <View>
        {
          _.map(this.state.selectionList, ({ key, value, selected }, index) => (
            <Item
              key={key}
              last={this.props.autoSubmit && index === this.state.selectionList.length - 1}
              onPress={() => {
                let newSelectionList;
                if (this.props.multiple) {
                  newSelectionList = _.map(this.state.selectionList, (selection) => {
                    let result = Object.assign({}, selection);
                    if (selection.key === key) {
                      Object.assign(result, {
                        selected: !selection.selected,
                      });
                    }
                    return result;
                  });
                  this.setState({
                    selectionList: newSelectionList,
                  });
                  this.props.onChangeValue(newSelectionList);
                } else {
                  newSelectionList = _.map(this.state.selectionList, (selection) => {
                    let result = {
                      key: selection.key,
                      value: selection.value,
                    };
                    if (selection.key === key) {
                      Object.assign(result, {
                        selected: true,
                      });
                    }
                    return result;
                  });
                }
                this.setState({
                  selectionList: newSelectionList,
                });
                this.props.onChangeValue(newSelectionList);
              }}
              text={`${(selected === true)?'V ': ''}${value}`}
            />
          ))
        }
      </View>
    );
  }
}

exports.prompt = async function(args) {
  return new Promise((resolve, reject) => {
    const TitleYesNo = titleYesNoRender;
    const input = defaultArgs(args);
    CallModal.show({
      renderFunction: class extends Component {
        constructor(props) {
          super(props);
          this.state = {
            value: props.value,
          }
        }
        handleValueChange = (value) => {
          this.setState({value});
          if (input.autoSubmit) {
            this.submitValue(value);
          }
        };
        handleSubmit = (value) => {
          this.submitValue(this.state.value);
        };
        handleCancel = () => {
          this.props.requestCloseModal();
          resolve();
        };
        submitValue = (value) => {
          this.props.requestCloseModal();
          let result = value;
          if (!_.isString(result)) {
            result = _.filter(result, ['selected', true]);
            result = _.map(result, 'key').join(',');
          }
          resolve(result);
          if (input.inputType === 'action') {
            const value = _.find(input.value, ['key', result]);
            if (_.isFunction(value.onSelect)) {
              value.onSelect();
            }
          }
        };
        render() {
          let content;
          switch(input.inputType){
            case 'text':
              content = (
                <TextInputPrompt
                  value={input.value}
                  onChangeValue={this.handleValueChange}
                />
              );
              break;
            case 'checkbox':
              content = (
                <CheckBoxPrompt
                  multiple
                  value={input.value}
                  onChangeValue={this.handleValueChange}
                />
              );
              break;
            case 'select':
              content = (
                <CheckBoxPrompt
                  autoSubmit={input.autoSubmit}
                  value={input.value}
                  onChangeValue={this.handleValueChange}
                />
              );
              break;
            case 'action':
              content = (
                <CheckBoxPrompt
                  autoSubmit={input.autoSubmit}
                  value={input.value}
                  onChangeValue={this.handleValueChange}
                />
              );
          }
          return (
            <TitleYesNo
              {...input}
              onOk={!input.autoSubmit && this.handleSubmit}
              onCancel={!input.autoSubmit && this.handleCancel}
            >
              {content}
            </TitleYesNo>
          )
        }
      }
    });
  });
}

module.exports = exports;<|endoftext|>


<commit_before>/*
 * CS3283/4 dataModifier.js
 * This acts as a facade class for modifying and update data for storage facade
 *
 */

import dataAdd from 'src/database/data-modifier/dataAdd';
import dataDelete from 'src/database/data-modifier/dataDelete';
import dataUpdate from 'src/database/data-modifier/dataUpdate';
import exceptions from 'src/database/exceptions';
import SqlCommands from 'src/database/sql-related/sqlCommands';
import StringManipulator from 'src/database/stringManipulation';

export default class dataModifier {
  static constructor() {}

  static deleteAllEntities(databaseName) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataDelete.deleteAllEntities(databaseName)
        .then(data => resolve(data))
        .catch(sqlErr => reject(sqlErr))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static createNewFile(organizationId, filePath, folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataAdd.createNewFile(organizationId, filePath, folderId)
        .then(fileId => resolve(fileId))
        .catch(sqlErr => reject(sqlErr))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static createNewFolder(organizationId, folderPath, folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataAdd.createNewFolder(organizationId, folderPath, folderId)
        .then(data => resolve(data))
        .catch(sqlErr => reject(sqlErr))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static saveFile(fileId, file) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataUpdate.saveFile(fileId, file)
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static deleteFile(fileId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataDelete.deleteFile(fileId)
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static deleteFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataDelete.deleteFolder(folderId)
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }
}
<commit_msg>Add resolveFileSaving function in dataModifier.js<commit_after>/*
 * CS3283/4 dataModifier.js
 * This acts as a facade class for modifying and update data for storage facade
 *
 */

import dataAdd from 'src/database/data-modifier/dataAdd';
import dataDelete from 'src/database/data-modifier/dataDelete';
import dataUpdate from 'src/database/data-modifier/dataUpdate';
import exceptions from 'src/database/exceptions';
import SqlCommands from 'src/database/sql-related/sqlCommands';
import StringManipulator from 'src/database/stringManipulation';

const stringManipulator = new StringManipulator();

const sqlCommands = new SqlCommands();

function resolveFileSaving(fileContent) {
  return stringManipulator.replaceAll(fileContent, '"', '\\"');
}

export default class dataModifier {
  static constructor() {}

  static deleteAllEntities(databaseName) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataDelete.deleteAllEntities(databaseName)
        .then(data => resolve(data))
        .catch(sqlErr => reject(sqlErr))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static createNewFile(organizationId, filePath, folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataAdd.createNewFile(organizationId, filePath, folderId)
        .then(fileId => resolve(fileId))
        .catch(sqlErr => reject(sqlErr))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static createNewFolder(organizationId, folderPath, folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataAdd.createNewFolder(organizationId, folderPath, folderId)
        .then(data => resolve(data))
        .catch(sqlErr => reject(sqlErr))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static saveFile(fileId, file) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataUpdate.saveFile(fileId, file)
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static deleteFile(fileId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataDelete.deleteFile(fileId)
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static deleteFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataDelete.deleteFolder(folderId)
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }
}
<|endoftext|>


<commit_before>/**
 * 获取url传值
 *
 * @param {String} name
 * @return {String}
 */
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

/**
 * 添加cookie
 *
 * @param {String} name
 * @param {String} value
 * @param {Number} expireHours
 */
function addcookie(name, value, expireHours) {
    var cookieString = name + "=" + escape(value) + "; path=/";
    // 判断是否设置过期时间
    if (expireHours > 0) {
        var date = new Date();
        date.setTime(date.getTime + expireHours * 3600 * 1000);
        cookieString = cookieString + "; expire=" + date.toGMTString();
    }
    document.cookie = cookieString;
}

/**
 * 获取cookie
 *
 * @param {String} name
 * @return {String}
 */
function getcookie(name) {
    var strcookie = document.cookie;
    var arrcookie = strcookie.split("; ");
    for (var i = 0; i < arrcookie.length; i++) {
        var arr = arrcookie[i].split("=");
        if (arr[0] == name) return arr[1];
    }
    return "";
}

/**
 * 删除cookie
 *
 * @param {String} name
 */
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getcookie(name);
    if (cval != null) document.cookie = name + "=" + cval + "; path=/;expires=" + exp.toGMTString();
}

/**
 * 手机号码判断
 *
 * @param {String} val
 * @return {Boolean}
 */
function isMobileNumber(val) {
    if (!(/^1[3|4|5|7|8][0-9]\d{8}$/.test(val))) {
        return false;
    } else {
        return true;
    }
}

/**
 * 返回上一层
 */
function goback() {
    window.history.go(-1);
    setTimeout(function () {
        window.location.href = "/";
    }, 500);
}

/**
 * 判断是否为身份证
 * 来源于网络
 *
 * @param {String} num
 * @return {Boolean}
 */
function isIdCardNo(num) {
    var num = num.toUpperCase(),
    len = num.length,
    re;
    if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))) {
        return false;
    }
    else {
        if (len == 15) {
            re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
            splitArr = num.match(re);
            // 检查生日日期是否正确 如19850843 或者 20000843
            var dtmBirth = new Date('19' + splitArr[2] + '/' + splitArr[3] + '/' + splitArr[4]);
            if (!((dtmBirth.getYear() == Number(splitArr[2])) && ((dtmBirth.getMonth() + 1) == Number(splitArr[3])) && (dtmBirth.getDate() == Number(splitArr[4])))) {
                // alert('输入的身份证号里出生日期不对！');
                return false;
            }
            else {
                return true;
            }
        }
        else if (len == 18) {
            re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
            var splitArr = num.match(re);
            var dtmBirth = new Date(splitArr[2] + "/" + splitArr[3] + "/" + splitArr[4]);
            if (!((dtmBirth.getFullYear() == Number(splitArr[2])) && ((dtmBirth.getMonth() + 1) == Number(splitArr[3])) && (dtmBirth.getDate() == Number(splitArr[4])))) {
                // alert('输入的身份证号里出生日期不对！');
                return false;
            }
            // 检验18位身份证的校验码是否正确。
            // 校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            var checkNum;
            var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            var nTemp = 0, i;
            for (i = 0; i < 17; i++) {
                nTemp += num.substr(i, 1) * arrInt[i];
            }
            checkNum = arrCh[nTemp % 11];
            if (checkNum != num.substr(17, 1)) {
                // alert('18位身份证的校验码不正确！应该为：' + checkNum);
                return false;
            }
            else {
                return true;
            }
        }

    }
}

/**
 * 判断是否为2~15字姓名
 *
 * @param {String} name
 * @return {Boolean}
 */
function isChineseName(name) {
    reg = /^[\u4E00-\u9FA5]{2,15}$/;
    if (!reg.test(name)) {
        return false;
    } else {
        return true;
    }
}

/**
 * 预加载图片
 *
 * @param {String|Array} urls
 */
function preLoadImages(urls) {// 可以是String Array或者String
    var argsLen = arguments.length,
        loadImage = function (url) {
            var img = new Image();
            img.src = url;
        };
    if (argsLen == 1) {
        if (typeof (urls) == "string" && (sLen = urls.length) > 1) {// 预加载一个图片
            loadImage(urls);
        }
        else if (Object.prototype.toString.call(arguments[0]) == "[object Array]" && urls.length > 0) {// 预加载多个图片
            for (var i = 0; i < urls.length; i++) {
                loadImage(urls[i]);
            }
        }
    }
}

/**
 * input输入框特殊字符过滤
 */
function filtInputValue(input) {
    var pattern = new RegExp("[%--`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——| {}【】‘’\"；：”“'。，、？]");        // 格式 RegExp("[在中间定义特殊过滤字符]")
    var s = input.value;
    var rs = "";
    for (var i = 0; i < s.length; i++) {
        rs = rs + s.substr(i, 1).replace(pattern, '');
    }
    input.value = rs;
}

/**
 * 对象拷贝
 *
 * @param {Object} target
 * @param {Object} source
 * @return {Object}
 */
function extend(target, source) {
    var length = arguments.length;
    if (length == 1) {
        source = arguments[0];
        target = this;
    }
    for (var p in source) {
        if (source.hasOwnProperty(p)) {
            target[p] = source[p];
        }
    }
    return target;
}

/**
 * 回到頂部缓动效果
 * @author rid.k
 *
 * @param {Float|undefine} acceleration
 * @param {Number|undefine} time
 */
function goTop(acceleration, time) {
    acceleration = acceleration || 0.1;
    time = time || 16;
    var x1 = 0;
    var y1 = 0;
    var x2 = 0;
    var y2 = 0;
    var x3 = 0;
    var y3 = 0;
    if (document.documentElement) {
        x1 = document.documentElement.scrollLeft || 0;
        y1 = document.documentElement.scrollTop || 0;
    }
    if (document.body) {
        x2 = document.body.scrollLeft || 0;
        y2 = document.body.scrollTop || 0;
    }
    x3 = window.scrollX || 0;
    y3 = window.scrollY || 0;
    // 滚动条到页面顶部的水平距离
    var x = Math.max(x1, Math.max(x2, x3));
    // 滚动条到页面顶部的垂直距离
    var y = Math.max(y1, Math.max(y2, y3));
    // 滚动距离 = 目前距离 / 速度, 因为距离原来越小, 速度是大于 1 的数, 所以滚动距离会越来越小
    var speed = 1 + acceleration;
    window.scrollTo(Math.floor(x / speed), Math.floor(y / speed));
    // 如果距离不为零, 继续调用迭代本函数
    if (x > 0 || y > 0) {
        var invokeFunction = "goTop(" + acceleration + ", " + time + ")";
        window.setTimeout(invokeFunction, time);
    }
};
<commit_msg>优化返回顶部函数<commit_after>/**
 * 获取url传值
 *
 * @param {String} name
 * @return {String}
 */
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

/**
 * 添加cookie
 *
 * @param {String} name
 * @param {String} value
 * @param {Number} expireHours
 */
function addcookie(name, value, expireHours) {
    var cookieString = name + "=" + escape(value) + "; path=/";
    // 判断是否设置过期时间
    if (expireHours > 0) {
        var date = new Date();
        date.setTime(date.getTime + expireHours * 3600 * 1000);
        cookieString = cookieString + "; expire=" + date.toGMTString();
    }
    document.cookie = cookieString;
}

/**
 * 获取cookie
 *
 * @param {String} name
 * @return {String}
 */
function getcookie(name) {
    var strcookie = document.cookie;
    var arrcookie = strcookie.split("; ");
    for (var i = 0; i < arrcookie.length; i++) {
        var arr = arrcookie[i].split("=");
        if (arr[0] == name) return arr[1];
    }
    return "";
}

/**
 * 删除cookie
 *
 * @param {String} name
 */
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getcookie(name);
    if (cval != null) document.cookie = name + "=" + cval + "; path=/;expires=" + exp.toGMTString();
}

/**
 * 手机号码判断
 *
 * @param {String} val
 * @return {Boolean}
 */
function isMobileNumber(val) {
    if (!(/^1[3|4|5|7|8][0-9]\d{8}$/.test(val))) {
        return false;
    } else {
        return true;
    }
}

/**
 * 返回上一层
 */
function goback() {
    window.history.go(-1);
    setTimeout(function () {
        window.location.href = "/";
    }, 500);
}

/**
 * 判断是否为身份证
 * 来源于网络
 *
 * @param {String} num
 * @return {Boolean}
 */
function isIdCardNo(num) {
    var num = num.toUpperCase(),
    len = num.length,
    re;
    if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))) {
        return false;
    }
    else {
        if (len == 15) {
            re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
            splitArr = num.match(re);
            // 检查生日日期是否正确 如19850843 或者 20000843
            var dtmBirth = new Date('19' + splitArr[2] + '/' + splitArr[3] + '/' + splitArr[4]);
            if (!((dtmBirth.getYear() == Number(splitArr[2])) && ((dtmBirth.getMonth() + 1) == Number(splitArr[3])) && (dtmBirth.getDate() == Number(splitArr[4])))) {
                // alert('输入的身份证号里出生日期不对！');
                return false;
            }
            else {
                return true;
            }
        }
        else if (len == 18) {
            re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
            var splitArr = num.match(re);
            var dtmBirth = new Date(splitArr[2] + "/" + splitArr[3] + "/" + splitArr[4]);
            if (!((dtmBirth.getFullYear() == Number(splitArr[2])) && ((dtmBirth.getMonth() + 1) == Number(splitArr[3])) && (dtmBirth.getDate() == Number(splitArr[4])))) {
                // alert('输入的身份证号里出生日期不对！');
                return false;
            }
            // 检验18位身份证的校验码是否正确。
            // 校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            var checkNum;
            var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            var nTemp = 0, i;
            for (i = 0; i < 17; i++) {
                nTemp += num.substr(i, 1) * arrInt[i];
            }
            checkNum = arrCh[nTemp % 11];
            if (checkNum != num.substr(17, 1)) {
                // alert('18位身份证的校验码不正确！应该为：' + checkNum);
                return false;
            }
            else {
                return true;
            }
        }

    }
}

/**
 * 判断是否为2~15字姓名
 *
 * @param {String} name
 * @return {Boolean}
 */
function isChineseName(name) {
    reg = /^[\u4E00-\u9FA5]{2,15}$/;
    if (!reg.test(name)) {
        return false;
    } else {
        return true;
    }
}

/**
 * 预加载图片
 *
 * @param {String|Array} urls
 */
function preLoadImages(urls) {// 可以是String Array或者String
    var argsLen = arguments.length,
        loadImage = function (url) {
            var img = new Image();
            img.src = url;
        };
    if (argsLen == 1) {
        if (typeof (urls) == "string" && (sLen = urls.length) > 1) {// 预加载一个图片
            loadImage(urls);
        }
        else if (Object.prototype.toString.call(arguments[0]) == "[object Array]" && urls.length > 0) {// 预加载多个图片
            for (var i = 0; i < urls.length; i++) {
                loadImage(urls[i]);
            }
        }
    }
}

/**
 * input输入框特殊字符过滤
 */
function filtInputValue(input) {
    var pattern = new RegExp("[%--`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——| {}【】‘’\"；：”“'。，、？]");        // 格式 RegExp("[在中间定义特殊过滤字符]")
    var s = input.value;
    var rs = "";
    for (var i = 0; i < s.length; i++) {
        rs = rs + s.substr(i, 1).replace(pattern, '');
    }
    input.value = rs;
}

/**
 * 对象拷贝
 *
 * @param {Object} target
 * @param {Object} source
 * @return {Object}
 */
function extend(target, source) {
    var length = arguments.length;
    if (length == 1) {
        source = arguments[0];
        target = this;
    }
    for (var p in source) {
        if (source.hasOwnProperty(p)) {
            target[p] = source[p];
        }
    }
    return target;
}

/**
 * 回到顶部缓动效果
 * @author rid.k ,Edited by Nelson 20160822
 *
 * @param {Float|undefine} acceleration
 * @param {Number|undefine} time
 */
function goTop(acceleration, time) {
    acceleration = acceleration || -0.02;
    time = time || 16; // 1秒内播放60帧以上(1000 / 60 = 16.6667)肉眼就不会觉得眩晕，感觉是平滑过度
    var y1 = 0;
    var y2 = 0;
    var y3 = 0;
    if (document.documentElement) {
        y1 = document.documentElement.scrollTop || 0;
    }
    if (document.body) {
        y2 = document.body.scrollTop || 0;
    }
    y3 = window.scrollY || 0;
    // 滚动条到页面顶部的垂直距离
    var y = Math.max(y1, Math.max(y2, y3));
    // 在相同的时间，因为要距离原来越小,直到0为止，
    // Δs = vt - at^2/2  下面将采用近似法
    // v = at
    // => s = at^2/2
    // => t = Math.sqrt(-2*y/acceleration)
    // => v = acceleration * Math.sqrt(-2*y/acceleration)
    // => Δs = vt = acceleration * Math.sqrt(-2*y/acceleration) * time 采用近似法
    var s = acceleration * Math.sqrt(-2 * y / acceleration) * time;
    window.scrollTo(0, Math.floor(y + s));
    // 如果距离不为零, 继续调用迭代本函数
    if (y > 0) {
        var invokeFunction = "goTop(" + acceleration + ", " + time + ")";
        window.setTimeout(invokeFunction, time);
    }
};

<|endoftext|>


<commit_before>// Implements something like the rudiments of the Python struct class;
// you can give it a format string and it will attempt to parse a stream
// of bytes or into numbers of different sizes, or format a stream of bytes
// from a set of values, corresponding to the format.

utils = function() {
    var extractString = function(bytes, start, len) {
        if (!len) {
            len = bytes.length;
        }
        var s = '';
        for (var i=start; i<start + len; ++i) {
            s += String.fromCharCode(bytes[i]);
        }
        return s;
    };
    // extract a null-terminated string of at most len bytes
    var extractZString = function(bytes, start, len) {
        if (!len) {
            len = bytes.length;
        }
        var s = '';
        for (var i=start; i<start + len; ++i) {
            if (bytes[i]) {
                s += String.fromCharCode(bytes[i]);
            } else {
                break;
            }
        }
        return s;
    };
    var extractInt = function(b, st) {
        // because js always does bit shift on 32-bit values and treats them
        // as signed, we have to fake it out by doing a multiply instead of
        // a shift on the largest value.
        return ((16777216 * b[st+3]) + (b[st+2] << 16) + (b[st+1] << 8) + b[st]);
    };
    var extractSignedInt = function(b, st) {
        return ((b[st+3] << 24) + (b[st+2] << 16) + (b[st+1] << 8) + b[st]);
    };
    var extractShort = function(b, st) {
        return ((b[st+1] << 8) + b[st]);
    };
    var extractByte = function(b, st) {
        return b[st];
    };
    // get a big-endian int
    var extractBEInt = function(b, st) {
        // because js always does bit shift on 32-bit values and treats them
        // as signed, we have to fake it out by doing a multiply instead of
        // a shift on the largest value.
        return ((16777216 * b[st]) + (b[st+1] << 16) + (b[st+2] << 8) + b[st+3]);
    };
    var extractSignedBEInt = function(b, st) {
        return ((b[st] << 24) + (b[st+1] << 16) + (b[st+2] << 8) + b[st+3]);
    };
    // get a big-endian short
    var extractBEShort = function(b, st) {
        return ((b[st] << 8) + b[st+1]);
    };
    var extractNothing = function() {
        return 0;
    };
    var storeInt = function(v, b, st) {
        b[st] = v & 0xFF;
        b[st + 1] = (v >> 8) & 0xFF;
        b[st + 2] = (v >> 16) & 0xFF;
        b[st + 3] = (v >> 24) & 0xFF;
    };
    var storeBEInt = function(v, b, st) {
        b[st + 3] = v & 0xFF;
        b[st + 2] = (v >> 8) & 0xFF;
        b[st + 1] = (v >> 16) & 0xFF;
        b[st] = (v >> 24) & 0xFF;
    };
    var storeShort = function(v, b, st) {
        b[st] = v & 0xFF;
        b[st + 1] = (v >> 8) & 0xFF;
    };
    var storeBEShort = function(v, b, st) {
        b[st + 1] = v & 0xFF;
        b[st] = (v >> 8) & 0xFF;
    };
    var storeByte = function(v, b, st) {
        b[st] = v & 0xFF;
    };
    var storeString = function(v, b, st) {
        var i=0;
        while (i<v.length) {
            b[st + i] = v[i];
            ++i;
        }
        b[st + i] = 0;
    };
    var storeNothing = function() {
    };

    var fields = {
        'i': { len: 4, put: storeInt, get: extractInt },
        'n': { len: 4, put: storeInt, get: extractSignedInt },
        's': { len: 2, put: storeShort, get: extractShort },
        'b': { len: 1, put: storeByte, get: extractByte },
        'I': { len: 4, put: storeBEInt, get: extractBEInt },
        'N': { len: 4, put: storeBEInt, get: extractSignedBEInt },
        'S': { len: 2, put: storeBEShort, get: extractBEShort },
        'z': { len: 0, put: storeString, get: extractZString },
        'Z': { len: 0, put: storeString, get: extractString },
    };

    var parseformat = function(format, names) {
        var formats = [];
        if (names == null)
            names = [];
        var nameindex = 0;
        var pat = /([0-9]*)([a-zA-Z.])/g;
        var a;
        var offset = 0;
        while ((a = pat.exec(format)) !== null) {
            var fmt = {};
            var count = 1;
            if (a[1]) {
                count = parseInt(a[1], 10);
            }
            var f = a[2];
            // we treat Z and z specially -- the length field is their
            // maximum length
            if (f === 'z' || f === 'Z') {
                fmt.len = count;
                fmt.offset = offset;
                offset += fmt.len;
                fmt.get = fields[f].get;
                fmt.put = fields[f].put;
                if (names[nameindex]) {
                    fmt.name = names[nameindex++];
                } else {
                    fmt.name = '_field_' + nameindex++;
                }
                formats.push(fmt);
            }
            else if (fields[f]) {
                for (var j=0; j<count; ++j) {
                    fmt.len = fields[f].len;
                    fmt.offset = offset;
                    offset += fmt.len;
                    fmt.get = fields[f].get;
                    fmt.put = fields[f].put;
                    if (names[nameindex]) {
                        fmt.name = names[nameindex++];
                    } else {
                        fmt.name = '_field_' + nameindex++;
                    }
                    formats.push(_.clone(fmt));
                }
            } else {
                fmt.len = count;
                fmt.offset = offset;
                offset += fmt.len;
                fmt.get = extractNothing;
                fmt.put = storeNothing;
                fmt.name = null;
                formats.push(fmt);
            }
        }
        return formats;

    };

    var structlen = function(s) {
        var fmts = parseformat(s);
        var t = 0;
        for (var i = 0; i < fmts.length; ++i) {
            t += fmts[i].len;
        }
        return t;
    };

    var pack = function(buf, offset, format) {
        var fmts = parseformat(format);

        var ctr = 0;
        for (var i=0; i < fmts.length; ++i) {
            fmts[i].put(arguments[i+3], buf, offset + ctr, fmts[i].len);
            ctr += fmts[i].len;
        }
        return ctr;
    };

    var createUnpacker = function() {
        return {
            format: '',
            names: [],
            add: function(fmts, nms) {
                this.format += fmts;
                this.names = this.names.concat(nms);
            },
            go: function(buf, offset, o) {
                return unpack(buf, offset, this.format, this.names, o);
            }
        };
    };

    // buf is an indexable array of bytes
    // offset is the starting offset within buf to unpack the structure
    // format is a format string
    // names is an array of names (within the result object) to store the
    // unpacked data; if a name is '_' the field is not stored.
    // o is the result object -- if it does not exist, it will be created
    // returns (and potentially modifies o)
    var unpack = function(buf, offset, format, names, o) {
        var result;
        if (o != null) {
            result = o;
        } else {
            result = {};
        }

        var fmts = parseformat(format, names);

        var ctr = 0;
        for (var i=0; i < fmts.length; ++i) {
            var value = fmts[i].get(buf, offset + ctr, fmts[i].len);
            if (fmts[i].name != null) {
                result[fmts[i].name] = value;
            }
            ctr += fmts[i].len;
        }
        result.unpack_length = ctr;
        // result.formats = fmts;
        return result;
    };

    var copyBytes = function(buf, offset, bytes, bytecount) {
        for (var i = 0; i < bytecount; ++i) {
            buf[offset + i] = bytes[i];
        }
        return bytecount;
    };

    var test = function() {
        var l = structlen('b6.Si');
        console.log(l);
        var p = parseformat('2ibsi4.b32z', 'abcd');
        console.log(p);
        var buf = new Uint8Array(32);
        var len = pack(buf, 0, 'iI2bsSb', 254, 65534, 55, 66, 1023, 256, 7);
        console.log(len);
        console.log(buf);
        var result = unpack(buf, 0, 'iI2bsS.', ['a', 'b', 'c', 'd', 'e', 'f']);
        console.log(result);
        buf[0] = 0xff;
        buf[1] = 0xff;
        buf[2] = 0xff;
        buf[3] = 0xff;
        result = unpack(buf, 0, 'i', ['x']);
        console.log(result);
        var v = [0, 30, 0, 0, 0, 1, 0, 7, 0, 0, 0, 1, 0, 7, 73, 110, 115, 117, 108, 101, 116, 0, 79, 109, 110, 105, 80, 111, 100, 0, 5, 170];
        for (var i = 0; i < v.length; ++i) {
            buf[i] = v[i];
        }
        result = unpack(buf, 0, '7S8z8zS', ['l', 'b', 'c', 'd', 'e', 'f', 'g', 's1', 's2', 'ck']);
        len = structlen('7S8z8zS');
        console.log(v.length, len);
        console.log(result);
    };

    return {
        extractString: extractString,
        extractZString: extractZString,
        extractInt: extractInt,
        extractShort: extractShort,
        extractByte: extractByte,
        extractBEInt: extractBEInt,
        extractBEShort: extractBEShort,
        storeInt: storeInt,
        storeBEInt: storeBEInt,
        storeShort: storeShort,
        storeBEShort: storeBEShort,
        storeByte: storeByte,
        storeString: storeString,
        pack: pack,
        createUnpacker: createUnpacker,
        unpack: unpack,
        structlen: structlen,
        copyBytes: copyBytes,
        test: test
    };
};

<commit_msg>cleanup a bit<commit_after>// Implements something like the rudiments of the Python struct class;
// you can give it a format string and it will attempt to parse a stream
// of bytes or into numbers of different sizes, or format a stream of bytes
// from a set of values, corresponding to the format.

utils = function() {
    var extractString = function(bytes, start, len) {
        if (!len) {
            len = bytes.length;
        }
        var s = '';
        for (var i=start; i<start + len; ++i) {
            s += String.fromCharCode(bytes[i]);
        }
        return s;
    };
    // extract a null-terminated string of at most len bytes
    var extractZString = function(bytes, start, len) {
        if (!len) {
            len = bytes.length;
        }
        var s = '';
        for (var i=start; i<start + len; ++i) {
            if (bytes[i]) {
                s += String.fromCharCode(bytes[i]);
            } else {
                break;
            }
        }
        return s;
    };
    var extractInt = function(b, st) {
        // because js always does bit shift on 32-bit values and treats them
        // as signed, we have to fake it out by doing a multiply instead of
        // a shift on the largest value.
        return ((16777216 * b[st+3]) + (b[st+2] << 16) + (b[st+1] << 8) + b[st]);
    };
    var extractSignedInt = function(b, st) {
        return ((b[st+3] << 24) + (b[st+2] << 16) + (b[st+1] << 8) + b[st]);
    };
    var extractShort = function(b, st) {
        return ((b[st+1] << 8) + b[st]);
    };
    var extractByte = function(b, st) {
        return b[st];
    };
    // get a big-endian int
    var extractBEInt = function(b, st) {
        // because js always does bit shift on 32-bit values and treats them
        // as signed, we have to fake it out by doing a multiply instead of
        // a shift on the largest value.
        return ((16777216 * b[st]) + (b[st+1] << 16) + (b[st+2] << 8) + b[st+3]);
    };
    var extractSignedBEInt = function(b, st) {
        return ((b[st] << 24) + (b[st+1] << 16) + (b[st+2] << 8) + b[st+3]);
    };
    // get a big-endian short
    var extractBEShort = function(b, st) {
        return ((b[st] << 8) + b[st+1]);
    };
    var extractNothing = function() {
        return 0;
    };
    var storeInt = function(v, b, st) {
        b[st] = v & 0xFF;
        b[st + 1] = (v >> 8) & 0xFF;
        b[st + 2] = (v >> 16) & 0xFF;
        b[st + 3] = (v >> 24) & 0xFF;
    };
    var storeBEInt = function(v, b, st) {
        b[st + 3] = v & 0xFF;
        b[st + 2] = (v >> 8) & 0xFF;
        b[st + 1] = (v >> 16) & 0xFF;
        b[st] = (v >> 24) & 0xFF;
    };
    var storeShort = function(v, b, st) {
        b[st] = v & 0xFF;
        b[st + 1] = (v >> 8) & 0xFF;
    };
    var storeBEShort = function(v, b, st) {
        b[st + 1] = v & 0xFF;
        b[st] = (v >> 8) & 0xFF;
    };
    var storeByte = function(v, b, st) {
        b[st] = v & 0xFF;
    };
    var storeString = function(v, b, st) {
        var i=0;
        while (i<v.length) {
            b[st + i] = v[i];
            ++i;
        }
        b[st + i] = 0;
    };
    var storeNothing = function() {
    };

    var fields = {
        'i': { len: 4, put: storeInt, get: extractInt },
        'n': { len: 4, put: storeInt, get: extractSignedInt },
        's': { len: 2, put: storeShort, get: extractShort },
        'b': { len: 1, put: storeByte, get: extractByte },
        'I': { len: 4, put: storeBEInt, get: extractBEInt },
        'N': { len: 4, put: storeBEInt, get: extractSignedBEInt },
        'S': { len: 2, put: storeBEShort, get: extractBEShort },
        'z': { len: 0, put: storeString, get: extractZString },
        'Z': { len: 0, put: storeString, get: extractString },
    };

    var parseformat = function(format, names) {
        var formats = [];
        if (names == null)
            names = [];
        var nameindex = 0;
        var pat = /([0-9]*)([a-zA-Z.])/g;
        var a;
        var offset = 0;
        while ((a = pat.exec(format)) !== null) {
            var fmt = {};
            var count = 1;
            if (a[1]) {
                count = parseInt(a[1], 10);
            }
            var f = a[2];
            // we treat Z and z specially -- the length field is their
            // maximum length
            if (f === 'z' || f === 'Z') {
                fmt.len = count;
                fmt.offset = offset;
                offset += fmt.len;
                fmt.get = fields[f].get;
                fmt.put = fields[f].put;
                if (names[nameindex]) {
                    fmt.name = names[nameindex++];
                } else {
                    fmt.name = '_field_' + nameindex++;
                }
                formats.push(fmt);
            }
            else if (fields[f]) {
                for (var j=0; j<count; ++j) {
                    fmt.len = fields[f].len;
                    fmt.offset = offset;
                    offset += fmt.len;
                    fmt.get = fields[f].get;
                    fmt.put = fields[f].put;
                    if (names[nameindex]) {
                        fmt.name = names[nameindex++];
                    } else {
                        fmt.name = '_field_' + nameindex++;
                    }
                    formats.push(_.clone(fmt));
                }
            } else {
                fmt.len = count;
                fmt.offset = offset;
                offset += fmt.len;
                fmt.get = extractNothing;
                fmt.put = storeNothing;
                fmt.name = null;
                formats.push(fmt);
            }
        }
        return formats;

    };

    var structlen = function(s) {
        var fmts = parseformat(s);
        var t = 0;
        for (var i = 0; i < fmts.length; ++i) {
            t += fmts[i].len;
        }
        return t;
    };

    var pack = function(buf, offset, format) {
        var fmts = parseformat(format);

        for (var i=0; i < fmts.length; ++i) {
            fmts[i].put(arguments[i+3], buf, offset + fmts[i].offset, fmts[i].len);
        }
        // inefficient but probably doesn't ever matter
        return structlen(format);
    };

    // This is if you prefer to build things with a chaining api
    var createUnpacker = function() {
        return {
            format: '',
            names: [],
            add: function(fmts, nms) {
                this.format += fmts;
                this.names = this.names.concat(nms);
            },
            go: function(buf, offset, o) {
                return unpack(buf, offset, this.format, this.names, o);
            }
        };
    };

    // buf is an indexable array of bytes
    // offset is the starting offset within buf to unpack the structure
    // format is a format string
    // names is an array of names (within the result object) to store the
    // unpacked data; if a name is '_' the field is not stored.
    // o is the result object -- if it does not exist, it will be created
    // returns (and potentially modifies o)
    var unpack = function(buf, offset, format, names, o) {
        var result;
        if (o != null) {
            result = o;
        } else {
            result = {};
        }

        var fmts = parseformat(format, names);

        for (var i=0; i < fmts.length; ++i) {
            var value = fmts[i].get(buf, offset + fmts[i].offset, fmts[i].len);
            if (fmts[i].name != null) {
                result[fmts[i].name] = value;
            }
        }
        // result.formats = fmts;
        return result;
    };

    var copyBytes = function(buf, offset, bytes, bytecount) {
        for (var i = 0; i < bytecount; ++i) {
            buf[offset + i] = bytes[i];
        }
        return bytecount;
    };

    var test = function() {
        var l = structlen('b6.Si');
        console.log(l);
        var p = parseformat('2ibsi4.b32z', 'abcd');
        console.log(p);
        var buf = new Uint8Array(32);
        var len = pack(buf, 0, 'iI2bsSb', 254, 65534, 55, 66, 1023, 256, 7);
        console.log(len);
        console.log(buf);
        var result = unpack(buf, 0, 'iI2bsS.', ['a', 'b', 'c', 'd', 'e', 'f']);
        console.log(result);
        buf[0] = 0xff;
        buf[1] = 0xff;
        buf[2] = 0xff;
        buf[3] = 0xff;
        result = unpack(buf, 0, 'i', ['x']);
        console.log(result);
        var v = [0, 30, 0, 0, 0, 1, 0, 7, 0, 0, 0, 1, 0, 7, 73, 110, 115, 117, 108, 101, 116, 0, 79, 109, 110, 105, 80, 111, 100, 0, 5, 170];
        for (var i = 0; i < v.length; ++i) {
            buf[i] = v[i];
        }
        result = unpack(buf, 0, '7S8z8zS', ['l', 'b', 'c', 'd', 'e', 'f', 'g', 's1', 's2', 'ck']);
        len = structlen('7S8z8zS');
        console.log(v.length, len);
        console.log(result);
    };

    return {
        extractString: extractString,
        extractZString: extractZString,
        extractInt: extractInt,
        extractShort: extractShort,
        extractByte: extractByte,
        extractBEInt: extractBEInt,
        extractBEShort: extractBEShort,
        storeInt: storeInt,
        storeBEInt: storeBEInt,
        storeShort: storeShort,
        storeBEShort: storeBEShort,
        storeByte: storeByte,
        storeString: storeString,
        pack: pack,
        createUnpacker: createUnpacker,
        unpack: unpack,
        structlen: structlen,
        copyBytes: copyBytes,
        test: test
    };
};

<|endoftext|>


<commit_before>/**
 * 矩形クラス
 */

function Rect(){
	return;
}
Rect.prototype = {
	init: function (x, y, w, h)
	{
		this.x = x;
		this.y = y;
		this.w = w;
		this.h = h;
		this.ex = x + w;
		this.ey = y + h;

		this.overlapRect = [];
		this.appendRect = [];
	},

	isContain: function(x, y)
	{
		//OR//
		var orResult = false, i, len;
		// if(this.x <= x && this.y <= y && (this.x + this.w) > x && (this.y + this.h) > y){
		if(this.x <= x && this.y <= y && this.ex > x && this.ey > y){
			orResult |= true;
		}
		len = this.appendRect.length;
		if(len > 0){
			for(i = 0; i < len; i++){
				if(this.appendRect[i].isContain(x, y)){
					orResult |= true;
					break;
				}
			}
		}
		//OR//

		return orResult;
	},

	isOverlap: function(r)
	{
		var orResult = false, i, len;
		if(this.isContain(r.x, r.y) || this.isContain(r.x, r.ey - 1) || this.isContain(r.ex - 1, r.y) || this.isContain(r.ex - 1, r.ey - 1)){
			orResult |= true;
		}
		len = this.appendRect.length;
		if(len > 0){
			for(i = 0; i < len; i++){
				if(this.appendRect[i].isOverlap(r)){
					orResult |= true;
					break;
				}
			}
		}

		return orResult;
	},

	isFit: function(r)
	{
		var orResult = false, i, len;
		if(r.x == this.x && r.y == this.y && r.ex == this.ex && r.ey == this.ey){
			orResult |= true;
		}
		len = this.appendRect.length;
		if(len > 0){
			for(i = 0; i < len; i++){
				if(this.appendRect[i].isFit(r)){
					orResult |= true;
					break;
				}
			}
		}

		return orResult;
	},

	append: function(add)
	{
		this.appendRect.push(add);
	},
};

/**
 * Make Rect
 * x, y, w, h
 * OR
 * x: [String] space delimiter & *x (startX startY endX endY)
 * x: [Array]
 */
function makeRect(x, y, w, h)
{
	var rects, m = 1, ptp = false, opt
		, reg  = /[x*]([0-9]+)/, c, xf, yf;
	if(typeof x == 'string'){
		x = x.split(' ');
	}
	if(typeof x == 'object'){
		x = x.map(function(a){
			return a.search(/^\d+$/) > -1 ? a | 0 : a;
		});
		opt = x[4] != null ? x[4] : '';
		m = opt != '' && opt.search(reg) > -1 ? opt.replace(reg, '$1') | 0 : m;
		ptp = opt != '' ? opt.search(/:pos/, '') > -1 : ptp;
		if(ptp){
			yf = x[1] > x[3];
			xf = x[0] > x[2];
			h = yf ? x[1] - x[3] + 1: x[3] - x[1] + 1;
			w = xf ? x[0] - x[2] + 1: x[2] - x[0] + 1;
			y = yf ? x[3] : x[1];
			x = xf ? x[2] : x[0];
		}else{
			h = x[3];
			w =x[2];
			y = x[1];
			x = x[0];
		}
	}
	rects = new Rect();
	rects.init(x * m, y * m, w * m, h * m);
	return rects;
}

function Ease(){
		this.count;
		this.range;
		this.start = 0;
		this.division;
		this.time;
		this.func;
	return;
}
Ease.prototype = {
	init: function(s, e, t){
		this.count = 0;
		this.start = s;
		this.end = e;
		this.range = e - s;
		this.time = t;
	},

	exp: function(s, e, t){
		var self = this;
		this.init(s, e, t);
		this.division = t * 0.1;
		this.func = function(){
			return 1 / Math.exp(self.division / (self.count + 1));
		};
	},

	swing: function(s, e, t){
		var self = this;
		this.init(s, e, t);
		this.division = t;
		this.func = function(){
			return 0.5 - Math.cos(self.count * (Math.PI / self.division)) / 2;
		};
	},

	next: function(){
		if(this.func == null){
			return this.start;
		}
		var p = this.func();
		this.count = this.count < this.time ? this.count + 1 : this.time;
		return p * this.range + this.start;
	}
};

/**
 * 0で桁埋め
 * @param keta
 * @param num
 * @returns {String}
 */

function formatNum(num, keta)
{

	var src = num + ''
		, cnt = keta - src.length;
	if (cnt <= 0)
		return src;
	while (cnt-- > 0)
	src = "0" + src;
	return src;
}

/**
 * 指定文字数の空きを文字でうめる
 * default STR_PAD_RIGHT
 * @param input
 * @param pad_length
 * @param pad_string
 * @param pad_type
 * @returns
 */
function str_pad(input, pad_length, pad_string, pad_type)
{
	if(typeof(input) == "number"){
		input = input + "";
	}else if(typeof(input) != "string"){
		return "";
	}
	if(input.length == 0){
		return "";
	}
	if(pad_length != null && input.length >= pad_length){
		if(pad_type == "STR_PAD_LEFT"){
			input = input.slice(input.length - pad_length);
		}else{
			input = input.slice(0, pad_length);
		}
		return input;
	}

	var addcount = pad_length - input.length;
	var addstr = "";

	for(var i = 0; i < addcount; i++){
		addstr += pad_string;
	}

	if(pad_type == "STR_PAD_LEFT"){
		input = addstr + input;
	}else{
		input = input + addstr;
	}

	return input;

//	dulog(charArray);
}

function clone(src){
	var dst, k
	;
	if(typeof src != 'object'){
		return src;
	}
	dst = src instanceof Array ? [] : {};
	for(k in src) {
		dst[k] = typeof src[k] == 'object' && (k != 'prototype' || k != '__proto__') ? clone(src[k]) : src[k];
	}
	return dst;
}

/**
 * APIインターフェース
 */
var APIServer = {url: null};
function initAPIServer(apiUrl)
{
	APIServer.url = apiUrl;
};

function sendToAPIServer(method, api, params, func, errorFunc)
{
	var query = [], key, x = new XMLHttpRequest();
	if(APIServer.url == null){console.error('not initialize api server'); return;}
	if(func != null){
		x.onreadystatechange = function(){
			var j;
			switch(x.readyState){
				case 0:break;//オブジェクト生成
				case 1:break;//オープン
				case 2:break;//ヘッダ受信
				case 3:break;//ボディ受信
				case 4:
							if((200 <= x.status && x.status < 300) || (x.status == 304)){
								j = x.responseText;
								try{
									j = typeof j == 'string' ? JSON.parse(j) : '';
								}catch(e){
									j = null;
								}
								func(j);
								x.abort();
							}else{
								errorFunc();
								x.abort();
							}
							 break;//send()完了
			}
		//	func;
		};
	}
	for(key in params){
		query.push(key + '=' + params[key]);
	}
	str = query.join('&');
	if(method.toUpperCase() == 'GET'){
		x.open(method, APIServer.url + '/' + api + '?' + str , true);
		str = "";
	}else{
		x.open(method, APIServer.url + '/' + api, true);
	}
	x.withCredentials = true;
	x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
	// Set-Cookie:LITROSOUND=8lr6fpmr30focapfnejn807mo5;
	x.send(str);
};

<commit_msg>Rectクラスに再計算メソッド追加<commit_after>/**
 * 矩形クラス
 */

function Rect(){
	return;
}
Rect.prototype = {
	init: function (x, y, w, h)
	{
		this.x = x;
		this.y = y;
		this.w = w;
		this.h = h;
		this.ex = x + w;
		this.ey = y + h;
		this.toString = this.convertString();
		this.overlapRect = [];
		this.appendRect = [];
	},

	isContain: function(x, y)
	{
		//OR//
		var orResult = false, i, len;
		this.reculc();

		// if(this.x <= x && this.y <= y && (this.x + this.w) > x && (this.y + this.h) > y){
		if(this.x <= x && this.y <= y && this.ex > x && this.ey > y){
			orResult = orResult || true;
		}
		len = this.appendRect.length;
		if(len > 0){
			for(i = 0; i < len; i++){
				if(this.appendRect[i].isContain(x, y)){
					orResult = orResult || true;
					break;
				}
			}
		}
		//OR//

		return orResult;
	},

	isOverlap: function(r)
	{
		this.reculc();
		var orResult = false, i, len;
		if(this.isContain(r.x, r.y) || this.isContain(r.x, r.ey - 1) || this.isContain(r.ex - 1, r.y) || this.isContain(r.ex - 1, r.ey - 1)){
			orResult |= true;
		}
		len = this.appendRect.length;
		if(len > 0){
			for(i = 0; i < len; i++){
				if(this.appendRect[i].isOverlap(r)){
					orResult |= true;
					break;
				}
			}
		}

		return orResult;
	},

	isFit: function(r)
	{
		this.reculc();
		var orResult = false, i, len;
		if(r.x == this.x && r.y == this.y && r.ex == this.ex && r.ey == this.ey){
			orResult |= true;
		}
		len = this.appendRect.length;
		if(len > 0){
			for(i = 0; i < len; i++){
				if(this.appendRect[i].isFit(r)){
					orResult |= true;
					break;
				}
			}
		}

		return orResult;
	},

	reculc: function(x, y, w, h)
	{
		var mul = 1;
		if(typeof x == 'string'){
			x = x.trim();
			if(x.indexOf('*') >= 0){
				mul = x.replace('*') | 0;
			}else if(x.indexOf('/') >= 0){
				mul = 1 / x.replace('/');
			}
		}

		this.x = (x != null ? x : this.x) * mul;
		this.y = (y != null ? y : this.y) * mul;
		this.w = (w != null ? w : this.w) * mul;
		this.h= (h != null ? h : this.h) * mul;

		this.ex = this.x + this.w;
		this.ey = this.y + this.h;
	},

	convertString: function()
	{
		return [this.x, this.y, this.w, this.h].join(' ');
	},

	append: function(add)
	{
		this.appendRect.push(add);
	},
};

/**
 * Make Rect
 * x, y, w, h
 * OR
 * x: [String] space delimiter & *x (startX startY endX endY)
 * x: [Array]
 */
function makeRect(x, y, w, h)
{
	var rects, m = 1, ptp = false, opt
		, reg  = /[x*]([0-9]+)/, c, xf, yf;
	if(typeof x == 'string'){
		x = x.split(' ').length > 3 ? x.split(' ') : x;
	}
	if(typeof x == 'object'){
		x = x.map(function(a){
			return a.search(/^\d+$/) > -1 ? a | 0 : a;
		});
		opt = x[4] != null ? x[4] : '';
		m = opt != '' && opt.search(reg) > -1 ? opt.replace(reg, '$1') | 0 : m;
		ptp = opt != '' ? opt.search(/:pos/, '') > -1 : ptp;
		if(ptp){
			yf = x[1] > x[3];
			xf = x[0] > x[2];
			h = yf ? x[1] - x[3] + 1: x[3] - x[1] + 1;
			w = xf ? x[0] - x[2] + 1: x[2] - x[0] + 1;
			y = yf ? x[3] : x[1];
			x = xf ? x[2] : x[0];
		}else{
			h = x[3];
			w =x[2];
			y = x[1];
			x = x[0];
		}
	}
	rects = new Rect();
	rects.init(x * m, y * m, w * m, h * m);
	return rects;
}

function Ease(){
		this.count;
		this.range;
		this.start = 0;
		this.division;
		this.time;
		this.func;
	return;
}
Ease.prototype = {
	init: function(s, e, t){
		this.count = 0;
		this.start = s;
		this.end = e;
		this.range = e - s;
		this.time = t;
	},

	exp: function(s, e, t){
		var self = this;
		this.init(s, e, t);
		this.division = t * 0.1;
		this.func = function(){
			return 1 / Math.exp(self.division / (self.count + 1));
		};
	},

	swing: function(s, e, t){
		var self = this;
		this.init(s, e, t);
		this.division = t;
		this.func = function(){
			return 0.5 - Math.cos(self.count * (Math.PI / self.division)) / 2;
		};
	},

	next: function(){
		if(this.func == null){
			return this.start;
		}
		var p = this.func();
		this.count = this.count < this.time ? this.count + 1 : this.time;
		return p * this.range + this.start;
	}
};

/**
 * 0で桁埋め
 * @param keta
 * @param num
 * @returns {String}
 */

function formatNum(num, keta)
{

	var src = num + ''
		, cnt = keta - src.length;
	if (cnt <= 0)
		return src;
	while (cnt-- > 0)
	src = "0" + src;
	return src;
}

/**
 * 指定文字数の空きを文字でうめる
 * default STR_PAD_RIGHT
 * @param input
 * @param pad_length
 * @param pad_string
 * @param pad_type
 * @returns
 */
function str_pad(input, pad_length, pad_string, pad_type)
{
	if(typeof(input) == "number"){
		input = input + "";
	}else if(typeof(input) != "string"){
		return "";
	}
	if(input.length == 0){
		return "";
	}
	if(pad_length != null && input.length >= pad_length){
		if(pad_type == "STR_PAD_LEFT"){
			input = input.slice(input.length - pad_length);
		}else{
			input = input.slice(0, pad_length);
		}
		return input;
	}

	var addcount = pad_length - input.length;
	var addstr = "";

	for(var i = 0; i < addcount; i++){
		addstr += pad_string;
	}

	if(pad_type == "STR_PAD_LEFT"){
		input = addstr + input;
	}else{
		input = input + addstr;
	}

	return input;

//	dulog(charArray);
}

function clone(src){
	var dst, k
	;
	if(typeof src != 'object'){
		return src;
	}
	dst = src instanceof Array ? [] : {};
	for(k in src) {
		dst[k] = typeof src[k] == 'object' && (k != 'prototype' || k != '__proto__') ? clone(src[k]) : src[k];
	}
	return dst;
}

/**
 * APIインターフェース
 */
var APIServer = {url: null};
function initAPIServer(apiUrl)
{
	APIServer.url = apiUrl;
};

function sendToAPIServer(method, api, params, func, errorFunc)
{
	var query = [], key, x = new XMLHttpRequest();
	if(APIServer.url == null){console.error('not initialize api server'); return;}
	if(func != null){
		x.onreadystatechange = function(){
			var j;
			switch(x.readyState){
				case 0:break;//オブジェクト生成
				case 1:break;//オープン
				case 2:break;//ヘッダ受信
				case 3:break;//ボディ受信
				case 4:
							if((200 <= x.status && x.status < 300) || (x.status == 304)){
								j = x.responseText;
								try{
									j = typeof j == 'string' ? JSON.parse(j) : '';
								}catch(e){
									j = null;
								}
								func(j);
								x.abort();
							}else{
								errorFunc();
								x.abort();
							}
							 break;//send()完了
			}
		//	func;
		};
	}
	for(key in params){
		query.push(key + '=' + params[key]);
	}
	str = query.join('&');
	if(method.toUpperCase() == 'GET'){
		x.open(method, APIServer.url + '/' + api + '?' + str , true);
		str = "";
	}else{
		x.open(method, APIServer.url + '/' + api, true);
	}
	x.withCredentials = true;
	x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
	// Set-Cookie:LITROSOUND=8lr6fpmr30focapfnejn807mo5;
	x.send(str);
};

<|endoftext|>


<commit_before>var util = {}
var Room = require('./models').Room

var async = require('async')
var jwt = require('jsonwebtoken')

//Helper function that sends JSON responses
function handleResp(res, status, data) {
    if (!(typeof data == 'object')) {
        console.log(data)
        data = {error: data}
    }
    res.status(status)
    res.json(data)
    res.end()
}

//Function used for validating request when a room is accessed
util.validateRoom = function (req, res, next) {
    var room_path = null
    //Pulls room_path identifier from body, path, or query string
    if (req.body.room_path) {
        room_path = req.body.room_path
    } else if (req.params.room_path) {
        room_path = req.params.room_path
    } else {
        room_path = req.query.room_path
    }
    // console.log('Room Path: '+room_path)
    Room.findOne({path: room_path}, function (err, room) {
        if (err) {
            return next(err)
        } else if (!room) {
            return handleResp(res, 404, 'Room not found')
        } else if (req.user && req.user._id != room.owner.toString()) {
            return handleResp(res, 406, 'User does not own room') //Matches req.user against the owner of the Room
        } else {
            req.room = room
            next()
        }
    })
}

//Verifies the presence of an authenticated user
util.clientValidateUser = function(req, res, next) {
    if (!req.user) {
        res.redirect('/')
    } else {
        next()
    }
}

util.clientValidateRoom = function(req, res, next) {
    var room_path = null
    //Pulls room_path identifier from body, path, or query string
    if (!req.user) {
        res.redirect('/')
    } else {
        if (req.body.room_path) {
            room_path = req.body.room_path
        } else if (req.params.room_path) {
            room_path = req.params.room_path
        } else {
            room_path = req.query.room_path
        }
        if (!req.user) {

        }
        Room.findOne({path: room_path}, function (err, room) {
            if (err) {
                return next(err)
            } else if (!room) {
                next(new Error('Room not found'))
            } else if (req.user && req.user._id != room.owner.toString()) {
                next(new Error('User does not own room'))
            } else {
                next()
            }
        })
    }
}

//Helper function used to verify the presence of certain fields in the request body
util.validateBody = function(fields) {
    return function(req, res, next) {
        async.each(fields, function(field, done) {
            if (!Object.prototype.hasOwnProperty.call(req.body, field)) { //If field is not found in request body
                return done('Invalid Fields')
            } else {
                done()
            }
        }, function(err) {
            if (!err) { //Passes request onto next route middleware if all fields are present
                next()
            } else {
                handleResp(res, 400, {error: 'Invalid fields'})
            }
        })
    }
}

//Helper function used for generating jsonwebtoken containing a user instance
util.generateToken = function(user) {
    return jwt.sign(user.toObject(), process.env.SECRET || 'dev_secret')
}

util.handleResp = handleResp

module.exports = util<commit_msg>Attached room model to request for util clientValidateRoom function<commit_after>var util = {}
var Room = require('./models').Room

var async = require('async')
var jwt = require('jsonwebtoken')

//Helper function that sends JSON responses
function handleResp(res, status, data) {
    if (!(typeof data == 'object')) {
        // console.log(data)
        data = {error: data}
    }
    res.status(status)
    res.json(data)
    res.end()
}

//Function used for validating request when a room is accessed
util.validateRoom = function (req, res, next) {
    var room_path = null
    //Pulls room_path identifier from body, path, or query string
    if (req.body.room_path) {
        room_path = req.body.room_path
    } else if (req.params.room_path) {
        room_path = req.params.room_path
    } else {
        room_path = req.query.room_path
    }
    // console.log('Room Path: '+room_path)
    Room.findOne({path: room_path}, function (err, room) {
        if (err) {
            return next(err)
        } else if (!room) {
            return handleResp(res, 404, 'Room not found')
        } else if (req.user && req.user._id != room.owner.toString()) {
            return handleResp(res, 406, 'User does not own room') //Matches req.user against the owner of the Room
        } else {
            req.room = room
            next()
        }
    })
}

//Verifies the presence of an authenticated user
util.clientValidateUser = function(req, res, next) {
    if (!req.user) {
        res.redirect('/')
    } else {
        next()
    }
}

util.clientValidateRoom = function(req, res, next) {
    var room_path = null
    //Pulls room_path identifier from body, path, or query string
    if (!req.user) {
        res.redirect('/')
    } else {
        if (req.body.room_path) {
            room_path = req.body.room_path
        } else if (req.params.room_path) {
            room_path = req.params.room_path
        } else {
            room_path = req.query.room_path
        }
        if (!req.user) {

        }
        Room.findOne({path: room_path}, function (err, room) {
            if (err) {
                return next(err)
            } else if (!room) {
                next(new Error('Room not found'))
            } else if (req.user && req.user._id != room.owner.toString()) {
                next(new Error('User does not own room'))
            } else {
                req.room = room
                next()
            }
        })
    }
}

//Helper function used to verify the presence of certain fields in the request body
util.validateBody = function(fields) {
    return function(req, res, next) {
        async.each(fields, function(field, done) {
            if (!Object.prototype.hasOwnProperty.call(req.body, field)) { //If field is not found in request body
                return done('Invalid Fields')
            } else {
                done()
            }
        }, function(err) {
            if (!err) { //Passes request onto next route middleware if all fields are present
                next()
            } else {
                handleResp(res, 400, {error: 'Invalid fields'})
            }
        })
    }
}

//Helper function used for generating jsonwebtoken containing a user instance
util.generateToken = function(user) {
    return jwt.sign(user.toObject(), process.env.SECRET || 'dev_secret')
}

util.handleResp = handleResp

module.exports = util<|endoftext|>


<commit_before>(function() {
  /*
  * Generate RFC4122 (v1 and v4) UUIDs
  *
  * Documentation at https://github.com/broofa/node-uuid
  */

  // 12219292800000 is the number of milliseconds between UUID epoch
  // 1582-10-15 00:00:00 and UNIX epoch 1970-01-01 00:00:00.
  var EPOCH_OFFSET = 12219292800000;

  // Number of 100ns ticks of the actual resolution of the system's clock
  var UUIDS_PER_TICK = 10000;

  // Use node.js Buffer class if available, otherwise use the Array class
  var BufferClass = typeof(Buffer) == 'function' ? Buffer : Array;

  // Buffer used for generating string uuids
  var _buf = new BufferClass(16);

  // Cache number <-> hex string for octet values
  var toString = [];
  var toNumber = {};
  for (var i = 0; i < 256; i++) {
    toString[i] = (i + 0x100).toString(16).substr(1);
    toNumber[toString[i]] = i;
  }

  function parse(s) {
    var buf = new BufferClass(16);
    var i = 0;
    s.toLowerCase().replace(/[0-9a-f][0-9a-f]/g, function(octet) {
      buf[i++] = toNumber[octet];
    });
    return buf;
  }

  function unparse(buf) {
    var tos = toString, b = buf;
    return tos[b[0]] + tos[b[1]] + tos[b[2]] + tos[b[3]] + '-' +
           tos[b[4]] + tos[b[5]] + '-' +
           tos[b[6]] + tos[b[7]] + '-' +
           tos[b[8]] + tos[b[9]] + '-' +
           tos[b[10]] + tos[b[11]] + tos[b[12]] +
           tos[b[13]] + tos[b[14]] + tos[b[15]];
  }

  var ff = 0xff;

  // Feature detect for the WHATWG crypto API. See
  // http://wiki.whatwg.org/wiki/Crypto
  var useCrypto = this.crypto && crypto.getRandomValues;
  var rnds = useCrypto ? new Uint32Array(4) : new Array(4);

  if (useCrypto) {
    crypto.getRandomValues(rnds);
  } else {
    rnds[0] = Math.random() * 0x100000000;
    rnds[1] = Math.random() * 0x100000000;
    rnds[2] = Math.random() * 0x100000000;
  }

  // Generate a node value for this instance. Use a randomly generated node
  // instead of a mac address. RFC suggests generating a 47 bit random integer,
  // but we're limited to 32 bit in js, so we just use two 32 bit.
  var node = [
    rnds[0] & ff | 0x01, // Set multicast bit, see 4.1.6 and 4.5
    rnds[0] >>> 8 & ff,
    rnds[0] >>> 16 & ff,
    rnds[0] >>> 24 & ff,
    rnds[1] & ff,
    rnds[1] >>> 8 & ff
  ];

  // Use 14 bit random unsigned integer to initialize clock_seq, see 4.2.2.
  var cs = rnds[2] & 0x3fff; // Cut down 32 bit random integer to 14 bit

  // Used to track time-regressions for updating the clock_seq
  var last = 0;

  // Number of UUIDs that have been created during the current millisecond-
  // interval. Used to simulate higher clock resolution as suggested in 4.2.1.2.
  var count = 0;

  // Inspired by https://github.com/LiosK/UUID.js
  // and http://docs.python.org/library/uuid.html
  function v1(fmt, buf, offset) {
    var b = fmt != 'binary' ? _buf : (buf ? buf : new BufferClass(16));
    var i = buf && offset || 0;

    // Get current time and simulate higher clock resolution
    var now = (new Date().getTime()) + EPOCH_OFFSET;
    count = (now === last) ? count + 1 : 0;

    // Per 4.2.1.2, if time regresses we bump the clock sequence.
    // (Or if we're generating more than 10k uuids/sec - an extremely unlikely
    // case the RFC doesn't address)
    if (now < last || count > UUIDS_PER_TICK) {
      cs++;
      count = 0;
    }
    last = now;

    // Timestamp, see 4.1.4
    var timestamp = now;
    var tl = ((timestamp & 0xfffffff) * 10000 + count) % 0x100000000;
    var tmh = ((timestamp / 0x100000000) * 10000) & 0xfffffff;
    var tm = tmh & 0xffff;
    var th = tmh >> 16;
    var thav = (th & 0xfff) | 0x1000; // Set version, see 4.1.3

    // Clock sequence
    var csl = cs & 0xff;
    var cshar = (cs >>> 8) | 0x80; // Set the variant, see 4.2.2

    // time_low
    b[i++] = tl >>> 24 & ff;
    b[i++] = tl >>> 16 & ff;
    b[i++] = tl >>> 8 & ff;
    b[i++] = tl & ff;

    // time_mid
    b[i++] = tm >>> 8 & ff;
    b[i++] = tm & ff;

    // time_high_and_version
    b[i++] = thav >>> 8 & ff;
    b[i++] = thav & ff;

    // clock_seq_hi_and_reserved
    b[i++] = cshar;

    // clock_seq_low
    b[i++] = csl;

    // node
    var n = 0;
    b[i++] = node[n++];
    b[i++] = node[n++];
    b[i++] = node[n++];
    b[i++] = node[n++];
    b[i++] = node[n++];
    b[i++] = node[n++];

    return fmt === undefined ? unparse(b) : b;
  }

  function v4(options, buf, offset) {
    if (typeof options === 'string') { // backwards compatibility
      options = {format: options};
    }
    options = options || {};

    var b = options.format != 'binary' ? _buf : (buf ? buf : new BufferClass(16));
    var i = buf && offset || 0;

    if (options.random) {
      rnds = options.random;
    } else {
      if (useCrypto) {
        crypto.getRandomValues(rnds);
      } else {
        rnds[0] = Math.random() * 0x100000000;
        rnds[1] = Math.random() * 0x100000000;
        rnds[2] = Math.random() * 0x100000000;
        rnds[3] = Math.random() * 0x100000000;
      }
    }

    var r = rnds[0];
    b[i++] = r & ff;
    b[i++] = r >>> 8 & ff;
    b[i++] = r >>> 16 & ff;
    b[i++] = r >>> 24 & ff;
    r = rnds[1];
    b[i++] = r & ff;
    b[i++] = r >>> 8 & ff;
    b[i++] = r >>> 16 & 0x0f | 0x40; // See RFC4122 sect. 4.1.3
    b[i++] = r >>> 24 & ff;
    r = rnds[2];
    b[i++] = r & 0x3f | 0x80; // See RFC4122 sect. 4.4
    b[i++] = r >>> 8 & ff;
    b[i++] = r >>> 16 & ff;
    b[i++] = r >>> 24 & ff;
    r = rnds[3];
    b[i++] = r & ff;
    b[i++] = r >>> 8 & ff;
    b[i++] = r >>> 16 & ff;
    b[i++] = r >>> 24 & ff;

    return options.format === undefined ? unparse(b) : b;
  }

  var uuid = v4;
  uuid.v1 = v1;
  uuid.v4 = v4;
  uuid.parse = parse;
  uuid.unparse = unparse;
  uuid.BufferClass = BufferClass;

  if (typeof(module) != 'undefined') {
    module.exports = uuid;
  } else {
    // In browser? Set as top-level function
    this.uuid = uuid;
  }
}());
<commit_msg>Allow specifying timestamp for v1 UUIDs, see #12 - A millisecond timestamp can be provided in the options object that is used instead of Date().getTime() if present<commit_after>(function() {
  /*
  * Generate RFC4122 (v1 and v4) UUIDs
  *
  * Documentation at https://github.com/broofa/node-uuid
  */

  // 12219292800000 is the number of milliseconds between UUID epoch
  // 1582-10-15 00:00:00 and UNIX epoch 1970-01-01 00:00:00.
  var EPOCH_OFFSET = 12219292800000;

  // Number of 100ns ticks of the actual resolution of the system's clock
  var UUIDS_PER_TICK = 10000;

  // Use node.js Buffer class if available, otherwise use the Array class
  var BufferClass = typeof(Buffer) == 'function' ? Buffer : Array;

  // Buffer used for generating string uuids
  var _buf = new BufferClass(16);

  // Cache number <-> hex string for octet values
  var toString = [];
  var toNumber = {};
  for (var i = 0; i < 256; i++) {
    toString[i] = (i + 0x100).toString(16).substr(1);
    toNumber[toString[i]] = i;
  }

  function parse(s) {
    var buf = new BufferClass(16);
    var i = 0;
    s.toLowerCase().replace(/[0-9a-f][0-9a-f]/g, function(octet) {
      buf[i++] = toNumber[octet];
    });
    return buf;
  }

  function unparse(buf) {
    var tos = toString, b = buf;
    return tos[b[0]] + tos[b[1]] + tos[b[2]] + tos[b[3]] + '-' +
           tos[b[4]] + tos[b[5]] + '-' +
           tos[b[6]] + tos[b[7]] + '-' +
           tos[b[8]] + tos[b[9]] + '-' +
           tos[b[10]] + tos[b[11]] + tos[b[12]] +
           tos[b[13]] + tos[b[14]] + tos[b[15]];
  }

  var ff = 0xff;

  // Feature detect for the WHATWG crypto API. See
  // http://wiki.whatwg.org/wiki/Crypto
  var useCrypto = this.crypto && crypto.getRandomValues;
  var rnds = useCrypto ? new Uint32Array(4) : new Array(4);

  if (useCrypto) {
    crypto.getRandomValues(rnds);
  } else {
    rnds[0] = Math.random() * 0x100000000;
    rnds[1] = Math.random() * 0x100000000;
    rnds[2] = Math.random() * 0x100000000;
  }

  // Generate a node value for this instance. Use a randomly generated node
  // instead of a mac address. RFC suggests generating a 47 bit random integer,
  // but we're limited to 32 bit in js, so we just use two 32 bit.
  var node = [
    rnds[0] & ff | 0x01, // Set multicast bit, see 4.1.6 and 4.5
    rnds[0] >>> 8 & ff,
    rnds[0] >>> 16 & ff,
    rnds[0] >>> 24 & ff,
    rnds[1] & ff,
    rnds[1] >>> 8 & ff
  ];

  // Use 14 bit random unsigned integer to initialize clock_seq, see 4.2.2.
  var cs = rnds[2] & 0x3fff; // Cut down 32 bit random integer to 14 bit

  // Used to track time-regressions for updating the clock_seq
  var last = 0;

  // Number of UUIDs that have been created during the current millisecond-
  // interval. Used to simulate higher clock resolution as suggested in 4.2.1.2.
  var count = 0;

  // Inspired by https://github.com/LiosK/UUID.js
  // and http://docs.python.org/library/uuid.html
  function v1(options, buf, offset) {
    if (typeof options === 'string') { // backwards compatibility
      options = {format: options};
    }
    options = options || {};

    var b = options.format != 'binary' ? _buf : (buf ? buf : new BufferClass(16));
    var i = buf && offset || 0;

    // Get current time and simulate higher clock resolution
    var now = (options.timestamp || new Date().getTime()) + EPOCH_OFFSET;
    count = (now === last) ? count + 1 : 0;

    // Per 4.2.1.2, if time regresses we bump the clock sequence.
    // (Or if we're generating more than 10k uuids/sec - an extremely unlikely
    // case the RFC doesn't address)
    if (now < last || count > UUIDS_PER_TICK) {
      cs++;
      count = 0;
    }
    last = now;

    // Timestamp, see 4.1.4
    var timestamp = now;
    var tl = ((timestamp & 0xfffffff) * 10000 + count) % 0x100000000;
    var tmh = ((timestamp / 0x100000000) * 10000) & 0xfffffff;
    var tm = tmh & 0xffff;
    var th = tmh >> 16;
    var thav = (th & 0xfff) | 0x1000; // Set version, see 4.1.3

    // Clock sequence
    var csl = cs & 0xff;
    var cshar = (cs >>> 8) | 0x80; // Set the variant, see 4.2.2

    // time_low
    b[i++] = tl >>> 24 & ff;
    b[i++] = tl >>> 16 & ff;
    b[i++] = tl >>> 8 & ff;
    b[i++] = tl & ff;

    // time_mid
    b[i++] = tm >>> 8 & ff;
    b[i++] = tm & ff;

    // time_high_and_version
    b[i++] = thav >>> 8 & ff;
    b[i++] = thav & ff;

    // clock_seq_hi_and_reserved
    b[i++] = cshar;

    // clock_seq_low
    b[i++] = csl;

    // node
    var n = 0;
    b[i++] = node[n++];
    b[i++] = node[n++];
    b[i++] = node[n++];
    b[i++] = node[n++];
    b[i++] = node[n++];
    b[i++] = node[n++];

    return options.format === undefined ? unparse(b) : b;
  }

  function v4(options, buf, offset) {
    if (typeof options === 'string') { // backwards compatibility
      options = {format: options};
    }
    options = options || {};

    var b = options.format != 'binary' ? _buf : (buf ? buf : new BufferClass(16));
    var i = buf && offset || 0;

    if (options.random) {
      rnds = options.random;
    } else {
      if (useCrypto) {
        crypto.getRandomValues(rnds);
      } else {
        rnds[0] = Math.random() * 0x100000000;
        rnds[1] = Math.random() * 0x100000000;
        rnds[2] = Math.random() * 0x100000000;
        rnds[3] = Math.random() * 0x100000000;
      }
    }

    var r = rnds[0];
    b[i++] = r & ff;
    b[i++] = r >>> 8 & ff;
    b[i++] = r >>> 16 & ff;
    b[i++] = r >>> 24 & ff;
    r = rnds[1];
    b[i++] = r & ff;
    b[i++] = r >>> 8 & ff;
    b[i++] = r >>> 16 & 0x0f | 0x40; // See RFC4122 sect. 4.1.3
    b[i++] = r >>> 24 & ff;
    r = rnds[2];
    b[i++] = r & 0x3f | 0x80; // See RFC4122 sect. 4.4
    b[i++] = r >>> 8 & ff;
    b[i++] = r >>> 16 & ff;
    b[i++] = r >>> 24 & ff;
    r = rnds[3];
    b[i++] = r & ff;
    b[i++] = r >>> 8 & ff;
    b[i++] = r >>> 16 & ff;
    b[i++] = r >>> 24 & ff;

    return options.format === undefined ? unparse(b) : b;
  }

  var uuid = v4;
  uuid.v1 = v1;
  uuid.v4 = v4;
  uuid.parse = parse;
  uuid.unparse = unparse;
  uuid.BufferClass = BufferClass;

  if (typeof(module) != 'undefined') {
    module.exports = uuid;
  } else {
    // In browser? Set as top-level function
    this.uuid = uuid;
  }
}());
<|endoftext|>


<commit_before>#!/usr/bin/env node

require('proof')(3, function (assert) {
    var hilbert = require('../..')
    console.log("Point (0,0) " + hilbert.hilbert(2, 0, 0) + " above ^^^ \n")
    console.log("Point (1,0) " + hilbert.hilbert(2, 1, 0) + " above ^^^ \n")
    console.log("Point (1,1) " + hilbert.hilbert(2, 1, 1) + " above ^^^ \n")
    console.log("Point (0,1) " + hilbert.hilbert(2, 0, 1) + " above ^^^ \n")
    console.log("Point (2,0) " + hilbert.hilbert(2, 2, 0) + " above ^^^ \n")
    console.log("Point (3,0) " + hilbert.hilbert(2, 3, 0) + " above ^^^ \n")
    console.log("Point (3,1) " + hilbert.hilbert(2, 3, 1) + " above ^^^ \n")
    console.log("Point (2,1) " + hilbert.hilbert(2, 2, 1) + " above ^^^ \n")
    console.log("Point (2,2) " + hilbert.hilbert(2, 2, 2) + " above ^^^ \n")
    console.log("Point (3,2) " + hilbert.hilbert(2, 3, 2) + " above ^^^ \n")
    console.log("Point (3,3) " + hilbert.hilbert(2, 3, 3) + " above ^^^ \n")
    console.log("Point (2,3) " + hilbert.hilbert(2, 2, 3) + " above ^^^ \n")
    console.log("Point (1,3) " + hilbert.hilbert(2, 1, 3) + " above ^^^ \n")
    console.log("Point (1,2) " + hilbert.hilbert(2, 1, 2) + " above ^^^ \n")
    console.log("Point (0,2) " + hilbert.hilbert(2, 0, 2) + " above ^^^ \n")
    console.log("Point (0,3) " + hilbert.hilbert(2, 0, 3) + " above ^^^ \n")
})
<commit_msg>Fix assertions in test file.<commit_after>#!/usr/bin/env node

require('proof')(10, prove)

function prove (assert) {
    var hilbert = require('../..')

    assert(hilbert.hilbert(2,0,3), 15, "(0,3) index equals 15")
    assert(hilbert.hilbert(2,4,0), 16, "(4,0) index equals 16")
    assert(hilbert.hilbert(2,0,7), 63, "(0,7) index equals 63")
    assert(hilbert.hilbert(2,8,0), 64, "(8,0) index equals 64")
    assert(hilbert.hilbert(2,0,15), 255, "(0,15) index equals 255")
    assert(hilbert.hilbert(2,16,0), 256, "(16,0) index equals 256")
    assert(hilbert.hilbert(2,0,31), 1023, "(0,31) index equals 1023")
    assert(hilbert.hilbert(2,32,0), 1024, "(32,0) index equals 1024")
    assert(hilbert.hilbert(2,0,63), 4095, "(0,63) index equals 4095")
    assert(hilbert.hilbert(2,64,0), 4096, "(64,0) index equals 4096")

    console.log(hilbert.hilbert(3,1,0,0))// 1
    console.log(hilbert.hilbert(3,1,1,0))// 2
    console.log(hilbert.hilbert(3,0,1,0))// 3
    console.log(hilbert.hilbert(3,0,1,1))// 4
    console.log(hilbert.hilbert(3,1,1,1))// 5
    console.log(hilbert.hilbert(3,1,0,1))// 6
    console.log(hilbert.hilbert(3,0,0,1))// 7
    console.log(hilbert.hilbert(3,2,0,0))// 8

    /*
    console.log("Point (0,0) " + hilbert.hilbert(2, 0, 0) + " above ^^^ \n")
    console.log("Point (1,0) " + hilbert.hilbert(2, 1, 0) + " above ^^^ \n")
    console.log("Point (1,1) " + hilbert.hilbert(2, 1, 1) + " above ^^^ \n")
    console.log("Point (0,1) " + hilbert.hilbert(2, 0, 1) + " above ^^^ \n")
    console.log("Point (2,0) " + hilbert.hilbert(2, 2, 0) + " above ^^^ \n")
    console.log("Point (3,0) " + hilbert.hilbert(2, 3, 0) + " above ^^^ \n")
    console.log("Point (3,1) " + hilbert.hilbert(2, 3, 1) + " above ^^^ \n")
    console.log("Point (2,1) " + hilbert.hilbert(2, 2, 1) + " above ^^^ \n")
    console.log("Point (2,2) " + hilbert.hilbert(2, 2, 2) + " above ^^^ \n")
    console.log("Point (3,2) " + hilbert.hilbert(2, 3, 2) + " above ^^^ \n")
    console.log("Point (3,3) " + hilbert.hilbert(2, 3, 3) + " above ^^^ \n")
    console.log("Point (2,3) " + hilbert.hilbert(2, 2, 3) + " above ^^^ \n")
    console.log("Point (1,3) " + hilbert.hilbert(2, 1, 3) + " above ^^^ \n")
    console.log("Point (1,2) " + hilbert.hilbert(2, 1, 2) + " above ^^^ \n")
    console.log("Point (0,2) " + hilbert.hilbert(2, 0, 2) + " above ^^^ \n")
    console.log("Point (0,3) " + hilbert.hilbert(2, 0, 3) + " above ^^^ \n")
    console.log("Point (4,0) " + hilbert.hilbert(2, 4, 0) + " above ^^^ \n")
    console.log("Point (4,1) " + hilbert.hilbert(2, 4, 1) + " above ^^^ \n")
    console.log("Point (5,1) " + hilbert.hilbert(2, 5, 1) + " above ^^^ \n")
    console.log("Point (5,0) " + hilbert.hilbert(2, 5, 0) + " above ^^^ \n")
    console.log("Point (6,0) " + hilbert.hilbert(2, 6, 0) + " above ^^^ \n")
    console.log("Point (7,0) " + hilbert.hilbert(2, 7, 0) + " above ^^^ \n")
    console.log("Point (7,1) " + hilbert.hilbert(2, 7, 1) + " above ^^^ \n")
    console.log("Point (6,1) " + hilbert.hilbert(2, 6, 1) + " above ^^^ \n")
    console.log("Point (6,2) " + hilbert.hilbert(2, 6, 2) + " above ^^^ \n")
    console.log("Point (7,2) " + hilbert.hilbert(2, 7, 2) + " above ^^^ \n")
    console.log("Point (7,3) " + hilbert.hilbert(2, 7, 3) + " above ^^^ \n")
    console.log("Point (6,3) " + hilbert.hilbert(2, 6, 3) + " above ^^^ \n")
    console.log("Point (5,3) " + hilbert.hilbert(2, 5, 3) + " above ^^^ \n")
    console.log("Point (5,2) " + hilbert.hilbert(2, 5, 2) + " above ^^^ \n")
    console.log("Point (4,2) " + hilbert.hilbert(2, 4, 2) + " above ^^^ \n")
    console.log("Point (4,3) " + hilbert.hilbert(2, 4, 3) + " above ^^^ \n")
    console.log("Point (4,4) " + hilbert.hilbert(2, 4, 4) + " above ^^^ \n")
    console.log("Point (4,5) " + hilbert.hilbert(2, 4, 5) + " above ^^^ \n")
    console.log("Point (5,5) " + hilbert.hilbert(2, 5, 5) + " above ^^^ \n")
    console.log("Point (5,4) " + hilbert.hilbert(2, 5, 4) + " above ^^^ \n")
    console.log("Point (6,4) " + hilbert.hilbert(2, 6, 4) + " above ^^^ \n")
    console.log("Point (7,4) " + hilbert.hilbert(2, 7, 4) + " above ^^^ \n")
    console.log("Point (7,5) " + hilbert.hilbert(2, 7, 5) + " above ^^^ \n")
    console.log("Point (6,5) " + hilbert.hilbert(2, 6, 5) + " above ^^^ \n")
    console.log("Point (6,6) " + hilbert.hilbert(2, 6, 6) + " above ^^^ \n")
    console.log("Point (7,6) " + hilbert.hilbert(2, 7, 6) + " above ^^^ \n")
    console.log("Point (7,7) " + hilbert.hilbert(2, 7, 7) + " above ^^^ \n")
    console.log("Point (6,7) " + hilbert.hilbert(2, 6, 7) + " above ^^^ \n")
    console.log("Point (5,7) " + hilbert.hilbert(2, 5, 7) + " above ^^^ \n")
    console.log("Point (5,6) " + hilbert.hilbert(2, 5, 6) + " above ^^^ \n")
    console.log("Point (4,6) " + hilbert.hilbert(2, 4, 6) + " above ^^^ \n")
    console.log("Point (4,7) " + hilbert.hilbert(2, 4, 7) + " above ^^^ \n")
    console.log("Point (3,7) " + hilbert.hilbert(2, 3, 7) + " above ^^^ \n")
    console.log("Point (2,7) " + hilbert.hilbert(2, 2, 7) + " above ^^^ \n")
    console.log("Point (2,6) " + hilbert.hilbert(2, 2, 6) + " above ^^^ \n")
    console.log("Point (3,6) " + hilbert.hilbert(2, 3, 6) + " above ^^^ \n")
    console.log("Point (3,5) " + hilbert.hilbert(2, 3, 5) + " above ^^^ \n")
    console.log("Point (3,4) " + hilbert.hilbert(2, 3, 4) + " above ^^^ \n")
    console.log("Point (2,4) " + hilbert.hilbert(2, 2, 4) + " above ^^^ \n")
    console.log("Point (2,5) " + hilbert.hilbert(2, 2, 5) + " above ^^^ \n")
    console.log("Point (1,5) " + hilbert.hilbert(2, 1, 5) + " above ^^^ \n")
    console.log("Point (1,4) " + hilbert.hilbert(2, 1, 4) + " above ^^^ \n")
    console.log("Point (0,4) " + hilbert.hilbert(2, 0, 4) + " above ^^^ \n")
    console.log("Point (0,5) " + hilbert.hilbert(2, 0, 5) + " above ^^^ \n")
    console.log("Point (0,6) " + hilbert.hilbert(2, 0, 6) + " above ^^^ \n")
    console.log("Point (1,6) " + hilbert.hilbert(2, 1, 6) + " above ^^^ \n")
    console.log("Point (1,7) " + hilbert.hilbert(2, 1, 7) + " above ^^^ \n")
    console.log("Point (0,7) " + hilbert.hilbert(2, 0, 7) + " above ^^^ \n")
*/
}
<|endoftext|>


<commit_before>/*jslint browser: true, undef: true *//*global Ext*/
Ext.define('SlateAdmin.view.progress.NavPanel', {
    extend: 'SlateAdmin.view.LinksNavPanel',
    xtype: 'progress-navpanel',

    title: 'Student Progress',
    data: true,

    applyData: function(data) {
        if (data !== true) {
            return data;
        }

        return [
            {
                href: '#progress/interims', text: 'Section Interim Reports',
                children: [
                    {
                        href: '#progress/interims/print', text: 'Search & Print'
                    }
                    // {
                    //     href: '#progress/interims/email', text: 'Email'
                    // }
                ]
            },
            {
                href: '#progress/narratives', text: 'Section Term Reports',
                children: [
                    {
                        href: '#progress/narratives/print', text: 'Search & Print'
                    }
                    // {
                    //     href: '#progress/narratives/email', text: 'Email'
                    // }
                ]
            }
        ];
    }
});<commit_msg>Clean progress navpanel syntax<commit_after>Ext.define('SlateAdmin.view.progress.NavPanel', {
    extend: 'SlateAdmin.view.LinksNavPanel',
    xtype: 'progress-navpanel',

    title: 'Student Progress',
    data: true,

    applyData: function(data) {
        if (data !== true) {
            return data;
        }

        return [
            {
                text: 'Section Interim Reports',
                href: '#progress/interims',
                children: [
                    {
                        text: 'Search & Print',
                        href: '#progress/interims/print'
                    }
                    // {
                    //     text: 'Email',
                    //     href: '#progress/interims/email'
                    // }
                ]
            },
            {
                text: 'Section Term Reports',
                href: '#progress/narratives',
                children: [
                    {
                        text: 'Search & Print',
                        href: '#progress/narratives/print'
                    }
                    // {
                    //     text: 'Email',
                    //     href: '#progress/narratives/email'
                    // }
                ]
            }
        ];
    }
});<|endoftext|>


<commit_before><commit_msg>add pivotal item for cache sharing to comments<commit_after><|endoftext|>