<commit_before>import { Component, PropTypes } from "react";
import { connect } from "react-redux";
import { graphql } from "react-apollo";
import ReactMixin from "react-mixin";
import gql from "graphql-tag";
import { withRouter } from "react-router";

import Split, {
  Left,
  Right,
} from "../../../components/@primitives/layout/split";
import Headerable from "../../../deprecated/mixins/mixins.Header";
import { nav as navActions, modal } from "../../../data/store";

import Layout from "./Layout";
import ErrTemplate from "./ErrTemplate";

const defaultArray = [];

class TemplateWithoutData extends Component {
  static propTypes = {
    dispatch: PropTypes.func.isRequired,
    router: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    attributes: PropTypes.object.isRequired,
    content: PropTypes.object.isRequired,
    campuses: PropTypes.object.isRequired,
    campus: PropTypes.string,
    zip: PropTypes.string,
  };

  state = {
    tags: [],
    query: "",
    latitude: null,
    longitude: null,
    campus: "",
    zip: "",
    submit: false,
    geoLocationLoading: false,
  };

  componentWillMount() {
    this.props.dispatch(navActions.setLevel("TOP"));
    if (this.headerAction) {
      this.headerAction({ title: "Group Finder" });
    }
  }

  componentWillReceiveProps(nextProps: Object) {
    this.props.dispatch(navActions.setLevel("TOP"));

    if (!nextProps.loading) {
      this.setState({
        campus: nextProps.campus,
        zip: nextProps.zip,
        ...nextProps.location.query,
      });
    } else {
      this.setState({
        ...nextProps.location.query,
      });
    }
  }

  componentDidMount() {
    const { router, location } = this.props;
    if (location.query.tags && location.query.tags.length) {
      delete location.query.tags;
      router.push(location);
    }
  }

  geoLocateMe = (e: Event) => {
    if (e) e.preventDefault();

    if (this.state.latitude && this.state.longitude) {
      this.setState({
        latitude: null,
        longitude: null,
        zip: this.props.zip,
        geoLocationLoading: false,
      });
    } else {
      this.setState({
        geoLocationLoading: true,
      });

      navigator.geolocation.getCurrentPosition(
        this.geolocationSuccess,
        this.geolocationError,
      );
    }
  };

  geolocationSuccess = (position: Object) => {
    this.setState({
      latitude: position.coords.latitude,
      longitude: position.coords.longitude,
      zip: "Using your location",
      geoLocationLoading: false,
    });
  };

  geolocationError = error => {
    this.props.dispatch(modal.render(ErrTemplate, { errorCode: error.code }));
    this.setState({
      geoLocationLoading: false,
    });
  };

  getResults = () => {
    const { router, location } = this.props;
    const { latitude, longitude, campus, zip, query } = this.state;
    // create an array of the attributes returned by graphql
    const attributeTags = this.props.attributes.tags.map(tag => tag.value);

    const q = [];

    // split the query up into individual words and check to see which
    // are actual attributes
    const tags = this.state.query
      .split(/[, ]+/)
      .reduce((result, tag, index, original) => {
        const t = tag.toLowerCase();
        if (attributeTags.indexOf(t) > -1) {
          result.push(t);
        } else if (t === "kid" && original[index + 1] === "friendly") {
          result.push("kid friendly");
        } else if (
          t !== "and" &&
          t !== "or" &&
          t !== "the" &&
          t !== "from" &&
          t !== "also" &&
          t !== "friendly" &&
          t !== "with"
        ) {
          q.push(t);
        }
        return result;
      }, []);

    // start building the router querystring
    location.query = {};

    if (q && q.length > 0 && q[0] !== "") {
      location.query.q = q.join(" ").toLowerCase();
    }

    if (tags.length) location.query.tags = tags.join(",").toLowerCase();

    if (location.query.campus) delete location.query.campus;
    if (location.query.schedules) delete location.query.schedules;

    if (query) location.query.query = query;
    if (latitude) location.query.latitude = latitude;
    if (longitude) location.query.longitude = longitude;
    if (campus) location.query.campus = campus;
    if (zip && !latitude && !longitude) location.query.zip = zip;

    // XXX i don't like the idea of having to push history twice
    // but this is the only way to preserve state with a back button
    router.push(location);

    // navigate too
    location.pathname = "/groups/finder";
    router.push(location);
  };

  // function that gets passed in to each field to update state on parent
  // component
  inputOnChange = (value: String, e: any) => {
    this.setState({
      [e.name]: value,
    });
  };

  // for tags only, add tags to state.query
  tagOnClick = (tag: String) => {
    let queryString = this.state.query || "";

    // regex checks queryString for exact word match with optional space (\s) or
    // comma (,?). notice the double backslashes
    const regex = `(,?\\s?\\b${tag.toString()}\\b)`;

    if (queryString.search(new RegExp(regex, "i")) > -1) {
      queryString = queryString.replace(new RegExp(regex, "i"), "");

      if (queryString[0] === ",") {
        queryString = queryString.substring(1);
      }
    } else {
      // if the tag was not found append to the end of querystring with a comma
      // and space
      queryString =
        queryString && queryString.length
          ? `${queryString}, ${tag.toString()}`
          : `${tag.toString()}`;
    }

    this.setState({
      query: queryString.trim(),
    });
  };

  submitTags = (e: Event) => {
    if (e) e.preventDefault();
    this.getResults();
  };

  findByQuery = (e: Event) => {
    if (e) e.preventDefault();
    document.getElementById("search").blur();
    this.getResults();
  };

  /* eslint-disable max-len */
  render() {
    const { attributes, campuses, campus, zip, content } = this.props;

    return (

        <Split>
          <Right
            mobile={false}
            classes={["background--left"]}
            background="//dg0ddngxdz549.cloudfront.net/images/cached/images/remote/http_s3.amazonaws.com/ns.images/newspring/groups/groups.1x1_1700_1700_90_c1.jpg"
          />
        </Split>
        <Left scroll classes={["background--light-secondary"]}>
          <Layout
            canSearchTags={
              false ||
              Boolean(this.state.tags.length) ||
              Boolean(this.state.query)
            }
            canSearchCampus={false || Boolean(this.state.campus)}
            canSearchLocation={
              false ||
              this.state.zip ||
              (this.state.latitude && this.state.longitude)
            }
            campuses={campuses || defaultArray}
            selectedCampus={this.state.campus}
            zip={
              this.state.latitude && this.state.longitude
                ? "Using your location"
                : this.state.zip
            }
            zipDisabled={Boolean(this.state.latitude && this.state.longitude)}
            searchQuery={this.state.query || ""}
            tags={(attributes && attributes.tags) || defaultArray}
            tagOnClick={this.tagOnClick}
            submitTags={this.submitTags}
            findByQuery={this.findByQuery}
            inputOnChange={this.inputOnChange}
            content={content.loading ? defaultArray : content.entries}
            getLocation={this.geoLocateMe}
            geoLocationLoading={this.state.geoLocationLoading}
            iconFill={"#505050"}
          />
        </Left>

    );
  }
  /* eslint-enable max-len */
}

const AUTOFILL_META_QUERY = gql`
  query autoFillMeta {
    person: currentPerson {
      home {
        zip
      }
      campus {
        name
      }
    }
    campuses {
      name
    }
  }
`;

const withAutoFillMeta = graphql(AUTOFILL_META_QUERY, {
  props: ({ data, data: { person, campuses } }) => ({
    ...data,
    zip: person ? person.home.zip : "",
    campus: person ? person.campus.name.toLowerCase() : "",
    campuses: campuses
      ? campuses
          .filter(x => {
            if (x.name === "Web") {
              return false;
            }

            return true;
          })
          .map(x => ({ label: x.name, value: x.name.toLowerCase() }))
      : defaultArray,
  }),
});

const GROUP_ATTRIBUTES_QUERY = gql`
  query GetGroupAttributes {
    tags: groupAttributes {
      id
      description
      value
    }
  }
`;

const withGroupAttributes = graphql(GROUP_ATTRIBUTES_QUERY, {
  name: "attributes",
});

const TAGGED_CONTENT_QUERY = gql`
  query GetTaggedContent(
    $tagName: String!
    $limit: Int
    $includeChannels: [String]
  ) {
    entries: taggedContent(
      tagName: $tagName
      limit: $limit
      includeChannels: $includeChannels
      cache: false
    ) {
      entryId: id
      title
      channelName
      meta {
        date
        summary
        urlTitle
      }
      content {
        images(sizes: ["large"]) {
          fileName
          fileType
          fileLabel
          url
        }
      }
    }
  }
`;

const withTaggedContent = graphql(TAGGED_CONTENT_QUERY, {
  name: "content",
  options: {
    variables: {
      tagName: "community",
      includeChannels: ["articles"],
      limit: 2,
    },
  },
});

const mapStateToProps = state => ({ location: state.routing.location });

export default withRouter(
  connect(mapStateToProps)(
    withGroupAttributes(
      withAutoFillMeta(
        withTaggedContent(ReactMixin.decorate(Headerable)(TemplateWithoutData)),
      ),
    ),
  ),
);

export { TemplateWithoutData };
<commit_msg>updated gql props to account for missing location data<commit_after>import { Component, PropTypes } from "react";
import { connect } from "react-redux";
import { graphql } from "react-apollo";
import ReactMixin from "react-mixin";
import gql from "graphql-tag";
import { withRouter } from "react-router";

import Split, {
  Left,
  Right,
} from "../../../components/@primitives/layout/split";
import Headerable from "../../../deprecated/mixins/mixins.Header";
import { nav as navActions, modal } from "../../../data/store";

import Layout from "./Layout";
import ErrTemplate from "./ErrTemplate";

const defaultArray = [];

class TemplateWithoutData extends Component {
  static propTypes = {
    dispatch: PropTypes.func.isRequired,
    router: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    attributes: PropTypes.object.isRequired,
    content: PropTypes.object.isRequired,
    campuses: PropTypes.object.isRequired,
    campus: PropTypes.string,
    zip: PropTypes.string,
  };

  state = {
    tags: [],
    query: "",
    latitude: null,
    longitude: null,
    campus: "",
    zip: "",
    submit: false,
    geoLocationLoading: false,
  };

  componentWillMount() {
    this.props.dispatch(navActions.setLevel("TOP"));
    if (this.headerAction) {
      this.headerAction({ title: "Group Finder" });
    }
  }

