<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

const chalk = require('chalk');
const child_process = require('child_process');
const fs = require('fs');
const path = require('path');
const parseCommandLine = require('../util/parseCommandLine');
const isPackagerRunning = require('../util/isPackagerRunning');
const Promise = require('promise');

/**
 * Starts the app on a connected Android emulator or device.
 */
function runAndroid(argv, config) {
  return new Promise((resolve, reject) => {
    _runAndroid(argv, config, resolve, reject);
  });
}

function _runAndroid(argv, config, resolve, reject) {
  const args = parseCommandLine([{
    command: 'install-debug',
    type: 'string',
    required: false,
  }, {
    command: 'root',
    type: 'string',
    description: 'Override the root directory for the android build (which contains the android directory)',
  }, {
    command: 'flavor',
    type: 'string',
    required: false,
  }], argv);

  args.root = args.root || '';

  if (!checkAndroid(args)) {
    console.log(chalk.red('Android project not found. Maybe run react-native android first?'));
    return;
  }

  resolve(isPackagerRunning().then(result => {
    if (result === 'running') {
      console.log(chalk.bold('JS server already running.'));
    } else if (result === 'unrecognized') {
      console.warn(chalk.yellow('JS server not recognized, continuing with build...'));
    } else {
      // result == 'not_running'
      console.log(chalk.bold('Starting JS server...'));
      startServerInNewWindow();
    }
    buildAndRun(args, reject);
  }));
}

// Verifies this is an Android project
function checkAndroid(args) {
  return fs.existsSync(path.join(args.root, 'android/gradlew'));
}

// Builds the app and runs it on a connected emulator / device.
function buildAndRun(args, reject) {
  process.chdir(path.join(args.root, 'android'));
  try {
    const cmd = process.platform.startsWith('win')
      ? 'gradlew.bat'
      : './gradlew';

    const gradleArgs = [];
    if (args['flavor']) {
        gradleArgs.push('install' +
          args['flavor'][0].toUpperCase() + args['flavor'].slice(1)
        );
    } else {
        gradleArgs.push('installDebug');
    }

    if (args['install-debug']) {
      gradleArgs.push(args['install-debug']);
    }

    console.log(chalk.bold(
      'Building and installing the app on the device (cd android && ' + cmd +
      ' ' + gradleArgs.join(' ') + ')...'
    ));

    child_process.execFileSync(cmd, gradleArgs, {
      stdio: [process.stdin, process.stdout, process.stderr],
    });
  } catch (e) {
    console.log(chalk.red(
      'Could not install the app on the device, read the error above for details.\n' +
      'Make sure you have an Android emulator running or a device connected and have\n' +
      'set up your Android development environment:\n' +
      'https://facebook.github.io/react-native/docs/android-setup.html'
    ));
    // stderr is automatically piped from the gradle process, so the user
    // should see the error already, there is no need to do
    // `console.log(e.stderr)`
    reject();
    return;
  }

  try {
    const packageName = fs.readFileSync(
      'app/src/main/AndroidManifest.xml',
      'utf8'
    ).match(/package="(.+?)"/)[1];

    const adbPath = process.env.ANDROID_HOME
      ? process.env.ANDROID_HOME + '/platform-tools/adb'
      : 'adb';

    const adbArgs = [
      'shell', 'am', 'start', '-n', packageName + '/.MainActivity'
    ];

    console.log(chalk.bold(
      'Starting the app (' + adbPath + ' ' + adbArgs.join(' ') + ')...'
    ));

    child_process.spawnSync(adbPath, adbArgs, {stdio: 'inherit'});
  } catch (e) {
    console.log(chalk.red(
      'adb invocation failed. Do you have adb in your PATH?'
    ));
    // stderr is automatically piped from the gradle process, so the user
    // should see the error already, there is no need to do
    // `console.log(e.stderr)`
    reject();
    return;
  }
}

function startServerInNewWindow() {
  const launchPackagerScript = path.resolve(
    __dirname, '..', '..', 'packager', 'launchPackager.command'
  );

  if (process.platform === 'darwin') {
    child_process.spawnSync('open', [launchPackagerScript]);
  } else if (process.platform === 'linux') {
    child_process.spawn(
      'xterm',
      ['-e', 'sh', launchPackagerScript],
      {detached: true}
    );
  } else if (/^win/.test(process.platform)) {
    console.log(chalk.yellow('Starting the packager in a new window ' +
      'is not supported on Windows yet.\nPlease start it manually using ' +
      '\'react-native start\'.'));
    console.log('We believe the best Windows ' +
      'support will come from a community of people\nusing React Native on ' +
      'Windows on a daily basis.\n' +
      'Would you be up for sending a pull request?');
  } else {
    console.log(chalk.red('Cannot start the packager. Unknown platform ' +
      process.platform));
  }
}

module.exports = runAndroid;
<commit_msg>run-android Chose your Term for OSX, and Linux<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

const chalk = require('chalk');
const child_process = require('child_process');
const fs = require('fs');
const path = require('path');
const parseCommandLine = require('../util/parseCommandLine');
const isPackagerRunning = require('../util/isPackagerRunning');
const Promise = require('promise');

/**
 * Starts the app on a connected Android emulator or device.
 */
function runAndroid(argv, config) {
  return new Promise((resolve, reject) => {
    _runAndroid(argv, config, resolve, reject);
  });
}

function _runAndroid(argv, config, resolve, reject) {
  const args = parseCommandLine([{
    command: 'install-debug',
    type: 'string',
    required: false,
  }, {
    command: 'root',
    type: 'string',
    description: 'Override the root directory for the android build (which contains the android directory)',
  }, {
    command: 'flavor',
    type: 'string',
    required: false,
  }], argv);

  args.root = args.root || '';

  if (!checkAndroid(args)) {
    console.log(chalk.red('Android project not found. Maybe run react-native android first?'));
    return;
  }

  resolve(isPackagerRunning().then(result => {
    if (result === 'running') {
      console.log(chalk.bold('JS server already running.'));
    } else if (result === 'unrecognized') {
      console.warn(chalk.yellow('JS server not recognized, continuing with build...'));
    } else {
      // result == 'not_running'
      console.log(chalk.bold('Starting JS server...'));
      startServerInNewWindow();
    }
    buildAndRun(args, reject);
  }));
}

// Verifies this is an Android project
function checkAndroid(args) {
  return fs.existsSync(path.join(args.root, 'android/gradlew'));
}

// Builds the app and runs it on a connected emulator / device.
function buildAndRun(args, reject) {
  process.chdir(path.join(args.root, 'android'));
  try {
    const cmd = process.platform.startsWith('win')
      ? 'gradlew.bat'
      : './gradlew';

    const gradleArgs = [];
    if (args['flavor']) {
        gradleArgs.push('install' +
          args['flavor'][0].toUpperCase() + args['flavor'].slice(1)
        );
    } else {
        gradleArgs.push('installDebug');
    }

    if (args['install-debug']) {
      gradleArgs.push(args['install-debug']);
    }

    console.log(chalk.bold(
      'Building and installing the app on the device (cd android && ' + cmd +
      ' ' + gradleArgs.join(' ') + ')...'
    ));

    child_process.execFileSync(cmd, gradleArgs, {
      stdio: [process.stdin, process.stdout, process.stderr],
    });
  } catch (e) {
    console.log(chalk.red(
      'Could not install the app on the device, read the error above for details.\n' +
      'Make sure you have an Android emulator running or a device connected and have\n' +
      'set up your Android development environment:\n' +
      'https://facebook.github.io/react-native/docs/android-setup.html'
    ));
    // stderr is automatically piped from the gradle process, so the user
    // should see the error already, there is no need to do
    // `console.log(e.stderr)`
    reject();
    return;
  }

  try {
    const packageName = fs.readFileSync(
      'app/src/main/AndroidManifest.xml',
      'utf8'
    ).match(/package="(.+?)"/)[1];

    const adbPath = process.env.ANDROID_HOME
      ? process.env.ANDROID_HOME + '/platform-tools/adb'
      : 'adb';

    const adbArgs = [
      'shell', 'am', 'start', '-n', packageName + '/.MainActivity'
    ];

    console.log(chalk.bold(
      'Starting the app (' + adbPath + ' ' + adbArgs.join(' ') + ')...'
    ));

    child_process.spawnSync(adbPath, adbArgs, {stdio: 'inherit'});
  } catch (e) {
    console.log(chalk.red(
      'adb invocation failed. Do you have adb in your PATH?'
    ));
    // stderr is automatically piped from the gradle process, so the user
    // should see the error already, there is no need to do
    // `console.log(e.stderr)`
    reject();
    return;
  }
}

function startServerInNewWindow() {
  var yargV = require('yargs').argv;

  const launchPackagerScript = path.resolve(
    __dirname, '..', '..', 'packager', 'launchPackager.command'
  );

  if (process.platform === 'darwin') {
    if (yargV.open) {
      return child_process.spawnSync('open', ['-a', yargV.open, launchPackagerScript]);
    }
    return child_process.spawnSync('open', [launchPackagerScript]);

  } else if (process.platform === 'linux') {
    if (yargV.open){
      return child_process.spawn(yargV.open,['-e', 'sh', launchPackagerScript], {detached: true});
    }
    return child_process.spawn('xterm',['-e', 'sh', launchPackagerScript],{detached: true});

  } else if (/^win/.test(process.platform)) {
    console.log(chalk.yellow('Starting the packager in a new window ' +
      'is not supported on Windows yet.\nPlease start it manually using ' +
      '\'react-native start\'.'));
    console.log('We believe the best Windows ' +
      'support will come from a community of people\nusing React Native on ' +
      'Windows on a daily basis.\n' +
      'Would you be up for sending a pull request?');
  } else {
    console.log(chalk.red('Cannot start the packager. Unknown platform ' +
      process.platform));
  }
}

module.exports = runAndroid;
<|endoftext|>


<commit_before>import PlaceholderSVG from '../../../static/asset/img-loading-placeholder.svg'
import PropTypes from 'prop-types'
import React from 'react'
import get from 'lodash/get'
import constPropTypes from '../../constants/prop-types'
import styled from 'styled-components'
import { articleLayout as layout } from '../../themes/layout'
import { colors, lineHeight, typography } from '../../themes/common-variables'
import { getSrcSet } from '../../utils/img'
import { replaceStorageUrlPrefix } from '../../utils/url'

const _ = {
  get
}

const Caption = styled.figcaption`
  display: ${props => props.toShow ? 'block': 'none' };
  text-align: justify;
  color: ${colors.gray.gray50};
  font-size: ${typography.font.size.medium};
  line-height: ${lineHeight.large};
  margin: 16px 24px 0 24px;
`

const ImgContainer = styled.div`
  position: relative;
  padding-bottom: ${(props) => {
    const height = props.height
    const width = props.width
    return ((height / width) * 100 ) + '%'
  }}
`

const ImgPlaceholder = styled.div`
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: ${props => props.toShow ? 'block' : 'none'};
`

const ImgBox = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: ${props => props.toShow ? '1' : '0' };
  transition:  opacity .5s;

  > img {
    width: 100%;
  }
