<commit_before>'use strict';

import Morph from './Morph.js';
import { search as githubSearch } from '../../src/client/search/github-search.js';
import * as dbSearch from '../../src/client/search/dropbox-search.js';

export default class SearchBar extends Morph {

  initialize() {
    this.searchButton = this.getSubmorph("#searchButton");
    this.setupButton = this.getSubmorph("#setupButton");
    this.searchField = this.getSubmorph("#searchField");
    this.searchResults = this.getSubmorph("#searchResults");

    this.searchButton.addEventListener("click", (evt) => { this.searchButtonClicked() });
    this.setupButton.addEventListener("click", (evt) => { this.setup() });
    this.searchField.addEventListener("keyup", (evt) => { this.searchFieldKeyup(evt) });

    this.searchableMounts = {
      "dropbox": [],
      "github": []
    };

    this.setup();
  }

  async setup() {
    this.findAvailableMounts();
    // some dummy index
    this.lunrIdx = await dbSearch.loadSearchIndex("https://lively4/dropbox/index.l4idx");
  }

  searchButtonClicked() {
    let query = this.searchField.value;
    this.search(query);
  }

  searchFieldKeyup(evt) {
    // enter
    if (evt.keyCode == 13) {
      let query = this.searchField.value;
      this.search(query);
    }
  }

  isSearchEnabled(path) {
    return this.getSubmorph(`input[data-path='${path}']`).checked;
  }

  async search(query) {
    console.log("[Search] searching for '" + query + "'");

    // let dbFileNames = await dbSearch.getSearchableFileNames(this.searchableMounts.dropbox[0].options);
    // console.log(JSON.stringify(dbFileNames));

    let results = []

    for (let mountType in this.searchableMounts) {
      let mounts = this.searchableMounts[mountType];
      for (let i in mounts) {
        let mount = mounts[i];
        if (this.isSearchEnabled(mount.path)) {
          results = results.concat(await mount.find(query, mount.options));
          // update search results
          this.searchResults.show(results, query);
        }
      }
    }
  }

  findAvailableMounts() {
    $.ajax({
        url: "https://lively4/sys/mounts",
        type: 'GET',
        success: (text) => {
          var mounts = JSON.parse(text);
          console.log(mounts);
          var mountsList = this.getSubmorph("#mounts-list");
          mountsList.innerHTML = "";
          mounts.forEach(mount => {
            let enabled = this.searchableMounts[mount.name];
            mountsList.innerHTML += `
              <li ${enabled ? '' : 'class="disabled"'}>
                <input data-path='${mount.path}' type='checkbox' ${enabled ? 'checked' : 'disabled'}> ${mount.path} (${mount.name})
              </li>`;
          });

          this.searchableMounts.dropbox = mounts.filter(mount => { return mount.name == "dropbox" }).map((mount) => {
            mount.find = (query) => {
              if (this.lunrIdx) {
                console.log("[search] done with lunr");
                return this.lunrIdx.search(query).map(res => { res.path = res.ref; return res; });
              }
              return [];
            }
            return mount;
          });

          this.searchableMounts.github = mounts.filter(mount => { return mount.name == "github" }).map((mount) => {
            mount.find = githubSearch;
            return mount;
          });
        },
        error: function(xhr, status, error) {
          console.log("could not get list of mounts for searching: " + error);
        }
      });
  }
}
<commit_msg>[search] correct path in dropbox search results<commit_after>'use strict';

import Morph from './Morph.js';
import { search as githubSearch } from '../../src/client/search/github-search.js';
import * as dbSearch from '../../src/client/search/dropbox-search.js';

export default class SearchBar extends Morph {

  initialize() {
    this.searchButton = this.getSubmorph("#searchButton");
    this.setupButton = this.getSubmorph("#setupButton");
    this.searchField = this.getSubmorph("#searchField");
    this.searchResults = this.getSubmorph("#searchResults");

    this.searchButton.addEventListener("click", (evt) => { this.searchButtonClicked() });
    this.setupButton.addEventListener("click", (evt) => { this.setup() });
    this.searchField.addEventListener("keyup", (evt) => { this.searchFieldKeyup(evt) });

    this.searchableMounts = {
      "dropbox": [],
      "github": []
    };

    this.setup();
  }

  async setup() {
    this.findAvailableMounts();
    // some dummy index
    this.lunrIdx = await dbSearch.loadSearchIndex("https://lively4/dropbox/index.l4idx");
    lively.notify("Info: ", "Dropbox index loaded!", 3);
  }

  searchButtonClicked() {
    let query = this.searchField.value;
    this.search(query);
  }

  searchFieldKeyup(evt) {
    // enter
    if (evt.keyCode == 13) {
      let query = this.searchField.value;
      this.search(query);
    }
  }

  isSearchEnabled(path) {
    return this.getSubmorph(`input[data-path='${path}']`).checked;
  }

  async search(query) {
    console.log("[Search] searching for '" + query + "'");

    // let dbFileNames = await dbSearch.getSearchableFileNames(this.searchableMounts.dropbox[0].options);
    // console.log(JSON.stringify(dbFileNames));

    let results = []

    for (let mountType in this.searchableMounts) {
      let mounts = this.searchableMounts[mountType];
      for (let i in mounts) {
        let mount = mounts[i];
        if (this.isSearchEnabled(mount.path)) {
          results = results.concat(await mount.find(query, mount.options));
          // update search results
          this.searchResults.show(results, query);
        }
      }
    }
  }

  findAvailableMounts() {
    $.ajax({
        url: "https://lively4/sys/mounts",
        type: 'GET',
        success: (text) => {
          var mounts = JSON.parse(text);
          console.log(mounts);
          var mountsList = this.getSubmorph("#mounts-list");
          mountsList.innerHTML = "";
          mounts.forEach(mount => {
            let enabled = this.searchableMounts[mount.name];
            mountsList.innerHTML += `
              <li ${enabled ? '' : 'class="disabled"'}>
                <input data-path='${mount.path}' type='checkbox' ${enabled ? 'checked' : 'disabled'}> ${mount.path} (${mount.name})
              </li>`;
          });

          this.searchableMounts.dropbox = mounts.filter(mount => { return mount.name == "dropbox" }).map((mount) => {
            mount.find = (query) => {
              if (this.lunrIdx) {
                return this.lunrIdx.search(query).map(res => { res.path = mount.path + res.ref; return res; });
              }
              return [];
            }
            return mount;
          });

          this.searchableMounts.github = mounts.filter(mount => { return mount.name == "github" }).map((mount) => {
            mount.find = githubSearch;
            return mount;
          });
        },
        error: function(xhr, status, error) {
          console.log("could not get list of mounts for searching: " + error);
        }
      });
  }
}
<|endoftext|>


<commit_before>/*
* @flow
*/

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
  Text,
  View,
  StyleSheet,
  Animated,
  Dimensions,
  Platform
} from 'react-native';

const screenWidth = Dimensions.get('window').width;

type PlaceholderContainerProps = {
  duration: number,
  delay: number,
  style: Object,
  animatedComponent: React.Element<*>,
  loader: Function,
  replace: boolean
};

type PlaceholderContainerState = {
  containerComponent: Object,
  animatedComponent: Object,
  startPosition: number,
  stopPosition: number,
  isContainerMeasured: boolean,
  isAnimatedComponentMeasured: boolean,
  Component: React.Element<*>
};

export default class PlaceholderContainer extends Component {
  props: PlaceholderContainerProps;
  state: PlaceholderContainerState;
  position: Animated.Value;
  placeholders: Array<React.Element<*>>;
  constructor(props: PlaceholderContainerProps) {
    super(props);
    this.state = {
      ContainerComponent: { x: 0, y: 0, width: 0, height: 0 },
      AnimatedComponent: { x: 0, y: 0, width: 0, height: 0 },
      startPosition: 0,
      stopPosition: 0,
      isContainerComponentMeasured: false,
      isAnimatedComponentMeasured: false,
      Component: null
    };
    this.position = new Animated.Value(0);
    this.placeholders = [];
    this._measureContainerComponent = this._measureView.bind(
      null,
      'ContainerComponent'
    );
    this._measureAnimatedComponent = this._measureView.bind(
      null,
      'AnimatedComponent'
    );
  }
  getChildContext(): Object {
    return {
      position: this.position,
      animatedComponent: this.props.animatedComponent,
      registerPlaceholder: this._registerPlaceholder
    };
  }
  componentDidMount(): void {
    const { loader, replace } = this.props;
    loader &&
      Promise.resolve(loader).then(Component => {
        !replace ? this.setState({ Component }) : this._replacePlaceholders();
      });
  }

  componentWillUnmount(): void {
    this.position.stopAnimation();
  }

  render(): React.Element<*> {
    const { style, elements, animatedComponent, children } = this.props;
    const { Component, isAnimatedComponentMeasured } = this.state;
    return (
      <View
        ref={ref => {
          this.containerRef = ref;
        }}
        onLayout={this._measureContainerComponent}
        style={style}
      >
        {!isAnimatedComponentMeasured &&
          <View
            ref={ref => {
              this.componentRef = ref;
            }}
            onLayout={this._measureAnimatedComponent}
            style={styles.offscreen}
          >
            {animatedComponent}
          </View>}
        {(Component && Component) || children}
      </View>
    );
  }

  _triggerAnimation = (): void => {
    const { duration, delay } = this.props;
    const { startPosition, stopPosition } = this.state;
    Animated.loop(Animated.sequence([
      Animated.timing(this.position, {
        toValue: stopPosition || screenWidth,
        duration: duration,
        useNativeDriver: true
      }),
      Animated.timing(this.position, {
        toValue: startPosition || 0,
        duration: 0,
        delay: delay || 0,
        useNativeDriver: true
      })
    ])).start();
  };

  _startAndRepeat = (): void => {
    const { Component } = this.state;
    !Component && this._triggerAnimation();
  };

  _measureView = (viewName: string, event: Object): void => {
    const { x, y, height, width } = event.nativeEvent.layout;
    this.setState(
      () => ({
        [viewName]: {
          x,
          y,
          height,
          width
        },
        [`is${viewName}Measured`]: true
      }),
      () => {
        this._setAnimationPositions();
      }
    );
  };

  _setAnimationPositions = (): void => {
    const {
      ContainerComponent,
      AnimatedComponent,
      isContainerComponentMeasured,
      isAnimatedComponentMeasured
    } = this.state;
    if (!isContainerComponentMeasured || !isAnimatedComponentMeasured) {
      return;
    }
    const startPosition = -(ContainerComponent.x + AnimatedComponent.width);
    const stopPosition =
      ContainerComponent.x + ContainerComponent.width + AnimatedComponent.width;
    this.setState(
      () => ({
        startPosition,
        stopPosition
      }),
      () => {
        this.position.setValue(startPosition);
        this._startAndRepeat();
      }
    );
  };

