<commit_before>/**
 * @file TextArea component
 * @author chao(chao.zhang@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Event from '../_vendors/Event';

export default class TextArea extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            focus: false,
            width: props.initialWidth,
            height: props.initialHeight,
            value: props.value
        };

        this.onFocus = ::this.onFocus;
        this.onBlur = ::this.onBlur;
        this.onChange = ::this.onChange;
        this.resizeHandle = ::this.resizeHandle;
        this.mouseUpHandle = ::this.mouseUpHandle;

    }

    onFocus() {
        this.setState({
            focus: true
        }, () => {
            this.props.onFocus && this.props.onFocus();
        });
    }

    onBlur() {
        this.setState({
            focus: false
        }, () => {
            this.props.onBlur && this.props.onBlur();
        });
    }

    /**
     * 根据textArea的宽高设置state中宽高
     */
    resizeHandle(e) {
        this.setState({
            width: e.target.clientWidth + 2,
            height: e.target.clientHeight + 2
        });
    }

    /**
     * mouseUp时，若textArea的宽高右边，则resizeHandle
     */
    mouseUpHandle(e) {
        if (e.target.clientWidth + 2 !== this.state.width || e.target.clientHeight + 2 !== this.state.height) {
            this.resizeHandle(e);
        }
    }

    /**
     * input变化时，如果为autoSize，则控制高度，使之随内容变化而变化
     */

    onChange(ev) {
        const {initialHeight, maxHeight, autoSize} = this.props;
        const oEvent = ev || event;
        const {target} = oEvent;

        if (autoSize) {

            const {style} = target;

            style.height = initialHeight + 'px';
            style.overflow = 'hidden';
            if (initialHeight < target.scrollHeight + 2) {
                if (maxHeight && maxHeight > target.scrollHeight + 2) {
                    style.height = target.scrollHeight + 2 + 'px';
                } else {
                    style.height = maxHeight + 'px';
                    style.overflow = 'auto';
                }
            }
        }

        this.setState({
            value: target.value
        }, () => {
            this.props.onChange && this.props.onChange(target.value);
        });
    }

    componentWillReceiveProps(nextProps) {
        const {width, height, value} = this.state;

        if (nextProps.initialWidth !== width || nextProps.initialHeight !== height || nextProps.value !== value) {
            this.setState({
                width: nextProps.initialWidth,
                height: nextProps.initialHeight,
                value: nextProps.value
            });
        }
    }

    componentDidMount() {
        const {autoSize, autoFocus} = this.props;

        if (!autoSize) {
            Event.addEvent(this.refs.textarea, 'mouseup', this.mouseUpHandle);
        }

        if (autoFocus === true) {
            this.refs.textarea.focus();
        }
    }

    componentWillUnmount() {
        const {autoSize} = this.props;

        if (!autoSize) {
            Event.removeEvent(this.refs.textarea, 'mouseup', this.mouseUpHandle);
        }
    }

    render() {

        const {className, style, cols, rows, autoSize, placeholder, maxWidth} = this.props,
            {focus, width, height, value} = this.state,

            textStyle = {
                height: height,
                width: width,
                overflow: autoSize ? 'hidden' : 'auto',
                resize: autoSize ? 'none' : 'both',
                maxWidth: maxWidth,
                ...style
            };

        return (
            <textarea ref="textarea"
                      className={`text-area ${focus ? 'area-focus' : ''} ${className}`}
                      style={{...textStyle}}
                      cols={cols}
                      rows={rows}
                      placeholder={placeholder}
                      value={value}
                      autoComplete="off"
                      autoCorrect="off"
                      autoCapitalize="off"
                      spellCheck="false"
                      onFocus={this.onFocus}
                      onBlur={this.onBlur}
                      onChange={this.onChange}></textarea>
        );

    }
};

TextArea.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The number of cols.
     */
    cols: PropTypes.number,

    /**
     * The number of rows.
     */
    rows: PropTypes.number,

    /**
     * The initial height of textArea.
     */
    initialHeight: PropTypes.number,

    /**
     * The initial height of textArea.
     */
    initialWidth: PropTypes.number,

    /**
     * The value of textArea.
     */
    value: PropTypes.string,

    /**
     * The max height of textArea.
     */
    maxHeight: PropTypes.number,

    /**
     * The max width of textArea.
     */
    maxWidth: PropTypes.number,

    /**
     * If true, the textArea will change its size by words.
     */
    autoSize: PropTypes.bool,

    /**
     * If true,the textField will autoFocus.
     */
    autoFocus: PropTypes.bool,

    /**
     * The placeholder of textArea.
     */
    placeholder: PropTypes.string,

    /**
     * When the value of textArea change, it will execute.
     */
    onChange: PropTypes.func,

    /**
     * When the textArea onBlur, it will execute.
     */
    onBlur: PropTypes.func,

    /**
     * When the textArea onFocus, it will execute.
     */
    onFocus: PropTypes.func

};

TextArea.defaultProps = {

    className: '',
    style: null,

    cols: 50,
    rows: 3,
    initialHeight: 30,
    initialWidth: 200,
    maxHeight: 100,
    maxWidth: 500,
    autoSize: true,
    autoFocus: false,
    placeholder: 'Please input something.',
    value: ''

};<commit_msg>text area bug<commit_after>/**
 * @file TextArea component
 * @author chao(chao.zhang@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Event from '../_vendors/Event';

export default class TextArea extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            focus: false,
            width: props.initialWidth,
            height: props.initialHeight,
            value: props.value
        };

        this.onFocus = ::this.onFocus;
        this.onBlur = ::this.onBlur;
        this.onChange = ::this.onChange;
        this.resizeHandle = ::this.resizeHandle;
        this.mouseUpHandle = ::this.mouseUpHandle;

    }

    onFocus() {
        this.setState({
            focus: true
        }, () => {
            this.props.onFocus && this.props.onFocus();
        });
    }

    onBlur() {
        this.setState({
            focus: false
        }, () => {
            this.props.onBlur && this.props.onBlur();
        });
    }

    /**
     * 根据textArea的宽高设置state中宽高
     */
    resizeHandle(e) {
        this.setState({
            width: e.target.offsetWidth,
            height: e.target.offsetHeight
        });
    }

    /**
     * mouseUp时，若textArea的宽高右边，则resizeHandle
     */
    mouseUpHandle(e) {
        if (e.target.offsetWidth !== this.state.width || e.target.offsetHeight !== this.state.height) {
            this.resizeHandle(e);
        }
    }

    /**
     * input变化时，如果为autoSize，则控制高度，使之随内容变化而变化
     */

    onChange(ev) {
        const {initialHeight, maxHeight, autoSize} = this.props;
        const oEvent = ev || event;
        const {target} = oEvent;

        if (autoSize) {

            const {style} = target;

            style.height = initialHeight + 'px';
            style.overflow = 'hidden';
            if (initialHeight < target.scrollHeight + 2) {
                if (maxHeight && maxHeight > target.scrollHeight + 2) {
                    style.height = target.scrollHeight + 2 + 'px';
                } else {
                    style.height = maxHeight + 'px';
                    style.overflow = 'auto';
                }
            }
        }

        this.setState({
            value: target.value
        }, () => {
            this.props.onChange && this.props.onChange(target.value);
        });
    }

    componentWillReceiveProps(nextProps) {
        const {width, height, value} = this.state;

        if (nextProps.initialWidth !== width || nextProps.initialHeight !== height || nextProps.value !== value) {
            this.setState({
                width: nextProps.initialWidth,
                height: nextProps.initialHeight,
                value: nextProps.value
            });
        }
    }

    componentDidMount() {
        const {autoSize, autoFocus} = this.props;

        if (!autoSize) {
            Event.addEvent(this.refs.textarea, 'mouseup', this.mouseUpHandle);
        }

        if (autoFocus === true) {
            this.refs.textarea.focus();
        }
    }

    componentWillUnmount() {
        const {autoSize} = this.props;

        if (!autoSize) {
            Event.removeEvent(this.refs.textarea, 'mouseup', this.mouseUpHandle);
        }
    }

    render() {

        const {className, style, cols, rows, autoSize, placeholder, maxWidth} = this.props,
            {focus, width, height, value} = this.state,

            textStyle = {
                height: height,
                width: width,
                overflow: autoSize ? 'hidden' : 'auto',
                resize: autoSize ? 'none' : 'both',
                maxWidth: maxWidth,
                ...style
            };

        return (
            <textarea ref="textarea"
                      className={`text-area ${focus ? 'area-focus' : ''} ${className}`}
                      style={{...textStyle}}
                      cols={cols}
                      rows={rows}
                      placeholder={placeholder}
                      value={value}
                      autoComplete="off"
                      autoCorrect="off"
                      autoCapitalize="off"
                      spellCheck="false"
                      onFocus={this.onFocus}
                      onBlur={this.onBlur}
                      onChange={this.onChange}></textarea>
        );

    }
};