`

class Image extends React.PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      isLoaded: false,
      toShowPlaceholder: true
    }
    this.onLoad = this._onLoad.bind(this)
    this._imgNode = null
    this._isMounted = false
  }

  componentDidMount() {
    this._isMounted = true

    // Check if img is already loaded, and cached on the browser.
    // If cached, React.img won't trigger onLoad event.
    // Hence, we need to trigger re-rendering.
    if (this._imgNode) {
      this.onLoad()
    }
  }

  componentWillUnmount() {
    this._isMounted = false
    this._imgNode = null
  }

  _onLoad() {
    this.setState({
      isLoaded: true
    })

    setTimeout(() => {
      if (this._isMounted) {
        this.setState({
          toShowPlaceholder: false
        })
      }
    }, 1000)
  }

  _getSizes(imgSizes) {
    if (!imgSizes) {
      return null
    }

    const hdSize = _.get(imgSizes, 'hd')
    const desktopSize = _.get(imgSizes, 'desktop')
    const tabletSize = _.get(imgSizes, 'tablet')
    const mobileSize = _.get(imgSizes, 'mobile')

    return `(min-width: ${layout.hd.width.large}px) ${hdSize}, ` +
      `(min-width: ${layout.desktop.width.large}px) ${desktopSize}, ` +
      `(min-width: ${layout.tablet.width.large}px) ${tabletSize}, ` +
      `(min-width: 0px)  ${mobileSize}`
  }

  _renderImgPlaceHolder(toShow) {
    return (
      <ImgPlaceholder
        toShow={toShow}
      >
        <PlaceholderSVG />
      </ImgPlaceholder>
    )
  }

  render() {
    const { isLoaded, toShowPlaceholder } = this.state
    const { alt, imgSet, imgSizes } = this.props
    const srcSet = getSrcSet(imgSet)
    const sizes = this._getSizes(imgSizes)

    return (
      <figure
        itemProp="image"
        itemScope
        itemType="http://schema.org/ImageObject"
      >
        <ImgContainer
          height={_.get(imgSet, 'tiny.height')}
          width={_.get(imgSet, 'tiny.width')}
        >
          {this._renderImgPlaceHolder(toShowPlaceholder)}
          <ImgBox
            toShow={isLoaded}
          >
            <img
              alt={alt}
              sizes={sizes}
              onLoad={this.onLoad}
              src={replaceStorageUrlPrefix(_.get(imgSet, 'mobile.url'))}
              srcSet={srcSet}
              ref={node => { this._imgNode = node }}
              itemProp="contentUrl"
            />
          </ImgBox>
        </ImgContainer>
        <Caption
          toShow={this.props.toShowCaption}
          itemProp="description"
        >
          {alt}
        </Caption>
      </figure>
    )
  }
}

Image.propTypes = {
  alt: PropTypes.string,
  imgSet: constPropTypes.img,
  imgSizes: constPropTypes.imgSizes,
  toShowCaption: PropTypes.bool
}

Image.defaultProps = {
  alt: '',
  imgSet: {},
  imgSizes: {},
  toShowCaption: true
}

export default Image
<commit_msg>fix(ui print): workaround to fix image overlaying text while printing<commit_after>import PlaceholderSVG from '../../../static/asset/img-loading-placeholder.svg'
import PropTypes from 'prop-types'
import React from 'react'
import get from 'lodash/get'
import constPropTypes from '../../constants/prop-types'
import styled from 'styled-components'
import { articleLayout as layout } from '../../themes/layout'
import { colors, lineHeight, typography } from '../../themes/common-variables'
import { getSrcSet } from '../../utils/img'
import { replaceStorageUrlPrefix } from '../../utils/url'

const _ = {
  get
}

const Caption = styled.figcaption`
  display: ${props => props.toShow ? 'block': 'none' };
  text-align: justify;
  color: ${colors.gray.gray50};
  font-size: ${typography.font.size.medium};
  line-height: ${lineHeight.large};
  margin: 16px 24px 0 24px;
`

const ImgContainer = styled.div`
  position: relative;
  padding-bottom: ${(props) => {
    const height = props.height
    const width = props.width
    return ((height / width) * 100 ) + '%'
  }};

  @media print {
    margin-bottom: ${(props) => {
      const height = props.height
      const width = props.width
      return ((height / width) * 100 ) + '%'
    }}
  };
`

const ImgPlaceholder = styled.div`
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: ${props => props.toShow ? 'block' : 'none'};
`

const ImgBox = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: ${props => props.toShow ? '1' : '0' };
  transition:  opacity .5s;

  > img {
    width: 100%;
  }
`

class Image extends React.PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      isLoaded: false,
      toShowPlaceholder: true
    }
    this.onLoad = this._onLoad.bind(this)
    this._imgNode = null
    this._isMounted = false
  }

  componentDidMount() {
    this._isMounted = true

    // Check if img is already loaded, and cached on the browser.
    // If cached, React.img won't trigger onLoad event.
    // Hence, we need to trigger re-rendering.
    if (this._imgNode) {
      this.onLoad()
    }
  }

  componentWillUnmount() {
    this._isMounted = false
    this._imgNode = null
  }

  _onLoad() {
    this.setState({
      isLoaded: true
    })

    setTimeout(() => {
      if (this._isMounted) {
        this.setState({
          toShowPlaceholder: false
        })
      }
    }, 1000)
  }

  _getSizes(imgSizes) {
    if (!imgSizes) {
      return null
    }

    const hdSize = _.get(imgSizes, 'hd')
    const desktopSize = _.get(imgSizes, 'desktop')
    const tabletSize = _.get(imgSizes, 'tablet')
    const mobileSize = _.get(imgSizes, 'mobile')

    return `(min-width: ${layout.hd.width.large}px) ${hdSize}, ` +
      `(min-width: ${layout.desktop.width.large}px) ${desktopSize}, ` +
      `(min-width: ${layout.tablet.width.large}px) ${tabletSize}, ` +
      `(min-width: 0px)  ${mobileSize}`
  }

  _renderImgPlaceHolder(toShow) {
    return (
      <ImgPlaceholder
        toShow={toShow}
      >
        <PlaceholderSVG />
      </ImgPlaceholder>
    )
  }

  render() {
    const { isLoaded, toShowPlaceholder } = this.state
    const { alt, imgSet, imgSizes } = this.props
    const srcSet = getSrcSet(imgSet)
    const sizes = this._getSizes(imgSizes)

    return (
      <figure
        itemProp="image"
        itemScope
        itemType="http://schema.org/ImageObject"
      >
        <ImgContainer
          height={_.get(imgSet, 'tiny.height')}
          width={_.get(imgSet, 'tiny.width')}
        >
          {this._renderImgPlaceHolder(toShowPlaceholder)}
          <ImgBox
            toShow={isLoaded}
          >
            <img
              alt={alt}
              sizes={sizes}
              onLoad={this.onLoad}
              src={replaceStorageUrlPrefix(_.get(imgSet, 'mobile.url'))}
              srcSet={srcSet}
              ref={node => { this._imgNode = node }}
              itemProp="contentUrl"
            />
          </ImgBox>
        </ImgContainer>
        <Caption
          toShow={this.props.toShowCaption}
          itemProp="description"
        >
          {alt}
        </Caption>
      </figure>
    )
  }
}

Image.propTypes = {
  alt: PropTypes.string,
  imgSet: constPropTypes.img,
  imgSizes: constPropTypes.imgSizes,
  toShowCaption: PropTypes.bool
}

Image.defaultProps = {
  alt: '',
  imgSet: {},
  imgSizes: {},
  toShowCaption: true
}

export default Image
<|endoftext|>


<commit_before><commit_msg>Add code to video detail component<commit_after>import React from 'react';
// import VideoListItem from './video_list_item';

const VideoDetail = ({video}) => {
  const videoId = video.id.videoId;
  const url = `https://www.youtube.com/embed/${videoId}`;
  return (

{video.snippet.title}

{video.snippet.description}

  );
};

export default VideoDetail;
<|endoftext|>


<commit_before><commit_msg>Build out VideoDetail<commit_after>import React from 'react'

const VideoDetail = ({video}) => {

    const videoId = video.id.videoId;
    const url = `https://www.youtube.com/embed/${videoId}`;
    console.log(url)
    return (

{video.snippet.title}

{video.snippet.description}

    );
};

export default VideoDetail;<|endoftext|>


<commit_before>import Rx from 'rx'
let fromEvent = Rx.Observable.fromEvent
let merge = Rx.Observable.merge
let combineLatest = Rx.Observable.combineLatest

import {pointerInteractions,interactionsFromCEvents,preventScroll} from '../../interactions/pointers'
import {windowResizes,elementResizes} from '../../interactions/sizing'

import {preventDefault,isTextNotEmpty,formatData,exists,combineLatestObj} from '../../utils/obsUtils'
import {selectionAt,meshFrom,isTransformTool,targetObject} from './utils2'

import {toArray,itemsEqual} from '../../utils/utils'

import {getCoordsFromPosSizeRect} from './deps/Selector'

//get original data +  picking infos
function addPickingInfos( inStream$, containerResizes$, camera, scene ){
  return inStream$
    .withLatestFrom(
      containerResizes$,
      function(event, clientRect){
        if(event){
          let input = document.querySelector('.container')//canvas
          let clientRect = input.getBoundingClientRect()

          let data = {
            pos:{x:event.clientX,y:event.clientY}
            ,rect:clientRect,width:clientRect.width,height:clientRect.height
            ,event
          }
          let mouseCoords = getCoordsFromPosSizeRect(data)
          return selectionAt(event, mouseCoords, camera, scene.children)
        }
        else{
          return {}
        }
      }
    )
}

//extract the object & position from a pickingInfo data
function objectAndPosition(pickingInfo){
  return {object:pickingInfo.object,point:pickingInfo.point}
}

export default function intent(drivers, data){
  let {DOM} = drivers
  let {camera, scene, transformControls} = data

  let windowResizes$ = windowResizes(1) //get from intents/interactions ?
  let elementResizes$ = elementResizes(".container",1)

  let {shortSingleTaps$,
    shortDoubleTaps$,
    longTaps$,
    zooms$,
    dragMoves$} = pointerInteractions(interactionsFromCEvents(DOM))

  //FIXME : needs to be done in a more coherent, reusable way
  //shut down "wobble effect if ANY user interaction takes place"
  const userAction$ = merge(
    shortSingleTaps$,
    shortDoubleTaps$,
    longTaps$,
    zooms$,
    dragMoves$
  )//.subscribe(e=>wobble.stop())

  DOM.select('canvas').events('contextmenu').subscribe( e => preventDefault(e) )

  let containerResizes$ = windowResizes$
    .map(function(){
      let input = document.querySelector('.container')//canvas
      if(input) return input.getBoundingClientRect()
    })
    .filter(exists)
    .startWith({width:window.innerWidth, height:window.innerHeight, aspect:window.innerWidth/window.innerHeight, bRect:undefined})

  const shortSingleTapsWPicking$ = addPickingInfos(shortSingleTaps$, windowResizes$, camera, scene)
    .shareReplay(1)
  const shortDoubleTapsWPicking$ = addPickingInfos(shortDoubleTaps$, windowResizes$, camera, scene)
    .shareReplay(1)
  let longTapsWPicking$          = addPickingInfos(longTaps$, windowResizes$, camera, scene)
    .shareReplay(1)

  //contextmenu observable should return undifined when any other basic interaction
  //took place (to cancel displaying context menu , etc)
  /*longTapsWPicking$ = longTapsWPicking$
    .merge(
      shortSingleTapsWPicking$.map(undefined),
      shortDoubleTapsWPicking$.map(undefined),
      dragMoves$.map(undefined)
    )*/

  //zoom action intent
  const zoomInOnPoint$ = shortDoubleTapsWPicking$
    .map(e => e.detail.pickingInfos.shift())
    .filter(exists)
    .map( objectAndPosition )

  const zoomToFit$ = Rx.Observable.just(true) //DOM.select('#zoomToFit').events("click")

  //Stream of selected meshes
  const selectMeshes$ = merge(
      shortSingleTapsWPicking$.map( meshFrom )
      ,longTapsWPicking$.map( meshFrom )
    )
    .map(toArray)//important !!
    //.distinctUntilChanged()
    .shareReplay(1)

  //what are the active controls : camera, object tranforms,
  let tControlsActive$ = merge(
    fromEvent(transformControls,"mouseDown").map(true),
    fromEvent(transformControls,"mouseUp").map(false)
  ).startWith(false)

  //let activeControls$
  //if transformControls are active, filter out dragMove gestures
  let fDragMoves$ = dragMoves$
    .combineLatest(tControlsActive$,function(dragMoves,tCActive){
      if(tCActive) return undefined
      return dragMoves
    })
    .filter(exists)
  //actual stream used for camera controls
  let filteredInteractions$ = {dragMoves$:fDragMoves$, zooms$}

  //stream of transformations done on the current selection
  const selectionsTransforms$ = fromEvent(transformControls, 'objectChange')
    .map(targetObject)
    .map(function(t){
      return {pos:t.position.toArray(),
        rot:t.rotation.toArray(),
        sca:t.scale.toArray()
      }
    })

  return {
    userAction$
    , zoomInOnPoint$
    , zoomToFit$
    , selectMeshes$

    ,shortSingleTapsWPicking$
    ,shortDoubleTapsWPicking$
    ,longTapsWPicking$

    ,filteredInteractions$

    ,selectionsTransforms$

  }
}<commit_msg>chore(): coerced position, rotation, scale to only be 3 components arrays when emiting transforms from webgl view<commit_after>import Rx from 'rx'
let fromEvent = Rx.Observable.fromEvent
let merge = Rx.Observable.merge
let combineLatest = Rx.Observable.combineLatest

