<commit_before>
var Worker = require('./lib/worker')

// XXX should we switch to a different way of things?
module.exports = function (context, next, isTest) {
  if (isTest) {
    throw new Error('test injection not supported')
  }
  var worker = new Worker({
    pty: !context.config.disablePty,
    emitter: context.emitter,
    logger: context.logger
  })
  context.loader.initExtensions(
    context.extdir, 'worker',
    worker.buildContext(context.config, context.extdir),
    null, function (err, initialized) {
      if (err) {
        context.logger.warn('Failed to initialize extensions', err.message, err.stack)
        return next(err)
      }
      worker.attach(context.emitter)
      context.logger.log('Simple Worker ready')
      next()
    })
  context.logger.log('Simple worker things')
}
module.exports.Worker = Worker
<commit_msg>rm log<commit_after>
var Worker = require('./lib/worker')

// XXX should we switch to a different way of things?
module.exports = function (context, next, isTest) {
  if (isTest) {
    throw new Error('test injection not supported')
  }
  var worker = new Worker({
    pty: !context.config.disablePty,
    emitter: context.emitter,
    logger: context.logger
  })
  context.loader.initExtensions(
    context.extdir, 'worker',
    worker.buildContext(context.config, context.extdir),
    null, function (err, initialized) {
      if (err) {
        context.logger.warn('Failed to initialize extensions', err.message, err.stack)
        return next(err)
      }
      worker.attach(context.emitter)
      context.logger.log('Simple Worker ready')
      next()
    })
}
module.exports.Worker = Worker
<|endoftext|>


<commit_before>var localVideo;
var localStream;
var remoteVideo;
var peerConnection;
var serverConnection;
var numClients;

var peerConnectionConfig = {
    'iceServers': [
        {'urls': 'stun:stun.services.mozilla.com'},
        {'urls': 'stun:stun.l.google.com:19302'},
    ]
};

const {desktopCapturer} = require('electron');

function pageReady() {
    localVideo = document.getElementById('localVideo');
    remoteVideo = document.getElementById('remoteVideo');
    var roomNameInput = document.getElementById('room-name');
    var startButton = document.getElementById("start-button");
    numClients = document.getElementById("numClients");
    startButton.addEventListener("click", function(e) {
        joinRoom(roomNameInput.value);
        start(true);
    });
}

function joinRoom(name) {
    serverConnection = new WebSocket('ws://127.0.0.1:3434/ws?room='+name);
    serverConnection.onmessage = gotMessageFromServer;

    var constraints = {
        video: true,
        audio: true,
    };

    desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
        if (error) throw error
        for (let i = 0; i < sources.length; ++i) {
            if (sources[i].name === 'Entire screen') {
            navigator.webkitGetUserMedia({
                audio: false,
                video: {
                mandatory: {
                    chromeMediaSource: 'desktop',
                    chromeMediaSourceId: sources[i].id,
                    minWidth: 1280,
                    maxWidth: 1280,
                    minHeight: 720,
                    maxHeight: 720
                }
                }
            }, getUserMediaSuccess, errorHandler("getUserMedia"))
            return
            } else {
                console.log(sources[i].name);
            }
        }
    })
}

function getUserMediaSuccess(stream) {
    localStream = stream;
    localVideo.srcObject = stream;
}

function start(isCaller) {
    peerConnection = new RTCPeerConnection(peerConnectionConfig);
    peerConnection.onicecandidate = gotIceCandidate;
    peerConnection.onaddstream = gotRemoteStream;
    peerConnection.addStream(localStream);

    if(isCaller) {
        peerConnection.createOffer().then(createdDescription).catch(errorHandler("createOffer"));
    }
}

function gotMessageFromServer(message) {
    if(!peerConnection) start(false);

    console.log("JSON:", message.data);
    var signal = JSON.parse(message.data);

    if(signal.sdp) {
        peerConnection.setRemoteDescription(new RTCSessionDescription(signal.sdp)).then(function() {
            // Only create answers in response to offers
            if(signal.sdp.type == 'offer') {
                peerConnection.createAnswer().then(createdDescription).catch(errorHandler("createAnswer"));
            }
        }).catch(errorHandler("setRemoteDescription"));
    } else if(signal.ice) {
        peerConnection.addIceCandidate(new RTCIceCandidate(signal.ice)).catch(errorHandler("addIceCandidate"));
    } else if(signal.numClients) {
        numClients.innerHTML = signal.numClients + " people are here.";
    }
}

function gotIceCandidate(event) {
    if(event.candidate != null) {
        serverConnection.send(JSON.stringify({'ice': event.candidate}));
    }
}

function createdDescription(description) {
    console.log('got description');

    peerConnection.setLocalDescription(description).then(function() {
        serverConnection.send(JSON.stringify({'sdp': peerConnection.localDescription}));
    }).catch(errorHandler("setLocalDescription"));
}

function gotRemoteStream(event) {
    console.log('got remote stream');
    remoteVideo.srcObject = event.stream;
}

function errorHandler(from) {
    return function(error) {
        console.log(from, error);
    }
}

pageReady();<commit_msg>Remove old code II<commit_after><|endoftext|>


<commit_before>var widget = document.getElementById('widget'),
	token = null,
	url = 'index.php',
	launchPopup = function () {
			window.open(url+'?auth', 'auth', 'toolbar=0,scrollbars=1,location=1,statusbar=1,menubar=0,resizable=1,width=800,height=650,left=450,top=250');
		},
	postComment = function () {
		if(!token){
			return;
		}
		var href = encodeURIComponent(document.location.href),
			title = ' left a comment at '+href,
			text = widget.getElementsByTagName('textarea')[0].value,
			description = encodeURIComponent(text.substr(0,9)+'...'),//title will be the first 10 char from comment w/ trailing elipses
			params = 'link='+href+'&title='+title+'&description='+description+'&token='+encodeURIComponent(token),
			callback = {
				success: function(o){
					if (o.responseText){
						console.log(o.responseText);
					}
				},
				failure: function(o){}
			};
		YAHOO.util.Connect.asyncRequest('POST', url+'?submit', callback, params);
	},
	buildWidget = function () {
		var html = '';
		if(token){
			html+=''
			+'publishing updates to Yahoo!';
		}else{
			html+=''
			+''
				+''
			+'';
		}
		html+=''
			+'<form>'
				+'<textarea></textarea>
'
				+'<button onclick="postComment(); return false">Post Comment</button>'
			+'</form>';
		widget.innerHTML = html;
		widget.style.display = 'block';
	},
	loader = new YAHOO.util.YUILoader({
	    require: ["connection", "cookie"],
	    loadOptional: true,
	    onSuccess: function() {
			token = YAHOO.util.Cookie.get("yosAccessToken");
			buildWidget();
	    },
	    timeout: 100000,
	    combine: true
	});
loader.insert();

<commit_msg>now swapping button for conf message, and closing popup, after user logs in<commit_after>var widget = document.getElementById('widget'),
	token = null,
	url = 'index.php',
	launchPopup = function () {
			var popup = window.open(url+'?auth', 'auth', 'toolbar=0,scrollbars=1,location=1,statusbar=1,menubar=0,resizable=1,width=800,height=650,left=450,top=250'),
			interval = setInterval(function(){
				token = YAHOO.util.Cookie.get("yosAccessToken");
				if(token){
					clearInterval(interval);
					var authButton = widget.getElementsByTagName('a')[0],
						authConf = widget.getElementsByTagName('span')[0];
					authButton.style.display = 'none';
					authConf.style.display = 'block';
					popup.close();
				}
			}, 1000);
		},
	postComment = function () {
		if(!token){
			return;
		}
		var href = encodeURIComponent(document.location.href),
			title = ' left a comment at '+href,
			text = widget.getElementsByTagName('textarea')[0].value,
			description = encodeURIComponent(text.substr(0,9)+'...'),//title will be the first 10 char from comment w/ trailing elipses
			params = 'link='+href+'&title='+title+'&description='+description+'&token='+encodeURIComponent(token),
			callback = {
				success: function(o){
					if (o.responseText){
						console.log(o.responseText);
					}
				},
				failure: function(o){}
			};
		YAHOO.util.Connect.asyncRequest('POST', url+'?submit', callback, params);
	},
	buildWidget = function () {
		var html =''
			+'publishing updates to Yahoo!'
			+''
				+''
			+''
			+'<form>'
				+'<textarea></textarea>
'
				+'<button onclick="postComment(); return false">Post Comment</button>'
			+'</form>';
		widget.innerHTML = html;
		widget.style.display = 'block';
	},
	loader = new YAHOO.util.YUILoader({
	    require: ["connection", "cookie"],
	    loadOptional: true,
	    onSuccess: function() {
			token = YAHOO.util.Cookie.get("yosAccessToken");
			buildWidget();
	    },
	    timeout: 100000,
	    combine: true
	});
loader.insert();

<|endoftext|>


<commit_before>// @flow

import type {
  BackendBridge,
  FrontendBridge,
} from 'react-devtools-shared/src/bridge';

const env = jasmine.getEnv();
env.beforeEach(() => {
  // These files should be required (and re-reuired) before each test,
  // rather than imported at the head of the module.
  // That's because we reset modules between tests,
  // which disconnects the DevTool's cache from the current dispatcher ref.
  const Agent = require('react-devtools-shared/src/backend/agent').default;
  const {initBackend} = require('react-devtools-shared/src/backend');
  const Bridge = require('react-devtools-shared/src/bridge').default;
  const Store = require('react-devtools-shared/src/devtools/store').default;
  const {installHook} = require('react-devtools-shared/src/hook');
  const {
    getDefaultComponentFilters,
    saveComponentFilters,
  } = require('react-devtools-shared/src/utils');

  // Fake timers let us flush Bridge operations between setup and assertions.
  jest.useFakeTimers();

  const originalConsoleError = console.error;
  // $FlowFixMe
  console.error = (...args) => {
    if (args[0] === 'Warning: React DevTools encountered an error: %s') {
      // Rethrow errors from React.
      throw args[1];
    }
    originalConsoleError.apply(console, args);
  };

  // Initialize filters to a known good state.
  saveComponentFilters(getDefaultComponentFilters());
  global.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = getDefaultComponentFilters();

  installHook(global);

  const bridgeListeners = [];
  const bridge = new Bridge({
    listen(callback) {
      bridgeListeners.push(callback);
      return () => {
        const index = bridgeListeners.indexOf(callback);
        if (index >= 0) {
          bridgeListeners.splice(index, 1);
        }
      };
    },
    send(event: string, payload: any, transferable?: Array<any>) {
      bridgeListeners.forEach(callback => callback({event, payload}));
    },
  });

  const agent = new Agent(((bridge: any): BackendBridge));

  const hook = global.__REACT_DEVTOOLS_GLOBAL_HOOK__;

  initBackend(hook, agent, global);

  const store = new Store(((bridge: any): FrontendBridge));

  global.agent = agent;
  global.bridge = bridge;
  global.store = store;
});
env.afterEach(() => {
  delete global.__REACT_DEVTOOLS_GLOBAL_HOOK__;

  // It's important to reset modules between test runs;
  // Without this, ReactDOM won't re-inject itself into the new hook.
  // It's also important to reset after tests, rather than before,
  // so that we don't disconnect the ReactCurrentDispatcher ref.
  jest.resetModules();
});
<commit_msg>Suppress act/renderer warning for DevTools tests<commit_after>// @flow