TextArea.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The number of cols.
     */
    cols: PropTypes.number,

    /**
     * The number of rows.
     */
    rows: PropTypes.number,

    /**
     * The initial height of textArea.
     */
    initialHeight: PropTypes.number,

    /**
     * The initial height of textArea.
     */
    initialWidth: PropTypes.number,

    /**
     * The value of textArea.
     */
    value: PropTypes.string,

    /**
     * The max height of textArea.
     */
    maxHeight: PropTypes.number,

    /**
     * The max width of textArea.
     */
    maxWidth: PropTypes.number,

    /**
     * If true, the textArea will change its size by words.
     */
    autoSize: PropTypes.bool,

    /**
     * If true,the textField will autoFocus.
     */
    autoFocus: PropTypes.bool,

    /**
     * The placeholder of textArea.
     */
    placeholder: PropTypes.string,

    /**
     * When the value of textArea change, it will execute.
     */
    onChange: PropTypes.func,

    /**
     * When the textArea onBlur, it will execute.
     */
    onBlur: PropTypes.func,

    /**
     * When the textArea onFocus, it will execute.
     */
    onFocus: PropTypes.func

};

TextArea.defaultProps = {

    className: '',
    style: null,

    cols: 50,
    rows: 3,
    initialHeight: 30,
    initialWidth: 200,
    maxHeight: 100,
    maxWidth: 500,
    autoSize: true,
    autoFocus: false,
    placeholder: 'Please input something.',
    value: ''

};<|endoftext|>


<commit_before>'use babel';

import AtomConsole from '../lib/atom-console';

// Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
//
// To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
// or `fdescribe`). Remove the `f` to unfocus the block.

describe('AtomConsole', () => {
    let workspaceElement, activationPromise;

    beforeEach(() => {
        workspaceElement = atom.views.getView(atom.workspace);
        activationPromise = atom.packages.activatePackage('atom console');
    });

    describe('when the atom-console:toggle event is triggered', () => {
        it('slides the console on or off screen', () => {
            // Before the activation event the view is not on the DOM, and no panel
            // has been created
            expect(workspaceElement.querySelector('.atom-console')).not.toExist();

            // This is an activation event, triggering it will cause the package to be
            // activated.
            atom.commands.dispatch(workspaceElement, 'atom-console:toggle');

            waitsForPromise(() => {
                return activationPromise;
            });

            runs(() => {
                expect(workspaceElement.querySelector('.atom-console')).toExist();

                let atomConsoleElement = workspaceElement.querySelector('.atom-console');
                expect(atomConsoleElement).toExist();

                let atomConsolePanel = atom.workspace.panelForItem(atomConsoleElement);
                expect(atomConsoleElement.style.height).not.toEqual(0);
                atom.commands.dispatch(workspaceElement, 'atom-console:toggle');
                expect(atomConsoleElement.style.height).toEqual(0);
            });
        });

        it('slides the console on or off screen', () => {
            // This test shows you an integration test testing at the view level.

            // Attaching the workspaceElement to the DOM is required to allow the
            // `toBeVisible()` matchers to work. Anything testing visibility or focus
            // requires that the workspaceElement is on the DOM. Tests that attach the
            // workspaceElement to the DOM are generally slower than those off DOM.
            jasmine.attachToDOM(workspaceElement);

            expect(workspaceElement.querySelector('.atom-console')).not.toExist();

            // This is an activation event, triggering it causes the package to be
            // activated.
            atom.commands.dispatch(workspaceElement, 'atom-console:toggle');

            waitsForPromise(() => {
                return activationPromise;
            });

            runs(() => {
                // Now we can test for view visibility
                let atomConsoleElement = workspaceElement.querySelector('.atom-console');
                expect(atomConsoleElement.style.height).not.toEqual(0);
                atom.commands.dispatch(workspaceElement, 'atom-console:toggle');
                expect(atomConsoleElement.style.height).toEqual(0);
            });
        });
    });
});
<commit_msg>fixed error in atom-console-spec.js<commit_after>'use babel';

import AtomConsole from '../lib/atom-console';

// Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
//
// To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
// or `fdescribe`). Remove the `f` to unfocus the block.

