<commit_before>import {I18N} from './i18n';
import {EventAggregator} from 'aurelia-event-aggregator';
import {customAttribute} from 'aurelia-templating';
import {SignalBindingBehavior} from 'aurelia-templating-resources';
import {ValueConverter} from 'aurelia-binding';
import {LazyOptional} from './utils';

export class TValueConverter {
  static inject() { return [I18N]; }
  constructor(i18n) {
    this.service = i18n;
  }

  toView(value, options) {
    return this.service.tr(value, options);
  }
}

@customAttribute('t-params')
export class TParamsCustomAttribute {
  static inject = [Element];
  service;

  constructor(element) {
    this.element = element;
  }

  valueChanged() {

  }
}

@customAttribute('t')
export class TCustomAttribute {

  static inject = [Element, I18N, EventAggregator, LazyOptional.of(TParamsCustomAttribute)];

  constructor(element, i18n, ea, tparams) {
    this.element = element;
    this.service = i18n;
    this.ea = ea;
    this.lazyParams = tparams;
  }

  bind() {
    this.params = this.lazyParams();

    if (this.params) {
      this.params.valueChanged = (newParams, oldParams) => {
        this.paramsChanged(this.value, newParams, oldParams);
      };
    }

    let p = this.params !== null ? this.params.value : undefined;
    this.subscription = this.ea.subscribe('i18n:locale:changed', () => {
      this.service.updateValue(this.element, this.value, p);
    });

    this.service.updateValue(this.element, this.value, p);
  }

  paramsChanged(newValue, newParams) {
    this.service.updateValue(this.element, newValue, newParams);
  }

  valueChanged(newValue) {
    let p = this.params !== null ? this.params.value : undefined;
    this.service.updateValue(this.element, newValue, p);
  }

  unbind() {
    // If unbind is called before timeout for subscription is triggered, subscription will be undefined
    if (this.subscription) {
      this.subscription.dispose();
    }
  }
}

export class TBindingBehavior {
  static inject = [SignalBindingBehavior];

  constructor(signalBindingBehavior) {
    this.signalBindingBehavior = signalBindingBehavior;
  }

  bind(binding, source) {
    // bind the signal behavior
    this.signalBindingBehavior.bind(binding, source, 'aurelia-translation-signal');

    // rewrite the expression to use the TValueConverter.
    // pass through any args to the binding behavior to the TValueConverter
    let sourceExpression = binding.sourceExpression;
    let expression = sourceExpression.expression;
    sourceExpression.expression = new ValueConverter(
      expression,
      't',
      sourceExpression.args,
      [expression, ...sourceExpression.args]);
  }

  unbind(binding, source) {
    // undo the expression rewrite
    binding.sourceExpression.expression = binding.sourceExpression.expression.expression;

    // unbind the signal behavior
    this.signalBindingBehavior.unbind(binding, source);
  }
}
<commit_msg>fix(binding): sourceExpression only once<commit_after>import {I18N} from './i18n';
import {EventAggregator} from 'aurelia-event-aggregator';
import {customAttribute} from 'aurelia-templating';
import {SignalBindingBehavior} from 'aurelia-templating-resources';
import {ValueConverter} from 'aurelia-binding';
import {LazyOptional} from './utils';

export class TValueConverter {
  static inject() { return [I18N]; }
  constructor(i18n) {
    this.service = i18n;
  }

  toView(value, options) {
    return this.service.tr(value, options);
  }
}

@customAttribute('t-params')
export class TParamsCustomAttribute {
  static inject = [Element];
  service;

  constructor(element) {
    this.element = element;
  }

  valueChanged() {

  }
}

@customAttribute('t')
export class TCustomAttribute {

  static inject = [Element, I18N, EventAggregator, LazyOptional.of(TParamsCustomAttribute)];

  constructor(element, i18n, ea, tparams) {
    this.element = element;
    this.service = i18n;
    this.ea = ea;
    this.lazyParams = tparams;
  }

  bind() {
    this.params = this.lazyParams();

    if (this.params) {
      this.params.valueChanged = (newParams, oldParams) => {
        this.paramsChanged(this.value, newParams, oldParams);
      };
    }

    let p = this.params !== null ? this.params.value : undefined;
    this.subscription = this.ea.subscribe('i18n:locale:changed', () => {
      this.service.updateValue(this.element, this.value, p);
    });

    this.service.updateValue(this.element, this.value, p);
  }

  paramsChanged(newValue, newParams) {
    this.service.updateValue(this.element, newValue, newParams);
  }

  valueChanged(newValue) {
    let p = this.params !== null ? this.params.value : undefined;
    this.service.updateValue(this.element, newValue, p);
  }

  unbind() {
    // If unbind is called before timeout for subscription is triggered, subscription will be undefined
    if (this.subscription) {
      this.subscription.dispose();
    }
  }
}

export class TBindingBehavior {
  static inject = [SignalBindingBehavior];

  constructor(signalBindingBehavior) {
    this.signalBindingBehavior = signalBindingBehavior;
  }

  bind(binding, source) {
    // bind the signal behavior
    this.signalBindingBehavior.bind(binding, source, 'aurelia-translation-signal');

    // rewrite the expression to use the TValueConverter.
    // pass through any args to the binding behavior to the TValueConverter
    let sourceExpression = binding.sourceExpression;

    // do create the sourceExpression only once
    if (sourceExpression.rewritten) {
      return;
    }
    sourceExpression.rewritten = true;

    let expression = sourceExpression.expression;
    sourceExpression.expression = new ValueConverter(
      expression,
      't',
      sourceExpression.args,
      [expression, ...sourceExpression.args]);
  }

  unbind(binding, source) {
    // unbind the signal behavior
    this.signalBindingBehavior.unbind(binding, source);
  }
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from "react"
import { findDOMNode } from "react-dom"
import urlify from "../_utils/urlify"

// react-router does not return leading and trailing slashes
// so we need to normalize according to collection data
const splatToUrl = (string) => ("/" + urlify(string))

const isDevelopment = process.env.NODE_ENV !== "production"
const isClient = typeof window !== "undefined"
const isDevelopmentClient = isDevelopment && isClient

let catchLinks
let browserHistory

if (isClient) {
  catchLinks = require("../_utils/catch-links").default
  browserHistory = require("../client").browserHistory
}

export default class PageContainer extends Component {

  static propTypes = {
    pages: PropTypes.object.isRequired,
    params: PropTypes.object,

    defaultLayout: PropTypes.string,

    // actions
    getPage: PropTypes.func.isRequired,
    setPageNotFound: PropTypes.func,
  };

  static contextTypes = {
    collection: PropTypes.array.isRequired,
    layouts: PropTypes.object.isRequired,
  };

  static defaultProps = {
    defaultLayout: "Page",
  };

  componentWillMount() {
    this.preparePage(this.props, this.context)
  }

  componentDidMount() {
    this.catchInternalLink()
  }

  componentWillReceiveProps(nextProps) {
    this.preparePage(nextProps, this.context)
  }

  componentDidUpdate() {
    this.catchInternalLink()
  }

  catchInternalLink() {
    if (!isClient) {
      return
    }

    if (this._content) {
      const layoutDOMElement = findDOMNode(this._content)
      if (layoutDOMElement) {
        catchLinks(layoutDOMElement, (href) => {
          const pathname = href.replace(process.env.STATINAMIC_PATHNAME, "")
          browserHistory.push(pathname)
        })
      }
    }
  }

  preparePage(props, context) {
    if (!context.layouts[props.defaultLayout]) {
      console.error(
        "statinamic: PageContainer: " +
        `default layout "${ props.defaultLayout }" doesn't exist. ` +
        `Please check your configuration ("layouts" part). ` +
        `If you haven't defined "${ props.defaultLayout }", you should. `
      )
    }

    const pageUrl = splatToUrl(props.params.splat)
    if (isDevelopmentClient) {
      console.info(`statinamic: PageContainer: '${ pageUrl }' rendering...`)
    }
    const page = props.pages[pageUrl]
    if (!page) {
      const item = context.collection.find(
        (item) => (
          item.__url === pageUrl ||
          item.__resourceUrl === pageUrl
        )
      )
      if (item) {
        props.getPage(pageUrl, item.__dataUrl)
      }
      else {
        // Here we know we don't have the "internal" link in the collection
        // so we can assume it's something else than a know page (eg: an asset)
        // Refreshing the page will it the appropriate resource.
        if (isClient) {
          window.location.reload()
        }
        else if (props.setPageNotFound) {
          props.setPageNotFound(pageUrl)
        }
        else {
          console.error(
            `statinamic: PageContainer: ` +
            `${ pageUrl } is a page not found.`
          )
        }
      }
    }
    else {
      if (page.error) {
        return
      }

      const Layout = this.getLayout(props, context, page)
      if (page.type !== undefined && !Layout) {
        console.error(
          "statinamic: PageContainer: " +
          `Unkown page type: "${ page.type }" component not available in ` +
          `"layouts" property. ` +
          `Please check the "layout" or "type" of page "${ page }" header.`
        )
      }
    }
  }

  getLayout(props, context, page) {
    return context.layouts[page.type || props.defaultLayout]
  }

  render() {
    const pageUrl = splatToUrl(this.props.params.splat)
    const page = this.props.pages[pageUrl]

    if (!page) {
      if (isDevelopmentClient) {
        console.info(`statinamic: PageContainer: '${ pageUrl }' no data`)
      }
      return null
    }
    if (isDevelopmentClient) {
      console.info(`statinamic: PageContainer: '${ pageUrl }'`, page)
    }

    if (typeof page !== "object") {
      console.info(
        `statinamic: PageContainer: page ${ pageUrl } should be an object`
      )
      return null
    }

    const { PageLoading, PageError } = this.context.layouts
    const Layout = this.getLayout(this.props, this.context, page)

    return (

        {
          !page.error && page.loading && PageLoading &&
          <PageLoading />
        }
        {
          !!page.error && !PageError &&

{ page.error }

{ page.errorText }

        }
        {
          !!page.error && PageError &&
          <PageError { ...page } />
        }
        {
          !page.error && !page.loading && Layout &&
          <Layout ref={ (ref) => this._content = ref } { ...page } />
        }

    )
  }
}
<commit_msg>Fix annoying failure when hitting "back" button when you have hit an asset<commit_after>import React, { Component, PropTypes } from "react"
import { findDOMNode } from "react-dom"
import urlify from "../_utils/urlify"

// react-router does not return leading and trailing slashes
// so we need to normalize according to collection data
const splatToUrl = (string) => ("/" + urlify(string))

const isDevelopment = process.env.NODE_ENV !== "production"
const isClient = typeof window !== "undefined"
const isDevelopmentClient = isDevelopment && isClient

let catchLinks
let browserHistory

if (isClient) {
  catchLinks = require("../_utils/catch-links").default
  browserHistory = require("../client").browserHistory
}

export default class PageContainer extends Component {

  static propTypes = {
    pages: PropTypes.object.isRequired,
    params: PropTypes.object,

    defaultLayout: PropTypes.string,

    // actions
    getPage: PropTypes.func.isRequired,
    setPageNotFound: PropTypes.func,
  };

  static contextTypes = {
    collection: PropTypes.array.isRequired,
    layouts: PropTypes.object.isRequired,
  };

  static defaultProps = {
    defaultLayout: "Page",
  };

  componentWillMount() {
    this.preparePage(this.props, this.context)
  }

  componentDidMount() {
    this.catchInternalLink()
  }

  componentWillReceiveProps(nextProps) {
    this.preparePage(nextProps, this.context)
  }

  componentDidUpdate() {
    this.catchInternalLink()
  }

  catchInternalLink() {
    if (!isClient) {
      return
    }

    if (this._content) {
      const layoutDOMElement = findDOMNode(this._content)
      if (layoutDOMElement) {
        catchLinks(layoutDOMElement, (href) => {
          const pathname = href.replace(process.env.STATINAMIC_PATHNAME, "")
          browserHistory.push(pathname)
        })
      }
    }
  }

