<commit_before>

import React from "react";
import {connectLean, thunk} from "../src/lean";

class RandomGif extends React.PureComponent {
    componentDidMount() {
        this.props.fetchGif();
    }
    render() {
        const {tag, status, url, fetchGif} = this.props;
        return (

{tag}

                {(url && status !== "fetching") && }

                <button onClick={fetchGif} disabled={status === "fetching"}>
                    {status === "fetching" ? "loading..." : "Next!"}
                </button>

        );
    }
}
RandomGif = connectLean({
    scope: "singleRandomGif",
    getInitialState() {
        return {
            status: "waiting",
            url: null,
        };
    },
    handlers: {
        setUrl(url) {
            return {url};
        },
        fetchGif() {

            return thunk((update, getProps) => {
                update({status: "fetching"});

                fetch("https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=" + getProps().tag)
                .then(res => res.json())
                .then(json => {
                    update({
                        status: "ok",
                        url: json.data.fixed_height_small_url,
                    });
                });
            });
        },
    },

})(RandomGif);

export default RandomGif;
<commit_msg>cleanup<commit_after>import React from "react";
import {connectLean, thunk} from "../src/lean";

class RandomGif extends React.PureComponent {
    componentDidMount() {
        this.props.fetchGif();
    }
    render() {
        const {tag, status, url, fetchGif} = this.props;
        return (

{tag}

                {(url && status !== "fetching") && }

                <button onClick={fetchGif} disabled={status === "fetching"}>
                    {status === "fetching" ? "loading..." : "Next!"}
                </button>

        );
    }
}
RandomGif = connectLean({
    scope: "singleRandomGif",
    getInitialState() {
        return {
            status: "waiting",
            url: null,
        };
    },
    handlers: {
        setUrl(url) {
            return {url};
        },
        fetchGif() {

            return thunk((update, getProps) => {
                update({status: "fetching"});

                fetch("https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=" + getProps().tag)
                .then(res => res.json())
                .then(json => {
                    update({
                        status: "ok",
                        url: json.data.fixed_height_small_url,
                    });
                });
            });
        },
    },

})(RandomGif);

export default RandomGif;
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { ActivityIndicator, ListView, View, TouchableOpacity } from 'react-native'
import { Actions } from 'react-native-router-flux'

import TitleBar from '../components/TitleBar'
import {DefaultText} from '../components/textComponents'
import RouteStopsRow from '../components/RouteStopsRow'
import AccessibilityView from '../components/AccessibilityView'

import styles from '../styles/stylesheet'
import strings from '../resources/translations'

import { fetchRouteStops } from '../actions/fetchRouteStops'

const UPDATE_INTERVAL_IN_SECS = 10

class RouteStopsPage extends Component {
    constructor(props)
    {
        super(props)

        let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})

        this.state = {
            dataSource: ds.cloneWithRows([]),
            fetchIntervalRunning: false
        }

        this.sceneName = 'routeStops'
    }

    createInterval = (props) => {
        this.fetchInterval = setInterval(() =>
        {
            if (!props.isFetching)
            {
                props.fetchDepartures(props.locationData.latitude, props.locationData.longitude)
            }
        }, UPDATE_INTERVAL_IN_SECS * 1000)
    }

    componentWillMount = () =>
    {
        this.props.fetchRouteStops(this.props.tripId, this.props.stopId)

        this.setState({fetchIntervalRunning: true})

        this.createInterval(this.props)
    }

    componentWillReceiveProps = (nextProps) =>
    {
        if (nextProps.scene.name == this.sceneName)
        {
            if (!this.state.fetchIntervalRunning)
            {
                this.setState({fetchIntervalRunning: true})

                this.createInterval(nextProps)
            }
        } else {
            if (this.state.fetchIntervalRunning)
            {
                this.setState({fetchIntervalRunning: false})

                clearInterval(this.fetchInterval)
            }
        }

        this.setState({dataSource: this.state.dataSource.cloneWithRows(nextProps.routeStops)})
    }

    renderRow = (renderData) =>
    {
        const goToStopVehicleRequestPage = () =>
        {
            Actions.routeStopRequest({})
        }

        return (
          <TouchableOpacity onPress={goToStopVehicleRequestPage}>
            <RouteStopsRow stopId={renderData.stop_code} stopName={renderData.stop_name} arrivalTime={renderData.arrives_in} />
          </TouchableOpacity>)
    }

    renderSeparator = () =>
    {
        return (<View style={styles.rowSeparator}></View>)
    }

    renderFooter = () =>
    {
        return (
        <View>
          <ActivityIndicator
            animating={this.props.isFetching}
          />
        </View>
        )
    }

    renderList = () =>
    {
        return (
          <View style={styles.flex1}>
            <TitleBar title={this.props.vehicleLine + ' ' + this.props.vehicleDestination} />
            {this.props.error ? <DefaultText style={styles.error}>{strings.backendError}</DefaultText> : null}
            <ListView
              enableEmptySections={true}
              dataSource={this.state.dataSource}
              renderRow={this.renderRow}
              renderFooter={this.renderFooter}
              renderSeparator={this.renderSeparator}
            />
          </View>
        )
    }

    renderSpinner = () =>
    {
        return (
          <View style={styles.spinnerContainer}>
            <View style={styles.spinnerBackground}>
              <ActivityIndicator
                size="large"
                animating={true}
              />
            </View>
          </View>
        )
    }

    render()
    {
        return (<AccessibilityView name={this.sceneName}>
            {this.props.routeIsReady ? this.renderList() : this.renderSpinner() }
        </AccessibilityView>)
    }
}

const mapStateToProps = (state) =>
{
    return {
        routeStops: state.fetchReducer.routeStops,
        isFetching: state.fetchReducer.isFetching,
        routeIsReady: state.fetchReducer.routeIsReady,
        error: state.fetchReducer.error,
        scene: state.routes.scene
    }
}

const mapDispatchToProps = (dispatch) =>
{
    return {
        fetchRouteStops: (tripId, BusId) =>
        {
            dispatch(fetchRouteStops(tripId, BusId))
        }
    }
}

RouteStopsPage.propTypes = {
    fetchRouteStops: React.PropTypes.func.isRequired,
    isFetching: React.PropTypes.bool.isRequired,
    routeIsReady: React.PropTypes.bool.isRequired,
    tripId: React.PropTypes.string.isRequired,
    stopId: React.PropTypes.string.isRequired,
    error: React.PropTypes.bool,
    vehicleLine: React.PropTypes.string.isRequired,
    vehicleDestination: React.PropTypes.string.isRequired,
    scene: React.PropTypes.object.isRequired
}

export default connect(mapStateToProps, mapDispatchToProps)(RouteStopsPage)
<commit_msg>bug fix<commit_after>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { ActivityIndicator, ListView, View, TouchableOpacity } from 'react-native'
import { Actions } from 'react-native-router-flux'

import TitleBar from '../components/TitleBar'
import {DefaultText} from '../components/textComponents'
import RouteStopsRow from '../components/RouteStopsRow'
import AccessibilityView from '../components/AccessibilityView'

import styles from '../styles/stylesheet'
import strings from '../resources/translations'

import { fetchRouteStops } from '../actions/fetchRouteStops'

const UPDATE_INTERVAL_IN_SECS = 10

class RouteStopsPage extends Component {
    constructor(props)
    {
        super(props)

        let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})

        this.state = {
            dataSource: ds.cloneWithRows([]),
            fetchIntervalRunning: false
        }

        this.sceneName = 'routeStops'
    }

    createInterval = (props) => {
        this.fetchInterval = setInterval(() =>
        {
            if (!props.isFetching)
            {
                props.fetchRouteStops(props.tripId, props.stopId)
            }
        }, UPDATE_INTERVAL_IN_SECS * 1000)
    }

    componentWillMount = () =>
    {
        this.props.fetchRouteStops(this.props.tripId, this.props.stopId)

        this.setState({fetchIntervalRunning: true})

        this.createInterval(this.props)
    }

    componentWillReceiveProps = (nextProps) =>
    {
        if (nextProps.scene.name == this.sceneName)
        {
            if (!this.state.fetchIntervalRunning)
            {
                this.setState({fetchIntervalRunning: true})

                this.createInterval(nextProps)
            }
        } else {
            if (this.state.fetchIntervalRunning)
            {
                this.setState({fetchIntervalRunning: false})

                clearInterval(this.fetchInterval)
            }
        }

        this.setState({dataSource: this.state.dataSource.cloneWithRows(nextProps.routeStops)})
    }

    renderRow = (renderData) =>
    {
        const goToStopVehicleRequestPage = () =>
        {
            Actions.routeStopRequest({})
        }

        return (
          <TouchableOpacity onPress={goToStopVehicleRequestPage}>
            <RouteStopsRow stopId={renderData.stop_code} stopName={renderData.stop_name} arrivalTime={renderData.arrives_in} />
          </TouchableOpacity>)
    }

    renderSeparator = () =>
    {
        return (<View style={styles.rowSeparator}></View>)
    }

    renderFooter = () =>
    {
        return (
        <View>
          <ActivityIndicator
            animating={this.props.isFetching}
          />
        </View>
        )
    }

    renderList = () =>
    {
        return (
          <View style={styles.flex1}>
            <TitleBar title={this.props.vehicleLine + ' ' + this.props.vehicleDestination} />
            {this.props.error ? <DefaultText style={styles.error}>{strings.backendError}</DefaultText> : null}
            <ListView
              enableEmptySections={true}
              dataSource={this.state.dataSource}
              renderRow={this.renderRow}
              renderFooter={this.renderFooter}
              renderSeparator={this.renderSeparator}
            />
          </View>
        )
    }

    renderSpinner = () =>
    {
        return (
          <View style={styles.spinnerContainer}>
            <View style={styles.spinnerBackground}>
              <ActivityIndicator
                size="large"
                animating={true}
              />
            </View>
          </View>
        )
    }

    render()
    {
        return (<AccessibilityView name={this.sceneName}>
            {this.props.routeIsReady ? this.renderList() : this.renderSpinner() }
        </AccessibilityView>)
    }
}

const mapStateToProps = (state) =>
{
    return {
        routeStops: state.fetchReducer.routeStops,
        isFetching: state.fetchReducer.isFetching,
        routeIsReady: state.fetchReducer.routeIsReady,
        error: state.fetchReducer.error,
        scene: state.routes.scene
    }
}

const mapDispatchToProps = (dispatch) =>
{
    return {
        fetchRouteStops: (tripId, BusId) =>
        {
            dispatch(fetchRouteStops(tripId, BusId))
        }
    }
}

RouteStopsPage.propTypes = {
    fetchRouteStops: React.PropTypes.func.isRequired,
    isFetching: React.PropTypes.bool.isRequired,
    routeIsReady: React.PropTypes.bool.isRequired,
    tripId: React.PropTypes.string.isRequired,
    stopId: React.PropTypes.string.isRequired,
    error: React.PropTypes.bool,
    vehicleLine: React.PropTypes.string.isRequired,
    vehicleDestination: React.PropTypes.string.isRequired,
    scene: React.PropTypes.object.isRequired
}

export default connect(mapStateToProps, mapDispatchToProps)(RouteStopsPage)
<|endoftext|>


<commit_before>/*  eslint no-magic-numbers: [0]  */

import * as AST from './ast';
import { FTLParserStream } from './ftlstream';
import { ParseError } from './errors';