  componentWillReceiveProps(nextProps: Object) {
    this.props.dispatch(navActions.setLevel("TOP"));

    if (!nextProps.loading) {
      this.setState({
        campus: nextProps.campus,
        zip: nextProps.zip,
        ...nextProps.location.query,
      });
    } else {
      this.setState({
        ...nextProps.location.query,
      });
    }
  }

  componentDidMount() {
    const { router, location } = this.props;
    if (location.query.tags && location.query.tags.length) {
      delete location.query.tags;
      router.push(location);
    }
  }

  geoLocateMe = (e: Event) => {
    if (e) e.preventDefault();

    if (this.state.latitude && this.state.longitude) {
      this.setState({
        latitude: null,
        longitude: null,
        zip: this.props.zip,
        geoLocationLoading: false,
      });
    } else {
      this.setState({
        geoLocationLoading: true,
      });

      navigator.geolocation.getCurrentPosition(
        this.geolocationSuccess,
        this.geolocationError,
      );
    }
  };

  geolocationSuccess = (position: Object) => {
    this.setState({
      latitude: position.coords.latitude,
      longitude: position.coords.longitude,
      zip: "Using your location",
      geoLocationLoading: false,
    });
  };

  geolocationError = error => {
    this.props.dispatch(modal.render(ErrTemplate, { errorCode: error.code }));
    this.setState({
      geoLocationLoading: false,
    });
  };

  getResults = () => {
    const { router, location } = this.props;
    const { latitude, longitude, campus, zip, query } = this.state;
    // create an array of the attributes returned by graphql
    const attributeTags = this.props.attributes.tags.map(tag => tag.value);

    const q = [];

    // split the query up into individual words and check to see which
    // are actual attributes
    const tags = this.state.query
      .split(/[, ]+/)
      .reduce((result, tag, index, original) => {
        const t = tag.toLowerCase();
        if (attributeTags.indexOf(t) > -1) {
          result.push(t);
        } else if (t === "kid" && original[index + 1] === "friendly") {
          result.push("kid friendly");
        } else if (
          t !== "and" &&
          t !== "or" &&
          t !== "the" &&
          t !== "from" &&
          t !== "also" &&
          t !== "friendly" &&
          t !== "with"
        ) {
          q.push(t);
        }
        return result;
      }, []);

    // start building the router querystring
    location.query = {};

    if (q && q.length > 0 && q[0] !== "") {
      location.query.q = q.join(" ").toLowerCase();
    }

    if (tags.length) location.query.tags = tags.join(",").toLowerCase();

    if (location.query.campus) delete location.query.campus;
    if (location.query.schedules) delete location.query.schedules;

    if (query) location.query.query = query;
    if (latitude) location.query.latitude = latitude;
    if (longitude) location.query.longitude = longitude;
    if (campus) location.query.campus = campus;
    if (zip && !latitude && !longitude) location.query.zip = zip;

    // XXX i don't like the idea of having to push history twice
    // but this is the only way to preserve state with a back button
    router.push(location);

    // navigate too
    location.pathname = "/groups/finder";
    router.push(location);
  };

  // function that gets passed in to each field to update state on parent
  // component
  inputOnChange = (value: String, e: any) => {
    this.setState({
      [e.name]: value,
    });
  };

  // for tags only, add tags to state.query
  tagOnClick = (tag: String) => {
    let queryString = this.state.query || "";

    // regex checks queryString for exact word match with optional space (\s) or
    // comma (,?). notice the double backslashes
    const regex = `(,?\\s?\\b${tag.toString()}\\b)`;

    if (queryString.search(new RegExp(regex, "i")) > -1) {
      queryString = queryString.replace(new RegExp(regex, "i"), "");

      if (queryString[0] === ",") {
        queryString = queryString.substring(1);
      }
    } else {
      // if the tag was not found append to the end of querystring with a comma
      // and space
      queryString =
        queryString && queryString.length
          ? `${queryString}, ${tag.toString()}`
          : `${tag.toString()}`;
    }

    this.setState({
      query: queryString.trim(),
    });
  };

  submitTags = (e: Event) => {
    if (e) e.preventDefault();
    this.getResults();
  };

  findByQuery = (e: Event) => {
    if (e) e.preventDefault();
    document.getElementById("search").blur();
    this.getResults();
  };

  /* eslint-disable max-len */
  render() {
    const { attributes, campuses, campus, zip, content } = this.props;

    return (

        <Split>
          <Right
            mobile={false}
            classes={["background--left"]}
            background="//dg0ddngxdz549.cloudfront.net/images/cached/images/remote/http_s3.amazonaws.com/ns.images/newspring/groups/groups.1x1_1700_1700_90_c1.jpg"
          />
        </Split>
        <Left scroll classes={["background--light-secondary"]}>
          <Layout
            canSearchTags={
              false ||
              Boolean(this.state.tags.length) ||
              Boolean(this.state.query)
            }
            canSearchCampus={false || Boolean(this.state.campus)}
            canSearchLocation={
              false ||
              this.state.zip ||
              (this.state.latitude && this.state.longitude)
            }
            campuses={campuses || defaultArray}
            selectedCampus={this.state.campus}
            zip={
              this.state.latitude && this.state.longitude
                ? "Using your location"
                : this.state.zip
            }
            zipDisabled={Boolean(this.state.latitude && this.state.longitude)}
            searchQuery={this.state.query || ""}
            tags={(attributes && attributes.tags) || defaultArray}
            tagOnClick={this.tagOnClick}
            submitTags={this.submitTags}
            findByQuery={this.findByQuery}
            inputOnChange={this.inputOnChange}
            content={content.loading ? defaultArray : content.entries}
            getLocation={this.geoLocateMe}
            geoLocationLoading={this.state.geoLocationLoading}
            iconFill={"#505050"}
          />
        </Left>

    );
  }
  /* eslint-enable max-len */
}

const AUTOFILL_META_QUERY = gql`
  query autoFillMeta {
    person: currentPerson {
      home {
        zip
      }
      campus {
        name
      }
    }
    campuses {
      name
    }
  }
`;

const withAutoFillMeta = graphql(AUTOFILL_META_QUERY, {
  props: ({ data, data: { person, campuses } }) => ({
    ...data,
    zip: person && person.home && person.home.zip ? person.home.zip : "",
    campus: person ? person.campus.name.toLowerCase() : "",
    campuses: campuses
      ? campuses
          .filter(x => {
            if (x.name === "Web") {
              return false;
            }

            return true;
          })
          .map(x => ({ label: x.name, value: x.name.toLowerCase() }))
      : defaultArray,
  }),
});

const GROUP_ATTRIBUTES_QUERY = gql`
  query GetGroupAttributes {
    tags: groupAttributes {
      id
      description
      value
    }
  }
`;

const withGroupAttributes = graphql(GROUP_ATTRIBUTES_QUERY, {
  name: "attributes",
});

const TAGGED_CONTENT_QUERY = gql`
  query GetTaggedContent(
    $tagName: String!
    $limit: Int
    $includeChannels: [String]
  ) {
    entries: taggedContent(
      tagName: $tagName
      limit: $limit
      includeChannels: $includeChannels
      cache: false
    ) {
      entryId: id
      title
      channelName
      meta {
        date
        summary
        urlTitle
      }
      content {
        images(sizes: ["large"]) {
          fileName
          fileType
          fileLabel
          url
        }
      }
    }
  }
`;

const withTaggedContent = graphql(TAGGED_CONTENT_QUERY, {
  name: "content",
  options: {
    variables: {
      tagName: "community",
      includeChannels: ["articles"],
      limit: 2,
    },
  },
});

const mapStateToProps = state => ({ location: state.routing.location });

export default withRouter(
  connect(mapStateToProps)(
    withGroupAttributes(
      withAutoFillMeta(
        withTaggedContent(ReactMixin.decorate(Headerable)(TemplateWithoutData)),
      ),
    ),
  ),
);

export { TemplateWithoutData };
<|endoftext|>


<commit_before>import React from 'react'

import { ISSUE_ADDR } from '@config'
import Popover from '@components/Popover'
import DiscussLinker from '@components/DiscussLinker'

import { Wrapper, DotDivider, SiteLink } from './styles/main_entries'

const splitMargin = '8px'
const MainEntries = () => (
  <Wrapper>

      <SiteLink>首页</SiteLink>

    <DotDivider space={splitMargin} />

      <SiteLink>社.区</SiteLink>

    <DotDivider space={splitMargin} />
    <Popover
      placement="bottom"
      trigger="click"
      content={<DiscussLinker title="专栏" addr={`${ISSUE_ADDR}/265`} />}
    >
      <SiteLink>专栏</SiteLink>
    </Popover>
    <DotDivider space={splitMargin} />
    <Popover
      placement="bottom"
      trigger="click"
      content={<DiscussLinker title="团队" addr={`${ISSUE_ADDR}/264`} />}
    >
      <SiteLink>团队</SiteLink>
    </Popover>
  </Wrapper>
)

export default MainEntries
<commit_msg>chore: wip<commit_after>import React from 'react'
import Link from 'next/link'

import { ISSUE_ADDR } from '@config'
import Popover from '@components/Popover'
import DiscussLinker from '@components/DiscussLinker'

import { Wrapper, DotDivider, SiteLink } from './styles/main_entries'

const splitMargin = '8px'
const MainEntries = () => (
  <Wrapper>
    <Link href="/home/posts" prefetch passHref>
      <SiteLink>首页</SiteLink>
    </Link>
    <DotDivider space={splitMargin} />
    <Link href="/communities" prefetch passHref>
      <SiteLink>社区</SiteLink>
    </Link>
    <DotDivider space={splitMargin} />
    <Popover
      placement="bottom"
      trigger="click"
      content={<DiscussLinker title="专栏" addr={`${ISSUE_ADDR}/265`} />}
    >
      <SiteLink>专栏</SiteLink>
    </Popover>
    <DotDivider space={splitMargin} />
    <Popover
      placement="bottom"
      trigger="click"
      content={<DiscussLinker title="团队" addr={`${ISSUE_ADDR}/264`} />}
    >
      <SiteLink>团队</SiteLink>
    </Popover>
  </Wrapper>
)

export default MainEntries
<|endoftext|>