import {pointerInteractions,interactionsFromCEvents,preventScroll} from '../../interactions/pointers'
import {windowResizes,elementResizes} from '../../interactions/sizing'

import {preventDefault,isTextNotEmpty,formatData,exists,combineLatestObj} from '../../utils/obsUtils'
import {selectionAt,meshFrom,isTransformTool,targetObject} from './utils2'

import {toArray,itemsEqual} from '../../utils/utils'

import {getCoordsFromPosSizeRect} from './deps/Selector'

//get original data +  picking infos
function addPickingInfos( inStream$, containerResizes$, camera, scene ){
  return inStream$
    .withLatestFrom(
      containerResizes$,
      function(event, clientRect){
        if(event){
          let input = document.querySelector('.container')//canvas
          let clientRect = input.getBoundingClientRect()

          let data = {
            pos:{x:event.clientX,y:event.clientY}
            ,rect:clientRect,width:clientRect.width,height:clientRect.height
            ,event
          }
          let mouseCoords = getCoordsFromPosSizeRect(data)
          return selectionAt(event, mouseCoords, camera, scene.children)
        }
        else{
          return {}
        }
      }
    )
}

//extract the object & position from a pickingInfo data
function objectAndPosition(pickingInfo){
  return {object:pickingInfo.object,point:pickingInfo.point}
}

export default function intent(drivers, data){
  let {DOM} = drivers
  let {camera, scene, transformControls} = data

  let windowResizes$ = windowResizes(1) //get from intents/interactions ?
  let elementResizes$ = elementResizes(".container",1)

  let {shortSingleTaps$,
    shortDoubleTaps$,
    longTaps$,
    zooms$,
    dragMoves$} = pointerInteractions(interactionsFromCEvents(DOM))

  //FIXME : needs to be done in a more coherent, reusable way
  //shut down "wobble effect if ANY user interaction takes place"
  const userAction$ = merge(
    shortSingleTaps$,
    shortDoubleTaps$,
    longTaps$,
    zooms$,
    dragMoves$
  )//.subscribe(e=>wobble.stop())

  DOM.select('canvas').events('contextmenu').subscribe( e => preventDefault(e) )

  let containerResizes$ = windowResizes$
    .map(function(){
      let input = document.querySelector('.container')//canvas
      if(input) return input.getBoundingClientRect()
    })
    .filter(exists)
    .startWith({width:window.innerWidth, height:window.innerHeight, aspect:window.innerWidth/window.innerHeight, bRect:undefined})

  const shortSingleTapsWPicking$ = addPickingInfos(shortSingleTaps$, windowResizes$, camera, scene)
    .shareReplay(1)
  const shortDoubleTapsWPicking$ = addPickingInfos(shortDoubleTaps$, windowResizes$, camera, scene)
    .shareReplay(1)
  let longTapsWPicking$          = addPickingInfos(longTaps$, windowResizes$, camera, scene)
    .shareReplay(1)

  //contextmenu observable should return undifined when any other basic interaction
  //took place (to cancel displaying context menu , etc)
  /*longTapsWPicking$ = longTapsWPicking$
    .merge(
      shortSingleTapsWPicking$.map(undefined),
      shortDoubleTapsWPicking$.map(undefined),
      dragMoves$.map(undefined)
    )*/

  //zoom action intent
  const zoomInOnPoint$ = shortDoubleTapsWPicking$
    .map(e => e.detail.pickingInfos.shift())
    .filter(exists)
    .map( objectAndPosition )

  const zoomToFit$ = Rx.Observable.just(true) //DOM.select('#zoomToFit').events("click")

  //Stream of selected meshes
  const selectMeshes$ = merge(
      shortSingleTapsWPicking$.map( meshFrom )
      ,longTapsWPicking$.map( meshFrom )
    )
    .map(toArray)//important !!
    //.distinctUntilChanged()
    .shareReplay(1)

  //what are the active controls : camera, object tranforms,
  let tControlsActive$ = merge(
    fromEvent(transformControls,"mouseDown").map(true),
    fromEvent(transformControls,"mouseUp").map(false)
  ).startWith(false)

  //let activeControls$
  //if transformControls are active, filter out dragMove gestures
  let fDragMoves$ = dragMoves$
    .combineLatest(tControlsActive$,function(dragMoves,tCActive){
      if(tCActive) return undefined
      return dragMoves
    })
    .filter(exists)
  //actual stream used for camera controls
  let filteredInteractions$ = {dragMoves$:fDragMoves$, zooms$}

  //stream of transformations done on the current selection
  const selectionsTransforms$ = fromEvent(transformControls, 'objectChange')
    .map(targetObject)
    .map(function(t){
      return {
        pos:t.position.toArray().slice(0,3),
        rot:t.rotation.toArray().slice(0,3),
        sca:t.scale.toArray().slice(0,3)
      }
    })

  return {
    userAction$
    , zoomInOnPoint$
    , zoomToFit$
    , selectMeshes$

    ,shortSingleTapsWPicking$
    ,shortDoubleTapsWPicking$
    ,longTapsWPicking$

    ,filteredInteractions$

    ,selectionsTransforms$

  }
}
<|endoftext|>


<commit_before>//Define coordinate system using PROJ4 standards
var osgb = new L.Proj.CRS('EPSG:27700',
  '+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000' +
  '+ellps=airy +datum=OSGB36 +units=m +no_defs',
  {
    resolutions: [2500, 1000, 500, 200, 100, 50, 25, 10, 5, 2.5, 1],
    bounds: L.bounds([1300000,0],[700000,0])
  }
);

//Leaflet map with OS options
var map = new L.Map('map', {
  crs: osgb,
  continuousWorld: true,
  worldCopyJump: false,
  minZoom: 1,
  maxZoom: 10,

  // controls
  dragging: false,
  touchZoom: false,
  doubleClickZoom: false,
  scrollWheelZoom: false,
  boxZoom: false,
  keyboard: false,
  tap: false,
  zoomControl: false,
  attributionControl: false
});

//New OSOpenSpace layer with API Key
var openspaceLayer = L.tileLayer.osopenspace("FFB702322FE0714DE0430B6CA40A06C6", {debug: true});
map.addLayer(openspaceLayer);

//Define name of CRS in GeoJSON using PROJ4
proj4.defs("urn:ogc:def:crs:EPSG:27700","+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +datum=OSGB36 +units=m +no_defs");

//Add the GeoJSON to the map
var geoJson = L.Proj.geoJson(extentData, {
  color: 'red',
  fillColor: '#f03',
  fillOpacity: 0.5
})
geoJson.addTo(map);

//Add a scale control to the map
L.control.scale().addTo(map);

//Center map view on geojson polygon
var bounds = geoJson.getBounds();
var center = bounds.getCenter();
map.setView([center.lat, center.lng], 9)
map.fitBounds(bounds, {maxZoom: 9, animate: false});

<commit_msg>change api key<commit_after>//Define coordinate system using PROJ4 standards
var osgb = new L.Proj.CRS('EPSG:27700',
  '+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000' +
  '+ellps=airy +datum=OSGB36 +units=m +no_defs',
  {
    resolutions: [2500, 1000, 500, 200, 100, 50, 25, 10, 5, 2.5, 1],
    bounds: L.bounds([1300000,0],[700000,0])
  }
);

//Leaflet map with OS options
var map = new L.Map('map', {
  crs: osgb,
  continuousWorld: true,
  worldCopyJump: false,
  minZoom: 1,
  maxZoom: 10,

  // controls
  dragging: false,
  touchZoom: false,
  doubleClickZoom: false,
  scrollWheelZoom: false,
  boxZoom: false,
  keyboard: false,
  tap: false,
  zoomControl: false,
  attributionControl: false
});

//New OSOpenSpace layer with API Key
var openspaceLayer = L.tileLayer.osopenspace("FFB702322FDF714DE0430B6CA40A06C6", {debug: true});
map.addLayer(openspaceLayer);

//Define name of CRS in GeoJSON using PROJ4
proj4.defs("urn:ogc:def:crs:EPSG:27700","+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +datum=OSGB36 +units=m +no_defs");

//Add the GeoJSON to the map
var geoJson = L.Proj.geoJson(extentData, {
  color: 'red',
  fillColor: '#f03',
  fillOpacity: 0.5
})
geoJson.addTo(map);

//Add a scale control to the map
L.control.scale().addTo(map);

//Center map view on geojson polygon
var bounds = geoJson.getBounds();
var center = bounds.getCenter();
map.setView([center.lat, center.lng], 9)
map.fitBounds(bounds, {maxZoom: 9, animate: false});
<|endoftext|>


<commit_before>'use strict';

// Setting up route
angular.module('core').config(['$stateProvider', '$urlRouterProvider',
	function($stateProvider, $urlRouterProvider) {
		// Redirect to home view when route not found
		$urlRouterProvider.otherwise('/');

		// Home state routing
		$stateProvider.
		state('home', {
			url: '/',
			templateUrl: 'modules/core/views/home.client.view.html'
		});
	}
]);<commit_msg>Add message path to routes<commit_after>'use strict';

// Setting up route
angular.module('core').config(['$stateProvider', '$urlRouterProvider',
	function($stateProvider, $urlRouterProvider) {
		// Redirect to home view when route not found
		$urlRouterProvider.otherwise('/');

		// Home state routing
		$stateProvider.
		state('message', {
			url: '/message/:id',
			templateUrl: 'modules/core/views/message.client.view.html'
		}).
		state('home', {
			url: '/',
			templateUrl: 'modules/core/views/home.client.view.html'
		});
	}
]);
<|endoftext|>


<commit_before>'use strict';

var through = require('through2'),
    path = require('path');
module.exports = function (assumeIndex) {
    return through.obj(function (file, enc, cb) {
        var fp = file.path,
            extname = path.extname(fp),
            len = extname.length,
            filename = path.basename(fp, extname),
            newPath = path.dirname(fp) + '/' + filename + '/' + path.basename(fp);

        if (assumeIndex) {
            newPath = path.dirname(fp) + '/' + filename + '/index.html';
        }

        if (filename !== 'index') {
            file.path = newPath;
        }

        this.push(file);
        cb();
    });
};
<commit_msg>Tweak permalinks<commit_after>'use strict';

var through = require('through2'),
    path = require('path');