export default class FluentParser {
  constructor({
    withSpans = true,
    withAnnotations = true,
  } = {}) {
    this.withSpans = withSpans;
    this.withAnnotations = withAnnotations;
  }

  parse(source) {
    let comment = null;

    const ps = new FTLParserStream(source);
    ps.skipWSLines();

    const entries = [];

    while (ps.current()) {
      const entry = getEntryOrJunk(this, ps);

      if (entry.type === 'Comment' && entries.length === 0) {
        comment = entry;
      } else {
        entries.push(entry);
      }

      ps.skipWSLines();
    }

    return new AST.Resource(entries, comment);
  }

  parseEntry(source) {
    const ps = new FTLParserStream(source);
    ps.skipWSLines();
    return getEntryOrJunk(this, ps);
  }
}

function getEntryOrJunk(parser, ps) {
  const entryStartPos = ps.getIndex();

  try {
    const entry = getEntry(ps);
    if (parser.withSpans) {
      entry.addSpan(entryStartPos, ps.getIndex());
    }
    return entry;
  } catch (err) {
    if (!(err instanceof ParseError)) {
      throw err;
    }

    const errorIndex = ps.getIndex();
    ps.skipToNextEntryStart();
    const nextEntryStart = ps.getIndex();

    // Create a Junk instance
    const slice = ps.getSlice(entryStartPos, nextEntryStart);
    const junk = new AST.Junk(slice);
    if (parser.withSpans) {
      junk.addSpan(entryStartPos, nextEntryStart);
    }
    if (parser.withAnnotations) {
      const annot = new AST.Annotation(err.code, err.args, err.message);
      annot.addSpan(errorIndex, errorIndex);
      junk.addAnnotation(annot);
    }
    return junk;
  }
}

function getEntry(ps) {
  let comment;

  if (ps.currentIs('/')) {
    comment = getComment(ps);
  }

  if (ps.currentIs('[')) {
    return getSection(ps, comment);
  }

  if (ps.isIDStart()) {
    return getMessage(ps, comment);
  }

  if (comment) {
    return comment;
  }
  throw new ParseError('E0002');
}

function getComment(ps) {
  ps.expectChar('/');
  ps.expectChar('/');
  ps.takeCharIf(' ');

  let content = '';

  while (true) {
    let ch;
    while ((ch = ps.takeChar(x => x !== '\n'))) {
      content += ch;
    }

    ps.next();

    if (ps.current() === '/') {
      content += '\n';
      ps.next();
      ps.expectChar('/');
      ps.takeCharIf(' ');
    } else {
      break;
    }
  }
  return new AST.Comment(content);
}

function getSection(ps, comment) {
  ps.expectChar('[');
  ps.expectChar('[');

  ps.skipLineWS();

  const symb = getSymbol(ps);

  ps.skipLineWS();

  ps.expectChar(']');
  ps.expectChar(']');

  ps.skipLineWS();

  ps.expectChar('\n');

  return new AST.Section(symb, comment);
}

function getMessage(ps, comment) {
  const id = getIdentifier(ps);

  ps.skipLineWS();

  let pattern;
  let attrs;
  let tags;

  if (ps.currentIs('=')) {
    ps.next();
    ps.skipLineWS();

    pattern = getPattern(ps);
  }

  if (ps.isPeekNextLineAttributeStart()) {
    attrs = getAttributes(ps);
  }

  if (ps.isPeekNextLineTagStart()) {
    if (attrs !== undefined) {
      throw new ParseError('E0012');
    }
    tags = getTags(ps);
  }

  if (pattern === undefined && attrs === undefined && tags === undefined) {
    throw new ParseError('E0005', id.name);
  }

  return new AST.Message(id, pattern, attrs, tags, comment);
}

function getAttributes(ps) {
  const attrs = [];

  while (true) {
    ps.expectChar('\n');
    ps.skipLineWS();

    ps.expectChar('.');

    const key = getIdentifier(ps);

    ps.skipLineWS();

    ps.expectChar('=');

    ps.skipLineWS();

    const value = getPattern(ps);

    if (value === undefined) {
      throw new ParseError('E0006', 'value');
    }

    attrs.push(new AST.Attribute(key, value));

    if (!ps.isPeekNextLineAttributeStart()) {
      break;
    }
  }
  return attrs;
}

function getTags(ps) {
  const tags = [];

  while (true) {
    ps.expectChar('\n');
    ps.skipLineWS();

    ps.expectChar('#');

    const symbol = getSymbol(ps);

    tags.push(new AST.Tag(symbol));

    if (!ps.isPeekNextLineTagStart()) {
      break;
    }
  }
  return tags;
}

function getIdentifier(ps) {
  let name = '';

  name += ps.takeIDStart();

  let ch;
  while ((ch = ps.takeIDChar())) {
    name += ch;
  }

  return new AST.Identifier(name);
}

function getVariantKey(ps) {
  const ch = ps.current();

  if (!ch) {
    throw new ParseError('E0013');
  }

  const cc = ch.charCodeAt(0);

  if ((cc >= 48 && cc <= 57) || cc === 45) { // 0-9, -
    return getNumber(ps);
  }

  return getSymbol(ps);
}

function getVariants(ps) {
  const variants = [];
  let hasDefault = false;

  while (true) {
    let defaultIndex = false;

    ps.expectChar('\n');
    ps.skipLineWS();

    if (ps.currentIs('*')) {
      if (hasDefault) {
        throw new ParseError('E0015');
      }
      ps.next();
      defaultIndex = true;
      hasDefault = true;
    }

    ps.expectChar('[');

    const key = getVariantKey(ps);

    ps.expectChar(']');

    ps.skipLineWS();

    const value = getPattern(ps);

    if (!value) {
      throw new ParseError('E0006', 'value');
    }

    variants.push(new AST.Variant(key, value, defaultIndex));

    if (!ps.isPeekNextLineVariantStart()) {
      break;
    }
  }

  if (!hasDefault) {
    throw new ParseError('E0010');
  }

  return variants;
}

function getSymbol(ps) {
  let name = '';

  name += ps.takeIDStart();

  while (true) {
    const ch = ps.takeSymbChar();
    if (ch) {
      name += ch;
    } else {
      break;
    }
  }

  return new AST.Symbol(name.trimRight());
}

function getDigits(ps) {
  let num = '';

  let ch;
  while ((ch = ps.takeDigit())) {
    num += ch;
  }

  if (num.length === 0) {
    throw new ParseError('E0004', '0-9');
  }

  return num;
}

function getNumber(ps) {
  let num = '';

  if (ps.currentIs('-')) {
    num += '-';
    ps.next();
  }

  num = `${num}${getDigits(ps)}`;

  if (ps.currentIs('.')) {
    num += '.';
    ps.next();
    num = `${num}${getDigits(ps)}`;
  }

  return new AST.NumberExpression(num);
}

function getPattern(ps) {
  let buffer = '';
  const elements = [];
  let firstLine = true;

  let ch;
  while ((ch = ps.current())) {
    if (ch === '\n') {
      if (firstLine && buffer.length !== 0) {
        break;
      }

      if (!ps.isPeekNextLinePattern()) {
        break;
      }

      ps.next();
      ps.skipLineWS();

      if (!firstLine) {
        buffer += ch;
      }
      firstLine = false;
      continue;
    } else if (ch === '\\') {
      const ch2 = ps.peek();
      if (ch2 === '{' || ch2 === '"') {
        buffer += ch2;
      } else {
        buffer += ch + ch2;
      }
      ps.next();
    } else if (ch === '{') {
      ps.next();

      ps.skipLineWS();

      if (buffer.length !== 0) {
        elements.push(new AST.TextElement(buffer));
      }

      buffer = '';

      elements.push(getExpression(ps));

      ps.expectChar('}');

      continue;
    } else {
      buffer += ps.ch;
    }
    ps.next();
  }

  if (buffer.length !== 0) {
    elements.push(new AST.TextElement(buffer));
  }

  return new AST.Pattern(elements);
}

function getExpression(ps) {
  if (ps.isPeekNextLineVariantStart()) {
    const variants = getVariants(ps);

    ps.expectChar('\n');
    ps.expectChar(' ');
    ps.skipLineWS();

    return new AST.SelectExpression(null, variants);
  }

  const selector = getSelectorExpression(ps);

  ps.skipLineWS();

  if (ps.currentIs('-')) {
    ps.peek();
    if (!ps.currentPeekIs('>')) {
      ps.resetPeek();
    } else {
      ps.next();
      ps.next();

      ps.skipLineWS();

      const variants = getVariants(ps);

      if (variants.length === 0) {
        throw new ParseError('E0011');
      }

      ps.expectChar('\n');
      ps.expectChar(' ');
      ps.skipLineWS();

      return new AST.SelectExpression(selector, variants);
    }
  }

  return selector;
}

function getSelectorExpression(ps) {
  const literal = getLiteral(ps);

  if (literal.type !== 'MessageReference') {
    return literal;
  }

  const ch = ps.current();

  if (ch === '.') {
    ps.next();

    const attr = getIdentifier(ps);
    return new AST.AttributeExpression(literal.id, attr);
  }

  if (ch === '[') {
    ps.next();

    const key = getVariantKey(ps);

    ps.expectChar(']');

    return new AST.VariantExpression(literal.id, key);
  }

  if (ch === '(') {
    ps.next();

    const args = getCallArgs(ps);

    ps.expectChar(')');

    return new AST.CallExpression(literal.id, args);
  }

  return literal;
}

function getCallArgs(ps) {
  const args = [];

  ps.skipLineWS();

  while (true) {
    if (ps.current() === ')') {
      break;
    }

    const exp = getSelectorExpression(ps);

    ps.skipLineWS();

    if (ps.current() === ':') {
      if (exp.type !== 'MessageReference') {
        throw new ParseError('E0009');
      }

      ps.next();
      ps.skipLineWS();

      const val = getArgVal(ps);

      args.push(new AST.NamedArgument(exp.id, val));
    } else {
      args.push(exp);
    }

    ps.skipLineWS();

    if (ps.current() === ',') {
      ps.next();
      ps.skipLineWS();
      continue;
    } else {
      break;
    }
  }
  return args;
}

function getArgVal(ps) {
  if (ps.isNumberStart()) {
    return getNumber(ps);
  } else if (ps.currentIs('"')) {
    return getString(ps);
  }
  throw new ParseError('E0006', 'value');
}

function getString(ps) {
  let val = '';

  ps.expectChar('"');

  let ch;
  while ((ch = ps.takeChar(x => x !== '"'))) {
    val += ch;
  }

  ps.next();

  return new AST.StringExpression(val);

}

function getLiteral(ps) {
  const ch = ps.current();

  if (!ch) {
    throw new ParseError('E0014');
  }

  if (ps.isNumberStart()) {
    return getNumber(ps);
  } else if (ch === '"') {
    return getString(ps);
  } else if (ch === '$') {
    ps.next();
    const name = getIdentifier(ps);
    return new AST.ExternalArgument(name);
  }

  const name = getIdentifier(ps);
  return new AST.MessageReference(name);
}
<commit_msg>Make all Parser functions methods<commit_after>/*  eslint no-magic-numbers: [0]  */

import * as AST from './ast';
import { FTLParserStream } from './ftlstream';
import { ParseError } from './errors';

export default class FluentParser {
  constructor({
    withSpans = true,
    withAnnotations = true,
  } = {}) {
    this.withSpans = withSpans;
    this.withAnnotations = withAnnotations;
  }