  _registerPlaceholder = (placeholder: React.Element<*>): void => {
    const { replace } = this.props;
    if (!replace) {
      return;
    }
    this.placeholders.push(placeholder);
  };

  _replacePlaceholders = (): void => {
    try {
      this.placeholders.forEach(placeholder => {
        placeholder._resolve();
      });
    } catch (e) {
      console.log('Something went wrong');
    }
  };
}

PlaceholderContainer.childContextTypes = {
  position: PropTypes.object.isRequired,
  animatedComponent: PropTypes.object.isRequired,
  registerPlaceholder: PropTypes.func.isRequired
};

const styles = StyleSheet.create({
  offscreen: {
    position: 'absolute',
    left: -1000
  }
});
<commit_msg>set interaction to false<commit_after>/*
* @flow
*/

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
  Text,
  View,
  StyleSheet,
  Animated,
  Dimensions,
  Platform
} from 'react-native';

const screenWidth = Dimensions.get('window').width;

type PlaceholderContainerProps = {
  duration: number,
  delay: number,
  style: Object,
  animatedComponent: React.Element<*>,
  loader: Function,
  replace: boolean
};

type PlaceholderContainerState = {
  containerComponent: Object,
  animatedComponent: Object,
  startPosition: number,
  stopPosition: number,
  isContainerMeasured: boolean,
  isAnimatedComponentMeasured: boolean,
  Component: React.Element<*>
};

export default class PlaceholderContainer extends Component {
  props: PlaceholderContainerProps;
  state: PlaceholderContainerState;
  position: Animated.Value;
  placeholders: Array<React.Element<*>>;
  constructor(props: PlaceholderContainerProps) {
    super(props);
    this.state = {
      ContainerComponent: { x: 0, y: 0, width: 0, height: 0 },
      AnimatedComponent: { x: 0, y: 0, width: 0, height: 0 },
      startPosition: 0,
      stopPosition: 0,
      isContainerComponentMeasured: false,
      isAnimatedComponentMeasured: false,
      Component: null
    };
    this.position = new Animated.Value(0);
    this.placeholders = [];
    this._measureContainerComponent = this._measureView.bind(
      null,
      'ContainerComponent'
    );
    this._measureAnimatedComponent = this._measureView.bind(
      null,
      'AnimatedComponent'
    );
  }
  getChildContext(): Object {
    return {
      position: this.position,
      animatedComponent: this.props.animatedComponent,
      registerPlaceholder: this._registerPlaceholder
    };
  }
  componentDidMount(): void {
    const { loader, replace } = this.props;
    loader &&
      Promise.resolve(loader).then(Component => {
        !replace ? this.setState({ Component }) : this._replacePlaceholders();
      });
  }

  componentWillUnmount(): void {
    this.position.stopAnimation();
  }

  render(): React.Element<*> {
    const { style, elements, animatedComponent, children } = this.props;
    const { Component, isAnimatedComponentMeasured } = this.state;
    return (
      <View
        ref={ref => {
          this.containerRef = ref;
        }}
        onLayout={this._measureContainerComponent}
        style={style}
      >
        {!isAnimatedComponentMeasured &&
          <View
            ref={ref => {
              this.componentRef = ref;
            }}
            onLayout={this._measureAnimatedComponent}
            style={styles.offscreen}
          >
            {animatedComponent}
          </View>}
        {(Component && Component) || children}
      </View>
    );
  }

  _triggerAnimation = (): void => {
    const { duration, delay } = this.props;
    const { startPosition, stopPosition } = this.state;
    Animated.loop(Animated.sequence([
      Animated.timing(this.position, {
        toValue: stopPosition || screenWidth,
        duration: duration,
        useNativeDriver: true,
        isInteraction: false
      }),
      Animated.timing(this.position, {
        toValue: startPosition || 0,
        duration: 0,
        delay: delay || 0,
        useNativeDriver: true,
        isInteraction: false
      })
    ])).start();
  };

  _startAndRepeat = (): void => {
    const { Component } = this.state;
    !Component && this._triggerAnimation();
  };

  _measureView = (viewName: string, event: Object): void => {
    const { x, y, height, width } = event.nativeEvent.layout;
    this.setState(
      () => ({
        [viewName]: {
          x,
          y,
          height,
          width
        },
        [`is${viewName}Measured`]: true
      }),
      () => {
        this._setAnimationPositions();
      }
    );
  };

  _setAnimationPositions = (): void => {
    const {
      ContainerComponent,
      AnimatedComponent,
      isContainerComponentMeasured,
      isAnimatedComponentMeasured
    } = this.state;
    if (!isContainerComponentMeasured || !isAnimatedComponentMeasured) {
      return;
    }
    const startPosition = -(ContainerComponent.x + AnimatedComponent.width);
    const stopPosition =
      ContainerComponent.x + ContainerComponent.width + AnimatedComponent.width;
    this.setState(
      () => ({
        startPosition,
        stopPosition
      }),
      () => {
        this.position.setValue(startPosition);
        this._startAndRepeat();
      }
    );
  };

  _registerPlaceholder = (placeholder: React.Element<*>): void => {
    const { replace } = this.props;
    if (!replace) {
      return;
    }
    this.placeholders.push(placeholder);
  };

  _replacePlaceholders = (): void => {
    try {
      this.placeholders.forEach(placeholder => {
        placeholder._resolve();
      });
    } catch (e) {
      console.log('Something went wrong');
    }
  };
}

PlaceholderContainer.childContextTypes = {
  position: PropTypes.object.isRequired,
  animatedComponent: PropTypes.object.isRequired,
  registerPlaceholder: PropTypes.func.isRequired
};

const styles = StyleSheet.create({
  offscreen: {
    position: 'absolute',
    left: -1000
  }
});
<|endoftext|>


<commit_before>/**
 * Copyright JS Foundation and other contributors, http://js.foundation
 *
 * Licensed 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.
 **/

module.exports = function(RED) {
    "use strict";

    function ChangeNode(n) {
        RED.nodes.createNode(this, n);
        var node = this;

        this.rules = n.rules;
        var rule;
        if (!this.rules) {
            rule = {
                t:(n.action=="replace"?"set":n.action),
                p:n.property||""
            }

            if ((rule.t === "set")||(rule.t === "move")) {
                rule.to = n.to||"";
            } else if (rule.t === "change") {
                rule.from = n.from||"";
                rule.to = n.to||"";
                rule.re = (n.reg===null||n.reg);
            }
            this.rules = [rule];
        }

        var valid = true;
        for (var i=0;i<this.rules.length;i++) {
            rule = this.rules[i];
            // Migrate to type-aware rules
            if (!rule.pt) {
                rule.pt = "msg";
            }
            if (rule.t === "change" && rule.re) {
                rule.fromt = 're';
                delete rule.re;
            }
            if (rule.t === "set" && !rule.tot) {
                if (rule.to.indexOf("msg.") === 0 && !rule.tot) {
                    rule.to = rule.to.substring(4);
                    rule.tot = "msg";
                }
            }
            if (!rule.tot) {
                rule.tot = "str";
            }
            if (!rule.fromt) {
                rule.fromt = "str";
            }
            if (rule.t === "change" && rule.fromt !== 'msg' && rule.fromt !== 'flow' && rule.fromt !== 'global') {
                rule.fromRE = rule.from;
                if (rule.fromt !== 're') {
                    rule.fromRE = rule.fromRE.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
                }
                try {
                    rule.fromRE = new RegExp(rule.fromRE, "g");
                } catch (e) {
                    valid = false;
                    this.error(RED._("change.errors.invalid-from",{error:e.message}));
                }
            }
            if (rule.tot === 'num') {
                rule.to = Number(rule.to);
            } else if (rule.tot === 'json' || rule.tot === 'bin') {
                try {
                    // check this is parsable JSON
                    JSON.parse(rule.to);
                } catch(e2) {
                    valid = false;
                    this.error(RED._("change.errors.invalid-json"));
                }
            } else if (rule.tot === 'bool') {
                rule.to = /^true$/i.test(rule.to);
            } else if (rule.tot === 'jsonata') {
                try {
                    rule.to = RED.util.prepareJSONataExpression(rule.to,this);
                } catch(e) {
                    valid = false;
                    this.error(RED._("change.errors.invalid-expr",{error:e.message}));
                }
            } else if (rule.tot === 'env') {
                rule.to = RED.util.evaluateNodeProperty(rule.to,'env');
            }
        }

        function applyRule(msg,rule) {
            try {
                var property = rule.p;
                var value = rule.to;
                if (rule.tot === 'json') {
                    value = JSON.parse(rule.to);
                } else if (rule.tot === 'bin') {
                    value = Buffer.from(JSON.parse(rule.to))
                }
                var current;
                var fromValue;
                var fromType;
                var fromRE;
                if (rule.tot === "msg") {
                    value = RED.util.getMessageProperty(msg,rule.to);
                } else if (rule.tot === 'flow') {
                    value = node.context().flow.get(rule.to);
                } else if (rule.tot === 'global') {
                    value = node.context().global.get(rule.to);
                } else if (rule.tot === 'date') {
                    value = Date.now();
                } else if (rule.tot === 'jsonata') {
                    try{
                        value = RED.util.evaluateJSONataExpression(rule.to,msg);
                    } catch(err) {
                        node.error(RED._("change.errors.invalid-expr",{error:err.message}));
                        return;
                    }
                }
                if (rule.t === 'change') {
                    if (rule.fromt === 'msg' || rule.fromt === 'flow' || rule.fromt === 'global') {
                        if (rule.fromt === "msg") {
                            fromValue = RED.util.getMessageProperty(msg,rule.from);
                        } else if (rule.fromt === 'flow') {
                            fromValue = node.context().flow.get(rule.from);
                        } else if (rule.fromt === 'global') {
                            fromValue = node.context().global.get(rule.from);
                        }
                        if (typeof fromValue === 'number' || fromValue instanceof Number) {
                            fromType = 'num';
                        } else if (typeof fromValue === 'boolean') {
                            fromType = 'bool'
                        } else if (fromValue instanceof RegExp) {
                            fromType = 're';
                            fromRE = fromValue;
                        } else if (typeof fromValue === 'string') {
                            fromType = 'str';
                            fromRE = fromValue.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
                            try {
                                fromRE = new RegExp(fromRE, "g");
                            } catch (e) {
                                valid = false;
                                node.error(RED._("change.errors.invalid-from",{error:e.message}));
                                return;
                            }
                        } else {
                            node.error(RED._("change.errors.invalid-from",{error:"unsupported type: "+(typeof fromValue)}));
                            return
                        }
                    } else {
                        fromType = rule.fromt;
                        fromValue = rule.from;
                        fromRE = rule.fromRE;
                    }
                }
                if (rule.pt === 'msg') {
                    if (rule.t === 'delete') {
                        RED.util.setMessageProperty(msg,property,undefined);
                    } else if (rule.t === 'set') {
                        RED.util.setMessageProperty(msg,property,value);
                    } else if (rule.t === 'change') {
                        current = RED.util.getMessageProperty(msg,property);
                        if (typeof current === 'string') {
                            if ((fromType === 'num' || fromType === 'bool' || fromType === 'str') && current === fromValue) {
                                // str representation of exact from number/boolean
                                // only replace if they match exactly
                                RED.util.setMessageProperty(msg,property,value);
                            } else {
                                current = current.replace(fromRE,value);
                                RED.util.setMessageProperty(msg,property,current);
                            }
                        } else if ((typeof current === 'number' || current instanceof Number) && fromType === 'num') {
                            if (current == Number(fromValue)) {
                                RED.util.setMessageProperty(msg,property,value);
                            }
                        } else if (typeof current === 'boolean' && fromType === 'bool') {
                            if (current.toString() === fromValue) {
                                RED.util.setMessageProperty(msg,property,value);
                            }
                        }
                    }
                }
                else {
                    var target;
                    if (rule.pt === 'flow') {
                        target = node.context().flow;
                    } else if (rule.pt === 'global') {
                        target = node.context().global;
                    }
                    if (target) {
                        if (rule.t === 'delete') {
                            target.set(property,undefined);
                        } else if (rule.t === 'set') {
                            target.set(property,value);
                        } else if (rule.t === 'change') {
                            current = target.get(property);
                            if (typeof current === 'string') {
                                if ((fromType === 'num' || fromType === 'bool' || fromType === 'str') && current === fromValue) {
                                    // str representation of exact from number/boolean
                                    // only replace if they match exactly
                                    target.set(property,value);
                                } else {
                                    current = current.replace(fromRE,value);
                                    target.set(property,current);
                                }
                            } else if ((typeof current === 'number' || current instanceof Number) && fromType === 'num') {
                                if (current == Number(fromValue)) {
                                    target.set(property,value);
                                }
                            } else if (typeof current === 'boolean' && fromType === 'bool') {
                                if (current.toString() === fromValue) {
                                    target.set(property,value);
                                }
                            }
                        }
                    }
                }
            } catch(err) {/*console.log(err.stack)*/}
            return msg;
        }
        if (valid) {
            this.on('input', function(msg) {
                for (var i=0; i<this.rules.length; i++) {
                    if (this.rules[i].t === "move") {
                        var r = this.rules[i];
                        if ((r.tot !== r.pt) || (r.p.indexOf(r.to) !== -1)) {
                            msg = applyRule(msg,{t:"set", p:r.to, pt:r.tot, to:r.p, tot:r.pt});
                            applyRule(msg,{t:"delete", p:r.p, pt:r.pt});
                        }
                        else { // 2 step move if we are moving from a child
                            msg = applyRule(msg,{t:"set", p:"_temp_move", pt:r.tot, to:r.p, tot:r.pt});
                            applyRule(msg,{t:"delete", p:r.p, pt:r.pt});
                            msg = applyRule(msg,{t:"set", p:r.to, pt:r.tot, to:"_temp_move", tot:r.pt});
                            applyRule(msg,{t:"delete", p:"_temp_move", pt:r.pt});
                        }
                    } else {
                        msg = applyRule(msg,this.rules[i]);
                    }
                    if (msg === null) {
                        return;
                    }
                }
                node.send(msg);
            });
        }
    }
    RED.nodes.registerType("change", ChangeNode);
};
<commit_msg>Ensure runtime errors in Change node can be caught Fixes #1769<commit_after>/**
 * Copyright JS Foundation and other contributors, http://js.foundation
 *
 * Licensed 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.
 **/