module.exports = function (assumeIndex) {
    return through.obj(function (file, enc, cb) {
        var fp = file.path,
            extname = path.extname(fp),
            len = extname.length,
            filename = path.basename(fp, extname),
            newPath = path.dirname(fp) + '/' + filename + '/' + path.basename(fp);

        if (assumeIndex) {
            newPath = path.dirname(fp) + '/' + filename + '/index.html';
        }

        if (filename !== 'index' || assumeIndex) {
            file.path = newPath;
        }

        this.push(file);
        cb();
    });
};
<|endoftext|>


<commit_before>angular.module('asch').controller('blockchainCtrl', function ($scope, $rootScope, apiService, ipCookie, $location, $window, NgTableParams, $translate,TransactionRecords) {
	$rootScope.active = 'blockchain';
	$rootScope.userlogin = true;
	$rootScope.blockchaintopList = true;
	$rootScope.blocktransactionsUnderBlock = false;
	$rootScope.blocktransactionsUnderAddress = false;
	$rootScope.blocktransactionsDetail = false;
	$rootScope.showdealInfo = function (i) {
		$rootScope.blockdetailinfo = false;
		$rootScope.accountdetailinfo = false;
		$scope.i = i;
		$rootScope.$broadcast('jiaoyi', $scope.i)
	}
	$rootScope.showdetailInfo = function (i) {
		$rootScope.accountdetailinfo = false;
		$rootScope.dealdetailinfo = false;
		$scope.i = i;
		$rootScope.$broadcast('detail', $scope.i)
	}
	$rootScope.showaccountdetailInfo = function (i) {
		$rootScope.blockdetailinfo = false;
		$rootScope.dealdetailinfo = false;
		$scope.i = i;
		$rootScope.$broadcast('accountdetail', $scope.i)
	}
	$scope.init = function () {
		initialTable();
	};
	function initialTable(){
		$scope.blockchaintableparams = new NgTableParams({
			page: 1,
			count: 20,
			sorting: {
				height: 'desc'
			}
		}, {
			total: 0,
			getData: function ($defer, params) {
				apiService.blocks({
					limit: params.count(),
					orderBy: 'height:desc',
					offset: (params.page() - 1) * params.count()
				}).success(function (res) {
					params.total(res.count);
					$defer.resolve(res.blocks);
				}).error(function (res) {
					toastError($translate.instant('ERR_SERVER_ERROR'));
				});
			}
		});
	}
	//搜索区块或地址或交易ID
	$scope.searchBlockOrAddress = function () {
		if (!$scope.search) {
			initialTable();
			toast($translate.instant('ERR_SEARCH_EMPTY'));
		}else{
			var content = $scope.search.replace(/(^\s*)|(\s*$)/g, "");
			if(/^[A-Za-z\d]{33,34}$/.test(content)){
				$rootScope.showAddressTransactions(content);
			}else if(/^\d+$/.test(content)){
				$rootScope.showBlockTransactionsByHeight(content);
			}else if(content.length==64){
		        $rootScope.showTransactionDetailById(content);
		    }else if(content.length<33 && !/^\d+$/.test(content)){
		        toast($translate.instant('ACCOUNT_NOT_FOUND'));
		    }else if(content.length>34 && !/^\d+$/.test(content)){
		        toast($translate.instant('TRANSACTION_ID_NOT_FOUND'));
		    }else{
		    	toast($translate.instant('INCORRECT_TYPEIN'));
		    }
		}
	}
	//区块下的交易详情
	$rootScope.showBlockTransactionsByHeight = function(i){
		apiService.blockDetail({
			height: i
		}).success(function (res) {
			if(res.success){
				$rootScope.blockchaintopList = false;
				$rootScope.blocktransactionsUnderBlock = true;
				$rootScope.blocktransactionsUnderAddress = false;
				$rootScope.blocktransactionsDetail = false;
				res.block.totalFee = res.block.totalFee / Math.pow(10,6);
		        res.block.reward = res.block.reward / Math.pow(10,6);
		        $scope.block = res.block;
		        $scope.blockTransactions = new TransactionRecords(res.block.id,"block");
		        $scope.blockTransactions.nextPage();
		    }else{
				toast(res.error);
			}
		}).error(function (res) {
			toastError($translate.instant('ERR_SERVER_ERROR'));
		});

	}
	$rootScope.showBlockTransactionsById = function(i){
		apiService.blockDetail({
			id:i
		}).success(function (res) {
			if(res.success){
				$rootScope.blockchaintopList = false;
				$rootScope.blocktransactionsUnderBlock = true;
				$rootScope.blocktransactionsUnderAddress = false;
				$rootScope.blocktransactionsDetail = false;
				res.block.totalFee = res.block.totalFee / Math.pow(10,6);
		        res.block.reward = res.block.reward / Math.pow(10,6);
		        $scope.block = res.block;
			}else{
				toast(res.error);
			}
		}).error(function (res) {
			toastError($translate.instant('ERR_SERVER_ERROR'));
		});
		$scope.blockTransactions = new TransactionRecords(i,"block");
		$scope.blockTransactions.nextPage();
	}
	//地址下的交易详情
	$rootScope.showAddressTransactions = function(i){
		if(i == "System")return;
		$scope.addressTransactions = new TransactionRecords(i,"address");
		$scope.addressTransactions.nextPage();
		apiService.accountdetail({
			address: i
		}).success(function (res) {
			if(res.success){
				$rootScope.blockchaintopList = false;
				$rootScope.blocktransactionsUnderBlock = false;
				$rootScope.blocktransactionsUnderAddress = true;
				$rootScope.blocktransactionsDetail = false;
				res.account.balance = res.account.balance / Math.pow(10,6);
				$scope.addressInfo = res;
				apiService.transactions({
					senderId: i,
			    	recipientId: i
				}).success(function (response) {
					if(response.success){
						$scope.addrTransactionCount = response.count;
					}else{
						toast(response.error);
					}
				});
			}else{
				toast(res.error);
			}
		}).error(function (res) {
			toastError($translate.instant('ERR_SERVER_ERROR'));
		});

	}
	//根据交易id查询交易信息
	$rootScope.showTransactionDetailById=function(i){
		apiService.transactiondetail({
			id: i
	    }).success(function (res) {
	    	if(res.success){
	    		$rootScope.blockchaintopList = false;
				$rootScope.blocktransactionsUnderBlock = false;
				$rootScope.blocktransactionsUnderAddress = false;
				$rootScope.blocktransactionsDetail = true;
		    	res.transaction.recipientId = res.transaction.recipientId === ""?"System":res.transaction.recipientId;
		    	res.transaction.currency = res.transaction.currency === ""?"ACC":res.transaction.currency;
		    	res.transaction.fee = res.transaction.fee / Math.pow(10,6);
		    	$scope.bytesCount = JSON.stringify(res).length;
				$scope.transactionsDetail = res.transaction;
			}else{
	    		toast(res.error);
	    	}
		}).error(function (res) {
			toastError($translate.instant('ERR_SERVER_ERROR'));
		});
	}
	//返回
	$scope.returnTopList = function(){
		initialTable();
		$rootScope.blockchaintopList = true;
		$rootScope.blocktransactionsUnderBlock = false;
		$rootScope.blocktransactionsUnderAddress = false;
		$rootScope.blocktransactionsDetail = false;
	}
	//展示全部
	$rootScope.otherbalancesInfo = false;
	$rootScope.showotherbalancesInfo = function (i) {
		apiService.myBalances({
			address: i
	    }).success(function (res) {
	    	if(res.success){
	    		if(res.count != 0){
	    			$rootScope.isBodyMask = true;
	    			$rootScope.otherbalancesInfo = true;
	    			for(var i=0;i<res.balances.length;i++){
	    				res.balances[i].balance = res.balances[i].balance / Math.pow(10,res.balances[i].precision);
	    			}
	    			$scope.otherbalances = res.balances;
	    		}else{
	    			toastError($translate.instant('NO_OTHERBALANCES'));
	    		}
	    	}else{
	    		toast(res.error);
	    	}
		}).error(function (res) {
			toastError($translate.instant('ERR_SERVER_ERROR'));
		});
    }
	$scope.close = function () {
        $rootScope.isBodyMask = false;
        $rootScope.otherbalancesInfo = false;
    };
});

angular.module('asch').factory('TransactionRecords', function(apiService) {
	var TransactionRecords = function(condition,type) {
	    this.items = [];
	    this.busy = false;
	    this.limit = 10;
	    this.offset = 0;
	    this.disable = false;
	    this.condition = condition;
	    this.type = type;
	};
	TransactionRecords.prototype.nextPage = function() {
	    if (this.busy) return;
	    this.busy = true;
		if(this.type == "block"){
			apiService.transactions({
				limit:this.limit,
				offset: this.offset,
				orderBy: 't_timestamp:desc',
				blockId:this.condition
			}).success(function (response) {
				if(response.success){
					//console.log(response);
					var items = response.transactions;
					for (var i = 0; i < items.length; i++) {
						items[i].recipientId = items[i].recipientId === ""?"System":items[i].recipientId;
						items[i].fee = items[i].fee / Math.pow(10,6);
			            this.items.push(items[i]);
			        }
			       	this.busy = false;
			    	if(this.offset+this.limit > response.count){
			    		this.offset += (this.offset+this.limit-response.count);
			    		this.disable= true;
			    	}else{
			    		this.offset += 10;
			    	}
				}else{
					toast(response.error);
				}
			}.bind(this)).error(function (response) {
				toastError($translate.instant('ERR_SERVER_ERROR'));
			});
		}else if(this.type == "address"){
			apiService.transactions({
				limit:this.limit,
				offset: this.offset,
				orderBy: 't_timestamp:desc',
				senderId:this.condition,
				recipientId:this.condition
			}).success(function (response) {
				if(response.success){
					//console.log(response);
					var items = response.transactions;
					for (var i = 0; i < items.length; i++) {
						items[i].recipientId = items[i].recipientId === ""?"System":items[i].recipientId;
						items[i].currency = items[i].currency === ""?"ACC":items[i].currency;
						items[i].fee = items[i].fee / Math.pow(10,6);
			            this.items.push(items[i]);
			        }
			       	this.busy = false;
			    	if(this.offset+this.limit > response.count){
			    		this.offset += (this.offset+this.limit-response.count);
			    		this.disable= true;
			    	}else{
			    		this.offset += 10;
			    	}
				}else{
					toast(response.error);
				}
			}.bind(this)).error(function (response) {
				toastError($translate.instant('ERR_SERVER_ERROR'));
			});
		}
	};
	return TransactionRecords;
});