  preparePage(props, context) {
    if (!context.layouts[props.defaultLayout]) {
      console.error(
        "statinamic: PageContainer: " +
        `default layout "${ props.defaultLayout }" doesn't exist. ` +
        `Please check your configuration ("layouts" part). ` +
        `If you haven't defined "${ props.defaultLayout }", you should. `
      )
    }

    const pageUrl = splatToUrl(props.params.splat)
    if (isDevelopmentClient) {
      console.info(`statinamic: PageContainer: '${ pageUrl }' rendering...`)
    }
    const page = props.pages[pageUrl]
    if (!page) {
      const item = context.collection.find(
        (item) => (
          item.__url === pageUrl ||
          item.__resourceUrl === pageUrl
        )
      )
      if (item) {
        props.getPage(pageUrl, item.__dataUrl)
      }
      else {
        // Here we know we don't have the "internal" link in the collection
        // so we can assume it's something else than a know page (eg: an asset)
        // Refreshing the page will it the appropriate resource.
        if (isClient) {
          window.location.href = window.location.href
        }
        else if (props.setPageNotFound) {
          props.setPageNotFound(pageUrl)
        }
        else {
          console.error(
            `statinamic: PageContainer: ` +
            `${ pageUrl } is a page not found.`
          )
        }
      }
    }
    else {
      if (page.error) {
        return
      }

      const Layout = this.getLayout(props, context, page)
      if (page.type !== undefined && !Layout) {
        console.error(
          "statinamic: PageContainer: " +
          `Unkown page type: "${ page.type }" component not available in ` +
          `"layouts" property. ` +
          `Please check the "layout" or "type" of page "${ page }" header.`
        )
      }
    }
  }

  getLayout(props, context, page) {
    return context.layouts[page.type || props.defaultLayout]
  }

  render() {
    const pageUrl = splatToUrl(this.props.params.splat)
    const page = this.props.pages[pageUrl]

    if (!page) {
      if (isDevelopmentClient) {
        console.info(`statinamic: PageContainer: '${ pageUrl }' no data`)
      }
      return null
    }
    if (isDevelopmentClient) {
      console.info(`statinamic: PageContainer: '${ pageUrl }'`, page)
    }

    if (typeof page !== "object") {
      console.info(
        `statinamic: PageContainer: page ${ pageUrl } should be an object`
      )
      return null
    }

    const { PageLoading, PageError } = this.context.layouts
    const Layout = this.getLayout(this.props, this.context, page)

    return (

        {
          !page.error && page.loading && PageLoading &&
          <PageLoading />
        }
        {
          !!page.error && !PageError &&

{ page.error }

{ page.errorText }

        }
        {
          !!page.error && PageError &&
          <PageError { ...page } />
        }
        {
          !page.error && !page.loading && Layout &&
          <Layout ref={ (ref) => this._content = ref } { ...page } />
        }

    )
  }
}
<|endoftext|>


<commit_before>const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xmlhttp = new XMLHttpRequest();

var latitude = 43.271338;
var longitude = 6.638375;

var city = latLonToCity(latitude, longitude);

console.log(city);

function latLonToCity(latitude, longitude) {
    var url = 'http://nominatim.openstreetmap.org/reverse?format=json'
                + '&lat=' + latitude + '&lon=' + longitude;

    var city;

    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var data = JSON.parse(this.responseText);
            city = getCity(data);
        }
    };
    xmlhttp.open("GET", url, false);
    xmlhttp.send();

    return city;
}

function getCity(data) {
    if (data['address']['city'] !== undefined) {
        return data['address']['city'];
    }
    if (data['address']['town'] !== undefined) {
        return data['address']['town'];
    }
    if (data['address']['village'] !== undefined) {
        return data['address']['village'];
    }
    return 'failure\n' + data;
}
<commit_msg>get population by wolframalpha<commit_after>const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xmlhttp = new XMLHttpRequest();

var latitude = 43.271338;
var longitude = 6.638375;

var city = latLonToCity(latitude, longitude);
console.log(city);

var population = getPopulation('Munich');
console.log(population);

function latLonToCity(latitude, longitude) {
    var url = 'http://nominatim.openstreetmap.org/reverse?format=json'
                + '&lat=' + latitude + '&lon=' + longitude;

    var city;

    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var data = JSON.parse(this.responseText);
            city = getCity(data);
        }
    };
    xmlhttp.open("GET", url, false);
    xmlhttp.send();

    return city;
}

function getCity(data) {
    if (data['address']['city'] !== undefined) {
        return data['address']['city'];
    }
    if (data['address']['town'] !== undefined) {
        return data['address']['town'];
    }
    if (data['address']['village'] !== undefined) {
        return data['address']['village'];
    }
    return 'failure\n' + data;
}

function getPopulation(place) {
    var appId = 'TV9Y52-9297TEGQHH';
    var url = 'http://api.wolframalpha.com/v2/query?input=' + place
                + '&appid=' +  appId;

    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            parseXML(this);
        }
    };
    xmlhttp.open("GET", url, false);
    xmlhttp.send();

    return place;
}

function parseXML(xml) {
    var xmlDoc = xml.responseXML;
    document.getElementById("queryresult").innerHTML =
    xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
}
<|endoftext|>


<commit_before>import PropTypes from "prop-types";
import React, { useCallback, useMemo, useState } from "react";
import styled from "styled-components";

import style from "@agir/front/genericComponents/_variables.scss";

import { useResponsiveMemo } from "@agir/front/genericComponents/grid";

import Button from "@agir/front/genericComponents/Button";
import Panel from "@agir/front/genericComponents/Panel";
import { RawFeatherIcon } from "@agir/front/genericComponents/FeatherIcon";

import { EVENT_TYPES } from "./eventForm.config";

const StyledOption = styled.li`
  display: flex;
  flex-flow: row nowrap;
  height: 2.75rem;
  align-items: center;
  font-size: 0.813rem;
  line-height: 1.3;
  color: ${({ $selected }) => ($selected ? style.primary500 : style.black1000)};
  font-weight: ${({ $selected }) => ($selected ? 600 : 400)};
  cursor: ${({ $selected }) => ($selected ? "default" : "pointer")};

  button {
    display: ${({ $selected }) => ($selected ? "none" : "inline")};
    margin-left: auto;
  }

  span {
    color: ${style.primary500};
    display: inline-block;
    font-size: 1.5rem;
    padding-right: 0.5rem;
  }
`;

const StyledOptions = styled.div`
  display: flex;
  flex-flow: column nowrap;
  padding-top: 0.5rem;

  ul {
    padding: 0;
    list-style: none;

    strong {
      display: block;
      height: 2.75rem;
      font-weight: 600;
      font-size: 1rem;
      line-height: 1.5;
      display: flex;
      align-items: center;
    }
  }
`;

const StyledDefaultOption = styled.button``;
const StyledDefaultOptions = styled.div`
  display: flex;
  flex-flow: row wrap;
  gap: 0.5rem;

  button {
    border-radius: 0;
    border: none;
    box-shadow: none;
    padding: 0;
    background-color: transparent;
    font-size: 0.813rem;
    font-weight: 600;
    cursor: pointer;
    color: ${style.primary500};

    &[disabled],
    &[disabled]:hover {
      opacity: 0.5;
      cursor: default;
    }
  }

  ${StyledDefaultOption} {
    padding: 0.5rem 0.75rem;
    color: ${style.black1000};
    display: inline-grid;
    grid-gap: 0.5rem;
    grid-template-columns: auto auto auto;
    align-items: center;
    border: 1px solid ${style.black100};

    &:hover {
      background-color: ${style.black50};
    }

    &[disabled],
    &[disabled]:hover {
      opacity: 1;
      background-color: transparent;
      cursor: default;
    }
  }
`;

const StyledField = styled.div`
  label {
    font-size: 0.813rem;
    font-weight: 600;
    line-height: 1;
    padding: 4px 0;
  }
`;

const SubtypeOption = (props) => {
  const { option, onClick, selected } = props;

  const handleClick = useCallback(() => {
    onClick(option);
  }, [option, onClick]);

  return (

  );
};

const DefaultOption = (props) => {
  const { option, onClick, selected, disabled } = props;

  const handleClick = useCallback(() => {
    onClick(option);
  }, [option, onClick]);

  return (

  );
};
SubtypeOption.propTypes = DefaultOption.propTypes = {
  option: PropTypes.shape({
    id: PropTypes.number,
    label: PropTypes.string,
    iconName: PropTypes.string,
    color: PropTypes.String,
    description: PropTypes.string,
  }),
  onClick: PropTypes.func,
  selected: PropTypes.bool,
  disabled: PropTypes.bool,
};

const SubtypeField = (props) => {
  const { onChange, value, name, error, disabled } = props;
  const [isPanelOpen, setIsPanelOpen] = useState(false);
  const openPanel = useCallback(() => {
    setIsPanelOpen(true);
  }, []);
  const closePanel = useCallback(() => {
    setIsPanelOpen(false);
  }, []);
  const panelPosition = useResponsiveMemo("right", "left");

  const handleChange = useCallback(
    (subtype) => {
      onChange(name, subtype);
      setIsPanelOpen(false);
    },
    [onChange, name]
  );

  const subtypes = useMemo(
    () => (Array.isArray(props.options) ? props.options : []),
    [props.options]
  );

  const options = useMemo(() => {
    const categories = { ...EVENT_TYPES };
    subtypes.forEach((subtype) => {
      const category =
        subtype.type && categories[subtype.type] ? subtype.type : "O";
      categories[category].subtypes = categories[category].subtypes || [];
      categories[category].subtypes.push(subtype);
    });

    return Object.values(categories).filter((category) =>
      Array.isArray(category.subtypes)
    );
  }, [subtypes]);

  const defaultOptions = useMemo(() => subtypes.slice(0, 4), [subtypes]);

  return (

      <Panel
        position={panelPosition}
        shouldShow={isPanelOpen}
        onClose={closePanel}
        onBack={closePanel}
        title="Type de l'événement"
        noScroll
      >

      </Panel>
    </StyledField>
  );
};
SubtypeField.propTypes = {
  onChange: PropTypes.func.isRequired,
  value: PropTypes.object,
  name: PropTypes.string.isRequired,
  options: PropTypes.arrayOf(PropTypes.object),
  error: PropTypes.string,
  disabled: PropTypes.bool,
  required: PropTypes.bool,
};
export default SubtypeField;
<commit_msg>fix(events): creation form subtypes labels<commit_after>import PropTypes from "prop-types";
import React, { useCallback, useMemo, useState } from "react";
import styled from "styled-components";

import style from "@agir/front/genericComponents/_variables.scss";

import { useResponsiveMemo } from "@agir/front/genericComponents/grid";

import Button from "@agir/front/genericComponents/Button";
import Panel from "@agir/front/genericComponents/Panel";
import { RawFeatherIcon } from "@agir/front/genericComponents/FeatherIcon";

import { EVENT_TYPES } from "./eventForm.config";

const StyledOption = styled.li`
  display: flex;
  flex-flow: row nowrap;
  height: 2.75rem;
  align-items: center;
  font-size: 0.813rem;
  line-height: 1.3;
  color: ${({ $selected }) => ($selected ? style.primary500 : style.black1000)};
  font-weight: ${({ $selected }) => ($selected ? 600 : 400)};
  cursor: ${({ $selected }) => ($selected ? "default" : "pointer")};

  button {
    display: ${({ $selected }) => ($selected ? "none" : "inline")};
    margin-left: auto;
  }

  span {
    color: ${style.primary500};
    display: inline-block;
    font-size: 1.5rem;
    padding-right: 0.5rem;
  }
`;