describe('AtomConsole', () => {
    let workspaceElement, activationPromise;

    beforeEach(() => {
        workspaceElement = atom.views.getView(atom.workspace);
        activationPromise = atom.packages.activatePackage('atom-console');
    });

    describe('when the atom-console:toggle event is triggered', () => {
        it('slides the console on or off screen', () => {
            // Before the activation event the view is not on the DOM, and no panel
            // has been created
            expect(workspaceElement.querySelector('.atom-console')).not.toExist();

            // This is an activation event, triggering it will cause the package to be
            // activated.
            atom.commands.dispatch(workspaceElement, 'atom-console:toggle');

            waitsForPromise(() => {
                return activationPromise;
            });

            runs(() => {
                expect(workspaceElement.querySelector('.atom-console')).toExist();

                let atomConsoleElement = workspaceElement.querySelector('.atom-console');
                expect(atomConsoleElement).toExist();

                let atomConsolePanel = atom.workspace.panelForItem(atomConsoleElement);
                expect(atomConsoleElement.style.height).not.toEqual(0);
                atom.commands.dispatch(workspaceElement, 'atom-console:toggle');
                expect(atomConsoleElement.style.height).toEqual(0);
            });
        });

        it('slides the console on or off screen', () => {
            // This test shows you an integration test testing at the view level.

            // Attaching the workspaceElement to the DOM is required to allow the
            // `toBeVisible()` matchers to work. Anything testing visibility or focus
            // requires that the workspaceElement is on the DOM. Tests that attach the
            // workspaceElement to the DOM are generally slower than those off DOM.
            jasmine.attachToDOM(workspaceElement);

            expect(workspaceElement.querySelector('.atom-console')).not.toExist();

            // This is an activation event, triggering it causes the package to be
            // activated.
            atom.commands.dispatch(workspaceElement, 'atom-console:toggle');

            waitsForPromise(() => {
                return activationPromise;
            });

            runs(() => {
                // Now we can test for view visibility
                let atomConsoleElement = workspaceElement.querySelector('.atom-console');
                expect(atomConsoleElement.style.height).not.toEqual(0);
                atom.commands.dispatch(workspaceElement, 'atom-console:toggle');
                expect(atomConsoleElement.style.height).toEqual(0);
            });
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

// User routes use users controller
var users = require('../controllers/users'),
    config = require('meanio').loadConfig();

module.exports = function(MeanUser, app, auth, database, passport) {

  app.route('/logout')
    .get(users.signout);
  app.route('/users/me')
    .get(users.me);

  // Setting up the users api
  app.route('/register')
    .post(users.create);

  app.route('/forgot-password')
    .post(users.forgotpassword);

  app.route('/reset/:token')
    .post(users.resetpassword);

  // Setting up the userId param
  app.param('userId', users.user);

  // AngularJS route to check for authentication
  app.route('/loggedin')
    .get(function(req, res) {
      res.send(req.isAuthenticated() ? req.user : '0');
    });

  // Setting the local strategy route
  app.route('/login')
    .post(passport.authenticate('local', {
      failureFlash: true
    }), function(req, res) {
      res.send({
        user: req.user,
        redirect: (req.user.roles.indexOf('admin') !== -1) ? req.get('referer') : false
      });
    });

  // AngularJS route to get config of social buttons
  app.route('/get-config')
    .get(function (req, res) {
      res.send(config);
    });

  // Setting the facebook oauth routes
  app.route('/auth/facebook')
    .get(passport.authenticate('facebook', {
      scope: ['email', 'user_about_me'],
      failureRedirect: '#!/login'
    }), users.signin);

  app.route('/auth/facebook/callback')
    .get(passport.authenticate('facebook', {
      failureRedirect: '#!/login'
    }), users.authCallback);

  // Setting the github oauth routes
  app.route('/auth/github')
    .get(passport.authenticate('github', {
      failureRedirect: '#!/login'
    }), users.signin);

  app.route('/auth/github/callback')
    .get(passport.authenticate('github', {
      failureRedirect: '#!/login'
    }), users.authCallback);

  // Setting the twitter oauth routes
  app.route('/auth/twitter')
    .get(passport.authenticate('twitter', {
      failureRedirect: '#!/login'
    }), users.signin);

  app.route('/auth/twitter/callback')
    .get(passport.authenticate('twitter', {
      failureRedirect: '#!/login'
    }), users.authCallback);

  // Setting the google oauth routes
  app.route('/auth/google')
    .get(passport.authenticate('google', {
      failureRedirect: '#!/login',
      scope: [
        'https://www.googleapis.com/auth/userinfo.profile',
        'https://www.googleapis.com/auth/userinfo.email'
      ]
    }), users.signin);

  app.route('/auth/google/callback')
    .get(passport.authenticate('google', {
      failureRedirect: '#!/login'
    }), users.authCallback);

  // Setting the linkedin oauth routes
  app.route('/auth/linkedin')
    .get(passport.authenticate('linkedin', {
      failureRedirect: '#!/login',
      scope: ['r_emailaddress']
    }), users.signin);

  app.route('/auth/linkedin/callback')
    .get(passport.authenticate('linkedin', {
      failureRedirect: '#!/login'
    }), users.authCallback);

};
<commit_msg>get-config is a security hole<commit_after>'use strict';

// User routes use users controller
var users = require('../controllers/users'),
    config = require('meanio').loadConfig();

module.exports = function(MeanUser, app, auth, database, passport) {

  app.route('/logout')
    .get(users.signout);
  app.route('/users/me')
    .get(users.me);

  // Setting up the users api
  app.route('/register')
    .post(users.create);

  app.route('/forgot-password')
    .post(users.forgotpassword);

  app.route('/reset/:token')
    .post(users.resetpassword);

  // Setting up the userId param
  app.param('userId', users.user);

  // AngularJS route to check for authentication
  app.route('/loggedin')
    .get(function(req, res) {
      res.send(req.isAuthenticated() ? req.user : '0');
    });

  // Setting the local strategy route
  app.route('/login')
    .post(passport.authenticate('local', {
      failureFlash: true
    }), function(req, res) {
      res.send({
        user: req.user,
        redirect: (req.user.roles.indexOf('admin') !== -1) ? req.get('referer') : false
      });
    });

  // AngularJS route to get config of social buttons
  /* Temporarely disabling to avoid security issue
  app.route('/get-config')
    .get(function (req, res) {
      res.send(config);
    });
*/

  // Setting the facebook oauth routes
  app.route('/auth/facebook')
    .get(passport.authenticate('facebook', {
      scope: ['email', 'user_about_me'],
      failureRedirect: '#!/login'
    }), users.signin);

  app.route('/auth/facebook/callback')
    .get(passport.authenticate('facebook', {
      failureRedirect: '#!/login'
    }), users.authCallback);

  // Setting the github oauth routes
  app.route('/auth/github')
    .get(passport.authenticate('github', {
      failureRedirect: '#!/login'
    }), users.signin);

  app.route('/auth/github/callback')
    .get(passport.authenticate('github', {
      failureRedirect: '#!/login'
    }), users.authCallback);

  // Setting the twitter oauth routes
  app.route('/auth/twitter')
    .get(passport.authenticate('twitter', {
      failureRedirect: '#!/login'
    }), users.signin);

  app.route('/auth/twitter/callback')
    .get(passport.authenticate('twitter', {
      failureRedirect: '#!/login'
    }), users.authCallback);

  // Setting the google oauth routes
  app.route('/auth/google')
    .get(passport.authenticate('google', {
      failureRedirect: '#!/login',
      scope: [
        'https://www.googleapis.com/auth/userinfo.profile',
        'https://www.googleapis.com/auth/userinfo.email'
      ]
    }), users.signin);

  app.route('/auth/google/callback')
    .get(passport.authenticate('google', {
      failureRedirect: '#!/login'
    }), users.authCallback);

  // Setting the linkedin oauth routes
  app.route('/auth/linkedin')
    .get(passport.authenticate('linkedin', {
      failureRedirect: '#!/login',
      scope: ['r_emailaddress']
    }), users.signin);

  app.route('/auth/linkedin/callback')
    .get(passport.authenticate('linkedin', {
      failureRedirect: '#!/login'
    }), users.authCallback);

};
<|endoftext|>


<commit_before>import {moduloActividad, actividadTest} from '../../helpers/actividadTest';

const nombre = "ElDetectiveChaparro";

moduloActividad(nombre);

actividadTest(nombre, {
	solucion: '<xml xmlns="http://www.w3.org/1999/xhtml"><block type="al_empezar_a_ejecutar" id="2" deletable="false" movable="false" editable="false" x="0" y="0"><statement name="program"><block type="Primersospechoso" id="3"><next><block type="Sacardisfraz" id="8"><next><block type="hasta" id="4" inline="true"><value name="condition"><block type="Descubralculpable" id="5"></block></value><statement name="block"><block type="Siguientesospechoso" id="7"><next><block type="Sacardisfraz" id="6"></block></next></block></statement></block></next></block></next></block></statement></block></xml>',
});

actividadTest(nombre, {
	descripcionAdicional: 'Da error si se quiere determinar si un sospechoso es culpable antes de interrogarlo',
	errorEsperado: 'No puedo saber si es el culpable, no lo he interrogado antes.',
	solucion: `<xml xmlns="http://www.w3.org/1999/xhtml">
  <block type="al_empezar_a_ejecutar" id="1" deletable="false" movable="false" editable="false" x="0" y="0">
    <statement name="program">
      <block type="PrimerSospechoso" id="JguD~YdHru6P~fcr%NY">
        <next>
          <block type="Hasta" id="eEne^.+K8A^2IFdubL?v">
            <value name="condition">
              <block type="EsCulpable" id="]RG,CNdY/tAwH5c5-Fa"></block>
            </value>
            <statement name="block">
              <block type="SiguienteSospechoso" id="zxo0AF]?Z!i,9bbiRJ+[">
                <next>
                  <block type="SacarDisfraz" id="Ed*!GNd4vswjF7HVjWL2"></block>
                </next>
              </block>
            </statement>
          </block>
        </next>
      </block>
    </statement>
  </block>
  <block type="repetir" id="hX[/K9]kVi:cxT;yI{bB" disabled="true" x="-20" y="480"></block>
</xml>`
});
<commit_msg>Corregida identacion e referencia a bloques del test detective chaparro<commit_after>import {moduloActividad, actividadTest} from '../../helpers/actividadTest';

const nombre = "ElDetectiveChaparro";

moduloActividad(nombre);

actividadTest(nombre, {
  solucion: `<?xml version="1.0" encoding="UTF-8"?>
  <xml xmlns="http://www.w3.org/1999/xhtml">
     <block type="al_empezar_a_ejecutar" id="2" deletable="false" movable="false" editable="false" x="0" y="0">
        <statement name="program">
           <block type="PrimerSospechoso" id="3">
              <next>
                 <block type="SacarDisfraz" id="8">
                    <next>
                       <block type="Hasta" id="4" inline="true">
                          <value name="condition">
                             <block type="EsCulpable" id="5" />
                          </value>
                          <statement name="block">
                             <block type="SiguienteSospechoso" id="7">
                                <next>
                                   <block type="SacarDisfraz" id="6" />
                                </next>
                             </block>
                          </statement>
                       </block>
                    </next>
                 </block>
              </next>
           </block>
        </statement>
     </block>
  </xml>`,
});

actividadTest(nombre, {
	descripcionAdicional: 'Da error si se quiere determinar si un sospechoso es culpable antes de interrogarlo',
	errorEsperado: 'No puedo saber si es el culpable, no lo he interrogado antes.',
	solucion: `<xml xmlns="http://www.w3.org/1999/xhtml">
  <block type="al_empezar_a_ejecutar" id="1" deletable="false" movable="false" editable="false" x="0" y="0">
    <statement name="program">
      <block type="PrimerSospechoso" id="JguD~YdHru6P~fcr%NY">
        <next>
          <block type="Hasta" id="eEne^.+K8A^2IFdubL?v">
            <value name="condition">
              <block type="EsCulpable" id="]RG,CNdY/tAwH5c5-Fa"></block>
            </value>
            <statement name="block">
              <block type="SiguienteSospechoso" id="zxo0AF]?Z!i,9bbiRJ+[">
                <next>
                  <block type="SacarDisfraz" id="Ed*!GNd4vswjF7HVjWL2"></block>
                </next>
              </block>
            </statement>
          </block>
        </next>
      </block>
    </statement>
  </block>
  <block type="repetir" id="hX[/K9]kVi:cxT;yI{bB" disabled="true" x="-20" y="480"></block>
</xml>`
});
<|endoftext|>


<commit_before>(function() {
  var app = angular.module('myreddit', ['ionic', 'angularMoment'])

  app.controller('ReditCtrl', function($http, $scope) {

    $scope.stories = [];

    $http.get('http://www.reddit.com/r/Android/new/.json')
      .success(function(response) {
        console.log(response.data.children);
        angular.forEach(response.data.children, function(child) {
          $scope.stories.push(child.data);
        });

      });

    $scope.loadOlderStories = functio() {
      var params = {};

      $http.get('http://www.reddit.com/r/Android/new/.json', {params: params})
        .success(function(response) {
          console.log(response.data.children);
          angular.forEach(response.data.children, function(child) {
            $scope.stories.push(child.data);
          });

        });
    };

  });

  app.run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
      if(window.cordova && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      }
      if(window.StatusBar) {
        StatusBar.styleDefault();
      }
    });
  })
})();
<commit_msg>Fixed function<commit_after>(function() {
  var app = angular.module('myreddit', ['ionic', 'angularMoment'])

  app.controller('ReditCtrl', function($http, $scope) {

    $scope.stories = [];

    $http.get('http://www.reddit.com/r/Android/new/.json')
      .success(function(response) {
        console.log(response.data.children);
        angular.forEach(response.data.children, function(child) {
          $scope.stories.push(child.data);
        });

      });

    $scope.loadOlderStories = function() {
      var params = {};

      $http.get('http://www.reddit.com/r/Android/new/.json', {params: params})
        .success(function(response) {
          console.log(response.data.children);
          angular.forEach(response.data.children, function(child) {
            $scope.stories.push(child.data);
          });

        });
    };

  });

  app.run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
      if(window.cordova && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      }
      if(window.StatusBar) {
        StatusBar.styleDefault();
      }
    });
  })
})();
<|endoftext|>