module.exports = function(RED) {
    "use strict";

    function ChangeNode(n) {
        RED.nodes.createNode(this, n);
        var node = this;

        this.rules = n.rules;
        var rule;
        if (!this.rules) {
            rule = {
                t:(n.action=="replace"?"set":n.action),
                p:n.property||""
            }

            if ((rule.t === "set")||(rule.t === "move")) {
                rule.to = n.to||"";
            } else if (rule.t === "change") {
                rule.from = n.from||"";
                rule.to = n.to||"";
                rule.re = (n.reg===null||n.reg);
            }
            this.rules = [rule];
        }

        var valid = true;
        for (var i=0;i<this.rules.length;i++) {
            rule = this.rules[i];
            // Migrate to type-aware rules
            if (!rule.pt) {
                rule.pt = "msg";
            }
            if (rule.t === "change" && rule.re) {
                rule.fromt = 're';
                delete rule.re;
            }
            if (rule.t === "set" && !rule.tot) {
                if (rule.to.indexOf("msg.") === 0 && !rule.tot) {
                    rule.to = rule.to.substring(4);
                    rule.tot = "msg";
                }
            }
            if (!rule.tot) {
                rule.tot = "str";
            }
            if (!rule.fromt) {
                rule.fromt = "str";
            }
            if (rule.t === "change" && rule.fromt !== 'msg' && rule.fromt !== 'flow' && rule.fromt !== 'global') {
                rule.fromRE = rule.from;
                if (rule.fromt !== 're') {
                    rule.fromRE = rule.fromRE.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
                }
                try {
                    rule.fromRE = new RegExp(rule.fromRE, "g");
                } catch (e) {
                    valid = false;
                    this.error(RED._("change.errors.invalid-from",{error:e.message}));
                }
            }
            if (rule.tot === 'num') {
                rule.to = Number(rule.to);
            } else if (rule.tot === 'json' || rule.tot === 'bin') {
                try {
                    // check this is parsable JSON
                    JSON.parse(rule.to);
                } catch(e2) {
                    valid = false;
                    this.error(RED._("change.errors.invalid-json"));
                }
            } else if (rule.tot === 'bool') {
                rule.to = /^true$/i.test(rule.to);
            } else if (rule.tot === 'jsonata') {
                try {
                    rule.to = RED.util.prepareJSONataExpression(rule.to,this);
                } catch(e) {
                    valid = false;
                    this.error(RED._("change.errors.invalid-expr",{error:e.message}));
                }
            } else if (rule.tot === 'env') {
                rule.to = RED.util.evaluateNodeProperty(rule.to,'env');
            }
        }

        function applyRule(msg,rule) {
            try {
                var property = rule.p;
                var value = rule.to;
                if (rule.tot === 'json') {
                    value = JSON.parse(rule.to);
                } else if (rule.tot === 'bin') {
                    value = Buffer.from(JSON.parse(rule.to))
                }
                var current;
                var fromValue;
                var fromType;
                var fromRE;
                if (rule.tot === "msg") {
                    value = RED.util.getMessageProperty(msg,rule.to);
                } else if (rule.tot === 'flow') {
                    value = node.context().flow.get(rule.to);
                } else if (rule.tot === 'global') {
                    value = node.context().global.get(rule.to);
                } else if (rule.tot === 'date') {
                    value = Date.now();
                } else if (rule.tot === 'jsonata') {
                    try{
                        value = RED.util.evaluateJSONataExpression(rule.to,msg);
                    } catch(err) {
                        node.error(RED._("change.errors.invalid-expr",{error:err.message}),msg);
                        return;
                    }
                }
                if (rule.t === 'change') {
                    if (rule.fromt === 'msg' || rule.fromt === 'flow' || rule.fromt === 'global') {
                        if (rule.fromt === "msg") {
                            fromValue = RED.util.getMessageProperty(msg,rule.from);
                        } else if (rule.fromt === 'flow') {
                            fromValue = node.context().flow.get(rule.from);
                        } else if (rule.fromt === 'global') {
                            fromValue = node.context().global.get(rule.from);
                        }
                        if (typeof fromValue === 'number' || fromValue instanceof Number) {
                            fromType = 'num';
                        } else if (typeof fromValue === 'boolean') {
                            fromType = 'bool'
                        } else if (fromValue instanceof RegExp) {
                            fromType = 're';
                            fromRE = fromValue;
                        } else if (typeof fromValue === 'string') {
                            fromType = 'str';
                            fromRE = fromValue.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
                            try {
                                fromRE = new RegExp(fromRE, "g");
                            } catch (e) {
                                valid = false;
                                node.error(RED._("change.errors.invalid-from",{error:e.message}),msg);
                                return;
                            }
                        } else {
                            node.error(RED._("change.errors.invalid-from",{error:"unsupported type: "+(typeof fromValue)}),msg);
                            return
                        }
                    } else {
                        fromType = rule.fromt;
                        fromValue = rule.from;
                        fromRE = rule.fromRE;
                    }
                }
                if (rule.pt === 'msg') {
                    if (rule.t === 'delete') {
                        RED.util.setMessageProperty(msg,property,undefined);
                    } else if (rule.t === 'set') {
                        RED.util.setMessageProperty(msg,property,value);
                    } else if (rule.t === 'change') {
                        current = RED.util.getMessageProperty(msg,property);
                        if (typeof current === 'string') {
                            if ((fromType === 'num' || fromType === 'bool' || fromType === 'str') && current === fromValue) {
                                // str representation of exact from number/boolean
                                // only replace if they match exactly
                                RED.util.setMessageProperty(msg,property,value);
                            } else {
                                current = current.replace(fromRE,value);
                                RED.util.setMessageProperty(msg,property,current);
                            }
                        } else if ((typeof current === 'number' || current instanceof Number) && fromType === 'num') {
                            if (current == Number(fromValue)) {
                                RED.util.setMessageProperty(msg,property,value);
                            }
                        } else if (typeof current === 'boolean' && fromType === 'bool') {
                            if (current.toString() === fromValue) {
                                RED.util.setMessageProperty(msg,property,value);
                            }
                        }
                    }
                }
                else {
                    var target;
                    if (rule.pt === 'flow') {
                        target = node.context().flow;
                    } else if (rule.pt === 'global') {
                        target = node.context().global;
                    }
                    if (target) {
                        if (rule.t === 'delete') {
                            target.set(property,undefined);
                        } else if (rule.t === 'set') {
                            target.set(property,value);
                        } else if (rule.t === 'change') {
                            current = target.get(property);
                            if (typeof current === 'string') {
                                if ((fromType === 'num' || fromType === 'bool' || fromType === 'str') && current === fromValue) {
                                    // str representation of exact from number/boolean
                                    // only replace if they match exactly
                                    target.set(property,value);
                                } else {
                                    current = current.replace(fromRE,value);
                                    target.set(property,current);
                                }
                            } else if ((typeof current === 'number' || current instanceof Number) && fromType === 'num') {
                                if (current == Number(fromValue)) {
                                    target.set(property,value);
                                }
                            } else if (typeof current === 'boolean' && fromType === 'bool') {
                                if (current.toString() === fromValue) {
                                    target.set(property,value);
                                }
                            }
                        }
                    }
                }
            } catch(err) {/*console.log(err.stack)*/}
            return msg;
        }
        if (valid) {
            this.on('input', function(msg) {
                for (var i=0; i<this.rules.length; i++) {
                    if (this.rules[i].t === "move") {
                        var r = this.rules[i];
                        if ((r.tot !== r.pt) || (r.p.indexOf(r.to) !== -1)) {
                            msg = applyRule(msg,{t:"set", p:r.to, pt:r.tot, to:r.p, tot:r.pt});
                            applyRule(msg,{t:"delete", p:r.p, pt:r.pt});
                        }
                        else { // 2 step move if we are moving from a child
                            msg = applyRule(msg,{t:"set", p:"_temp_move", pt:r.tot, to:r.p, tot:r.pt});
                            applyRule(msg,{t:"delete", p:r.p, pt:r.pt});
                            msg = applyRule(msg,{t:"set", p:r.to, pt:r.tot, to:"_temp_move", tot:r.pt});
                            applyRule(msg,{t:"delete", p:"_temp_move", pt:r.pt});
                        }
                    } else {
                        msg = applyRule(msg,this.rules[i]);
                    }
                    if (msg === null) {
                        return;
                    }
                }
                node.send(msg);
            });
        }
    }
    RED.nodes.registerType("change", ChangeNode);
};
<|endoftext|>