const StyledOptions = styled.div`
  display: flex;
  flex-flow: column nowrap;
  padding-top: 0.5rem;

  ul {
    padding: 0;
    list-style: none;

    strong {
      display: block;
      height: 2.75rem;
      font-weight: 600;
      font-size: 1rem;
      line-height: 1.5;
      display: flex;
      align-items: center;
    }
  }
`;

const StyledDefaultOption = styled.button``;
const StyledDefaultOptions = styled.div`
  display: flex;
  flex-flow: row wrap;
  gap: 0.5rem;

  button {
    border-radius: 0;
    border: none;
    box-shadow: none;
    padding: 0;
    background-color: transparent;
    font-size: 0.813rem;
    font-weight: 600;
    cursor: pointer;
    color: ${style.primary500};

    &[disabled],
    &[disabled]:hover {
      opacity: 0.5;
      cursor: default;
    }
  }

  ${StyledDefaultOption} {
    padding: 0.5rem 0.75rem;
    color: ${style.black1000};
    display: inline-grid;
    grid-gap: 0.5rem;
    grid-template-columns: auto auto auto;
    align-items: center;
    border: 1px solid ${style.black100};

    &:hover {
      background-color: ${style.black50};
    }

    &[disabled],
    &[disabled]:hover {
      opacity: 1;
      background-color: transparent;
      cursor: default;
    }
  }
`;

const StyledField = styled.div`
  label {
    font-size: 0.813rem;
    font-weight: 600;
    line-height: 1;
    padding: 4px 0;
  }
`;

const SubtypeOption = (props) => {
  const { option, onClick, selected } = props;

  const handleClick = useCallback(() => {
    onClick(option);
  }, [option, onClick]);

  return (

  );
};

const DefaultOption = (props) => {
  const { option, onClick, selected, disabled } = props;

  const handleClick = useCallback(() => {
    onClick(option);
  }, [option, onClick]);

  return (

  );
};
SubtypeOption.propTypes = DefaultOption.propTypes = {
  option: PropTypes.shape({
    id: PropTypes.number,
    label: PropTypes.string,
    iconName: PropTypes.string,
    color: PropTypes.String,
    description: PropTypes.string,
  }),
  onClick: PropTypes.func,
  selected: PropTypes.bool,
  disabled: PropTypes.bool,
};

const SubtypeField = (props) => {
  const { onChange, value, name, error, disabled } = props;
  const [isPanelOpen, setIsPanelOpen] = useState(false);
  const openPanel = useCallback(() => {
    setIsPanelOpen(true);
  }, []);
  const closePanel = useCallback(() => {
    setIsPanelOpen(false);
  }, []);
  const panelPosition = useResponsiveMemo("right", "left");

  const handleChange = useCallback(
    (subtype) => {
      onChange(name, subtype);
      setIsPanelOpen(false);
    },
    [onChange, name]
  );

  const subtypes = useMemo(
    () => (Array.isArray(props.options) ? props.options : []),
    [props.options]
  );

  const options = useMemo(() => {
    const categories = { ...EVENT_TYPES };
    subtypes.forEach((subtype) => {
      const category =
        subtype.type && categories[subtype.type] ? subtype.type : "O";
      categories[category].subtypes = categories[category].subtypes || [];
      categories[category].subtypes.push(subtype);
    });

    return Object.values(categories).filter((category) =>
      Array.isArray(category.subtypes)
    );
  }, [subtypes]);

  const defaultOptions = useMemo(() => subtypes.slice(0, 4), [subtypes]);

  return (

      <Panel
        position={panelPosition}
        shouldShow={isPanelOpen}
        onClose={closePanel}
        onBack={closePanel}
        title="Type de l'événement"
        noScroll
      >

      </Panel>
    </StyledField>
  );
};
SubtypeField.propTypes = {
  onChange: PropTypes.func.isRequired,
  value: PropTypes.object,
  name: PropTypes.string.isRequired,
  options: PropTypes.arrayOf(PropTypes.object),
  error: PropTypes.string,
  disabled: PropTypes.bool,
  required: PropTypes.bool,
};
export default SubtypeField;
<|endoftext|>


<commit_before>import * as types from './authActionTypes';

const initialState = {
  isUserSignedIn: false,
  isInProgress: false,
  hasError: false,
  errorMessage: '',
  uid: 0,
  displayName: ''
};

export function auth(state = initialState, action) {
  switch(action.type) {
    case types.SIGNIN_SUCCESS:
      const { uid, displayName } = action;
      return {
        ...state,
        isUserSignedIn: true,
        isInProgress: false,
        uid,
        displayName
      };
    case types.SIGNIN:
      return {
        ...state,
        isInProgress: true
      };
    case types.SIGIN_ERROR:
      const { errorMessage } = action;
      return {
        ...state,
        hasError: true,
        errorMessage
      };
    default:
      return state;
  }
}
<commit_msg>fix the typo in variable name<commit_after>import * as types from './authActionTypes';

const initialState = {
  isUserSignedIn: false,
  isInProgress: false,
  hasError: false,
  errorMessage: '',
  uid: 0,
  displayName: ''
};

export function auth(state = initialState, action) {
  switch(action.type) {
    case types.SIGNIN_SUCCESS:
      const { uid, displayName } = action;
      return {
        ...state,
        isUserSignedIn: true,
        isInProgress: false,
        uid,
        displayName
      };
    case types.SIGNIN:
      return {
        ...state,
        isInProgress: true
      };
    case types.SIGNIN_ERROR:
      const { errorMessage } = action;
      return {
        ...state,
        hasError: true,
        errorMessage
      };
    default:
      return state;
  }
}
<|endoftext|>


<commit_before>"use strict";

module.exports = async(bot, logger, modules) => {
	const format = (time) => {
        let pad = (s) => {
            return (s < 10 ? '0' : '') + s;
        }
        let hours = Math.floor(time / (60*60));
        let minutes = Math.floor(time % (60*60) / 60);
        let seconds = Math.floor(time % 60);

		/*return pad(hours) + '{hour} ' + pad(minutes) + '{min} ' + pad(seconds)+'{sec}';*/
		return pad(hours) + ':' + pad(minutes) + ':' + pad(seconds);
	}
    bot.onText(new RegExp('^\/(?:작동시간|uptime)+(?:@'+global.botinfo.username+')?'), async (msg, match) => {
		if(Math.round((new Date()).getTime() / 1000) - msg.date <= 180) {
			const chatid = msg.chat.id;
			let temp;
			try {
				logger.info('chatid: '+chatid+', username: '+modules.getuser(msg.from)+', lang: '+msg.from.language_code+', command: '+msg.text+', type: command received');
				temp = await modules.getlang(msg, logger);
				bot.sendMessage(chatid, "✅ "+temp.text(msg.chat.type, 'command.uptime.message')
					.replace(/{uptime}/g, format(process.uptime()))
					/*.replace(/{hour}/g, temp.person('command.uptime.hour'))
					.replace(/{min}/g, temp.person('command.uptime.min'))
					.replace(/{sec}/g, temp.person('command.uptime.sec')), */{
					reply_to_message_id: msg.message_id});
				logger.info('chatid: '+chatid+', username: '+modules.getuser(msg.from)+', lang: '+msg.from.language_code+', command: '+msg.text+', type: valid');
			} catch (e) {
				logger.error('chatid: '+chatid+', username: '+modules.getuser(msg.from)+', lang: '+msg.from.language_code+', command: '+msg.text+', type: error');
				logger.debug(e.stack);
			}
		}
	});
}<commit_msg>오류 수정<commit_after>"use strict";

module.exports = async(bot, logger, modules) => {
	const format = (time) => {
        let pad = (s) => {
            return (s < 10 ? '0' : '') + s;
        }
        let hours = Math.floor(time / (60*60));
        let minutes = Math.floor(time % (60*60) / 60);
        let seconds = Math.floor(time % 60);

		/*return pad(hours) + '{hour} ' + pad(minutes) + '{min} ' + pad(seconds)+'{sec}';*/
		return pad(hours) + ':' + pad(minutes) + ':' + pad(seconds);
	}
    bot.onText(new RegExp('^\/(?:작동시간|uptime)+(?:@'+global.botinfo.username+')?'), async (msg, match) => {
		if(Math.round((new Date()).getTime() / 1000) - msg.date <= 180) {
			const chatid = msg.chat.id;
			let temp;
			try {
				logger.info('chatid: '+chatid+', username: '+modules.getuser(msg.from)+', lang: '+msg.from.language_code+', command: '+msg.text+', type: command received');
				temp = await modules.getlang(msg, logger);
				bot.sendMessage(chatid, "✅ "+temp.text(msg.chat.type, 'command.uptime.message')
					.replace(/{uptime}/g, format(process.uptime()))
					/*.replace(/{hour}/g, temp.person('command.uptime.hour'))
					.replace(/{min}/g, temp.person('command.uptime.min'))
					.replace(/{sec}/g, temp.person('command.uptime.sec'))*/, {
					reply_to_message_id: msg.message_id});
				logger.info('chatid: '+chatid+', username: '+modules.getuser(msg.from)+', lang: '+msg.from.language_code+', command: '+msg.text+', type: valid');
			} catch (e) {
				logger.error('chatid: '+chatid+', username: '+modules.getuser(msg.from)+', lang: '+msg.from.language_code+', command: '+msg.text+', type: error');
				logger.debug(e.stack);
			}
		}
	});
}<|endoftext|>