<commit_before>var srcDir   = __dirname + "/../";

module.exports = {
    all: {
        src: [
                srcDir + "*.js",
                srcDir + "lib/*.js",
                srcDir + "adapter/**/*.js",
                srcDir + "tasks/**/*.js",
                srcDir + "www/**/*.js",
                '!' + srcDir + "www/lib/**/*.js",
                '!' + srcDir + 'node_modules/**/*.js',
                '!' + srcDir + 'adapter/admin/www/lib/**/*.js',
                '!' + srcDir + 'adapter/*/node_modules/**/*.js',
                '!' + srcDir + 'adapter/legacy/www/*/**/*.js'
        ],
        options: require('./jscsRules.js')
    }
};<commit_msg>Update jscs.js<commit_after>var srcDir   = __dirname + "/../";

module.exports = {
    all: {
        src: [
                srcDir + "*.js",
                srcDir + "lib/*.js",
                srcDir + "adapter/**/*.js",
                srcDir + "tasks/**/*.js",
                srcDir + "www/**/*.js",
                '!' + srcDir + "www/lib/**/*.js",
                '!' + srcDir + 'node_modules/**/*.js',
                '!' + srcDir + 'adapter/admin/www/lib/**/*.js',
                '!' + srcDir + 'adapter/*/node_modules/**/*.js',
                '!' + srcDir + 'adapter/legacy/www/*/**/*.js'
        ],
        options: require('./jscsRules.js')
    }
};
<|endoftext|>


<commit_before>// These global variables are not a problem because the algorithm is
// synchronous.
let permissionsByObject
let getObject

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

const authorized = () => true // eslint-disable-line no-unused-vars
const forbiddden = () => false // eslint-disable-line no-unused-vars

const and = (...checkers) => (object, permission) => { // eslint-disable-line no-unused-vars
  for (const checker of checkers) {
    if (!checker(object, permission)) {
      return false
    }
  }
  return true
}

const or = (...checkers) => (object, permission) => { // eslint-disable-line no-unused-vars
  for (const checker of checkers) {
    if (checker(object, permission)) {
      return true
    }
  }
  return false
}

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

const checkMember = (memberName) => (object, permission) => {
  const member = object[memberName]
  return checkAuthorization(member, permission)
}

const checkSelf = ({ id }, permission) => {
  const permissionsForObject = permissionsByObject[id]

  return (
    permissionsForObject &&
    permissionsForObject[permission]
  )
}

// ===================================================================

const checkAuthorizationByTypes = {
  host: or(checkSelf, checkMember('$pool')),

  message: checkMember('$object'),

  network: or(checkSelf, checkMember('$pool')),

  SR: or(checkSelf, checkMember('$pool')),

  task: checkMember('$host'),

  VBD: checkMember('VDI'),

  // Access to a VDI is granted if the user has access to the
  // containing SR or to a linked VM.
  VDI (vdi, permission) {
    // Check authorization for the containing SR.
    if (checkAuthorization(vdi.$SR, permission)) {
      return true
    }

    // Check authorization for each of the connected VMs.
    for (const vbdId of vdi.$VBDs) {
      if (checkAuthorization(getObject(vbdId).VM, permission)) {
        return true
      }
    }

    return false
  },

  'VDI-snapshot': checkMember('$snapshot_of'),

  VIF: or(checkMember('$network'), checkMember('$VM')),

  VM: or(checkSelf, checkMember('$container')),

  'VM-controller': checkMember('$container'),

  'VM-snapshot': checkMember('$snapshot_of'),

  'VM-template': or(checkSelf, checkMember('$pool'))
}

// Hoisting is important for this function.
function checkAuthorization (objectId, permission) {
  const object = getObject(objectId)
  if (!object) {
    return false
  }

  const checker = checkAuthorizationByTypes[object.type] || checkSelf

  return checker(object, permission)
}

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

export default (
  permissionsByObject_,
  getObject_,
  permissions,
  permission
) => {
  // Assign global variables.
  permissionsByObject = permissionsByObject_
  getObject = getObject_

  try {
    if (permission) {
      return checkAuthorization(permissions, permission)
    } else {
      for (const [objectId, permission] of permissions) {
        if (!checkAuthorization(objectId, permission)) {
          return false
        }
      }
    }

    return true
  } finally {
    // Free the global variables.
    permissionsByObject = getObject = null
  }
}
<commit_msg>fix: workaround for VDI snapshots with $snaphot_of which point to themselves<commit_after>// These global variables are not a problem because the algorithm is
// synchronous.
let permissionsByObject
let getObject

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

const authorized = () => true // eslint-disable-line no-unused-vars
const forbiddden = () => false // eslint-disable-line no-unused-vars

const and = (...checkers) => (object, permission) => { // eslint-disable-line no-unused-vars
  for (const checker of checkers) {
    if (!checker(object, permission)) {
      return false
    }
  }
  return true
}

const or = (...checkers) => (object, permission) => { // eslint-disable-line no-unused-vars
  for (const checker of checkers) {
    if (checker(object, permission)) {
      return true
    }
  }
  return false
}

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

const checkMember = (memberName) => (object, permission) => {
  const member = object[memberName]
  return member !== object.id && checkAuthorization(member, permission)
}

const checkSelf = ({ id }, permission) => {
  const permissionsForObject = permissionsByObject[id]

  return (
    permissionsForObject &&
    permissionsForObject[permission]
  )
}

// ===================================================================

const checkAuthorizationByTypes = {
  host: or(checkSelf, checkMember('$pool')),

  message: checkMember('$object'),

  network: or(checkSelf, checkMember('$pool')),

  SR: or(checkSelf, checkMember('$pool')),

  task: checkMember('$host'),

  VBD: checkMember('VDI'),

  // Access to a VDI is granted if the user has access to the
  // containing SR or to a linked VM.
  VDI (vdi, permission) {
    // Check authorization for the containing SR.
    if (checkAuthorization(vdi.$SR, permission)) {
      return true
    }

    // Check authorization for each of the connected VMs.
    for (const vbdId of vdi.$VBDs) {
      if (checkAuthorization(getObject(vbdId).VM, permission)) {
        return true
      }
    }

    return false
  },

  'VDI-snapshot': checkMember('$snapshot_of'),

  VIF: or(checkMember('$network'), checkMember('$VM')),

  VM: or(checkSelf, checkMember('$container')),

  'VM-controller': checkMember('$container'),

  'VM-snapshot': checkMember('$snapshot_of'),

  'VM-template': or(checkSelf, checkMember('$pool'))
}

// Hoisting is important for this function.
function checkAuthorization (objectId, permission) {
  const object = getObject(objectId)
  if (!object) {
    return false
  }

  const checker = checkAuthorizationByTypes[object.type] || checkSelf

  return checker(object, permission)
}

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

export default (
  permissionsByObject_,
  getObject_,
  permissions,
  permission
) => {
  // Assign global variables.
  permissionsByObject = permissionsByObject_
  getObject = getObject_

  try {
    if (permission) {
      return checkAuthorization(permissions, permission)
    } else {
      for (const [objectId, permission] of permissions) {
        if (!checkAuthorization(objectId, permission)) {
          return false
        }
      }
    }

    return true
  } finally {
    // Free the global variables.
    permissionsByObject = getObject = null
  }
}
<|endoftext|>


<commit_before>document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady(){}