<commit_before>/*
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

// #/:core/analysis
sammy.get
(
  /^#\/([\w\d-]+)\/(analysis)$/,
  function( context )
  {
    var core_basepath = this.active_core.attr( 'data-basepath' );
    var content_element = $( '#content' );

    $.get
    (
      'tpl/analysis.html',
      function( template )
      {
        content_element
          .html( template );

        var analysis_element = $( '#analysis', content_element );
        var analysis_form = $( 'form', analysis_element );
        var analysis_result = $( '#analysis-result', analysis_element );
        analysis_result.hide();

        $.ajax
        (
          {
            url : core_basepath + '/admin/luke?wt=json&show=schema',
            dataType : 'json',
            context : $( '#type_or_name', analysis_form ),
            beforeSend : function( xhr, settings )
            {
              this
                .html( '<option value="">Loading ... </option>' )
                .addClass( 'loader' );
            },
            success : function( response, text_status, xhr )
            {
              var content = '';

              var fields = [];
              for( var field_name in response.schema.fields )
              {
                fields.push
                (
                  '<option value="fieldname=' + field_name + '">' + field_name + '</option>'
                );
              }
              if( 0 !== fields.length )
              {
                content += '<optgroup label="Fields">' + "\n";
                content += fields.sort().join( "\n" ) + "\n";
                content += '</optgroup>' + "\n";
              }

              var types = [];
              for( var type_name in response.schema.types )
              {
                types.push
                (
                  '<option value="fieldtype=' + type_name + '">' + type_name + '</option>'
                );
              }
              if( 0 !== types.length )
              {
                content += '<optgroup label="Types">' + "\n";
                content += types.sort().join( "\n" ) + "\n";
                content += '</optgroup>' + "\n";
              }

              this
                .html( content );

              $( 'option[value="fieldname\=' + response.schema.defaultSearchField + '"]', this )
                .attr( 'selected', 'selected' );
            },
            error : function( xhr, text_status, error_thrown)
            {
            },
            complete : function( xhr, text_status )
            {
              this
                .removeClass( 'loader' );
            }
          }
        );

        $( '.analysis-error .head a', analysis_element )
          .die( 'click' )
          .live
          (
            'click',
            function( event )
            {
              $( this ).parents( '.analysis-error' )
                .toggleClass( 'expanded' );
            }
          );

        $( '.verbose_output a', analysis_element )
          .die( 'click' )
          .live
          (
            'click',
            function( event )
            {
              $( this ).parent()
                .toggleClass( 'active' );

              analysis_result
                .toggleClass( 'verbose_output' );

              check_empty_spacer();
            }
          );

        var check_empty_spacer = function()
        {
          var spacer_holder = $( 'td.part.data.spacer .holder', analysis_result );

          if( 0 === spacer_holder.size() )
          {
            return false;
          }

          var verbose_output = analysis_result.hasClass( 'verbose_output' );

          spacer_holder
            .each
            (
              function( index, element )
              {
                element = $( element );

                if( verbose_output )
                {
                  var cell = element.parent();
                  element.height( cell.height() );
                }
                else
                {
                  element.removeAttr( 'style' );
                }
              }
            );
        }

        var button = $( 'button', analysis_form )

        analysis_form
          .ajaxForm
          (
            {
              url : core_basepath + '/analysis/field?wt=json',
              dataType : 'json',
              beforeSubmit : function( array, form, options )
              {
                loader.show( button );
                button.attr( 'disabled', true );

                array.push( { name: 'analysis.showmatch', value: 'true' } );

                var type_or_name = $( '#type_or_name', form ).val().split( '=' );

                array.push( { name: 'analysis.' + type_or_name[0], value: type_or_name[1] } );
              },
              success : function( response, status_text, xhr, form )
              {
                $( '.analysis-error', analysis_element )
                  .hide();

                analysis_result
                  .empty()
                  .show();

                for( var name in response.analysis.field_names )
                {
                  build_analysis_table( 'name', name, response.analysis.field_names[name] );
                }

                for( var name in response.analysis.field_types )
                {
                  build_analysis_table( 'type', name, response.analysis.field_types[name] );
                }

                check_empty_spacer();
              },
              error : function( xhr, text_status, error_thrown )
              {
                analysis_result
                  .empty()
                  .hide();

                if( 404 === xhr.status )
                {
                  $( '#analysis-handler-missing', analysis_element )
                    .show();
                }
                else
                {
                  var error_message = error_thrown.match( /^(.+Exception):\s+(.*)$/ );

                  $( '#analysis-error', analysis_element )
                    .show();

                  if( error_message )
                  {
                    $( '#analysis-error .head a span', analysis_element )
                      .text( error_message[1] );

                    $( '#analysis-error .body', analysis_element )
                      .text( error_message[2].replace( /(\s+at\s+)/g, " at\n" ) );
                  }
                  else
                  {
                    $( '#analysis-error .head a span', analysis_element )
                      .text( error_thrown );
                  }
                }
              },
              complete : function()
              {
                loader.hide( $( 'button', analysis_form ) );
                button.removeAttr( 'disabled' );
              }
            }
          );

          var generate_class_name = function( type )
          {
            var classes = [type];
            if( 'text' !== type )
            {
              classes.push( 'verbose_output' );
            }
            return classes.join( ' ' );
          }

          var build_analysis_table = function( field_or_name, name, analysis_data )
          {
            for( var type in analysis_data )
            {
              var type_length = analysis_data[type].length;
              if( 0 !== type_length )
              {
                var global_elements_count = 0;
                for( var i = 0; i < analysis_data[type].length; i += 2 )
                {
                  if( 'string' === typeof analysis_data[type][i+1] )
                  {
                    analysis_data[type][i+1] = [{ 'text': analysis_data[type][i+1] }]
                  }
                  global_elements_count = Math.max( global_elements_count, analysis_data[type][i+1].length );
                }

                var content = '
' + "\n";
                content += '
' + "\n";

                for( var i = 0; i < analysis_data[type].length; i += 2 )
                {
                  var colspan = 1;
                  var elements = analysis_data[type][i+1];
                  var elements_count = global_elements_count;

                  if( !elements[0] || !elements[0].positionHistory )
                  {
                    colspan = elements_count;
                    elements_count = 1;
                  }

                  var legend = [];
                  for( var key in elements[0] )
                  {
                    var key_parts = key.split( '#' );
                    var used_key = key_parts.pop();
                    var short_key = used_key;

                    if( 1 === key_parts.length )
                    {
                      used_key = '' + used_key + '';
                    }

                    if( 'positionHistory' === short_key || 'match' === short_key )
                    {
                      continue;
                    }

                    legend.push
                    (
                      '
' +
                      '' + used_key + '	' +
                      '
'
                    );
                  }

                  content += '
' + "\n";
                  content += '
' + "\n";

                    // analyzer
                    var analyzer_name = analysis_data[type][i]
                                                                .replace( /(\$1)+$/g, '' );

                    var analyzer_short = -1 !== analyzer_name.indexOf( '$' )
                                       ? analyzer_name.split( '$' )[1]
                                       : analyzer_name.split( '.' ).pop();
                    analyzer_short = analyzer_short.match( /[A-Z]/g ).join( '' );

                    content += '
' + "\n";
                    content += '' + "\n";
                    content += analyzer_short + '
	' + "\n";

                    // legend
                    content += '
' + "\n";
                    content += '
' + "\n";
                    content += '
' + "\n";
                    content += '
' + "\n";
                    content += legend.join( "\n" ) + "\n";
                    content += '

	' + "\n";

                    // data
                    var cell_content = '

	';
                    var cells = new Array( elements_count + 1 ).join( cell_content );
                    content += cells + "\n";

                  content += '
' + "\n";
                  content += '
' + "\n";
                }
                content += '
' + "\n";
                content += '
' + "\n";

                $( '.' + type, analysis_result )
                  .remove();

                analysis_result
                  .append( content );

                var analysis_result_type = $( '.' + type, analysis_result );

                for( var i = 0; i < analysis_data[type].length; i += 2 )
                {
                  for( var j = 0; j < analysis_data[type][i+1].length; j += 1 )
                  {
                    var pos = analysis_data[type][i+1][j].positionHistory
                        ? analysis_data[type][i+1][j].positionHistory[0]
                        : 1;
                    var selector = 'tr.step:eq(' + ( i / 2 ) +') '
                                 + 'td.data:eq(' + ( pos - 1 ) + ') '
                                 + '.holder';
                    var cell = $( selector, analysis_result_type );

                    cell.parent()
                      .removeClass( 'spacer' );

                    var table = $( 'table tr.details', cell );
                    if( 0 === table.size() )
                    {
                      cell
                        .html
                        (
                          '
' +
                          '

'
                        );
                      var table = $( 'table tr.details', cell );
                    }

                    var tokens = [];
                    for( var key in analysis_data[type][i+1][j] )
                    {
                      var short_key = key.split( '#' ).pop();

                      if( 'positionHistory' === short_key || 'match' === short_key )
                      {
                        continue;
                      }

                      var classes = [];
                      classes.push( generate_class_name( short_key ) );

                      var data = analysis_data[type][i+1][j][key];
                      if( 'object' === typeof data && data instanceof Array )
                      {
                        data = data.join( ' ' );
                      }
                      if( 'string' === typeof data )
                      {
                        data = data.esc();
                      }

                      if( null === data || 0 === data.length )
                      {
                        classes.push( 'empty' );
                        data = '∅';
                      }

                      if( analysis_data[type][i+1][j].match &&
                        ( 'text' === short_key || 'raw_bytes' === short_key ) )
                      {
                        classes.push( 'match' );
                      }

                      tokens.push
                      (
                        '
' +
                        '' + data + '	' +
                        '
'
                      );
                    }
                    table
                      .append
                      (
                        '' +
                        '
' +
                        tokens.join( "\n" ) +
                        '
	'
                      );
                  }
                }

              }
            }
          }

      }
    );
  }
);
<commit_msg>SOLR-3205: Improved Error-Handling on Analysis<commit_after>/*
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

// #/:core/analysis
sammy.get
(
  /^#\/([\w\d-]+)\/(analysis)$/,
  function( context )
  {
    var core_basepath = this.active_core.attr( 'data-basepath' );
    var content_element = $( '#content' );

    $.get
    (
      'tpl/analysis.html',
      function( template )
      {
        content_element
          .html( template );

        var analysis_element = $( '#analysis', content_element );
        var analysis_form = $( 'form', analysis_element );
        var analysis_result = $( '#analysis-result', analysis_element );
        analysis_result.hide();

        $.ajax
        (
          {
            url : core_basepath + '/admin/luke?wt=json&show=schema',
            dataType : 'json',
            context : $( '#type_or_name', analysis_form ),
            beforeSend : function( xhr, settings )
            {
              this
                .html( '<option value="">Loading ... </option>' )
                .addClass( 'loader' );
            },
            success : function( response, text_status, xhr )
            {
              var content = '';

              var fields = [];
              for( var field_name in response.schema.fields )
              {
                fields.push
                (
                  '<option value="fieldname=' + field_name + '">' + field_name + '</option>'
                );
              }
              if( 0 !== fields.length )
              {
                content += '<optgroup label="Fields">' + "\n";
                content += fields.sort().join( "\n" ) + "\n";
                content += '</optgroup>' + "\n";
              }

              var types = [];
              for( var type_name in response.schema.types )
              {
                types.push
                (
                  '<option value="fieldtype=' + type_name + '">' + type_name + '</option>'
                );
              }
              if( 0 !== types.length )
              {
                content += '<optgroup label="Types">' + "\n";
                content += types.sort().join( "\n" ) + "\n";
                content += '</optgroup>' + "\n";
              }

              this
                .html( content );

              $( 'option[value="fieldname\=' + response.schema.defaultSearchField + '"]', this )
                .attr( 'selected', 'selected' );
            },
            error : function( xhr, text_status, error_thrown)
            {
            },
            complete : function( xhr, text_status )
            {
              this
                .removeClass( 'loader' );
            }
          }
        );

        $( '.analysis-error .head a', analysis_element )
          .die( 'click' )
          .live
          (
            'click',
            function( event )
            {
              $( this ).parents( '.analysis-error' )
                .toggleClass( 'expanded' );
            }
          );

        $( '.verbose_output a', analysis_element )
          .die( 'click' )
          .live
          (
            'click',
            function( event )
            {
              $( this ).parent()
                .toggleClass( 'active' );

              analysis_result
                .toggleClass( 'verbose_output' );

              check_empty_spacer();
            }
          );

        var check_empty_spacer = function()
        {
          var spacer_holder = $( 'td.part.data.spacer .holder', analysis_result );

          if( 0 === spacer_holder.size() )
          {
            return false;
          }

          var verbose_output = analysis_result.hasClass( 'verbose_output' );

          spacer_holder
            .each
            (
              function( index, element )
              {
                element = $( element );

                if( verbose_output )
                {
                  var cell = element.parent();
                  element.height( cell.height() );
                }
                else
                {
                  element.removeAttr( 'style' );
                }
              }
            );
        }

        var button = $( 'button', analysis_form )

        analysis_form
          .ajaxForm
          (
            {
              url : core_basepath + '/analysis/field?wt=json',
              dataType : 'json',
              beforeSubmit : function( array, form, options )
              {
                loader.show( button );
                button.attr( 'disabled', true );

                array.push( { name: 'analysis.showmatch', value: 'true' } );

                var type_or_name = $( '#type_or_name', form ).val().split( '=' );
                array.push( { name: 'analysis.' + type_or_name[0], value: type_or_name[1] } );
              },
              success : function( response, status_text, xhr, form )
              {
                $( '.analysis-error', analysis_element )
                  .hide();

                analysis_result
                  .empty()
                  .show();

                for( var name in response.analysis.field_names )
                {
                  build_analysis_table( 'name', name, response.analysis.field_names[name] );
                }

                for( var name in response.analysis.field_types )
                {
                  build_analysis_table( 'type', name, response.analysis.field_types[name] );
                }

                check_empty_spacer();
              },
              error : function( xhr, text_status, error_thrown )
              {
                analysis_result
                  .empty()
                  .hide();

                if( 404 === xhr.status )
                {
                  $( '#analysis-handler-missing', analysis_element )
                    .show();
                }
                else
                {
                  $( '#analysis-error', analysis_element )
                    .show();

                  var response = null;
                  try
                  {
                    eval( 'response = ' + xhr.responseText + ';' );
                  }
                  catch( e )
                  {
                    console.error( e );
                  }

                  $( '#analysis-error .body', analysis_element )
                    .text( response ? response.error.msg : xhr.responseText );
                }
              },
              complete : function()
              {
                loader.hide( $( 'button', analysis_form ) );
                button.removeAttr( 'disabled' );
              }
            }
          );

          var generate_class_name = function( type )
          {
            var classes = [type];
            if( 'text' !== type )
            {
              classes.push( 'verbose_output' );
            }
            return classes.join( ' ' );
          }

          var build_analysis_table = function( field_or_name, name, analysis_data )
          {
            for( var type in analysis_data )
            {
              var type_length = analysis_data[type].length;
              if( 0 !== type_length )
              {
                var global_elements_count = 0;
                for( var i = 0; i < analysis_data[type].length; i += 2 )
                {
                  if( 'string' === typeof analysis_data[type][i+1] )
                  {
                    analysis_data[type][i+1] = [{ 'text': analysis_data[type][i+1] }]
                  }
                  global_elements_count = Math.max( global_elements_count, analysis_data[type][i+1].length );
                }

                var content = '
' + "\n";
                content += '
' + "\n";

                for( var i = 0; i < analysis_data[type].length; i += 2 )
                {
                  var colspan = 1;
                  var elements = analysis_data[type][i+1];
                  var elements_count = global_elements_count;

                  if( !elements[0] || !elements[0].positionHistory )
                  {
                    colspan = elements_count;
                    elements_count = 1;
                  }

                  var legend = [];
                  for( var key in elements[0] )
                  {
                    var key_parts = key.split( '#' );
                    var used_key = key_parts.pop();
                    var short_key = used_key;

                    if( 1 === key_parts.length )
                    {
                      used_key = '' + used_key + '';
                    }

                    if( 'positionHistory' === short_key || 'match' === short_key )
                    {
                      continue;
                    }

                    legend.push
                    (
                      '
' +
                      '' + used_key + '	' +
                      '
'
                    );
                  }

                  content += '
' + "\n";
                  content += '
' + "\n";

                    // analyzer
                    var analyzer_name = analysis_data[type][i].replace( /(\$1)+$/g, '' );

                    var analyzer_short = -1 !== analyzer_name.indexOf( '$' )
                                       ? analyzer_name.split( '$' )[1]
                                       : analyzer_name.split( '.' ).pop();
                    analyzer_short = analyzer_short.match( /[A-Z]/g ).join( '' );

                    content += '
' + "\n";
                    content += '' + "\n";
                    content += analyzer_short.esc() + '
	' + "\n";

                    // legend
                    content += '
' + "\n";
                    content += '
' + "\n";
                    content += '
' + "\n";
                    content += '
' + "\n";
                    content += legend.join( "\n" ) + "\n";
                    content += '

	' + "\n";

                    // data
                    var cell_content = '

	';
                    var cells = new Array( elements_count + 1 ).join( cell_content );
                    content += cells + "\n";

                  content += '
' + "\n";
                  content += '
' + "\n";
                }
                content += '
' + "\n";
                content += '
' + "\n";

                $( '.' + type, analysis_result )
                  .remove();

                analysis_result
                  .append( content );

                var analysis_result_type = $( '.' + type, analysis_result );

                for( var i = 0; i < analysis_data[type].length; i += 2 )
                {
                  for( var j = 0; j < analysis_data[type][i+1].length; j += 1 )
                  {
                    var pos = analysis_data[type][i+1][j].positionHistory
                        ? analysis_data[type][i+1][j].positionHistory[0]
                        : 1;
                    var selector = 'tr.step:eq(' + ( i / 2 ) +') '
                                 + 'td.data:eq(' + ( pos - 1 ) + ') '
                                 + '.holder';
                    var cell = $( selector, analysis_result_type );

                    cell.parent()
                      .removeClass( 'spacer' );

                    var table = $( 'table tr.details', cell );
                    if( 0 === table.size() )
                    {
                      cell
                        .html
                        (
                          '
' +
                          '

'
                        );
                      var table = $( 'table tr.details', cell );
                    }

                    var tokens = [];
                    for( var key in analysis_data[type][i+1][j] )
                    {
                      var short_key = key.split( '#' ).pop();

                      if( 'positionHistory' === short_key || 'match' === short_key )
                      {
                        continue;
                      }

                      var classes = [];
                      classes.push( generate_class_name( short_key ) );

                      var data = analysis_data[type][i+1][j][key];
                      if( 'object' === typeof data && data instanceof Array )
                      {
                        data = data.join( ' ' );
                      }
                      if( 'string' === typeof data )
                      {
                        data = data.esc();
                      }

                      if( null === data || 0 === data.length )
                      {
                        classes.push( 'empty' );
                        data = '∅';
                      }

                      if( analysis_data[type][i+1][j].match &&
                        ( 'text' === short_key || 'raw_bytes' === short_key ) )
                      {
                        classes.push( 'match' );
                      }

                      tokens.push
                      (
                        '
' +
                        '' + data + '	' +
                        '
'
                      );
                    }
                    table
                      .append
                      (
                        '' +
                        '
' +
                        tokens.join( "\n" ) +
                        '
	'
                      );
                  }
                }

              }
            }
          }

      }
    );
  }
);
<|endoftext|>


<commit_before>/**
 * TimeShift on local storage.
 */