<commit_before>(function() {
  var count = "";
  var sdir = "f";
  var buf = "";
  var yank = 0;
  var mark = [];
  function emptyBuffer() { buf = ""; }
  function pushInBuffer(str) { buf += str; };
  function pushCountDigit(digit) { return function(cm) {count += digit;} }
  function popCount() { var i = parseInt(count); count = ""; return i || 1; }
  function countTimes(func) {
    if (typeof func == "string") func = CodeMirror.commands[func];
    return function(cm) { for (var i = 0, c = popCount(); i < c; ++i) func(cm); }
  }

  function iterObj(o, f) {
    for (var prop in o) if (o.hasOwnProperty(prop)) f(prop, o[prop]);
  }

  var word = [/\w/, /[^\w\s]/], bigWord = [/\S/];
  function findWord(line, pos, dir, regexps) {
    var stop = 0, next = -1;
    if (dir > 0) { stop = line.length; next = 0; }
    var start = stop, end = stop;
    // Find bounds of next one.
    outer: for (; pos != stop; pos += dir) {
      for (var i = 0; i < regexps.length; ++i) {
        if (regexps[i].test(line.charAt(pos + next))) {
          start = pos;
          for (; pos != stop; pos += dir) {
            if (!regexps[i].test(line.charAt(pos + next))) break;
          }
          end = pos;
          break outer;
        }
      }
    }
    return {from: Math.min(start, end), to: Math.max(start, end)};
  }
  function moveToWord(cm, regexps, dir, where) {
    var cur = cm.getCursor(), ch = cur.ch, line = cm.getLine(cur.line), word;
    while (true) {
      word = findWord(line, ch, dir, regexps);
      ch = word[where == "end" ? "to" : "from"];
      if (ch == cur.ch && word.from != word.to) ch = word[dir < 0 ? "from" : "to"];
      else break;
    }
    cm.setCursor(cur.line, word[where == "end" ? "to" : "from"], true);
  }
  function joinLineNext(cm) {
    var cur = cm.getCursor(), ch = cur.ch, line = cm.getLine(cur.line);
    CodeMirror.commands.goLineEnd(cm);
    if (cur.line != cm.lineCount()) {
      CodeMirror.commands.goLineEnd(cm);
      cm.replaceSelection(" ", "end");
      CodeMirror.commands.delCharRight(cm);
    }
  }
  function editCursor(mode) {
    if (mode == "vim-insert") {
      // put in your cursor css changing code
    } else if (mode == "vim") {
      // put in your cursor css changing code
    }
  }
  function delTillMark(cm, cHar) {
    var i = mark[cHar], l = cm.getCursor().line, start = i > l ? l : i, end = i > l ? i : l;
    cm.setCursor(start);
    for (var c = start; c <= end; c++) {
      pushInBuffer("\n"+cm.getLine(start));
      cm.removeLine(start);
    }
  }
  function yankTillMark(cm, cHar) {
    var i = mark[cHar], l = cm.getCursor().line, start = i > l ? l : i, end = i > l ? i : l;
    for (var c = start; c <= end; c++) {
      pushInBuffer("\n"+cm.getLine(c));
    }
    cm.setCursor(start);
  }
  function goLineStartText(cm) {
    // Go to the start of the line where the text begins, or the end for whitespace-only lines
    var cur = cm.getCursor(), firstNonWS = cm.getLine(cur.line).search(/\S/);
    cm.setCursor(cur.line, firstNonWS == -1 ? line.length : firstNonWS, true);
  }

  var map = CodeMirror.keyMap.vim = {
    "0": function(cm) {count.length > 0 ? pushCountDigit("0")(cm) : CodeMirror.commands.goLineStart(cm);},
    // Pipe (|); TODO: should be *screen* chars, so need a util function to turn tabs into spaces?
    "Shift-\\": function(cm) {cm.setCursor(cm.getCursor().line, popCount() - 1, true);},
    // Shift-6 is caret (^)
    "Shift-6": function(cm) {popCount(); goLineStartText(cm);},
    "A": function(cm) {popCount(); cm.setCursor(cm.getCursor().line, cm.getCursor().ch+1, true); cm.setOption("keyMap", "vim-insert"); editCursor("vim-insert");},
    "Shift-A": function(cm) {popCount(); CodeMirror.commands.goLineEnd(cm); cm.setOption("keyMap", "vim-insert"); editCursor("vim-insert");},
    "I": function(cm) {popCount(); cm.setOption("keyMap", "vim-insert"); editCursor("vim-insert");},
    "Shift-I": function(cm) {popCount(); goLineStartText(cm); cm.setOption("keyMap", "vim-insert"); editCursor("vim-insert");},
    "O": function(cm) {popCount(); CodeMirror.commands.goLineEnd(cm); cm.replaceSelection("\n", "end"); cm.setOption("keyMap", "vim-insert"); editCursor("vim-insert");},
    "Shift-O": function(cm) {popCount(); CodeMirror.commands.goLineStart(cm); cm.replaceSelection("\n", "start"); cm.setOption("keyMap", "vim-insert"); editCursor("vim-insert");},
    "G": function(cm) {cm.setOption("keyMap", "vim-prefix-g");},
    "D": function(cm) {cm.setOption("keyMap", "vim-prefix-d"); emptyBuffer();},
    "Shift-D": function(cm) {
      emptyBuffer();
      mark["Shift-D"] = cm.getCursor(false).line;
      cm.setCursor(cm.getCursor(true).line);
      delTillMark(cm,"Shift-D"); mark = [];
    },
    "M": function(cm) {cm.setOption("keyMap", "vim-prefix-m"); mark = [];},
    "Y": function(cm) {cm.setOption("keyMap", "vim-prefix-y"); emptyBuffer(); yank = 0;},
    "Shift-Y": function(cm) {
      emptyBuffer();
      mark["Shift-D"] = cm.getCursor(false).line;
      cm.setCursor(cm.getCursor(true).line);
      yankTillMark(cm,"Shift-D"); mark = [];
    },
    "/": function(cm) {var f = CodeMirror.commands.find; f && f(cm); sdir = "f"},
    "Shift-/": function(cm) {
      var f = CodeMirror.commands.find;
      if (f) { f(cm); CodeMirror.commands.findPrev(cm); sdir = "r"; }
    },
    "N": function(cm) {
      var fn = CodeMirror.commands.findNext;
      if (fn) sdir != "r" ? fn(cm) : CodeMirror.commands.findPrev(cm);
    },
    "Shift-N": function(cm) {
      var fn = CodeMirror.commands.findNext;
      if (fn) sdir != "r" ? CodeMirror.commands.findPrev(cm) : fn.findNext(cm);
    },
    "Shift-G": function(cm) {count == "" ? cm.setCursor(cm.lineCount()) : cm.setCursor(parseInt(count)-1); popCount(); CodeMirror.commands.goLineStart(cm);},
    catchall: function(cm) {/*ignore*/}
  };
  // Add bindings for number keys
  for (var i = 1; i < 10; ++i) map[i] = pushCountDigit(i);
  // Add bindings that are influenced by number keys
  iterObj({
    "H": "goColumnLeft", "L": "goColumnRight", "J": "goLineDown",
    "K": "goLineUp", "Left": "goColumnLeft", "Right": "goColumnRight",
    "Down": "goLineDown", "Up": "goLineUp", "Backspace": "goCharLeft",
    "Space": "goCharRight",
    "B": function(cm) {moveToWord(cm, word, -1, "end");},
    "E": function(cm) {moveToWord(cm, word, 1, "end");},
    "W": function(cm) {moveToWord(cm, word, 1, "start");},
    "Shift-B": function(cm) {moveToWord(cm, bigWord, -1, "end");},
    "Shift-E": function(cm) {moveToWord(cm, bigWord, 1, "end");},
    "Shift-W": function(cm) {moveToWord(cm, bigWord, 1, "start");},
    "X": function(cm) {CodeMirror.commands.delCharRight(cm)},
    "P": function(cm) {
      var cur = cm.getCursor().line;
      if (buf!= "") {
        CodeMirror.commands.goLineEnd(cm);
        cm.replaceSelection(buf, "end");
      }
      cm.setCursor(cur+1);
    },
    "Shift-X": function(cm) {CodeMirror.commands.delCharLeft(cm)},
    "Shift-J": function(cm) {joinLineNext(cm)},
    "Shift-`": function(cm) {
      var cur = cm.getCursor(), cHar = cm.getRange({line: cur.line, ch: cur.ch}, {line: cur.line, ch: cur.ch+1});
      cHar = cHar != cHar.toLowerCase() ? cHar.toLowerCase() : cHar.toUpperCase();
      cm.replaceRange(cHar, {line: cur.line, ch: cur.ch}, {line: cur.line, ch: cur.ch+1});
      cm.setCursor(cur.line, cur.ch+1);
    },
    "Ctrl-B": function(cm) {CodeMirror.commands.goPageUp(cm)},
    "Ctrl-F": function(cm) {CodeMirror.commands.goPageDown(cm)},
    "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
    "U": "undo", "Ctrl-R": "redo", "Shift-4": "goLineEnd"
   }, function(key, cmd) { map[key] = countTimes(cmd); });

  CodeMirror.keyMap["vim-prefix-g"] = {
    "E": countTimes(function(cm) { moveToWord(cm, word, -1, "start");}),
    "Shift-E": countTimes(function(cm) { moveToWord(cm, bigWord, -1, "start");}),
    auto: "vim",
    catchall: function(cm) {/*ignore*/}
  };

  CodeMirror.keyMap["vim-prefix-m"] = {
    auto: "vim",
    catchall: function(cm) {/*ignore*/}
  };

  CodeMirror.keyMap["vim-prefix-d"] = {
    "D": countTimes(function(cm) { pushInBuffer("\n"+cm.getLine(cm.getCursor().line)); cm.removeLine(cm.getCursor().line); }),
    "'": function(cm) {cm.setOption("keyMap", "vim-prefix-d'"); emptyBuffer();},
    auto: "vim",
    catchall: function(cm) {/*ignore*/}
  };

  CodeMirror.keyMap["vim-prefix-d'"] = {
    auto: "vim",
    catchall: function(cm) {/*ignore*/}
  };

  CodeMirror.keyMap["vim-prefix-y'"] = {
    auto: "vim",
    catchall: function(cm) {/*ignore*/}
  };

  // iterate through uppercase alphabet char codes
  for (var i = 65; i < 65 + 26; i++) {
    // apply for `letter` and 'Shift-' + `letter`
    for (var m = String.fromCharCode(i); m.length < 8; m = "Shift-" + m) {
      CodeMirror.keyMap["vim-prefix-m"][m] = function(cm) {
        mark[m] = cm.getCursor().line;
      };
      CodeMirror.keyMap["vim-prefix-d'"][m] = function(cm) {
        delTillMark(cm,m);
      };
      CodeMirror.keyMap["vim-prefix-y'"][m] = function(cm) {
        yankTillMark(cm,m);
      };
    }
  }

  CodeMirror.keyMap["vim-prefix-y"] = {
    "Y": countTimes(function(cm) { pushInBuffer("\n"+cm.getLine(cm.getCursor().line+yank)); yank++; }),
    "'": function(cm) {cm.setOption("keyMap", "vim-prefix-y'"); emptyBuffer();},
    auto: "vim",
    catchall: function(cm) {/*ignore*/}
  };

  CodeMirror.keyMap["vim-insert"] = {
    "Esc": function(cm) {
      cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1, true);
      cm.setOption("keyMap", "vim");
      editCursor("vim");
           },
    "Ctrl-N": function(cm) {/* Code to bring up autocomplete hint */},
    "Ctrl-P": function(cm) {/* Code to bring up autocomplete hint */},
    fallthrough: ["default"]
  };
})();
<commit_msg>Vim keymap: fix o and O to put in automatic indentation.<commit_after>(function() {
  var count = "";
  var sdir = "f";
  var buf = "";
  var yank = 0;
  var mark = [];
  function emptyBuffer() { buf = ""; }
  function pushInBuffer(str) { buf += str; };
  function pushCountDigit(digit) { return function(cm) {count += digit;} }
  function popCount() { var i = parseInt(count); count = ""; return i || 1; }
  function countTimes(func) {
    if (typeof func == "string") func = CodeMirror.commands[func];
    return function(cm) { for (var i = 0, c = popCount(); i < c; ++i) func(cm); }
  }

  function iterObj(o, f) {
    for (var prop in o) if (o.hasOwnProperty(prop)) f(prop, o[prop]);
  }

  var word = [/\w/, /[^\w\s]/], bigWord = [/\S/];
  function findWord(line, pos, dir, regexps) {
    var stop = 0, next = -1;
    if (dir > 0) { stop = line.length; next = 0; }
    var start = stop, end = stop;
    // Find bounds of next one.
    outer: for (; pos != stop; pos += dir) {
      for (var i = 0; i < regexps.length; ++i) {
        if (regexps[i].test(line.charAt(pos + next))) {
          start = pos;
          for (; pos != stop; pos += dir) {
            if (!regexps[i].test(line.charAt(pos + next))) break;
          }
          end = pos;
          break outer;
        }
      }
    }
    return {from: Math.min(start, end), to: Math.max(start, end)};
  }
  function moveToWord(cm, regexps, dir, where) {
    var cur = cm.getCursor(), ch = cur.ch, line = cm.getLine(cur.line), word;
    while (true) {
      word = findWord(line, ch, dir, regexps);
      ch = word[where == "end" ? "to" : "from"];
      if (ch == cur.ch && word.from != word.to) ch = word[dir < 0 ? "from" : "to"];
      else break;
    }
    cm.setCursor(cur.line, word[where == "end" ? "to" : "from"], true);
  }
  function joinLineNext(cm) {
    var cur = cm.getCursor(), ch = cur.ch, line = cm.getLine(cur.line);
    CodeMirror.commands.goLineEnd(cm);
    if (cur.line != cm.lineCount()) {
      CodeMirror.commands.goLineEnd(cm);
      cm.replaceSelection(" ", "end");
      CodeMirror.commands.delCharRight(cm);
    }
  }
  function editCursor(mode) {
    if (mode == "vim-insert") {
      // put in your cursor css changing code
    } else if (mode == "vim") {
      // put in your cursor css changing code
    }
  }
  function delTillMark(cm, cHar) {
    var i = mark[cHar], l = cm.getCursor().line, start = i > l ? l : i, end = i > l ? i : l;
    cm.setCursor(start);
    for (var c = start; c <= end; c++) {
      pushInBuffer("\n"+cm.getLine(start));
      cm.removeLine(start);
    }
  }
  function yankTillMark(cm, cHar) {
    var i = mark[cHar], l = cm.getCursor().line, start = i > l ? l : i, end = i > l ? i : l;
    for (var c = start; c <= end; c++) {
      pushInBuffer("\n"+cm.getLine(c));
    }
    cm.setCursor(start);
  }
  function goLineStartText(cm) {
    // Go to the start of the line where the text begins, or the end for whitespace-only lines
    var cur = cm.getCursor(), firstNonWS = cm.getLine(cur.line).search(/\S/);
    cm.setCursor(cur.line, firstNonWS == -1 ? line.length : firstNonWS, true);
  }

  var map = CodeMirror.keyMap.vim = {
    "0": function(cm) {count.length > 0 ? pushCountDigit("0")(cm) : CodeMirror.commands.goLineStart(cm);},
    // Pipe (|); TODO: should be *screen* chars, so need a util function to turn tabs into spaces?
    "Shift-\\": function(cm) {cm.setCursor(cm.getCursor().line, popCount() - 1, true);},
    // Shift-6 is caret (^)
    "Shift-6": function(cm) {popCount(); goLineStartText(cm);},
    "A": function(cm) {popCount(); cm.setCursor(cm.getCursor().line, cm.getCursor().ch+1, true); cm.setOption("keyMap", "vim-insert"); editCursor("vim-insert");},
    "Shift-A": function(cm) {popCount(); CodeMirror.commands.goLineEnd(cm); cm.setOption("keyMap", "vim-insert"); editCursor("vim-insert");},
    "I": function(cm) {popCount(); cm.setOption("keyMap", "vim-insert"); editCursor("vim-insert");},
    "Shift-I": function(cm) {popCount(); goLineStartText(cm); cm.setOption("keyMap", "vim-insert"); editCursor("vim-insert");},
    "O": function(cm) {popCount(); CodeMirror.commands.goLineEnd(cm); CodeMirror.commands.newlineAndIndent(cm); cm.setOption("keyMap", "vim-insert"); editCursor("vim-insert");},
    "Shift-O": function(cm) {popCount(); CodeMirror.commands.goLineStart(cm); cm.replaceSelection("\n", "start"); cm.indentLine(cm.getCursor().line); cm.setOption("keyMap", "vim-insert"); editCursor("vim-insert");},
    "G": function(cm) {cm.setOption("keyMap", "vim-prefix-g");},
    "D": function(cm) {cm.setOption("keyMap", "vim-prefix-d"); emptyBuffer();},
    "Shift-D": function(cm) {
      emptyBuffer();
      mark["Shift-D"] = cm.getCursor(false).line;
      cm.setCursor(cm.getCursor(true).line);
      delTillMark(cm,"Shift-D"); mark = [];
    },
    "M": function(cm) {cm.setOption("keyMap", "vim-prefix-m"); mark = [];},
    "Y": function(cm) {cm.setOption("keyMap", "vim-prefix-y"); emptyBuffer(); yank = 0;},
    "Shift-Y": function(cm) {
      emptyBuffer();
      mark["Shift-D"] = cm.getCursor(false).line;
      cm.setCursor(cm.getCursor(true).line);
      yankTillMark(cm,"Shift-D"); mark = [];
    },
    "/": function(cm) {var f = CodeMirror.commands.find; f && f(cm); sdir = "f"},
    "Shift-/": function(cm) {
      var f = CodeMirror.commands.find;
      if (f) { f(cm); CodeMirror.commands.findPrev(cm); sdir = "r"; }
    },
    "N": function(cm) {
      var fn = CodeMirror.commands.findNext;
      if (fn) sdir != "r" ? fn(cm) : CodeMirror.commands.findPrev(cm);
    },
    "Shift-N": function(cm) {
      var fn = CodeMirror.commands.findNext;
      if (fn) sdir != "r" ? CodeMirror.commands.findPrev(cm) : fn.findNext(cm);
    },
    "Shift-G": function(cm) {count == "" ? cm.setCursor(cm.lineCount()) : cm.setCursor(parseInt(count)-1); popCount(); CodeMirror.commands.goLineStart(cm);},
    catchall: function(cm) {/*ignore*/}
  };
  // Add bindings for number keys
  for (var i = 1; i < 10; ++i) map[i] = pushCountDigit(i);
  // Add bindings that are influenced by number keys
  iterObj({
    "H": "goColumnLeft", "L": "goColumnRight", "J": "goLineDown",
    "K": "goLineUp", "Left": "goColumnLeft", "Right": "goColumnRight",
    "Down": "goLineDown", "Up": "goLineUp", "Backspace": "goCharLeft",
    "Space": "goCharRight",
    "B": function(cm) {moveToWord(cm, word, -1, "end");},
    "E": function(cm) {moveToWord(cm, word, 1, "end");},
    "W": function(cm) {moveToWord(cm, word, 1, "start");},
    "Shift-B": function(cm) {moveToWord(cm, bigWord, -1, "end");},
    "Shift-E": function(cm) {moveToWord(cm, bigWord, 1, "end");},
    "Shift-W": function(cm) {moveToWord(cm, bigWord, 1, "start");},
    "X": function(cm) {CodeMirror.commands.delCharRight(cm)},
    "P": function(cm) {
      var cur = cm.getCursor().line;
      if (buf!= "") {
        CodeMirror.commands.goLineEnd(cm);
        cm.replaceSelection(buf, "end");
      }
      cm.setCursor(cur+1);
    },
    "Shift-X": function(cm) {CodeMirror.commands.delCharLeft(cm)},
    "Shift-J": function(cm) {joinLineNext(cm)},
    "Shift-`": function(cm) {
      var cur = cm.getCursor(), cHar = cm.getRange({line: cur.line, ch: cur.ch}, {line: cur.line, ch: cur.ch+1});
      cHar = cHar != cHar.toLowerCase() ? cHar.toLowerCase() : cHar.toUpperCase();
      cm.replaceRange(cHar, {line: cur.line, ch: cur.ch}, {line: cur.line, ch: cur.ch+1});
      cm.setCursor(cur.line, cur.ch+1);
    },
    "Ctrl-B": function(cm) {CodeMirror.commands.goPageUp(cm)},
    "Ctrl-F": function(cm) {CodeMirror.commands.goPageDown(cm)},
    "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
    "U": "undo", "Ctrl-R": "redo", "Shift-4": "goLineEnd"
   }, function(key, cmd) { map[key] = countTimes(cmd); });

  CodeMirror.keyMap["vim-prefix-g"] = {
    "E": countTimes(function(cm) { moveToWord(cm, word, -1, "start");}),
    "Shift-E": countTimes(function(cm) { moveToWord(cm, bigWord, -1, "start");}),
    auto: "vim",
    catchall: function(cm) {/*ignore*/}
  };

  CodeMirror.keyMap["vim-prefix-m"] = {
    auto: "vim",
    catchall: function(cm) {/*ignore*/}
  };

  CodeMirror.keyMap["vim-prefix-d"] = {
    "D": countTimes(function(cm) { pushInBuffer("\n"+cm.getLine(cm.getCursor().line)); cm.removeLine(cm.getCursor().line); }),
    "'": function(cm) {cm.setOption("keyMap", "vim-prefix-d'"); emptyBuffer();},
    auto: "vim",
    catchall: function(cm) {/*ignore*/}
  };

  CodeMirror.keyMap["vim-prefix-d'"] = {
    auto: "vim",
    catchall: function(cm) {/*ignore*/}
  };

  CodeMirror.keyMap["vim-prefix-y'"] = {
    auto: "vim",
    catchall: function(cm) {/*ignore*/}
  };

  // iterate through uppercase alphabet char codes
  for (var i = 65; i < 65 + 26; i++) {
    // apply for `letter` and 'Shift-' + `letter`
    for (var m = String.fromCharCode(i); m.length < 8; m = "Shift-" + m) {
      CodeMirror.keyMap["vim-prefix-m"][m] = function(cm) {
        mark[m] = cm.getCursor().line;
      };
      CodeMirror.keyMap["vim-prefix-d'"][m] = function(cm) {
        delTillMark(cm,m);
      };
      CodeMirror.keyMap["vim-prefix-y'"][m] = function(cm) {
        yankTillMark(cm,m);
      };
    }
  }

  CodeMirror.keyMap["vim-prefix-y"] = {
    "Y": countTimes(function(cm) { pushInBuffer("\n"+cm.getLine(cm.getCursor().line+yank)); yank++; }),
    "'": function(cm) {cm.setOption("keyMap", "vim-prefix-y'"); emptyBuffer();},
    auto: "vim",
    catchall: function(cm) {/*ignore*/}
  };

  CodeMirror.keyMap["vim-insert"] = {
    // TODO: override navigation keys so that Esc will cancel automatic indentation from o, O, i_<CR>
    "Esc": function(cm) {
      cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1, true);
      cm.setOption("keyMap", "vim");
      editCursor("vim");
           },
    "Ctrl-N": function(cm) {/* Code to bring up autocomplete hint */},
    "Ctrl-P": function(cm) {/* Code to bring up autocomplete hint */},
    fallthrough: ["default"]
  };
})();
<|endoftext|>