<commit_msg>Default currency set as 'ACC'<commit_after>angular.module('asch').controller('blockchainCtrl', function ($scope, $rootScope, apiService, ipCookie, $location, $window, NgTableParams, $translate,TransactionRecords) {
	$rootScope.active = 'blockchain';
	$rootScope.userlogin = true;
	$rootScope.blockchaintopList = true;
	$rootScope.blocktransactionsUnderBlock = false;
	$rootScope.blocktransactionsUnderAddress = false;
	$rootScope.blocktransactionsDetail = false;
	$rootScope.showdealInfo = function (i) {
		$rootScope.blockdetailinfo = false;
		$rootScope.accountdetailinfo = false;
		$scope.i = i;
		$rootScope.$broadcast('jiaoyi', $scope.i)
	}
	$rootScope.showdetailInfo = function (i) {
		$rootScope.accountdetailinfo = false;
		$rootScope.dealdetailinfo = false;
		$scope.i = i;
		$rootScope.$broadcast('detail', $scope.i)
	}
	$rootScope.showaccountdetailInfo = function (i) {
		$rootScope.blockdetailinfo = false;
		$rootScope.dealdetailinfo = false;
		$scope.i = i;
		$rootScope.$broadcast('accountdetail', $scope.i)
	}
	$scope.init = function () {
		initialTable();
	};
	function initialTable(){
		$scope.blockchaintableparams = new NgTableParams({
			page: 1,
			count: 20,
			sorting: {
				height: 'desc'
			}
		}, {
			total: 0,
			getData: function ($defer, params) {
				apiService.blocks({
					limit: params.count(),
					orderBy: 'height:desc',
					offset: (params.page() - 1) * params.count()
				}).success(function (res) {
					params.total(res.count);
					$defer.resolve(res.blocks);
				}).error(function (res) {
					toastError($translate.instant('ERR_SERVER_ERROR'));
				});
			}
		});
	}
	//搜索区块或地址或交易ID
	$scope.searchBlockOrAddress = function () {
		if (!$scope.search) {
			initialTable();
			toast($translate.instant('ERR_SEARCH_EMPTY'));
		}else{
			var content = $scope.search.replace(/(^\s*)|(\s*$)/g, "");
			if(/^[A-Za-z\d]{33,34}$/.test(content)){
				$rootScope.showAddressTransactions(content);
			}else if(/^\d+$/.test(content)){
				$rootScope.showBlockTransactionsByHeight(content);
			}else if(content.length==64){
		        $rootScope.showTransactionDetailById(content);
		    }else if(content.length<33 && !/^\d+$/.test(content)){
		        toast($translate.instant('ACCOUNT_NOT_FOUND'));
		    }else if(content.length>34 && !/^\d+$/.test(content)){
		        toast($translate.instant('TRANSACTION_ID_NOT_FOUND'));
		    }else{
		    	toast($translate.instant('INCORRECT_TYPEIN'));
		    }
		}
	}
	//区块下的交易详情
	$rootScope.showBlockTransactionsByHeight = function(i){
		apiService.blockDetail({
			height: i
		}).success(function (res) {
			if(res.success){
				$rootScope.blockchaintopList = false;
				$rootScope.blocktransactionsUnderBlock = true;
				$rootScope.blocktransactionsUnderAddress = false;
				$rootScope.blocktransactionsDetail = false;
				res.block.totalFee = res.block.totalFee / Math.pow(10,6);
		        res.block.reward = res.block.reward / Math.pow(10,6);
		        $scope.block = res.block;
		        $scope.blockTransactions = new TransactionRecords(res.block.id,"block");
		        $scope.blockTransactions.nextPage();
		    }else{
				toast(res.error);
			}
		}).error(function (res) {
			toastError($translate.instant('ERR_SERVER_ERROR'));
		});

	}
	$rootScope.showBlockTransactionsById = function(i){
		apiService.blockDetail({
			id:i
		}).success(function (res) {
			if(res.success){
				$rootScope.blockchaintopList = false;
				$rootScope.blocktransactionsUnderBlock = true;
				$rootScope.blocktransactionsUnderAddress = false;
				$rootScope.blocktransactionsDetail = false;
				res.block.totalFee = res.block.totalFee / Math.pow(10,6);
		        res.block.reward = res.block.reward / Math.pow(10,6);
		        $scope.block = res.block;
			}else{
				toast(res.error);
			}
		}).error(function (res) {
			toastError($translate.instant('ERR_SERVER_ERROR'));
		});
		$scope.blockTransactions = new TransactionRecords(i,"block");
		$scope.blockTransactions.nextPage();
	}
	//地址下的交易详情
	$rootScope.showAddressTransactions = function(i){
		if(i == "System")return;
		$scope.addressTransactions = new TransactionRecords(i,"address");
		$scope.addressTransactions.nextPage();
		apiService.accountdetail({
			address: i
		}).success(function (res) {
			if(res.success){
				$rootScope.blockchaintopList = false;
				$rootScope.blocktransactionsUnderBlock = false;
				$rootScope.blocktransactionsUnderAddress = true;
				$rootScope.blocktransactionsDetail = false;
				res.account.balance = res.account.balance / Math.pow(10,6);
				$scope.addressInfo = res;
				apiService.transactions({
					senderId: i,
			    	recipientId: i
				}).success(function (response) {
					if(response.success){
						$scope.addrTransactionCount = response.count;
					}else{
						toast(response.error);
					}
				});
			}else{
				toast(res.error);
			}
		}).error(function (res) {
			toastError($translate.instant('ERR_SERVER_ERROR'));
		});

	}
	//根据交易id查询交易信息
	$rootScope.showTransactionDetailById=function(i){
		apiService.transactiondetail({
			id: i
	    }).success(function (res) {
	    	if(res.success){
	    		$rootScope.blockchaintopList = false;
				$rootScope.blocktransactionsUnderBlock = false;
				$rootScope.blocktransactionsUnderAddress = false;
				$rootScope.blocktransactionsDetail = true;
		    	res.transaction.recipientId = res.transaction.recipientId === ""?"System":res.transaction.recipientId;
		    	res.transaction.currency = res.transaction.currency === ""?"ACC":res.transaction.currency;
		    	res.transaction.fee = res.transaction.fee / Math.pow(10,6);
		    	$scope.bytesCount = JSON.stringify(res).length;
				$scope.transactionsDetail = res.transaction;
			}else{
	    		toast(res.error);
	    	}
		}).error(function (res) {
			toastError($translate.instant('ERR_SERVER_ERROR'));
		});
	}
	//返回
	$scope.returnTopList = function(){
		initialTable();
		$rootScope.blockchaintopList = true;
		$rootScope.blocktransactionsUnderBlock = false;
		$rootScope.blocktransactionsUnderAddress = false;
		$rootScope.blocktransactionsDetail = false;
	}
	//展示全部
	$rootScope.otherbalancesInfo = false;
	$rootScope.showotherbalancesInfo = function (i) {
		apiService.myBalances({
			address: i
	    }).success(function (res) {
	    	if(res.success){
	    		if(res.count != 0){
	    			$rootScope.isBodyMask = true;
	    			$rootScope.otherbalancesInfo = true;
	    			for(var i=0;i<res.balances.length;i++){
	    				res.balances[i].balance = res.balances[i].balance / Math.pow(10,res.balances[i].precision);
	    			}
	    			$scope.otherbalances = res.balances;
	    		}else{
	    			toastError($translate.instant('NO_OTHERBALANCES'));
	    		}
	    	}else{
	    		toast(res.error);
	    	}
		}).error(function (res) {
			toastError($translate.instant('ERR_SERVER_ERROR'));
		});
    }
	$scope.close = function () {
        $rootScope.isBodyMask = false;
        $rootScope.otherbalancesInfo = false;
    };
});

angular.module('asch').factory('TransactionRecords', function(apiService) {
	var TransactionRecords = function(condition,type) {
	    this.items = [];
	    this.busy = false;
	    this.limit = 10;
	    this.offset = 0;
	    this.disable = false;
	    this.condition = condition;
	    this.type = type;
	};
	TransactionRecords.prototype.nextPage = function() {
	    if (this.busy) return;
	    this.busy = true;
		if(this.type == "block"){
			apiService.transactions({
				limit:this.limit,
				offset: this.offset,
				orderBy: 't_timestamp:desc',
				blockId:this.condition
			}).success(function (response) {
				if(response.success){
					//console.log(response);
					var items = response.transactions;
					for (var i = 0; i < items.length; i++) {
						items[i].recipientId = items[i].recipientId === ""?"System":items[i].recipientId;
						items[i].currency = items[i].currency === ""?"ACC":items[i].currency;
						items[i].fee = items[i].fee / Math.pow(10,6);
			            this.items.push(items[i]);
			        }
			       	this.busy = false;
			    	if(this.offset+this.limit > response.count){
			    		this.offset += (this.offset+this.limit-response.count);
			    		this.disable= true;
			    	}else{
			    		this.offset += 10;
			    	}
				}else{
					toast(response.error);
				}
			}.bind(this)).error(function (response) {
				toastError($translate.instant('ERR_SERVER_ERROR'));
			});
		}else if(this.type == "address"){
			apiService.transactions({
				limit:this.limit,
				offset: this.offset,
				orderBy: 't_timestamp:desc',
				senderId:this.condition,
				recipientId:this.condition
			}).success(function (response) {
				if(response.success){
					//console.log(response);
					var items = response.transactions;
					for (var i = 0; i < items.length; i++) {
						items[i].recipientId = items[i].recipientId === ""?"System":items[i].recipientId;
						items[i].currency = items[i].currency === ""?"ACC":items[i].currency;
						items[i].fee = items[i].fee / Math.pow(10,6);
			            this.items.push(items[i]);
			        }
			       	this.busy = false;
			    	if(this.offset+this.limit > response.count){
			    		this.offset += (this.offset+this.limit-response.count);
			    		this.disable= true;
			    	}else{
			    		this.offset += 10;
			    	}
				}else{
					toast(response.error);
				}
			}.bind(this)).error(function (response) {
				toastError($translate.instant('ERR_SERVER_ERROR'));
			});
		}
	};
	return TransactionRecords;
});

<|endoftext|>


<commit_before>const test = require('tape')
const BorrowState = require('../lib/module.js')

const sleep50ms = require('./sleep.js')
const countTo = require('./count-to.js')

;[true, false].forEach((unsafe) => {
  test(`read-only-parallel (${unsafe ? 'un' : ''}safe)`, (t) => {
    t.plan(3)
    t.timeoutAfter(100)
    let myState = new BorrowState()
    countTo(3).forEach(() => {
      myState.block('r')
        .then(sleep50ms)
        .then((state) => {
          t.ok(true)
          state.unblock()
        })
    })
  })
})
<commit_msg>Make sure to count up test additions<commit_after>const test = require('tape')
const BorrowState = require('../lib/module.js')

const sleep50ms = require('./sleep.js')
const countTo = require('./count-to.js')

;[true, false].forEach((unsafe) => {
  test(`read-only-parallel (${unsafe ? 'un' : ''}safe)`, (t) => {
    t.plan(6)
    t.timeoutAfter(100)
    let myState = new BorrowState()
    countTo(3).forEach(() => {
      t.ok(true)
      myState.block('r')
        .then(sleep50ms)
        .then((state) => {
          t.ok(true)
          state.unblock()
        })
    })
  })
})
<|endoftext|>


<commit_before>// we will re-enable the broken browsers once saucelabs will fix all the timeout issues
module.exports = {
  browsers: {
    slIphone5: {
      base: 'SauceLabs',
      browserName: 'iphone',
      version: '8.4'
    },
    slIpad: {
      base: 'SauceLabs',
      browserName: 'ipad',
      version: '10.3'
    },
    slIphone6: {
      base: 'SauceLabs',
      browserName: 'iphone',
      version: '10.3'
    },
    slSafari7: {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.9'
    },
    slSafari8: {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.10'
    },
    slSafari9: {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.11'
    },
    slIE9: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '9'
    },
    slIE10: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '10'
    },
    slIE11: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '11'
    },
    slEdge: {
      base: 'SauceLabs',
      browserName: 'MicrosoftEdge',
      platform: 'Windows 10'
    },
    slChrome: {
      base: 'SauceLabs',
      browserName: 'chrome'
    },
    slFirefox: {
      base: 'SauceLabs',
      browserName: 'firefox'
    },
    slAndroid5: {
      base: 'SauceLabs',
      browserName: 'android',
      version: '5.1'
    },
    slAndroid4: {
      base: 'SauceLabs',
      browserName: 'android',
      version: '4.4'
    }
  }
}
<commit_msg>updated: stick to edge 15 for the unit test<commit_after>// we will re-enable the broken browsers once saucelabs will fix all the timeout issues
module.exports = {
  browsers: {
    slIphone5: {
      base: 'SauceLabs',
      browserName: 'iphone',
      version: '8.4'
    },
    slIpad: {
      base: 'SauceLabs',
      browserName: 'ipad',
      version: '10.3'
    },
    slIphone6: {
      base: 'SauceLabs',
      browserName: 'iphone',
      version: '10.3'
    },
    slSafari7: {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.9'
    },
    slSafari8: {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.10'
    },
    slSafari9: {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.11'
    },
    slIE9: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '9'
    },
    slIE10: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '10'
    },
    slIE11: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '11'
    },
    slEdge: {
      base: 'SauceLabs',
      browserName: 'MicrosoftEdge',
      version: '15',
      platform: 'Windows 10'
    },
    slChrome: {
      base: 'SauceLabs',
      browserName: 'chrome'
    },
    slFirefox: {
      base: 'SauceLabs',
      browserName: 'firefox'
    },
    slAndroid5: {
      base: 'SauceLabs',
      browserName: 'android',
      version: '5.1'
    },
    slAndroid4: {
      base: 'SauceLabs',
      browserName: 'android',
      version: '4.4'
    }
  }
}
<|endoftext|>