(function(){

    _debug('typeof(timeShift)', typeof(timeShift));

    if (typeof(timeShift) === "undefined"){
        return;
    }

    module.time_shift_local = {

        enabled : false,
        channel : {},

        init : function(){
            _debug('time_shift_local.init');

            this.enabled = false;

            _debug('stb.profile.ts_enabled', stb.profile.ts_enabled);
            _debug('stb.profile.ts_enable_icon', stb.profile.ts_enable_icon);
            _debug('stb.profile.ts_path', stb.profile.ts_path);
            _debug('stb.profile.ts_max_length', stb.profile.ts_max_length);
            _debug('stb.profile.ts_buffer_use', stb.profile.ts_buffer_use);
            _debug('stb.profile.ts_action_on_exit', stb.profile.ts_action_on_exit);
            _debug('stb.profile.ts_delay', stb.profile.ts_delay);

            if (!stb.profile.ts_enabled){
                return;
            }

            if (!stb.profile.ts_path){
                return;
            }

            if (!stb.usbdisk.is_valid_path_for_write(stb.profile.ts_path)){
                return;
            }

            this.enabled = true;

            _debug('time_shift_local.enabled', this.enabled);

            var save_path = stb.profile.ts_path + '/records';

            stb.ExecAction(Utf8.encode('make_dir ' + save_path));

            timeShift.SetTimeShiftFolder(save_path);
            timeShift.SetMaxDuration(stb.profile.ts_max_length);
            timeShift.SetSlidingMode(stb.profile.ts_buffer_use === 'cyclic');
        },

        enable_mode : function(){
            _debug('time_shift_local.enable_mode');

            this.channel = stb.player.cur_media_item;

            var result = timeShift.EnterTimeShift();

            _debug('result', result);

            return !result;
        },

        disable_mode : function(){
            _debug('time_shift_local.disable_mode');

            if (stb.profile.ts_action_on_exit === "no_save"){
                var result = timeShift.ExitTimeShift();
            }else if (stb.profile.ts_action_on_exit === "save"){

                var now = new Date();

                var file_path = stb.profile.ts_path
                    + '/' + this.channel.toTranslit() + '/'
                    + now.getFullYear()
                    + '' + this.format_date(now.getMonth() + 1)
                    + '' + this.format_date(now.getDate())
                    + '-' + this.format_date(now.getHours())
                    + '' + this.format_date(now.getMinutes())
                    + '' + this.format_date(now.getSeconds());

                result = timeShift.ExitTimeShiftAndSave(file_path);
            }

            _debug('result', result);

            return !result;
        },

        format_date : function(param){
            if (param<10){
                return '0'+param
            }
            return param
        }
    };

    module.time_shift_local.init();

    stb.usbdisk.add_onmount_callback(function(){
        module.time_shift_local.init();
    });

    stb.usbdisk.add_onumount_callback(function(){
        module.time_shift_local.init();
    });

})();