<commit_before>export { Pointwise };

import * as FloatValue from "../../Unpacker/FloatValue.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import * as Weights from "../../Unpacker/Weights.js";
import { ConvBiasActivation } from "./BoundsArraySet_ConvBiasActivation.js";
import { ChannelPartInfo, FiltersBiasesPartInfo } from  "../Pointwise/Pointwise_ChannelPartInfo.js";

/**
 * The element value bounds for pointwise convolution-bias-activation.
 *
 */
class Pointwise extends ConvBiasActivation {

  /**
   */
  constructor( inputChannelCount, outputChannelCount ) {
    super( inputChannelCount, outputChannelCount );
  }

  /**
   * Set this.bPassThrough[] according to inChannelPartInfoArray.
   *
   * @param {Pointwise.FiltersBiasesPartInfo[]} aFiltersBiasesPartInfoArray
   *   The input channel range array which describe lower/higher half channels index range.
   */
  set_bPassThrough_all_byChannelPartInfoArray( aFiltersBiasesPartInfoArray ) {

    let outChannelBegin = 0, outChannelEnd = 0; // [ outChannelBegin, outChannelEnd ) are output channels of the current FiltersBiasesPart.

    FiltersBiasesPartIndexLoop:
    for ( let aFiltersBiasesPartIndex = 0; aFiltersBiasesPartIndex < aFiltersBiasesPartInfoArray.length; ++aFiltersBiasesPartIndex ) {
      let aFiltersBiasesPartInfo = aFiltersBiasesPartInfoArray[ aFiltersBiasesPartIndex ];
      let inChannelPartInfoArray = aFiltersBiasesPartInfo.aChannelPartInfoArray;

      outChannelBegin = outChannelEnd; // Begin from the ending of the previous FiltersBiasesPart.

      {
        let outChannel = outChannelBegin;

        InChannelPartIndexLoop:
        for ( let inChannelPartIndex = 0; inChannelPartIndex < inChannelPartInfoArray.length; ++inChannelPartIndex ) {
          let inChannelPartInfo = inChannelPartInfoArray[ inChannelPartIndex ];

          for ( let outChannelSub = 0; outChannelSub < inChannelPartInfo.outputChannelCount; ++outChannelSub, ++outChannel ) {
            if ( outChannel >= this.outputChannelCount )
              break InChannelPartIndexLoop; // Never exceeds the total output channel count.

              this.bPassThrough[ outChannel ] = inChannelPartInfo.bPassThrough;

          } // outChannelSub, outChannel
        } // inChannelPartIndex

        outChannelEnd = outChannel; // Record the ending output channel index of the current FiltersBiasesPart.
      }

    } // aFiltersBiasesPartIndex

  }

}