$(document).ready(function(){

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

    // initialize ol

    var view = new ol.View({
    	center: ol.proj.transform([73.241, 61.143], 'EPSG:4326', 'EPSG:3857'),
    	zoom: 16
    });

    var map = new ol.Map({
      layers: [
        new ol.layer.Tile({
          source: new ol.source.XYZ({
            url: 'http://tiles.{a-z}.st.vmp.ru/{z}/{x}/{y}.png',
            tilePixelRatio: 1,
            minZoom: 12,
            maxZoom: 18
          }),
        })
      ],
      target: 'map',
      view: view,
      interactions: ol.interaction.defaults({
          keyboard: false,
          DragAndDrop: false,
          altShiftDragRotate:false,
          pinchRotate:true
      })
    });

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

    // marker

    var markerEl = document.getElementById('location-marker');
    var marker = new ol.Overlay({
      positioning: 'center-center',
      element: markerEl,
      stopEvent: false
    });
    map.addOverlay(marker);

    var positions = new ol.geom.LineString([],
        /** @type {ol.geom.GeometryLayout} */ ('XYZM'));

    // activate fuck
    var geolocation = new ol.Geolocation(/** @type {olx.GeolocationOptions} */ ({
      projection: view.getProjection(),
      trackingOptions: {
        maximumAge: 10000,
        enableHighAccuracy: true,
        timeout: 600000
      }
    }));

    var speed = '';

    var deltaMean = 500;

    // listener
    geolocation.on('change', function(evt) {
      var position = geolocation.getPosition();
      var accuracy = geolocation.getAccuracy();
      var heading  = geolocation.getHeading() || 0;
      var speed    = geolocation.getSpeed() || 0; // GLOBAL VARIABLE

      // -----  Speed.
      speedometr = setInterval(function(){
          var speed = geolocation.getSpeed() || 0; // GLOBAL VARIABLE
          $("#speed").html(speed);
          console.log("Speed: "+ speed);
      }, 2000);

      if(speed > 2) {
            geolocation.setTracking(true); // Start position tracking
      } else {
          geolocation.setTracking(false);
      }

      var m = Date.now();

      console.log(speed);
      addPosition(position, heading, m, speed);

      var coords = positions.getCoordinates();
      var len = coords.length;
      if (len >= 2) {
        deltaMean = (coords[len - 1][3] - coords[0][3]) / (len - 1);
      }

    });

    geolocation.on('error', function() {
      alert('geolocation error');
    });

    function radToDeg(rad) {
      return rad * 360 / (Math.PI * 2);
    }
    function degToRad(deg) {
      return deg * Math.PI * 2 / 360;
    }
    // invert negative
    function mod(n) {
      return ((n % (2 * Math.PI)) + (2 * Math.PI)) % (2 * Math.PI);
    }

    function addPosition(position, heading, m, speed) {
      var x = position[0];
      var y = position[1];
      var fCoords = positions.getCoordinates();
      var previous = fCoords[fCoords.length - 1];
      var prevHeading = previous && previous[2];
      if (prevHeading) {
        var headingDiff = heading - mod(prevHeading);

        if (Math.abs(headingDiff) > Math.PI) {      // < 180 ok da
          var sign = (headingDiff >= 0) ? 1 : -1;
          headingDiff = - sign * (2 * Math.PI - Math.abs(headingDiff));
        }
        heading = prevHeading + headingDiff;
      }
      positions.appendCoordinate([x, y, heading, m]);

      positions.setCoordinates(positions.getCoordinates().slice(-20));

      if (heading && speed) {
        markerEl.src = 'img/location.png';
      } else {
        markerEl.src = 'img/location-static.png';
      }
    }

    var previousM = 0;

    // set center
    map.beforeRender(function(map, frameState) {
      if (frameState !== null) {
        var m = frameState.time - deltaMean * 1.5;      // get out smoother than ever!
        m = Math.max(m, previousM);
        previousM = m;
        var c = positions.getCoordinateAtM(m, true);    // stackoverflow magic!
        var view = frameState.viewState;
        if (c) {
          view.center = getCenterWithHeading(c, -c[2], view.resolution);
          view.rotation = -c[2];
          marker.setPosition(c);
        }
      }
      return true;
    });

    function getCenterWithHeading(position, rotation, resolution) {
      var size = map.getSize();
      var height = size[1];

      return [
        position[0] - Math.sin(rotation) * height * resolution * 1 / 4,
        position[1] + Math.cos(rotation) * height * resolution * 1 / 4
      ];
    }

    // callback
    function render() {
      map.render();
    }

    // TADA
    function geolocate() {
      geolocation.setTracking(true); // Start position tracking
      map.on('postcompose', render);
      map.render();
    }

    geolocate();

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

    // timer

    var hours = 0, mins = 0, secs = 0;
    function resetTimer(){
    	secs = 0, mins = 0, hours = 0;
    }
    function startTimer(){
    	tick = setInterval(function(){
    		secs += 1;
    		if(secs < 10){
    			hsecs = ':0' + secs;
    		} else if(secs == 60){
    			mins += 1;
    			secs = 0;
    			hsecs = ':0' + secs;
    		}
    		else
    			hsecs = ':' + secs;

    		if(mins < 10)
    			hmins = '0' + mins;
    		else if(mins == 60){
    			hours += 1;
    			mins = 0;
    			hmins = '0' + mins;
    		}
    		else
    			hmins = mins

    		if(hours == 0)
    			hhours = '';
    		else {
    			hhours = hours + ':';
    			hsecs = "" + hsecs + "";

    		}

    		$("#timer").html(hhours + hmins + hsecs);
    	}, 1000);
    }
    function stopTimer(){
    	clearInterval(tick);
    }
    startTimer();

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

    // parse json and get routes

    $.getJSON( "json/routes.json", function( data ) {
      // for loop. parsing all routes.
      for(var i=0; i < data.routes.length; i++){
        var item = data.routes[i][i+1][0];

        var kind = {
          'dist': {
            css: "dist",
            header: "На дистанцию"
          },
          'time': {
            css: "time",
            header: "На время"
          }
        }
        item.length = item.length.toString().slice(0, -1);
        item.length = item.length.replace(".", ",");
        $("#routes").append("\

\

"+ kind[item.kind].header +"
\

"+ item.name +"
\

" + item.length +" км
\
          <button>Начать</button>\
          ");

        console.log(i+1 + " route serializing");
        // parsing
        var routesArr = new Array();
        for(var e=0; e < item.latlngs.length; e++){
          routesArr.push(item.latlngs[e]);
        }
        var rend = {}
        rend.latlngs = routesArr;
        addRoutes(rend);

        // $("#routes").append("\
        //
\
        //
На время
\
        //
Кедровый лог
\
        //
17 мин
\
        //     <button>Начать</button>\
        //
");
      }
    });

    var countLineRoutes = 0;
    var vectorLayerLineFirst = new ol.layer.Vector({});

    function addRoutes(coord) {
      if (countLineRoutes == 0) {
        var comp = new Array();

        for (var i = 0; i < coord.latlngs.length; i++) {
          var xandy = ol.proj.transform([coord.latlngs[i].lng, coord.latlngs[i].lat], 'EPSG:4326', 'EPSG:3857');
          comp.push(xandy);
        }

        var firstroutesF = new ol.Feature({
          geometry: new ol.geom.LineString(comp)
        });

        var vectorLineFirst = new ol.source.Vector({});
        vectorLineFirst.addFeature(firstroutesF);

        vectorLayerLineFirst = new ol.layer.Vector({
          source: vectorLineFirst
        });

        map.addLayer(vectorLayerLineFirst);
        countLineRoutes++;
        console.log(comp);
      }
    }

});

setTimeout(function(){
  frameNumb = 0;
  $(function () {

      $('.fotorama')
      .on('fotorama:showend ',
              function (e, fotorama) {
                  var frameNumb = fotorama.activeIndex + 1;
                  console.log(frameNumb);
              }
          )
          .fotorama();
    });
}, 500);
<commit_msg>fix a bug c:<commit_after>document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady(){}

$(document).ready(function(){

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

    // initialize ol

    var view = new ol.View({
    	center: ol.proj.transform([73.241, 61.143], 'EPSG:4326', 'EPSG:3857'),
    	zoom: 16
    });

    var map = new ol.Map({
      layers: [
        new ol.layer.Tile({
          source: new ol.source.XYZ({
            url: 'http://tiles.{a-z}.st.vmp.ru/{z}/{x}/{y}.png',
            tilePixelRatio: 1,
            minZoom: 12,
            maxZoom: 18
          }),
        })
      ],
      target: 'map',
      view: view,
      interactions: ol.interaction.defaults({
          keyboard: false,
          DragAndDrop: false,
          altShiftDragRotate:false,
          pinchRotate:true
      })
    });

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

    // marker

    var markerEl = document.getElementById('location-marker');
    var marker = new ol.Overlay({
      positioning: 'center-center',
      element: markerEl,
      stopEvent: false
    });
    map.addOverlay(marker);

    var positions = new ol.geom.LineString([],
        /** @type {ol.geom.GeometryLayout} */ ('XYZM'));

    // activate fuck
    var geolocation = new ol.Geolocation(/** @type {olx.GeolocationOptions} */ ({
      projection: view.getProjection(),
      trackingOptions: {
        maximumAge: 10000,
        enableHighAccuracy: true,
        timeout: 600000
      }
    }));

    var speed = '';

    var deltaMean = 500;

    // listener
    geolocation.on('change', function(evt) {
      var position = geolocation.getPosition();
      var accuracy = geolocation.getAccuracy();
      var heading  = geolocation.getHeading() || 0;
      var speed    = geolocation.getSpeed() || 0; // GLOBAL VARIABLE

      // -----  Speed.
      clearInterval(speedometr);
      speedometr = setInterval(function(){
          var speed = geolocation.getSpeed() || 0; // GLOBAL VARIABLE
          $("#speed").html(speed);
          console.log("Speed: "+ speed);
      }, 2000);

      if(speed > 2) {
            geolocation.setTracking(true); // Start position tracking
      } else {
          geolocation.setTracking(false);
      }

      var m = Date.now();

      console.log(speed);
      addPosition(position, heading, m, speed);

      var coords = positions.getCoordinates();
      var len = coords.length;
      if (len >= 2) {
        deltaMean = (coords[len - 1][3] - coords[0][3]) / (len - 1);
      }

    });

    geolocation.on('error', function() {
      alert('geolocation error');
    });

    function radToDeg(rad) {
      return rad * 360 / (Math.PI * 2);
    }
    function degToRad(deg) {
      return deg * Math.PI * 2 / 360;
    }
    // invert negative
    function mod(n) {
      return ((n % (2 * Math.PI)) + (2 * Math.PI)) % (2 * Math.PI);
    }

    function addPosition(position, heading, m, speed) {
      var x = position[0];
      var y = position[1];
      var fCoords = positions.getCoordinates();
      var previous = fCoords[fCoords.length - 1];
      var prevHeading = previous && previous[2];
      if (prevHeading) {
        var headingDiff = heading - mod(prevHeading);

        if (Math.abs(headingDiff) > Math.PI) {      // < 180 ok da
          var sign = (headingDiff >= 0) ? 1 : -1;
          headingDiff = - sign * (2 * Math.PI - Math.abs(headingDiff));
        }
        heading = prevHeading + headingDiff;
      }
      positions.appendCoordinate([x, y, heading, m]);

      positions.setCoordinates(positions.getCoordinates().slice(-20));

      if (heading && speed) {
        markerEl.src = 'img/location.png';
      } else {
        markerEl.src = 'img/location-static.png';
      }
    }

    var previousM = 0;

    // set center
    map.beforeRender(function(map, frameState) {
      if (frameState !== null) {
        var m = frameState.time - deltaMean * 1.5;      // get out smoother than ever!
        m = Math.max(m, previousM);
        previousM = m;
        var c = positions.getCoordinateAtM(m, true);    // stackoverflow magic!
        var view = frameState.viewState;
        if (c) {
          view.center = getCenterWithHeading(c, -c[2], view.resolution);
          view.rotation = -c[2];
          marker.setPosition(c);
        }
      }
      return true;
    });

    function getCenterWithHeading(position, rotation, resolution) {
      var size = map.getSize();
      var height = size[1];

      return [
        position[0] - Math.sin(rotation) * height * resolution * 1 / 4,
        position[1] + Math.cos(rotation) * height * resolution * 1 / 4
      ];
    }

    // callback
    function render() {
      map.render();
    }

    // TADA
    function geolocate() {
      geolocation.setTracking(true); // Start position tracking
      map.on('postcompose', render);
      map.render();
    }

    geolocate();

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

    // timer

    var hours = 0, mins = 0, secs = 0;
    function resetTimer(){
    	secs = 0, mins = 0, hours = 0;
    }
    function startTimer(){
    	tick = setInterval(function(){
    		secs += 1;
    		if(secs < 10){
    			hsecs = ':0' + secs;
    		} else if(secs == 60){
    			mins += 1;
    			secs = 0;
    			hsecs = ':0' + secs;
    		}
    		else
    			hsecs = ':' + secs;

    		if(mins < 10)
    			hmins = '0' + mins;
    		else if(mins == 60){
    			hours += 1;
    			mins = 0;
    			hmins = '0' + mins;
    		}
    		else
    			hmins = mins

    		if(hours == 0)
    			hhours = '';
    		else {
    			hhours = hours + ':';
    			hsecs = "" + hsecs + "";

    		}

    		$("#timer").html(hhours + hmins + hsecs);
    	}, 1000);
    }
    function stopTimer(){
    	clearInterval(tick);
    }
    startTimer();

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

    // parse json and get routes

    $.getJSON( "json/routes.json", function( data ) {
      // for loop. parsing all routes.
      for(var i=0; i < data.routes.length; i++){
        var item = data.routes[i][i+1][0];

        var kind = {
          'dist': {
            css: "dist",
            header: "На дистанцию"
          },
          'time': {
            css: "time",
            header: "На время"
          }
        }
        item.length = item.length.toString().slice(0, -1);
        item.length = item.length.replace(".", ",");
        $("#routes").append("\

\

"+ kind[item.kind].header +"
\

"+ item.name +"
\

" + item.length +" км
\
          <button>Начать</button>\
          ");

        console.log(i+1 + " route serializing");
        // parsing
        var routesArr = new Array();
        for(var e=0; e < item.latlngs.length; e++){
          routesArr.push(item.latlngs[e]);
        }
        var rend = {}
        rend.latlngs = routesArr;
        addRoutes(rend);

        // $("#routes").append("\
        //
\
        //
На время
\
        //
Кедровый лог
\
        //
17 мин
\
        //     <button>Начать</button>\
        //
");
      }
    });

    var countLineRoutes = 0;
    var vectorLayerLineFirst = new ol.layer.Vector({});

    function addRoutes(coord) {
      if (countLineRoutes == 0) {
        var comp = new Array();

        for (var i = 0; i < coord.latlngs.length; i++) {
          var xandy = ol.proj.transform([coord.latlngs[i].lng, coord.latlngs[i].lat], 'EPSG:4326', 'EPSG:3857');
          comp.push(xandy);
        }

        var firstroutesF = new ol.Feature({
          geometry: new ol.geom.LineString(comp)
        });

        var vectorLineFirst = new ol.source.Vector({});
        vectorLineFirst.addFeature(firstroutesF);

        vectorLayerLineFirst = new ol.layer.Vector({
          source: vectorLineFirst
        });

        map.addLayer(vectorLayerLineFirst);
        countLineRoutes++;
        console.log(comp);
      }
    }

});

setTimeout(function(){
  frameNumb = 0;
  $(function () {

      $('.fotorama')
      .on('fotorama:showend ',
              function (e, fotorama) {
                  var frameNumb = fotorama.activeIndex + 1;
                  console.log(frameNumb);
              }
          )
          .fotorama();
    });
}, 500);
<|endoftext|>


<commit_before>export const IDENTIFIER_RULES = `Only a-z, 0-9 and - are allowed.
  Name must not begin or end with a hypen,
  or contain more than one hypen in a row`;

export const PATCH_BASENAME_RULES = IDENTIFIER_RULES;

/**
 * Enumeration of possible pin types
 *
 * @name PIN_TYPE
 * @enum {string}
 */
export const PIN_TYPE = {
  STRING: 'string',
  NUMBER: 'number',
  BOOLEAN: 'boolean',
  PULSE: 'pulse',
  BYTE: 'byte',
  PORT: 'port',
  DEAD: 'dead',
  // generic types
  T1: 't1',
  T2: 't2',
  T3: 't3',
};

export const INPUT_PULSE_PIN_BINDING_OPTIONS = {
  NEVER: 'Never',
  CONTINUOUSLY: 'Continuously',
  ON_BOOT: 'On Boot',
};

export const DEFAULT_VALUE_OF_TYPE = {
  [PIN_TYPE.STRING]: '""',
  [PIN_TYPE.NUMBER]: '0',
  [PIN_TYPE.BOOLEAN]: 'False',
  [PIN_TYPE.PULSE]: INPUT_PULSE_PIN_BINDING_OPTIONS.NEVER,
  [PIN_TYPE.BYTE]: '00h',
  [PIN_TYPE.PORT]: 'D0',
  [PIN_TYPE.DEAD]: '',
  [PIN_TYPE.T1]: '',
  [PIN_TYPE.T2]: '',
  [PIN_TYPE.T3]: '',
};

export const MAX_ARITY_STEP = 3;

/**
 * A lookup table that answers the question
 * 'can a type A be cast to type B?' for static types.
 * Generic types are handled separately.
 *
 * Map contains only compatible types.
 * All other types is not compatigle by default.
 *
 * @example
 *   STATIC_TYPES_COMPATIBILITY[PIN_TYPE.BOOLEAN][PIN_TYPE.STRING] // true
 *   // boolean can be cast to string
 *
 * @name STATIC_TYPES_COMPATIBILITY
 */
export const STATIC_TYPES_COMPATIBILITY = {
  [PIN_TYPE.BOOLEAN]: {
    [PIN_TYPE.BOOLEAN]: true,
    [PIN_TYPE.NUMBER]: true,
    [PIN_TYPE.PULSE]: true,
    [PIN_TYPE.STRING]: true,
  },
  [PIN_TYPE.NUMBER]: {
    [PIN_TYPE.BOOLEAN]: true,
    [PIN_TYPE.NUMBER]: true,
    [PIN_TYPE.STRING]: true,
  },
  [PIN_TYPE.BYTE]: {
    [PIN_TYPE.BYTE]: true,
    [PIN_TYPE.STRING]: true,
  },
  // nothing can be cast to or from pulse
  [PIN_TYPE.PULSE]: {
    [PIN_TYPE.PULSE]: true,
  },
  // nothing can be cast from string
  [PIN_TYPE.STRING]: {
    [PIN_TYPE.STRING]: true,
  },
  [PIN_TYPE.PORT]: {
    [PIN_TYPE.PORT]: true,
  },
};

// node types that provide a constant value
export const CONST_NODETYPES = {
  [PIN_TYPE.NUMBER]: 'xod/core/constant-number',
  [PIN_TYPE.BOOLEAN]: 'xod/core/constant-boolean',
  [PIN_TYPE.STRING]: 'xod/core/constant-string',
  [PIN_TYPE.BYTE]: 'xod/core/constant-byte',
  [PIN_TYPE.PORT]: 'xod/core/constant-port',
};

// node types that provide a constant pulse,
// once(on start) or continuously
export const PULSE_CONST_NODETYPES = {
  // [INPUT_PULSE_PIN_BINDING_OPTIONS.NEVER]: Do not create Node for `Never`
  [INPUT_PULSE_PIN_BINDING_OPTIONS.ON_BOOT]: 'xod/core/boot',
  [INPUT_PULSE_PIN_BINDING_OPTIONS.CONTINUOUSLY]: 'xod/core/continuously',
};

// node types that prints values into Serial
// to debug xod programm, it should be omitted
// from Project before transpilation without
// turned on debug mode
// tweak-* nodes should not be omitted,
// they will just act as slightly less efficient constants
export const DEBUG_NODETYPES = [
  'xod/core/watch',
  'xod/core/console-log',
  'xod/debug/watch',
  'xod/debug/console-log',
];

/**
 * Enumeration of possible pin directions
 *
 * @name PIN_DIRECTION
 * @enum {string}
 */
export const PIN_DIRECTION = {
  INPUT: 'input',
  OUTPUT: 'output',
};

export const OPPOSITE_DIRECTION = {
  [PIN_DIRECTION.INPUT]: PIN_DIRECTION.OUTPUT,
  [PIN_DIRECTION.OUTPUT]: PIN_DIRECTION.INPUT,
};

/**
 * Enumeration of possible pin labels by directions
 *
 * @name PIN_LABEL_BY_DIRECTION
 * @enum {string}
 */
export const PIN_LABEL_BY_DIRECTION = {
  [PIN_DIRECTION.INPUT]: 'IN',
  [PIN_DIRECTION.OUTPUT]: 'OUT',
};

/**
 * 'Magic' pin keys for terminal nodes.
 * See {@link flatten}
 *
 * @name TERMINAL_PIN_KEYS
 * @enum {string}
 */
export const TERMINAL_PIN_KEYS = {
  [PIN_DIRECTION.INPUT]: '__in__',
  [PIN_DIRECTION.OUTPUT]: '__out__',
};

/**
 * Path for a 'magic' patch, whose instance is placed
 * to mark patches that are not implemented in XOD.
 *
 * Such patches usually contain only terminal nodes
 * and provide implementations in target platforms
 * native languages.
 *
 * @name NOT_IMPLEMENTED_IN_XOD_PATH
 * @type {string}
 */
export const NOT_IMPLEMENTED_IN_XOD_PATH =
  'xod/patch-nodes/not-implemented-in-xod';

/**
 * Path for a 'magic' patch, whose instance is placed
 * to mark abstract nodes.
 *
 * @name ABSTRACT_MARKER_PATH
 * @type {string}
 */
export const ABSTRACT_MARKER_PATH = 'xod/patch-nodes/abstract';

/**
 * Path for a 'magic' patch, whose instance is placed
 * to mark deprecated nodes.
 */
export const DEPRECATED_MARKER_PATH = 'xod/patch-nodes/deprecated';

/**
 * Path for a 'magic' terminal patch, whose instance is
 * used in constructor nodes of custom types.
 */
export const OUTPUT_SELF_PATH = 'xod/patch-nodes/output-self';

/**
 * Path for a 'magic' patch, whose instance is placed
 * to mark utility nodes.
 */
export const UTILITY_MARKER_PATH = 'xod/patch-nodes/utility';

/**
 * Path for a 'magic' patch, whose instance is placed
 * to mark patches with an attached tabtest.
 */
export const TABTEST_MARKER_PATH = 'xod/patch-nodes/tabtest';

export const FROM_BUS_PATH = 'xod/patch-nodes/from-bus';
export const TO_BUS_PATH = 'xod/patch-nodes/to-bus';

export const JUMPER_PATCH_PATH = 'xod/patch-nodes/jumper';

export const UNTITLED_PROJECT = 'untitled';

// { markerName: fileName }
export const MANAGED_ATTACHMENT_FILENAMES = {
  [NOT_IMPLEMENTED_IN_XOD_PATH]: 'patch.cpp',
  [TABTEST_MARKER_PATH]: 'patch.test.tsv',
};

const IMPL_TEMPLATE = `
struct State {
};

{{ GENERATED_CODE }}

void evaluate(Context ctx) {
    //auto inValue = getValue<input_IN>(ctx);
    //emitValue<output_OUT>(ctx, inValue);
}
`;

const TABTEST_TEMPLATE = 'IN\tOUT\n"some input"\t"expected output"';

export const MANAGED_ATTACHMENT_TEMPLATES = {
  [NOT_IMPLEMENTED_IN_XOD_PATH]: IMPL_TEMPLATE,
  [TABTEST_MARKER_PATH]: TABTEST_TEMPLATE,
};
<commit_msg>feat(xod-project): make the port type castable to the string type<commit_after>export const IDENTIFIER_RULES = `Only a-z, 0-9 and - are allowed.
  Name must not begin or end with a hypen,
  or contain more than one hypen in a row`;

export const PATCH_BASENAME_RULES = IDENTIFIER_RULES;

/**
 * Enumeration of possible pin types
 *
 * @name PIN_TYPE
 * @enum {string}
 */
export const PIN_TYPE = {
  STRING: 'string',
  NUMBER: 'number',
  BOOLEAN: 'boolean',
  PULSE: 'pulse',
  BYTE: 'byte',
  PORT: 'port',
  DEAD: 'dead',
  // generic types
  T1: 't1',
  T2: 't2',
  T3: 't3',
};

export const INPUT_PULSE_PIN_BINDING_OPTIONS = {
  NEVER: 'Never',
  CONTINUOUSLY: 'Continuously',
  ON_BOOT: 'On Boot',
};

export const DEFAULT_VALUE_OF_TYPE = {
  [PIN_TYPE.STRING]: '""',
  [PIN_TYPE.NUMBER]: '0',
  [PIN_TYPE.BOOLEAN]: 'False',
  [PIN_TYPE.PULSE]: INPUT_PULSE_PIN_BINDING_OPTIONS.NEVER,
  [PIN_TYPE.BYTE]: '00h',
  [PIN_TYPE.PORT]: 'D0',
  [PIN_TYPE.DEAD]: '',
  [PIN_TYPE.T1]: '',
  [PIN_TYPE.T2]: '',
  [PIN_TYPE.T3]: '',
};

export const MAX_ARITY_STEP = 3;

/**
 * A lookup table that answers the question
 * 'can a type A be cast to type B?' for static types.
 * Generic types are handled separately.
 *
 * Map contains only compatible types.
 * All other types is not compatigle by default.
 *
 * @example
 *   STATIC_TYPES_COMPATIBILITY[PIN_TYPE.BOOLEAN][PIN_TYPE.STRING] // true
 *   // boolean can be cast to string
 *
 * @name STATIC_TYPES_COMPATIBILITY
 */
export const STATIC_TYPES_COMPATIBILITY = {
  [PIN_TYPE.BOOLEAN]: {
    [PIN_TYPE.BOOLEAN]: true,
    [PIN_TYPE.NUMBER]: true,
    [PIN_TYPE.PULSE]: true,
    [PIN_TYPE.STRING]: true,
  },
  [PIN_TYPE.NUMBER]: {
    [PIN_TYPE.BOOLEAN]: true,
    [PIN_TYPE.NUMBER]: true,
    [PIN_TYPE.STRING]: true,
  },
  [PIN_TYPE.BYTE]: {
    [PIN_TYPE.BYTE]: true,
    [PIN_TYPE.STRING]: true,
  },
  // nothing can be cast to or from pulse
  [PIN_TYPE.PULSE]: {
    [PIN_TYPE.PULSE]: true,
  },
  // nothing can be cast from string
  [PIN_TYPE.STRING]: {
    [PIN_TYPE.STRING]: true,
  },
  [PIN_TYPE.PORT]: {
    [PIN_TYPE.PORT]: true,
    [PIN_TYPE.STRING]: true,
  },
};

// node types that provide a constant value
export const CONST_NODETYPES = {
  [PIN_TYPE.NUMBER]: 'xod/core/constant-number',
  [PIN_TYPE.BOOLEAN]: 'xod/core/constant-boolean',
  [PIN_TYPE.STRING]: 'xod/core/constant-string',
  [PIN_TYPE.BYTE]: 'xod/core/constant-byte',
  [PIN_TYPE.PORT]: 'xod/core/constant-port',
};

// node types that provide a constant pulse,
// once(on start) or continuously
export const PULSE_CONST_NODETYPES = {
  // [INPUT_PULSE_PIN_BINDING_OPTIONS.NEVER]: Do not create Node for `Never`
  [INPUT_PULSE_PIN_BINDING_OPTIONS.ON_BOOT]: 'xod/core/boot',
  [INPUT_PULSE_PIN_BINDING_OPTIONS.CONTINUOUSLY]: 'xod/core/continuously',
};

// node types that prints values into Serial
// to debug xod programm, it should be omitted
// from Project before transpilation without
// turned on debug mode
// tweak-* nodes should not be omitted,
// they will just act as slightly less efficient constants
export const DEBUG_NODETYPES = [
  'xod/core/watch',
  'xod/core/console-log',
  'xod/debug/watch',
  'xod/debug/console-log',
];

/**
 * Enumeration of possible pin directions
 *
 * @name PIN_DIRECTION
 * @enum {string}
 */
export const PIN_DIRECTION = {
  INPUT: 'input',
  OUTPUT: 'output',
};

export const OPPOSITE_DIRECTION = {
  [PIN_DIRECTION.INPUT]: PIN_DIRECTION.OUTPUT,
  [PIN_DIRECTION.OUTPUT]: PIN_DIRECTION.INPUT,
};

/**
 * Enumeration of possible pin labels by directions
 *
 * @name PIN_LABEL_BY_DIRECTION
 * @enum {string}
 */
export const PIN_LABEL_BY_DIRECTION = {
  [PIN_DIRECTION.INPUT]: 'IN',
  [PIN_DIRECTION.OUTPUT]: 'OUT',
};

/**
 * 'Magic' pin keys for terminal nodes.
 * See {@link flatten}
 *
 * @name TERMINAL_PIN_KEYS
 * @enum {string}
 */
export const TERMINAL_PIN_KEYS = {
  [PIN_DIRECTION.INPUT]: '__in__',
  [PIN_DIRECTION.OUTPUT]: '__out__',
};

/**
 * Path for a 'magic' patch, whose instance is placed
 * to mark patches that are not implemented in XOD.
 *
 * Such patches usually contain only terminal nodes
 * and provide implementations in target platforms
 * native languages.
 *
 * @name NOT_IMPLEMENTED_IN_XOD_PATH
 * @type {string}
 */
export const NOT_IMPLEMENTED_IN_XOD_PATH =
  'xod/patch-nodes/not-implemented-in-xod';

/**
 * Path for a 'magic' patch, whose instance is placed
 * to mark abstract nodes.
 *
 * @name ABSTRACT_MARKER_PATH
 * @type {string}
 */
export const ABSTRACT_MARKER_PATH = 'xod/patch-nodes/abstract';

/**
 * Path for a 'magic' patch, whose instance is placed
 * to mark deprecated nodes.
 */
export const DEPRECATED_MARKER_PATH = 'xod/patch-nodes/deprecated';

/**
 * Path for a 'magic' terminal patch, whose instance is
 * used in constructor nodes of custom types.
 */
export const OUTPUT_SELF_PATH = 'xod/patch-nodes/output-self';

/**
 * Path for a 'magic' patch, whose instance is placed
 * to mark utility nodes.
 */
export const UTILITY_MARKER_PATH = 'xod/patch-nodes/utility';

/**
 * Path for a 'magic' patch, whose instance is placed
 * to mark patches with an attached tabtest.
 */
export const TABTEST_MARKER_PATH = 'xod/patch-nodes/tabtest';

export const FROM_BUS_PATH = 'xod/patch-nodes/from-bus';
export const TO_BUS_PATH = 'xod/patch-nodes/to-bus';

export const JUMPER_PATCH_PATH = 'xod/patch-nodes/jumper';

export const UNTITLED_PROJECT = 'untitled';

// { markerName: fileName }
export const MANAGED_ATTACHMENT_FILENAMES = {
  [NOT_IMPLEMENTED_IN_XOD_PATH]: 'patch.cpp',
  [TABTEST_MARKER_PATH]: 'patch.test.tsv',
};

const IMPL_TEMPLATE = `
struct State {
};

{{ GENERATED_CODE }}

void evaluate(Context ctx) {
    //auto inValue = getValue<input_IN>(ctx);
    //emitValue<output_OUT>(ctx, inValue);
}
`;

const TABTEST_TEMPLATE = 'IN\tOUT\n"some input"\t"expected output"';

export const MANAGED_ATTACHMENT_TEMPLATES = {
  [NOT_IMPLEMENTED_IN_XOD_PATH]: IMPL_TEMPLATE,
  [TABTEST_MARKER_PATH]: TABTEST_TEMPLATE,
};
<|endoftext|>


<commit_before>/*
 * grunt-contrib-sass
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 Sindre Sorhus, contributors
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
  'use strict';

  // TODO: ditch this when grunt v0.4 is released
  grunt.util = grunt.util || grunt.utils;

  var path = require('path');
  var async = grunt.util.async;

  grunt.registerMultiTask('sass', 'Compile Sass to CSS', function() {
    var helpers = require('grunt-contrib-lib').init(grunt);
    var options = helpers.options(this);
    var cb = this.async();
    var args = ['--stdin'].concat(helpers.optsToArgs(options));

    grunt.verbose.writeflags(options, 'Options');

    // TODO: ditch this when grunt v0.4 is released
    this.files = this.files || helpers.normalizeMultiTaskFiles(this.data, this.target);

    async.forEachSeries(this.files, function(el, cb2) {
      var elArgs = [el.dest];
      var src = el.src;
      var files = grunt.file.expandFiles(src);
      var max = files.map(function (filepath) {
        return grunt.file.read(filepath)
      }).join('\n')

      if (path.extname(src) === '.scss') {
        elArgs.push('--scss');
      }

      // Make sure grunt creates the destination folders
      grunt.file.write(el.dest, '');

      // Add dirs of specified files to the sass path
      files.forEach(function(el) {
        elArgs.push('--load-path', path.dirname(el));
      });

      var sass = grunt.util.spawn({
        cmd: process.platform === 'win32' ? 'sass.bat' : 'sass',
        args: elArgs.concat(args)
      }, function(error, result, code) {
        cb2(code > 0);
      }).on('exit', function(code) {
        if ( code === 127 ) {
          grunt.fail.fatal('\nYou need to have Ruby and Sass installed for ' +
            'this task to work.\nMore info: ' +
            'https://github.com/gruntjs/grunt-contrib-sass\n');
        }
      });

      sass.stdin.write(new Buffer(max));
      sass.stdin.end();
      sass.stdout.pipe(process.stdout);
      sass.stderr.pipe(process.stderr);
    }, function(error) {
      cb(!error);
    });
  });
};
<commit_msg>semicolons<commit_after>/*
 * grunt-contrib-sass
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 Sindre Sorhus, contributors
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
  'use strict';

  // TODO: ditch this when grunt v0.4 is released
  grunt.util = grunt.util || grunt.utils;

  var path = require('path');
  var async = grunt.util.async;

  grunt.registerMultiTask('sass', 'Compile Sass to CSS', function() {
    var helpers = require('grunt-contrib-lib').init(grunt);
    var options = helpers.options(this);
    var cb = this.async();
    var args = ['--stdin'].concat(helpers.optsToArgs(options));

    grunt.verbose.writeflags(options, 'Options');

    // TODO: ditch this when grunt v0.4 is released
    this.files = this.files || helpers.normalizeMultiTaskFiles(this.data, this.target);

    async.forEachSeries(this.files, function(el, cb2) {
      var elArgs = [el.dest];
      var src = el.src;
      var files = grunt.file.expandFiles(src);
      var max = files.map(function (filepath) {
        return grunt.file.read(filepath);
      }).join('\n');

      if (path.extname(src) === '.scss') {
        elArgs.push('--scss');
      }

      // Make sure grunt creates the destination folders
      grunt.file.write(el.dest, '');

      // Add dirs of specified files to the sass path
      files.forEach(function(el) {
        elArgs.push('--load-path', path.dirname(el));
      });

      var sass = grunt.util.spawn({
        cmd: process.platform === 'win32' ? 'sass.bat' : 'sass',
        args: elArgs.concat(args)
      }, function(error, result, code) {
        cb2(code > 0);
      }).on('exit', function(code) {
        if ( code === 127 ) {
          grunt.fail.fatal('\nYou need to have Ruby and Sass installed for ' +
            'this task to work.\nMore info: ' +
            'https://github.com/gruntjs/grunt-contrib-sass\n');
        }
      });

      sass.stdin.write(new Buffer(max));
      sass.stdin.end();
      sass.stdout.pipe(process.stdout);
      sass.stderr.pipe(process.stderr);
    }, function(error) {
      cb(!error);
    });
  });
};
<|endoftext|>