  parse(source) {
    let comment = null;

    const ps = new FTLParserStream(source);
    ps.skipWSLines();

    const entries = [];

    while (ps.current()) {
      const entry = this.getEntryOrJunk(ps);

      if (entry.type === 'Comment' && entries.length === 0) {
        comment = entry;
      } else {
        entries.push(entry);
      }

      ps.skipWSLines();
    }

    return new AST.Resource(entries, comment);
  }

  parseEntry(source) {
    const ps = new FTLParserStream(source);
    ps.skipWSLines();
    return this.getEntryOrJunk(ps);
  }

  getEntryOrJunk(ps) {
    const entryStartPos = ps.getIndex();

    try {
      const entry = this.getEntry(ps);
      if (this.withSpans) {
        entry.addSpan(entryStartPos, ps.getIndex());
      }
      return entry;
    } catch (err) {
      if (!(err instanceof ParseError)) {
        throw err;
      }

      const errorIndex = ps.getIndex();
      ps.skipToNextEntryStart();
      const nextEntryStart = ps.getIndex();

      // Create a Junk instance
      const slice = ps.getSlice(entryStartPos, nextEntryStart);
      const junk = new AST.Junk(slice);
      if (this.withSpans) {
        junk.addSpan(entryStartPos, nextEntryStart);
      }
      if (this.withAnnotations) {
        const annot = new AST.Annotation(err.code, err.args, err.message);
        annot.addSpan(errorIndex, errorIndex);
        junk.addAnnotation(annot);
      }
      return junk;
    }
  }

  getEntry(ps) {
    let comment;

    if (ps.currentIs('/')) {
      comment = this.getComment(ps);
    }

    if (ps.currentIs('[')) {
      return this.getSection(ps, comment);
    }

    if (ps.isIDStart()) {
      return this.getMessage(ps, comment);
    }

    if (comment) {
      return comment;
    }
    throw new ParseError('E0002');
  }

  getComment(ps) {
    ps.expectChar('/');
    ps.expectChar('/');
    ps.takeCharIf(' ');

    let content = '';

    while (true) {
      let ch;
      while ((ch = ps.takeChar(x => x !== '\n'))) {
        content += ch;
      }

      ps.next();

      if (ps.current() === '/') {
        content += '\n';
        ps.next();
        ps.expectChar('/');
        ps.takeCharIf(' ');
      } else {
        break;
      }
    }
    return new AST.Comment(content);
  }

  getSection(ps, comment) {
    ps.expectChar('[');
    ps.expectChar('[');

    ps.skipLineWS();

    const symb = this.getSymbol(ps);

    ps.skipLineWS();

    ps.expectChar(']');
    ps.expectChar(']');

    ps.skipLineWS();

    ps.expectChar('\n');

    return new AST.Section(symb, comment);
  }

  getMessage(ps, comment) {
    const id = this.getIdentifier(ps);

    ps.skipLineWS();

    let pattern;
    let attrs;
    let tags;

    if (ps.currentIs('=')) {
      ps.next();
      ps.skipLineWS();

      pattern = this.getPattern(ps);
    }

    if (ps.isPeekNextLineAttributeStart()) {
      attrs = this.getAttributes(ps);
    }

    if (ps.isPeekNextLineTagStart()) {
      if (attrs !== undefined) {
        throw new ParseError('E0012');
      }
      tags = this.getTags(ps);
    }

    if (pattern === undefined && attrs === undefined && tags === undefined) {
      throw new ParseError('E0005', id.name);
    }

    return new AST.Message(id, pattern, attrs, tags, comment);
  }

  getAttributes(ps) {
    const attrs = [];

    while (true) {
      ps.expectChar('\n');
      ps.skipLineWS();

      ps.expectChar('.');

      const key = this.getIdentifier(ps);

      ps.skipLineWS();

      ps.expectChar('=');

      ps.skipLineWS();

      const value = this.getPattern(ps);

      if (value === undefined) {
        throw new ParseError('E0006', 'value');
      }

      attrs.push(new AST.Attribute(key, value));

      if (!ps.isPeekNextLineAttributeStart()) {
        break;
      }
    }
    return attrs;
  }

  getTags(ps) {
    const tags = [];

    while (true) {
      ps.expectChar('\n');
      ps.skipLineWS();

      ps.expectChar('#');

      const symbol = this.getSymbol(ps);

      tags.push(new AST.Tag(symbol));

      if (!ps.isPeekNextLineTagStart()) {
        break;
      }
    }
    return tags;
  }

  getIdentifier(ps) {
    let name = '';

    name += ps.takeIDStart();

    let ch;
    while ((ch = ps.takeIDChar())) {
      name += ch;
    }

    return new AST.Identifier(name);
  }

  getVariantKey(ps) {
    const ch = ps.current();

    if (!ch) {
      throw new ParseError('E0013');
    }

    const cc = ch.charCodeAt(0);

    if ((cc >= 48 && cc <= 57) || cc === 45) { // 0-9, -
      return this.getNumber(ps);
    }

    return this.getSymbol(ps);
  }

  getVariants(ps) {
    const variants = [];
    let hasDefault = false;

    while (true) {
      let defaultIndex = false;

      ps.expectChar('\n');
      ps.skipLineWS();

      if (ps.currentIs('*')) {
        if (hasDefault) {
          throw new ParseError('E0015');
        }
        ps.next();
        defaultIndex = true;
        hasDefault = true;
      }

      ps.expectChar('[');

      const key = this.getVariantKey(ps);

      ps.expectChar(']');

      ps.skipLineWS();

      const value = this.getPattern(ps);

      if (!value) {
        throw new ParseError('E0006', 'value');
      }

      variants.push(new AST.Variant(key, value, defaultIndex));

      if (!ps.isPeekNextLineVariantStart()) {
        break;
      }
    }

    if (!hasDefault) {
      throw new ParseError('E0010');
    }

    return variants;
  }

  getSymbol(ps) {
    let name = '';

    name += ps.takeIDStart();

    while (true) {
      const ch = ps.takeSymbChar();
      if (ch) {
        name += ch;
      } else {
        break;
      }
    }

    return new AST.Symbol(name.trimRight());
  }

  getDigits(ps) {
    let num = '';

    let ch;
    while ((ch = ps.takeDigit())) {
      num += ch;
    }

    if (num.length === 0) {
      throw new ParseError('E0004', '0-9');
    }

    return num;
  }

  getNumber(ps) {
    let num = '';

    if (ps.currentIs('-')) {
      num += '-';
      ps.next();
    }

    num = `${num}${this.getDigits(ps)}`;

    if (ps.currentIs('.')) {
      num += '.';
      ps.next();
      num = `${num}${this.getDigits(ps)}`;
    }

    return new AST.NumberExpression(num);
  }

  getPattern(ps) {
    let buffer = '';
    const elements = [];
    let firstLine = true;

    let ch;
    while ((ch = ps.current())) {
      if (ch === '\n') {
        if (firstLine && buffer.length !== 0) {
          break;
        }

        if (!ps.isPeekNextLinePattern()) {
          break;
        }

        ps.next();
        ps.skipLineWS();

        if (!firstLine) {
          buffer += ch;
        }
        firstLine = false;
        continue;
      } else if (ch === '\\') {
        const ch2 = ps.peek();
        if (ch2 === '{' || ch2 === '"') {
          buffer += ch2;
        } else {
          buffer += ch + ch2;
        }
        ps.next();
      } else if (ch === '{') {
        ps.next();

        ps.skipLineWS();

        if (buffer.length !== 0) {
          elements.push(new AST.TextElement(buffer));
        }

        buffer = '';

        elements.push(this.getExpression(ps));

        ps.expectChar('}');

        continue;
      } else {
        buffer += ps.ch;
      }
      ps.next();
    }

    if (buffer.length !== 0) {
      elements.push(new AST.TextElement(buffer));
    }

    return new AST.Pattern(elements);
  }

  getExpression(ps) {
    if (ps.isPeekNextLineVariantStart()) {
      const variants = this.getVariants(ps);

      ps.expectChar('\n');
      ps.expectChar(' ');
      ps.skipLineWS();

      return new AST.SelectExpression(null, variants);
    }

    const selector = this.getSelectorExpression(ps);

    ps.skipLineWS();

    if (ps.currentIs('-')) {
      ps.peek();
      if (!ps.currentPeekIs('>')) {
        ps.resetPeek();
      } else {
        ps.next();
        ps.next();

        ps.skipLineWS();

        const variants = this.getVariants(ps);

        if (variants.length === 0) {
          throw new ParseError('E0011');
        }

        ps.expectChar('\n');
        ps.expectChar(' ');
        ps.skipLineWS();

        return new AST.SelectExpression(selector, variants);
      }
    }

    return selector;
  }

  getSelectorExpression(ps) {
    const literal = this.getLiteral(ps);

    if (literal.type !== 'MessageReference') {
      return literal;
    }

    const ch = ps.current();

    if (ch === '.') {
      ps.next();

      const attr = this.getIdentifier(ps);
      return new AST.AttributeExpression(literal.id, attr);
    }

    if (ch === '[') {
      ps.next();

      const key = this.getVariantKey(ps);

      ps.expectChar(']');

      return new AST.VariantExpression(literal.id, key);
    }

    if (ch === '(') {
      ps.next();

      const args = this.getCallArgs(ps);

      ps.expectChar(')');

      return new AST.CallExpression(literal.id, args);
    }

    return literal;
  }

  getCallArgs(ps) {
    const args = [];

    ps.skipLineWS();

    while (true) {
      if (ps.current() === ')') {
        break;
      }

      const exp = this.getSelectorExpression(ps);

      ps.skipLineWS();

      if (ps.current() === ':') {
        if (exp.type !== 'MessageReference') {
          throw new ParseError('E0009');
        }

        ps.next();
        ps.skipLineWS();

        const val = this.getArgVal(ps);

        args.push(new AST.NamedArgument(exp.id, val));
      } else {
        args.push(exp);
      }

      ps.skipLineWS();

      if (ps.current() === ',') {
        ps.next();
        ps.skipLineWS();
        continue;
      } else {
        break;
      }
    }
    return args;
  }

  getArgVal(ps) {
    if (ps.isNumberStart()) {
      return this.getNumber(ps);
    } else if (ps.currentIs('"')) {
      return this.getString(ps);
    }
    throw new ParseError('E0006', 'value');
  }

  getString(ps) {
    let val = '';

    ps.expectChar('"');

    let ch;
    while ((ch = ps.takeChar(x => x !== '"'))) {
      val += ch;
    }

    ps.next();

    return new AST.StringExpression(val);

  }

  getLiteral(ps) {
    const ch = ps.current();

    if (!ch) {
      throw new ParseError('E0014');
    }

    if (ps.isNumberStart()) {
      return this.getNumber(ps);
    } else if (ch === '"') {
      return this.getString(ps);
    } else if (ch === '$') {
      ps.next();
      const name = this.getIdentifier(ps);
      return new AST.ExternalArgument(name);
    }

    const name = this.getIdentifier(ps);
    return new AST.MessageReference(name);
  }
}
<|endoftext|>