<commit_msg>Update BoundsArraySet_Pointwise.js<commit_after>export { Pointwise };

import * as FloatValue from "../../Unpacker/FloatValue.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import * as Weights from "../../Unpacker/Weights.js";
import { ConvBiasActivation } from "./BoundsArraySet_ConvBiasActivation.js";
import { ChannelPartInfo, FiltersBiasesPartInfo } from  "../Pointwise/Pointwise_ChannelPartInfo.js";

/**
 * The element value bounds for pointwise convolution-bias-activation.
 *
 * Only outputChannelCount0 is used. The outputChannelCount1 always undefined.
 *
 * @see ConvBiasActivation
 */
class Pointwise extends ConvBiasActivation {

  /**
   */
  constructor( inputs, outputChannelCount0 ) {
    super( inputs, outputChannelCount0 );
  }

  /**
   * Set this.bPassThrough[] according to inChannelPartInfoArray.
   *
   * @param {Pointwise.FiltersBiasesPartInfo[]} aFiltersBiasesPartInfoArray
   *   The input channel range array which describe lower/higher half channels index range.
   */
  set_bPassThrough_all_byChannelPartInfoArray( aFiltersBiasesPartInfoArray ) {

    let outChannelBegin = 0, outChannelEnd = 0; // [ outChannelBegin, outChannelEnd ) are output channels of the current FiltersBiasesPart.

    FiltersBiasesPartIndexLoop:
    for ( let aFiltersBiasesPartIndex = 0; aFiltersBiasesPartIndex < aFiltersBiasesPartInfoArray.length; ++aFiltersBiasesPartIndex ) {
      let aFiltersBiasesPartInfo = aFiltersBiasesPartInfoArray[ aFiltersBiasesPartIndex ];
      let inChannelPartInfoArray = aFiltersBiasesPartInfo.aChannelPartInfoArray;

      outChannelBegin = outChannelEnd; // Begin from the ending of the previous FiltersBiasesPart.

      {
        let outChannel = outChannelBegin;

        InChannelPartIndexLoop:
        for ( let inChannelPartIndex = 0; inChannelPartIndex < inChannelPartInfoArray.length; ++inChannelPartIndex ) {
          let inChannelPartInfo = inChannelPartInfoArray[ inChannelPartIndex ];

          for ( let outChannelSub = 0; outChannelSub < inChannelPartInfo.outputChannelCount; ++outChannelSub, ++outChannel ) {
            if ( outChannel >= this.outputChannelCount )
              break InChannelPartIndexLoop; // Never exceeds the total output channel count.

              this.bPassThrough[ outChannel ] = inChannelPartInfo.bPassThrough;

          } // outChannelSub, outChannel
        } // inChannelPartIndex

        outChannelEnd = outChannel; // Record the ending output channel index of the current FiltersBiasesPart.
      }

    } // aFiltersBiasesPartIndex

  }

}

<|endoftext|>


<commit_before>/*
 *
 * AvatarsRow
 *
 */

import React from 'react'
import T from 'prop-types'
import R from 'ramda'

import { ATATARS_LIST_LENGTH } from '@config/general'
import { buildLog, prettyNum } from '@utils'

import Tooltip from '@components/Tooltip'

import {
  Wrapper,
  AvatarsItem,
  MoreItem,
  AvatarsImg,
  AvatarsMore,
} from './styles'

/* eslint-disable-next-line */
const log = buildLog('c:AvatarsRow:index')

const validUser = R.compose(
  R.not,
  R.isNil
)

const getUniqueArray = (arr, comp) => {
  const unique = arr
    .map(e => e[comp])

    // store the keys of the unique objects
    .map((e, i, final) => final.indexOf(e) === i && i)

    // eliminate the dead keys & store unique objects
    .filter(e => arr[e])
    .map(e => arr[e])

  return unique
}

const AvatarsRow = ({
  users,
  total,
  height,
  limit,
  onUserSelect,
  onTotalSelect,
  reverse,
}) => {
  if (users.length === 0) {
    return
  }

  users = R.filter(validUser, getUniqueArray(users, 'id'))
  const sortedUsers = reverse ? users : R.reverse(users)

  return (
    <Wrapper height={height}>
      {total <= 1 ? (

      ) : (
        <MoreItem onClick={onTotalSelect.bind(this, { users, total })}>
          <Tooltip content={`所有评论共 ${total} 条`}>
            <AvatarsMore total={total}>{prettyNum(total)}</AvatarsMore>
          </Tooltip>
        </MoreItem>
      )}

      {R.slice(0, limit, sortedUsers).map(user => (
        <AvatarsItem key={user.id} onClick={onUserSelect.bind(this, user)}>
          <Tooltip content={user.nickname} delay={200}>
            <AvatarsImg src={user.avatar} />
          </Tooltip>
        </AvatarsItem>
      ))}
    </Wrapper>
  )
}

AvatarsRow.propTypes = {
  users: T.arrayOf(
    T.shape({
      id: T.string,
      avatar: T.string,
      nickname: T.string,
      extra_id: T.string,
    })
  ),
  total: T.number.isRequired,
  height: T.string,
  limit: T.number,
  onUserSelect: T.func,
  onTotalSelect: T.func,
  reverse: T.bool,
}

AvatarsRow.defaultProps = {
  height: '32px',
  users: [],
  limit: ATATARS_LIST_LENGTH.POSTS,
  onUserSelect: log,
  onTotalSelect: log,
  reverse: true,
}

export default AvatarsRow
<commit_msg>fix(comments): dup init in logic & dup display in avatarRows<commit_after>/*
 *
 * AvatarsRow
 *
 */

import React from 'react'
import T from 'prop-types'
import R from 'ramda'

import { ATATARS_LIST_LENGTH } from '@config/general'
import { buildLog, prettyNum } from '@utils'

import Tooltip from '@components/Tooltip'

import {
  Wrapper,
  AvatarsItem,
  MoreItem,
  AvatarsImg,
  AvatarsMore,
} from './styles'

/* eslint-disable-next-line */
const log = buildLog('c:AvatarsRow:index')

const validUser = R.compose(
  R.not,
  R.isNil
)

const getUniqueArray = (arr, comp) => {
  const unique = arr
    .map(e => e[comp])

    // store the keys of the unique objects
    .map((e, i, final) => final.indexOf(e) === i && i)

    // eliminate the dead keys & store unique objects
    .filter(e => arr[e])
    .map(e => arr[e])

  return unique
}

const AvatarsRow = ({
  users,
  total,
  height,
  limit,
  onUserSelect,
  onTotalSelect,
  reverse,
}) => {
  if (users.length === 0) {
    return
  }

<<<<<<>>>>>> fix(comments): dup init in logic & dup display in avatarRows
  const sortedUsers = reverse ? users : R.reverse(users)

  return (
    <Wrapper height={height}>
      {total <= 1 ? (

      ) : (
        <MoreItem onClick={onTotalSelect.bind(this, { users, total })}>
          <Tooltip content={`所有评论共 ${total} 条`}>
            <AvatarsMore total={total}>{prettyNum(total)}</AvatarsMore>
          </Tooltip>
        </MoreItem>
      )}

      {R.slice(0, limit, sortedUsers).map(user => (
        <AvatarsItem key={user.id} onClick={onUserSelect.bind(this, user)}>
          <Tooltip content={user.nickname} delay={200}>
            <AvatarsImg src={user.avatar} />
          </Tooltip>
        </AvatarsItem>
      ))}
    </Wrapper>
  )
}

AvatarsRow.propTypes = {
  users: T.arrayOf(
    T.shape({
      id: T.string,
      avatar: T.string,
      nickname: T.string,
      extra_id: T.string,
    })
  ),
  total: T.number.isRequired,
  height: T.string,
  limit: T.number,
  onUserSelect: T.func,
  onTotalSelect: T.func,
  reverse: T.bool,
}

AvatarsRow.defaultProps = {
  height: '32px',
  users: [],
  limit: ATATARS_LIST_LENGTH.POSTS,
  onUserSelect: log,
  onTotalSelect: log,
  reverse: true,
}

export default AvatarsRow
<|endoftext|>


<commit_before>// -----------------------------------------------------------------------------
// VARIABLES
// -----------------------------------------------------------------------------

// Default modifier keys for binds
const MODIFIERS = ['ctrl', 'shift']

// Grid width and height for centering windows with different sizes
const GRID_WIDTH = 12
const GRID_HEIGHT = 10

// Margin to have around each window edge
const MARGIN = 10

// -----------------------------------------------------------------------------
// FUNCTIONS
// -----------------------------------------------------------------------------

Bind.on("s", MODIFIERS, () => {
  Stark.run("/usr/bin/open", [
    "/System/Library/Frameworks/ScreenSaver.framework/Versions/Current/Resources/ScreenSaverEngine.app"
  ]);
});

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

Bind.on("z", MODIFIERS, () => {
  const win = Window.focused();
  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.width / GRID_WIDTH) * 2;
  const y = r.y + (r.height / GRID_HEIGHT) * 2;

  const width = (r.width / GRID_WIDTH) * 8;
  const height = (r.height / GRID_HEIGHT) * 6;

  win.setFrame({ x, y, width, height });
});

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

Bind.on("x", MODIFIERS, () => {
  const win = Window.focused();
  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.width / GRID_WIDTH;
  const y = r.y + (r.height / GRID_HEIGHT);

  const width = (r.width / GRID_WIDTH) * 10;
  const height = (r.height / GRID_HEIGHT) * 8;

  win.setFrame({ x, y, width, height });
});

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