loader.next();<commit_msg>Fixed local time-shift settings (issue #2731)<commit_after>/**
 * TimeShift on local storage.
 */

(function(){

    _debug('typeof(timeShift)', typeof(timeShift));

    if (typeof(timeShift) === "undefined"){
        return;
    }

    module.time_shift_local = {

        enabled : false,
        channel : {},

        init : function(){
            _debug('time_shift_local.init');

            this.enabled = false;

            _debug('stb.profile.ts_enabled', stb.profile.ts_enabled);
            _debug('stb.profile.ts_enable_icon', stb.profile.ts_enable_icon);
            _debug('stb.profile.ts_path', stb.profile.ts_path);
            _debug('stb.profile.ts_max_length', stb.profile.ts_max_length);
            _debug('stb.profile.ts_buffer_use', stb.profile.ts_buffer_use);
            _debug('stb.profile.ts_action_on_exit', stb.profile.ts_action_on_exit);
            _debug('stb.profile.ts_delay', stb.profile.ts_delay);

            if (parseInt(stb.profile.ts_enabled, 10) != 1){
                return;
            }

            if (!stb.profile.ts_path){
                return;
            }

            if (!stb.usbdisk.is_valid_path_for_write(stb.profile.ts_path)){
                _debug('path not valid');
                return;
            }

            this.enabled = true;

            _debug('time_shift_local.enabled', this.enabled);

            var save_path = stb.profile.ts_path + '/records';

            stb.ExecAction(Utf8.encode('make_dir ' + save_path));

            timeShift.SetTimeShiftFolder(save_path);
            timeShift.SetMaxDuration(stb.profile.ts_max_length);
            timeShift.SetSlidingMode(stb.profile.ts_buffer_use === 'cyclic');
        },

        enable_mode : function(){
            _debug('time_shift_local.enable_mode');

            this.channel = stb.player.cur_media_item;

            var result = timeShift.EnterTimeShift();

            _debug('result', result);

            return !result;
        },

        disable_mode : function(){
            _debug('time_shift_local.disable_mode');

            if (stb.profile.ts_action_on_exit === "no_save"){
                var result = timeShift.ExitTimeShift();
            }else if (stb.profile.ts_action_on_exit === "save"){

                var now = new Date();

                var file_path = stb.profile.ts_path
                    + '/' + this.channel.toTranslit() + '/'
                    + now.getFullYear()
                    + '' + this.format_date(now.getMonth() + 1)
                    + '' + this.format_date(now.getDate())
                    + '-' + this.format_date(now.getHours())
                    + '' + this.format_date(now.getMinutes())
                    + '' + this.format_date(now.getSeconds());

                result = timeShift.ExitTimeShiftAndSave(file_path);
            }

            _debug('result', result);

            return !result;
        },

        format_date : function(param){
            if (param<10){
                return '0'+param
            }
            return param
        }
    };

    module.time_shift_local.init();

    stb.usbdisk.add_onmount_callback(function(){
        module.time_shift_local.init();
    });

    stb.usbdisk.add_onumount_callback(function(){
        module.time_shift_local.init();
    });

})();

loader.next();<|endoftext|>


<commit_before>var expect = require('expect.js');
var mongoose = require('mongoose');
var cnx;
var sut = require('../../app/services/mongodbStorage.js');
var fs = require('fs');

function init(done) {
	var dbServer = (process.env.DB_SERVER) ? process.env.DB_SERVER : "localhost:27017";
	var dbCnx = "mongodb://" + dbServer + "/eventBackend_BinaryTest";
	mongoose.createConnection(dbCnx);
	cnx = mongoose.connect(dbCnx, {}, function(db) {
		sut.apply(cnx);
		done();
	});
}

describe('mongodb binary storage', function() {
	this.timeout(5000);
	before(init);

	it('store & delete', function(done) {
		sut.uploadFile('manifest.yml', 'key01', 'text/yaml', 'a.yml', function(err, data) {
			if (err) {
				return done(err);
			}
			expect(err).to.be(null);
			expect(data._id).not.to.be(null);
			expect(data.contentType).to.be('binary/octet-stream');
			expect(data.length > 0).to.be(true);
			expect(data).to.have.property('md5');
			expect(data.filename).to.be('key01');

			sut.deleteFile('key01', function (err, data) {
				if (err) {
					return done(err);
				}

				return done();
			});
		});
	});

	it('find', function(done) {
		sut.uploadFile('manifest.yml', 'key02', 'text/yaml', 'a.yml', function(err, data) {
			if (err) {
				return done(err);
			}
			expect(err).to.be(null);
			expect(data._id).not.to.be(null);
			expect(data.filename).to.be('key02');

			sut.downloadFile('key02', 'ab.yml', function (err, filename1) {
				if (err) {
					return done(err);
				}
				expect(filename1).to.be('ab.yml');

				fs.unlinkSync('ab.yml'); //delete file

				sut.deleteFile('key02', function (err, data) {
					if (err) {
						return done(err);
					}
					return done();
				});
			});

		});
	});

});<commit_msg>disable eslint warning<commit_after>var expect = require('expect.js');
var mongoose = require('mongoose');
var cnx; // eslint-disable-line no-unused-vars
var sut = require('../../app/services/mongodbStorage.js');
var fs = require('fs');

function init(done) {
	var dbServer = (process.env.DB_SERVER) ? process.env.DB_SERVER : "localhost:27017";
	var dbCnx = "mongodb://" + dbServer + "/eventBackend_BinaryTest";
	mongoose.createConnection(dbCnx);
	cnx = mongoose.connect(dbCnx, {}, function(db) {
		sut.apply(cnx);
		done();
	});
}

describe('mongodb binary storage', function() {
	this.timeout(5000);
	before(init);

	it('store & delete', function(done) {
		sut.uploadFile('manifest.yml', 'key01', 'text/yaml', 'a.yml', function(err, data) {
			if (err) {
				return done(err);
			}
			expect(err).to.be(null);
			expect(data._id).not.to.be(null);
			expect(data.contentType).to.be('binary/octet-stream');
			expect(data.length > 0).to.be(true);
			expect(data).to.have.property('md5');
			expect(data.filename).to.be('key01');

			sut.deleteFile('key01', function (err, data) {
				if (err) {
					return done(err);
				}

				return done();
			});
		});
	});

	it('find', function(done) {
		sut.uploadFile('manifest.yml', 'key02', 'text/yaml', 'a.yml', function(err, data) {
			if (err) {
				return done(err);
			}
			expect(err).to.be(null);
			expect(data._id).not.to.be(null);
			expect(data.filename).to.be('key02');

			sut.downloadFile('key02', 'ab.yml', function (err, filename1) {
				if (err) {
					return done(err);
				}
				expect(filename1).to.be('ab.yml');

				fs.unlinkSync('ab.yml'); //delete file

				sut.deleteFile('key02', function (err, data) {
					if (err) {
						return done(err);
					}
					return done();
				});
			});

		});
	});

});<|endoftext|>


<commit_before>var listeningTabIds = {};
var port = null; // This is the port used to communicate to the native host

function changeToActiveIcon(tabId) {
    if (typeof tabId === "undefined") {
        // If programmer forgot to pass the tabId, return early.
        console.warn('Must pass a tabId to changeToActiveIcon');
        return;
    }

    chrome.browserAction.setIcon({
        path: {
            19: 'vim-logo-pink-shadow-19.png',
            38: 'vim-logo-pink-shadow-38.png'
        },
        tabId: tabId
    });
}

function changeToInactiveIcon(tabId) {
    if (typeof tabId === "undefined") {
        // If programmer forgot to pass the tabId, return early.
        console.warn('Must pass a tabId to changeToInactiveIcon');
        return;
    }

    chrome.browserAction.setIcon({
        path: {
            19: 'vim-logo-green-shadow-19.png',
            38: 'vim-logo-green-shadow-38.png'
        },
        tabId: tabId
    });
}

function stopListening(tabId) {
    delete listeningTabIds[tabId];
    changeToInactiveIcon(tabId);
    console.log('Will stop automatically reloading tab', tabId);
}

function startListening(tabId) {
    listeningTabIds[tabId] = tabId;
    changeToActiveIcon(tabId);
    console.log('Will start reloading tab', tabId, 'on relevant Vim events.');
}

chrome.browserAction.onClicked.addListener(function(tab) {
    if (listeningTabIds[tab.id]) {
        stopListening(tab.id);
    } else {
        startListening(tab.id);
    }
});

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    // This gets fired twice, first where changeInfo.status is "loading" and
    // the second when changeInfo.status is "complete". We only need to
    // react to the first.
    if (changeInfo.status === 'loading' && listeningTabIds[tabId]) {
        console.log('user refreshed a listened-for tab');
        changeToActiveIcon(tabId);
    }
});