<commit_before>define([
    'crafty'
], function(Crafty) {

  'use strict';

  var TILE_WIDTH = 32;
  var ASSETS = {
    'sprites': {
      'images/game/player.png': {
        'tile': TILE_WIDTH,
        'tileh': TILE_WIDTH,
        'map': {'SpritePlayer': [0, 0]},
      },
      'images/game/wall.png': {
        'tile': TILE_WIDTH,
        'tileh': TILE_WIDTH,
        'map': {'SpriteWall': [0, 0]}
      },
      'images/game/door.png': {
      'tile': TILE_WIDTH,
      'tileh': TILE_WIDTH,
      'map': {'SpriteDoor': [0,0]}
      }
    }
  }

  var _player;
  var _modelAdpt;
  var _playerModelAdpt;

  function initCrafty() {
    Crafty.c('Player', {
      init: function() {
        this.requires('2D, Canvas, Fourway, Collision, SpritePlayer, SpriteAnimation');

        this.fourway(_playerModelAdpt.getSpeed());

        this.reel('PlayerMovingRight',600, 0, 0, 1);
        this.reel('PlayerMovingUp',   600, 1, 0, 1);
        this.reel('PlayerMovingLeft', 600, 2, 0, 1);
        this.reel('PlayerMovingDown', 600, 3, 0, 1);

        this.onHit('Solid', this.stopMovement);
        this.onHit('Door', this.useDoor);

        this.bind('NewDirection', function(data) {
          if (data.x > 0) {
            this.animate('PlayerMovingRight', -1);
          } else if (data.x < 0) {
            this.animate('PlayerMovingLeft', -1);
          } else if (data.y > 0) {
            this.animate('PlayerMovingDown', -1);
          } else if (data.y < 0) {
            this.animate('PlayerMovingUp', -1);
          } else {
            this.pauseAnimation();
          }
        });

        this.bind('Moved', function(oldPosition) {
          _playerModelAdpt.setX(this.x);
          _playerModelAdpt.setY(this.y);
        });
      },

      stopMovement: function() {
        if (this._movement) {
          this.x -= this._movement.x;
          this.y -= this._movement.y;
        }
      },

      useDoor: function(doorParts) {
        console.log(doorParts[0].obj.doorID);
        _modelAdpt.onDoorVisit(doorParts[0].obj.doorID);
      }

    });

    Crafty.c('Wall', {
      init: function() {
        this.requires('2D, Canvas, Solid, SpriteWall');
      }
    });

    Crafty.c('Door', {
      init: function() {
        this.requires('2D, Canvas, SpriteDoor');
      }
    });

    Crafty.init(_modelAdpt.getDimensions().width * TILE_WIDTH,
                _modelAdpt.getDimensions().height * TILE_WIDTH,
                document.getElementById('game-stage'));

    Crafty.load(ASSETS, function() {
    });

  }

  function start() {
  }

  function loadRoom(roomConfig) {
    Crafty('obj').each(function() { this.destroy(); });
    Crafty.background(roomConfig.background);
    setupBarriers(roomConfig.doors);
    _player = Crafty.e('Player').attr({x: _playerModelAdpt.getX(), y: _playerModelAdpt.getY()});
  }

  function makePlayerView(playerModelAdpt) {
    _playerModelAdpt = playerModelAdpt;

    _player = Crafty.e('Player');

    return _player;
  }

  function setupBarriers(gateways) {
    var widthInTiles = _modelAdpt.getDimensions().width;
    var heightInTiles = _modelAdpt.getDimensions().height;

    for (var j = 0; j < widthInTiles; j++) {
      if(!('north' in gateways && (j == widthInTiles/2 || j == widthInTiles/2-1))) {
        Crafty.e('Wall').attr({x: j * TILE_WIDTH, y: 0});
      }
      else {
        Crafty.e('Door').attr({x: j * TILE_WIDTH, y: 0, doorID: 'north'});
      }
      if(!('south' in gateways && (j == widthInTiles/2 || j == widthInTiles/2-1))) {
        Crafty.e('Wall').attr({x: j * TILE_WIDTH, y: (heightInTiles - 1) * TILE_WIDTH});
      }
      else {
        Crafty.e('Door').attr({x: j * TILE_WIDTH, y: (heightInTiles - 1) * TILE_WIDTH, doorID: 'south'});
      }
    }

    for (var i = 0; i < heightInTiles; i++) {
      if(!('west' in gateways && (i == heightInTiles/2 || i == heightInTiles/2-1))) {
        Crafty.e('Wall').attr({x: 0, y: i * TILE_WIDTH});
      }
      else {
        Crafty.e('Door').attr({x: 0, y: i * TILE_WIDTH, doorID: 'west'});
      }
      if(!('east' in gateways && (i == heightInTiles/2 || i == heightInTiles/2-1))) {
        Crafty.e('Wall').attr({x: (widthInTiles - 1) * TILE_WIDTH, y: i * TILE_WIDTH});
      }
      else {
        Crafty.e('Door').attr({x: (widthInTiles - 1) * TILE_WIDTH, y: i * TILE_WIDTH, doorID: 'east'});
      }
    }

  }

  return function GameView(modelAdpt) {
    _modelAdpt = modelAdpt;

    document.getElementById('speed-inc').addEventListener('click', function() {
      _playerModelAdpt.onSpeedIncClick();
    });

    document.getElementById('speed-dec').addEventListener('click', function() {
      _playerModelAdpt.onSpeedDecClick();
    });

    initCrafty();

    this.loadRoom = loadRoom;
    this.start = start;
    this.makePlayerView = makePlayerView;
  }
});
<commit_msg>Actually divided pixel width by tile width.<commit_after>define([
    'crafty'
], function(Crafty) {

  'use strict';

  var TILE_WIDTH = 32;
  var ASSETS = {
    'sprites': {
      'images/game/player.png': {
        'tile': TILE_WIDTH,
        'tileh': TILE_WIDTH,
        'map': {'SpritePlayer': [0, 0]},
      },
      'images/game/wall.png': {
        'tile': TILE_WIDTH,
        'tileh': TILE_WIDTH,
        'map': {'SpriteWall': [0, 0]}
      },
      'images/game/door.png': {
      'tile': TILE_WIDTH,
      'tileh': TILE_WIDTH,
      'map': {'SpriteDoor': [0,0]}
      }
    }
  }

  var _player;
  var _modelAdpt;
  var _playerModelAdpt;

  function initCrafty() {
    Crafty.c('Player', {
      init: function() {
        this.requires('2D, Canvas, Fourway, Collision, SpritePlayer, SpriteAnimation');

        this.fourway(_playerModelAdpt.getSpeed());

        this.reel('PlayerMovingRight',600, 0, 0, 1);
        this.reel('PlayerMovingUp',   600, 1, 0, 1);
        this.reel('PlayerMovingLeft', 600, 2, 0, 1);
        this.reel('PlayerMovingDown', 600, 3, 0, 1);

        this.onHit('Solid', this.stopMovement);
        this.onHit('Door', this.useDoor);

        this.bind('NewDirection', function(data) {
          if (data.x > 0) {
            this.animate('PlayerMovingRight', -1);
          } else if (data.x < 0) {
            this.animate('PlayerMovingLeft', -1);
          } else if (data.y > 0) {
            this.animate('PlayerMovingDown', -1);
          } else if (data.y < 0) {
            this.animate('PlayerMovingUp', -1);
          } else {
            this.pauseAnimation();
          }
        });

        this.bind('Moved', function(oldPosition) {
          _playerModelAdpt.setX(this.x);
          _playerModelAdpt.setY(this.y);
        });
      },

      stopMovement: function() {
        if (this._movement) {
          this.x -= this._movement.x;
          this.y -= this._movement.y;
        }
      },

      useDoor: function(doorParts) {
        console.log(doorParts[0].obj.doorID);
        _modelAdpt.onDoorVisit(doorParts[0].obj.doorID);
      }

    });

    Crafty.c('Wall', {
      init: function() {
        this.requires('2D, Canvas, Solid, SpriteWall');
      }
    });

    Crafty.c('Door', {
      init: function() {
        this.requires('2D, Canvas, SpriteDoor');
      }
    });

    Crafty.init(_modelAdpt.getDimensions().width,
                _modelAdpt.getDimensions().height,
                document.getElementById('game-stage'));

    Crafty.load(ASSETS, function() {
    });

  }

  function start() {
  }

  function loadRoom(roomConfig) {
    Crafty('obj').each(function() { this.destroy(); });
    Crafty.background(roomConfig.background);
    setupBarriers(roomConfig.doors);
    _player = Crafty.e('Player').attr({x: _playerModelAdpt.getX(), y: _playerModelAdpt.getY()});
  }

  function makePlayerView(playerModelAdpt) {
    _playerModelAdpt = playerModelAdpt;

    _player = Crafty.e('Player');

    return _player;
  }

  function setupBarriers(gateways) {
    var widthInTiles = _modelAdpt.getDimensions().width/TILE_WIDTH;
    var heightInTiles = _modelAdpt.getDimensions().height/TILE_WIDTH;

    for (var j = 0; j < widthInTiles; j++) {
      if(!('north' in gateways && (j == widthInTiles/2 || j == widthInTiles/2-1))) {
        Crafty.e('Wall').attr({x: j * TILE_WIDTH, y: 0});
      }
      else {
        Crafty.e('Door').attr({x: j * TILE_WIDTH, y: 0, doorID: 'north'});
      }
      if(!('south' in gateways && (j == widthInTiles/2 || j == widthInTiles/2-1))) {
        Crafty.e('Wall').attr({x: j * TILE_WIDTH, y: (heightInTiles - 1) * TILE_WIDTH});
      }
      else {
        Crafty.e('Door').attr({x: j * TILE_WIDTH, y: (heightInTiles - 1) * TILE_WIDTH, doorID: 'south'});
      }
    }

    for (var i = 0; i < heightInTiles; i++) {
      if(!('west' in gateways && (i == heightInTiles/2 || i == heightInTiles/2-1))) {
        Crafty.e('Wall').attr({x: 0, y: i * TILE_WIDTH});
      }
      else {
        Crafty.e('Door').attr({x: 0, y: i * TILE_WIDTH, doorID: 'west'});
      }
      if(!('east' in gateways && (i == heightInTiles/2 || i == heightInTiles/2-1))) {
        Crafty.e('Wall').attr({x: (widthInTiles - 1) * TILE_WIDTH, y: i * TILE_WIDTH});
      }
      else {
        Crafty.e('Door').attr({x: (widthInTiles - 1) * TILE_WIDTH, y: i * TILE_WIDTH, doorID: 'east'});
      }
    }

  }

  return function GameView(modelAdpt) {
    _modelAdpt = modelAdpt;

    document.getElementById('speed-inc').addEventListener('click', function() {
      _playerModelAdpt.onSpeedIncClick();
    });

    document.getElementById('speed-dec').addEventListener('click', function() {
      _playerModelAdpt.onSpeedDecClick();
    });

    initCrafty();

    this.loadRoom = loadRoom;
    this.start = start;
    this.makePlayerView = makePlayerView;
  }
});
<|endoftext|>