import type {
  BackendBridge,
  FrontendBridge,
} from 'react-devtools-shared/src/bridge';

const env = jasmine.getEnv();
env.beforeEach(() => {
  // These files should be required (and re-reuired) before each test,
  // rather than imported at the head of the module.
  // That's because we reset modules between tests,
  // which disconnects the DevTool's cache from the current dispatcher ref.
  const Agent = require('react-devtools-shared/src/backend/agent').default;
  const {initBackend} = require('react-devtools-shared/src/backend');
  const Bridge = require('react-devtools-shared/src/bridge').default;
  const Store = require('react-devtools-shared/src/devtools/store').default;
  const {installHook} = require('react-devtools-shared/src/hook');
  const {
    getDefaultComponentFilters,
    saveComponentFilters,
  } = require('react-devtools-shared/src/utils');

  // Fake timers let us flush Bridge operations between setup and assertions.
  jest.useFakeTimers();

  const originalConsoleError = console.error;
  // $FlowFixMe
  console.error = (...args) => {
    const firstArg = args[0];
    if (firstArg === 'Warning: React DevTools encountered an error: %s') {
      // Rethrow errors from React.
      throw args[1];
    } else if (
      typeof firstArg === 'string' &&
      firstArg.startsWith("Warning: It looks like you're using the wrong act()")
    ) {
      // DevTools intentionally wraps updates with acts from both DOM and test-renderer,
      // since test updates are expected to impact both renderers.
      return;
    }
    originalConsoleError.apply(console, args);
  };

  // Initialize filters to a known good state.
  saveComponentFilters(getDefaultComponentFilters());
  global.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = getDefaultComponentFilters();

  installHook(global);

  const bridgeListeners = [];
  const bridge = new Bridge({
    listen(callback) {
      bridgeListeners.push(callback);
      return () => {
        const index = bridgeListeners.indexOf(callback);
        if (index >= 0) {
          bridgeListeners.splice(index, 1);
        }
      };
    },
    send(event: string, payload: any, transferable?: Array<any>) {
      bridgeListeners.forEach(callback => callback({event, payload}));
    },
  });

  const agent = new Agent(((bridge: any): BackendBridge));

  const hook = global.__REACT_DEVTOOLS_GLOBAL_HOOK__;

  initBackend(hook, agent, global);

  const store = new Store(((bridge: any): FrontendBridge));

  global.agent = agent;
  global.bridge = bridge;
  global.store = store;
});
env.afterEach(() => {
  delete global.__REACT_DEVTOOLS_GLOBAL_HOOK__;

  // It's important to reset modules between test runs;
  // Without this, ReactDOM won't re-inject itself into the new hook.
  // It's also important to reset after tests, rather than before,
  // so that we don't disconnect the ReactCurrentDispatcher ref.
  jest.resetModules();
});
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import icons from '../Icon/icons';
import SubmitButton from './SubmitButton';
import get from 'extensions/themeGet';

/**
 * NOTE: all paddings in button are adjusted to accomodate
 * border widths on both sides. If border widths are changed,
 * also change padding to compensate!
 *
 * Vertical paddings are also displaced to accomodate text cap and base lines.
 * Basically, 1px is added to the top, 1px subtracted from the bottom.
 */

const Button = styled.button`
  font-size: 0.8rem;
  text-decoration: none;
  font-weight: 700;
  font-family: ${get('fonts.brand')};
  text-transform: uppercase;

  border-width: ${get('thicknesses.normal')};
  border-style: solid;
  border-radius: 3em;
  border-color: ${get('colors.primary.default')};

  color: ${get('colors.text.inverted')};
  background: ${get('colors.primary.default')};

  padding: 12px 28px 10px 28px;
  display: inline-block;
  position: relative;
  overflow: hidden;
  line-height: normal;
  white-space: nowrap;

  vertical-align: middle;
  text-align: center;

  cursor: pointer;
  -webkit-user-drag: none;
  /* should get auto-prefixed */
  user-select: none;

  box-sizing: border-box;

  transition: all 0.25s ease;

  outline: none;

  &:hover:not(:disabled),
  &:focus:not(:disabled) {
    background: ${get('colors.primary.dark')};
    border-color: ${get('colors.primary.dark')};
    box-shadow: ${get('shadows.short')};
  }

  &:disabled {
    background: ${get('colors.background.disabled')};
    color: ${get('colors.text.disabled')};
    border-color: ${get('colors.background.disabled')};
    cursor: default;
    opacity: 0.5;
  }

  &::before, &::after {
    position: absolute;
    height: 100%;
    color: inherit;
    transition: all 0.3s;
    speak: none;
    font-family: ${get('fonts.icon')};
  }

  &::before {
    content: '${({ leftIcon, iconHelper }) => iconHelper(leftIcon)}';
    left: -200px;
  }

  &::after {
    content: '${({ rightIcon, iconHelper }) => iconHelper(rightIcon)}';
    right: -200px;
  }

  &:hover:not(:disabled)::before {
    left: 10px;
  }

  &:hover:not(:disabled)::after {
    right: 10px;
  }
`;

Button.propTypes = {
  /**
   * An icon name for an icon to pop in from the left side of the button on hover.
   */
  leftIcon: PropTypes.string,
  /**
   * An icon name for an icon to pop in from the right side of the button on hover.
   */
  rightIcon: PropTypes.string,
  /**
   * Use this to override the icon provider function (advanced). An icon provider function takes an icon name and
   * provides a unicode character to render.
   */
  iconHelper: PropTypes.func,
  /**
   * A class name to add to the button element.
   */
  className: PropTypes.string,
  /**
   * An id to add to the button element.
   */
  id: PropTypes.string,
};

Button.defaultProps = {
  leftIcon: null,
  rightIcon: null,
  iconHelper: icons,
  className: null,
  id: null,
};

Button.Submit = SubmitButton;

Button.Secondary = styled(Button)`
  color: ${get('colors.primary.dark')};
  border-color: ${get('colors.primary.dark')};
  background: transparent;

  &:hover:not(:disabled),
  &:focus:not(:disabled) {
    color: ${get('colors.text.inverted')};
    background: ${get('colors.primary.dark')};
    border-color: ${get('colors.primary.dark')};
  }
`;

Button.Small = styled(Button)`
  padding: 10px 28px 9px 28px;
  font-size: 0.6rem;
`;

Button.Large = styled(Button)`
  padding: 14px 38px 12px 38px;
  font-size: 0.9rem;
`;

Button.Danger = styled(Button)`
  border-color: ${get('colors.negative.default')};
  background: ${get('colors.negative.default')};

  &:hover:not(:disabled),
  &:focus:not(:disabled) {
    background: ${get('colors.negative.dark')};
    border-color: ${get('colors.negative.dark')};
  }
`;

/**
 * @component
 */
export default Button;
<commit_msg>UI-206 change secondary button border width<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import icons from '../Icon/icons';
import SubmitButton from './SubmitButton';
import get from 'extensions/themeGet';

/**
 * NOTE: all paddings in button are adjusted to accomodate
 * border widths on both sides. If border widths are changed,
 * also change padding to compensate!
 *
 * Vertical paddings are also displaced to accomodate text cap and base lines.
 * Basically, 1px is added to the top, 1px subtracted from the bottom.
 */

const Button = styled.button`
  font-size: 0.8rem;
  text-decoration: none;
  font-weight: 700;
  font-family: ${get('fonts.brand')};
  text-transform: uppercase;

  border-width: ${get('thicknesses.normal')};
  border-style: solid;
  border-radius: 3em;
  border-color: ${get('colors.primary.default')};

  color: ${get('colors.text.inverted')};
  background: ${get('colors.primary.default')};

  padding: 12px 28px 10px 28px;
  display: inline-block;
  position: relative;
  overflow: hidden;
  line-height: normal;
  white-space: nowrap;

  vertical-align: middle;
  text-align: center;

  cursor: pointer;
  -webkit-user-drag: none;
  /* should get auto-prefixed */
  user-select: none;

  box-sizing: border-box;

  transition: all 0.25s ease;

  outline: none;

  &:hover:not(:disabled),
  &:focus:not(:disabled) {
    background: ${get('colors.primary.dark')};
    border-color: ${get('colors.primary.dark')};
    box-shadow: ${get('shadows.short')};
  }

  &:disabled {
    background: ${get('colors.background.disabled')};
    color: ${get('colors.text.disabled')};
    border-color: ${get('colors.background.disabled')};
    cursor: default;
    opacity: 0.5;
  }

  &::before, &::after {
    position: absolute;
    height: 100%;
    color: inherit;
    transition: all 0.3s;
    speak: none;
    font-family: ${get('fonts.icon')};
  }

  &::before {
    content: '${({ leftIcon, iconHelper }) => iconHelper(leftIcon)}';
    left: -200px;
  }

  &::after {
    content: '${({ rightIcon, iconHelper }) => iconHelper(rightIcon)}';
    right: -200px;
  }

  &:hover:not(:disabled)::before {
    left: 10px;
  }

  &:hover:not(:disabled)::after {
    right: 10px;
  }
`;

Button.propTypes = {
  /**
   * An icon name for an icon to pop in from the left side of the button on hover.
   */
  leftIcon: PropTypes.string,
  /**
   * An icon name for an icon to pop in from the right side of the button on hover.
   */
  rightIcon: PropTypes.string,
  /**
   * Use this to override the icon provider function (advanced). An icon provider function takes an icon name and
   * provides a unicode character to render.
   */
  iconHelper: PropTypes.func,
  /**
   * A class name to add to the button element.
   */
  className: PropTypes.string,
  /**
   * An id to add to the button element.
   */
  id: PropTypes.string,
};

Button.defaultProps = {
  leftIcon: null,
  rightIcon: null,
  iconHelper: icons,
  className: null,
  id: null,
};

Button.Submit = SubmitButton;

Button.Secondary = styled(Button)`
  color: ${get('colors.primary.dark')};
  border-color: ${get('colors.primary.dark')};
  background: transparent;
  border-width: ${get('thicknesses.wide')};

  &:hover:not(:disabled),
  &:focus:not(:disabled) {
    color: ${get('colors.text.inverted')};
    background: ${get('colors.primary.dark')};
    border-color: ${get('colors.primary.dark')};
  }
`;

Button.Small = styled(Button)`
  padding: 10px 28px 9px 28px;
  font-size: 0.6rem;
`;

Button.Large = styled(Button)`
  padding: 14px 38px 12px 38px;
  font-size: 0.9rem;
`;

Button.Danger = styled(Button)`
  border-color: ${get('colors.negative.default')};
  background: ${get('colors.negative.default')};

  &:hover:not(:disabled),
  &:focus:not(:disabled) {
    background: ${get('colors.negative.dark')};
    border-color: ${get('colors.negative.dark')};
  }
`;

/**
 * @component
 */
export default Button;
<|endoftext|>


<commit_before>/**
 *
 * Logout
 *
 */