// Native Messaging
function sendNativeMessage(message) {
    port.postMessage(message);
}

function onNativeMessage(eventName) {
    console.log('Event page got native message from host:', eventName);
    switch (eventName) {
        case 'BufWritePost':
            Object.keys(listeningTabIds).forEach(function(tabId) {
                tabId = parseInt(tabId);
                console.log('Found listening tab id', tabId);
                chrome.tabs.reload(tabId, null, function() {
                    console.log('Reloading tab id', tabId);
                    // Check if we're listening to this tab, and change the
                    // icon if so. We probably are still listening, but
                    // currently manual user refreshes aren't handled.
                    if (listeningTabIds[tabId]) {
                        console.log('tab has reloaded; changing icon');
                        changeToActiveIcon(tabId);
                    }
                });
            });
            break;
        default:
            sendNativeMessage('Event name', eventName, 'is unknown. Doing nothing.');
            break;
    }
}

function onDisconnected() {
    console.error('Failed to connect. ' + chrome.runtime.lastError.message);
}

function connect() {
    var hostName = "org.vim.stayfresh";
    port = chrome.runtime.connectNative(hostName);
    port.onMessage.addListener(onNativeMessage);
    port.onDisconnect.addListener(onDisconnected);
    console.log("Event page connecting to native messaging host ", hostName);
}

connect();
<commit_msg>Stop listening when user visits new URL same tab.<commit_after>var listeningTabIds = {};
var port = null; // This is the port used to communicate to the native host

function changeToActiveIcon(tabId) {
    if (typeof tabId === "undefined") {
        // If programmer forgot to pass the tabId, return early.
        console.warn('Must pass a tabId to changeToActiveIcon');
        return;
    }

    chrome.browserAction.setIcon({
        path: {
            19: 'vim-logo-pink-shadow-19.png',
            38: 'vim-logo-pink-shadow-38.png'
        },
        tabId: tabId
    });
}

function changeToInactiveIcon(tabId) {
    if (typeof tabId === "undefined") {
        // If programmer forgot to pass the tabId, return early.
        console.warn('Must pass a tabId to changeToInactiveIcon');
        return;
    }

    chrome.browserAction.setIcon({
        path: {
            19: 'vim-logo-green-shadow-19.png',
            38: 'vim-logo-green-shadow-38.png'
        },
        tabId: tabId
    });
}

function stopListening(tabId) {
    delete listeningTabIds[tabId];
    changeToInactiveIcon(tabId);
    console.log('Will stop automatically reloading tab', tabId);
}

function startListening(tabId) {
    listeningTabIds[tabId] = tabId;
    changeToActiveIcon(tabId);
    console.log('Will start reloading tab', tabId, 'on relevant Vim events.');
}

chrome.browserAction.onClicked.addListener(function(tab) {
    if (listeningTabIds[tab.id]) {
        stopListening(tab.id);
    } else {
        startListening(tab.id);
    }
});

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    // This gets fired twice, first where changeInfo.status is "loading" and
    // the second when changeInfo.status is "complete". We only need to
    // react to the first.
    if (changeInfo.url) {
        // In this case, the user went to a new URL in the same tab. We
        // should stop listening.
        stopListening(tabId);
    } else if (changeInfo.status === 'loading' && listeningTabIds[tabId]) {
        console.log('user refreshed a listened-for tab');
        startListening(tabId);
    }
});

// Native Messaging
function sendNativeMessage(message) {
    port.postMessage(message);
}

function onNativeMessage(eventName) {
    console.log('Event page got native message from host:', eventName);
    switch (eventName) {
        case 'BufWritePost':
            Object.keys(listeningTabIds).forEach(function(tabId) {
                tabId = parseInt(tabId);
                console.log('Found listening tab id', tabId);
                chrome.tabs.reload(tabId, null, function() {
                    console.log('Reloading tab id', tabId);
                    // Check if we're listening to this tab, and change the
                    // icon if so. We probably are still listening, but
                    // currently manual user refreshes aren't handled.
                    if (listeningTabIds[tabId]) {
                        startListening(tabId);
                    }
                });
            });
            break;
        default:
            sendNativeMessage('Event name', eventName, 'is unknown. Doing nothing.');
            break;
    }
}

function onDisconnected() {
    console.error('Failed to connect. ' + chrome.runtime.lastError.message);
}

function connect() {
    var hostName = "org.vim.stayfresh";
    port = chrome.runtime.connectNative(hostName);
    port.onMessage.addListener(onNativeMessage);
    port.onDisconnect.addListener(onDisconnected);
    console.log("Event page connecting to native messaging host ", hostName);
}

connect();
<|endoftext|>


<commit_before>//Require Module
var log4js = require('log4js');
var logger = log4js.getLogger('Logging');
var moment = require('moment-timezone');
var fs = require('fs');

/**
 * Check time format "hh:mm"
 * @param{String} time
 * @return{Boolean} true
 * */

function checkTimeFormat(time){

    //If the time format is wrong, throw error.

    var checking = time.match(/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/);

    if(!checking){

        return false;
    }

    return true;
}

/**
 * Convert time to ms
 * @param{String} time
 * @return{Number} totalMs
 */

function getTimeMs(time){

    //Call checkTimeFormat to make sure the format is right.

    var format = checkTimeFormat(time);

    if(format == true){

    //Split the time and convert it to ms

    var splitedTime = time.split(':');

    var hour = splitedTime[0];

    var minute = splitedTime[1];

    var hourMs = hour * 60 * 60 * 1000;

    var minMs = minute * 60 *1000;

    var totalMs = hourMs + minMs;

    return totalMs;

    }

    return;
}

/**
 * Get the date of today with init time (00:00:00)
 * @param{string} timeZone
 * @return {Object(Date)} newCurrentDate
 */

function getInitTime(timeZone){

    if(timeZone == '' || timeZone == null){

        //Get the date of today, and set the time to 00:00:00

        var currentDate = new Date();

        currentDate.setHours(0);
        currentDate.setMinutes(0);
        currentDate.setSeconds(0);
        currentDate.setMilliseconds(0);

        return currentDate;

    }

    //If user setted timezone, using moment to convert the date with timezone

    var currentDate = new Date();

    var currentDateTz = new moment.tz(new Date(),timeZone);

    //Make sure the month and date of converted date is same of currentDate
    //After that, set it to 00:00:00

    currentDateTz.month(currentDate.getMonth());
    currentDateTz.date(currentDate.getDate());
    currentDateTz.hours(0);
    currentDateTz.minutes(0);
    currentDateTz.seconds(0);
    currentDateTz.milliseconds(0);

    //Get the ms and convert it to date object.

    var currentDateMs = currentDateTz.valueOf();

    var newCurrentDate = new Date(currentDateMs)

    return newCurrentDate;
}

/**
 * Check the success time is match keepAliveTime and lastAliveTime.
 * It will return the date which convent from totalKeepAliveTimeMs,
 * it mean the script can send alive mail. Otherwise if it return null,
 * it should not send any mail.
 *
 * @param {Array} keepAliveTimes
 * @param {Number['Timestamp']} lastAliveTime
 * @param {Number['Timestamp'} lastSuccessTime
 * @param {String} timeZone
 * @return {Object(Date)} new Date(totalKeepAliveTimeMs1)
 */

function checkKeepAliveTime(keepAliveTimes,lastAliveTime,lastSuccessTime,timeZone){

    //Get a initDate by calling the getInitTime function

    var currentDateInited = getInitTime(timeZone).getTime();

    //Convert lastSuccessTime,lastAliveTime(If it is not null) and keepAliveTime to ms.

    for(var i =0; i < keepAliveTimes.length; i++){
        var lastSuccessTimeMs = lastSuccessTime.getTime();
        var lastAliveTimeMs = null;

        try{
            lastAliveTimeMs = lastAliveTime.getTime();
        }catch(err){}
        var keepAliveTimeMs1 = keepAliveTimes[i];
        var keepAliveTimeMs2 = keepAliveTimes[i+1];

        //Convert the KeepAliveTime to be a timestamp of current Date.

        var totalKeepAliveTimeMs1 = keepAliveTimeMs1 + currentDateInited;
        var totalKeepAliveTimeMs2 = keepAliveTimeMs2 + currentDateInited;

        logger.debug('keepAliveTimes: ', new Date(totalKeepAliveTimeMs1));
        logger.debug('lastSuccessTime: ', new Date(lastSuccessTimeMs));

        /*If the keepAliveTimeMs2 is NaN,
         *lastSuccessTimeMs is bigger than totalKeepAliveTimeMs1,
         *return a date object of totalKeepAliveTime.
         */

        if(isNaN(keepAliveTimeMs2) && lastSuccessTimeMs >= totalKeepAliveTimeMs1){

            if(lastAliveTime == null){

                return new Date(totalKeepAliveTimeMs1);
            }

            /*If the keepAliveTimeMs2 is NaN,
            *lastSuccessTimeMs is bigger than totalKeepAliveTimeMs1,
            *but lastAliveTimeMs is bigger than totalKeepAliveTimeMs1,
            *it will return undefined.
            */

            if(lastAliveTimeMs >= totalKeepAliveTimeMs1){

                return null;

            }

            return new Date(totalKeepAliveTimeMs1);
        }

        /*If the keepAliveTimeMs2 is not NaN,
         *lastSuccessTimeMs is bigger than totalKeepAliveTimeMs1
         *and smaller than totalKeepAliveTimeMs2,
         *it will return a date object of totalKeepAliveTime.
         */

        if(lastSuccessTimeMs >= totalKeepAliveTimeMs1 && lastSuccessTimeMs < totalKeepAliveTimeMs2){
            if(lastAliveTime == null){

                return new Date(totalKeepAliveTimeMs1);

            }

            /*If the keepAliveTimeMs2 is not NaN,
             *lastSuccessTimeMs is bigger than totalKeepAliveTimeMs1,
             *but lastAliveTimeMs is bigger than totalKeepAliveTimeMs1,
             *it will be skip.
             */

            if(lastAliveTimeMs >= totalKeepAliveTimeMs1){

                continue;
            }

            return new Date(totalKeepAliveTimeMs1);
        }
    }
}