<commit_before>/**
 * Main JS file for Casper behaviours
 */

/* globals jQuery, document */
(function ($) {
    "use strict";

    var animEndEventNames = {
            'WebkitAnimation': 'webkitAnimationEnd',
            'OAnimation': 'oAnimationEnd',
            'msAnimation': 'MSAnimationEnd',
            'animation': 'animationend'
        },
        animEndEventName = animEndEventNames[Modernizr.prefixed('animation')],
        onEndAnimation = function (el, callback) {
            var onEndCallbackFn = function (ev) {
                if (ev.target != this) {
                    return;
                }
                this.removeEventListener(animEndEventName, onEndCallbackFn);
                if (callback && typeof callback === 'function') {
                    callback.call();
                }
            };
            el.addEventListener(animEndEventName, onEndCallbackFn);
        };
    var $document = $(document),
        containers = [].slice.call($('.slide')),
        containersCount = containers.length,
        current = 0,
        isAnimating = false,
        pageTriggers = [];
    var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

    $document.ready(function () {

        $('.menu-icon').on('click', function (e) {
            $('body').toggleClass('open');
            $(this).toggleClass('open');
        });

        $('pre code').each(function (i, block) {
            hljs.highlightBlock(block);
        });

        initSlider();

        bindScroll();

        redesignPagination();

        loadCover();

        lazyLoadDefault();

        addBanner();

    });

    document.addEventListener('keydown', function (ev) {
        var keyCode = ev.keyCode || ev.which,
            isNavOpen = $('body').hasClass('open');

        switch (keyCode) {
            // left key
        case 37:
            if (current > 0 && !isNavOpen) {
                navigate(pageTriggers[current - 1]);
            }
            break;
            // right key
        case 39:
            if (current < containersCount - 1 && !isNavOpen) {
                navigate(pageTriggers[current + 1]);
            }
            break;
        }
    });

    function initSlider() {
        var thumbString = '';
        containers.forEach(function (item, index) {
            thumbString += '';
        });
        if (containers.length > 1) {
            var ctrlString = '';
            if (!isMobile) {
                 ctrlString = '
<svg class="icon icon-chevron-left"><use xlink:href="#icon-chevron-left"></use></svg><svg class="icon icon-chevron-right"><use xlink:href="#icon-chevron-right"></use></svg>
';
            }
            $('#slideshow').append([ctrlString, '
', thumbString, '
'].join(''));
            bindEvent();
        }
        pageTriggers = [].slice.call($('.thumb a'));
        $(containers[current]).addClass('slider--current');
        $('.slide').each(function (index, item) {
            var coverEl = $(item).find('.bg-overlay ');
            if (coverEl.hasClass('loaded')) {
                return;
            }
            var url = coverEl.attr('url');
            var img = new Image();
            img.src = url;
            img.onload = function() {
                coverEl.css({
                    'background-image': 'url(' + url + ')',
                });
                coverEl.addClass('loaded');
                if (index === 0) {
                    coverEl.parent().addClass('loaded');
                }
            }
        });
    }

    function bindEvent() {
        $('.js-ctrl-left').on('click', function () {
            if (current > 0) {
                navigate(pageTriggers[current - 1]);
            }
        });
        $('.js-ctrl-right').on('click', function () {
            if (current < containersCount - 1) {
                navigate(pageTriggers[current + 1]);
            }
        });

        if (isMobile) {
            $("#slideshow").swipe({
                //Generic swipe handler for all directions
                swipe: function (event, direction, distance, duration, fingerCount, fingerData) {
                    if (direction == 'left') {
                        if (current < containersCount - 1) {
                            navigate(pageTriggers[current + 1]);
                        }
                    } else if (direction == 'right') {
                        if (current > 0) {
                            navigate(pageTriggers[current - 1]);
                        }
                    } else if (direction == 'down') {
                        var sT = $('html').scrollTop();
                        if(sT == 0) {
                            $('body').toggleClass('open');
                            $('.menu-icon').toggleClass('open');
                        } else {
                           $('html').animate({'scrollTop': 0},500);
                        }

                    } else if(direction == 'up'){
                        return false;
                    }
                },
                threshold: 0,
                allowPageScroll: 'vertical',
            });
        }
    }

    function bindScroll() {
        var articleHeight = $('.js-article').height() - 80;
        var contentHeight = $('.content').height();
        var coverLoaded = false;
        $(document.body).on('scroll', function(e) {
            var top = e.target.scrollTop;
            var wH = window.innerHeight;
            var fixHeight = window.innerHeight + 70;
            if (!isMobile) {
                if ( top > fixHeight) {
                    $('.js-nav').addClass('fixed');
                } else if ($('.js-nav').hasClass('fixed')) {
                    $('.js-nav').removeClass('fixed');
                }
            }
            if (top > fixHeight) {
                $('.js-progress').css({
                    width: parseInt(((top - fixHeight) / articleHeight) * 100) + '%'
                });
            }
            if (top > 70 && top <= wH) {
                $('.overlay').css({
                    opacity: 0.2 + 0.8 * (top / wH),
                });
                $('.js-post-meta').css({
                    opacity: 1 - 0.8 * (top / wH),
                    transform: 'translateY(' + top / 3 + 'px)',
                });
                $('.js-post-cover').css({
                    backgroundPositionY: '-' + top / 4 + 'px',
                });
            } else if(top < 70) {
                $('.js-post-cover').css({
                    backgroundPositionY: '0px',
                });
            }
            var ratio = 1;
            if (isMobile) {
                ratio = 3;
            }
            if (top > (contentHeight - 700)) {
                $('.blur-circle.sm').css({
                   // opacity: 1 - 0.8 * (top / wH),
                    transform: 'translateY(' + (contentHeight - top - 700) / (2 * ratio)  + 'px)',
                });
                $('.blur-circle.md').css({
                    // opacity: 1 - 0.8 * (top / wH),
                     transform: 'translateY(' + (contentHeight - top - 700) / (3 * ratio) + 'px)',
                 });
                $('.blur-circle.lg').css({
                    // opacity: 1 - 0.8 * (top / wH),
                     transform: 'translateY(' + (contentHeight - top - 700) / (2 * ratio) + 'px)',
                 });
            }
            // the height of the fifth post
            if (top > 2000 && !coverLoaded) {
                lazyLoadOthers();
                coverLoaded = true;
            }

        });
    }

    function navigate(pageTrigger) {
        var oldcurrent = current,
            newcurrent = pageTriggers.indexOf(pageTrigger);
        if (isAnimating || oldcurrent === newcurrent) return;
        isAnimating = true;

        var currentPageTrigger = pageTriggers[current],
            nextContainer = containers[newcurrent],
            currentContainer = containers[current],
            dir = newcurrent > oldcurrent ? 'left' : 'right';

        $(currentPageTrigger).removeClass('active');
        $(pageTrigger).addClass('active');
        // update current
        current = newcurrent;
        $(nextContainer).addClass(dir === 'left' ? 'slider--animInRight' : 'slider--animInLeft');
        $(currentContainer).addClass(dir === 'left' ? 'slider--animOutLeft' : 'slider--animOutRight');
        onEndAnimation(currentContainer, function () {
            $(currentContainer).removeClass(dir === 'left' ? 'slider--animOutLeft' : 'slider--animOutRight');
            $(nextContainer).removeClass(dir === 'left' ? 'slider--animInRight' : 'slider--animInLeft');
            $(currentContainer).removeClass('slider--current');
            $(nextContainer).addClass('slider--current');
            isAnimating = false;
        });
    }

    var uniqueArray = function(arrArg) {
        return arrArg.filter(function(elem, pos,arr) {
          return arr.indexOf(elem) == pos;
        });
    };

    var buildUrl = function(page) {
        var path = location.pathname;
        if (path.indexOf('/page')) {
            return path.split('/page')[0] + '/page/' + page;
        }
        return '/page/' + page;
    }

    function redesignPagination() {
        var targetEl = $('nav.pagination');
        var prevIcon = '<svg class="icon icon-chevron-left"><use xlink:href="#icon-chevron-left"></use></svg>';
        var nextIcon = '<svg class="icon icon-chevron-right"><use xlink:href="#icon-chevron-right"></use></svg>';
        if (targetEl.length > 0) {
            var str = $('.page-number').text().trim();
            var current = str.split(' ')[1] * 1;
            var total = str.split(' ')[3] * 1;
            var arr = uniqueArray([1, 2, current, '...', total - 1, total]);
            var newHtml = '
';
            if (current > 2) {
                newHtml += '' + prevIcon + '';
            }
            for (var i = 0; i < arr.length; i++) {
                if (typeof arr[i] === 'number' && arr[i] > 0) {
                    var url = buildUrl(arr[i]);
                    newHtml += '' + arr[i] + '';
                } else if (i === '...' && total > 4) {
                    newHtml += '...'
                }
            }
            if ( current < total - 1) {
                newHtml += '' + nextIcon + '';
            }
            newHtml += '
';
            targetEl.hide();
            $('.js-pagination').append(newHtml);
        }
    }

    function loadCover() {
        var coverEl = $('.js-post-cover');
        var imgUrl = coverEl.attr('url');
        if (coverEl.length > 0 && coverEl.attr('url')) {
            var img = new Image();
            img.src = coverEl.attr('url');
            img.onload = function() {
                coverEl.css({
                    'background-image': 'url(' + imgUrl + ')',
                });
                coverEl.parent().addClass('loaded');
            }
        }
    }

    function loadPostCover (coverEl) {
        if (coverEl.hasClass('loaded')) {
            return;
        }
        var url = coverEl.attr('url');
        var img = new Image();
        img.src = url;
        img.onload = function() {
            coverEl.addClass('loaded');
            coverEl.prepend(img);
        }
    }

    function lazyLoadDefault() {
        $('.post').each(function(index, item) {
            if (index >= 4) {
                return;
            }
            var coverEl = $(item).find('.cover');
            loadPostCover(coverEl)
        });
    }
    function lazyLoadOthers() {
        $('.post').each(function(index, item) {
            if (index < 4) {
                return;
            }
            var coverEl = $(item).find('.cover');
            loadPostCover(coverEl)
        });
    }
    function addBanner() {
        var bannerEl = $('.post-banner');
        if (window.h5_config && h5_config.banner) {
            var config = h5_config.banner;
            bannerEl.addClass(config.class || 'sm');
            bannerEl.css({
                backgroundImage: 'url(' + (config.img) + ')',
            });
            bannerEl.find('.wrap').text(config.text || '')
        }
    }

})(jQuery);<commit_msg>fix: pagination url error<commit_after>/**
 * Main JS file for Casper behaviours
 */

/* globals jQuery, document */
(function ($) {
    "use strict";

    var animEndEventNames = {
            'WebkitAnimation': 'webkitAnimationEnd',
            'OAnimation': 'oAnimationEnd',
            'msAnimation': 'MSAnimationEnd',
            'animation': 'animationend'
        },
        animEndEventName = animEndEventNames[Modernizr.prefixed('animation')],
        onEndAnimation = function (el, callback) {
            var onEndCallbackFn = function (ev) {
                if (ev.target != this) {
                    return;
                }
                this.removeEventListener(animEndEventName, onEndCallbackFn);
                if (callback && typeof callback === 'function') {
                    callback.call();
                }
            };
            el.addEventListener(animEndEventName, onEndCallbackFn);
        };
    var $document = $(document),
        containers = [].slice.call($('.slide')),
        containersCount = containers.length,
        current = 0,
        isAnimating = false,
        pageTriggers = [];
    var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

    $document.ready(function () {

        $('.menu-icon').on('click', function (e) {
            $('body').toggleClass('open');
            $(this).toggleClass('open');
        });

        $('pre code').each(function (i, block) {
            hljs.highlightBlock(block);
        });

        initSlider();

        bindScroll();

        redesignPagination();

        loadCover();

        lazyLoadDefault();

        addBanner();

    });

    document.addEventListener('keydown', function (ev) {
        var keyCode = ev.keyCode || ev.which,
            isNavOpen = $('body').hasClass('open');

        switch (keyCode) {
            // left key
        case 37:
            if (current > 0 && !isNavOpen) {
                navigate(pageTriggers[current - 1]);
            }
            break;
            // right key
        case 39:
            if (current < containersCount - 1 && !isNavOpen) {
                navigate(pageTriggers[current + 1]);
            }
            break;
        }
    });

    function initSlider() {
        var thumbString = '';
        containers.forEach(function (item, index) {
            thumbString += '';
        });
        if (containers.length > 1) {
            var ctrlString = '';
            if (!isMobile) {
                 ctrlString = '
<svg class="icon icon-chevron-left"><use xlink:href="#icon-chevron-left"></use></svg><svg class="icon icon-chevron-right"><use xlink:href="#icon-chevron-right"></use></svg>
';
            }
            $('#slideshow').append([ctrlString, '
', thumbString, '
'].join(''));
            bindEvent();
        }
        pageTriggers = [].slice.call($('.thumb a'));
        $(containers[current]).addClass('slider--current');
        $('.slide').each(function (index, item) {
            var coverEl = $(item).find('.bg-overlay ');
            if (coverEl.hasClass('loaded')) {
                return;
            }
            var url = coverEl.attr('url');
            var img = new Image();
            img.src = url;
            img.onload = function() {
                coverEl.css({
                    'background-image': 'url(' + url + ')',
                });
                coverEl.addClass('loaded');
                if (index === 0) {
                    coverEl.parent().addClass('loaded');
                }
            }
        });
    }

    function bindEvent() {
        $('.js-ctrl-left').on('click', function () {
            if (current > 0) {
                navigate(pageTriggers[current - 1]);
            }
        });
        $('.js-ctrl-right').on('click', function () {
            if (current < containersCount - 1) {
                navigate(pageTriggers[current + 1]);
            }
        });

        if (isMobile) {
            $("#slideshow").swipe({
                //Generic swipe handler for all directions
                swipe: function (event, direction, distance, duration, fingerCount, fingerData) {
                    if (direction == 'left') {
                        if (current < containersCount - 1) {
                            navigate(pageTriggers[current + 1]);
                        }
                    } else if (direction == 'right') {
                        if (current > 0) {
                            navigate(pageTriggers[current - 1]);
                        }
                    } else if (direction == 'down') {
                        var sT = $('html').scrollTop();
                        if(sT == 0) {
                            $('body').toggleClass('open');
                            $('.menu-icon').toggleClass('open');
                        } else {
                           $('html').animate({'scrollTop': 0},500);
                        }

                    } else if(direction == 'up'){
                        return false;
                    }
                },
                threshold: 0,
                allowPageScroll: 'vertical',
            });
        }
    }

    function bindScroll() {
        var articleHeight = $('.js-article').height() - 80;
        var contentHeight = $('.content').height();
        var coverLoaded = false;
        $(document.body).on('scroll', function(e) {
            var top = e.target.scrollTop;
            var wH = window.innerHeight;
            var fixHeight = window.innerHeight + 70;
            if (!isMobile) {
                if ( top > fixHeight) {
                    $('.js-nav').addClass('fixed');
                } else if ($('.js-nav').hasClass('fixed')) {
                    $('.js-nav').removeClass('fixed');
                }
            }
            if (top > fixHeight) {
                $('.js-progress').css({
                    width: parseInt(((top - fixHeight) / articleHeight) * 100) + '%'
                });
            }
            if (top > 70 && top <= wH) {
                $('.overlay').css({
                    opacity: 0.2 + 0.8 * (top / wH),
                });
                $('.js-post-meta').css({
                    opacity: 1 - 0.8 * (top / wH),
                    transform: 'translateY(' + top / 3 + 'px)',
                });
                $('.js-post-cover').css({
                    backgroundPositionY: '-' + top / 4 + 'px',
                });
            } else if(top < 70) {
                $('.js-post-cover').css({
                    backgroundPositionY: '0px',
                });
            }
            var ratio = 1;
            if (isMobile) {
                ratio = 3;
            }
            if (top > (contentHeight - 700)) {
                $('.blur-circle.sm').css({
                   // opacity: 1 - 0.8 * (top / wH),
                    transform: 'translateY(' + (contentHeight - top - 700) / (2 * ratio)  + 'px)',
                });
                $('.blur-circle.md').css({
                    // opacity: 1 - 0.8 * (top / wH),
                     transform: 'translateY(' + (contentHeight - top - 700) / (3 * ratio) + 'px)',
                 });
                $('.blur-circle.lg').css({
                    // opacity: 1 - 0.8 * (top / wH),
                     transform: 'translateY(' + (contentHeight - top - 700) / (2 * ratio) + 'px)',
                 });
            }
            // the height of the fifth post
            if (top > 2000 && !coverLoaded) {
                lazyLoadOthers();
                coverLoaded = true;
            }

        });
    }

    function navigate(pageTrigger) {
        var oldcurrent = current,
            newcurrent = pageTriggers.indexOf(pageTrigger);
        if (isAnimating || oldcurrent === newcurrent) return;
        isAnimating = true;

        var currentPageTrigger = pageTriggers[current],
            nextContainer = containers[newcurrent],
            currentContainer = containers[current],
            dir = newcurrent > oldcurrent ? 'left' : 'right';

        $(currentPageTrigger).removeClass('active');
        $(pageTrigger).addClass('active');
        // update current
        current = newcurrent;
        $(nextContainer).addClass(dir === 'left' ? 'slider--animInRight' : 'slider--animInLeft');
        $(currentContainer).addClass(dir === 'left' ? 'slider--animOutLeft' : 'slider--animOutRight');
        onEndAnimation(currentContainer, function () {
            $(currentContainer).removeClass(dir === 'left' ? 'slider--animOutLeft' : 'slider--animOutRight');
            $(nextContainer).removeClass(dir === 'left' ? 'slider--animInRight' : 'slider--animInLeft');
            $(currentContainer).removeClass('slider--current');
            $(nextContainer).addClass('slider--current');
            isAnimating = false;
        });
    }

    var uniqueArray = function(arrArg) {
        return arrArg.filter(function(elem, pos,arr) {
          return arr.indexOf(elem) == pos;
        });
    };

    var buildUrl = function(page) {
        var path = location.pathname;
        if (path.indexOf('/page') > -1) {
            return path.split('/page')[0] + '/page/' + page;
        }
        return '/page/' + page;
    }

    function redesignPagination() {
        var targetEl = $('nav.pagination');
        var prevIcon = '<svg class="icon icon-chevron-left"><use xlink:href="#icon-chevron-left"></use></svg>';
        var nextIcon = '<svg class="icon icon-chevron-right"><use xlink:href="#icon-chevron-right"></use></svg>';
        if (targetEl.length > 0) {
            var str = $('.page-number').text().trim();
            var current = str.split(' ')[1] * 1;
            var total = str.split(' ')[3] * 1;
            var arr = uniqueArray([1, 2, current, '...', total - 1, total]);
            var newHtml = '
';
            if (current > 2) {
                newHtml += '' + prevIcon + '';
            }
            for (var i = 0; i < arr.length; i++) {
                if (typeof arr[i] === 'number' && arr[i] > 0) {
                    var url = buildUrl(arr[i]);
                    newHtml += '' + arr[i] + '';
                } else if (i === '...' && total > 4) {
                    newHtml += '...'
                }
            }
            if ( current < total - 1) {
                newHtml += '' + nextIcon + '';
            }
            newHtml += '
';
            targetEl.hide();
            $('.js-pagination').append(newHtml);
        }
    }

    function loadCover() {
        var coverEl = $('.js-post-cover');
        var imgUrl = coverEl.attr('url');
        if (coverEl.length > 0 && coverEl.attr('url')) {
            var img = new Image();
            img.src = coverEl.attr('url');
            img.onload = function() {
                coverEl.css({
                    'background-image': 'url(' + imgUrl + ')',
                });
                coverEl.parent().addClass('loaded');
            }
        }
    }

    function loadPostCover (coverEl) {
        if (coverEl.hasClass('loaded')) {
            return;
        }
        var url = coverEl.attr('url');
        var img = new Image();
        img.src = url;
        img.onload = function() {
            coverEl.addClass('loaded');
            coverEl.prepend(img);
        }
    }

    function lazyLoadDefault() {
        $('.post').each(function(index, item) {
            if (index >= 4) {
                return;
            }
            var coverEl = $(item).find('.cover');
            loadPostCover(coverEl)
        });
    }
    function lazyLoadOthers() {
        $('.post').each(function(index, item) {
            if (index < 4) {
                return;
            }
            var coverEl = $(item).find('.cover');
            loadPostCover(coverEl)
        });
    }
    function addBanner() {
        var bannerEl = $('.post-banner');
        if (window.h5_config && h5_config.banner) {
            var config = h5_config.banner;
            bannerEl.addClass(config.class || 'sm');
            bannerEl.css({
                backgroundImage: 'url(' + (config.img) + ')',
            });
            bannerEl.find('.wrap').text(config.text || '')
        }
    }

})(jQuery);<|endoftext|>


<commit_before>$(document).ready(function() {

    var turn = 0

    var taken1 = {
        1: false,
        2: false,
        3: false,
        4: false,
        5: false,
        6: false,
        7: false,
        8: false,
        9: false
    }

    var pairs1 = {
        3: false,
        4: false,
        5: false,
        6: false,
        7: false,
        8: false,
        9: false,
        10: false,
        11: false,
        12: false,
        13: false,
        14: false,
        15: false,
        16: false,
        17: false
    }

    var taken2 = {
        1: false,
        2: false,
        3: false,
        4: false,
        5: false,
        6: false,
        7: false,
        8: false,
        9: false
    }

    var pairs2 = {
        3: false,
        4: false,
        5: false,
        6: false,
        7: false,
        8: false,
        9: false,
        10: false,
        11: false,
        12: false,
        13: false,
        14: false,
        15: false,
        16: false,
        17: false
    }

    $("td").click(function(event) {

        var cell_value = parseInt(event.target.id);

        if (turn % 2 == 0) {

            $("#" + cell_value).text("X");

            if (pairs1[15 - cell_value]) {
                alert("Player One Wins!")
            };

            for (var k = 1; k < 10; k++) {
                if ((taken1[k]) && (k + cell_value < 15)) {
                    pairs1[k + cell_value] = true;
                };
            };

            taken1[cell_value] = true;

        } else {

            $("#" + cell_value).text("O");

            if (pairs2[15 - cell_value]) {
                alert("Player Two Wins!")
            };

            for (var k = 1; k < 10; k++) {
                if ((taken2[k]) && (k + cell_value < 15)) {
                    pairs2[k + cell_value] = true;
                };
            };

            taken2[cell_value] = true;
        };

        turn += 1;
    });
});
<commit_msg>one turn per player<commit_after>$(document).ready(function() {

    var turn = 0

    var gameArray = []

    var taken1 = {
        1: false,
        2: false,
        3: false,
        4: false,
        5: false,
        6: false,
        7: false,
        8: false,
        9: false
    }

    var pairs1 = {
        3: false,
        4: false,
        5: false,
        6: false,
        7: false,
        8: false,
        9: false,
        10: false,
        11: false,
        12: false,
        13: false,
        14: false,
        15: false,
        16: false,
        17: false
    }

    var taken2 = {
        1: false,
        2: false,
        3: false,
        4: false,
        5: false,
        6: false,
        7: false,
        8: false,
        9: false
    }

    var pairs2 = {
        3: false,
        4: false,
        5: false,
        6: false,
        7: false,
        8: false,
        9: false,
        10: false,
        11: false,
        12: false,
        13: false,
        14: false,
        15: false,
        16: false,
        17: false
    }

    $("td").click(function(event) {

        var cellValue = parseInt(event.target.id);

        if (gameArray.indexOf(cellValue) == -1) {

            if (turn % 2 == 0) {

                $("#" + cellValue).text("X");

                if (pairs1[15 - cellValue]) {
                    location.reload();
                    alert("Player One Wins!");
                };

                for (var k = 1; k < 10; k++) {
                    if ((taken1[k]) && (k + cellValue < 15)) {
                        pairs1[k + cellValue] = true;
                    };
                };

                taken1[cellValue] = true;

            } else {

                $("#" + cellValue).text("O");

                if (pairs2[15 - cellValue]) {
                    location.reload();
                    alert("Player Two Wins!");
                };

                for (var k = 1; k < 10; k++) {
                    if ((taken2[k]) && (k + cellValue < 15)) {
                        pairs2[k + cellValue] = true;
                    };
                };

                taken2[cellValue] = true;
            };

            turn += 1;
            gameArray.push(cellValue);
            console.log(gameArray);
        };
    });
});<|endoftext|>


<commit_before>const lost = require('lost')
const pxtorem = require('postcss-pxtorem')

module.exports = {
  siteMetadata: {
    siteUrl:"https://www.maxgrok.com",
    url: 'https://www.maxgrok.com',
    title: 'Blog by Max Goodman',
    subtitle:
      'full stack && blockchain engineer.',
    copyright: '© All rights reserved.',
    disqusShortname: '',
    menu: [
      {
        label: 'Home',
        path: '/'
      },
      // {
      //   label: 'Posts',
      //   path: '/posts'
      // },
      {
        label: 'Code',
        path: '/code'
      },
      {
        label: 'Talks',
        path: '/talks'
      },
      {
        label: 'Companies',
        path: '/companies'
      },
      {
        label: 'Press',
        path: '/press'
      },
      {
        label: "Education",
        path:'/edu'
      },
      {
        label: 'About me',
        path: '/about'
      },
      {
        label: 'Contact me',
        path: '/contact'
      },
    ],
    author: {
      name: 'Max Goodman',
      email: 'max@atrest.us',
      // telegram: '#',
      twitter: '@maxxgrok',
      github: 'maxgrok',
      // rss: '#',
      // vk: '#',
    },
  },
  plugins: [
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/src/pages`,
        name: 'pages',
      },
    },
    {
      resolve: 'gatsby-plugin-feed',
      options: {
        query: `
          {
            site {
              siteMetadata {
                url: url
                title
                description: subtitle
              }
            }
          }
        `,
        feeds: [
          {
            serialize: ({ query: { site, allMarkdownRemark } }) =>
              allMarkdownRemark.edges.map(edge =>
                Object.assign({}, edge.node.frontmatter, {
                  description: edge.node.frontmatter.description,
                  date: edge.node.frontmatter.date,
                  url: site.siteMetadata.site_url + edge.node.fields.slug,
                  guid: site.siteMetadata.site_url + edge.node.fields.slug,
                  custom_elements: [{ 'content:encoded': edge.node.html }],
                })
              ),
            query: `
              {
                allMarkdownRemark(
                  limit: 1000,
                  sort: { order: DESC, fields: [frontmatter___date] },
                  filter: { frontmatter: { layout: { eq: "post" }, draft: { ne: true } } }
                ) {
                  edges {
                    node {
                      html
                      fields {
                        slug
                      }
                      frontmatter {
                        title
                        date
                        layout
                        draft
                        description
                      }
                    }
                  }
                }
              }
            `,
            output: '/rss.xml',
          },
        ],
      },
    },
    {
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [
          {
            resolve: 'gatsby-remark-images',
            options: {
              maxWidth: 960,
            },
          },
          {
            resolve: 'gatsby-remark-responsive-iframe',
            options: { wrapperStyle: 'margin-bottom: 1.0725rem' },
          },
          'gatsby-remark-prismjs',
          'gatsby-remark-copy-linked-files',
          'gatsby-remark-smartypants',
        ],
      },
    },
    'gatsby-transformer-sharp',
    'gatsby-plugin-sharp',
    {
      resolve: 'gatsby-plugin-google-analytics',
      options: { trackingId: 'UA-73379983-2' },
    },
    {
      resolve: 'gatsby-plugin-google-fonts',
      options: {
        fonts: ['roboto:400,400i,500,700'],
      },
    },
    {
      resolve: 'gatsby-plugin-sitemap',
      options: {
        query: `
            {
              site {
                siteMetadata {
                  siteUrl
                  url
                }
              }
              allSitePage(
                filter: {
                  path: { regex: "/^(?!/404/|/404.html|/dev-404-page/)/" }
                }
              ) {
                edges {
                  node {
                    path
                  }
                }
              }
          }`,
        output: '/sitemap.xml',
        serialize: ({ site, allSitePage }) =>
          allSitePage.edges.map(edge => {
            return {
              url: site.siteMetadata.url + edge.node.path,
              changefreq: 'daily',
              priority: 0.7,
            }
          }),
      },
    },
    'gatsby-plugin-offline',
    'gatsby-plugin-catch-links',
    'gatsby-plugin-react-helmet',
    {
      resolve: 'gatsby-plugin-sass',
      options: {
        postCssPlugins: [
          lost(),
          pxtorem({
            rootValue: 16,
            unitPrecision: 5,
            propList: [
              'font',
              'font-size',
              'line-height',
              'letter-spacing',
              'margin',
              'margin-top',
              'margin-left',
              'margin-bottom',
              'margin-right',
              'padding',
              'padding-top',
              'padding-left',
              'padding-bottom',
              'padding-right',
              'border-radius',
              'width',
              'max-width',
            ],
            selectorBlackList: [],
            replace: true,
            mediaQuery: false,
            minPixelValue: 0,
          }),
        ],
        precision: 8,
      },
    },
  ],
}
<commit_msg>edits to title<commit_after>const lost = require('lost')
const pxtorem = require('postcss-pxtorem')

module.exports = {
  siteMetadata: {
    siteUrl:"https://www.maxgrok.com",
    url: 'https://www.maxgrok.com',
    title: 'Max',
    subtitle:
      'full stack && blockchain engineer.',
    copyright: '© All rights reserved.',
    disqusShortname: '',
    menu: [
      {
        label: 'Home',
        path: '/'
      },
      // {
      //   label: 'Posts',
      //   path: '/posts'
      // },
      {
        label: 'Code',
        path: '/code'
      },
      {
        label: 'Talks',
        path: '/talks'
      },
      {
        label: 'Companies',
        path: '/companies'
      },
      {
        label: 'Press',
        path: '/press'
      },
      {
        label: "Education",
        path:'/edu'
      },
      {
        label: 'About me',
        path: '/about'
      },
      {
        label: 'Contact me',
        path: '/contact'
      },
    ],
    author: {
      name: 'Max Goodman',
      email: 'max@atrest.us',
      // telegram: '#',
      twitter: '@maxxgrok',
      github: 'maxgrok',
      // rss: '#',
      // vk: '#',
    },
  },
  plugins: [
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/src/pages`,
        name: 'pages',
      },
    },
    {
      resolve: 'gatsby-plugin-feed',
      options: {
        query: `
          {
            site {
              siteMetadata {
                url: url
                title
                description: subtitle
              }
            }
          }
        `,
        feeds: [
          {
            serialize: ({ query: { site, allMarkdownRemark } }) =>
              allMarkdownRemark.edges.map(edge =>
                Object.assign({}, edge.node.frontmatter, {
                  description: edge.node.frontmatter.description,
                  date: edge.node.frontmatter.date,
                  url: site.siteMetadata.site_url + edge.node.fields.slug,
                  guid: site.siteMetadata.site_url + edge.node.fields.slug,
                  custom_elements: [{ 'content:encoded': edge.node.html }],
                })
              ),
            query: `
              {
                allMarkdownRemark(
                  limit: 1000,
                  sort: { order: DESC, fields: [frontmatter___date] },
                  filter: { frontmatter: { layout: { eq: "post" }, draft: { ne: true } } }
                ) {
                  edges {
                    node {
                      html
                      fields {
                        slug
                      }
                      frontmatter {
                        title
                        date
                        layout
                        draft
                        description
                      }
                    }
                  }
                }
              }
            `,
            output: '/rss.xml',
          },
        ],
      },
    },
    {
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [
          {
            resolve: 'gatsby-remark-images',
            options: {
              maxWidth: 960,
            },
          },
          {
            resolve: 'gatsby-remark-responsive-iframe',
            options: { wrapperStyle: 'margin-bottom: 1.0725rem' },
          },
          'gatsby-remark-prismjs',
          'gatsby-remark-copy-linked-files',
          'gatsby-remark-smartypants',
        ],
      },
    },
    'gatsby-transformer-sharp',
    'gatsby-plugin-sharp',
    {
      resolve: 'gatsby-plugin-google-analytics',
      options: { trackingId: 'UA-73379983-2' },
    },
    {
      resolve: 'gatsby-plugin-google-fonts',
      options: {
        fonts: ['roboto:400,400i,500,700'],
      },
    },
    {
      resolve: 'gatsby-plugin-sitemap',
      options: {
        query: `
            {
              site {
                siteMetadata {
                  siteUrl
                  url
                }
              }
              allSitePage(
                filter: {
                  path: { regex: "/^(?!/404/|/404.html|/dev-404-page/)/" }
                }
              ) {
                edges {
                  node {
                    path
                  }
                }
              }
          }`,
        output: '/sitemap.xml',
        serialize: ({ site, allSitePage }) =>
          allSitePage.edges.map(edge => {
            return {
              url: site.siteMetadata.url + edge.node.path,
              changefreq: 'daily',
              priority: 0.7,
            }
          }),
      },
    },
    'gatsby-plugin-offline',
    'gatsby-plugin-catch-links',
    'gatsby-plugin-react-helmet',
    {
      resolve: 'gatsby-plugin-sass',
      options: {
        postCssPlugins: [
          lost(),
          pxtorem({
            rootValue: 16,
            unitPrecision: 5,
            propList: [
              'font',
              'font-size',
              'line-height',
              'letter-spacing',
              'margin',
              'margin-top',
              'margin-left',
              'margin-bottom',
              'margin-right',
              'padding',
              'padding-top',
              'padding-left',
              'padding-bottom',
              'padding-right',
              'border-radius',
              'width',
              'max-width',
            ],
            selectorBlackList: [],
            replace: true,
            mediaQuery: false,
            minPixelValue: 0,
          }),
        ],
        precision: 8,
      },
    },
  ],
}
<|endoftext|>


<commit_before>const authentication = require('feathers-authentication');
const jwt = require('feathers-authentication-jwt');
<% if(strategies.indexOf('local') !== -1) { %>const local = require('feathers-authentication-local');<% } %>
<% if(oauthProviders.length){ %>const oauth2 = require('feathers-authentication-oauth2');<% } %>
<% oauthProviders.forEach(provider => { %>const <%= provider.strategyName %> = require('<%= provider.module %>');
<% }); %>
module.exports = function () {
  const app = this;
  const config = app.get('authentication');

  // Set up authentication with the secret
  app.configure(authentication(config));
  app.configure(jwt());<% if(strategies.indexOf('local') !== -1) { %>
  app.configure(local(config.local));<% } %>
<% oauthProviders.forEach(provider => { %>
  app.configure(oauth2(Object.assign({
    name: '<%= provider.name %>',
    Strategy: <%= provider.strategyName %>
  }, config.<%= provider.name %>)));
<% }); %>
  // The `authentication` service is used to create a JWT.
  // The before `create` hook registers strategies that can be used
  // to create a new valid JWT (e.g. local or oauth2)
  app.service('authentication').hooks({
    before: {
      create: [
        authentication.hooks.authenticate(config.strategies)
      ],
      remove: [
        authentication.hooks.authenticate('jwt')
      ]
    }
  });
};
<commit_msg>app.configure consistency (#276)<commit_after>const authentication = require('feathers-authentication');
const jwt = require('feathers-authentication-jwt');
<% if(strategies.indexOf('local') !== -1) { %>const local = require('feathers-authentication-local');<% } %>
<% if(oauthProviders.length){ %>const oauth2 = require('feathers-authentication-oauth2');<% } %>
<% oauthProviders.forEach(provider => { %>const <%= provider.strategyName %> = require('<%= provider.module %>');
<% }); %>
module.exports = function () {
  const app = this;
  const config = app.get('authentication');

  // Set up authentication with the secret
  app.configure(authentication(config));
  app.configure(jwt(config.jwt));<% if(strategies.indexOf('local') !== -1) { %>
  app.configure(local(config.local));<% } %>
<% oauthProviders.forEach(provider => { %>
  app.configure(oauth2(Object.assign({
    name: '<%= provider.name %>',
    Strategy: <%= provider.strategyName %>
  }, config.<%= provider.name %>)));
<% }); %>
  // The `authentication` service is used to create a JWT.
  // The before `create` hook registers strategies that can be used
  // to create a new valid JWT (e.g. local or oauth2)
  app.service('authentication').hooks({
    before: {
      create: [
        authentication.hooks.authenticate(config.strategies)
      ],
      remove: [
        authentication.hooks.authenticate('jwt')
      ]
    }
  });
};
<|endoftext|>


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

/*
Copyright 2017 New Vector Ltd

Licensed 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.
*/

/*
 * Looks through all the translation files and removes any strings
 * which don't appear in en_EN.json.
 * Use this if you remove a translation, but merge any outstanding changes
 * from weblate first or you'll need to resolve the conflict in weblate.
 */

const fs = require('fs');
const path = require('path');

const I18NDIR = 'src/i18n/strings';

const enStrings = JSON.parse(fs.readFileSync(path.join(I18NDIR, 'en_EN.json')));

for (const filename of fs.readdirSync(I18NDIR)) {
    if (filename === 'en_EN.json') continue;
    if (filename === 'basefile.json') continue;
    if (!filename.endsWith('.json')) continue;

    const trs = JSON.parse(fs.readFileSync(path.join(I18NDIR, filename)));
    const oldLen = Object.keys(trs).length;
    for (const tr of Object.keys(trs)) {
        if (enStrings[tr] === undefined) {
            delete trs[tr];
        }
    }

    const removed = oldLen - Object.keys(trs).length;
    if (removed > 0) {
        console.log(`${filename}: removed ${removed} translations`);
        // XXX: This is totally relying on the impl serialising the JSON object in the
        // same order as they were parsed from the file. JSON.stringify() has a specific argument
        // that can be used to control the order, but JSON.parse() lacks any kind of equivalent.
        // Empirically this does maintain the order on my system, so I'm going to leave it like
        // this for now.
        fs.writeFileSync(path.join(I18NDIR, filename), JSON.stringify(trs, undefined, 4) + "\n");
    }
}
<commit_msg>Don't remove other plural variants<commit_after>#!/usr/bin/env node

/*
Copyright 2017 New Vector Ltd

Licensed 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.
*/

/*
 * Looks through all the translation files and removes any strings
 * which don't appear in en_EN.json.
 * Use this if you remove a translation, but merge any outstanding changes
 * from weblate first or you'll need to resolve the conflict in weblate.
 */

const fs = require('fs');
const path = require('path');

const I18NDIR = 'src/i18n/strings';

const enStringsRaw = JSON.parse(fs.readFileSync(path.join(I18NDIR, 'en_EN.json')));

const enStrings = new Set();
for (const str of Object.keys(enStringsRaw)) {
    const parts = str.split('|');
    if (parts.length > 1) {
        enStrings.add(parts[0]);
    } else {
        enStrings.add(str);
    }
}

for (const filename of fs.readdirSync(I18NDIR)) {
    if (filename === 'en_EN.json') continue;
    if (filename === 'basefile.json') continue;
    if (!filename.endsWith('.json')) continue;

    const trs = JSON.parse(fs.readFileSync(path.join(I18NDIR, filename)));
    const oldLen = Object.keys(trs).length;
    for (const tr of Object.keys(trs)) {
        const parts = tr.split('|');
        const trKey = parts.length > 1 ? parts[0] : tr;
        if (!enStrings.has(trKey)) {
            delete trs[tr];
        }
    }

    const removed = oldLen - Object.keys(trs).length;
    if (removed > 0) {
        console.log(`${filename}: removed ${removed} translations`);
        // XXX: This is totally relying on the impl serialising the JSON object in the
        // same order as they were parsed from the file. JSON.stringify() has a specific argument
        // that can be used to control the order, but JSON.parse() lacks any kind of equivalent.
        // Empirically this does maintain the order on my system, so I'm going to leave it like
        // this for now.
        fs.writeFileSync(path.join(I18NDIR, filename), JSON.stringify(trs, undefined, 4) + "\n");
    }
}
<|endoftext|>