/* eslint-disable */
import React, { useState } from 'react';
import { FormattedMessage } from 'react-intl';
import { withRouter } from 'react-router-dom';
import { get } from 'lodash';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  ButtonDropdown,
  DropdownItem,
  DropdownMenu,
  DropdownToggle,
} from 'reactstrap';
import { auth } from 'strapi-helper-plugin';
import Wrapper from './components';

const Logout = ({ history: { push } }) => {
  const [isOpen, setIsOpen] = useState(false);
  const toggle = () => setIsOpen(prev => !prev);
  const handleGoTo = () => {
    const id = get(auth.getUserInfo(), 'id');

    push({
      pathname: `/plugins/content-manager/strapi::administrator/${id}`,
      search:
        '?redirectUrl=/plugins/content-manager/strapi::administrator/&_page=0&_limit=0&_sort=id',
    });
  };
  const handleGoToAdministrator = () => {
    push({
      pathname: '/plugins/content-manager/strapi::administrator',
    });
  };
  const handleLogout = () => {
    auth.clearAppStorage();
    push('/auth/login');
  };

  return (
    <Wrapper>
      <ButtonDropdown isOpen={isOpen} toggle={toggle}>
        <DropdownToggle>
          {get(auth.getUserInfo(), 'username')}
          <FontAwesomeIcon icon="caret-down" />
        </DropdownToggle>
        <DropdownMenu className="dropDownContent">
          <DropdownItem onClick={handleGoTo} className="item">
            <FormattedMessage id="app.components.Logout.profile" />
          </DropdownItem>
          <DropdownItem onClick={handleGoToAdministrator} className="item">
            <FormattedMessage id="app.components.Logout.admin" />
          </DropdownItem>
          <DropdownItem onClick={handleLogout}>
            <FormattedMessage id="app.components.Logout.logout" />
            <FontAwesomeIcon icon="sign-out-alt" />
          </DropdownItem>
        </DropdownMenu>
      </ButtonDropdown>
    </Wrapper>
  );
};

export default withRouter(Logout);
<commit_msg>back button url fix<commit_after>/**
 *
 * Logout
 *
 */

/* eslint-disable */
import React, { useState } from 'react';
import { FormattedMessage } from 'react-intl';
import { withRouter } from 'react-router-dom';
import { get } from 'lodash';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  ButtonDropdown,
  DropdownItem,
  DropdownMenu,
  DropdownToggle,
} from 'reactstrap';
import { auth } from 'strapi-helper-plugin';
import Wrapper from './components';

const Logout = ({ history: { push } }) => {
  const [isOpen, setIsOpen] = useState(false);
  const toggle = () => setIsOpen(prev => !prev);
  const handleGoTo = () => {
    const id = get(auth.getUserInfo(), 'id');

    push({
      pathname: `/plugins/content-manager/strapi::administrator/${id}`,
      search: '?redirectUrl=/plugins/content-manager/strapi::administrator',
    });
  };
  const handleGoToAdministrator = () => {
    push({
      pathname: '/plugins/content-manager/strapi::administrator',
    });
  };
  const handleLogout = () => {
    auth.clearAppStorage();
    push('/auth/login');
  };

  return (
    <Wrapper>
      <ButtonDropdown isOpen={isOpen} toggle={toggle}>
        <DropdownToggle>
          {get(auth.getUserInfo(), 'username')}
          <FontAwesomeIcon icon="caret-down" />
        </DropdownToggle>
        <DropdownMenu className="dropDownContent">
          <DropdownItem onClick={handleGoTo} className="item">
            <FormattedMessage id="app.components.Logout.profile" />
          </DropdownItem>
          <DropdownItem onClick={handleGoToAdministrator} className="item">
            <FormattedMessage id="app.components.Logout.admin" />
          </DropdownItem>
          <DropdownItem onClick={handleLogout}>
            <FormattedMessage id="app.components.Logout.logout" />
            <FontAwesomeIcon icon="sign-out-alt" />
          </DropdownItem>
        </DropdownMenu>
      </ButtonDropdown>
    </Wrapper>
  );
};

export default withRouter(Logout);
<|endoftext|>


<commit_before>/**
 * AnchorJS - v4.1.0 - 2017-09-20
 * https://github.com/bryanbraun/anchorjs
 * Copyright (c) 2017 Bryan Braun; Licensed MIT
 */