<commit_before>// days to seconds for time graph
function getDays(seconds) {
    exactDays = seconds / 86400;
    return exactDays.toFixed(2);
}
function getHours(seconds) {
    exactHours = seconds / 3600;
    return exactHours.toFixed(1);
}

var shortDeptNames = {
    "Office of the Mayor":                  'Mayor',
    "City Administrator":                   'City Admin',
    "City Clerk":                           'Clerk',
    "City Auditor":                         'Auditor',
    "City Attorney":                        'Attorney',
    "Parks and Recreation":                 'Parks & Rec',
    "Public Works Agency":                  'Public Works',
    "Department of Planning and Building":  'Planning',
    "Fire Department":                      'Fire',
    "Library Services":                     'Library',
    "Office of Controller and Treasury":    'Treasury',
    "Contracts and Compliance":             'Contracts',
    "Information Technology (IT)":          'IT',
    "Office of Neighborhood Investment":    'Neighborhood',
    "Health and Human Services":            'Health',
    "Human Resources":                      'HR',
    "Budget and Revenue - Revenue Division":            'Budget',
    "Council District 1 - Dan Kalb":        'D1',
    "Council District 2 - Pat Kernighan":   'D2',
    "Council District 3 - Lynette Gibson McElhaney":    'D3',
    "Council District 4 - Libby Schaaf":    'D4',
    "Council District 5 - Noel Gallo":      'D5',
    "Council District 6 - Desley Brooks":   'D6',
    "Council District 7 - Larry Reid":      'D7',
    "Council At Large - Rebecca Kaplan":    'Council',
    "Oakland Police Department":            'Police'
}

// Create Frequency Graph for department requests volume
// ==================================

$(function(){

    var margin = {top: 30, right: 40, bottom: 30, left: 40},
        height = 250 - margin.top - margin.bottom,
        width = $('#responses-freq-viz').parent().width() - margin.left - margin.right;

    $('#responses-freq-viz').parents('.well').height(height + 270);

    var formatYAxis = d3.format("f");

    var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .1);

    var y = d3.scale.linear()
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left")
        .tickFormat(formatYAxis)
        .ticks(5);

    var svg = d3.select("#responses-freq-viz").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var tip = d3.tip()
        .attr('class', 'd3-tip')
        .offset([-10, 0])
        .html(function(d) {
          return d.department + "

Requests: " + d.freq + "
";
        });
    svg.call(tip);

    d3.json(viz_data_freq, function(error, json) {
        // if (error) return console.warn("Didn't recive departments frequencies.");
        data = viz_data_freq;
        x.domain(data.map(function(d) { return shortDeptNames[d.department]; }));
        y.domain([0, d3.max(data, function(d) { return d.freq; })]);

        // X-Axis
        svg.append("g")
            .attr("class", "no-line axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis)
            .style("width", "50px")
            .attr("text-anchor", "end")
            .attr("textLength", "10");

        svg.selectAll("text")

        // Y-Axis
        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis)
            .append("text")
            .attr("transform", "rotate(-90)")
            .attr("y", 6)
            .attr("dy", ".71em");

        // Heading Text
        svg.append("text")
            .attr("x", (width/4))
            .attr("y", -10)
            .style("font-size", "14px")
            .style("fill", "#333333")
            .style("font-weight", "bold")
            .text("Top Five Departments - Total Number of Requests");

        // draw bars vectors
        svg.selectAll(".bar")
            .data(data)
            .enter().append("rect")
            .attr("class", "bar")
            .attr("x", function(d) { return x(shortDeptNames[d.department]); })
            .attr("width", x.rangeBand())
            .attr("y", function(d) { return y(d.freq); })
            .attr("height", function(d) { return height - y(d.freq); })
            .on('mouseover', tip.show)
            .on('mouseout', tip.hide);
  });
});

// Create Average Response Time Graph
// ==================================

$(function() {

    var marginHoriz = {top: 30, right: 20, bottom: 30, left: 90},
        height = 250 - marginHoriz.top - marginHoriz.bottom,
        width = $('#responses-time-viz').parent().width() - marginHoriz.left - marginHoriz.right;

    var xResponseTime = d3.scale.linear()
        .range([0, width]);

    var yDepartments = d3.scale.ordinal()
        .rangeRoundBands([height, 0], .1);

    var xResponseTimeAxis = d3.svg.axis()
        .scale(xResponseTime)
        .orient("bottom");

    var yDepartmentsAxis = d3.svg.axis()
        .scale(yDepartments)
        .orient("left")
        .ticks(5);

    var svgNext = d3.select("#responses-time-viz").append("svg")
        .attr("width", width + marginHoriz.left + marginHoriz.right)
        .attr("height", height + marginHoriz.top + marginHoriz.bottom)
        .append("g")
        .attr("transform", "translate(" + marginHoriz.left + "," + marginHoriz.top + ")");

    var tipNext = d3.tip()
        .attr('class', 'd3-tip')
        .offset([-10, 0])
        .html(function(d) {
          return d.department + "

Requests: " + getDays(d.time) + " days
";
        });

    svgNext.call(tipNext);

d3.json(viz_data_time, function(error, json) {
        // if (error) return console.warn("Didn't recive departments frequencies.");
        data = viz_data_time;

        xResponseTime.domain([0, getDays(d3.max(data, function(d) { return d.time; }))]);
        yDepartments.domain(data.map(function(d) { return shortDeptNames[d.department]; }));

        // xAxis -- Time responses graph
        svgNext.append("g")
            .attr("class", "x axis")
            .attr("transform", "rotate(-90)")
            .attr("transform", "translate(0," + height + ")")
            .call(xResponseTimeAxis);

        // yAxis -- Depatments listings
        svgNext.append("g")
            .attr("class", "no-line axis")
            .call(yDepartmentsAxis)
            .attr("dy", ".71em")
            .style("text-anchor", "end");

        // draw bars
        svgNext.selectAll(".bar")
            .data(data)
            .enter().append("rect")
            .attr("class", "bar")
            .attr("width", function(d) { return xResponseTime(getDays(d.time)); })
            .attr("y", function(d) { return yDepartments(shortDeptNames[d.department]); })
            .attr("height", yDepartments.rangeBand())
            .on('mouseover', tipNext.show)
            .on('mouseout', tipNext.hide);

        // Heading Text
        svgNext.append("text")
            .attr("x", (width/4))
            .attr("y", -10)
            .style("font-size", "14px")
            .style("fill", "#333333")
            .style("font-weight", "bold")
            .text("Top Five Departments - Quickest Average Response Time");
  });
});<commit_msg>moar title changes<commit_after>// days to seconds for time graph
function getDays(seconds) {
    exactDays = seconds / 86400;
    return exactDays.toFixed(2);
}
function getHours(seconds) {
    exactHours = seconds / 3600;
    return exactHours.toFixed(1);
}

var shortDeptNames = {
    "Office of the Mayor":                  'Mayor',
    "City Administrator":                   'City Admin',
    "City Clerk":                           'Clerk',
    "City Auditor":                         'Auditor',
    "City Attorney":                        'Attorney',
    "Parks and Recreation":                 'Parks & Rec',
    "Public Works Agency":                  'Public Works',
    "Department of Planning and Building":  'Planning',
    "Fire Department":                      'Fire',
    "Library Services":                     'Library',
    "Office of Controller and Treasury":    'Treasury',
    "Contracts and Compliance":             'Contracts',
    "Information Technology (IT)":          'IT',
    "Office of Neighborhood Investment":    'Neighborhood',
    "Health and Human Services":            'Health',
    "Human Resources":                      'HR',
    "Budget and Revenue - Revenue Division":            'Budget',
    "Council District 1 - Dan Kalb":        'D1',
    "Council District 2 - Pat Kernighan":   'D2',
    "Council District 3 - Lynette Gibson McElhaney":    'D3',
    "Council District 4 - Libby Schaaf":    'D4',
    "Council District 5 - Noel Gallo":      'D5',
    "Council District 6 - Desley Brooks":   'D6',
    "Council District 7 - Larry Reid":      'D7',
    "Council At Large - Rebecca Kaplan":    'Council',
    "Oakland Police Department":            'Police'
}

// Create Frequency Graph for department requests volume
// ==================================

$(function(){

    var margin = {top: 30, right: 40, bottom: 30, left: 40},
        height = 250 - margin.top - margin.bottom,
        width = $('#responses-freq-viz').parent().width() - margin.left - margin.right;

    $('#responses-freq-viz').parents('.well').height(height + 270);

    var formatYAxis = d3.format("f");

    var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .1);

    var y = d3.scale.linear()
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left")
        .tickFormat(formatYAxis)
        .ticks(5);

    var svg = d3.select("#responses-freq-viz").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var tip = d3.tip()
        .attr('class', 'd3-tip')
        .offset([-10, 0])
        .html(function(d) {
          return d.department + "

Requests: " + d.freq + "
";
        });
    svg.call(tip);

    d3.json(viz_data_freq, function(error, json) {
        // if (error) return console.warn("Didn't recive departments frequencies.");
        data = viz_data_freq;
        x.domain(data.map(function(d) { return shortDeptNames[d.department]; }));
        y.domain([0, d3.max(data, function(d) { return d.freq; })]);

        // X-Axis
        svg.append("g")
            .attr("class", "no-line axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis)
            .style("width", "50px")
            .attr("text-anchor", "end")
            .attr("textLength", "10");

        svg.selectAll("text")

        // Y-Axis
        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis)
            .append("text")
            .attr("transform", "rotate(-90)")
            .attr("y", 6)
            .attr("dy", ".71em");

        // Heading Text
        svg.append("text")
            .attr("x", (width/4))
            .attr("y", -10)
            .style("font-size", "14px")
            .style("fill", "#333333")
            .style("font-weight", "bold")
            .text("Total Number of Requests - Top Five Departments");

        // draw bars vectors
        svg.selectAll(".bar")
            .data(data)
            .enter().append("rect")
            .attr("class", "bar")
            .attr("x", function(d) { return x(shortDeptNames[d.department]); })
            .attr("width", x.rangeBand())
            .attr("y", function(d) { return y(d.freq); })
            .attr("height", function(d) { return height - y(d.freq); })
            .on('mouseover', tip.show)
            .on('mouseout', tip.hide);
  });
});

// Create Average Response Time Graph
// ==================================