<commit_before>(function ($, fluid) {

	fluid.defaults("fluid.uiOptions.panels.contrast", {
		gradeNames: ["fluid.uiOptions.panels", "autoInit"],
		preferenceMap: {
			"fluid.uiOptions.contrast": {
				"model.value": "default"
			}
		},
		events: {
			onToggleContrastAdjusters: null
		},
		listeners: {
			"afterRender.bindEventPreferenceSwitchContrast": {
				"this": "{that}.dom.valueCheckbox",
				"method": "change",
				"args": ["{that}.events.onToggleContrastAdjusters.fire"]
			},
			"onToggleContrastAdjusters.showHide": {
				"this": "{that}.dom.contrastAdjusters",
				"method": "slideToggle"
			},
			"afterRender.setContrastAdjusters": {
				listener: "fluid.uiOptions.panels.contrast.setContrastAdjusters",
				args: ["{that}.dom.contrastAdjusters", "{that}.model.value"]
			},
			"afterRender.setATTRaddToMyPreferencesLabel": {
				"this": "{that}.dom.addToMyPreferencesLabel",
				"method": "attr",
				"args": [{
					"tooltip-checked": "{that}.options.strings.tooltipChecked",
					"tooltip-unchecked": "{that}.options.strings.tooltipUnchecked",
				}]
			}
		},
		selectors: {
            valueCheckbox: ".flc-uiOptions-constrastInput",
            headingLabel: ".flc-uiOptions-contrast-label",
            panelLabel: ".headerTitle",
            addToMyPreferencesLabel: ".addToMyPreferencesLabel",
            contrastAdjusters: ".fl-uiOptions-category"
		},
        selectorsToIgnore: ["contrastAdjusters"],
		protoTree: {
			valueCheckbox: "${value}",
            headingLabel: {messagekey: "contrast"},
            panelLabel: {messagekey: "addContrast"},
            addToMyPreferencesLabel: " "
		},
		strings: {
			tooltipChecked: {
				expander: {
					func: "fluid.uiOptions.pmt.lookupMsg",
					args: ["{uiOptionsLoader}.msgBundle", "tooltipChecked"]
				}
			},
			tooltipUnchecked: {
				expander: {
					func: "fluid.uiOptions.pmt.lookupMsg",
					args: ["{uiOptionsLoader}.msgBundle", "tooltipUnchecked"]
				}
			}
		},
		components: {
            preview: {
                type: "fluid.uiOptions.preview",
                createOnEvent: "afterRender",
                container: ".flc-uiOptions-contrast .flc-uiOptions-preview-per-setting-frame",
                options: {
                    templateUrl: "../../src/shared/preview/html/uiOptionsContrastPreview.html",
                    events: {
                    	onPreviewLoad: null
                    },
                    listeners: {
                    	"onCreate.init": "fluid.uiOptions.panels.contrast.initPreview"
                    },
                    selectors: {
                    	previewText: ".flc-uiOptions-preview-per-setting-label"
                    },
                    strings: {
                    	previewText: {
                    		expander: {
            					func: "fluid.uiOptions.pmt.lookupMsg",
            					args: ["{uiOptionsLoader}.msgBundle", "contrastPreviewText"]
            				}
                    	}
                    }
                }
            }
        },

        outerPreviewEnhancerOptions: "{originalEnhancerOptions}.options.originalUserOptions",
        emptyComponentType: "fluid.emptySubcomponent",
        distributeOptions: [{
            source: "{that}.options.outerPreviewEnhancerOptions",
            removeSource: true,
            target: "{that preview enhancer}.options"
        }, {
            source: "{that}.options.emptyComponentType",
            removeSource: true,
            target: "{that preview enhancer magnifier}.type"
        }]
	});

	fluid.uiOptions.panels.contrast.initPreview = function (that) {
		that.events.onReady.addListener(function () {
			var p = that.locate("previewText", that.enhancerContainer);
			p.text(that.options.strings.previewText);
		});
	}

	fluid.uiOptions.panels.contrast.setContrastAdjusters = function (contrastAdjuster, flag) {
    	contrastAdjuster[flag ? "show" : "hide"]();
    };
})(jQuery, fluid);
<commit_msg>Trying to set preview text declaratively. No go yet.<commit_after>(function ($, fluid) {

	fluid.defaults("fluid.uiOptions.panels.contrast", {
		gradeNames: ["fluid.uiOptions.panels", "autoInit"],
		preferenceMap: {
			"fluid.uiOptions.contrast": {
				"model.value": "default"
			}
		},
		events: {
			onToggleContrastAdjusters: null
		},
		listeners: {
			"afterRender.bindEventPreferenceSwitchContrast": {
				"this": "{that}.dom.valueCheckbox",
				"method": "change",
				"args": ["{that}.events.onToggleContrastAdjusters.fire"]
			},
			"onToggleContrastAdjusters.showHide": {
				"this": "{that}.dom.contrastAdjusters",
				"method": "slideToggle"
			},
			"afterRender.setContrastAdjusters": {
				listener: "fluid.uiOptions.panels.contrast.setContrastAdjusters",
				args: ["{that}.dom.contrastAdjusters", "{that}.model.value"]
			},
			"afterRender.setATTRaddToMyPreferencesLabel": {
				"this": "{that}.dom.addToMyPreferencesLabel",
				"method": "attr",
				"args": [{
					"tooltip-checked": "{that}.options.strings.tooltipChecked",
					"tooltip-unchecked": "{that}.options.strings.tooltipUnchecked",
				}]
			}
		},
		selectors: {
            valueCheckbox: ".flc-uiOptions-constrastInput",
            headingLabel: ".flc-uiOptions-contrast-label",
            panelLabel: ".headerTitle",
            addToMyPreferencesLabel: ".addToMyPreferencesLabel",
            contrastAdjusters: ".fl-uiOptions-category"
		},
        selectorsToIgnore: ["contrastAdjusters"],
		protoTree: {
			valueCheckbox: "${value}",
            headingLabel: {messagekey: "contrast"},
            panelLabel: {messagekey: "addContrast"},
            addToMyPreferencesLabel: " "
		},
		strings: {
			tooltipChecked: {
				expander: {
					func: "fluid.uiOptions.pmt.lookupMsg",
					args: ["{uiOptionsLoader}.msgBundle", "tooltipChecked"]
				}
			},
			tooltipUnchecked: {
				expander: {
					func: "fluid.uiOptions.pmt.lookupMsg",
					args: ["{uiOptionsLoader}.msgBundle", "tooltipUnchecked"]
				}
			}
		},
		components: {
            preview: {
                type: "fluid.uiOptions.preview",
                createOnEvent: "afterRender",
                container: ".flc-uiOptions-contrast .flc-uiOptions-preview-per-setting-frame",
                options: {
                    templateUrl: "../../src/shared/preview/html/uiOptionsContrastPreview.html",
                    events: {
                    	onPreviewLoad: null
                    },
                    listeners: {
                    	"onReady.setEnhancerText": {
                            listener: "{enhancer}.setText"
                        }
                    },
                    components: {
                    	enhancer: {
                            options: {
                                selectors: {
                                    previewText: ".flc-uiOptions-preview-per-setting-label"
                                },
                                strings: {
                                    previewText: {
                                        expander: {
                                            func: "fluid.uiOptions.pmt.lookupMsg",
                                            args: ["{uiOptionsLoader}.msgBundle", "contrastPreviewText"]
                                        }
                                    }
                                },
                                invokers: {
	                                setText: {
	                                    "this": "{that}.dom.previewText",
	                                    "method": "text",
	                                    "args": ["{that}.options.strings.previewText"]
	                                }
                                }
                            }
                        }
                    }
                }
            }
        },

        outerPreviewEnhancerOptions: "{originalEnhancerOptions}.options.originalUserOptions",
        emptyComponentType: "fluid.emptySubcomponent",
        distributeOptions: [{
            source: "{that}.options.outerPreviewEnhancerOptions",
            removeSource: true,
            target: "{that preview enhancer}.options"
        }, {
            source: "{that}.options.emptyComponentType",
            removeSource: true,
            target: "{that preview enhancer magnifier}.type"
        }]
	});

	fluid.uiOptions.panels.contrast.initPreview = function (that) {
		/*that.events.onReady.addListener(function () {
			var p = that.locate("previewText", that.enhancerContainer);
			p.text(that.options.strings.previewText);
		});*/
	}

	fluid.uiOptions.panels.contrast.setContrastAdjusters = function (contrastAdjuster, flag) {
    	contrastAdjuster[flag ? "show" : "hide"]();
    };
})(jQuery, fluid);
<|endoftext|>


<commit_before>'use strict';