module.exports = {
    checkTimeFormat:checkTimeFormat,
    getTimeMs:getTimeMs,
    getInitTime:getInitTime,
    checkKeepAliveTime:checkKeepAliveTime
}
<commit_msg>improve format<commit_after>//Require Module
var log4js = require('log4js');
var logger = log4js.getLogger('Logging');
var moment = require('moment-timezone');
var fs = require('fs');

/**
 * Check time format "hh:mm"
 * @param{String} time
 * @return{Boolean} true
 * */

function checkTimeFormat(time){

    //If the time format is wrong, throw error.

    var checking = time.match(/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/);

    if(!checking){

        return false;
    }

    return true;
}

/**
 * Convert time to ms
 * @param{String} time
 * @return{Number} totalMs
 */

function getTimeMs(time){

    //Call checkTimeFormat to make sure the format is right.

    var format = checkTimeFormat(time);

    if(format == true){

    //Split the time and convert it to ms

    var splitedTime = time.split(':');

    var hour = splitedTime[0];

    var minute = splitedTime[1];

    var hourMs = hour * 60 * 60 * 1000;

    var minMs = minute * 60 *1000;

    var totalMs = hourMs + minMs;

    return totalMs;

    }

    return;
}

/**
 * Get the date of today with init time (00:00:00)
 * @param{string} timeZone
 * @return {Object(Date)} newCurrentDate
 */

function getInitTime(timeZone){

    if(timeZone == '' || timeZone == null){

        //Get the date of today, and set the time to 00:00:00

        var currentDate = new Date();

        currentDate.setHours(0);
        currentDate.setMinutes(0);
        currentDate.setSeconds(0);
        currentDate.setMilliseconds(0);

        return currentDate;

    }

    //If user setted timezone, using moment to convert the date with timezone

    var currentDate = new Date();

    var currentDateTz = new moment.tz(new Date(),timeZone);

    //Make sure the month and date of converted date is same of currentDate
    //After that, set it to 00:00:00

    currentDateTz.month(currentDate.getMonth());
    currentDateTz.date(currentDate.getDate());
    currentDateTz.hours(0);
    currentDateTz.minutes(0);
    currentDateTz.seconds(0);
    currentDateTz.milliseconds(0);

    //Get the ms and convert it to date object.

    var currentDateMs = currentDateTz.valueOf();

    var newCurrentDate = new Date(currentDateMs)

    return newCurrentDate;
}

/**
 * Check the success time is match keepAliveTime and lastAliveTime.
 * It will return the date which convent from totalKeepAliveTimeMs,
 * it mean the script can send alive mail. Otherwise if it return null,
 * it should not send any mail.
 *
 * @param {Number[]} keepAliveTimes (Timestamp, in ms)
 * @param {Number} lastAliveTime (Timestamp, in ms)
 * @param {Number} lastSuccessTime (Timestamp, in ms)
 * @param {String} timeZone
 * @return {Date} Date, null for mismatch
 */

function checkKeepAliveTime(keepAliveTimes,lastAliveTime,lastSuccessTime,timeZone){

    //Get a initDate by calling the getInitTime function

    var currentDateInited = getInitTime(timeZone).getTime();

    //Convert lastSuccessTime,lastAliveTime(If it is not null) and keepAliveTime to ms.

    for(var i =0; i < keepAliveTimes.length; i++){
        var lastSuccessTimeMs = lastSuccessTime.getTime();
        var lastAliveTimeMs = null;

        try{
            lastAliveTimeMs = lastAliveTime.getTime();
        }catch(err){}
        var keepAliveTimeMs1 = keepAliveTimes[i];
        var keepAliveTimeMs2 = keepAliveTimes[i+1];

        //Convert the KeepAliveTime to be a timestamp of current Date.

        var totalKeepAliveTimeMs1 = keepAliveTimeMs1 + currentDateInited;
        var totalKeepAliveTimeMs2 = keepAliveTimeMs2 + currentDateInited;

        logger.debug('keepAliveTimes: ', new Date(totalKeepAliveTimeMs1));
        logger.debug('lastSuccessTime: ', new Date(lastSuccessTimeMs));

        /*If the keepAliveTimeMs2 is NaN,
         *lastSuccessTimeMs is bigger than totalKeepAliveTimeMs1,
         *return a date object of totalKeepAliveTime.
         */

        if(isNaN(keepAliveTimeMs2) && lastSuccessTimeMs >= totalKeepAliveTimeMs1){

            if(lastAliveTime == null){

                return new Date(totalKeepAliveTimeMs1);
            }

            /*If the keepAliveTimeMs2 is NaN,
            *lastSuccessTimeMs is bigger than totalKeepAliveTimeMs1,
            *but lastAliveTimeMs is bigger than totalKeepAliveTimeMs1,
            *it will return undefined.
            */

            if(lastAliveTimeMs >= totalKeepAliveTimeMs1){

                return null;

            }

            return new Date(totalKeepAliveTimeMs1);
        }

        /*If the keepAliveTimeMs2 is not NaN,
         *lastSuccessTimeMs is bigger than totalKeepAliveTimeMs1
         *and smaller than totalKeepAliveTimeMs2,
         *it will return a date object of totalKeepAliveTime.
         */

        if(lastSuccessTimeMs >= totalKeepAliveTimeMs1 && lastSuccessTimeMs < totalKeepAliveTimeMs2){
            if(lastAliveTime == null){

                return new Date(totalKeepAliveTimeMs1);

            }

            /*If the keepAliveTimeMs2 is not NaN,
             *lastSuccessTimeMs is bigger than totalKeepAliveTimeMs1,
             *but lastAliveTimeMs is bigger than totalKeepAliveTimeMs1,
             *it will be skip.
             */

            if(lastAliveTimeMs >= totalKeepAliveTimeMs1){

                continue;
            }

            return new Date(totalKeepAliveTimeMs1);
        }
    }
}

module.exports = {
    checkTimeFormat:checkTimeFormat,
    getTimeMs:getTimeMs,
    getInitTime:getInitTime,
    checkKeepAliveTime:checkKeepAliveTime
}
<|endoftext|>


<commit_before>var ApplicationController = (function () {

    // Instance stores a reference to the Singleton
    var instance;

    function init() {

        var onlineUserCounterId = 1;

        // create a new data store instance
        var dataStore = DataStore.getInstance();

        // create and assign callback for the online user counter
        var callback_ToFP4tA9ZdRg = function (counter) {
            notifyFrontEndAboutOnlineUserCounter(counter.getCount());
        }
        dataStore.subscribeToNewCounter(callback_ToFP4tA9ZdRg, onlineUserCounterId);

        // create and assign a callback for new cells
        var callback_QyRg1nwivb0n = function (cells) {
            notifyFronEndAboutNewCells(cells);
        }
        dataStore.subscribeToNewRegister(callback_QyRg1nwivb0n);

        //Send a message to the front end to update the online user counter
        function notifyFrontEndAboutOnlineUserCounter(count) {
            var msg = MessagePassing.MessageToFront(MessagePassing.MessageTypes.USER_COUNT_UPDATED, count);
            BackEndMessaging.sendMessage(msg);
        }

        //Send a message to the front end to update a set of cells
        function notifyFronEndAboutNewCells(cells) {

            var arrayOfCells = [];
            if (!(cells instanceof Array)){
                for(var key in cells) {
                    arrayOfCells.push(cells[key]);
                }
            }else{
                arrayOfCells = cells;
            }

            if (arrayOfCells.length == 0) {
                return;
            }

            var cellToSend, res, allNewCells = [];
            arrayOfCells.forEach(function (cell) {

                // set the cell in the app controller
                cells[cell.getId()] = cell;

                // split the id
                res = cell.getId().split('-');

                // create the object to send to the front end
                cellToSend = {};
                cellToSend.row = res[0];
                cellToSend.col = res[1];
                cellToSend.value = cell.getValue();

                allNewCells.push(cellToSend);
            });

            var msg = MessagePassing.MessageToFront(MessagePassing.MessageTypes.NEW_CELL_VALUE, allNewCells);
            BackEndMessaging.sendMessage(msg);
        }

        return {

            // update the value of a cell
            updateCell: function (row, column, value) {
                var id = row + "-" + column;
                dataStore.saveCell(id, value);
            },

            // launch the necessary processes associated with application startup
            appStarted: function () {
                debug("App started code");

                var c = Context.getInstance();

                // update the replica identity
                var ri = c.getReplicaIdentity();
                ri.updateTimestamp();
                c.setReplicaIdentity(ri);

                // increment the online user counter
                dataStore.incrementCounter(onlineUserCounterId);

                // update online user counter
                notifyFrontEndAboutOnlineUserCounter(dataStore.getCounterValue(onlineUserCounterId));

                // start recovery protocol
                ReplicationController.Init();

                // start checking for experiments to run
                //c.startTestCheck();
            },

            // launch the necessary processes associated with application closing
            appClosed: function () {
                debug("App closing");

                // set direct replication flag as false, so it will attempt when restarted
                var c = Context.getInstance();
                c.setDirectReplicationFlag(false);

                // stop checking for experiments to run
                c.stopTestCheck();

                // clear the list of known peers
                c.clearPeerList();

                // decrement the counter of online users
                dataStore.decrementCounter(onlineUserCounterId);
            }

        };

    }

    return {

        // Get the Singleton instance if one exists
        // or create one if it doesn't
        getInstance: function () {

            if (!instance) {
                instance = init();
            }

            return instance;
        }

    };

})();