Bind.on("c", MODIFIERS, () => {
  const win = Window.focused();
  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width - (MARGIN * 2);
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

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

Bind.on("f", MODIFIERS, () => {
  const win = Window.focused();
  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const width = r.width / 2;
  const height = r.height - (MARGIN * 2);

  const x = r.x + (width / 2);
  const y = r.y + MARGIN;

  win.setFrame({ x, y, width, height });
});

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

Bind.on("h", MODIFIERS, () => {
  const win = Window.focused();
  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

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

Bind.on("l", MODIFIERS, () => {
  const win = Window.focused();
  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.x + (r.width / 2)) + (MARGIN / 2);
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

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

Bind.on("j", MODIFIERS, () => {
  const win = Window.focused();
  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height / 2 - (MARGIN + (MARGIN / 2));

  win.setFrame({ x, y, width, height });
});

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

Bind.on("k", MODIFIERS, () => {
  const win = Window.focused();
  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.x + (r.width / 2)) + (MARGIN / 2);
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height / 2 - (MARGIN + (MARGIN / 2));

  win.setFrame({ x, y, width, height });
});

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

Bind.on("t", MODIFIERS, () => {
  const app = App.find("Tweetbot");
  if (!app) {
    return;
  }

  _.each(app.windows(), (win) => {
    const r = win.screen.frameWithoutDockOrMenu;

    const x = r.x + MARGIN;
    const y = r.y + MARGIN;

    const width = r.width / 4 - (MARGIN + (MARGIN / 2));
    const height = r.height - (MARGIN * 2);

    win.setFrame({ x, y, width, height });
  });
});

// -----------------------------------------------------------------------------
<commit_msg>Update .stark.js margin size<commit_after>// -----------------------------------------------------------------------------
// VARIABLES
// -----------------------------------------------------------------------------

// Default modifier keys for binds
const MODIFIERS = ['ctrl', 'shift']

// Grid width and height for centering windows with different sizes
const GRID_WIDTH = 12
const GRID_HEIGHT = 10

// Margin to have around each window edge
const MARGIN = 5

// -----------------------------------------------------------------------------
// FUNCTIONS
// -----------------------------------------------------------------------------

Bind.on("s", MODIFIERS, () => {
  Stark.run("/usr/bin/open", [
    "/System/Library/Frameworks/ScreenSaver.framework/Versions/Current/Resources/ScreenSaverEngine.app"
  ]);
});

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

Bind.on("z", MODIFIERS, () => {
  const win = Window.focused();
  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.width / GRID_WIDTH) * 2;
  const y = r.y + (r.height / GRID_HEIGHT) * 2;

  const width = (r.width / GRID_WIDTH) * 8;
  const height = (r.height / GRID_HEIGHT) * 6;

  win.setFrame({ x, y, width, height });
});

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

Bind.on("x", MODIFIERS, () => {
  const win = Window.focused();
  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.width / GRID_WIDTH;
  const y = r.y + (r.height / GRID_HEIGHT);

  const width = (r.width / GRID_WIDTH) * 10;
  const height = (r.height / GRID_HEIGHT) * 8;

  win.setFrame({ x, y, width, height });
});

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

Bind.on("c", MODIFIERS, () => {
  const win = Window.focused();
  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width - (MARGIN * 2);
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

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

Bind.on("f", MODIFIERS, () => {
  const win = Window.focused();
  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const width = r.width / 2;
  const height = r.height - (MARGIN * 2);

  const x = r.x + (width / 2);
  const y = r.y + MARGIN;

  win.setFrame({ x, y, width, height });
});

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

Bind.on("h", MODIFIERS, () => {
  const win = Window.focused();
  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

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

Bind.on("l", MODIFIERS, () => {
  const win = Window.focused();
  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.x + (r.width / 2)) + (MARGIN / 2);
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

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

Bind.on("j", MODIFIERS, () => {
  const win = Window.focused();
  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height / 2 - (MARGIN + (MARGIN / 2));

  win.setFrame({ x, y, width, height });
});

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

Bind.on("k", MODIFIERS, () => {
  const win = Window.focused();
  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.x + (r.width / 2)) + (MARGIN / 2);
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height / 2 - (MARGIN + (MARGIN / 2));

  win.setFrame({ x, y, width, height });
});

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

Bind.on("t", MODIFIERS, () => {
  const app = App.find("Tweetbot");
  if (!app) {
    return;
  }

  _.each(app.windows(), (win) => {
    const r = win.screen.frameWithoutDockOrMenu;

    const x = r.x + MARGIN;
    const y = r.y + MARGIN;

    const width = r.width / 4 - (MARGIN + (MARGIN / 2));
    const height = r.height - (MARGIN * 2);

    win.setFrame({ x, y, width, height });
  });
});

// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before>'use babel'

import React from 'react'
import styled from 'styled-components'
import { connect } from 'react-redux'

// Loader with animations
const Wrap = styled.span`
  color: #61AFEF;
  margin-left: 10px;
  cursor: pointer;
`

const StatusBarElement = (props) => {
  return (
    <Wrap {...props}>
      <i className="icon icon-comment-discussion"> {props.counter} </i>
    </Wrap>
  )
}

function mapStateToProps(state) {
  const { channels, teams } = state

  const counter = teams.reduce((acc, team) => {
    return acc + (Object.keys(channels[team.id] || {})).reduce((memo, key) => {
      return memo + channels[team.id][key].unreadCount
    }, 0)
  }, 0)

  return {
    counter,
  }
}

export default connect(mapStateToProps)(StatusBarElement)
<commit_msg>Add color change<commit_after>'use babel'

import React from 'react'
import styled from 'styled-components'
import { connect } from 'react-redux'

// Loader with animations
const Wrap = styled.span`
  color: ${ (props) => props.counter === 0 ? '' : '#61AFEF' };
  margin-left: 10px;
  cursor: pointer;
`

const StatusBarElement = (props) => {
  return (
    <Wrap {...props}>
      <i className="icon icon-comment-discussion"> {props.counter} </i>
    </Wrap>
  )
}

function mapStateToProps(state) {
  const { channels, teams } = state

  const counter = teams.reduce((acc, team) => {
    return acc + (Object.keys(channels[team.id] || {})).reduce((memo, key) => {
      return memo + channels[team.id][key].unreadCount
    }, 0)
  }, 0)

  return {
    counter,
  }
}

export default connect(mapStateToProps)(StatusBarElement)
<|endoftext|>


<commit_before>/*eslint no-bitwise:0 */
const CloakedCollectionView = Ember.CollectionView.extend({
  cloakView: Ember.computed.alias('itemViewClass'),
  topVisible: null,
  bottomVisible: null,
  offsetFixedTopElement: null,
  offsetFixedBottomElement: null,
  loadingHTML: 'Loading...',
  scrollDebounce: 10,

  init() {
    const cloakView = this.get('cloakView'),
          idProperty = this.get('idProperty'),
          uncloakDefault = !!this.get('uncloakDefault');

    // Set the slack ratio differently to allow for more or less slack in preloading
    const slackRatio = parseFloat(this.get('slackRatio'));
    if (!slackRatio) { this.set('slackRatio', 1.0); }

    const CloakedView = this.container.lookupFactory('view:cloaked');
    this.set('itemViewClass', CloakedView.extend({
      classNames: [cloakView + '-cloak'],
      cloaks: cloakView,
      preservesContext: this.get('preservesContext') === 'true',
      cloaksController: this.get('itemController'),
      defaultHeight: this.get('defaultHeight'),

      init() {
        this._super();
        if (idProperty) {
          this.set('elementId', cloakView + '-cloak-' + this.get('content.' + idProperty));
        }
        if (uncloakDefault) {
          this.uncloak();
        } else {
          this.cloak();
        }
      }
    }));

    this._super();
    Ember.run.next(this, 'scrolled');
  },

  /**
    If the topmost visible view changed, we will notify the controller if it has an appropriate hook.

    @method _topVisibleChanged
    @observes topVisible
  **/
  _topVisibleChanged: function() {
    const controller = this.get('controller');
    if (controller.topVisibleChanged) { controller.topVisibleChanged(this.get('topVisible')); }
  }.observes('topVisible'),

  /**
    If the bottommost visible view changed, we will notify the controller if it has an appropriate hook.

    @method _bottomVisible
    @observes bottomVisible
  **/
  _bottomVisible: function() {
    const controller = this.get('controller');
    if (controller.bottomVisibleChanged) { controller.bottomVisibleChanged(this.get('bottomVisible')); }
  }.observes('bottomVisible'),

  /**
    Binary search for finding the topmost view on screen.

    @method findTopView
    @param {Array} childViews the childViews to search through
    @param {Number} windowTop The top of the viewport to search against
    @param {Number} min The minimum index to search through of the child views
    @param {Number} max The max index to search through of the child views
    @returns {Number} the index into childViews of the topmost view
  **/
  findTopView(childViews, viewportTop, min, max) {
    if (max < min) { return min; }

    const wrapperTop = this.get('wrapperTop')>>0;

    while(max>min){
      const mid = Math.floor((min + max) / 2),
          // in case of not full-window scrolling
          $view = childViews[mid].$(),

          // .position is quite expensive, shortcut here to get a slightly rougher
          // but much faster value
          parentOffsetTop = $view.offsetParent().offset().top,
          offsetTop = $view.offset().top,

          viewBottom = (offsetTop - parentOffsetTop) + wrapperTop + $view.height();

      console.log(viewBottom);

      if (viewBottom > viewportTop) {
        max = mid-1;
      } else {
        min = mid+1;
      }
    }

    return min;
  },

  /**
    Determine what views are onscreen and cloak/uncloak them as necessary.

    @method scrolled
  **/
  scrolled() {
    if (!this.get('scrollingEnabled')) { return; }

    const childViews = this.get('childViews');
    if ((!childViews) || (childViews.length === 0)) { return; }

    const self = this,
          toUncloak = [],
          onscreen = [],
          onscreenCloaks = [],
          $w = $(window),
          windowHeight = this.get('wrapperHeight') || ( window.innerHeight ? window.innerHeight : $w.height() ),
          slack = Math.round(windowHeight * this.get('slackRatio')),
          offsetFixedTopElement = this.get('offsetFixedTopElement'),
          offsetFixedBottomElement = this.get('offsetFixedBottomElement'),
          bodyHeight = this.get('wrapperHeight') ? this.$().height() : $('body').height();

    let windowTop = this.get('wrapperTop') || $w.scrollTop();

    const viewportTop = windowTop - slack,
          topView = this.findTopView(childViews, viewportTop, 0, childViews.length-1);

    let windowBottom = windowTop + windowHeight;
    let viewportBottom = windowBottom + slack;

    if (windowBottom > bodyHeight) { windowBottom = bodyHeight; }
    if (viewportBottom > bodyHeight) { viewportBottom = bodyHeight; }

    if (offsetFixedTopElement) {
      windowTop += (offsetFixedTopElement.outerHeight(true) || 0);
    }

    if (offsetFixedBottomElement) {
      windowBottom -= (offsetFixedBottomElement.outerHeight(true) || 0);
    }

    // Find the bottom view and what's onscreen
    let bottomView = topView;
    let bottomVisible = null;
    while (bottomView < childViews.length) {
      const view = childViews[bottomView];
      const $view = view.$();

      if (!$view) { break; }

      // in case of not full-window scrolling
      const scrollOffset = this.get('wrapperTop') || 0;
      const viewTop = $view.offset().top + scrollOffset;
      const viewBottom = viewTop + $view.height();

      if (viewTop > viewportBottom) { break; }
      toUncloak.push(view);

      if (viewBottom > windowTop && viewTop <= windowBottom) {
        const content = view.get('content');
        onscreen.push(content);

        if (!view.get('isPlaceholder')) {
          bottomVisible = content;
        }
        onscreenCloaks.push(view);
      }

      bottomView++;
    }
    if (bottomView >= childViews.length) { bottomView = childViews.length - 1; }

    // If our controller has a `sawObjects` method, pass the on screen objects to it.
    const controller = this.get('controller');
    if (onscreen.length) {
      this.setProperties({topVisible: onscreen[0], bottomVisible });
      if (controller && controller.sawObjects) {
        Em.run.schedule('afterRender', function() {
          controller.sawObjects(onscreen);
        });
      }
    } else {
      this.setProperties({topVisible: null, bottomVisible: null});
    }

    const toCloak = childViews.slice(0, topView).concat(childViews.slice(bottomView+1));

    this._uncloak = toUncloak;
    if(this._nextUncloak){
      Em.run.cancel(this._nextUncloak);
      this._nextUncloak = null;
    }

    Em.run.schedule('afterRender', this, function() {
      onscreenCloaks.forEach(function (v) {
        if(v && v.uncloak) {
          v.uncloak();
        }
      });
      toCloak.forEach(function (v) { v.cloak(); });
      if (self._nextUncloak) { Em.run.cancel(self._nextUncloak); }
      self._nextUncloak = Em.run.later(self, self.uncloakQueue,50);
    });

    for (let j=bottomView; j<childViews.length; j++) {
      const checkView = childViews[j];
      if (!checkView._containedView) {
        const loadingHTML = this.get('loadingHTML');
        if (!Em.isEmpty(loadingHTML) && !checkView.get('loading')) {
          checkView.$().html(loadingHTML);
        }
        return;
      }
    }
  },

  uncloakQueue() {
    const maxPerRun = 3, delay = 50, self = this;
    let processed = 0;

    if(this._uncloak){
      while(processed < maxPerRun && this._uncloak.length>0){
        const view = this._uncloak.shift();
        if(view && view.uncloak && !view._containedView){
          Em.run.schedule('afterRender', view, view.uncloak);
          processed++;
        }
      }
      if(this._uncloak.length === 0){
        this._uncloak = null;
      } else {
        Em.run.schedule('afterRender', self, function(){
          if(self._nextUncloak){
            Em.run.cancel(self._nextUncloak);
          }
          self._nextUncloak = Em.run.next(self, function(){
            if(self._nextUncloak){
              Em.run.cancel(self._nextUncloak);
            }
            self._nextUncloak = Em.run.later(self,self.uncloakQueue,delay);
          });
        });
      }
    }
  },

  scrollTriggered() {
    if ($('body').data('disable-cloaked-view')) {
      return;
    }
    Em.run.scheduleOnce('afterRender', this, 'scrolled');
  },

  _startEvents: function() {
    if (this.get('offsetFixed')) {
      Em.warn("Cloaked-collection's `offsetFixed` is deprecated. Use `offsetFixedTop` instead.");
    }

    const self = this,
        offsetFixedTop = this.get('offsetFixedTop') || this.get('offsetFixed'),
        offsetFixedBottom = this.get('offsetFixedBottom'),
        scrollDebounce = this.get('scrollDebounce'),
        onScrollMethod = function() {
          Ember.run.debounce(self, 'scrollTriggered', scrollDebounce);
        };

    if (offsetFixedTop) {
      this.set('offsetFixedTopElement', $(offsetFixedTop));
    }

    if (offsetFixedBottom) {
      this.set('offsetFixedBottomElement', $(offsetFixedBottom));
    }

    $(document).bind('touchmove.ember-cloak', onScrollMethod);
    $(window).bind('scroll.ember-cloak', onScrollMethod);
    this.addObserver('wrapperTop', self, onScrollMethod);
    this.addObserver('wrapperHeight', self, onScrollMethod);
    this.addObserver('content.@each', self, onScrollMethod);
    this.scrollTriggered();

    this.set('scrollingEnabled', true);
  }.on('didInsertElement'),

  cleanUp() {
    $(document).unbind('touchmove.ember-cloak');
    $(window).unbind('scroll.ember-cloak');
    this.set('scrollingEnabled', false);
  },

  _endEvents: function() {
    this.cleanUp();
  }.on('willDestroyElement')
});

Ember.Handlebars.helper('cloaked-collection', Ember.testing ? Ember.CollectionView : CloakedCollectionView);
export default CloakedCollectionView;
<commit_msg>remove leftover code<commit_after>/*eslint no-bitwise:0 */
const CloakedCollectionView = Ember.CollectionView.extend({
  cloakView: Ember.computed.alias('itemViewClass'),
  topVisible: null,
  bottomVisible: null,
  offsetFixedTopElement: null,
  offsetFixedBottomElement: null,
  loadingHTML: 'Loading...',
  scrollDebounce: 10,

  init() {
    const cloakView = this.get('cloakView'),
          idProperty = this.get('idProperty'),
          uncloakDefault = !!this.get('uncloakDefault');

    // Set the slack ratio differently to allow for more or less slack in preloading
    const slackRatio = parseFloat(this.get('slackRatio'));
    if (!slackRatio) { this.set('slackRatio', 1.0); }

    const CloakedView = this.container.lookupFactory('view:cloaked');
    this.set('itemViewClass', CloakedView.extend({
      classNames: [cloakView + '-cloak'],
      cloaks: cloakView,
      preservesContext: this.get('preservesContext') === 'true',
      cloaksController: this.get('itemController'),
      defaultHeight: this.get('defaultHeight'),

      init() {
        this._super();
        if (idProperty) {
          this.set('elementId', cloakView + '-cloak-' + this.get('content.' + idProperty));
        }
        if (uncloakDefault) {
          this.uncloak();
        } else {
          this.cloak();
        }
      }
    }));

    this._super();
    Ember.run.next(this, 'scrolled');
  },

  /**
    If the topmost visible view changed, we will notify the controller if it has an appropriate hook.

    @method _topVisibleChanged
    @observes topVisible
  **/
  _topVisibleChanged: function() {
    const controller = this.get('controller');
    if (controller.topVisibleChanged) { controller.topVisibleChanged(this.get('topVisible')); }
  }.observes('topVisible'),

  /**
    If the bottommost visible view changed, we will notify the controller if it has an appropriate hook.

    @method _bottomVisible
    @observes bottomVisible
  **/
  _bottomVisible: function() {
    const controller = this.get('controller');
    if (controller.bottomVisibleChanged) { controller.bottomVisibleChanged(this.get('bottomVisible')); }
  }.observes('bottomVisible'),

  /**
    Binary search for finding the topmost view on screen.

    @method findTopView
    @param {Array} childViews the childViews to search through
    @param {Number} windowTop The top of the viewport to search against
    @param {Number} min The minimum index to search through of the child views
    @param {Number} max The max index to search through of the child views
    @returns {Number} the index into childViews of the topmost view
  **/
  findTopView(childViews, viewportTop, min, max) {
    if (max < min) { return min; }

    const wrapperTop = this.get('wrapperTop')>>0;

    while(max>min){
      const mid = Math.floor((min + max) / 2),
          // in case of not full-window scrolling
          $view = childViews[mid].$(),

          // .position is quite expensive, shortcut here to get a slightly rougher
          // but much faster value
          parentOffsetTop = $view.offsetParent().offset().top,
          offsetTop = $view.offset().top,
          viewBottom = (offsetTop - parentOffsetTop) + wrapperTop + $view.height();

      if (viewBottom > viewportTop) {
        max = mid-1;
      } else {
        min = mid+1;
      }
    }

    return min;
  },

  /**
    Determine what views are onscreen and cloak/uncloak them as necessary.

    @method scrolled
  **/
  scrolled() {
    if (!this.get('scrollingEnabled')) { return; }

    const childViews = this.get('childViews');
    if ((!childViews) || (childViews.length === 0)) { return; }

    const self = this,
          toUncloak = [],
          onscreen = [],
          onscreenCloaks = [],
          $w = $(window),
          windowHeight = this.get('wrapperHeight') || ( window.innerHeight ? window.innerHeight : $w.height() ),
          slack = Math.round(windowHeight * this.get('slackRatio')),
          offsetFixedTopElement = this.get('offsetFixedTopElement'),
          offsetFixedBottomElement = this.get('offsetFixedBottomElement'),
          bodyHeight = this.get('wrapperHeight') ? this.$().height() : $('body').height();

    let windowTop = this.get('wrapperTop') || $w.scrollTop();

    const viewportTop = windowTop - slack,
          topView = this.findTopView(childViews, viewportTop, 0, childViews.length-1);

    let windowBottom = windowTop + windowHeight;
    let viewportBottom = windowBottom + slack;

    if (windowBottom > bodyHeight) { windowBottom = bodyHeight; }
    if (viewportBottom > bodyHeight) { viewportBottom = bodyHeight; }

    if (offsetFixedTopElement) {
      windowTop += (offsetFixedTopElement.outerHeight(true) || 0);
    }

    if (offsetFixedBottomElement) {
      windowBottom -= (offsetFixedBottomElement.outerHeight(true) || 0);
    }

    // Find the bottom view and what's onscreen
    let bottomView = topView;
    let bottomVisible = null;
    while (bottomView < childViews.length) {
      const view = childViews[bottomView];
      const $view = view.$();

      if (!$view) { break; }

      // in case of not full-window scrolling
      const scrollOffset = this.get('wrapperTop') || 0;
      const viewTop = $view.offset().top + scrollOffset;
      const viewBottom = viewTop + $view.height();

      if (viewTop > viewportBottom) { break; }
      toUncloak.push(view);

      if (viewBottom > windowTop && viewTop <= windowBottom) {
        const content = view.get('content');
        onscreen.push(content);

        if (!view.get('isPlaceholder')) {
          bottomVisible = content;
        }
        onscreenCloaks.push(view);
      }

      bottomView++;
    }
    if (bottomView >= childViews.length) { bottomView = childViews.length - 1; }

    // If our controller has a `sawObjects` method, pass the on screen objects to it.
    const controller = this.get('controller');
    if (onscreen.length) {
      this.setProperties({topVisible: onscreen[0], bottomVisible });
      if (controller && controller.sawObjects) {
        Em.run.schedule('afterRender', function() {
          controller.sawObjects(onscreen);
        });
      }
    } else {
      this.setProperties({topVisible: null, bottomVisible: null});
    }

    const toCloak = childViews.slice(0, topView).concat(childViews.slice(bottomView+1));

    this._uncloak = toUncloak;
    if(this._nextUncloak){
      Em.run.cancel(this._nextUncloak);
      this._nextUncloak = null;
    }

    Em.run.schedule('afterRender', this, function() {
      onscreenCloaks.forEach(function (v) {
        if(v && v.uncloak) {
          v.uncloak();
        }
      });
      toCloak.forEach(function (v) { v.cloak(); });
      if (self._nextUncloak) { Em.run.cancel(self._nextUncloak); }
      self._nextUncloak = Em.run.later(self, self.uncloakQueue,50);
    });

    for (let j=bottomView; j<childViews.length; j++) {
      const checkView = childViews[j];
      if (!checkView._containedView) {
        const loadingHTML = this.get('loadingHTML');
        if (!Em.isEmpty(loadingHTML) && !checkView.get('loading')) {
          checkView.$().html(loadingHTML);
        }
        return;
      }
    }
  },

  uncloakQueue() {
    const maxPerRun = 3, delay = 50, self = this;
    let processed = 0;

    if(this._uncloak){
      while(processed < maxPerRun && this._uncloak.length>0){
        const view = this._uncloak.shift();
        if(view && view.uncloak && !view._containedView){
          Em.run.schedule('afterRender', view, view.uncloak);
          processed++;
        }
      }
      if(this._uncloak.length === 0){
        this._uncloak = null;
      } else {
        Em.run.schedule('afterRender', self, function(){
          if(self._nextUncloak){
            Em.run.cancel(self._nextUncloak);
          }
          self._nextUncloak = Em.run.next(self, function(){
            if(self._nextUncloak){
              Em.run.cancel(self._nextUncloak);
            }
            self._nextUncloak = Em.run.later(self,self.uncloakQueue,delay);
          });
        });
      }
    }
  },

  scrollTriggered() {
    if ($('body').data('disable-cloaked-view')) {
      return;
    }
    Em.run.scheduleOnce('afterRender', this, 'scrolled');
  },

  _startEvents: function() {
    if (this.get('offsetFixed')) {
      Em.warn("Cloaked-collection's `offsetFixed` is deprecated. Use `offsetFixedTop` instead.");
    }

    const self = this,
        offsetFixedTop = this.get('offsetFixedTop') || this.get('offsetFixed'),
        offsetFixedBottom = this.get('offsetFixedBottom'),
        scrollDebounce = this.get('scrollDebounce'),
        onScrollMethod = function() {
          Ember.run.debounce(self, 'scrollTriggered', scrollDebounce);
        };

    if (offsetFixedTop) {
      this.set('offsetFixedTopElement', $(offsetFixedTop));
    }

    if (offsetFixedBottom) {
      this.set('offsetFixedBottomElement', $(offsetFixedBottom));
    }

    $(document).bind('touchmove.ember-cloak', onScrollMethod);
    $(window).bind('scroll.ember-cloak', onScrollMethod);
    this.addObserver('wrapperTop', self, onScrollMethod);
    this.addObserver('wrapperHeight', self, onScrollMethod);
    this.addObserver('content.@each', self, onScrollMethod);
    this.scrollTriggered();

    this.set('scrollingEnabled', true);
  }.on('didInsertElement'),

  cleanUp() {
    $(document).unbind('touchmove.ember-cloak');
    $(window).unbind('scroll.ember-cloak');
    this.set('scrollingEnabled', false);
  },

  _endEvents: function() {
    this.cleanUp();
  }.on('willDestroyElement')
});

Ember.Handlebars.helper('cloaked-collection', Ember.testing ? Ember.CollectionView : CloakedCollectionView);
export default CloakedCollectionView;
<|endoftext|>


<commit_before>'use strict'
module.exports = {
	router:{
		movie:'/test/movie/router.js',
		list:'/test/list/router.js'
	},
	controller:{
		test:'test/controller/index.js'
	}
}<commit_msg>change file path for test<commit_after>'use strict'
module.exports = {
	router:{
		movie:'/test/movie/router.js',
		list:'/test/list/router.js'
	},
	controller:{
		movie:'/test/movie/controller/index.js',
		list:'/test/list/controller/index.js'
	}
}<|endoftext|>