$(function() {

    var marginHoriz = {top: 30, right: 20, bottom: 30, left: 90},
        height = 250 - marginHoriz.top - marginHoriz.bottom,
        width = $('#responses-time-viz').parent().width() - marginHoriz.left - marginHoriz.right;

    var xResponseTime = d3.scale.linear()
        .range([0, width]);

    var yDepartments = d3.scale.ordinal()
        .rangeRoundBands([height, 0], .1);

    var xResponseTimeAxis = d3.svg.axis()
        .scale(xResponseTime)
        .orient("bottom");

    var yDepartmentsAxis = d3.svg.axis()
        .scale(yDepartments)
        .orient("left")
        .ticks(5);

    var svgNext = d3.select("#responses-time-viz").append("svg")
        .attr("width", width + marginHoriz.left + marginHoriz.right)
        .attr("height", height + marginHoriz.top + marginHoriz.bottom)
        .append("g")
        .attr("transform", "translate(" + marginHoriz.left + "," + marginHoriz.top + ")");

    var tipNext = d3.tip()
        .attr('class', 'd3-tip')
        .offset([-10, 0])
        .html(function(d) {
          return d.department + "

Requests: " + getDays(d.time) + " days
";
        });

    svgNext.call(tipNext);

d3.json(viz_data_time, function(error, json) {
        // if (error) return console.warn("Didn't recive departments frequencies.");
        data = viz_data_time;

        xResponseTime.domain([0, getDays(d3.max(data, function(d) { return d.time; }))]);
        yDepartments.domain(data.map(function(d) { return shortDeptNames[d.department]; }));

        // xAxis -- Time responses graph
        svgNext.append("g")
            .attr("class", "x axis")
            .attr("transform", "rotate(-90)")
            .attr("transform", "translate(0," + height + ")")
            .call(xResponseTimeAxis);

        // yAxis -- Depatments listings
        svgNext.append("g")
            .attr("class", "no-line axis")
            .call(yDepartmentsAxis)
            .attr("dy", ".71em")
            .style("text-anchor", "end");

        // draw bars
        svgNext.selectAll(".bar")
            .data(data)
            .enter().append("rect")
            .attr("class", "bar")
            .attr("width", function(d) { return xResponseTime(getDays(d.time)); })
            .attr("y", function(d) { return yDepartments(shortDeptNames[d.department]); })
            .attr("height", yDepartments.rangeBand())
            .on('mouseover', tipNext.show)
            .on('mouseout', tipNext.hide);

        // Heading Text
        svgNext.append("text")
            .attr("x", (width/4))
            .attr("y", -10)
            .style("font-size", "14px")
            .style("fill", "#333333")
            .style("font-weight", "bold")
            .text("Quickest Average Response Time -Top Five Departments");
  });
});<|endoftext|>


<commit_before>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';

import { FlatList, View, VirtualizedList, Text, StyleSheet } from 'react-native';
import { SearchBar } from 'react-native-ui-components';

import globalStyles from '../globalStyles';
import { UIDatabase } from '../database/index';

import { schema } from '../database/schema';

const TYPES = {
  BOOLEAN: 'boolean',
  DATE: 'date',
  NUMBER: 'number',
  STRING: 'string',
  ARRAY: 'array',
  OBJECT: 'object',
};

const REALM_TYPES = {
  BOOL: 'bool',
  DATE: 'date',
  DOUBLE: 'double',
  FLOAT: 'float',
  INT: 'int',
  LIST: 'list',
  OBJECT: 'object',
  STRING: 'string',
};

const TYPE_MAPPINGS = {
  [TYPES.BOOLEAN]: [REALM_TYPES.BOOL],
  [TYPES.DATE]: [REALM_TYPES.DATE],
  [TYPES.NUMBER]: [REALM_TYPES.INT, REALM_TYPES.FLOAT, REALM_TYPES.DOUBLE],
  [TYPES.STRING]: [REALM_TYPES.STRING],
  [TYPES.ARRAY]: [REALM_TYPES.LIST],
  [TYPES.OBJECT]: [REALM_TYPES.OBJECT],
};

const typeMapper = new Map(
  Object.entries(TYPE_MAPPINGS)
    .map(([type, realmTypes]) => realmTypes.map(realmType => [realmType, type]))
    .flat()
);

const parseType = realmType => {
  const { type } = realmType;
  if (type) return parseType(type);
  return typeMapper.get(realmType) || TYPES.OBJECT;
};

const getObjectTypes = ({ schema: objectSchemas }) =>
  objectSchemas.map(({ schema: objectSchema }) => objectSchema.name);

const getObjectFields = ({ schema: objectSchemas }) =>
  objectSchemas
    .map(({ schema: objectSchema }) => {
      const { name, properties } = objectSchema;
      const fields = Object.entries(properties)
        .map(([field, type]) => ({
          [field]: parseType(type),
        }))
        .reduce((acc, field) => ({ ...acc, ...field }), {});
      return { [name]: fields };
    })
    .reduce((acc, object) => ({ ...acc, ...object }));

const OBJECT_TYPES = getObjectTypes(schema);
const OBJECT_FIELDS = getObjectFields(schema);

const toCapitalCase = value => value.charAt(0).toUpperCase() + value.slice(1);

const parseString = value => String(value);
const parseNumber = value => String(value);
const parseObject = value => value.id;
const parseArray = value => value.length;
const parseBoolean = value => toCapitalCase(String(value));
const parseDate = value => value.toString();

const parseCell = (value, type) => {
  if (value === null || value === undefined) return 'N/A';
  switch (type) {
    case TYPES.STRING:
      return parseString(value);
    case TYPES.NUMBER:
      return parseNumber(value);
    case TYPES.OBJECT:
      return parseObject(value);
    case TYPES.ARRAY:
      return parseArray(value);
    case TYPES.BOOLEAN:
      return parseBoolean(value);
    case TYPES.DATE:
      return parseDate(value);
    default:
      return '';
  }
};

const getInitialState = database => {
  const [objectString] = OBJECT_TYPES;
  const objectData = database.objects(objectString);
  const searchString = objectString;
  const filterString = '';
  const filteredData = objectData;
  return { objectString, objectData, searchString, filterString, filteredData };
};

const getUpdatedState = (database, state) => {
  const { objectString, objectData, searchString, filterString, filteredData } = state;
  const newState = { searchString, filterString };
  const updateObject = searchString !== objectString && OBJECT_TYPES.indexOf(searchString) >= 0;
  newState.objectString = updateObject ? searchString : objectString;
  newState.objectData = updateObject ? database.objects(newState.objectString) : objectData;
  if (filterString === '') {
    newState.filteredData = newState.objectData;
  } else {
    try {
      newState.filteredData = newState.objectData.filtered(filterString);
    } catch (err) {
      newState.filteredData = updateObject ? newState.objectData : filteredData;
    }
  }

  return newState;
};

/**
 * A page for displaying objects in the local database. Includes search and filtering functionality.
 *
 * @prop   {UIDatabase}     database       App wide database.
 * @state  {string}         objectString   Current database object.
 * @state  {string}         searchString   Current search string. Used to update current object.
 * @state  {string}         filterString   Current filter string. Used to update filtered data.
 * @state  {Realm.Results}  objectData     Reference to current database object results. Used to
 *                                         roll back filter state when filter is reset.
 * @state  {Realm.Results}  filteredData   Reference to current database object results after filter
 *                                         has been applied. Displayed to the user.
 */
export const RealmExplorer = ({ database }) => {
  const [state, setState] = useState(getInitialState(database));

  const onSearchChange = searchString => {
    setState({ ...state, searchString });
  };

  const onFilterChange = filterString => {
    setState({ ...state, filterString });
  };

  useEffect(() => setState(getUpdatedState(database, state)), [
    state.searchString,
    state.filterString,
  ]);

  const objectFields = OBJECT_FIELDS[state.objectString];

  const headerRowKeyExtractor = (_, index) => index.toString();
  const rowKeyExtractor = ({ id }) => id;

  const renderHeaderRow = headerRow => {
    const { item } = headerRow;
    const cells = Object.keys(item).map(columnKey => (
      <View style={styles.cell}>
        <Text style={styles.cellText}>{columnKey}</Text>
      </View>
    ));
    return <View style={styles.row}>{cells}</View>;
  };

  const renderRow = row => {
    const { item } = row;
    const cells = Object.entries(objectFields).map(([columnKey, columnType]) => {
      const cell = item[columnKey];
      const cellValue = parseCell(cell, columnType);
      return (
        <View style={styles.cell}>
          <Text style={styles.cellText}>{cellValue}</Text>
        </View>
      );
    });
    return <View style={styles.row}>{cells}</View>;
  };

  const { filteredData, searchString } = state;
  const headerData = [objectFields];

  return (
    <View style={[globalStyles.container]}>
      <SearchBar value={searchString} onChange={onSearchChange} placeholder="Table name" />
      <SearchBar onChange={onFilterChange} placeholder="Filter string" />
      <FlatList
        data={headerData}
        keyExtractor={headerRowKeyExtractor}
        renderItem={renderHeaderRow}
      />
      <VirtualizedList
        data={filteredData}
        getItem={(d, i) => d[i]}
        getItemCount={d => d.length}
        keyExtractor={rowKeyExtractor}
        renderItem={renderRow}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  cell: {
    flex: 1,
  },
  cellText: {
    textAlign: 'center',
  },
  row: {
    flex: 1,
    flexBasis: 0,
    flexDirection: 'row',
    flexGrow: 1,
    flexWrap: 'nowrap',
    justifyContent: 'space-between',
  },
});

RealmExplorer.propTypes = {
  database: PropTypes.instanceOf(UIDatabase).isRequired,
};

export default RealmExplorer;
<commit_msg>Replace FlatList header with ListHeaderComponent prop<commit_after>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React, { useState, useEffect, useCallback } from 'react';
import PropTypes from 'prop-types';

import { View, VirtualizedList, Text, StyleSheet } from 'react-native';
import { SearchBar } from 'react-native-ui-components';

import globalStyles from '../globalStyles';
import { UIDatabase } from '../database/index';

import { schema } from '../database/schema';

const TYPES = {
  BOOLEAN: 'boolean',
  DATE: 'date',
  NUMBER: 'number',
  STRING: 'string',
  ARRAY: 'array',
  OBJECT: 'object',
};

const REALM_TYPES = {
  BOOL: 'bool',
  DATE: 'date',
  DOUBLE: 'double',
  FLOAT: 'float',
  INT: 'int',
  LIST: 'list',
  OBJECT: 'object',
  STRING: 'string',
};

const TYPE_MAPPINGS = {
  [TYPES.BOOLEAN]: [REALM_TYPES.BOOL],
  [TYPES.DATE]: [REALM_TYPES.DATE],
  [TYPES.NUMBER]: [REALM_TYPES.INT, REALM_TYPES.FLOAT, REALM_TYPES.DOUBLE],
  [TYPES.STRING]: [REALM_TYPES.STRING],
  [TYPES.ARRAY]: [REALM_TYPES.LIST],
  [TYPES.OBJECT]: [REALM_TYPES.OBJECT],
};

const typeMapper = new Map(
  Object.entries(TYPE_MAPPINGS)
    .map(([type, realmTypes]) => realmTypes.map(realmType => [realmType, type]))
    .flat()
);

const parseType = realmType => {
  const { type } = realmType;
  if (type) return parseType(type);
  return typeMapper.get(realmType) || TYPES.OBJECT;
};

const getObjectTypes = ({ schema: objectSchemas }) =>
  objectSchemas.map(({ schema: objectSchema }) => objectSchema.name);

const getObjectFields = ({ schema: objectSchemas }) =>
  objectSchemas
    .map(({ schema: objectSchema }) => {
      const { name, properties } = objectSchema;
      const fields = Object.entries(properties)
        .map(([field, type]) => ({
          [field]: parseType(type),
        }))
        .reduce((acc, field) => ({ ...acc, ...field }), {});
      return { [name]: fields };
    })
    .reduce((acc, object) => ({ ...acc, ...object }));

const OBJECT_TYPES = getObjectTypes(schema);
const OBJECT_FIELDS = getObjectFields(schema);

const toCapitalCase = value => value.charAt(0).toUpperCase() + value.slice(1);

const parseString = value => String(value);
const parseNumber = value => String(value);
const parseObject = value => value.id;
const parseArray = value => value.length;
const parseBoolean = value => toCapitalCase(String(value));
const parseDate = value => value.toString();