!function(A,e){"use strict";"function"==typeof define&&define.amd?define([],e):"object"==typeof module&&module.exports?module.exports=e():(A.AnchorJS=e(),A.anchors=new A.AnchorJS)}(this,function(){"use strict";return function(A){function e(A){A.icon=A.hasOwnProperty("icon")?A.icon:"",A.visible=A.hasOwnProperty("visible")?A.visible:"hover",A.placement=A.hasOwnProperty("placement")?A.placement:"right",A.ariaLabel=A.hasOwnProperty("ariaLabel")?A.ariaLabel:"Anchor",A.class=A.hasOwnProperty("class")?A.class:"",A.truncate=A.hasOwnProperty("truncate")?Math.floor(A.truncate):64}function t(A){var e;if("string"==typeof A||A instanceof String)e=[].slice.call(document.querySelectorAll(A));else{if(!(Array.isArray(A)||A instanceof NodeList))throw new Error("The selector provided to AnchorJS was invalid.");e=[].slice.call(A)}return e}function i(){if(null===document.head.querySelector("style.anchorjs")){var A,e=document.createElement("style");e.className="anchorjs",e.appendChild(document.createTextNode("")),void 0===(A=document.head.querySelector('[rel="stylesheet"], style'))?document.head.appendChild(e):document.head.insertBefore(e,A),e.sheet.insertRule(" .anchorjs-link {   opacity: 0;   text-decoration: none;   -webkit-font-smoothing: antialiased;   -moz-osx-font-smoothing: grayscale; }",e.sheet.cssRules.length),e.sheet.insertRule(" *:hover > .anchorjs-link, .anchorjs-link:focus  {   opacity: 1; }",e.sheet.cssRules.length),e.sheet.insertRule(" [data-anchorjs-icon]::after {   content: attr(data-anchorjs-icon); }",e.sheet.cssRules.length),e.sheet.insertRule(' @font-face {   font-family: "anchorjs-icons";   src: url(data:n/a;base64,AAEAAAALAIAAAwAwT1MvMg8yG2cAAAE4AAAAYGNtYXDp3gC3AAABpAAAAExnYXNwAAAAEAAAA9wAAAAIZ2x5ZlQCcfwAAAH4AAABCGhlYWQHFvHyAAAAvAAAADZoaGVhBnACFwAAAPQAAAAkaG10eASAADEAAAGYAAAADGxvY2EACACEAAAB8AAAAAhtYXhwAAYAVwAAARgAAAAgbmFtZQGOH9cAAAMAAAAAunBvc3QAAwAAAAADvAAAACAAAQAAAAEAAHzE2p9fDzz1AAkEAAAAAADRecUWAAAAANQA6R8AAAAAAoACwAAAAAgAAgAAAAAAAAABAAADwP/AAAACgAAA/9MCrQABAAAAAAAAAAAAAAAAAAAAAwABAAAAAwBVAAIAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAMCQAGQAAUAAAKZAswAAACPApkCzAAAAesAMwEJAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAAAAAQAAg//0DwP/AAEADwABAAAAAAQAAAAAAAAAAAAAAIAAAAAAAAAIAAAACgAAxAAAAAwAAAAMAAAAcAAEAAwAAABwAAwABAAAAHAAEADAAAAAIAAgAAgAAACDpy//9//8AAAAg6cv//f///+EWNwADAAEAAAAAAAAAAAAAAAAACACEAAEAAAAAAAAAAAAAAAAxAAACAAQARAKAAsAAKwBUAAABIiYnJjQ3NzY2MzIWFxYUBwcGIicmNDc3NjQnJiYjIgYHBwYUFxYUBwYGIwciJicmNDc3NjIXFhQHBwYUFxYWMzI2Nzc2NCcmNDc2MhcWFAcHBgYjARQGDAUtLXoWOR8fORYtLTgKGwoKCjgaGg0gEhIgDXoaGgkJBQwHdR85Fi0tOAobCgoKOBoaDSASEiANehoaCQkKGwotLXoWOR8BMwUFLYEuehYXFxYugC44CQkKGwo4GkoaDQ0NDXoaShoKGwoFBe8XFi6ALjgJCQobCjgaShoNDQ0NehpKGgobCgoKLYEuehYXAAAADACWAAEAAAAAAAEACAAAAAEAAAAAAAIAAwAIAAEAAAAAAAMACAAAAAEAAAAAAAQACAAAAAEAAAAAAAUAAQALAAEAAAAAAAYACAAAAAMAAQQJAAEAEAAMAAMAAQQJAAIABgAcAAMAAQQJAAMAEAAMAAMAAQQJAAQAEAAMAAMAAQQJAAUAAgAiAAMAAQQJAAYAEAAMYW5jaG9yanM0MDBAAGEAbgBjAGgAbwByAGoAcwA0ADAAMABAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAH//wAP) format("truetype"); }',e.sheet.cssRules.length)}}this.options=A||{},this.elements=[],e(this.options),this.isTouchDevice=function(){return!!("ontouchstart"in window||window.DocumentTouch&&document instanceof DocumentTouch)},this.add=function(A){var n,o,s,a,r,c,h,l,u,d,f,p=[];if(e(this.options),"touch"===(f=this.options.visible)&&(f=this.isTouchDevice()?"always":"hover"),A||(A="h2, h3, h4, h5, h6"),0===(n=t(A)).length)return this;for(i(),o=document.querySelectorAll("[id]"),s=[].map.call(o,function(A){return A.id}),r=0;r<n.length;r++)if(this.hasAnchorJSLink(n[r]))p.push(r);else{if(n[r].hasAttribute("id"))a=n[r].getAttribute("id");else if(n[r].hasAttribute("data-anchor-id"))a=n[r].getAttribute("data-anchor-id");else{u=l=this.urlify(n[r].textContent),h=0;do{void 0!==c&&(u=l+"-"+h),c=s.indexOf(u),h+=1}while(-1!==c);c=void 0,s.push(u),n[r].setAttribute("id",u),a=u}a.replace(/-/g," "),(d=document.createElement("a")).className="anchorjs-link "+this.options.class,d.href="#"+a,d.setAttribute("aria-label",this.options.ariaLabel),d.setAttribute("data-anchorjs-icon",this.options.icon),"always"===f&&(d.style.opacity="1"),""===this.options.icon&&(d.style.font="1em/1 anchorjs-icons","left"===this.options.placement&&(d.style.lineHeight="inherit")),"left"===this.options.placement?(d.style.position="absolute",d.style.marginLeft="-1em",d.style.paddingRight="0.5em",n[r].insertBefore(d,n[r].firstChild)):(d.style.paddingLeft="0.375em",n[r].appendChild(d))}for(r=0;r<p.length;r++)n.splice(p[r]-r,1);return this.elements=this.elements.concat(n),this},this.remove=function(A){for(var e,i,n=t(A),o=0;o<n.length;o++)(i=n[o].querySelector(".anchorjs-link"))&&(-1!==(e=this.elements.indexOf(n[o]))&&this.elements.splice(e,1),n[o].removeChild(i));return this},this.removeAll=function(){this.remove(this.elements)},this.urlify=function(A){var t=/[& +$,:;=?@"#{}|^~[`%!'<>\]\.\/\(\)\*\\]/g;return this.options.truncate||e(this.options),A.trim().replace(/\'/gi,"").replace(t,"-").replace(/-{2,}/g,"-").substring(0,this.options.truncate).replace(/^-+|-+$/gm,"").toLowerCase()},this.hasAnchorJSLink=function(A){var e=A.firstChild&&(" "+A.firstChild.className+" ").indexOf(" anchorjs-link ")>-1,t=A.lastChild&&(" "+A.lastChild.className+" ").indexOf(" anchorjs-link ")>-1;return e||t||!1}}});<commit_msg>Update anchor.min.js to v4.1.1.<commit_after>/**
 * AnchorJS - v4.1.1 - 2018-07-01
 * https://github.com/bryanbraun/anchorjs
 * Copyright (c) 2018 Bryan Braun; Licensed MIT
 */
!function(A,e){"use strict";"function"==typeof define&&define.amd?define([],e):"object"==typeof module&&module.exports?module.exports=e():(A.AnchorJS=e(),A.anchors=new A.AnchorJS)}(this,function(){"use strict";return function(A){function d(A){A.icon=A.hasOwnProperty("icon")?A.icon:"",A.visible=A.hasOwnProperty("visible")?A.visible:"hover",A.placement=A.hasOwnProperty("placement")?A.placement:"right",A.ariaLabel=A.hasOwnProperty("ariaLabel")?A.ariaLabel:"Anchor",A.class=A.hasOwnProperty("class")?A.class:"",A.truncate=A.hasOwnProperty("truncate")?Math.floor(A.truncate):64}function f(A){var e;if("string"==typeof A||A instanceof String)e=[].slice.call(document.querySelectorAll(A));else{if(!(Array.isArray(A)||A instanceof NodeList))throw new Error("The selector provided to AnchorJS was invalid.");e=[].slice.call(A)}return e}this.options=A||{},this.elements=[],d(this.options),this.isTouchDevice=function(){return!!("ontouchstart"in window||window.DocumentTouch&&document instanceof DocumentTouch)},this.add=function(A){var e,t,i,n,o,s,r,a,c,h,l,u=[];if(d(this.options),"touch"===(l=this.options.visible)&&(l=this.isTouchDevice()?"always":"hover"),A||(A="h2, h3, h4, h5, h6"),0===(e=f(A)).length)return this;for(function(){if(null===document.head.querySelector("style.anchorjs")){var A,e=document.createElement("style");e.className="anchorjs",e.appendChild(document.createTextNode("")),void 0===(A=document.head.querySelector('[rel="stylesheet"], style'))?document.head.appendChild(e):document.head.insertBefore(e,A),e.sheet.insertRule(" .anchorjs-link {   opacity: 0;   text-decoration: none;   -webkit-font-smoothing: antialiased;   -moz-osx-font-smoothing: grayscale; }",e.sheet.cssRules.length),e.sheet.insertRule(" *:hover > .anchorjs-link, .anchorjs-link:focus  {   opacity: 1; }",e.sheet.cssRules.length),e.sheet.insertRule(" [data-anchorjs-icon]::after {   content: attr(data-anchorjs-icon); }",e.sheet.cssRules.length),e.sheet.insertRule(' @font-face {   font-family: "anchorjs-icons";   src: url(data:n/a;base64,AAEAAAALAIAAAwAwT1MvMg8yG2cAAAE4AAAAYGNtYXDp3gC3AAABpAAAAExnYXNwAAAAEAAAA9wAAAAIZ2x5ZlQCcfwAAAH4AAABCGhlYWQHFvHyAAAAvAAAADZoaGVhBnACFwAAAPQAAAAkaG10eASAADEAAAGYAAAADGxvY2EACACEAAAB8AAAAAhtYXhwAAYAVwAAARgAAAAgbmFtZQGOH9cAAAMAAAAAunBvc3QAAwAAAAADvAAAACAAAQAAAAEAAHzE2p9fDzz1AAkEAAAAAADRecUWAAAAANQA6R8AAAAAAoACwAAAAAgAAgAAAAAAAAABAAADwP/AAAACgAAA/9MCrQABAAAAAAAAAAAAAAAAAAAAAwABAAAAAwBVAAIAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAMCQAGQAAUAAAKZAswAAACPApkCzAAAAesAMwEJAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAAAAAQAAg//0DwP/AAEADwABAAAAAAQAAAAAAAAAAAAAAIAAAAAAAAAIAAAACgAAxAAAAAwAAAAMAAAAcAAEAAwAAABwAAwABAAAAHAAEADAAAAAIAAgAAgAAACDpy//9//8AAAAg6cv//f///+EWNwADAAEAAAAAAAAAAAAAAAAACACEAAEAAAAAAAAAAAAAAAAxAAACAAQARAKAAsAAKwBUAAABIiYnJjQ3NzY2MzIWFxYUBwcGIicmNDc3NjQnJiYjIgYHBwYUFxYUBwYGIwciJicmNDc3NjIXFhQHBwYUFxYWMzI2Nzc2NCcmNDc2MhcWFAcHBgYjARQGDAUtLXoWOR8fORYtLTgKGwoKCjgaGg0gEhIgDXoaGgkJBQwHdR85Fi0tOAobCgoKOBoaDSASEiANehoaCQkKGwotLXoWOR8BMwUFLYEuehYXFxYugC44CQkKGwo4GkoaDQ0NDXoaShoKGwoFBe8XFi6ALjgJCQobCjgaShoNDQ0NehpKGgobCgoKLYEuehYXAAAADACWAAEAAAAAAAEACAAAAAEAAAAAAAIAAwAIAAEAAAAAAAMACAAAAAEAAAAAAAQACAAAAAEAAAAAAAUAAQALAAEAAAAAAAYACAAAAAMAAQQJAAEAEAAMAAMAAQQJAAIABgAcAAMAAQQJAAMAEAAMAAMAAQQJAAQAEAAMAAMAAQQJAAUAAgAiAAMAAQQJAAYAEAAMYW5jaG9yanM0MDBAAGEAbgBjAGgAbwByAGoAcwA0ADAAMABAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAH//wAP) format("truetype"); }',e.sheet.cssRules.length)}}(),t=document.querySelectorAll("[id]"),i=[].map.call(t,function(A){return A.id}),o=0;o<e.length;o++)if(this.hasAnchorJSLink(e[o]))u.push(o);else{if(e[o].hasAttribute("id"))n=e[o].getAttribute("id");else if(e[o].hasAttribute("data-anchor-id"))n=e[o].getAttribute("data-anchor-id");else{for(c=a=this.urlify(e[o].textContent),r=0;void 0!==s&&(c=a+"-"+r),r+=1,-1!==(s=i.indexOf(c)););s=void 0,i.push(c),e[o].setAttribute("id",c),n=c}n.replace(/-/g," "),(h=document.createElement("a")).className="anchorjs-link "+this.options.class,h.href="#"+n,h.setAttribute("aria-label",this.options.ariaLabel),h.setAttribute("data-anchorjs-icon",this.options.icon),"always"===l&&(h.style.opacity="1"),""===this.options.icon&&(h.style.font="1em/1 anchorjs-icons","left"===this.options.placement&&(h.style.lineHeight="inherit")),"left"===this.options.placement?(h.style.position="absolute",h.style.marginLeft="-1em",h.style.paddingRight="0.5em",e[o].insertBefore(h,e[o].firstChild)):(h.style.paddingLeft="0.375em",e[o].appendChild(h))}for(o=0;o<u.length;o++)e.splice(u[o]-o,1);return this.elements=this.elements.concat(e),this},this.remove=function(A){for(var e,t,i=f(A),n=0;n<i.length;n++)(t=i[n].querySelector(".anchorjs-link"))&&(-1!==(e=this.elements.indexOf(i[n]))&&this.elements.splice(e,1),i[n].removeChild(t));return this},this.removeAll=function(){this.remove(this.elements)},this.urlify=function(A){return this.options.truncate||d(this.options),A.trim().replace(/\'/gi,"").replace(/[& +$,:;=?@"#{}|^~[`%!'<>\]\.\/\(\)\*\\\n\t\b\v]/g,"-").replace(/-{2,}/g,"-").substring(0,this.options.truncate).replace(/^-+|-+$/gm,"").toLowerCase()},this.hasAnchorJSLink=function(A){var e=A.firstChild&&-1<(" "+A.firstChild.className+" ").indexOf(" anchorjs-link "),t=A.lastChild&&-1<(" "+A.lastChild.className+" ").indexOf(" anchorjs-link ");return e||t||!1}}});<|endoftext|>


<commit_before>/*********************************************
This ambient module example reports sound and
light levels to the console, and console.logs
whenever a specified light or sound level
trigger is met.
*********************************************/

var tessel = require('tessel');
var ambientPort = tessel.port('a');

// Import the ambient library and use designated port
require('../').use(ambientPort, function(err, ambient) {

  // If there was a problem
  if (err) {
    // Report it and return
    return console.log("Error initializing:", err);
  }

 // Get a stream of light data
  ambient.on('light', function(data) {
    console.log("Got some  light: ", data);
  });

  // Get a stream of sound level data
  ambient.on('sound', function(data) {
    console.log("Got some  sound: ", data);
  });

  // Set trigger levels
  // The trigger value is a float between zero to 1
  ambient.setLightTrigger(0.15);

  ambient.on('light-trigger', function(data) {
    console.log("Our light trigger was hit:", data);

    // Clear the trigger so it stops firing
    ambient.clearLightTrigger();
  });

  // Set a sound level trigger
  // The trigger is a float between 0 and 1
  // Basically any sound will trip this trigger
  ambient.setSoundTrigger(0.001);

  ambient.on('sound-trigger', function(data) {

    console.log("Something happened with sound: ", data);

    // Clear it
    ambient.clearSoundTrigger();
  });
});

setInterval(function() {}, 200);

// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
<commit_msg>whoops couple of changes in ambient.js<commit_after>/*********************************************
This ambient module example reports sound and
light levels to the console, and console.logs
whenever a specified light or sound level
trigger is met.
*********************************************/

// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/

var tessel = require('tessel');
var ambientPort = tessel.port('a');

// Import the ambient library and use designated port
require('../').use(ambientPort, function(err, ambient) {

  // If there was a problem
  if (err) {
    // Report it and return
    return console.log("Error initializing:", err);
  }

 // Get a stream of light data
  ambient.on('light', function(data) {
    console.log("Got some  light: ", data);
  });

  // Get a stream of sound level data
  ambient.on('sound', function(data) {
    console.log("Got some  sound: ", data);
  });

  // Set trigger levels
  // The trigger value is a float between zero to 1
  ambient.setLightTrigger(0.15);

  ambient.on('light-trigger', function(data) {
    console.log("Our light trigger was hit:", data);

    // Clear the trigger so it stops firing
    ambient.clearLightTrigger();
  });

  // Set a sound level trigger
  // The trigger is a float between 0 and 1
  // Basically any sound will trip this trigger
  ambient.setSoundTrigger(0.001);

  ambient.on('sound-trigger', function(data) {

    console.log("Something happened with sound: ", data);

    // Clear it
    ambient.clearSoundTrigger();
  });
});

setInterval(function() {}, 200);
<|endoftext|>


<commit_before>import Color from './color';

const NAME = Symbol.for('CIE L*a*b*');
const KEYS = Object.freeze({
  L: Symbol.for('l'),
  A: Symbol.for('a'),
  B: Symbol.for('b')
});

export default class Lab extends Color {
  constructor(l, a, b) {
    super(NAME, [[KEYS.L, l], [KEYS.A, a], [KEYS.B, b]]);
  }
}
<commit_msg>Added a method that clones an instance of Lab<commit_after>import Color from './color';

const NAME = Symbol.for('CIE L*a*b*');
const KEYS = Object.freeze({
  L: Symbol.for('l'),
  A: Symbol.for('a'),
  B: Symbol.for('b')
});

export default class Lab extends Color {
  constructor(l, a, b) {
    super(NAME, [[KEYS.L, l], [KEYS.A, a], [KEYS.B, b]]);
  }

  clone() {
    return new Lab(NAME, ...this.values());
  }
}
<|endoftext|>


<commit_before>/*
 Copyright 2019 Carmilla Mina Jankovic

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

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

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

const BaseDialog = require('./BaseDialog');

const elementCreator = require('../../../ElementCreator');
const labelHandler = require('../../../labels/LabelHandler');
const userComposer = require('../../../data/composers/UserComposer');
const positionComposer = require('../../../data/composers/PositionComposer');
const eventCentral = require('../../../EventCentral');
const viewSwitcher = require('../../../ViewSwitcher');

const ids = {
  PICTURE: 'picture',
};

class UserSelfDialog extends BaseDialog {
  constructor({
    classes = [],
    elementId = `uDialog-${Date.now()}`,
  }) {
    const user = userComposer.getCurrentUser();
    const {
      image,
      partOfTeams,
      fullName,
      username,
      objectId: userId,
    } = user;
    const userPosition = positionComposer.getPosition({ positionId: user.objectId });

    const inputs = [
      elementCreator.createImageInput({
        elementId: ids.PICTURE,
        inputName: 'picture',
        appendPreview: true,
        previewId: 'imagePreview-userSelf',
      }),
    ];
    const lowerButtons = [
      elementCreator.createButton({
        text: labelHandler.getLabel({ baseObject: 'BaseDialog', label: 'cancel' }),
        clickFuncs: {
          leftFunc: () => {
            this.removeFromView();
          },
        },
      }),
      // elementCreator.createButton({
      //   text: labelHandler.getLabel({ baseObject: 'UserSelfDialog', label: 'rename' }),
      //   clickFuncs: {
      //     leftFunc: () => {
      //       const renameDialog = new BaseDialog({
      //         inputs: [
      //           elementCreator.createInput({
      //             elementId: 'username',
      //             inputName: 'username',
      //             type: 'text',
      //             isRequired: true,
      //             maxLength: 10,
      //             placeholder: labelHandler.getLabel({ baseObject: 'LoginDialog', label: 'username' }),
      //           }),
      //         ],
      //         lowerButtons: [
      //           elementCreator.createButton({
      //             text: labelHandler.getLabel({ baseObject: 'BaseDialog', label: 'cancel' }),
      //             clickFuncs: {
      //               leftFunc: () => { renameDialog.removeFromView(); },
      //             },
      //           }),
      //           elementCreator.createButton({
      //             text: labelHandler.getLabel({ baseObject: 'BaseDialog', label: 'update' }),
      //             clickFuncs: {
      //               leftFunc: () => {
      //                 if (this.hasEmptyRequiredInputs()) {
      //                   return;
      //                 }
      //
      //                 userComposer.updateUsername({
      //                   userId,
      //                   username: renameDialog.getInputValue('username'),
      //                   callback: ({ error: updateError }) => {
      //                     if (updateError) {
      //                       console.log('Failed to update username');
      //
      //                       return;
      //                     }
      //
      //                     const parentElement = renameDialog.getParentElement();
      //
      //                     renameDialog.removeFromView();
      //                     this.addToView({ element: parentElement });
      //                   },
      //                 });
      //               },
      //             },
      //           }),
      //         ],
      //       });
      //
      //       renameDialog.addToView({ element: this.getParentElement() });
      //       this.removeFromView();
      //     },
      //   },
      // }),
      elementCreator.createButton({
        text: labelHandler.getLabel({ baseObject: 'BaseDialog', label: 'update' }),
        clickFuncs: {
          leftFunc: () => {
            if (this.hasEmptyRequiredInputs()) {
              return;
            }

            const params = {
              userId,
              callback: ({ error }) => {
                if (error) {
                  console.log(error);

                  return;
                }

                this.removeFromView();
              },
            };
            const imagePreview = document.getElementById('imagePreview-userSelf');

            if (imagePreview.getAttribute('src')) {
              params.image = {
                source: imagePreview.getAttribute('src'),
                imageName: imagePreview.getAttribute('name'),
                width: imagePreview.naturalWidth,
                height: imagePreview.naturalHeight,
              };
            }

            console.log('update user ', params);

            userComposer.updateUser(params);
          },
        },
      }),
    ];

    if (userPosition) {
      lowerButtons.push(elementCreator.createButton({
        text: labelHandler.getLabel({ baseObject: 'UserDialog', label: 'trackPosition' }),
        clickFuncs: {
          leftFunc: () => {
            viewSwitcher.switchViewByType({ type: viewSwitcher.ViewTypes.WORLDMAP });

            eventCentral.emitEvent({
              event: eventCentral.Events.FOCUS_MAPPOSITION,
              params: { position: userPosition },
            });

            this.removeFromView();
          },
        },
      }));
    }

    const upperText = [
      `${labelHandler.getLabel({ baseObject: 'UserDialog', label: 'userInfo' })}`,
      '',
    ];

    if (fullName) {
      upperText.push(fullName);
    }

    upperText.push(`${labelHandler.getLabel({ baseObject: 'UserDialog', label: 'username' })}: ${username}`);

    if (partOfTeams && partOfTeams.length > 0) {
      upperText.push(`${labelHandler.getLabel({ baseObject: 'UserDialog', label: 'partOfTeam' })}: ${partOfTeams}`);
    }

    if (userPosition && userPosition.coordinatesHistory && userPosition.coordinatesHistory[0]) {
      const positionLabel = `(${userPosition.lastUpdated}): Lat ${userPosition.coordinatesHistory[0].latitude} Long ${userPosition.coordinatesHistory[0].longitude}`;

      upperText.push(`${labelHandler.getLabel({ baseObject: 'UserDialog', label: 'position' })}: ${positionLabel}`);
    }

    const images = [];

    if (image) {
      images.push(elementCreator.createPicture({
        picture: image,
      }));
    }
    super({
      elementId,
      lowerButtons,
      upperText,
      images,
      inputs,
      classes: classes.concat(['userSelfDialog']),
    });
  }
}

module.exports = UserSelfDialog;
<commit_msg>Set text on the profile image button<commit_after>/*
 Copyright 2019 Carmilla Mina Jankovic

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

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

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

const BaseDialog = require('./BaseDialog');

const elementCreator = require('../../../ElementCreator');
const labelHandler = require('../../../labels/LabelHandler');
const userComposer = require('../../../data/composers/UserComposer');
const positionComposer = require('../../../data/composers/PositionComposer');
const eventCentral = require('../../../EventCentral');
const viewSwitcher = require('../../../ViewSwitcher');

const ids = {
  PICTURE: 'picture',
};

class UserSelfDialog extends BaseDialog {
  constructor({
    classes = [],
    elementId = `uDialog-${Date.now()}`,
  }) {
    const user = userComposer.getCurrentUser();
    const {
      image,
      partOfTeams,
      fullName,
      username,
      objectId: userId,
    } = user;
    const userPosition = positionComposer.getPosition({ positionId: user.objectId });

    const inputs = [
      elementCreator.createImageInput({
        buttonText: labelHandler.getLabel({ baseObject: 'RegisterDialog', label: 'image' }),
        elementId: ids.PICTURE,
        inputName: 'picture',
        appendPreview: true,
        previewId: 'imagePreview-userSelf',
      }),
    ];
    const lowerButtons = [
      elementCreator.createButton({
        text: labelHandler.getLabel({ baseObject: 'BaseDialog', label: 'cancel' }),
        clickFuncs: {
          leftFunc: () => {
            this.removeFromView();
          },
        },
      }),
      // elementCreator.createButton({
      //   text: labelHandler.getLabel({ baseObject: 'UserSelfDialog', label: 'rename' }),
      //   clickFuncs: {
      //     leftFunc: () => {
      //       const renameDialog = new BaseDialog({
      //         inputs: [
      //           elementCreator.createInput({
      //             elementId: 'username',
      //             inputName: 'username',
      //             type: 'text',
      //             isRequired: true,
      //             maxLength: 10,
      //             placeholder: labelHandler.getLabel({ baseObject: 'LoginDialog', label: 'username' }),
      //           }),
      //         ],
      //         lowerButtons: [
      //           elementCreator.createButton({
      //             text: labelHandler.getLabel({ baseObject: 'BaseDialog', label: 'cancel' }),
      //             clickFuncs: {
      //               leftFunc: () => { renameDialog.removeFromView(); },
      //             },
      //           }),
      //           elementCreator.createButton({
      //             text: labelHandler.getLabel({ baseObject: 'BaseDialog', label: 'update' }),
      //             clickFuncs: {
      //               leftFunc: () => {
      //                 if (this.hasEmptyRequiredInputs()) {
      //                   return;
      //                 }
      //
      //                 userComposer.updateUsername({
      //                   userId,
      //                   username: renameDialog.getInputValue('username'),
      //                   callback: ({ error: updateError }) => {
      //                     if (updateError) {
      //                       console.log('Failed to update username');
      //
      //                       return;
      //                     }
      //
      //                     const parentElement = renameDialog.getParentElement();
      //
      //                     renameDialog.removeFromView();
      //                     this.addToView({ element: parentElement });
      //                   },
      //                 });
      //               },
      //             },
      //           }),
      //         ],
      //       });
      //
      //       renameDialog.addToView({ element: this.getParentElement() });
      //       this.removeFromView();
      //     },
      //   },
      // }),
      elementCreator.createButton({
        text: labelHandler.getLabel({ baseObject: 'BaseDialog', label: 'update' }),
        clickFuncs: {
          leftFunc: () => {
            if (this.hasEmptyRequiredInputs()) {
              return;
            }

            const params = {
              userId,
              callback: ({ error }) => {
                if (error) {
                  console.log(error);

                  return;
                }

                this.removeFromView();
              },
            };
            const imagePreview = document.getElementById('imagePreview-userSelf');

            if (imagePreview.getAttribute('src')) {
              params.image = {
                source: imagePreview.getAttribute('src'),
                imageName: imagePreview.getAttribute('name'),
                width: imagePreview.naturalWidth,
                height: imagePreview.naturalHeight,
              };
            }

            console.log('update user ', params);

            userComposer.updateUser(params);
          },
        },
      }),
    ];

    if (userPosition) {
      lowerButtons.push(elementCreator.createButton({
        text: labelHandler.getLabel({ baseObject: 'UserDialog', label: 'trackPosition' }),
        clickFuncs: {
          leftFunc: () => {
            viewSwitcher.switchViewByType({ type: viewSwitcher.ViewTypes.WORLDMAP });

            eventCentral.emitEvent({
              event: eventCentral.Events.FOCUS_MAPPOSITION,
              params: { position: userPosition },
            });

            this.removeFromView();
          },
        },
      }));
    }

    const upperText = [
      `${labelHandler.getLabel({ baseObject: 'UserDialog', label: 'userInfo' })}`,
      '',
    ];

    if (fullName) {
      upperText.push(fullName);
    }

    upperText.push(`${labelHandler.getLabel({ baseObject: 'UserDialog', label: 'username' })}: ${username}`);

    if (partOfTeams && partOfTeams.length > 0) {
      upperText.push(`${labelHandler.getLabel({ baseObject: 'UserDialog', label: 'partOfTeam' })}: ${partOfTeams}`);
    }

    if (userPosition && userPosition.coordinatesHistory && userPosition.coordinatesHistory[0]) {
      const positionLabel = `(${userPosition.lastUpdated}): Lat ${userPosition.coordinatesHistory[0].latitude} Long ${userPosition.coordinatesHistory[0].longitude}`;

      upperText.push(`${labelHandler.getLabel({ baseObject: 'UserDialog', label: 'position' })}: ${positionLabel}`);
    }

    const images = [];

    if (image) {
      images.push(elementCreator.createPicture({
        picture: image,
      }));
    }
    super({
      elementId,
      lowerButtons,
      upperText,
      images,
      inputs,
      classes: classes.concat(['userSelfDialog']),
    });
  }
}

module.exports = UserSelfDialog;
<|endoftext|>


<commit_before>var config = require('../config');
var gulp = require('gulp');
var shell = require('gulp-shell');

gulp.task('docs', shell.task([
  'node_modules/jsdoc/jsdoc.js '+
    '-c node_modules/angular-jsdoc/common/conf.json '+   // config file
    '-t node_modules/angular-jsdoc/angular-template '+   // template file
    '-d ' + config.docs.dest +                           // output directory
    ' ./OVERVIEW.md ' +                            // to include README.md as index contents
    '-r ' + config.app.src +               // source code directory
    ' -u ' + config.docs.src                              // tutorials directory
]));<commit_msg>JSDoc: Changed build template to default<commit_after>var config = require('../config');
var gulp = require('gulp');
var shell = require('gulp-shell');

gulp.task('docs', shell.task([
  'node_modules/jsdoc/jsdoc.js '+
    '-c node_modules/angular-jsdoc/common/conf.json '+   // config file
    '-t node_modules/angular-jsdoc/default '+   // template file
    '-d ' + config.docs.dest +                           // output directory
    ' ./OVERVIEW.md ' +                            // to include README.md as index contents
    '-r ' + config.app.src +               // source code directory
    ' -u ' + config.docs.src                              // tutorials directory
]));<|endoftext|>


<commit_before>var gulp = require("gulp"),
    rimraf = require("rimraf"),
    concat = require("gulp-concat"),
    cssmin = require("gulp-cssmin"),
    uglify = require("gulp-uglify"),
    rename = require("gulp-rename"),
    sourcemaps = require("gulp-sourcemaps");
var less = require('gulp-less');
var path = require('path');
var uglifycss = require('gulp-uglifycss');
var gutil = require('gulp-util');
var plumber = require('gulp-plumber');
var injectString = require('gulp-inject-string');

//Moduleify
function JsnsModule(settings) {
    if (settings['moduleStart'] === undefined) {
        function moduleStart() {
            if (this['operation'] === undefined) {
                this.operation = 'define';
            }

            var header = 'jsns.' + this.operation + '("' + this.moduleName + '", [';

            var autoDepArgs = '';
            if (this['dependencies'] !== undefined) {
                for (i = 0; i < this.dependencies.length; ++i) {
                    var dep = this.dependencies[i];
                    header += '"' + dep + '", '
                    autoDepArgs += ', ' + dep.replace('.', '_');
                }
            }

            header += '], function(exports, module ' + autoDepArgs + ') {';
            return header;
        }
        settings.moduleStart = moduleStart;
    }

    if (settings['moduleEnd'] === undefined) {
        function moduleEnd() {
            return '});';
        }
        settings.moduleEnd = moduleEnd;
    }

    return gulp.src(settings.libs, { base: settings.base })
        .pipe(sourcemaps.init())
        .pipe(concat(settings.output))
        .pipe(injectString.wrap(settings.moduleStart(), settings.moduleEnd()))
        .pipe(gulp.dest(settings.dest));
}

module.exports = JsnsModule;<commit_msg>Removed gulp task.<commit_after><|endoftext|>


<commit_before>var utility = require('./utility');
var config = require('./config');
var processors = require('./processors');
var getData = utility.getData;
var db = require('./db');
var r = require('./redis');
var redis = r.client;
var jobs = r.jobs;
var kue = r.kue;
var logger = utility.logger;
var generateJob = utility.generateJob;
var async = require('async');
var operations = require('./operations');
var insertMatch = operations.insertMatch;
var queueReq = operations.queueReq;
var fullhistory = require('./tasks/fullhistory');
var updatenames = require('./tasks/updatenames');
var selector = require('./selector');
var domain = require('domain');
var trackedPlayers = {};
var activePlayers = {};
var ratingPlayers = {};
/*
var seaport = require('seaport');
var server = seaport.createServer();
server.listen(config.REGISTRY_PORT);
*/
var retrievers = config.RETRIEVER_HOST;
//don't need these handlers when kue supports job ttl in 0.9?
process.on('SIGTERM', function() {
    clearActiveJobs(function(err) {
        process.exit(err || 1);
    });
});
process.on('SIGINT', function() {
    clearActiveJobs(function(err) {
        process.exit(err || 1);
    });
});
var d = domain.create();
d.on('error', function(err) {
    console.log(err.stack);
    clearActiveJobs(function(err2) {
        process.exit(err2 || err || 1);
    });
});
d.run(function() {
    console.log("[WORKER] starting worker");
    build(function() {
        startScan();
        jobs.promote();
        jobs.process('api', config.STEAM_API_KEY.split(",").length, processors.processApi);
        jobs.process('mmr', processors.processMmr);
        jobs.process('request', processors.processApi);
        setInterval(fullhistory, 3 * 60 * 1000, function() {});
        setInterval(updatenames, 3 * 60 * 1000, function() {});
        setInterval(build, 3 * 60 * 1000, function() {});
        //todo implement redis window check
        //setInterval(apiStatus, 2 * 60 * 1000);
    });
});

function clearActiveJobs(cb) {
    jobs.active(function(err, ids) {
        if (err) {
            return cb(err);
        }
        async.mapSeries(ids, function(id, cb) {
            kue.Job.get(id, function(err, job) {
                if (job) {
                    console.log("requeued job %s", id);
                    job.inactive();
                }
                cb(err);
            });
        }, function(err) {
            console.log("cleared active jobs");
            cb(err);
        });
    });
}

function build(cb) {
    console.log("rebuilding sets");
    async.series({
        "trackedPlayers": function(cb) {
            db.players.find(selector("tracked"), function(err, docs) {
                if (err) {
                    return cb(err);
                }
                var t = {};
                docs.forEach(function(player) {
                    t[player.account_id] = true;
                });
                //console.log(t);
                cb(err, t);
            });
        },
        "activePlayers": function(cb) {
            db.players.find({
                last_visited: {
                    $ne: null
                }
            }, function(err, docs) {
                if (err) {
                    return cb(err);
                }
                var t = {};
                docs.forEach(function(player) {
                    t[player.account_id] = true;
                });
                //console.log(t);
                cb(err, t);
            });
        },
        "retrievers": function(cb) {
            var r = {};
            var b = [];
            var ps = retrievers.split(",").map(function(r) {
                return "http://" + r;
            });
            async.each(ps, function(url, cb) {
                getData(url, function(err, body) {
                    if (err) {
                        return cb(err);
                    }
                    for (var key in body.accounts) {
                        b.push(body.accounts[key]);
                    }
                    for (var key in body.accountToIdx) {
                        r[key] = url + "?account_id=" + key;
                    }
                    cb(err);
                });
            }, function(err) {
                var result = {
                    ratingPlayers: r,
                    bots: b,
                    retrievers: ps
                };
                cb(err, result);
            });
        }
    }, function(err, result) {
        if (err) {
            return build(cb);
        }
        result.ratingPlayers = result.retrievers.ratingPlayers;
        result.bots = result.retrievers.bots;
        result.retrievers = result.retrievers.retrievers;
        trackedPlayers = result.trackedPlayers;
        ratingPlayers = result.ratingPlayers;
        activePlayers = result.activePlayers;
        for (var key in result) {
            redis.set(key, JSON.stringify(result[key]));
        }
        cb();
    });
}

function startScan() {
    if (config.START_SEQ_NUM === "AUTO") {
        var container = generateJob("api_history", {});
        getData(container.url, function(err, data) {
            if (err) {
                return startScan();
            }
            scanApi(data.result.matches[0].match_seq_num);
        });
    }
    else if (config.START_SEQ_NUM) {
        scanApi(config.START_SEQ_NUM);
    }
    else {
        redis.get("match_seq_num", function(err, result) {
            if (!err && result) {
                scanApi(result);
            }
            else {
                return startScan();
            }
        });
    }
}
var q = async.queue(function(match, cb) {
    async.each(match.players, function(p, cb) {
        if (p.account_id in activePlayers) {
            //skipped
            match.parse_status = 3;
        }
        if (p.account_id in trackedPlayers) {
            //queued
            match.parse_status = 0;
        }
        if (p.account_id in ratingPlayers && match.lobby_type === 7) {
            queueReq("mmr", {
                match_id: match.match_id,
                account_id: p.account_id,
                url: ratingPlayers[p.account_id]
            }, function(err) {
                cb(err);
            });
        }
        else {
            cb();
        }
    }, function(err) {
        if (err) {
            return cb(err);
        }
        if (match.parse_status === 0 || match.parse_status === 3) {
            insertMatch(match, function(err) {
                if (err) {
                    return cb(err, match);
                }
                //queue parse
                if (match.parse_status === 0) {
                    queueReq("parse", match, function(err, job) {
                        cb(err, match);
                    });
                }
                else {
                    return cb(err, match);
                }
            });
        }
        else {
            cb(err, match);
        }
    });
});

function scanApi(seq_num) {
    var container = generateJob("api_sequence", {
        start_at_match_seq_num: seq_num
    });
    getData(container.url, function(err, data) {
        if (err) {
            return scanApi(seq_num);
        }
        var resp = data.result.matches;
        var next_seq_num = seq_num;
        if (resp.length) {
            next_seq_num = resp[resp.length - 1].match_seq_num + 1;
        }
        logger.info("[API] seq_num:%s, matches:%s, queue:%s", seq_num, resp.length, q.length());
        q.push(resp, function(err, match) {
            if (err) {
                console.log("failed to insert match from scanApi");
                process.exit(1);
            }
            else {
                //set the redis progress
                redis.set("match_seq_num", match.match_seq_num);
            }
        });
        //wait 100ms for each match less than 100
        var delay = (100 - resp.length) * 100;
        setTimeout(function() {
            scanApi(next_seq_num);
        }, delay);
    });
}

function apiStatus() {
    db.matches.findOne({}, {
        fields: {
            _id: 1
        },
        sort: {
            match_seq_num: -1
        }
    }, function(err, match) {
        var elapsed = (new Date() - db.matches.id(match._id).getTimestamp());
        console.log(elapsed);
        if (elapsed > 15 * 60 * 1000) {
            redis.set("apiDown", 1);
        }
        else {
            redis.set("apiDown", 0);
        }
    });
}
<commit_msg>increase delay to 6 min<commit_after>var utility = require('./utility');
var config = require('./config');
var processors = require('./processors');
var getData = utility.getData;
var db = require('./db');
var r = require('./redis');
var redis = r.client;
var jobs = r.jobs;
var kue = r.kue;
var logger = utility.logger;
var generateJob = utility.generateJob;
var async = require('async');
var operations = require('./operations');
var insertMatch = operations.insertMatch;
var queueReq = operations.queueReq;
var fullhistory = require('./tasks/fullhistory');
var updatenames = require('./tasks/updatenames');
var selector = require('./selector');
var domain = require('domain');
var trackedPlayers = {};
var activePlayers = {};
var ratingPlayers = {};
/*
var seaport = require('seaport');
var server = seaport.createServer();
server.listen(config.REGISTRY_PORT);
*/
var retrievers = config.RETRIEVER_HOST;
//don't need these handlers when kue supports job ttl in 0.9?
process.on('SIGTERM', function() {
    clearActiveJobs(function(err) {
        process.exit(err || 1);
    });
});
process.on('SIGINT', function() {
    clearActiveJobs(function(err) {
        process.exit(err || 1);
    });
});
var d = domain.create();
d.on('error', function(err) {
    console.log(err.stack);
    clearActiveJobs(function(err2) {
        process.exit(err2 || err || 1);
    });
});
d.run(function() {
    console.log("[WORKER] starting worker");
    build(function() {
        startScan();
        jobs.promote();
        jobs.process('api', config.STEAM_API_KEY.split(",").length, processors.processApi);
        jobs.process('mmr', processors.processMmr);
        jobs.process('request', processors.processApi);
        setInterval(fullhistory, 6 * 60 * 1000, function() {});
        setInterval(updatenames, 3 * 60 * 1000, function() {});
        setInterval(build, 3 * 60 * 1000, function() {});
        //todo implement redis window check
        //setInterval(apiStatus, 2 * 60 * 1000);
    });
});

function clearActiveJobs(cb) {
    jobs.active(function(err, ids) {
        if (err) {
            return cb(err);
        }
        async.mapSeries(ids, function(id, cb) {
            kue.Job.get(id, function(err, job) {
                if (job) {
                    console.log("requeued job %s", id);
                    job.inactive();
                }
                cb(err);
            });
        }, function(err) {
            console.log("cleared active jobs");
            cb(err);
        });
    });
}

function build(cb) {
    console.log("rebuilding sets");
    async.series({
        "trackedPlayers": function(cb) {
            db.players.find(selector("tracked"), function(err, docs) {
                if (err) {
                    return cb(err);
                }
                var t = {};
                docs.forEach(function(player) {
                    t[player.account_id] = true;
                });
                //console.log(t);
                cb(err, t);
            });
        },
        "activePlayers": function(cb) {
            db.players.find({
                last_visited: {
                    $ne: null
                }
            }, function(err, docs) {
                if (err) {
                    return cb(err);
                }
                var t = {};
                docs.forEach(function(player) {
                    t[player.account_id] = true;
                });
                //console.log(t);
                cb(err, t);
            });
        },
        "retrievers": function(cb) {
            var r = {};
            var b = [];
            var ps = retrievers.split(",").map(function(r) {
                return "http://" + r;
            });
            async.each(ps, function(url, cb) {
                getData(url, function(err, body) {
                    if (err) {
                        return cb(err);
                    }
                    for (var key in body.accounts) {
                        b.push(body.accounts[key]);
                    }
                    for (var key in body.accountToIdx) {
                        r[key] = url + "?account_id=" + key;
                    }
                    cb(err);
                });
            }, function(err) {
                var result = {
                    ratingPlayers: r,
                    bots: b,
                    retrievers: ps
                };
                cb(err, result);
            });
        }
    }, function(err, result) {
        if (err) {
            return build(cb);
        }
        result.ratingPlayers = result.retrievers.ratingPlayers;
        result.bots = result.retrievers.bots;
        result.retrievers = result.retrievers.retrievers;
        trackedPlayers = result.trackedPlayers;
        ratingPlayers = result.ratingPlayers;
        activePlayers = result.activePlayers;
        for (var key in result) {
            redis.set(key, JSON.stringify(result[key]));
        }
        cb();
    });
}

function startScan() {
    if (config.START_SEQ_NUM === "AUTO") {
        var container = generateJob("api_history", {});
        getData(container.url, function(err, data) {
            if (err) {
                return startScan();
            }
            scanApi(data.result.matches[0].match_seq_num);
        });
    }
    else if (config.START_SEQ_NUM) {
        scanApi(config.START_SEQ_NUM);
    }
    else {
        redis.get("match_seq_num", function(err, result) {
            if (!err && result) {
                scanApi(result);
            }
            else {
                return startScan();
            }
        });
    }
}
var q = async.queue(function(match, cb) {
    async.each(match.players, function(p, cb) {
        if (p.account_id in activePlayers) {
            //skipped
            match.parse_status = 3;
        }
        if (p.account_id in trackedPlayers) {
            //queued
            match.parse_status = 0;
        }
        if (p.account_id in ratingPlayers && match.lobby_type === 7) {
            queueReq("mmr", {
                match_id: match.match_id,
                account_id: p.account_id,
                url: ratingPlayers[p.account_id]
            }, function(err) {
                cb(err);
            });
        }
        else {
            cb();
        }
    }, function(err) {
        if (err) {
            return cb(err);
        }
        if (match.parse_status === 0 || match.parse_status === 3) {
            insertMatch(match, function(err) {
                if (err) {
                    return cb(err, match);
                }
                //queue parse
                if (match.parse_status === 0) {
                    queueReq("parse", match, function(err, job) {
                        cb(err, match);
                    });
                }
                else {
                    return cb(err, match);
                }
            });
        }
        else {
            cb(err, match);
        }
    });
});

function scanApi(seq_num) {
    var container = generateJob("api_sequence", {
        start_at_match_seq_num: seq_num
    });
    getData(container.url, function(err, data) {
        if (err) {
            return scanApi(seq_num);
        }
        var resp = data.result.matches;
        var next_seq_num = seq_num;
        if (resp.length) {
            next_seq_num = resp[resp.length - 1].match_seq_num + 1;
        }
        logger.info("[API] seq_num:%s, matches:%s, queue:%s", seq_num, resp.length, q.length());
        q.push(resp, function(err, match) {
            if (err) {
                console.log("failed to insert match from scanApi");
                process.exit(1);
            }
            else {
                //set the redis progress
                redis.set("match_seq_num", match.match_seq_num);
            }
        });
        //wait 100ms for each match less than 100
        var delay = (100 - resp.length) * 100;
        setTimeout(function() {
            scanApi(next_seq_num);
        }, delay);
    });
}

function apiStatus() {
    db.matches.findOne({}, {
        fields: {
            _id: 1
        },
        sort: {
            match_seq_num: -1
        }
    }, function(err, match) {
        var elapsed = (new Date() - db.matches.id(match._id).getTimestamp());
        console.log(elapsed);
        if (elapsed > 15 * 60 * 1000) {
            redis.set("apiDown", 1);
        }
        else {
            redis.set("apiDown", 0);
        }
    });
}
<|endoftext|>


<commit_before>console.log('worker test');
<commit_msg>try worker with env<commit_after>console.log(process.env['DB_PORT']);
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var fs = require('fs')
  , path = require('path');

var d3 = require('d3')
  , _ = require('underscore');

var pathname = path.join('private', 'graphs', process.argv[2])
fs.readFile(pathname, { encoding: 'utf8' }, function(err, data) {
  if (err) {
    throw err;
  }

  var adj = JSON.parse(data);

  function computeNodes(refs) {
    return _.map(adj, function(value, key) {
      refs[key] = { id: key };
      return refs[key];
    });
  };

  var refs = {}
    , nodes = computeNodes(refs)
    , links = d3.merge(nodes.map(function(source) {
        return adj[source.id].map(function(targetId) {
          return { source: refs[source.id]
                 , target: refs[targetId]
                 };
        });
      }));

  var width = 960
    , height = 500;

  var force = d3.layout.force()
      .nodes(nodes)
      .links(links)
      .size([ width, height ]);

  var EPSILON = 0.05;

  force.start();

  while (force.alpha() > EPSILON) {
    force.tick();
  }

  force.stop();

  var result = {};
  _.each(refs, function(value, key) {
    result[key] = { x: value.x, y: value.y };
  });

  console.log(JSON.stringify(result));
});
<commit_msg>Changed epsilon to zero.<commit_after>
/**
 * Module dependencies.
 */

var fs = require('fs')
  , path = require('path');

var d3 = require('d3')
  , _ = require('underscore');

var pathname = path.join('private', 'graphs', process.argv[2])
fs.readFile(pathname, { encoding: 'utf8' }, function(err, data) {
  if (err) {
    throw err;
  }

  var adj = JSON.parse(data);

  function computeNodes(refs) {
    return _.map(adj, function(value, key) {
      refs[key] = { id: key };
      return refs[key];
    });
  };

  var refs = {}
    , nodes = computeNodes(refs)
    , links = d3.merge(nodes.map(function(source) {
        return adj[source.id].map(function(targetId) {
          return { source: refs[source.id]
                 , target: refs[targetId]
                 };
        });
      }));

  var width = 960
    , height = 500;

  var force = d3.layout.force()
      .nodes(nodes)
      .links(links)
      .size([ width, height ]);

  var EPSILON = 0;

  force.start();

  while (force.alpha() > EPSILON) {
    force.tick();
  }

  force.stop();

  var result = {};
  _.each(refs, function(value, key) {
    result[key] = { x: value.x, y: value.y };
  });

  console.log(JSON.stringify(result));
});
<|endoftext|>


<commit_before>/**
 *  File worker that is started by the main server process. It downloads and anylyzes the zile in a different process
 *  leaving the main process for the server
 *
 *  We could kick off more processes for the analyzation, eg. each per file. I think this program to be mostly web application that server
 *  analyzation, but offers a way for the mainteiner to download the file again.
 *
 *  Call chaing in this solution after creating http.createServer if file does not exist
 *  getZipZile -> unZipData -> analyzeData -> printAnalyzation
 */

var path = require('path');
var fs = require('fs');
var admZip = require('adm-zip');
var http = require('http');

// Configuration file
var config = require(path.join(__dirname, 'config.js'));

function analyzeJSON(filesJSON) {
	console.info("Data structure ready, starting to analyze data...");

	var result = {
		from : undefined,
		to : undefined,
		days : 0,
		categories : {},
		locations : {},
		incidents : {}
	};

	var fileCounter = filesJSON.length;
	filesJSON.forEach(function(fileJSON) {
		fileCounter--;

		var dayCounter = fileJSON.autoreporter.opendata.length;
		fileJSON.autoreporter.opendata.forEach(function(day) {
			dayCounter--;

			// Capturing start and end dates
			var dateFrom = new Date(day.date.from);
			if (result.from == undefined || result.from.getTime() > dateFrom.getTime())
				result.from = dateFrom;

			var dateTo = new Date(day.date.to);
			if (result.to == undefined || result.to.getTime() < dateTo.getTime())
				result.to = dateTo;

			// Creating new year and month to object if does not exist
			if (!result.incidents.hasOwnProperty(dateFrom.getFullYear()))
				result.incidents[dateFrom.getFullYear()] = {};

			if (!result.incidents[dateFrom.getFullYear()].hasOwnProperty(dateFrom.getMonth()))
				result.incidents[dateFrom.getFullYear()][dateFrom.getMonth()] = 0;

			var occurrencyCounter = day.asn.length;
			day.asn.forEach(function(occurrency) {
				occurrencyCounter--;

				var ipaddressCounter = occurrency.ipaddress.length;
				occurrency.ipaddress.forEach(function(ipaddress) {
					ipaddressCounter--;

					var location = ipaddress.city + '-' + ipaddress.cc;

					// Creating new location to object if does not exist
					if (result.locations.hasOwnProperty(location)) {
						result.locations[location]++;
					} else {
						result.locations[location] = 1;
					}

					var incidentCounter = ipaddress.incident.length;
					ipaddress.incident.forEach(function(incident) {
						incidentCounter--;

						// Counting every incident under a month
						result.incidents[dateFrom.getFullYear()][dateFrom.getMonth()]++;

						// Creating new category to object if does not exist
						if (result.categories.hasOwnProperty(incident.category.main)) {
							result.categories[incident.category.main]++;
						} else {
							result.categories[incident.category.main] = 1;
						}

						// After every loop is done, print the result and setting analyzation done
						if (fileCounter == 0 && dayCounter == 0 && occurrencyCounter == 0 && ipaddressCounter == 0 && incidentCounter == 0) {
							var oneDay = (1000 * 60 * 60 * 24);
							result.days = Math.abs((result.from.getTime() - result.to.getTime()) / (oneDay));

							result.done = true;

							fs.writeFile(config.pathAnalyzation, JSON.stringify(result), function(err) {
								if (err)
									throw err;
								console.log('Analyzation saved to file ' + config.pathAnalyzation);
							});

							// Pass results back to parent process
							process.send(result);
						}
					});
				});
			});
		});
	});
};

function unZipData() {

	try {
		var zip = new admZip(config.pathJSON);
		var zipEntries = zip.getEntries();

		console.info(config.JSON + " contains " + zipEntries.length + " files, extracting to array");
		var filesJSON = new Array(zipEntries.length);

		// Unzippping everything to data array as JSON objects then exec callback
		var index = 0;

		zipEntries.forEach(function(entry) {

			var entryName = entry.entryName;

			zip.readAsTextAsync(entry, function(data) {
				console.log('Decompressing ' + entryName + ' as a JSON object to array index ' + index);

				try {
					filesJSON[index++] = JSON.parse(data);
					if (index == zipEntries.length)
						analyzeJSON(filesJSON);
				} catch(err) {
					console.error('JSON parsing failed, please delete existing file and try again. Error: ', err);
					process.exit(1);
				}
			});
		});
	} catch(err) {
		console.error('Reading ' + config.JSON + ' failed, please delete existing file and try again. Error:', err);
		process.exit(1);
	}

};

function getZipfile() {
	console.log('Checking if ' + config.pathFolder + ' exists, creating if does not');

	fs.mkdir(config.pathFolder, function() {
		var lenght = 0;
		var file = fs.createWriteStream(config.pathJSON);
		var request = http.get(config.JSON_url, function(response) {

			var change = -1;
			console.log('Downloading file.. ' + config.JSON_url);

			response.on('data', function(chunk) {
				file.write(chunk);
				lenght += chunk.length;

				var percent = Math.round((lenght / response.headers['content-length']) * 100);

				if (change != percent) {
					change = percent;
					process.stdout.write(" " + percent + "%");
				}
			});

			response.on('end', function() {
				console.log();
				file.close();
			});

			file.on('close', function() {
				unZipData();
			});
		});
	});
};

// Worker process starts: analyzation file does not exist, checking json.zip
process.on('message', function(data) {
	if (data === 'start') {
		fs.exists(config.pathJSON, function(exists) {
			if (exists) {
				console.warn(config.JSON + ' exists, but there is no ' + config.analyzation + ', starting unzip');
				unZipData();
			} else {
				console.warn(config.JSON + ' file does not exist...');
				getZipfile();
			}
		});
	} else if (data === 'reset') {
		getZipfile();
	} else if (data === 'exit') {
		process.exit(0);
	}
});
<commit_msg>description update<commit_after>/**
 *  File worker that is started by the main server process. It downloads and anylyzes the zile in a different process
 *  leaving the main process for the server
 *
 *  We could kick off more processes for the analyzation, eg. each per file. I think this program to be mostly web application that server
 *  analyzation, but offers a way for the mainteiner to download the file again.
 *
 *  Call chaing in this solution after creating http.createServer if file does not exist
 *  getZipZile -> unZipData -> analyzeData
 */

var path = require('path');
var fs = require('fs');
var admZip = require('adm-zip');
var http = require('http');

// Configuration file
var config = require(path.join(__dirname, 'config.js'));

function analyzeJSON(filesJSON) {
	console.info("Data structure ready, starting to analyze data...");

	var result = {
		from : undefined,
		to : undefined,
		days : 0,
		categories : {},
		locations : {},
		incidents : {}
	};

	var fileCounter = filesJSON.length;
	filesJSON.forEach(function(fileJSON) {
		fileCounter--;

		var dayCounter = fileJSON.autoreporter.opendata.length;
		fileJSON.autoreporter.opendata.forEach(function(day) {
			dayCounter--;

			// Capturing start and end dates
			var dateFrom = new Date(day.date.from);
			if (result.from == undefined || result.from.getTime() > dateFrom.getTime())
				result.from = dateFrom;

			var dateTo = new Date(day.date.to);
			if (result.to == undefined || result.to.getTime() < dateTo.getTime())
				result.to = dateTo;

			// Creating new year and month to object if does not exist
			if (!result.incidents.hasOwnProperty(dateFrom.getFullYear()))
				result.incidents[dateFrom.getFullYear()] = {};

			if (!result.incidents[dateFrom.getFullYear()].hasOwnProperty(dateFrom.getMonth()))
				result.incidents[dateFrom.getFullYear()][dateFrom.getMonth()] = 0;

			var occurrencyCounter = day.asn.length;
			day.asn.forEach(function(occurrency) {
				occurrencyCounter--;

				var ipaddressCounter = occurrency.ipaddress.length;
				occurrency.ipaddress.forEach(function(ipaddress) {
					ipaddressCounter--;

					var location = ipaddress.city + '-' + ipaddress.cc;

					// Creating new location to object if does not exist
					if (result.locations.hasOwnProperty(location)) {
						result.locations[location]++;
					} else {
						result.locations[location] = 1;
					}

					var incidentCounter = ipaddress.incident.length;
					ipaddress.incident.forEach(function(incident) {
						incidentCounter--;

						// Counting every incident under a month
						result.incidents[dateFrom.getFullYear()][dateFrom.getMonth()]++;

						// Creating new category to object if does not exist
						if (result.categories.hasOwnProperty(incident.category.main)) {
							result.categories[incident.category.main]++;
						} else {
							result.categories[incident.category.main] = 1;
						}

						// After every loop is done, print the result and setting analyzation done
						if (fileCounter == 0 && dayCounter == 0 && occurrencyCounter == 0 && ipaddressCounter == 0 && incidentCounter == 0) {
							var oneDay = (1000 * 60 * 60 * 24);
							result.days = Math.abs((result.from.getTime() - result.to.getTime()) / (oneDay));

							result.done = true;

							fs.writeFile(config.pathAnalyzation, JSON.stringify(result), function(err) {
								if (err)
									throw err;
								console.log('Analyzation saved to file ' + config.pathAnalyzation);
							});

							// Pass results back to parent process
							process.send(result);
						}
					});
				});
			});
		});
	});
};

function unZipData() {

	try {
		var zip = new admZip(config.pathJSON);
		var zipEntries = zip.getEntries();

		console.info(config.JSON + " contains " + zipEntries.length + " files, extracting to array");
		var filesJSON = new Array(zipEntries.length);

		// Unzippping everything to data array as JSON objects then exec callback
		var index = 0;

		zipEntries.forEach(function(entry) {

			var entryName = entry.entryName;

			zip.readAsTextAsync(entry, function(data) {
				console.log('Decompressing ' + entryName + ' as a JSON object to array index ' + index);

				try {
					filesJSON[index++] = JSON.parse(data);
					if (index == zipEntries.length)
						analyzeJSON(filesJSON);
				} catch(err) {
					console.error('JSON parsing failed, please delete existing file and try again. Error: ', err);
					process.exit(1);
				}
			});
		});
	} catch(err) {
		console.error('Reading ' + config.JSON + ' failed, please delete existing file and try again. Error:', err);
		process.exit(1);
	}

};

function getZipfile() {
	console.log('Checking if ' + config.pathFolder + ' exists, creating if does not');

	fs.mkdir(config.pathFolder, function() {
		var lenght = 0;
		var file = fs.createWriteStream(config.pathJSON);
		var request = http.get(config.JSON_url, function(response) {

			var change = -1;
			console.log('Downloading file.. ' + config.JSON_url);

			response.on('data', function(chunk) {
				file.write(chunk);
				lenght += chunk.length;

				var percent = Math.round((lenght / response.headers['content-length']) * 100);

				if (change != percent) {
					change = percent;
					process.stdout.write(" " + percent + "%");
				}
			});

			response.on('end', function() {
				console.log();
				file.close();
			});

			file.on('close', function() {
				unZipData();
			});
		});
	});
};

// Worker process starts: analyzation file does not exist, checking json.zip
process.on('message', function(data) {
	if (data === 'start') {
		fs.exists(config.pathJSON, function(exists) {
			if (exists) {
				console.warn(config.JSON + ' exists, but there is no ' + config.analyzation + ', starting unzip');
				unZipData();
			} else {
				console.warn(config.JSON + ' file does not exist...');
				getZipfile();
			}
		});
	} else if (data === 'reset') {
		getZipfile();
	} else if (data === 'exit') {
		process.exit(0);
	}
});
<|endoftext|>