// for minification, explicitly declare dependencies $scope and $http
metadataEditorApp.controller('BaseController',

    ['$scope', '$http', '$log', '$window', 'formOptions', 'updateForms', 'recordService',
        'AttachmentService', 'Geoprocessing', 'hostname', 'sessionId',

    function($scope, $http, $log, $window, formOptions, updateForms,
        recordService, AttachmentService, Geoprocessing, hostname, sessionId)
    {
        // initialize list of existing metadata records
        $scope.allRecords = [];

        $scope.options = {};

        // export to XML
        var exportAddr = function(oid, xmlType) {
            return hostname + '/api/metadata/' + oid + '/' + xmlType;
        };
        $scope.export_ = function(type) {
            var oid = $scope.currentRecord._id.$oid;

            var prefix = '';
            if (sessionId === 'local')
            {
                prefix = 'http://';
            }
            $window.open(prefix + exportAddr(oid, type));
        };

        $scope.updateRecordsList = function() {
            recordService.list()
                .success(function(data) {
                    $scope.allRecords = data.results;
                });
        };

        $scope.updateRecordsList();

        $scope.errors = [];

        /** load up formOptions constants (defined in app.js) **/
        $scope.topicCategoryChoices = formOptions.topicCategoryChoices;

        // order for contact fields
        $scope.orderedContactFields = formOptions.orderedContactFields;

        // contact fields mapping for layperson-to-iso translation
        $scope.cfieldsMap = formOptions.cfieldsMap;

        // set date options
        $scope.dateOptions = {
            changeYear: true,
            changeMonth: true,
            yearRange: '1700:+10'
        };

        // create time picker vars

        $scope.hours = [];
        for (var i = 0; i < 24; i++)
        {
          $scope.hours.push(i);
        }

        $scope.minute_seconds = [];
        for (var i = 0; i < 60; i++)
        {
          $scope.minute_seconds.push(i);
        }

        $scope.knownDataFormats = formOptions.knownDataFormats;

        $scope.spatialDataOptions = formOptions.spatialDataOptions;

        $scope.hierarchyLevels = formOptions.hierarchyLevels;

        $scope.createNewRecord = function() {

            var freshISO = recordService.getFreshISORecord();

            $scope.newRecord = true;
            $scope.currentRecord = freshISO;

            //set geocode write-in box to be blank
            $scope.options.bboxInput ='';

            // iso data formats come from a pre-defined list to from ISO std
            $scope.dataFormats = {
              iso: [''],
              // aux, ie auxiliary, is a single text input write-in
              aux: ''
            };
        };

        // initialize form with placeholder data for creating a new record
        $scope.createNewRecord();

        $scope.createNewDublinRecord = function() {
            var freshDC = recordService.getFreshDCRecord();

            $scope.newRecord = true;
            $scope.currentRecord = freshDC;

            //set geocode write-in box to be blank
            $scope.options.bboxInput ='';

        };

        $scope.createNewDublinRecord();

        /**
         * On click of Load MILES Defaults button,
         * load the defaults in MILES defaults json file
         */
        $scope.loadDefaultMILES = function() {

            var milesFields = recordService.getMilesDefaults();

            for (var key in milesFields)
            {
                if (milesFields.hasOwnProperty(key))
                {
                    // only want to overwrite country and state for MILES
                    if (key === "citation")
                    {
                        for (var idx = 0; idx < $scope.currentRecord.citation.length; idx++)
                        {
                            $scope.currentRecord.citation[idx].country =
                                milesFields[key][0].country;

                            $scope.currentRecord.citation[idx].state =
                                milesFields[key][0].state;
                        }
                    }
                    else if (['place_keywords', 'thematic_keywords'].indexOf(key) > -1)
                    {
                        $scope.currentRecord[key] = milesFields[key].join(', ');
                    }
                    else
                    {
                        $scope.currentRecord[key] = milesFields[key];
                    }
                }
            }
            //set geocode write-in box to be Idaho
            $scope.options.bboxInput ='Idaho';
        };

        /**
         * Load NKN as the only data access contact
         */
        $scope.loadDefaultNKNAsDistributor = function () {

            var nknContact = recordService.getNKNAsDistributor();

            $scope.currentRecord.access[0] = nknContact;
        };

        /**
         * Load a record that from the server and display fields in form
         * @param  {string} recordId The server-generated ID
         */
        $scope.editRecord = function (recordId) {

            recordService.getRecordToEdit(recordId)
                .success(function (data) {
                    $scope.newRecord = false;

                    updateForms($scope, data.record);
                })
                .error(function (error) {
                    $scope.errors.push("Error in loading record to edit");
                });

             //set geocode write-in box to be blank
            $scope.options.bboxInput = '';
        };

        /**
         * On submit of metadata form, submitRecord. This both updates the server
         * and makes sure the form is current.
         */
        $scope.submitDraftRecord = function() {

            recordService.saveDraft($scope)
                .success( function (data) {
                    // need to update the sheet with the ID

                    updateForms($scope, data.record);

                    $scope.newRecord = false;

                    $scope.addedContacts = {
                        'access': 0,
                        'citation': 0
                    };

                    $scope.updateRecordsList();
                })
                .error( function (data) {
                    // TODO
                });
        };

        /** Function to identify if the record is ISO or Dublin based on schema_type field
        used to execute same function but set condition before hand, using for Edit
        */

        $scope.isISO = function(schemaType){
            if (schemaType == 'Dataset (ISO)')
                return true;
            else
                return false;
        };

        $scope.isPublished = function(pubDate){
            if (pubDate > 0)
                return true;
            else
                return false;
        };

        /**
         * Delete a draft record.
         *
         * TODO: Currently there is no restriction on deleting
         * published records, but we should restrict that in the future.
         */
        $scope.deleteById = function(recordId) {

            if ($scope.currentRecord._id !== undefined) {
                var currentRecordId = $scope.currentRecord._id.$oid;
            }

            // delete record, then if the currently loaded record's ID is
            // identical to the one deleted, clear form and re-initialize
            recordService.delete(recordId)
                .success( function (res) {
                    if (currentRecordId === recordId) {
                        $scope.createNewRecord();
                    }

                    $scope.updateRecordsList();
                })
                .error( function (res) {
                    $log.log('yo in erroring out');
                });
        };

        /**
         * Publish a record to the portal. Requires all fields to be valid
         */
        $scope.publishRecord = function() {

            recordService.publish($scope)
                .success( function (data) {

                    // why?
                    // updateForms(data.record);

                    $scope.newRecord = false;

                    $scope.addedContacts = {
                        'access': 0,
                        'citation': 0
                    };

                    $scope.updateRecordsList();
                })
                .error( function (data) {
                    // TODO
                });
        };

        $scope.addedContacts =
        {
          'access': 0,
          'citation': 0
        };

        $scope.addContactCitation = function()
        {
            $scope.currentRecord.citation
                .push({
                    'name': '', 'email': '', 'org': '', 'address': '',
                    'city': '', 'state': '', 'zipcode': '',
                    'country': '', 'phone': ''
                }
            );

            $scope.addedContacts.citation += 1;
        };

        $scope.addContactAccess = function()
        {
            $scope.currentRecord.access
                .push({
                    'name': '', 'email': '', 'org': '', 'address': '',
                    'city': '', 'state': '', 'zipcode': '',
                    'country': '', 'phone': ''
                }
            );

            $scope.addedContacts.access += 1;
        };

        $scope.cancelAddContactCitation = function()
        {
          if ($scope.addedContacts.citation > 0)
          {
            $scope.currentRecord.citation.pop();
            $scope.addedContacts.citation -= 1;
          }
        };

        $scope.cancelAddContactAccess = function()
        {
          if ($scope.addedContacts.access > 0)
          {
            $scope.currentRecord.access.pop();
            $scope.addedContacts.access -= 1;
          }
        };

        $scope.removeOnlineResource = function(resourceIndex)
        {
          if ($scope.currentRecord.online.length === 1)
          {
            $scope.currentRecord.online[0] = "";
          }
          else
          {
            $scope.currentRecord.online.splice(resourceIndex, 1);
          }
        };

        $scope.addOnlineResource = function()
        {
          $scope.currentRecord.online.push("");
        };

        $scope.getBbox = function()
        {
            Geoprocessing.getBbox($scope.options.bboxInput)
                .success( function(data) {
                    $scope.currentRecord.north_lat = data.north;
                    $scope.currentRecord.south_lat = data.south;
                    $scope.currentRecord.east_lon = data.east;
                    $scope.currentRecord.west_lon = data.west;
                })
                .error( function(error) { $log.log(error); });
        };

        $scope.attachmentInfo = {
            newAttachment: ''
        };
        $scope.attachFile = function() {
            // first upload file, then in success callback, attach to record

            var file = $scope.attachmentInfo.newAttachment;

            // $log.log($scope);

            $log.log(file);

            AttachmentService.uploadFile(file)
                .success(function (data) {
                    var url = data.url;
                    var recordId;
                    if ($scope.currentRecord.hasOwnProperty('_id'))
                    {
                        recordId = $scope.currentRecord._id.$oid;
                    }
                    else
                    {
                        $scope.submitDraftRecord();
                        recordId = $scope.currentRecord._id.$oid;
                    }

                    AttachmentService.attachFile(url, recordId)
                        .success(function (attachData) {

                            $scope.currentRecord.attachments =
                                attachData.record.attachments;

                            $scope.updateRecordsList();
                        });
                });
        };

        $scope.detachFile = function(attachmentId) {

            // the attachmentId needs to be fetched from the attachments
            var recordId = $scope.currentRecord._id.$oid;

            AttachmentService.detachFile(attachmentId, recordId)
                .success(function (data) {
                    updateForms($scope, data.record);
                });
        };
  } // end of callback for controller initialization
])
.controller('ISOController', ['formOptions', function(formOptions) {
    this.standard = 'iso';
    this.statusChoicesIsoMap = formOptions.statusChoicesIsoMap;

    // our more human-readable update frequency choices need trans to ISO 19115
    this.updateFrequencyChoicesMap = formOptions.updateFrequencyChoicesMap;
  }
])
.controller('DCController', [function()
  {
    this.standard = 'dc';
  }
])
//map work
.controller('MapController',function($scope, $compile, NgMap)
  {
    var vm = this;
    vm.ne, vm.sw, vm.center;
    NgMap.getMap().then(function(map) {
        vm.map = map;
        if (vm.ne !== undefined)
        {
            $scope.currentRecord.north_lat = vm.ne.lat();
            $scope.currentRecord.south_lat = vm.sw.lat();
            $scope.currentRecord.east_lon = vm.ne.lng();
            $scope.currentRecord.west_lon = vm.sw.lng();
        }
  });
    vm.boundsChanged = function() {
        vm.ne = this.getBounds().getNorthEast();
        vm.sw = this.getBounds().getSouthWest();
        vm.center = this.getBounds().getCenter();
        vm.map.setCenter(vm.center);
        vm.map.fitBounds(this.getBounds());
        $scope.currentRecord.north_lat = vm.ne.lat();
        $scope.currentRecord.south_lat = vm.sw.lat();
        $scope.currentRecord.east_lon = vm.ne.lng();
        $scope.currentRecord.west_lon = vm.sw.lng();
    };
});
<commit_msg>fixed bug showing attachFile button after delete<commit_after>'use strict';