const parseCell = (value, type) => {
  if (value === null || value === undefined) return 'N/A';
  switch (type) {
    case TYPES.STRING:
      return parseString(value);
    case TYPES.NUMBER:
      return parseNumber(value);
    case TYPES.OBJECT:
      return parseObject(value);
    case TYPES.ARRAY:
      return parseArray(value);
    case TYPES.BOOLEAN:
      return parseBoolean(value);
    case TYPES.DATE:
      return parseDate(value);
    default:
      return '';
  }
};

const getInitialState = database => {
  const [objectString] = OBJECT_TYPES;
  const objectData = database.objects(objectString);
  const searchString = objectString;
  const filterString = '';
  const filteredData = objectData;
  return { objectString, objectData, searchString, filterString, filteredData };
};

const getUpdatedState = (database, state) => {
  const { objectString, objectData, searchString, filterString, filteredData } = state;
  const newState = { searchString, filterString };
  const updateObject = searchString !== objectString && OBJECT_TYPES.indexOf(searchString) >= 0;
  newState.objectString = updateObject ? searchString : objectString;
  newState.objectData = updateObject ? database.objects(newState.objectString) : objectData;
  if (filterString === '') {
    newState.filteredData = newState.objectData;
  } else {
    try {
      newState.filteredData = newState.objectData.filtered(filterString);
    } catch (err) {
      newState.filteredData = updateObject ? newState.objectData : filteredData;
    }
  }

  return newState;
};

const renderHeader = objectFields => {
  const headerCells = Object.keys(objectFields).map(columnKey => (
    <View key={columnKey} style={styles.cell}>
      <Text style={styles.cellText}>{columnKey}</Text>
    </View>
  ));
  return <View style={styles.row}>{headerCells}</View>;
};

/**
 * A page for displaying objects in the local database. Includes search and filtering functionality.
 *
 * @prop   {UIDatabase}     database       App wide database.
 * @state  {string}         objectString   Current database object.
 * @state  {string}         searchString   Current search string. Used to update current object.
 * @state  {string}         filterString   Current filter string. Used to update filtered data.
 * @state  {Realm.Results}  objectData     Reference to current database object results. Used to
 *                                         roll back filter state when filter is reset.
 * @state  {Realm.Results}  filteredData   Reference to current database object results after filter
 *                                         has been applied. Displayed to the user.
 */
export const RealmExplorer = ({ database }) => {
  const [state, setState] = useState(getInitialState(database));

  const onSearchChange = searchString => {
    setState({ ...state, searchString });
  };

  const onFilterChange = filterString => {
    setState({ ...state, filterString });
  };

  useEffect(() => setState(getUpdatedState(database, state)), [
    state.searchString,
    state.filterString,
  ]);

  const objectFields = OBJECT_FIELDS[state.objectString];

  const rowKeyExtractor = ({ id }) => id;

  const renderRow = row => {
    const { item } = row;
    const cells = Object.entries(objectFields).map(([columnKey, columnType]) => {
      const cell = item[columnKey];
      const cellValue = parseCell(cell, columnType);
      return (
        <View style={styles.cell}>
          <Text style={styles.cellText}>{cellValue}</Text>
        </View>
      );
    });
    return <View style={styles.row}>{cells}</View>;
  };

  const { filteredData, searchString } = state;

  const header = useCallback(() => renderHeader(objectFields), [objectFields]);

  return (
    <View style={[globalStyles.container]}>
      <SearchBar value={searchString} onChange={onSearchChange} placeholder="Table name" />
      <SearchBar onChange={onFilterChange} placeholder="Filter string" />
      <VirtualizedList
        ListHeaderComponent={header}
        data={filteredData}
        getItem={(d, i) => d[i]}
        getItemCount={d => d.length}
        keyExtractor={rowKeyExtractor}
        renderItem={renderRow}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  cell: {
    flex: 1,
  },
  cellText: {
    textAlign: 'center',
  },
  row: {
    flex: 1,
    flexBasis: 0,
    flexDirection: 'row',
    flexGrow: 1,
    flexWrap: 'nowrap',
    justifyContent: 'space-between',
  },
});

RealmExplorer.propTypes = {
  database: PropTypes.instanceOf(UIDatabase).isRequired,
};

export default RealmExplorer;
<|endoftext|>


<commit_before>'use strict';

angular.module('sumaAnalysis')
  .directive('sumaActiveActs', function () {
    return {
      restrict: 'A',
      templateUrl: 'views/directives/activeActs.html',
      scope: {acts: '=', locs: '='},
      link: function (scope, ele, attrs, depthFilter) {
        scope.display = false;

        function setActsDisplayStatus () {
          var states = _.uniq(_.pluck(scope.acts, 'filter'));

          if (_.contains(states, 'require') || _.contains(states, 'exclude')) {
            scope.display = true;
            scope.actsActive = true;
          } else {
            if (!scope.locsActive) {
              scope.display = false;
            }
            scope.actsActive = false;

          }
        }

        function setLocsDisplayStatus () {
          var states = _.uniq(_.pluck(scope.locs, 'filter'));

          if (_.contains(states, false)) {
            scope.display = true;
            scope.locsActive = true;
          } else {
            if (!scope.actsActive) {
              scope.display = false;
            }
            scope.locsActive = false;
          }
        }

        scope.$watch('acts', setActsDisplayStatus, true);
        scope.$watch('locs', setLocsDisplayStatus, true);
      }
    };
  });
<commit_msg>clean up activeActs directive<commit_after>'use strict';

angular.module('sumaAnalysis')
  .directive('sumaActiveActs', function () {
    return {
      restrict: 'A',
      templateUrl: 'views/directives/activeActs.html',
      scope: {acts: '=', locs: '='},
      link: function (scope, ele, attrs, depthFilter) {
        scope.display = false;
        scope.actsActive = false;
        scope.locsActive = false;

        function setActsDisplayStatus () {
          var states = _.uniq(_.pluck(scope.acts, 'filter'));

          if (_.contains(states, 'require') || _.contains(states, 'exclude')) {
            scope.display = true;
            scope.actsActive = true;
          } else {
            if (!scope.locsActive) {
              scope.display = false;
            }
            scope.actsActive = false;
          }
        }

        function setLocsDisplayStatus () {
          var states = _.uniq(_.pluck(scope.locs, 'filter'));

          if (_.contains(states, false)) {
            scope.display = true;
            scope.locsActive = true;
          } else {
            if (!scope.actsActive) {
              scope.display = false;
            }
            scope.locsActive = false;
          }
        }

        scope.$watch('acts', setActsDisplayStatus, true);
        scope.$watch('locs', setLocsDisplayStatus, true);
      }
    };
  });
<|endoftext|>


<commit_before>const React = require('react-native');
const route = require('trie-route');
const sceneWrapper = require('./sceneWrapper');
const SceneManager = require('./sceneManager');

const {
  Component
} = React;

function parseScenes(children, arr, parentPath) {
  React.Children.forEach(children, (child) => {
    const { children, path, component, loadingComponent } = child.props;
    const childPath = parentPath + '/' + path;

    arr.push({
      path: childPath,
      component: sceneWrapper(loadingComponent)(component)
    });

    parseScenes(children, arr, childPath);
  });
}

class Scene extends Component {
  constructor(baseProps) {
    super(baseProps);
    this.router = route.create();

    const { initialScenePath, children, props } = baseProps;

    if (!initialScenePath) {
      throw new Error('Root Scene must have initialScenePath prop');
    }

    let scenes = [];
    parseScenes(children, scenes, '');

    this.nextOptions = {};

    this.initialScene = null;
    scenes.forEach((scene) => {
      this.router.path(scene.path, (params, queryStrings) => {
        if (!this.initialScene) {
          this.initialScene = {
            component: scene.component,
            params: params,
            queryStrings: queryStrings,
            props: props
          };
        } else {
          this.refs.sceneManager.push(this.nextOptions.side || 'right',
                                      !!this.nextOptions.withAnimation,
                                      scene.component,
                                      this.nextOptions.props || {},
                                      params,
                                      queryStrings);
          this.nextOptions = {};
        }
      });
    });

    this.router.process(initialScenePath);
  }

  //options => props, side, withAnimation
  goto(path, options={}) {
    this.nextOptions = options;
    this.router.process(path);
  }

  goback() {
    const { sceneManager } = this.refs;
    sceneManager.pop();
  }

  render() {
    if (!this.initialScene) {
      throw new Error('initialScenePath not found');
    }

    return (
      <SceneManager
        ref="sceneManager"
        initialScene={this.initialScene}/>
    );
  }
}

Scene.propTypes = {
  initialScenePath: React.PropTypes.string,
  path: React.PropTypes.string,
  component: React.PropTypes.func,
  loadingComponent: React.PropTypes.func
};

module.exports = Scene;
<commit_msg>wip of using capture mode<commit_after>const React = require('react-native');
const route = require('trie-route');
const sceneWrapper = require('./sceneWrapper');
const SceneManager = require('./sceneManager');

const {
  Component
} = React;

function parseScenes(children, arr, parentPath) {
  React.Children.forEach(children, (child) => {
    const { children, path, component, loadingComponent } = child.props;
    const childPath = parentPath + '/' + path;

    arr.push({
      path: childPath,
      component: sceneWrapper(loadingComponent)(component)
    });

    parseScenes(children, arr, childPath);
  });
}

class Scene extends Component {
  constructor(baseProps) {
    super(baseProps);
    this.router = route.create();

    const { initialScenePath, children, props } = baseProps;

    if (!initialScenePath) {
      throw new Error('Root Scene must have initialScenePath prop');
    }

    let scenes = [];
    parseScenes(children, scenes, '');

    this.nextOptions = {};

    this.initialScene = {};

    scenes.forEach((scene) => {
      this.router.path(scene.path, (params, queryStrings, context) => {

        //if this.nextOptions is null, it means that this route is a child of
        //another node.
        if (this.nextOptions) {
          //setup some internal variables
          context.side = this.nextOptions.side || 'right';
          context.withAnimation = !!this.nextOptions.withAnimation;
          context.props = this.nextOptions.props || {};
        }

        //setup component and params
        context.component = scene.component;
        context.params = params;
        context.queryStrings = queryStrings;
        context.child = {};

        //reset nextOptions
        //since the rest of scenes are going to be included as child,
        //we don't need the options any more
        this.nextOptions = null;

        //return the empty child so the next route can populate the child context
        return context.child;
      });
    });

    this.initialScene = this.router.capture(initialScenePath);
    if (!this.initialScene) {
      throw new Error(`scene with path '${initialScenePath}' not found`);
    }
  }

  _renderScenes(path) {
    const { sceneManager } = this.refs;
    const scenes = this.router.capture(path);

    if (!scenes) {
      throw new Error(`scene with path '${path}' not found`);
    }

    //push the obj which contains all the information required for SceneManager
    //to render and display the content.
    sceneManager.push(obj);
  }

  //options => props, side, withAnimation
  goto(path, options={}) {
    //set the options and call the render.
    this.nextOptions = options;
    this._renderScenes(path);
  }

  goback() {
    const { sceneManager } = this.refs;
    sceneManager.pop();
  }

  render() {
    if (!this.initialScene) {
      throw new Error('initialScenePath not found');
    }

    return (
      <SceneManager
        ref="sceneManager"
        initialScene={this.initialScene}/>
    );
  }
}

Scene.propTypes = {
  //this variable only uses for root scene, it will be ignored for any other scene
  initialScenePath: React.PropTypes.string,
  //the rest of props are inly use in child scenes and they are ignored in root scene
  path: React.PropTypes.string,
  component: React.PropTypes.func,
  loadingComponent: React.PropTypes.func
};

module.exports = Scene;
<|endoftext|>