<commit_msg>Making the app look for tests.<commit_after>var ApplicationController = (function () {

    // Instance stores a reference to the Singleton
    var instance;

    function init() {

        var onlineUserCounterId = 1;

        // create a new data store instance
        var dataStore = DataStore.getInstance();

        // create and assign callback for the online user counter
        var callback_ToFP4tA9ZdRg = function (counter) {
            notifyFrontEndAboutOnlineUserCounter(counter.getCount());
        }
        dataStore.subscribeToNewCounter(callback_ToFP4tA9ZdRg, onlineUserCounterId);

        // create and assign a callback for new cells
        var callback_QyRg1nwivb0n = function (cells) {
            notifyFronEndAboutNewCells(cells);
        }
        dataStore.subscribeToNewRegister(callback_QyRg1nwivb0n);

        //Send a message to the front end to update the online user counter
        function notifyFrontEndAboutOnlineUserCounter(count) {
            var msg = MessagePassing.MessageToFront(MessagePassing.MessageTypes.USER_COUNT_UPDATED, count);
            BackEndMessaging.sendMessage(msg);
        }

        //Send a message to the front end to update a set of cells
        function notifyFronEndAboutNewCells(cells) {

            var arrayOfCells = [];
            if (!(cells instanceof Array)){
                for(var key in cells) {
                    arrayOfCells.push(cells[key]);
                }
            }else{
                arrayOfCells = cells;
            }

            if (arrayOfCells.length == 0) {
                return;
            }

            var cellToSend, res, allNewCells = [];
            arrayOfCells.forEach(function (cell) {

                // set the cell in the app controller
                cells[cell.getId()] = cell;

                // split the id
                res = cell.getId().split('-');

                // create the object to send to the front end
                cellToSend = {};
                cellToSend.row = res[0];
                cellToSend.col = res[1];
                cellToSend.value = cell.getValue();

                allNewCells.push(cellToSend);
            });

            var msg = MessagePassing.MessageToFront(MessagePassing.MessageTypes.NEW_CELL_VALUE, allNewCells);
            BackEndMessaging.sendMessage(msg);
        }

        return {

            // update the value of a cell
            updateCell: function (row, column, value) {
                var id = row + "-" + column;
                dataStore.saveCell(id, value);
            },

            // launch the necessary processes associated with application startup
            appStarted: function () {
                debug("App started code");

                var c = Context.getInstance();

                // update the replica identity
                var ri = c.getReplicaIdentity();
                ri.updateTimestamp();
                c.setReplicaIdentity(ri);

                // increment the online user counter
                dataStore.incrementCounter(onlineUserCounterId);

                // update online user counter
                notifyFrontEndAboutOnlineUserCounter(dataStore.getCounterValue(onlineUserCounterId));

                // start recovery protocol
                ReplicationController.Init();

                // start checking for experiments to run
                c.startTestCheck();
            },

            // launch the necessary processes associated with application closing
            appClosed: function () {
                debug("App closing");

                // set direct replication flag as false, so it will attempt when restarted
                var c = Context.getInstance();
                c.setDirectReplicationFlag(false);

                // stop checking for experiments to run
                c.stopTestCheck();

                // clear the list of known peers
                c.clearPeerList();

                // decrement the counter of online users
                dataStore.decrementCounter(onlineUserCounterId);
            }

        };

    }

    return {

        // Get the Singleton instance if one exists
        // or create one if it doesn't
        getInstance: function () {

            if (!instance) {
                instance = init();
            }

            return instance;
        }

    };

})();

<|endoftext|>


<commit_before>import TextInputRow from './TextInputRow';
import SwitchRow from './SwitchRow';
import SelectRow from './SelectRow';

import SelectList from './SelectList';
import SelectOption from './SelectOption';

export {
  TextInputRow,
  SwitchRow,
  SelectRow,

  SelectList,
  SelectOption,
};
<commit_msg>export parseSelectOptions<commit_after>import TextInputRow from './TextInputRow';
import SwitchRow from './SwitchRow';
import SelectRow from './SelectRow';

import SelectList from './SelectList';
import SelectOption from './SelectOption';
import parseSelectOptions from './utils/parseSelectOptions';

export {
  TextInputRow,
  SwitchRow,
  SelectRow,

  SelectList,
  SelectOption,
  parseSelectOptions,
};
<|endoftext|>


<commit_before>import angular from 'angular';
import Module from 'app.module';
import template from './template.html';
import notify from 'notify';

require("brandicon");

const CONTROLLER_NAME = 'UsersUserPicturesBrandController';
const STATE_NAME = 'users-user-pictures-brand';

function chunkBy(arr, count) {
    var newArr = [];
    var size = Math.ceil(count);
    for (var i=0; i<arr.length; i+=size) {
        newArr.push(arr.slice(i, i+size));
    }
    return newArr;
}

angular.module(Module)
    .config(['$stateProvider',
        function config($stateProvider) {
            $stateProvider.state( {
                name: STATE_NAME,
                url: '/users/:identity/pictures/:brand?page',
                controller: CONTROLLER_NAME,
                controllerAs: 'ctrl',
                template: template
            });
        }
    ])
    .controller(CONTROLLER_NAME, [
        '$scope', '$http', '$state',
        function($scope, $http, $state) {

            var ctrl = this;

            function init() {

                ctrl.identity = ctrl.user.identity ? ctrl.user.identity : 'user' + ctrl.user.id;

                $http({
                    method: 'GET',
                    url: '/api/item',
                    params: {
                        type_id: 5,
                        limit: 1,
                        catname: $state.params.name,
                        fields: 'name_only,catname'
                    }
                }).then(function(response) {
                    if (response.data.items.length <= 0) {
                        $state.go('error-404');
                        return;
                    }
                    ctrl.brand = response.data.items[0];

                    $scope.pageEnv({
                        layout: {
                            blankPage: false,
                            needRight: false
                        },
                        name: 'page/141/name',
                        pageId: 141,
                        args: {
                            USER_NAME: ctrl.user.name,
                            USER_IDENTITY: ctrl.identity,
                            BRAND_NAME: ctrl.brand.name_only,
                            BRAND_CATNAME: ctrl.brand.catname
                        }
                    });

                    $http({
                        method: 'GET',
                        url: '/api/picture',
                        params: {
                            status: 'accepted',
                            fields: 'owner,thumbnail,votes,views,comments_count,name_html,name_text',
                            limit: 30,
                            page: $state.params.page,
                            item_id: ctrl.brand.id,
                            owner_id: ctrl.user.id,
                            order: 1
                        }
                    }).then(function(response) {
                        ctrl.pictures = response.data.pictures;
                        ctrl.chunks = chunkBy(ctrl.pictures, 6);
                        ctrl.paginator = response.data.paginator;
                    }, function(response) {
                        notify.response(response);
                    });

                }, function(response) {
                    notify.response(response);
                });
            }

            var result = $state.params.identity.match(/^user([0-9]+)$/);

            if (result) {
                $http({
                    method: 'GET',
                    url: '/api/user/' + result[1],
                    fields: 'identity'
                }).then(function(response) {
                    ctrl.user = response.data;
                    init();
                }, function(response) {
                    notify.response(response);
                });

            } else {
                $http({
                    method: 'GET',
                    url: '/api/user',
                    params: {
                        identity: $state.params.identity,
                        limit: 1,
                        fields: 'identity'
                    }
                }).then(function(response) {
                    if (response.data.items.length <= 0) {
                        $state.go('error-404');
                        return;
                    }
                    ctrl.user = response.data.items[0];
                    init();
                }, function(response) {
                    notify.response(response);
                });
            }

        }
    ]);

export default CONTROLLER_NAME;
<commit_msg>brand catname filter fix<commit_after>import angular from 'angular';
import Module from 'app.module';
import template from './template.html';
import notify from 'notify';

require("brandicon");

const CONTROLLER_NAME = 'UsersUserPicturesBrandController';
const STATE_NAME = 'users-user-pictures-brand';

function chunkBy(arr, count) {
    var newArr = [];
    var size = Math.ceil(count);
    for (var i=0; i<arr.length; i+=size) {
        newArr.push(arr.slice(i, i+size));
    }
    return newArr;
}

angular.module(Module)
    .config(['$stateProvider',
        function config($stateProvider) {
            $stateProvider.state( {
                name: STATE_NAME,
                url: '/users/:identity/pictures/:brand?page',
                controller: CONTROLLER_NAME,
                controllerAs: 'ctrl',
                template: template
            });
        }
    ])
    .controller(CONTROLLER_NAME, [
        '$scope', '$http', '$state',
        function($scope, $http, $state) {

            var ctrl = this;

            function init() {

                if (ctrl.user.deleted) {
                    $state.go('error-404');
                    return;
                }

                ctrl.identity = ctrl.user.identity ? ctrl.user.identity : 'user' + ctrl.user.id;

                $http({
                    method: 'GET',
                    url: '/api/item',
                    params: {
                        type_id: 5,
                        limit: 1,
                        catname: $state.params.brand,
                        fields: 'name_only,catname'
                    }
                }).then(function(response) {
                    if (response.data.items.length <= 0) {
                        $state.go('error-404');
                        return;
                    }
                    ctrl.brand = response.data.items[0];

                    $scope.pageEnv({
                        layout: {
                            blankPage: false,
                            needRight: false
                        },
                        name: 'page/141/name',
                        pageId: 141,
                        args: {
                            USER_NAME: ctrl.user.name,
                            USER_IDENTITY: ctrl.identity,
                            BRAND_NAME: ctrl.brand.name_only,
                            BRAND_CATNAME: ctrl.brand.catname
                        }
                    });

                    $http({
                        method: 'GET',
                        url: '/api/picture',
                        params: {
                            status: 'accepted',
                            fields: 'owner,thumbnail,votes,views,comments_count,name_html,name_text',
                            limit: 30,
                            page: $state.params.page,
                            item_id: ctrl.brand.id,
                            owner_id: ctrl.user.id,
                            order: 1
                        }
                    }).then(function(response) {
                        ctrl.pictures = response.data.pictures;
                        ctrl.chunks = chunkBy(ctrl.pictures, 6);
                        ctrl.paginator = response.data.paginator;
                    }, function(response) {
                        notify.response(response);
                    });

                }, function(response) {
                    notify.response(response);
                });
            }

            var result = $state.params.identity.match(/^user([0-9]+)$/);

            if (result) {
                $http({
                    method: 'GET',
                    url: '/api/user/' + result[1],
                    fields: 'identity'
                }).then(function(response) {
                    ctrl.user = response.data;
                    init();
                }, function(response) {
                    notify.response(response);
                });

            } else {
                $http({
                    method: 'GET',
                    url: '/api/user',
                    params: {
                        identity: $state.params.identity,
                        limit: 1,
                        fields: 'identity'
                    }
                }).then(function(response) {
                    if (response.data.items.length <= 0) {
                        $state.go('error-404');
                        return;
                    }
                    ctrl.user = response.data.items[0];
                    init();
                }, function(response) {
                    notify.response(response);
                });
            }

        }
    ]);

export default CONTROLLER_NAME;
<|endoftext|>