// for minification, explicitly declare dependencies $scope and $http
metadataEditorApp.controller('BaseController',

    ['$scope', '$http', '$log', '$window', 'formOptions', 'updateForms', 'recordService',
        'AttachmentService', 'Geoprocessing', 'hostname', 'sessionId',

    function($scope, $http, $log, $window, formOptions, updateForms,
        recordService, AttachmentService, Geoprocessing, hostname, sessionId)
    {
        // initialize list of existing metadata records
        $scope.allRecords = [];

        $scope.options = {};

        // export to XML
        var exportAddr = function(oid, xmlType) {
            return hostname + '/api/metadata/' + oid + '/' + xmlType;
        };
        $scope.export_ = function(type) {
            var oid = $scope.currentRecord._id.$oid;

            var prefix = '';
            if (sessionId === 'local')
            {
                prefix = 'http://';
            }
            $window.open(prefix + exportAddr(oid, type));
        };

        $scope.updateRecordsList = function() {
            recordService.list()
                .success(function(data) {
                    $scope.allRecords = data.results;
                });
        };

        $scope.updateRecordsList();

        $scope.errors = [];

        /** load up formOptions constants (defined in app.js) **/
        $scope.topicCategoryChoices = formOptions.topicCategoryChoices;

        // order for contact fields
        $scope.orderedContactFields = formOptions.orderedContactFields;

        // contact fields mapping for layperson-to-iso translation
        $scope.cfieldsMap = formOptions.cfieldsMap;

        // set date options
        $scope.dateOptions = {
            changeYear: true,
            changeMonth: true,
            yearRange: '1700:+10'
        };

        // create time picker vars

        $scope.hours = [];
        for (var i = 0; i < 24; i++)
        {
          $scope.hours.push(i);
        }

        $scope.minute_seconds = [];
        for (i = 0; i < 60; i++)
        {
          $scope.minute_seconds.push(i);
        }

        $scope.knownDataFormats = formOptions.knownDataFormats;

        $scope.spatialDataOptions = formOptions.spatialDataOptions;

        $scope.hierarchyLevels = formOptions.hierarchyLevels;

        $scope.createNewRecord = function() {

            var freshISO = recordService.getFreshISORecord();

            $scope.newRecord = true;
            $scope.currentRecord = freshISO;

            //set geocode write-in box to be blank
            $scope.options.bboxInput ='';

            // iso data formats come from a pre-defined list to from ISO std
            $scope.dataFormats = {
              iso: [''],
              // aux, ie auxiliary, is a single text input write-in
              aux: ''
            };

            $scope.attachmentInfo = {
                newAttachment: ''
            };
        };

        // initialize form with placeholder data for creating a new record
        $scope.createNewRecord();

        $scope.createNewDublinRecord = function() {
            var freshDC = recordService.getFreshDCRecord();

            $scope.newRecord = true;
            $scope.currentRecord = freshDC;

            //set geocode write-in box to be blank
            $scope.options.bboxInput ='';

        };

        $scope.createNewDublinRecord();

        /**
         * On click of Load MILES Defaults button,
         * load the defaults in MILES defaults json file
         */
        $scope.loadDefaultMILES = function() {

            var milesFields = recordService.getMilesDefaults();

            for (var key in milesFields)
            {
                if (milesFields.hasOwnProperty(key))
                {
                    // only want to overwrite country and state for MILES
                    if (key === "citation")
                    {
                        for (var idx = 0; idx < $scope.currentRecord.citation.length; idx++)
                        {
                            $scope.currentRecord.citation[idx].country =
                                milesFields[key][0].country;

                            $scope.currentRecord.citation[idx].state =
                                milesFields[key][0].state;
                        }
                    }
                    else if (['place_keywords', 'thematic_keywords'].indexOf(key) > -1)
                    {
                        $scope.currentRecord[key] = milesFields[key].join(', ');
                    }
                    else
                    {
                        $scope.currentRecord[key] = milesFields[key];
                    }
                }
            }
            //set geocode write-in box to be Idaho
            $scope.options.bboxInput ='Idaho';
        };

        /**
         * Load NKN as the only data access contact
         */
        $scope.loadDefaultNKNAsDistributor = function () {

            var nknContact = recordService.getNKNAsDistributor();

            $scope.currentRecord.access[0] = nknContact;
        };

        /**
         * Load a record that from the server and display fields in form
         * @param  {string} recordId The server-generated ID
         */
        $scope.editRecord = function (recordId) {

            recordService.getRecordToEdit(recordId)
                .success(function (data) {
                    $scope.newRecord = false;

                    updateForms($scope, data.record);
                })
                .error(function (error) {
                    $scope.errors.push("Error in loading record to edit");
                });

             //set geocode write-in box to be blank
            $scope.options.bboxInput = '';
        };

        /**
         * On submit of metadata form, submitRecord. This both updates the server
         * and makes sure the form is current.
         */
        $scope.submitDraftRecord = function() {

            recordService.saveDraft($scope)
                .success( function (data) {
                    // need to update the sheet with the ID

                    updateForms($scope, data.record);

                    $scope.newRecord = false;

                    $scope.addedContacts = {
                        'access': 0,
                        'citation': 0
                    };

                    $scope.updateRecordsList();
                })
                .error( function (data) {
                    // TODO
                });
        };

        /** Function to identify if the record is ISO or Dublin based on schema_type field
        used to execute same function but set condition before hand, using for Edit
        */

        $scope.isISO = function(schemaType){
            if (schemaType == 'Dataset (ISO)')
                return true;
            else
                return false;
        };

        $scope.isPublished = function(pubDate){
            if (pubDate > 0)
                return true;
            else
                return false;
        };

        /**
         * Delete a draft record.
         *
         * TODO: Currently there is no restriction on deleting
         * published records, but we should restrict that in the future.
         */
        $scope.deleteById = function(recordId) {

            if ($scope.currentRecord._id !== undefined) {
                var currentRecordId = $scope.currentRecord._id.$oid;
            }

            // delete record, then if the currently loaded record's ID is
            // identical to the one deleted, clear form and re-initialize
            recordService.delete(recordId)
                .success( function (res) {
                    if (currentRecordId === recordId) {
                        $scope.createNewRecord();
                    }

                    $scope.updateRecordsList();
                })
                .error( function (res) {
                    $log.log('yo in erroring out');
                });
        };

        /**
         * Publish a record to the portal. Requires all fields to be valid
         */
        $scope.publishRecord = function() {

            recordService.publish($scope)
                .success( function (data) {

                    // why?
                    // updateForms(data.record);

                    $scope.newRecord = false;

                    $scope.addedContacts = {
                        'access': 0,
                        'citation': 0
                    };

                    $scope.updateRecordsList();
                })
                .error( function (data) {
                    // TODO
                });
        };

        $scope.addedContacts =
        {
          'access': 0,
          'citation': 0
        };

        $scope.addContactCitation = function()
        {
            $scope.currentRecord.citation
                .push({
                    'name': '', 'email': '', 'org': '', 'address': '',
                    'city': '', 'state': '', 'zipcode': '',
                    'country': '', 'phone': ''
                }
            );

            $scope.addedContacts.citation += 1;
        };

        $scope.addContactAccess = function()
        {
            $scope.currentRecord.access
                .push({
                    'name': '', 'email': '', 'org': '', 'address': '',
                    'city': '', 'state': '', 'zipcode': '',
                    'country': '', 'phone': ''
                }
            );

            $scope.addedContacts.access += 1;
        };

        $scope.cancelAddContactCitation = function()
        {
          if ($scope.addedContacts.citation > 0)
          {
            $scope.currentRecord.citation.pop();
            $scope.addedContacts.citation -= 1;
          }
        };

        $scope.cancelAddContactAccess = function()
        {
          if ($scope.addedContacts.access > 0)
          {
            $scope.currentRecord.access.pop();
            $scope.addedContacts.access -= 1;
          }
        };

        $scope.removeOnlineResource = function(resourceIndex)
        {
          if ($scope.currentRecord.online.length === 1)
          {
            $scope.currentRecord.online[0] = "";
          }
          else
          {
            $scope.currentRecord.online.splice(resourceIndex, 1);
          }
        };

        $scope.addOnlineResource = function()
        {
          $scope.currentRecord.online.push("");
        };

        $scope.getBbox = function()
        {
            Geoprocessing.getBbox($scope.options.bboxInput)
                .success( function(data) {
                    $scope.currentRecord.north_lat = data.north;
                    $scope.currentRecord.south_lat = data.south;
                    $scope.currentRecord.east_lon = data.east;
                    $scope.currentRecord.west_lon = data.west;
                })
                .error( function(error) { $log.log(error); });
        };

        $scope.attachmentInfo = {
            newAttachment: ''
        };
        $scope.attachFile = function() {
            // first upload file, then in success callback, attach to record

            var file = $scope.attachmentInfo.newAttachment;

            // $log.log($scope);

            $log.log(file);

            AttachmentService.uploadFile(file)
                .success(function (data) {
                    var url = data.url;
                    var recordId;
                    if ($scope.currentRecord.hasOwnProperty('_id'))
                    {
                        recordId = $scope.currentRecord._id.$oid;
                    }
                    else
                    {
                        $scope.submitDraftRecord();
                        recordId = $scope.currentRecord._id.$oid;
                    }

                    AttachmentService.attachFile(url, recordId)
                        .success(function (attachData) {

                            $scope.currentRecord.attachments =
                                attachData.record.attachments;

                            $scope.updateRecordsList();
                        });
                });
        };

        $scope.detachFile = function(attachmentId) {

            // the attachmentId needs to be fetched from the attachments
            var recordId = $scope.currentRecord._id.$oid;

            AttachmentService.detachFile(attachmentId, recordId)
                .success(function (data) {
                    updateForms($scope, data.record);
                });
        };
  } // end of callback for controller initialization
])
.controller('ISOController', ['formOptions', function(formOptions) {
    this.standard = 'iso';
    this.statusChoicesIsoMap = formOptions.statusChoicesIsoMap;

    // our more human-readable update frequency choices need trans to ISO 19115
    this.updateFrequencyChoicesMap = formOptions.updateFrequencyChoicesMap;
  }
])
.controller('DCController', [function()
  {
    this.standard = 'dc';
  }
])
//map work
.controller('MapController',function($scope, $compile, NgMap)
  {
    var vm = this;
    vm.ne, vm.sw, vm.center;
    NgMap.getMap().then(function(map) {
        vm.map = map;
        if (vm.ne !== undefined)
        {
            $scope.currentRecord.north_lat = vm.ne.lat();
            $scope.currentRecord.south_lat = vm.sw.lat();
            $scope.currentRecord.east_lon = vm.ne.lng();
            $scope.currentRecord.west_lon = vm.sw.lng();
        }
  });
    vm.boundsChanged = function() {
        vm.ne = this.getBounds().getNorthEast();
        vm.sw = this.getBounds().getSouthWest();
        vm.center = this.getBounds().getCenter();
        vm.map.setCenter(vm.center);
        vm.map.fitBounds(this.getBounds());
        $scope.currentRecord.north_lat = vm.ne.lat();
        $scope.currentRecord.south_lat = vm.sw.lat();
        $scope.currentRecord.east_lon = vm.ne.lng();
        $scope.currentRecord.west_lon = vm.sw.lng();
    };
});
<|endoftext|>


<commit_before>import livesearch from './helpers/livesearch';
import { resizeIframes } from './helpers/iFrameResize';
import './help/contactForm';
import text from './helpers/form_bug_text';

const MAXIMUM_ALLOWABLE_TOTAL_ATTACHMENTS_SIZE_BYTE = Number($('.form-control-file').data('maxAttachmentSizeMb')) * 1024 * 1024;

$(document).ready(() => {
	$('.btn-poll').on('click', (e) => {
		e.preventDefault();

		document.cookie = 'pollClicked=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/';
	});

	// only fill textarea if empty
	if (!$('textarea[name= problemDescription]').val()) {
		$('textarea[name= problemDescription]').text(text);
	}

	$('.form-control-file').change(function x() {
		const form = $(this).closest('form');
		let fileSize = 0;
		if (this.files.length > 0) {
			for (let i = 0; i <= this.files.length - 1; i += 1) {
				if (this.files.item(i).type.includes('image/')
				|| this.files.item(i).type.includes('video/')
				|| this.files.item(i).type.includes('application/msword')
				|| this.files.item(i).type.includes('application/pdf')) {
					form.find('.file-alert').html('');
					form.find(':submit').prop('disabled', false);
				} else {
					form.find('.file-alert').html(`<i class="fa fa-exclamation"></i> "${this.files.item(i).name}" ist kein Bild, Video oder zulässige Datei`);
					form.find(':submit').prop('disabled', true);
					return;
				}
				fileSize += this.files.item(i).size;
			}
		}
		if (fileSize > MAXIMUM_ALLOWABLE_TOTAL_ATTACHMENTS_SIZE_BYTE) {
			if (this.files.length > 1) {
				form.find('.file-alert').html(' Die angehängten Dateien überschreiten die maximal zulässige Gesamtgröße!');
			} else {
				form.find('.file-alert').html(' Die angehängte Datei überschreitet die maximal zulässige Größe!');
			}
			form.find(':submit').prop('disabled', true);
		} else {
			form.find('.file-alert').html('');
			form.find(':submit').prop('disabled', false);
		}
	});
});

// iFrame full height
resizeIframes(undefined, () => {
	document.querySelectorAll('.mobile-warning').forEach((warning) => {
		warning.remove();
	});
	document.querySelectorAll('iframe').forEach((frame) => {
		frame.setAttribute('scrolling', 'no');
	});
});

/* script for iFrame
// this needs to be embedded on every page that should be displayed via iFrame
// and the message to the parent should be send, whenever the page resizes.
// This script shouldn't be removed from here unless it's saved somewhere save where we can find it when needed.

window.addEventListener("message", (event) => {
    const message = JSON.parse(event.data);
    if(message.function){
        if(message.function === "getSize" && message.identifier){
            window.parent.postMessage(JSON.stringify({
                identifier: message.identifier,
                size: {
                    x: document.body.scrollWidth,
                    y: document.body.scrollHeight
                }
            }), '*');
        }
    }
}, false);
*/

// confluence live-search
function truncate(text, length) {
	if (text.length <= length) {
		return text;
	}
	const subString = text.substr(0, length - 1);
	return `${subString.substr(0, subString.lastIndexOf(' '))}...`;
}

function extractResults(result) {
	return result.results;
}

function parseData(result) {
	if (result) {
		return {
			class: '',
			link: `/help/confluence/${result.id}`,
			title: result.title,
			short_description: truncate(result.bodyTextHighlights, 100),
		};
	}
	return {
		class: 'disabled',
		link: '#',
		title: 'Keine Ergebnisse gefunden 😪',
		short_description: 'Probiere es mit anderen Suchbegriffen erneut',
	};
}
const config = {
	// eslint-disable-next-line
	url: 'https://docs.schul-cloud.org/rest/searchv3/1.0/search?queryString=${inputValue}&where=SCDOK&type=page&pageSize=10&highlight=false',
	extractResultArray: extractResults,
	dataParser: parseData,
	livesearchRootSelector: '.live-search',
	inputSelector: 'input.search',
	resultContainerSelector: '.live-search-results',
};
livesearch(config);
<commit_msg>Update help.js<commit_after>import livesearch from './helpers/livesearch';
import { resizeIframes } from './helpers/iFrameResize';
import './help/contactForm';
import text from './helpers/form_bug_text';

/* eslint-disable max-len */
const MAXIMUM_ALLOWABLE_TOTAL_ATTACHMENTS_SIZE_BYTE = Number($('.form-control-file').data('maxAttachmentSizeMb')) * 1024 * 1024;

$(document).ready(() => {
	$('.btn-poll').on('click', (e) => {
		e.preventDefault();

		document.cookie = 'pollClicked=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/';
	});

	// only fill textarea if empty
	if (!$('textarea[name= problemDescription]').val()) {
		$('textarea[name= problemDescription]').text(text);
	}

	$('.form-control-file').change(function x() {
		const form = $(this).closest('form');
		let fileSize = 0;
		if (this.files.length > 0) {
			for (let i = 0; i <= this.files.length - 1; i += 1) {
				if (this.files.item(i).type.includes('image/')
				|| this.files.item(i).type.includes('video/')
				|| this.files.item(i).type.includes('application/msword')
				|| this.files.item(i).type.includes('application/pdf')) {
					form.find('.file-alert').html('');
					form.find(':submit').prop('disabled', false);
				} else {
					form.find('.file-alert').html(`<i class="fa fa-exclamation"></i> "${this.files.item(i).name}" ist kein Bild, Video oder zulässige Datei`);
					form.find(':submit').prop('disabled', true);
					return;
				}
				fileSize += this.files.item(i).size;
			}
		}
		if (fileSize > MAXIMUM_ALLOWABLE_TOTAL_ATTACHMENTS_SIZE_BYTE) {
			if (this.files.length > 1) {
				form.find('.file-alert').html(' Die angehängten Dateien überschreiten die maximal zulässige Gesamtgröße!');
			} else {
				form.find('.file-alert').html(' Die angehängte Datei überschreitet die maximal zulässige Größe!');
			}
			form.find(':submit').prop('disabled', true);
		} else {
			form.find('.file-alert').html('');
			form.find(':submit').prop('disabled', false);
		}
	});
});

// iFrame full height
resizeIframes(undefined, () => {
	document.querySelectorAll('.mobile-warning').forEach((warning) => {
		warning.remove();
	});
	document.querySelectorAll('iframe').forEach((frame) => {
		frame.setAttribute('scrolling', 'no');
	});
});

/* script for iFrame
// this needs to be embedded on every page that should be displayed via iFrame
// and the message to the parent should be send, whenever the page resizes.
// This script shouldn't be removed from here unless it's saved somewhere save where we can find it when needed.

window.addEventListener("message", (event) => {
    const message = JSON.parse(event.data);
    if(message.function){
        if(message.function === "getSize" && message.identifier){
            window.parent.postMessage(JSON.stringify({
                identifier: message.identifier,
                size: {
                    x: document.body.scrollWidth,
                    y: document.body.scrollHeight
                }
            }), '*');
        }
    }
}, false);
*/

// confluence live-search
function truncate(text, length) {
	if (text.length <= length) {
		return text;
	}
	const subString = text.substr(0, length - 1);
	return `${subString.substr(0, subString.lastIndexOf(' '))}...`;
}

function extractResults(result) {
	return result.results;
}

function parseData(result) {
	if (result) {
		return {
			class: '',
			link: `/help/confluence/${result.id}`,
			title: result.title,
			short_description: truncate(result.bodyTextHighlights, 100),
		};
	}
	return {
		class: 'disabled',
		link: '#',
		title: 'Keine Ergebnisse gefunden 😪',
		short_description: 'Probiere es mit anderen Suchbegriffen erneut',
	};
}
const config = {
	// eslint-disable-next-line
	url: 'https://docs.schul-cloud.org/rest/searchv3/1.0/search?queryString=${inputValue}&where=SCDOK&type=page&pageSize=10&highlight=false',
	extractResultArray: extractResults,
	dataParser: parseData,
	livesearchRootSelector: '.live-search',
	inputSelector: 'input.search',
	resultContainerSelector: '.live-search-results',
};
livesearch(config);
<|endoftext|>


<commit_before>var mingy = require('../lib/mingy')
  , Parser = mingy.Parser
  , Command = mingy.Command

// define locations in our special game
var locations = {
  "hallway": {
    "description": "You are in a hallway. From here you can go north.",
    "exits": {"north": "room"}
  },
  "room": {
    "description": "You are in a room. From here you can go south.",
    "exits": {"south": "hallway"}
  }
}

// define props in our special game
var props = {
  "rock": {
    "description": "The rock is alright.",
    "location": "hallway"
  }
}

// define commands
var commands = []

commands.push(command = new Command('quit'))
command.set('syntax', ['quit', 'exit'])
command.set('logic', function(args) {
  process.exit(0)
})

commands.push(command = new Command('help'))
command.set('syntax', ['help'])
command.set('logic', function(args) {

  var output = ''

  output += "You can use the following commands:\n"
  output += "  'look' (or 'l') to look around\n"
  output += "  'go <direction>' to walk in a direction\n"
  output += "  'get <object>' to pick up something\n"
  output += "  'drop <object>' to drop something\n"
  output += "  'inventory' (or 'i') to list what you're carrying\n"
  output += "  'exit' to quit the game\n"

  return output
})

commands.push(command = new Command('look'))
command.set('syntax', ['l', 'look'])
command.set('logic', function(args, env) {

  var output = ''

  // describe location
  output += env.locations[env.location].description + "\n"

  // describe nearby props
  for (var propName in env.props) {
    var prop = env.props[propName]
    if (prop.location == env.location) {
      output += "You see a " + propName + ".\n"
    }
  }

  return output
})

commands.push(command = new Command('go'))
command.set('syntax', ['go <direction>'])
command.set('logic', function(args, env) {

  var output = ''

  var location = env.locations[env.location]

  if (location.exits[args.direction]) {
    output += "You go " + args.direction + ".\n"
    env.location = location.exits[args.direction]
  }
  else {
    output += "You can't go that way.\n"
  }

  return output
})

commands.push(command = new Command('get'))
command.set('syntax', ['get <prop>'])
command.set('logic', function(args, env) {

  var output = ''

  if (env.props[args.prop]) {

    if (env.props[args.prop].location == env.location) {
      env.props[args.prop].location = 'player'
      output += "You take the " + args.prop + ".\n"
    }
    else if (env.props[args.prop].location == 'player') {
      output += "You already have it, Einstein.\n"
    }
    else {
      output += "I don't see a " + args.prop + ".\n"
    }
  }
  else {
    output += "I don't see a " + args.prop + ".\n"
  }

  return output
})

commands.push(command = new Command('drop'))
command.set('syntax', ['drop <prop>'])
command.set('logic', function(args, env) {

  var output = ''

  if (env.props[args.prop]) {

    if (env.props[args.prop].location == 'player') {
      env.props[args.prop].location = env.location
      output += "You drop the " + args.prop + ".\n"
    }
    else {
      output += "You don't have a " + args.prop + ".\n"
    }
  }
  else {
    output += "You don't have a " + args.prop + ".\n"
  }

  return output
})

commands.push(command = new Command('inventory'))
command.set('syntax', ['i', 'inventory'])
command.set('logic', function(args, env) {

  var output = ''

  // list props being carried
  for (var propName in env.props) {
    var prop = env.props[propName]
    if (prop.location == 'player') {
      output += "You have a " + propName + ".\n"
    }
  }

  if (output == '') {
    output += "You're carrying nothing.\n"
  }

  return output
})

// begin adventurings!
console.log("Welcome to Rock Moving Adventure!\n")
console.log("In a world gone mad, one rock is out of place.")
console.log("Enter 'help' for a list of commands.")

var parser = new Parser(commands)
parser.setEnv('locations', locations)
parser.setEnv('props', props)
parser.setEnv('location', 'hallway')
parser.shell('>', function(parser) {
  if (parser.env.props.rock.location == 'room') {
    console.log("Congratulationis!!! You set things right and won the game!\n")
    process.exit(0)
  }
})
<commit_msg>Fixed issue.<commit_after>var mingy = require('../lib/mingy')
  , Parser = mingy.Parser
  , Command = mingy.Command

// define locations in our special game
var locations = {
  "hallway": {
    "description": "You are in a hallway. From here you can go north.",
    "exits": {"north": "room"}
  },
  "room": {
    "description": "You are in a room. From here you can go south.",
    "exits": {"south": "hallway"}
  }
}

// define props in our special game
var props = {
  "rock": {
    "description": "The rock is alright.",
    "location": "hallway"
  }
}

// define commands
var commands = []

commands.push(command = new Command('quit'))
command.set('syntax', ['quit', 'exit'])
command.set('logic', function(args) {
  process.exit(0)
})

commands.push(command = new Command('help'))
command.set('syntax', ['help'])
command.set('logic', function(args) {

  var output = ''

  output += "You can use the following commands:\n"
  output += "  'look' (or 'l') to look around\n"
  output += "  'go <direction>' to walk in a direction\n"
  output += "  'get <object>' to pick up something\n"
  output += "  'drop <object>' to drop something\n"
  output += "  'inventory' (or 'i') to list what you're carrying\n"
  output += "  'exit' to quit the game\n"

  return output
})

commands.push(command = new Command('look'))
command.set('syntax', ['l', 'look'])
command.set('logic', function(args, env) {

  var output = ''

  // describe location
  output += env.locations[env.location].description + "\n"

  // describe nearby props
  for (var propName in env.props) {
    var prop = env.props[propName]
    if (prop.location == env.location) {
      output += "You see a " + propName + ".\n"
    }
  }

  return output
})

commands.push(command = new Command('go'))
command.set('syntax', ['go <direction>'])
command.set('logic', function(args, env) {

  var output = ''

  var location = env.locations[env.location]

  if (location.exits[args.direction]) {
    output += "You go " + args.direction + ".\n"
    env.location = location.exits[args.direction]
  }
  else {
    output += "You can't go that way.\n"
  }

  return output
})

commands.push(command = new Command('get'))
command.set('syntax', ['get <prop>'])
command.set('logic', function(args, env) {

  var output = ''

  if (env.props[args.prop]) {

    if (env.props[args.prop].location == env.location) {
      env.props[args.prop].location = 'player'
      output += "You take the " + args.prop + ".\n"
    }
    else if (env.props[args.prop].location == 'player') {
      output += "You already have it, Einstein.\n"
    }
  }

  // haven't gotten anything, so there's nothing to be got
  if (output == '') {
    output += "I don't see a " + args.prop + ".\n"
  }

  return output
})

commands.push(command = new Command('drop'))
command.set('syntax', ['drop <prop>'])
command.set('logic', function(args, env) {

  var output = ''

  if (env.props[args.prop]) {

    if (env.props[args.prop].location == 'player') {
      env.props[args.prop].location = env.location
      output += "You drop the " + args.prop + ".\n"
    }
  }

  // haven't dropped anything, so there's nothing to drop
  if (output == '') {
    output += "You don't have a " + args.prop + ".\n"
  }

  return output
})

commands.push(command = new Command('inventory'))
command.set('syntax', ['i', 'inventory'])
command.set('logic', function(args, env) {

  var output = ''

  // list props being carried
  for (var propName in env.props) {
    var prop = env.props[propName]
    if (prop.location == 'player') {
      output += "You have a " + propName + ".\n"
    }
  }

  if (output == '') {
    output += "You're carrying nothing.\n"
  }

  return output
})

// begin adventurings!
console.log("Welcome to Rock Moving Adventure!\n")
console.log("In a world gone mad, one rock is out of place.")
console.log("Enter 'help' for a list of commands.")

var parser = new Parser(commands)
parser.setEnv('locations', locations)
parser.setEnv('props', props)
parser.setEnv('location', 'hallway')
parser.shell('>', function(parser) {
  if (parser.env.props.rock.location == 'room') {
    console.log("Congratulationis!!! You set things right and won the game!\n")
    process.exit(0)
  }
})
<|endoftext|>


<commit_before>import React from 'react'
import { DeepZoom } from '../../plugins/DeepZoom'

const DeepZoomDemo = () => {
  return (

      <DeepZoom url="http://www.gigapan.com/embeds/x9jj_i-vmX8/" />

  )
}

export default DeepZoomDemo
<commit_msg>Added dzi to demo<commit_after>import React from 'react'
import DeepZoom from '../../plugins/DeepZoom/osd'

const DeepZoomDemo = () => {
  return (

      <DeepZoom
        title={'Paris'}
        url={'https://s3-us-west-2.amazonaws.com/indepthapp/deepzooms/paris/paris.dzi'}
      />

  )
}

export default DeepZoomDemo
<|endoftext|>


<commit_before>angular.module('BeersApp.controllers', []).
controller('beersController', function($scope, beerAPIservice) {
    $scope.nameFilter = null;
    $scope.beersList = [];

    beerAPIservice.getBeers().success(function (response) {
        $scope.beersList = response;
    });
});<commit_msg>Code cleanup and loading indication handling<commit_after>angular.module('BeersApp.controllers', []).
controller('beersController', function($scope, beerAPIservice) {

  $scope.searchFilter = null;
  $scope.beersList = [];

  beerAPIservice.getBeers().success(function (response) {
    document.getElementById('intro').style.display = 'none';
    document.body.className = '';
    $scope.beersList = response;
  });

});<|endoftext|>


<commit_before>import { flatMap, kebabCase, pick, size } from 'lodash';
import md5 from 'js-md5';

const ORG_INFO_ATTRS = ['org_name', 'org_logo_url'];
const ADMIN_ATTRS = ['email', 'name', 'password', 'password_confirmation', 'username'];

export const addGravatarUrlToResource = (resource) => {
  const { email } = resource;

  const emailHash = md5(email.toLowerCase());
  const gravatarURL = `https://www.gravatar.com/avatar/${emailHash}?d=blank&size=200`;

  return {
    ...resource,
    gravatarURL,
  };
};

const labelSlug = (label) => {
  const { display_text: displayText } = label;

  if (!displayText) return undefined;

  const lowerDisplayText = displayText.toLowerCase();

  return kebabCase(lowerDisplayText);
};

const filterTarget = (targetType) => {
  return (target) => {
    return target.target_type === targetType ? [target.id] : [];
  };
};

export const formatConfigDataForServer = (config) => {
  const orgInfoAttrs = pick(config, ['org_logo_url', 'org_name']);
  const serverSettingsAttrs = pick(config, ['kolide_server_url']);
  const smtpSettingsAttrs = pick(config, [
    'authentication_method', 'authentication_type', 'domain', 'email_enabled', 'enable_ssl_tls',
    'enable_start_tls', 'password', 'port', 'sender_address', 'server', 'user_name', 'verify_ssl_certs',
  ]);

  const orgInfo = size(orgInfoAttrs) && { org_info: orgInfoAttrs };
  const serverSettings = size(serverSettingsAttrs) && { server_settings: serverSettingsAttrs };
  const smtpSettings = size(smtpSettingsAttrs) && { smtp_settings: smtpSettingsAttrs };

  return {
    ...orgInfo,
    ...serverSettings,
    ...smtpSettings,
  };
};

export const formatSelectedTargetsForApi = (selectedTargets, appendID = false) => {
  const targets = selectedTargets || [];
  const hosts = flatMap(targets, filterTarget('hosts'));
  const labels = flatMap(targets, filterTarget('labels'));

  if (appendID) {
    return { host_ids: hosts, label_ids: labels };
  }

  return { hosts, labels };
};

const setupData = (formData) => {
  const orgInfo = pick(formData, ORG_INFO_ATTRS);
  const adminInfo = pick(formData, ADMIN_ATTRS);

  return {
    kolide_server_url: formData.kolide_server_url,
    org_info: {
      ...orgInfo,
    },
    admin: {
      admin: true,
      ...adminInfo,
    },
  };
};

export default { addGravatarUrlToResource, formatConfigDataForServer, formatSelectedTargetsForApi, labelSlug, setupData };
<commit_msg>send osquery enroll secret to server (#1077)<commit_after>import { flatMap, kebabCase, pick, size } from 'lodash';
import md5 from 'js-md5';

const ORG_INFO_ATTRS = ['org_name', 'org_logo_url'];
const ADMIN_ATTRS = ['email', 'name', 'password', 'password_confirmation', 'username'];

export const addGravatarUrlToResource = (resource) => {
  const { email } = resource;

  const emailHash = md5(email.toLowerCase());
  const gravatarURL = `https://www.gravatar.com/avatar/${emailHash}?d=blank&size=200`;

  return {
    ...resource,
    gravatarURL,
  };
};

const labelSlug = (label) => {
  const { display_text: displayText } = label;

  if (!displayText) return undefined;

  const lowerDisplayText = displayText.toLowerCase();

  return kebabCase(lowerDisplayText);
};

const filterTarget = (targetType) => {
  return (target) => {
    return target.target_type === targetType ? [target.id] : [];
  };
};

export const formatConfigDataForServer = (config) => {
  const orgInfoAttrs = pick(config, ['org_logo_url', 'org_name']);
  const serverSettingsAttrs = pick(config, ['kolide_server_url', 'osquery_enroll_secret']);
  const smtpSettingsAttrs = pick(config, [
    'authentication_method', 'authentication_type', 'domain', 'email_enabled', 'enable_ssl_tls',
    'enable_start_tls', 'password', 'port', 'sender_address', 'server', 'user_name', 'verify_ssl_certs',
  ]);

  const orgInfo = size(orgInfoAttrs) && { org_info: orgInfoAttrs };
  const serverSettings = size(serverSettingsAttrs) && { server_settings: serverSettingsAttrs };
  const smtpSettings = size(smtpSettingsAttrs) && { smtp_settings: smtpSettingsAttrs };

  return {
    ...orgInfo,
    ...serverSettings,
    ...smtpSettings,
  };
};

export const formatSelectedTargetsForApi = (selectedTargets, appendID = false) => {
  const targets = selectedTargets || [];
  const hosts = flatMap(targets, filterTarget('hosts'));
  const labels = flatMap(targets, filterTarget('labels'));

  if (appendID) {
    return { host_ids: hosts, label_ids: labels };
  }

  return { hosts, labels };
};

const setupData = (formData) => {
  const orgInfo = pick(formData, ORG_INFO_ATTRS);
  const adminInfo = pick(formData, ADMIN_ATTRS);

  return {
    kolide_server_url: formData.kolide_server_url,
    org_info: {
      ...orgInfo,
    },
    admin: {
      admin: true,
      ...adminInfo,
    },
  };
};

export default { addGravatarUrlToResource, formatConfigDataForServer, formatSelectedTargetsForApi, labelSlug, setupData };
<|endoftext|>


<commit_before>
// check out https://github.com/visionmedia/node-pwd

/**
 * Module dependencies.
 */

var crypto = require('crypto');

/**
 * Bytesize.
 */

var len = 128;

/**
 * Iterations. ~300ms
 */

var iterations = 12000;

/**
 * Hashes a password with optional `salt`, otherwise
 * generate a salt for `pass` and invoke `fn(err, salt, hash)`.
 *
 * @param {String} password to hash
 * @param {String} optional salt
 * @param {Function} callback
 * @api public
 */

exports.hash = function (pwd, salt, fn) {
  if (3 == arguments.length) {
    crypto.pbkdf2(pwd, salt, iterations, len, function(err, hash){
      fn(err, (new Buffer(hash, 'binary')).toString('base64'));
    });
  } else {
    fn = salt;
    crypto.randomBytes(len, function(err, salt){
      if (err) return fn(err);
      salt = salt.toString('base64');
      crypto.pbkdf2(pwd, salt, iterations, len, function(err, hash){
        if (err) return fn(err);
        fn(null, salt, (new Buffer(hash, 'binary')).toString('base64'));
      });
    });
  }
};<commit_msg>Removed Buffer call with 'binary' encoding option in auth example.<commit_after>
// check out https://github.com/visionmedia/node-pwd

/**
 * Module dependencies.
 */

var crypto = require('crypto');

/**
 * Bytesize.
 */

var len = 128;

/**
 * Iterations. ~300ms
 */

var iterations = 12000;

/**
 * Hashes a password with optional `salt`, otherwise
 * generate a salt for `pass` and invoke `fn(err, salt, hash)`.
 *
 * @param {String} password to hash
 * @param {String} optional salt
 * @param {Function} callback
 * @api public
 */

exports.hash = function (pwd, salt, fn) {
  if (3 == arguments.length) {
    crypto.pbkdf2(pwd, salt, iterations, len, function(err, hash){
      fn(err, hash.toString('base64'));
    });
  } else {
    fn = salt;
    crypto.randomBytes(len, function(err, salt){
      if (err) return fn(err);
      salt = salt.toString('base64');
      crypto.pbkdf2(pwd, salt, iterations, len, function(err, hash){
        if (err) return fn(err);
        fn(null, salt, hash.toString('base64'));
      });
    });
  }
};
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.8.0
(function() {
  var Gitlab, credentials, gitlab;

  process.stdout.write('\u001B[2J\u001B[0;0f');

  Gitlab = require('..');

  credentials = {
    url: 'http://demo.gitlab.com',
    token: 'bad-token'
  };

  gitlab = new Gitlab({
    url: credentials.url,
    token: credentials.token
  });

  gitlab.projects.all(function(err, resp, result) {
    return console.log({
      err: err,
      resp: resp,
      result: result
    });
  });

}).call(this);
<commit_msg>rebuild example<commit_after>// Generated by CoffeeScript 1.8.0
(function() {
  var Gitlab, credentials, gitlab;

  process.stdout.write('\u001B[2J\u001B[0;0f');

  Gitlab = require('..');

  credentials = {
    url: 'http://demo.gitlab.com',
    token: 'bad-token'
  };

  gitlab = new Gitlab({
    url: credentials.url,
    token: credentials.token
  });

  gitlab.projects.all(function(err, resp, result) {
    console.log("having:    ", {
      err: err,
      resp: resp,
      result: result
    });
    return console.log("should get: { err: '401 Unauthorized', resp: undefined, result: undefined }");
  });

}).call(this);
<|endoftext|>