<commit_before>'use strict';
const mongoClient = require('mongodb').MongoClient;
const fs = require('fs');

// Environment file
/*var env = require('node-env-file');
env(__dirname + '/../.env');*/

/*Quentin*/var url = 'mongodb://' + process.env.ASLAN_MESSENGER_DB_TOKEN + '@aslanmessenger-shard-00-00-rh6fw.mongodb.net:27017,aslanmessenger-shard-00-01-rh6fw.mongodb.net:27017,aslanmessenger-shard-00-02-rh6fw.mongodb.net:27017/AslanMessenger?ssl=true&replicaSet=AslanMessenger-shard-0&authSource=admin'
/*Nicolas*///var url = 'mongodb://' + process.env.ASLAN_MESSENGER_DB_TOKEN + '@aslandb-shard-00-00-fdkfh.mongodb.net:27017,aslandb-shard-00-01-fdkfh.mongodb.net:27017,aslandb-shard-00-02-fdkfh.mongodb.net:27017/<DATABASE>?ssl=true&replicaSet=AslanDB-shard-0&authSource=admin';
/*Olivier*///var url = 'mongodb://' + process.env.MONGO_DB_TOKEN + '@aslandb-shard-00-01-yened.mongodb.net:27017/grandlyon?ssl=true&authSource=admin';
/*Quentin2*///var url = 'mongodb://' + process.env.ASLAN_MESSENGER_DB_TOKEN + '@aslandb-shard-00-00-vrrhw.mongodb.net:27017,aslandb-shard-00-01-vrrhw.mongodb.net:27017,aslandb-shard-00-02-vrrhw.mongodb.net:27017/AslanDB>?ssl=true&replicaSet=AslanDB-shard-0&authSource=admin';
/*Arnaud*///var url = 'mongodb://' + process.env.ASLAN_MESSENGER_DB_TOKEN + '@cluster0-shard-00-00-l8lif.mongodb.net:27017,cluster0-shard-00-01-l8lif.mongodb.net:27017,cluster0-shard-00-02-l8lif.mongodb.net:27017/AslanDB>?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin';

const GrandLyonCollection = "AslanMessenger";

exports.getData = function(table, query, callback) {
  // Connexion au serveur avec la méthode connect
  mongoClient.connect(url, function (err, db) {
    try{
      if (err) {
          return console.log('Connection failed', err);
      }
      console.log('Connexion successful on', "aslandb-shard-00-01-yened.mongodb.net:27017");
      console.log('Connected on db:', db.databaseName);

      // Nous allons travailler ici ...
      /*db.collection(table).find(query).toArray(function(err, collections) {
          if (err) {
            console.log(err);
          } else {
            return collections;
          }
      });*/
    db.collection(table).find(query).toArray(callback);

    } catch(error) {
      console.log("error");
      console.log(error);
    }
  });
}

exports.loadJSonData = function(filePath) {
  // Connexion au serveur avec la méthode connect
  mongoClient.connect(url, function (err, db) {
    try{
      if (err) {
          return console.log('Connection failed', err);
      }
        fs.readFile(filePath, 'utf8', function (err, data) {
          if (err) throw err;

          var json = JSON.parse(data);

          db.collection(GrandLyonCollection).insert(json, function(err, doc) {
              console.log("Load done");
          if(err) throw err;
          });
        });
    } catch(error) {
      console.log(error);
    }
  });
}

exports.replaceDocument = function (filePath) {
    // Connexion au serveur avec la méthode connect
    mongoClient.connect(url, function (err, db) {
        try {
            if (err) {
                return console.log('Connection failed', err);
            }
            fs.readFile(filePath, 'utf8', function (err, data) {
                if (err) throw err;

                var json = JSON.parse(data);

                db.collection(GrandLyonCollection).findOneAndReplace({ "doc_id": json.doc_id}, json, function (err, doc) {
                    console.log("Load done");
                    if (err) throw err;
                });
            });
        } catch (error) {
            console.log(error);
        }
    });
}

exports.insertData = function(table, object, callback) {
    // Connexion au serveur avec la méthode connect
    mongoClient.connect(url, function (err, db) {
        try{
            if (err) {
                callback(err, null);
                return console.log('Connection failed', err);
            } else {
                console.log('Connexion successful on', "aslandb-shard-00-01-yened.mongodb.net:27017");
                console.log('Connected on db:', db.databaseName);
                console.log('Insert Data into ', table);
                db.collection(table).insert(object, function (err, results) {
                    console.log(err);
                    if (err) {
                        throw err;
                    } else {
                        callback(results.ops);
                    }
                });
            }
        } catch(error) {
            console.log("error");
            console.log(error);
            callback(error, null);
        }
    });
}<commit_msg>Branchement nouvelle DB<commit_after>'use strict';
const mongoClient = require('mongodb').MongoClient;
const fs = require('fs');

// Environment file
/*var env = require('node-env-file');
env(__dirname + '/../.env');*/

/*Quentin*///var url = 'mongodb://' + process.env.ASLAN_MESSENGER_DB_TOKEN + '@aslanmessenger-shard-00-00-rh6fw.mongodb.net:27017,aslanmessenger-shard-00-01-rh6fw.mongodb.net:27017,aslanmessenger-shard-00-02-rh6fw.mongodb.net:27017/AslanMessenger?ssl=true&replicaSet=AslanMessenger-shard-0&authSource=admin'
/*Nicolas*///var url = 'mongodb://' + process.env.ASLAN_MESSENGER_DB_TOKEN + '@aslandb-shard-00-00-fdkfh.mongodb.net:27017,aslandb-shard-00-01-fdkfh.mongodb.net:27017,aslandb-shard-00-02-fdkfh.mongodb.net:27017/<DATABASE>?ssl=true&replicaSet=AslanDB-shard-0&authSource=admin';
/*Olivier*///var url = 'mongodb://' + process.env.MONGO_DB_TOKEN + '@aslandb-shard-00-01-yened.mongodb.net:27017/grandlyon?ssl=true&authSource=admin';
/*Quentin2*///var url = 'mongodb://' + process.env.ASLAN_MESSENGER_DB_TOKEN + '@aslandb-shard-00-00-vrrhw.mongodb.net:27017,aslandb-shard-00-01-vrrhw.mongodb.net:27017,aslandb-shard-00-02-vrrhw.mongodb.net:27017/AslanDB>?ssl=true&replicaSet=AslanDB-shard-0&authSource=admin';
/*Arnaud*///var url = 'mongodb://' + process.env.ASLAN_MESSENGER_DB_TOKEN + '@cluster0-shard-00-00-l8lif.mongodb.net:27017,cluster0-shard-00-01-l8lif.mongodb.net:27017,cluster0-shard-00-02-l8lif.mongodb.net:27017/AslanDB>?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin';
/*MLab*/var url = 'mongodb://' + process.env.ASLAN_MESSENGER_DB_TOKEN + '@ds131511.mlab.com:31511/h441admin'

const GrandLyonCollection = "AslanMessenger";

exports.getData = function(table, query, callback) {
  // Connexion au serveur avec la méthode connect
  mongoClient.connect(url, function (err, db) {
    try{
      if (err) {
          return console.log('Connection failed', err);
      }
      console.log('Connexion successful on', "aslandb-shard-00-01-yened.mongodb.net:27017");
      console.log('Connected on db:', db.databaseName);

      // Nous allons travailler ici ...
      /*db.collection(table).find(query).toArray(function(err, collections) {
          if (err) {
            console.log(err);
          } else {
            return collections;
          }
      });*/
    db.collection(table).find(query).toArray(callback);

    } catch(error) {
      console.log("error");
      console.log(error);
    }
  });
}

exports.loadJSonData = function(filePath) {
  // Connexion au serveur avec la méthode connect
  mongoClient.connect(url, function (err, db) {
    try{
      if (err) {
          return console.log('Connection failed', err);
      }
        fs.readFile(filePath, 'utf8', function (err, data) {
          if (err) throw err;

          var json = JSON.parse(data);

          db.collection(GrandLyonCollection).insert(json, function(err, doc) {
              console.log("Load done");
          if(err) throw err;
          });
        });
    } catch(error) {
      console.log(error);
    }
  });
}

exports.replaceDocument = function (filePath) {
    // Connexion au serveur avec la méthode connect
    mongoClient.connect(url, function (err, db) {
        try {
            if (err) {
                return console.log('Connection failed', err);
            }
            fs.readFile(filePath, 'utf8', function (err, data) {
                if (err) throw err;

                var json = JSON.parse(data);

                db.collection(GrandLyonCollection).findOneAndReplace({ "doc_id": json.doc_id}, json, function (err, doc) {
                    console.log("Load done");
                    if (err) throw err;
                });
            });
        } catch (error) {
            console.log(error);
        }
    });
}

exports.insertData = function(table, object, callback) {
    // Connexion au serveur avec la méthode connect
    mongoClient.connect(url, function (err, db) {
        try{
            if (err) {
                callback(err, null);
                return console.log('Connection failed', err);
            } else {
                console.log('Connexion successful on', "aslandb-shard-00-01-yened.mongodb.net:27017");
                console.log('Connected on db:', db.databaseName);
                console.log('Insert Data into ', table);
                db.collection(table).insert(object, function (err, results) {
                    console.log(err);
                    if (err) {
                        throw err;
                    } else {
                        callback(results.ops);
                    }
                });
            }
        } catch(error) {
            console.log("error");
            console.log(error);
            callback(error, null);
        }
    });
}<|endoftext|>


<commit_before>/* global angular */

(function () {
    angular
        .module('profile')
        .component('profileForm', {
            templateUrl: 'partials/profile-form.html',
            controller: profileForm,
            controllerAs: 'vm',
            bindings: {
                onFailure: '&',
                onSubmit: '&',
                checkAndClose: '&'
            }
        });

    profileForm.$inject = [
        'UsersService',
        'AuthService',
        'ProfileService',
        'Notification',
        '$timeout',
        '$scope',
    ];

    function profileForm(UsersService, AuthService, ProfileService, Notification, $timeout, $scope) {
        const vm = this;

        vm.index = 0;
        vm.cancel = cancel;
        vm.count = 0;
        vm.profile = {};
        vm.errors = {};
        vm.hasAboutMeErrors = false;
        vm.unsavedData = false;
        let originalProfileJson = '';

        vm.$onInit = function () {
            getEditProfile();
        };

        vm.removeItem = (options) => {
            ProfileService.removeItem(options);
        };

        vm.addItem = (options) => {
            ProfileService.addItem(options);
        };

        vm.save = () => {
            UsersService.saveProfile(AuthService.user.researchEntity, vm.profile).then(response => {

                if (response.profile) {
                    vm.profile = response.profile;
                }

                if (response.errors && !_.isEmpty(response.errors)) {
                    vm.errors = response.errors;

                    vm.hasAboutMeErrors = false;
                    if (
                        _.has(vm.errors, 'image') ||
                        _.has(vm.errors, 'displayNames') ||
                        _.has(vm.errors, 'titles') ||
                        _.has(vm.errors, 'description') ||
                        _.has(vm.errors, 'role') ||
                        _.has(vm.errors, 'website') ||
                        _.has(vm.errors, 'address') ||
                        _.has(vm.errors, 'interests')
                    ) {
                        vm.hasAboutMeErrors = true;
                    }

                    $timeout(() => {
                        const errorTab = document.querySelector('.js-profile-tabs .nav-item.has-error');
                        if (errorTab) {
                            const errorTabIndex = errorTab.getAttribute('index');
                            $scope.active = parseInt(errorTabIndex);
                        }
                    });
                }

                if (response.message) {
                    if (!_.isEmpty(response.count) || response.count > 0) {
                        vm.count = response.count;
                        Notification.error(response.message);
                    } else {
                        vm.count = 0;
                        Notification.success(response.message);

                        originalProfileJson = angular.toJson(vm.profile);
                    }
                }
            });
        };

        function getEditProfile() {
            UsersService.getProfile(AuthService.user.researchEntity, true).then(response => {
                vm.profile = response.plain();
                originalProfileJson = angular.toJson(vm.profile);

                $scope.$broadcast('setupBasicInformation', vm.profile);
            });
        }

        function cancel() {
            if (_.isFunction(vm.checkAndClose())) {
                vm.checkAndClose()(() => angular.toJson(vm.profile) === originalProfileJson);
            }
        }

        function executeOnFailure() {
            if (_.isFunction(vm.onFailure())) {
                vm.onFailure()();
            }
        }
    }
})();
<commit_msg>Clean error when submitting profile form<commit_after>/* global angular */

(function () {
    angular
        .module('profile')
        .component('profileForm', {
            templateUrl: 'partials/profile-form.html',
            controller: profileForm,
            controllerAs: 'vm',
            bindings: {
                onFailure: '&',
                onSubmit: '&',
                checkAndClose: '&'
            }
        });

    profileForm.$inject = [
        'UsersService',
        'AuthService',
        'ProfileService',
        'Notification',
        '$timeout',
        '$scope',
    ];

    function profileForm(UsersService, AuthService, ProfileService, Notification, $timeout, $scope) {
        const vm = this;

        vm.index = 0;
        vm.cancel = cancel;
        vm.count = 0;
        vm.profile = {};
        vm.errors = {};
        vm.hasAboutMeErrors = false;
        vm.unsavedData = false;
        let originalProfileJson = '';

        vm.$onInit = function () {
            getEditProfile();
        };

        vm.removeItem = (options) => {
            ProfileService.removeItem(options);
        };

        vm.addItem = (options) => {
            ProfileService.addItem(options);
        };

        vm.save = () => {
            UsersService.saveProfile(AuthService.user.researchEntity, vm.profile).then(response => {

                vm.hasAboutMeErrors = false;

                if (response.profile) {
                    vm.profile = response.profile;
                }

                if (response.errors && !_.isEmpty(response.errors)) {
                    vm.errors = response.errors;

                    if (
                        _.has(vm.errors, 'image') ||
                        _.has(vm.errors, 'displayNames') ||
                        _.has(vm.errors, 'titles') ||
                        _.has(vm.errors, 'description') ||
                        _.has(vm.errors, 'role') ||
                        _.has(vm.errors, 'website') ||
                        _.has(vm.errors, 'address') ||
                        _.has(vm.errors, 'interests')
                    ) {
                        vm.hasAboutMeErrors = true;
                    }

                    $timeout(() => {
                        const errorTab = document.querySelector('.js-profile-tabs .nav-item.has-error');
                        if (errorTab) {
                            const errorTabIndex = errorTab.getAttribute('index');
                            $scope.active = parseInt(errorTabIndex);
                        }
                    });
                } else {
                    vm.errors = {};
                }

                if (response.message) {
                    if (!_.isEmpty(response.count) || response.count > 0) {
                        vm.count = response.count;
                        Notification.error(response.message);
                    } else {
                        vm.count = 0;
                        Notification.success(response.message);

                        originalProfileJson = angular.toJson(vm.profile);
                    }
                }
            });
        };

        function getEditProfile() {
            UsersService.getProfile(AuthService.user.researchEntity, true).then(response => {
                vm.profile = response.plain();
                originalProfileJson = angular.toJson(vm.profile);

                $scope.$broadcast('setupBasicInformation', vm.profile);
            });
        }

        function cancel() {
            if (_.isFunction(vm.checkAndClose())) {
                vm.checkAndClose()(() => angular.toJson(vm.profile) === originalProfileJson);
            }
        }

        function executeOnFailure() {
            if (_.isFunction(vm.onFailure())) {
                vm.onFailure()();
            }
        }
    }
})();
<|endoftext|>


<commit_before>import React from 'react';
import ProviderCard from './ProviderCard';

import { Button } from "react-bootstrap";

class ProvidersList extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            offset: 50,
        };

    };

    loadMore(){
        this.setState({
          offset: this.state.offset +=50
        });

    }

    render() {
        const styles = {
            activitiesStyle: {
                display: "flex",
                flexWrap: "wrap",
                flexDirection: "row",
                justifyContent: "space-around",
                width: '100%',
            },

        };

        // If no providers found
        if (this.props.providers.length < 1) {
            return
Ingen arrangører funnet
;
        }

        const prov = this.props.providers.slice(0, this.state.offset);

        const providers = prov.map(provider =>
            <ProviderCard key={provider.Id} provider={provider} id={provider.Id}/>
        );

        return

            {providers}
            <Button   className="btn-success" onClick={() => this.loadMore()}>Last flere</Button>

    }
}

export default ProvidersList;
<commit_msg>added comment<commit_after>import React from 'react';
import ProviderCard from './ProviderCard';

import { Button } from "react-bootstrap";

class ProvidersList extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            offset: 50,
        };

    };

    loadMore(){
        this.setState({
          offset: this.state.offset +=50
        });

    }

    render() {
        const styles = {
            activitiesStyle: {
                display: "flex",
                flexWrap: "wrap",
                flexDirection: "row",
                justifyContent: "space-around",
                width: '100%',
            },

        };

        // If no providers found
        if (this.props.providers.length < 1) {
            return
Ingen arrangører funnet
;
        }

        // Slice the reducer data that is provided to match the offset.
        const prov = this.props.providers.slice(0, this.state.offset);

        const providers = prov.map(provider =>
            <ProviderCard key={provider.Id} provider={provider} id={provider.Id}/>
        );

        return

            {providers}
            <Button   className="btn-success" onClick={() => this.loadMore()}>Last flere</Button>

    }
}

export default ProvidersList;
<|endoftext|>


<commit_before>/**
 * External dependencies
 */
import PropTypes from 'prop-types';

/**
 * WordPress dependencies
 */
import { useEffect, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import { Panel, Title, InputGroup, getCommonValue, SelectMenu } from './shared';

function StylePanel( { selectedElements, onSetProperties } ) {
	const textAlign = getCommonValue( selectedElements, 'textAlign' );
	const letterSpacing = getCommonValue( selectedElements, 'letterSpacing' );
	const lineHeight = getCommonValue( selectedElements, 'lineHeight' );
	const padding = getCommonValue( selectedElements, 'padding' );
	const [ state, setState ] = useState( { textAlign, letterSpacing, lineHeight, padding } );
	useEffect( () => {
		setState( { textAlign, letterSpacing, lineHeight, padding } );
	}, [ textAlign, letterSpacing, lineHeight, padding ] );
	const handleSubmit = ( evt ) => {
		onSetProperties( state );
		evt.preventDefault();
	};

	const alignmentOptions = [
		{ name: __( 'Default', 'amp' ), slug: '', thisValue: '' },
		{ name: __( 'Left', 'amp' ), slug: 'left', thisValue: 'left' },
		{ name: __( 'Right', 'amp' ), slug: 'right', thisValue: 'right' },
		{ name: __( 'Center', 'amp' ), slug: 'center', thisValue: 'center' },
		{ name: __( 'Justify', 'amp' ), slug: 'justify', thisValue: 'justify' },
	];

	return (
		<Panel onSubmit={ handleSubmit }>
			<Title>
				{ __( 'Style', 'amp' ) }
			</Title>
			<SelectMenu
				label={ __( 'Alignment', 'amp' ) }
				options={ alignmentOptions }
				isMultiple={ '' === textAlign }
				value={ state.textAlign }
				onChange={ ( value ) => setState( { ...state, textAlign: value } ) }
			/>
			<InputGroup
				label={ __( 'Line height', 'amp' ) }
				value={ state.lineHeight }
				isMultiple={ '' === lineHeight }
				onChange={ ( value ) => setState( { ...state, lineHeight: isNaN( value ) ? '' : parseFloat( value ) } ) }
				step="0.1"
			/>
			<InputGroup
				label={ __( 'Letter-spacing', 'amp' ) }
				value={ state.letterSpacing }
				isMultiple={ '' === letterSpacing }
				onChange={ ( value ) => setState( { ...state, letterSpacing: isNaN( value ) ? '' : value } ) }
				postfix="em"
				step="0.1"
			/>
			<InputGroup
				label={ __( 'Padding', 'amp' ) }
				value={ state.padding }
				isMultiple={ '' === padding }
				onChange={ ( value ) => setState( { ...state, padding: isNaN( value ) ? '' : value } ) }
				postfix="%"
			/>
		</Panel>
	);
}

StylePanel.propTypes = {
	selectedElements: PropTypes.array.isRequired,
	onSetProperties: PropTypes.func.isRequired,
};

export default StylePanel;
<commit_msg>Improve translations.<commit_after>/**
 * External dependencies
 */
import PropTypes from 'prop-types';

/**
 * WordPress dependencies
 */
import { useEffect, useState } from '@wordpress/element';
import { __, _x } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import { Panel, Title, InputGroup, getCommonValue, SelectMenu } from './shared';

function StylePanel( { selectedElements, onSetProperties } ) {
	const textAlign = getCommonValue( selectedElements, 'textAlign' );
	const letterSpacing = getCommonValue( selectedElements, 'letterSpacing' );
	const lineHeight = getCommonValue( selectedElements, 'lineHeight' );
	const padding = getCommonValue( selectedElements, 'padding' );
	const [ state, setState ] = useState( { textAlign, letterSpacing, lineHeight, padding } );
	useEffect( () => {
		setState( { textAlign, letterSpacing, lineHeight, padding } );
	}, [ textAlign, letterSpacing, lineHeight, padding ] );
	const handleSubmit = ( evt ) => {
		onSetProperties( state );
		evt.preventDefault();
	};

	const alignmentOptions = [
		{ name: __( 'Default', 'amp' ), slug: '', thisValue: '' },
		{ name: __( 'Left', 'amp' ), slug: 'left', thisValue: 'left' },
		{ name: __( 'Right', 'amp' ), slug: 'right', thisValue: 'right' },
		{ name: __( 'Center', 'amp' ), slug: 'center', thisValue: 'center' },
		{ name: __( 'Justify', 'amp' ), slug: 'justify', thisValue: 'justify' },
	];

	return (
		<Panel onSubmit={ handleSubmit }>
			<Title>
				{ __( 'Style', 'amp' ) }
			</Title>
			<SelectMenu
				label={ __( 'Alignment', 'amp' ) }
				options={ alignmentOptions }
				isMultiple={ '' === textAlign }
				value={ state.textAlign }
				onChange={ ( value ) => setState( { ...state, textAlign: value } ) }
			/>
			<InputGroup
				label={ __( 'Line height', 'amp' ) }
				value={ state.lineHeight }
				isMultiple={ '' === lineHeight }
				onChange={ ( value ) => setState( { ...state, lineHeight: isNaN( value ) ? '' : parseFloat( value ) } ) }
				step="0.1"
			/>
			<InputGroup
				label={ __( 'Letter-spacing', 'amp' ) }
				value={ state.letterSpacing }
				isMultiple={ '' === letterSpacing }
				onChange={ ( value ) => setState( { ...state, letterSpacing: isNaN( value ) ? '' : value } ) }
				postfix={ _x( 'em', 'em, the measurement of size', 'amp' ) }
				step="0.1"
			/>
			<InputGroup
				label={ __( 'Padding', 'amp' ) }
				value={ state.padding }
				isMultiple={ '' === padding }
				onChange={ ( value ) => setState( { ...state, padding: isNaN( value ) ? '' : value } ) }
				postfix={ _x( '%', 'Percentage', 'amp' ) }
			/>
		</Panel>
	);
}

StylePanel.propTypes = {
	selectedElements: PropTypes.array.isRequired,
	onSetProperties: PropTypes.func.isRequired,
};

export default StylePanel;
<|endoftext|>


<commit_before>import { basename } from 'path'

import * as dateFns from 'date-fns'
import dedent from 'dedent'
import * as R from 'ramda'
import * as React from 'react'
import { FormattedRelative } from 'react-intl'
import { Link } from 'react-router-dom'
import * as M from '@material-ui/core'

import { Crumb, copyWithoutSpaces, render as renderCrumbs } from 'components/BreadCrumbs'
import Sparkline from 'components/Sparkline'
import AsyncResult from 'utils/AsyncResult'
import * as AWS from 'utils/AWS'
import * as Config from 'utils/Config'
import Data from 'utils/Data'
import * as NamedRoutes from 'utils/NamedRoutes'
import * as SVG from 'utils/SVG'
import { linkStyle } from 'utils/StyledLink'
import parseSearch from 'utils/parseSearch'
import { getBreadCrumbs, up, decode } from 'utils/s3paths'
import { readableBytes, readableQuantity } from 'utils/string'

import Code from './Code'
import FilePreview from './FilePreview'
import Section from './Section'
import * as requests from './requests'
import { withSignedUrl } from './utils'

const getCrumbs = ({ bucket, path, urls }) =>
  R.chain(
    ({ label, path: segPath }) => [
      Crumb.Segment({ label, to: urls.bucketDir(bucket, segPath) }),
      Crumb.Sep(<> / </>),
    ],
    [{ label: bucket, path: '' }, ...getBreadCrumbs(up(path))],
  )

const useVersionInfoStyles = M.makeStyles(({ typography }) => ({
  version: {
    ...linkStyle,
    alignItems: 'center',
    display: 'inline-flex',
  },
  mono: {
    fontFamily: typography.monospace.fontFamily,
  },
  list: {
    width: 420,
  },
}))

function VersionInfo({ bucket, path, version }) {
  const s3req = AWS.S3.useRequest()
  const { urls } = NamedRoutes.use()

  const [anchor, setAnchor] = React.useState()
  const [opened, setOpened] = React.useState(false)
  const open = React.useCallback(() => setOpened(true), [])
  const close = React.useCallback(() => setOpened(false), [])

  const classes = useVersionInfoStyles()

  return (
    <>
      {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}

        {version ? (
          {version.substring(0, 12)}
        ) : (
          'latest'
        )}{' '}
        <M.Icon>expand_more</M.Icon>

      <Data fetch={requests.objectVersions} params={{ s3req, bucket, path }}>
        {R.pipe(
          AsyncResult.case({
            Ok: (versions) => (
              <M.List className={classes.list}>
                {versions.map((v) => (
                  <M.ListItem
                    key={v.id}
                    button
                    onClick={close}
                    selected={version ? v.id === version : v.isLatest}
                    component={Link}
                    to={urls.bucketFile(bucket, path, v.id)}
                  >
                    <M.ListItemText
                      primary={

                          <FormattedRelative value={v.lastModified} />
                          {' | '}
                          {v.size != null ? readableBytes(v.size) : 'DELETED'}
                          {v.isLatest && ' | latest'}

                      }
                      secondary={

                          {v.lastModified.toLocaleString()}

                          {v.id}

                      }
                    />
                    {!v.deleteMarker && (
                      <M.ListItemSecondaryAction>
                        {withSignedUrl({ bucket, key: path, version: v.id }, (url) => (
                          <M.IconButton href={url}>
                            <M.Icon>arrow_downward</M.Icon>
                          </M.IconButton>
                        ))}
                      </M.ListItemSecondaryAction>
                    )}
                  </M.ListItem>
                ))}
              </M.List>
            ),
            Err: () => (
              <M.List>
                <M.ListItem>
                  <M.ListItemIcon>
                    <M.Icon>error</M.Icon>
                  </M.ListItemIcon>
                  <M.Typography variant="body1">Error fetching versions</M.Typography>
                </M.ListItem>
              </M.List>
            ),
            _: () => (
              <M.List>
                <M.ListItem>
                  <M.ListItemIcon>
                    <M.CircularProgress size={24} />
                  </M.ListItemIcon>
                  <M.Typography variant="body1">Fetching versions</M.Typography>
                </M.ListItem>
              </M.List>
            ),
          }),
          (children) => (
            <M.Popover
              open={opened && !!anchor}
              anchorEl={anchor}
              onClose={close}
              anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
              transformOrigin={{ vertical: 'top', horizontal: 'center' }}
            >
              {children}
            </M.Popover>
          ),
        )}
      </Data>
    </>
  )
}

const AnnotationsBox = M.styled('div')(({ theme: t }) => ({
  background: M.colors.lightBlue[50],
  border: [[1, 'solid', M.colors.lightBlue[400]]],
  borderRadius: t.shape.borderRadius,
  fontFamily: t.typography.monospace.fontFamily,
  fontSize: t.typography.body2.fontSize,
  overflow: 'auto',
  padding: t.spacing(1),
  whiteSpace: 'pre',
  width: '100%',
}))

function Annotations({ bucket, path, version }) {
  const s3req = AWS.S3.useRequest()
  return (
    <Data fetch={requests.objectMeta} params={{ s3req, bucket, path, version }}>
      {AsyncResult.case({
        Ok: (meta) =>
          !!meta &&
          !R.isEmpty(meta) && (

              <AnnotationsBox>{JSON.stringify(meta, null, 2)}</AnnotationsBox>

          ),
        _: () => null,
      })}
    </Data>
  )
}

function Analytics({ analyticsBucket, bucket, path }) {
  const [cursor, setCursor] = React.useState(null)
  const s3req = AWS.S3.useRequest()
  const today = React.useMemo(() => new Date(), [])
  const formatDate = (date) =>
    dateFns.format(
      date,
      today.getFullYear() === date.getFullYear() ? `d MMM` : `d MMM yyyy`,
    )

  return (
    <Data
      fetch={requests.objectAccessCounts}
      params={{ s3req, analyticsBucket, bucket, path, today }}
    >
      {(res) => (

          {AsyncResult.case(
            {
              Ok: ({ counts, total }) => (
                <M.Box
                  display="flex"
                  width="100%"
                  justifyContent="space-between"
                  alignItems="center"
                >
                  <M.Box>
                    <M.Typography variant="h5">Downloads</M.Typography>
                    <M.Typography variant="h4" component="div">
                      {readableQuantity(cursor === null ? total : counts[cursor].value)}
                    </M.Typography>
                    <M.Typography variant="overline" component="span">
                      {cursor === null
                        ? `${counts.length} days`
                        : formatDate(counts[cursor].date)}
                    </M.Typography>
                  </M.Box>
                  <M.Box width="calc(100% - 7rem)">
                    <Sparkline
                      data={R.pluck('value', counts)}
                      onCursor={setCursor}
                      width={1000}
                      height={60}
                      stroke={SVG.Paint.Server(
                        <linearGradient x2="0" y2="100%" gradientUnits="userSpaceOnUse">
                          <stop offset="0" stopColor={M.colors.blueGrey[800]} />
                          <stop offset="100%" stopColor={M.colors.blueGrey[100]} />
                        </linearGradient>,
                      )}
                    />
                  </M.Box>
                </M.Box>
              ),
              Err: () => <M.Typography>No analytics available</M.Typography>,
              _: () => <M.CircularProgress />,
            },
            res,
          )}

      )}
    </Data>
  )
}

const useStyles = M.makeStyles((t) => ({
  crumbs: {
    ...t.typography.body1,
    maxWidth: '100%',
    overflowWrap: 'break-word',
  },
  name: {
    ...t.typography.body1,
    maxWidth: 'calc(100% - 160px)',
    overflowWrap: 'break-word',
    [t.breakpoints.down('xs')]: {
      maxWidth: 'calc(100% - 40px)',
    },
  },
  topBar: {
    alignItems: 'flex-end',
    display: 'flex',
    marginBottom: t.spacing(2),
  },
  at: {
    color: t.palette.text.secondary,
  },
  spacer: {
    flexGrow: 1,
  },
  button: {
    flexShrink: 0,
    marginBottom: -3,
    marginTop: -3,
  },
}))

export default function File({
  match: {
    params: { bucket, path: encodedPath },
  },
  location,
}) {
  const { version } = parseSearch(location.search)
  const classes = useStyles()
  const { urls } = NamedRoutes.use()
  const { analyticsBucket } = Config.useConfig()
  const t = M.useTheme()
  const xs = M.useMediaQuery(t.breakpoints.down('xs'))

  const path = decode(encodedPath)

  const code = dedent`
    import quilt3
    b = quilt3.Bucket("s3://${bucket}")
    b.fetch("${path}", "./${basename(path)}")
  `

  return (
    <M.Box pt={2} pb={4}>

        {renderCrumbs(getCrumbs({ bucket, path, urls }))}

          {basename(path)} @

          <VersionInfo bucket={bucket} path={path} version={version} />

        {withSignedUrl({ bucket, key: path, version }, (url) =>
          xs ? (
            <M.IconButton
              className={classes.button}
              href={url}
              edge="end"
              size="small"
              download
            >
              <M.Icon>arrow_downward</M.Icon>
            </M.IconButton>
          ) : (
            <M.Button
              href={url}
              className={classes.button}
              variant="outlined"
              size="small"
              startIcon={<M.Icon>arrow_downward</M.Icon>}
              download
            >
              Download file
            </M.Button>
          ),
        )}

        {code}

      {!!analyticsBucket && <Analytics {...{ analyticsBucket, bucket, path }} />}

        <FilePreview handle={{ bucket, key: path, version }} />

      <Annotations bucket={bucket} path={path} version={version} />
    </M.Box>
  )
}
<commit_msg>catalog/app/containers/Bucket/File.js: use single quotes instead of backticks<commit_after>import { basename } from 'path'

import * as dateFns from 'date-fns'
import dedent from 'dedent'
import * as R from 'ramda'
import * as React from 'react'
import { FormattedRelative } from 'react-intl'
import { Link } from 'react-router-dom'
import * as M from '@material-ui/core'

import { Crumb, copyWithoutSpaces, render as renderCrumbs } from 'components/BreadCrumbs'
import Sparkline from 'components/Sparkline'
import AsyncResult from 'utils/AsyncResult'
import * as AWS from 'utils/AWS'
import * as Config from 'utils/Config'
import Data from 'utils/Data'
import * as NamedRoutes from 'utils/NamedRoutes'
import * as SVG from 'utils/SVG'
import { linkStyle } from 'utils/StyledLink'
import parseSearch from 'utils/parseSearch'
import { getBreadCrumbs, up, decode } from 'utils/s3paths'
import { readableBytes, readableQuantity } from 'utils/string'

import Code from './Code'
import FilePreview from './FilePreview'
import Section from './Section'
import * as requests from './requests'
import { withSignedUrl } from './utils'

const getCrumbs = ({ bucket, path, urls }) =>
  R.chain(
    ({ label, path: segPath }) => [
      Crumb.Segment({ label, to: urls.bucketDir(bucket, segPath) }),
      Crumb.Sep(<> / </>),
    ],
    [{ label: bucket, path: '' }, ...getBreadCrumbs(up(path))],
  )

const useVersionInfoStyles = M.makeStyles(({ typography }) => ({
  version: {
    ...linkStyle,
    alignItems: 'center',
    display: 'inline-flex',
  },
  mono: {
    fontFamily: typography.monospace.fontFamily,
  },
  list: {
    width: 420,
  },
}))

function VersionInfo({ bucket, path, version }) {
  const s3req = AWS.S3.useRequest()
  const { urls } = NamedRoutes.use()

  const [anchor, setAnchor] = React.useState()
  const [opened, setOpened] = React.useState(false)
  const open = React.useCallback(() => setOpened(true), [])
  const close = React.useCallback(() => setOpened(false), [])

  const classes = useVersionInfoStyles()

  return (
    <>
      {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}

        {version ? (
          {version.substring(0, 12)}
        ) : (
          'latest'
        )}{' '}
        <M.Icon>expand_more</M.Icon>

      <Data fetch={requests.objectVersions} params={{ s3req, bucket, path }}>
        {R.pipe(
          AsyncResult.case({
            Ok: (versions) => (
              <M.List className={classes.list}>
                {versions.map((v) => (
                  <M.ListItem
                    key={v.id}
                    button
                    onClick={close}
                    selected={version ? v.id === version : v.isLatest}
                    component={Link}
                    to={urls.bucketFile(bucket, path, v.id)}
                  >
                    <M.ListItemText
                      primary={

                          <FormattedRelative value={v.lastModified} />
                          {' | '}
                          {v.size != null ? readableBytes(v.size) : 'DELETED'}
                          {v.isLatest && ' | latest'}

                      }
                      secondary={

                          {v.lastModified.toLocaleString()}

                          {v.id}

                      }
                    />
                    {!v.deleteMarker && (
                      <M.ListItemSecondaryAction>
                        {withSignedUrl({ bucket, key: path, version: v.id }, (url) => (
                          <M.IconButton href={url}>
                            <M.Icon>arrow_downward</M.Icon>
                          </M.IconButton>
                        ))}
                      </M.ListItemSecondaryAction>
                    )}
                  </M.ListItem>
                ))}
              </M.List>
            ),
            Err: () => (
              <M.List>
                <M.ListItem>
                  <M.ListItemIcon>
                    <M.Icon>error</M.Icon>
                  </M.ListItemIcon>
                  <M.Typography variant="body1">Error fetching versions</M.Typography>
                </M.ListItem>
              </M.List>
            ),
            _: () => (
              <M.List>
                <M.ListItem>
                  <M.ListItemIcon>
                    <M.CircularProgress size={24} />
                  </M.ListItemIcon>
                  <M.Typography variant="body1">Fetching versions</M.Typography>
                </M.ListItem>
              </M.List>
            ),
          }),
          (children) => (
            <M.Popover
              open={opened && !!anchor}
              anchorEl={anchor}
              onClose={close}
              anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
              transformOrigin={{ vertical: 'top', horizontal: 'center' }}
            >
              {children}
            </M.Popover>
          ),
        )}
      </Data>
    </>
  )
}

const AnnotationsBox = M.styled('div')(({ theme: t }) => ({
  background: M.colors.lightBlue[50],
  border: [[1, 'solid', M.colors.lightBlue[400]]],
  borderRadius: t.shape.borderRadius,
  fontFamily: t.typography.monospace.fontFamily,
  fontSize: t.typography.body2.fontSize,
  overflow: 'auto',
  padding: t.spacing(1),
  whiteSpace: 'pre',
  width: '100%',
}))

function Annotations({ bucket, path, version }) {
  const s3req = AWS.S3.useRequest()
  return (
    <Data fetch={requests.objectMeta} params={{ s3req, bucket, path, version }}>
      {AsyncResult.case({
        Ok: (meta) =>
          !!meta &&
          !R.isEmpty(meta) && (

              <AnnotationsBox>{JSON.stringify(meta, null, 2)}</AnnotationsBox>

          ),
        _: () => null,
      })}
    </Data>
  )
}

function Analytics({ analyticsBucket, bucket, path }) {
  const [cursor, setCursor] = React.useState(null)
  const s3req = AWS.S3.useRequest()
  const today = React.useMemo(() => new Date(), [])
  const formatDate = (date) =>
    dateFns.format(
      date,
      today.getFullYear() === date.getFullYear() ? 'd MMM' : 'd MMM yyyy',
    )

  return (
    <Data
      fetch={requests.objectAccessCounts}
      params={{ s3req, analyticsBucket, bucket, path, today }}
    >
      {(res) => (

          {AsyncResult.case(
            {
              Ok: ({ counts, total }) => (
                <M.Box
                  display="flex"
                  width="100%"
                  justifyContent="space-between"
                  alignItems="center"
                >
                  <M.Box>
                    <M.Typography variant="h5">Downloads</M.Typography>
                    <M.Typography variant="h4" component="div">
                      {readableQuantity(cursor === null ? total : counts[cursor].value)}
                    </M.Typography>
                    <M.Typography variant="overline" component="span">
                      {cursor === null
                        ? `${counts.length} days`
                        : formatDate(counts[cursor].date)}
                    </M.Typography>
                  </M.Box>
                  <M.Box width="calc(100% - 7rem)">
                    <Sparkline
                      data={R.pluck('value', counts)}
                      onCursor={setCursor}
                      width={1000}
                      height={60}
                      stroke={SVG.Paint.Server(
                        <linearGradient x2="0" y2="100%" gradientUnits="userSpaceOnUse">
                          <stop offset="0" stopColor={M.colors.blueGrey[800]} />
                          <stop offset="100%" stopColor={M.colors.blueGrey[100]} />
                        </linearGradient>,
                      )}
                    />
                  </M.Box>
                </M.Box>
              ),
              Err: () => <M.Typography>No analytics available</M.Typography>,
              _: () => <M.CircularProgress />,
            },
            res,
          )}

      )}
    </Data>
  )
}

const useStyles = M.makeStyles((t) => ({
  crumbs: {
    ...t.typography.body1,
    maxWidth: '100%',
    overflowWrap: 'break-word',
  },
  name: {
    ...t.typography.body1,
    maxWidth: 'calc(100% - 160px)',
    overflowWrap: 'break-word',
    [t.breakpoints.down('xs')]: {
      maxWidth: 'calc(100% - 40px)',
    },
  },
  topBar: {
    alignItems: 'flex-end',
    display: 'flex',
    marginBottom: t.spacing(2),
  },
  at: {
    color: t.palette.text.secondary,
  },
  spacer: {
    flexGrow: 1,
  },
  button: {
    flexShrink: 0,
    marginBottom: -3,
    marginTop: -3,
  },
}))

export default function File({
  match: {
    params: { bucket, path: encodedPath },
  },
  location,
}) {
  const { version } = parseSearch(location.search)
  const classes = useStyles()
  const { urls } = NamedRoutes.use()
  const { analyticsBucket } = Config.useConfig()
  const t = M.useTheme()
  const xs = M.useMediaQuery(t.breakpoints.down('xs'))

  const path = decode(encodedPath)

  const code = dedent`
    import quilt3
    b = quilt3.Bucket("s3://${bucket}")
    b.fetch("${path}", "./${basename(path)}")
  `

  return (
    <M.Box pt={2} pb={4}>

        {renderCrumbs(getCrumbs({ bucket, path, urls }))}

          {basename(path)} @

          <VersionInfo bucket={bucket} path={path} version={version} />

        {withSignedUrl({ bucket, key: path, version }, (url) =>
          xs ? (
            <M.IconButton
              className={classes.button}
              href={url}
              edge="end"
              size="small"
              download
            >
              <M.Icon>arrow_downward</M.Icon>
            </M.IconButton>
          ) : (
            <M.Button
              href={url}
              className={classes.button}
              variant="outlined"
              size="small"
              startIcon={<M.Icon>arrow_downward</M.Icon>}
              download
            >
              Download file
            </M.Button>
          ),
        )}

        {code}

      {!!analyticsBucket && <Analytics {...{ analyticsBucket, bucket, path }} />}

        <FilePreview handle={{ bucket, key: path, version }} />

      <Annotations bucket={bucket} path={path} version={version} />
    </M.Box>
  )
}
<|endoftext|>


<commit_before>var Stations = (function() {
  return Backbone.Collection.extend({
    model: Station,
    url: 'http://sensorweb.demo.52north.org/sensorwebclient-webapp-stable/api/v1/services/PEGELONLINE/stations.json?show=expanded',

    initialize: function(){

    },

    getByCoordinates: function(coord) {
      coordArray = [].concat( coord );

      newCollection = new Stations();
      this.each(function(elem) {
        var c = elem.get('geometry').coordinates;
        if (c[0] == coord[0] && c[1] == coord[1]) {
          newCollection.add(elem);
        }
      });

      return newCollection;
    }
  });
})();<commit_msg>removes dead link<commit_after>var Stations = (function() {
  return Backbone.Collection.extend({
    model: Station,

    initialize: function(){

    },

    getByCoordinates: function(coord) {
      coordArray = [].concat( coord );

      newCollection = new Stations();
      this.each(function(elem) {
        var c = elem.get('geometry').coordinates;
        if (c[0] == coord[0] && c[1] == coord[1]) {
          newCollection.add(elem);
        }
      });

      return newCollection;
    }
  });
})();<|endoftext|>


<commit_before>// --
// Core.UI.js - provides all UI functions
// Copyright (C) 2001-2010 OTRS AG, http://otrs.org/\n";
// --
// $Id: Core.UI.js,v 1.1 2010-06-04 11:19:31 mn Exp $
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --

"use strict";

/**
 * @namespace
 * @description
 *      This is the global namespace
 */
var Core = Core || {};

/**
 * @namespace
 * @exports TargetNS as Core.UI
 * @description
 *      This namespace contains all UI functions
 */
Core.UI = (function (TargetNS) {

    var IDGeneratorCount = 0;

    /**
     * @function
     * @description
     *      This function is used for the adjustment of the table head of OverviewSmall
     * @param {jQueryObject} $THead the thead thats th's should be adjusted
     * @param {jQueryObject} $TBody the tbody
     * @return nothing
     */
    TargetNS.AdjustTableHead = function ($THead, $TBody) {
        function CalculateColumnDimensions($TableHeadElement, $TableBodyElement) {
            var TableHeadWidth,
                TableHeadPadding,
                TableBodyWidth,
                TableBodyPadding;

            TableHeadWidth = $TableHeadElement.width();
            TableHeadPadding = parseInt($TableHeadElement.css('padding-left'), 10) + parseInt($TableHeadElement.css('padding-right'), 10);

            TableBodyWidth = $TableBodyElement.width();
            TableBodyPadding = parseInt($TableBodyElement.css('padding-left'), 10) + parseInt($TableBodyElement.css('padding-right'), 10);

            return {
                HeadWidth:      TableHeadWidth,
                HeadPadding:    TableHeadPadding,
                BodyWidth:      TableBodyWidth,
                BodyPadding:    TableBodyPadding
            };
        }

        var $TableHead = $THead.find('tr th'),
            $TableHeadElement,
            $TableBody = $TBody.find('tr:first td'),
            $TableBodyElement,
            $OverviewHeaderSmall = $THead.closest('.OverviewHeaderSmall'),
            $ActionRow = $THead.closest('.ActionRow'),
            TableOriginalWidth,
            Dimensions = {},
            ColumnNewWidth,
            Adjustment = {},
            I;

        // Restore original width of table parents (after resizing of window)
        if ($TBody.closest('div.Scroller').length) {
            $TBody.closest('div.Scroller').width('auto').parents('div:first').width('auto');
        }

        // Calculate the width of the table frame
        TableOriginalWidth = $TBody.closest('table').width();
        // Set table head to same width
        $THead.parents('table').width(TableOriginalWidth + 'px');

        // First round: adjust obvious differences
        for (I = 0; I < $TableBody.size(); I++) {
            $TableHeadElement = $TableHead.eq(I);
            $TableBodyElement = $TableBody.eq(I);

            // Skip column, if column has class "Fixed"
            if (!($TableHeadElement.hasClass('Fixed') || $TableBodyElement.hasClass('Fixed'))) {
                // Calculate the column dimensions
                Dimensions = CalculateColumnDimensions($TableHeadElement, $TableBodyElement);

                // The width of the new Head column
                ColumnNewWidth = Dimensions.BodyWidth + Dimensions.BodyPadding - Dimensions.HeadPadding;
                $TableHeadElement.width(ColumnNewWidth + 'px');

                // If now the head column is bigger than the body column, there's more text in the header than in the body
                // and we have to adjust the body columns
                // so calculate again!
                Dimensions = CalculateColumnDimensions($TableHeadElement, $TableBodyElement);

                // If header column is larger, save new body column width in array for later adjustment
                if ((Dimensions.HeadWidth + Dimensions.HeadPadding) > (Dimensions.BodyWidth + Dimensions.BodyPadding)) {
                    ColumnNewWidth = Dimensions.HeadWidth + Dimensions.HeadPadding - Dimensions.BodyPadding;
                    Adjustment[I] = ColumnNewWidth;
                }
            }
        }

        // Second round: Adjust the body columns as calculated before
        for (I = 0; I < $TableBody.size(); I++) {
            if (Adjustment[I]) {
                $TableBody.eq(I).width(Adjustment[I] + 'px');
            }
        }
    };

    /**
     * @function
     * @description
     *      This function makes the control div static if it hits the top
     * @param {jQueryObject} $Control the control div
     * @return nothing
     */
    TargetNS.StaticTableControl = function ($Control) {
        var Offset = $Control.offset().top,
            Height = $Control.height();

        $(window).scroll(function (event) {
            var y = $(this).scrollTop(),
                Height = $Control.height();

            // TODO: Cache the class and css changes

            if (y >= Offset) {
                $Control.addClass('Fixed');
                $Control.nextAll('.Overview:first').css('margin-top', Height);
            }
            else {
                $Control.removeClass('Fixed');
                $Control.nextAll('.Overview:first').css('margin-top', 0);
            }
        });
    };

    /**
     * @function
     * @description
     *      This function initializes the toggle mechanism for all widgets with a WidgetAction toggle icon
     * @return nothing
     */
    TargetNS.InitWidgetActionToggle = function () {
        $(".WidgetAction.Toggle > a")
            .each(function () {
                var $WidgetElement = $(this).closest("div.Header").parent('div');
                    ContentDivID = TargetNS.GetID($WidgetElement.children('.Content'));
                $(this)
                    .attr('aria-controls', ContentDivID)
                    .attr('aria-expanded', $WidgetElement.hasClass('Expanded'));
            })
            .unbind('click.WidgetToggle')
            .bind('click.WidgetToggle', function () {
                function ToggleWidget() {
                    $WidgetElement
                        .toggleClass('Collapsed')
                        .toggleClass('Expanded')
                        .end()
                        .end()
                        .attr('aria-expanded', $(this).closest("div.Header").parent('div').hasClass('Expanded'));
                }

                var $WidgetElement = $(this).closest("div.Header").parent('div'),
                    Animate = $WidgetElement.hasClass('Animate'),
                    $that = $(this);

                if (Animate && Core.Config.Get('AnimationEnabled')) {
                    $WidgetElement.addClass('AnimationRunning').find('.Content').slideToggle("slow", function() {
                        ToggleWidget();
                        $WidgetElement.removeClass('AnimationRunning');
                    });
                } else {
                    ToggleWidget();
                }

                return false;
            });
    };

    /**
     * @function
     * @description
     *      This function initializes the close buttons for the message boxes that show server messages
     * @return nothing
     */
    TargetNS.InitMessageBoxClose = function () {
        $(".MessageBox > a.Close")
            .unbind('click.MessageBoxClose')
            .bind('click.MessageBoxClose', function (Event) {
                $(this).parent().remove();
                Event.preventDefault();
            });
    };

    /**
     * @function
     * @description
     *      This function adds special not valid attributes to HTML via javascript
     * @return nothing
     */
    TargetNS.ProcessTagAttributeClasses = function () {
        $('.AutocompleteOff')
            .attr('autocomplete', 'off');
    };

    /**
     * @function
     * @description
     *      Returns the ID of the Element and creates one for it if nessessary.
     * @param {jQueryObject} Element
     * @return {String} ID
     */
    TargetNS.GetID = function ($Element) {
        var ID = $Element.attr('id');
        if (!ID) {
            $Element.attr('id', ID = 'OTRS_UI_AutogeneratedID_' + IDGeneratorCount++);
            // Debug this
            Core.Debug.Log('Auto-generated required ID ' + ID + ' for element', $Element);
        }
        return ID;
    };

    /**
     * @function
     * @description
     *      This function is the wrapper for registering an event on an HTML element.
     * @param {String} EventType The event type (click, change, ...)
     * @param {jQueryObject} $Element the element(s) on which the event is triggered
     * @param {Function} EventFunction The function which should be executed on event (gets Parameter Event)
     */
    TargetNS.RegisterEvent = function (EventType, $Element, EventFunction) {
        if (isJQueryObject($Element) && $Element.length && $.isFunction(EventFunction)) {
            $Element.bind(EventType, EventFunction);
        }
    };

    /**
     * @function
     * @description
     *      This function is the wrapper for registering an live event on an HTML element.
     * @param {String} EventType The event type (click, change, ...)
     * @param {jQueryObject} $Element the element(s) on which the event is triggered
     * @param {Function} EventFunction The function which should be executed on event (gets Parameter Event)
     */
    TargetNS.RegisterLiveEvent = function (EventType, $Element, EventFunction) {
        if (isJQueryObject($Element) && $Element.length && $.isFunction(EventFunction)) {
            $Element.live(EventType, EventFunction);
        }
    };

    /**
     * @function
     * @description
     *      This functions toggles two Containers with a nice slide effect.
     * @param {jQueryObject} $Element1 First container element
     * @param {jQueryObject} $Element1 Second container element
     */
    TargetNS.ToggleTwoContainer = function ($Element1, $Element2) {
        if (isJQueryObject($Element1, $Element2) && $Element1.length && $Element2.length) {
            $Element1.slideToggle('fast', function () {
                $Element2.slideToggle('fast');
            });
        }
    };

    TargetNS.RegisterToggleTwoContainer = function ($ClickedElement, $Element1, $Element2) {
        if (isJQueryObject($ClickedElement) && $ClickedElement.length) {
            $ClickedElement.click(function () {
                TargetNS.ToggleTwoContainer($Element1, $Element2);
                return false;
            });
        }
    };

    return TargetNS;
}(Core.UI || {}));<commit_msg>Improved fixed table header function.<commit_after>// --
// Core.UI.js - provides all UI functions
// Copyright (C) 2001-2010 OTRS AG, http://otrs.org/\n";
// --
// $Id: Core.UI.js,v 1.2 2010-06-22 15:47:19 fn Exp $
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --

"use strict";

/**
 * @namespace
 * @description
 *      This is the global namespace
 */
var Core = Core || {};

/**
 * @namespace
 * @exports TargetNS as Core.UI
 * @description
 *      This namespace contains all UI functions
 */
Core.UI = (function (TargetNS) {

    var IDGeneratorCount = 0;

    /**
     * @function
     * @description
     *      This function is used for the adjustment of the table head of OverviewSmall
     * @param {jQueryObject} $THead the thead thats th's should be adjusted
     * @param {jQueryObject} $TBody the tbody
     * @return nothing
     */
    TargetNS.initTableHead = function ($THead, $TBody) {
        var TBodyWidth = $TBody.outerWidth();
        // set the thead-width to the tbody-width (is not the same because of the scrollbar in the tbody)
        $THead.width(TBodyWidth + 'px');
        // initial adjustion of the tablehead elements
        TargetNS.AdjustTableHead($THead, $TBody);
    };

    /**
     * @function
     * @description
     *      This function is used for the adjustment of the table head of OverviewSmall
     * @param {jQueryObject} $Elements object containing elements (here: table elements)
     * @return Array containing outer-widths (width+padding+border) of the given $Elements
     */
    function GetWidths($Elements, Position) {
        var Storage = new Array(),
            Size = $Elements.length;
        if(Position){
            return $Elements.eq(Position).outerWidth();
        }
        else {
            for(var I = 0;I < Size;I++) {
                Storage[I] = $Elements.eq(I).outerWidth();
            };
            return Storage;
        }
    };

    TargetNS.AdjustTableHead = function ($THead, $TBody) {
        var $THeadElements = $THead.find('tr th'),
            THeadElementWidth,
            $TBodyElements = $TBody.find('tr:first td'),
            TBodyWidths = GetWidths($TBodyElements),
            TableSize = $THeadElements.size(),
            Adjusted = true,
            Adjustments = new Array(),
            I;

        // First round: adjust obvious differences
        for (I = 0; I < TableSize; I++) {
            $THeadElements.eq(I).width(TBodyWidths[I] + 'px');
            THeadElementWidth = GetWidths($THeadElements, I);
            if(THeadElementWidth > TBodyWidths[I]){
                Adjustments[I] = THeadElementWidth;
                Adjusted = false;
            }
        }

        // Second round: Adjust the body columns as calculated before
        if(!Adjusted){
            for (I = 0; I < TableSize; I++) {
                if (Adjustments[I]) {
                    $TBodyElements.eq(I).width(Adjustments[I] + 'px');
                }
            };
            TargetNS.AdjustTableHead($THead, $TBody);
        }
    };

    /**
     * @function
     * @description
     *      This function makes the control div static if it hits the top
     * @param {jQueryObject} $Control the control div
     * @return nothing
     */
    TargetNS.StaticTableControl = function ($Control) {
        var Offset = $Control.offset().top,
            Height = $Control.height();

        $(window).scroll(function (event) {
            var y = $(this).scrollTop(),
                Height = $Control.height();

            // TODO: Cache the class and css changes

            if (y >= Offset) {
                $Control.addClass('Fixed');
                $Control.nextAll('.Overview:first').css('margin-top', Height);
            }
            else {
                $Control.removeClass('Fixed');
                $Control.nextAll('.Overview:first').css('margin-top', 0);
            }
        });
    };

    /**
     * @function
     * @description
     *      This function initializes the toggle mechanism for all widgets with a WidgetAction toggle icon
     * @return nothing
     */
    TargetNS.InitWidgetActionToggle = function () {
        $(".WidgetAction.Toggle > a")
            .each(function () {
                var $WidgetElement = $(this).closest("div.Header").parent('div');
                    ContentDivID = TargetNS.GetID($WidgetElement.children('.Content'));
                $(this)
                    .attr('aria-controls', ContentDivID)
                    .attr('aria-expanded', $WidgetElement.hasClass('Expanded'));
            })
            .unbind('click.WidgetToggle')
            .bind('click.WidgetToggle', function () {
                function ToggleWidget() {
                    $WidgetElement
                        .toggleClass('Collapsed')
                        .toggleClass('Expanded')
                        .end()
                        .end()
                        .attr('aria-expanded', $(this).closest("div.Header").parent('div').hasClass('Expanded'));
                }

                var $WidgetElement = $(this).closest("div.Header").parent('div'),
                    Animate = $WidgetElement.hasClass('Animate'),
                    $that = $(this);

                if (Animate && Core.Config.Get('AnimationEnabled')) {
                    $WidgetElement.addClass('AnimationRunning').find('.Content').slideToggle("slow", function() {
                        ToggleWidget();
                        $WidgetElement.removeClass('AnimationRunning');
                    });
                } else {
                    ToggleWidget();
                }

                return false;
            });
    };

    /**
     * @function
     * @description
     *      This function initializes the close buttons for the message boxes that show server messages
     * @return nothing
     */
    TargetNS.InitMessageBoxClose = function () {
        $(".MessageBox > a.Close")
            .unbind('click.MessageBoxClose')
            .bind('click.MessageBoxClose', function (Event) {
                $(this).parent().remove();
                Event.preventDefault();
            });
    };

    /**
     * @function
     * @description
     *      This function adds special not valid attributes to HTML via javascript
     * @return nothing
     */
    TargetNS.ProcessTagAttributeClasses = function () {
        $('.AutocompleteOff')
            .attr('autocomplete', 'off');
    };

    /**
     * @function
     * @description
     *      Returns the ID of the Element and creates one for it if nessessary.
     * @param {jQueryObject} Element
     * @return {String} ID
     */
    TargetNS.GetID = function ($Element) {
        var ID = $Element.attr('id');
        if (!ID) {
            $Element.attr('id', ID = 'OTRS_UI_AutogeneratedID_' + IDGeneratorCount++);
            // Debug this
            Core.Debug.Log('Auto-generated required ID ' + ID + ' for element', $Element);
        }
        return ID;
    };

    /**
     * @function
     * @description
     *      This function is the wrapper for registering an event on an HTML element.
     * @param {String} EventType The event type (click, change, ...)
     * @param {jQueryObject} $Element the element(s) on which the event is triggered
     * @param {Function} EventFunction The function which should be executed on event (gets Parameter Event)
     */
    TargetNS.RegisterEvent = function (EventType, $Element, EventFunction) {
        if (isJQueryObject($Element) && $Element.length && $.isFunction(EventFunction)) {
            $Element.bind(EventType, EventFunction);
        }
    };

    /**
     * @function
     * @description
     *      This function is the wrapper for registering an live event on an HTML element.
     * @param {String} EventType The event type (click, change, ...)
     * @param {jQueryObject} $Element the element(s) on which the event is triggered
     * @param {Function} EventFunction The function which should be executed on event (gets Parameter Event)
     */
    TargetNS.RegisterLiveEvent = function (EventType, $Element, EventFunction) {
        if (isJQueryObject($Element) && $Element.length && $.isFunction(EventFunction)) {
            $Element.live(EventType, EventFunction);
        }
    };

    /**
     * @function
     * @description
     *      This functions toggles two Containers with a nice slide effect.
     * @param {jQueryObject} $Element1 First container element
     * @param {jQueryObject} $Element1 Second container element
     */
    TargetNS.ToggleTwoContainer = function ($Element1, $Element2) {
        if (isJQueryObject($Element1, $Element2) && $Element1.length && $Element2.length) {
            $Element1.slideToggle('fast', function () {
                $Element2.slideToggle('fast');
            });
        }
    };

    TargetNS.RegisterToggleTwoContainer = function ($ClickedElement, $Element1, $Element2) {
        if (isJQueryObject($ClickedElement) && $ClickedElement.length) {
            $ClickedElement.click(function () {
                TargetNS.ToggleTwoContainer($Element1, $Element2);
                return false;
            });
        }
    };

    return TargetNS;
}(Core.UI || {}));<|endoftext|>


<commit_before>/**
 * Created by apizzimenti on 11/12/16.
 */

/**
 * @author Anthony Pizzimenti
 *
 * @desc Removes all duplicates from the specified array.
 *
 * @param array {Array} Array to be cleaned.
 * @param check {boolean} Strict types with comparisons?
 *
 * @returns {Array}
 *
 * @this f
 *
 * @example
 */

f.clean = function (array, check) {

    // sort array so index checking is easier
    quicksort(array, 0, array.length - 1);

    // initialize indexer
    var i = 0;

    while (i < array.length) {

        if (f.equalWithCheck(a[i], a[i + 1], check)) {
            // if adjacent indices are the same, remove next index and don't increase index
            f.removeIndex(array, i + 1);
            continue;
        }

        i++;
    }

    return array;
};
<commit_msg>add example to docs<commit_after>/**
 * Created by apizzimenti on 11/12/16.
 */

/**
 * @author Anthony Pizzimenti
 *
 * @desc Removes all duplicates from the specified array.
 *
 * @param array {Array} Array to be cleaned.
 * @param check {boolean} Strict types with comparisons?
 *
 * @returns {Array}
 *
 * @this f
 *
 * @example
 *
 * var a = [1, 2, 3, 4, 5, "2", "3"];
 * f.clean(a)
 * // a = [1, "2", "3", 4, 5]
 *
 * var b = [1, 2, 3, 4, 5, "2", "3"];
 * f.clean(b, true);
 * // b = [1, "2", 2, 3, "3", 4, 5]
 */

f.clean = function (array, check) {

    // sort array so index checking is easier
    quicksort(array, 0, array.length - 1);

    // initialize indexer
    var i = 0;

    while (i < array.length) {

        if (f.equalWithCheck(a[i], a[i + 1], check)) {
            // if adjacent indices are the same, remove next index and don't increase index
            f.removeIndex(array, i + 1);
            continue;
        }

        i++;
    }

    return array;
};
<|endoftext|>


<commit_before>

/*!
 * Stylus - plugin - url
 * Copyright(c) 2010 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var utils = require('../utils')
  , nodes = require('../nodes')
  , fs = require('fs')
  , path = require('path')
  , xml2js = require('xml2js');

/**
 * Initialize a new `Image` with the given `ctx` and `path.
 *
 * @param {Evaluator} ctx
 * @param {String} path
 * @api private
 */

var Image = module.exports = function Image(ctx, path) {
  this.ctx = ctx;
  this.path = utils.lookup(path, ctx.paths);
  if (!this.path) throw new Error('failed to locate file ' + path);
};

/**
 * Open the image for reading.
 *
 * @api private
 */

Image.prototype.open = function(){
  this.fd = fs.openSync(this.path, 'r');
  this.length = fs.fstatSync(this.fd).size;
  this.extname = path.extname(this.path).slice(1);
};

/**
 * Close the file.
 *
 * @api private
 */

Image.prototype.close = function(){
  if (this.fd) fs.closeSync(this.fd);
};

/**
 * Return the type of image, supports:
 *
 *  - gif
 *  - png
 *  - jpeg
 *  - svg
 *
 * @return {String}
 * @api private
 */

Image.prototype.type = function(){
  var type
    , buf = new Buffer(4);

  fs.readSync(this.fd, buf, 0, 4, 0);

  // GIF
  if (0x47 == buf[0] && 0x49 == buf[1] && 0x46 == buf[2]) type = 'gif';

  // PNG
  else if (0x50 == buf[1] && 0x4E == buf[2] && 0x47 == buf[3]) type = 'png';

  // JPEG
  else if (0xff == buf[0] && 0xd8 == buf[1]) type = 'jpeg';

  // SVG
  else if ('svg' == this.extname) type = this.extname;

  return type;
};

/**
 * Return image dimensions `[width, height]`.
 *
 * @return {Array}
 * @api private
 */

Image.prototype.size = function(){
  var type = this.type()
    , width
    , height
    , buf
    , offset
    , blockSize;

  function uint16(b) { return b[1] << 8 | b[0]; }
  function uint32(b) { return b[0] << 24 | b[1] << 16 | b[2] << 8 | b[3]; }

  // Determine dimensions
  switch (type) {
    case 'jpeg':
      buf = new Buffer(this.length);
      fs.readSync(this.fd, buf, 0, this.length);
      offset = 4;
      blockSize = buf[offset] << 8 | buf[offset + 1];

      while (offset < this.length) {
        offset += blockSize;
        if (offset >= this.length || 0xff != buf[offset]) break;
        if (0xc0 == buf[offset + 1] ) {
          height = buf[offset + 5] << 8 | buf[offset + 6];
          width = buf[offset + 7] << 8 | buf[offset + 8];
        } else {
          offset += 2;
          blockSize = buf[offset] << 8 | buf[offset + 1];
        }
      }
      break;
    case 'png':
      buf = new Buffer(8);
      // IHDR chunk width / height uint32_t big-endian
      fs.readSync(this.fd, buf, 0, 8, 16);
      width = uint32(buf);
      height = uint32(buf.slice(4, 8));
      break;
    case 'gif':
      buf = new Buffer(4);
      // width / height uint16_t little-endian
      fs.readSync(this.fd, buf, 0, 4, 6);
      width = uint16(buf);
      height = uint16(buf.slice(2, 4));
      break;
    case 'svg':
      buf = new Buffer(this.length);
      fs.readSync(this.fd, buf, 0, this.length);
      buf = buf.toString('utf8');
      xml2js.parseString(buf, function(err, res) {
        if (res.svg && res.svg.$) {
          width = parseInt(res.svg.$.width, 10);
          height = parseInt(res.svg.$.height, 10);
        }
      });
      break;
  }

  if ('number' != typeof width) throw new Error('failed to find width of "' + this.path + '"');
  if ('number' != typeof height) throw new Error('failed to find height of "' + this.path + '"');

  return [width, height];
};
<commit_msg>refactoring<commit_after>

/*!
 * Stylus - plugin - url
 * Copyright(c) 2010 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var utils = require('../utils')
  , nodes = require('../nodes')
  , fs = require('fs')
  , path = require('path')
  , xml2js = require('xml2js');

/**
 * Initialize a new `Image` with the given `ctx` and `path.
 *
 * @param {Evaluator} ctx
 * @param {String} path
 * @api private
 */

var Image = module.exports = function Image(ctx, path) {
  this.ctx = ctx;
  this.path = utils.lookup(path, ctx.paths);
  if (!this.path) throw new Error('failed to locate file ' + path);
};

/**
 * Open the image for reading.
 *
 * @api private
 */

Image.prototype.open = function(){
  this.fd = fs.openSync(this.path, 'r');
  this.length = fs.fstatSync(this.fd).size;
  this.extname = path.extname(this.path).slice(1);
};

/**
 * Close the file.
 *
 * @api private
 */

Image.prototype.close = function(){
  if (this.fd) fs.closeSync(this.fd);
};

/**
 * Return the type of image, supports:
 *
 *  - gif
 *  - png
 *  - jpeg
 *  - svg
 *
 * @return {String}
 * @api private
 */

Image.prototype.type = function(){
  var type
    , buf = new Buffer(4);

  fs.readSync(this.fd, buf, 0, 4, 0);

  // GIF
  if (0x47 == buf[0] && 0x49 == buf[1] && 0x46 == buf[2]) type = 'gif';

  // PNG
  else if (0x50 == buf[1] && 0x4E == buf[2] && 0x47 == buf[3]) type = 'png';

  // JPEG
  else if (0xff == buf[0] && 0xd8 == buf[1]) type = 'jpeg';

  // SVG
  else if ('svg' == this.extname) type = this.extname;

  return type;
};

/**
 * Return image dimensions `[width, height]`.
 *
 * @return {Array}
 * @api private
 */

Image.prototype.size = function(){
  var type = this.type()
    , width
    , height
    , buf
    , offset
    , blockSize
    , attrs;

  function uint16(b) { return b[1] << 8 | b[0]; }
  function uint32(b) { return b[0] << 24 | b[1] << 16 | b[2] << 8 | b[3]; }

  // Determine dimensions
  switch (type) {
    case 'jpeg':
      buf = new Buffer(this.length);
      fs.readSync(this.fd, buf, 0, this.length);
      offset = 4;
      blockSize = buf[offset] << 8 | buf[offset + 1];

      while (offset < this.length) {
        offset += blockSize;
        if (offset >= this.length || 0xff != buf[offset]) break;
        if (0xc0 == buf[offset + 1] ) {
          height = buf[offset + 5] << 8 | buf[offset + 6];
          width = buf[offset + 7] << 8 | buf[offset + 8];
        } else {
          offset += 2;
          blockSize = buf[offset] << 8 | buf[offset + 1];
        }
      }
      break;
    case 'png':
      buf = new Buffer(8);
      // IHDR chunk width / height uint32_t big-endian
      fs.readSync(this.fd, buf, 0, 8, 16);
      width = uint32(buf);
      height = uint32(buf.slice(4, 8));
      break;
    case 'gif':
      buf = new Buffer(4);
      // width / height uint16_t little-endian
      fs.readSync(this.fd, buf, 0, 4, 6);
      width = uint16(buf);
      height = uint16(buf.slice(2, 4));
      break;
    case 'svg':
      buf = new Buffer(this.length);
      fs.readSync(this.fd, buf, 0, this.length);
      buf = buf.toString('utf8');
      xml2js.parseString(buf, function(err, res) {
        if (res.svg) {
          attrs = res.svg.$;
          if (attrs.width && attrs.height) {
            width = parseInt(attrs.width, 10);
            height = parseInt(attrs.height, 10);
          }
        }
      });
      break;
  }

  if ('number' != typeof width) throw new Error('failed to find width of "' + this.path + '"');
  if ('number' != typeof height) throw new Error('failed to find height of "' + this.path + '"');

  return [width, height];
};
<|endoftext|>


<commit_before>var path = require('path')
var fs = require('fs')
var isPromise = require('is-promise')
var once = require('once')
var Promise = require('bluebird')

exports.initialize = function (instance, verbose) {
  if (!instance._initialized) {
    // explicitly silent jsreport logging if verboseMode is not activated
    if (!verbose) {
      if (instance.options.logger) {
        instance.options.logger.silent = true
      } else {
        instance.options.logger = {
          silent: true
        }
      }
    }

    // initializing jsreport instance
    return instance.init().then(function () {
      return instance
    }).catch(function (err) {
      var msg = 'An error has occurred when trying to initialize jsreport..'
      var errorToReject

      if (err.code === 'EADDRINUSE') {
        msg += ' seems like there is already a server running in port: ' + err.port
      }

      errorToReject = new Error(msg)
      errorToReject.originalError = err

      throw errorToReject
    })
  }

  return Promise.resolve(instance)
}

exports.find = function find (cwd) {
  return new Promise(function (resolve, reject) {
    // finding entry point before activating CLI
    var isAlreadyResolved = false
    var existsPackageJson
    var jsreportModuleInfo
    var userPkg
    var jsreportEntryPoint
    var pathToJsreportEntryPoint
    var jsreportEntryPointExport
    var entryPointExportResult
    var resolveInstanceOnce

    existsPackageJson = fs.existsSync(path.join(cwd, './package.json'))
    jsreportModuleInfo = getJsreportModuleInstalled(cwd, existsPackageJson)

    if (!jsreportModuleInfo) {
      return reject(new Error('Couldn\'t find a jsreport intallation necessary to process the command, try to install jsreport first'))
    }

    if (!existsPackageJson) {
      // creating a default instance
      return resolve({
        from: jsreportModuleInfo.name,
        isDefault: true,
        instance: createDefaultInstance(
          jsreportModuleInfo.module
        )
      })
    }

    userPkg = require(path.join(cwd, './package.json'))
    jsreportEntryPoint = (userPkg.jsreport || {}).entryPoint

    if (!jsreportEntryPoint) {
      return resolve({
        from: jsreportModuleInfo.name,
        isDefault: true,
        instance: createDefaultInstance(
          jsreportModuleInfo.module
        )
      })
    }

    pathToJsreportEntryPoint = path.resolve(cwd, jsreportEntryPoint)

    try {
      jsreportEntryPointExport = require(pathToJsreportEntryPoint)

      if (typeof jsreportEntryPointExport === 'function') {
        // prevents resolving an instance more than once
        resolveInstanceOnce = once(resolveInstance)
        entryPointExportResult = jsreportEntryPointExport(resolveInstanceOnce)

        if (isAlreadyResolved) {
          return
        }

        // check if function returns a promise,
        // otherwise just wait until user calls `resolveInstanceOnce`
        if (isPromise(entryPointExportResult)) {
          if (resolveInstanceOnce.called) {
            isAlreadyResolved = true
            return reject(createDuplicateResolutionError(pathToJsreportEntryPoint))
          }

          handlePromiseExport(entryPointExportResult, {
            entryPoint: pathToJsreportEntryPoint,
            resolveCheck: resolveInstanceOnce,
            jsreportModule: jsreportModuleInfo.module
          }, function (err, instance) {
            if (isAlreadyResolved) {
              return
            }

            isAlreadyResolved = true

            if (err) {
              return reject(err)
            }

            return resolve({
              from: jsreportModuleInfo.name,
              isDefault: false,
              instance: instance,
              entryPoint: pathToJsreportEntryPoint
            })
          })
        }
      } else if (isJsreportInstance(jsreportEntryPointExport, jsreportModuleInfo.module)) {
        return resolve({
          from: jsreportModuleInfo.name,
          isDefault: false,
          instance: jsreportEntryPointExport,
          entryPoint: pathToJsreportEntryPoint
        })
      } else {
        return reject(new Error(
          'Entry point must return a valid jsreport instance or a function resolving to a jsreport instance, check file in ' +
          pathToJsreportEntryPoint
        ))
      }
    } catch (e) {
      var errorToReject

      if (e.code === 'MODULE_NOT_FOUND') {
        errorToReject = new Error('Couldn\'t find a jsreport entry point in: ' + pathToJsreportEntryPoint)
      } else {
        errorToReject = new Error('An error has occurred when trying to find a jsreport instance..')
        errorToReject.originalError = e
      }

      return reject(errorToReject)
    }

    function resolveInstance (err, instance) {
      var errorToReject

      if (isAlreadyResolved) {
        return
      }

      isAlreadyResolved = true

      if (err) {
        errorToReject = new Error('An error has occurred when trying to find a jsreport instance..')
        errorToReject.originalError = err
        return reject(errorToReject)
      }

      if (!isJsreportInstance(instance, jsreportModuleInfo.module)) {
        return reject(new Error(
          'Callback in entry point must return a valid jsreport instance, check file in ' +
          pathToJsreportEntryPoint
        ))
      }

      resolve({
        from: jsreportModuleInfo.name,
        isDefault: false,
        instance: instance,
        entryPoint: pathToJsreportEntryPoint
      })
    }
  })
}

exports.isJsreportInstance = isJsreportInstance

function createDuplicateResolutionError (pathToJsreportEntryPoint) {
  return new Error(
    'jsreport instance is already resolved, are you using promise and callback at the same time? ' +
    'you should only use one way to resolve the instance from entry point, check file in ' +
    pathToJsreportEntryPoint
  )
}

function isJsreportInstance (instance, jsreportModule) {
  if (!instance) {
    return false
  }

  // only check if jsreportModule is not null or undefined
  if (jsreportModule != null) {
    return instance instanceof jsreportModule.Reporter
  }

  // if no jsreportModule is passed try to check if "instance" looks
  // like a jsreport instance
  return (
    typeof instance.init === 'function' &&
    typeof instance.render === 'function' &&
    typeof instance.afterConfigLoaded === 'function' &&
    instance.extensionsManager != null &&
    instance.beforeRenderListeners != null &&
    instance.afterRenderListeners != null
  )
}

function createDefaultInstance (jsreportModule) {
  return jsreportModule()
}

function handlePromiseExport (promiseToInstance, options, cb) {
  var entryPoint = options.entryPoint
  var jsreportModule = options.jsreportModule
  var resolveCheck = options.resolveCheck

  promiseToInstance.then(function (jsreportInstance) {
    if (resolveCheck.called) {
      return cb(createDuplicateResolutionError(entryPoint))
    }

    if (!isJsreportInstance(jsreportInstance, jsreportModule)) {
      return cb(
        new Error(
          'Promise in entry point must resolve to a jsreport instance, check file in ' +
          entryPoint
        )
      )
    }

    cb(null, jsreportInstance)
  }).catch(function (getJsreportInstanceError) {
    if (resolveCheck.called) {
      return cb(createDuplicateResolutionError(entryPoint))
    }

    cb(getJsreportInstanceError)
  })
}

function getJsreportModuleInstalled (cwd, existsPackageJson) {
  var detectedJsreport
  var detectedModule
  var userPkg
  var userDependencies

  if (existsPackageJson) {
    userPkg = require(path.join(cwd, './package.json'))
    userDependencies = userPkg.dependencies || {}

    if (userDependencies['jsreport']) {
      detectedJsreport = 'jsreport'
    } else if (userDependencies['jsreport-core']) {
      detectedJsreport = 'jsreport-core'
    }
  }

  if (!detectedJsreport) {
    if (fs.existsSync(path.join(cwd, 'node_modules/jsreport'))) {
      detectedJsreport = 'jsreport'
    } else if (fs.existsSync(path.join(cwd, 'node_modules/jsreport-core'))) {
      detectedJsreport = 'jsreport-core'
    }
  }

  if (!detectedJsreport) {
    return null
  }

  try {
    // always require top-level package from cwd
    detectedModule = require(require.resolve(path.join(cwd, 'node_modules', detectedJsreport)))

    detectedModule = {
      name: detectedJsreport,
      module: detectedModule
    }
  } catch (err) {
    detectedModule = null
  }

  return detectedModule
}
<commit_msg>Update instanceHandler.js<commit_after>var path = require('path')
var fs = require('fs')
var isPromise = require('is-promise')
var once = require('once')
var Promise = require('bluebird')

exports.initialize = function (instance, verbose) {
  if (!instance._initialized) {
    // explicitly silent jsreport logging if verboseMode is not activated
    if (!verbose) {
      if (instance.options.logger) {
        instance.options.logger.silent = true
      } else {
        instance.options.logger = {
          silent: true
        }
      }
    }

    // initializing jsreport instance
    return instance.init().then(function () {
      return instance
    }).catch(function (err) {
      var msg = 'An error has occurred when trying to initialize jsreport..'
      var errorToReject

      if (err.code === 'EADDRINUSE') {
        msg += ' seems like there is already a server running in port: ' + err.port
      }

      errorToReject = new Error(msg)
      errorToReject.originalError = err

      throw errorToReject
    })
  }

  return Promise.resolve(instance)
}

exports.find = function find (cwd) {
  return new Promise(function (resolve, reject) {
    // finding entry point before activating CLI
    var isAlreadyResolved = false
    var existsPackageJson
    var jsreportModuleInfo
    var userPkg
    var jsreportEntryPoint
    var pathToJsreportEntryPoint
    var jsreportEntryPointExport
    var entryPointExportResult
    var resolveInstanceOnce

    existsPackageJson = fs.existsSync(path.join(cwd, './package.json'))
    jsreportModuleInfo = getJsreportModuleInstalled(cwd, existsPackageJson)

    if (!jsreportModuleInfo) {
      return reject(new Error('Couldn\'t find a jsreport installation necessary to process the command, try to install jsreport first.'))
    }

    if (!existsPackageJson) {
      // creating a default instance
      return resolve({
        from: jsreportModuleInfo.name,
        isDefault: true,
        instance: createDefaultInstance(
          jsreportModuleInfo.module
        )
      })
    }

    userPkg = require(path.join(cwd, './package.json'))
    jsreportEntryPoint = (userPkg.jsreport || {}).entryPoint

    if (!jsreportEntryPoint) {
      return resolve({
        from: jsreportModuleInfo.name,
        isDefault: true,
        instance: createDefaultInstance(
          jsreportModuleInfo.module
        )
      })
    }

    pathToJsreportEntryPoint = path.resolve(cwd, jsreportEntryPoint)

    try {
      jsreportEntryPointExport = require(pathToJsreportEntryPoint)

      if (typeof jsreportEntryPointExport === 'function') {
        // prevents resolving an instance more than once
        resolveInstanceOnce = once(resolveInstance)
        entryPointExportResult = jsreportEntryPointExport(resolveInstanceOnce)

        if (isAlreadyResolved) {
          return
        }

        // check if function returns a promise,
        // otherwise just wait until user calls `resolveInstanceOnce`
        if (isPromise(entryPointExportResult)) {
          if (resolveInstanceOnce.called) {
            isAlreadyResolved = true
            return reject(createDuplicateResolutionError(pathToJsreportEntryPoint))
          }

          handlePromiseExport(entryPointExportResult, {
            entryPoint: pathToJsreportEntryPoint,
            resolveCheck: resolveInstanceOnce,
            jsreportModule: jsreportModuleInfo.module
          }, function (err, instance) {
            if (isAlreadyResolved) {
              return
            }

            isAlreadyResolved = true

            if (err) {
              return reject(err)
            }

            return resolve({
              from: jsreportModuleInfo.name,
              isDefault: false,
              instance: instance,
              entryPoint: pathToJsreportEntryPoint
            })
          })
        }
      } else if (isJsreportInstance(jsreportEntryPointExport, jsreportModuleInfo.module)) {
        return resolve({
          from: jsreportModuleInfo.name,
          isDefault: false,
          instance: jsreportEntryPointExport,
          entryPoint: pathToJsreportEntryPoint
        })
      } else {
        return reject(new Error(
          'Entry point must return a valid jsreport instance or a function resolving to a jsreport instance, check file in ' +
          pathToJsreportEntryPoint
        ))
      }
    } catch (e) {
      var errorToReject

      if (e.code === 'MODULE_NOT_FOUND') {
        errorToReject = new Error('Couldn\'t find a jsreport entry point in: ' + pathToJsreportEntryPoint)
      } else {
        errorToReject = new Error('An error has occurred when trying to find a jsreport instance..')
        errorToReject.originalError = e
      }

      return reject(errorToReject)
    }

    function resolveInstance (err, instance) {
      var errorToReject

      if (isAlreadyResolved) {
        return
      }

      isAlreadyResolved = true

      if (err) {
        errorToReject = new Error('An error has occurred when trying to find a jsreport instance..')
        errorToReject.originalError = err
        return reject(errorToReject)
      }

      if (!isJsreportInstance(instance, jsreportModuleInfo.module)) {
        return reject(new Error(
          'Callback in entry point must return a valid jsreport instance, check file in ' +
          pathToJsreportEntryPoint
        ))
      }

      resolve({
        from: jsreportModuleInfo.name,
        isDefault: false,
        instance: instance,
        entryPoint: pathToJsreportEntryPoint
      })
    }
  })
}

exports.isJsreportInstance = isJsreportInstance

function createDuplicateResolutionError (pathToJsreportEntryPoint) {
  return new Error(
    'jsreport instance is already resolved, are you using promise and callback at the same time? ' +
    'you should only use one way to resolve the instance from entry point, check file in ' +
    pathToJsreportEntryPoint
  )
}

function isJsreportInstance (instance, jsreportModule) {
  if (!instance) {
    return false
  }

  // only check if jsreportModule is not null or undefined
  if (jsreportModule != null) {
    return instance instanceof jsreportModule.Reporter
  }

  // if no jsreportModule is passed try to check if "instance" looks
  // like a jsreport instance
  return (
    typeof instance.init === 'function' &&
    typeof instance.render === 'function' &&
    typeof instance.afterConfigLoaded === 'function' &&
    instance.extensionsManager != null &&
    instance.beforeRenderListeners != null &&
    instance.afterRenderListeners != null
  )
}

function createDefaultInstance (jsreportModule) {
  return jsreportModule()
}

function handlePromiseExport (promiseToInstance, options, cb) {
  var entryPoint = options.entryPoint
  var jsreportModule = options.jsreportModule
  var resolveCheck = options.resolveCheck

  promiseToInstance.then(function (jsreportInstance) {
    if (resolveCheck.called) {
      return cb(createDuplicateResolutionError(entryPoint))
    }

    if (!isJsreportInstance(jsreportInstance, jsreportModule)) {
      return cb(
        new Error(
          'Promise in entry point must resolve to a jsreport instance, check file in ' +
          entryPoint
        )
      )
    }

    cb(null, jsreportInstance)
  }).catch(function (getJsreportInstanceError) {
    if (resolveCheck.called) {
      return cb(createDuplicateResolutionError(entryPoint))
    }

    cb(getJsreportInstanceError)
  })
}

function getJsreportModuleInstalled (cwd, existsPackageJson) {
  var detectedJsreport
  var detectedModule
  var userPkg
  var userDependencies

  if (existsPackageJson) {
    userPkg = require(path.join(cwd, './package.json'))
    userDependencies = userPkg.dependencies || {}

    if (userDependencies['jsreport']) {
      detectedJsreport = 'jsreport'
    } else if (userDependencies['jsreport-core']) {
      detectedJsreport = 'jsreport-core'
    }
  }

  if (!detectedJsreport) {
    if (fs.existsSync(path.join(cwd, 'node_modules/jsreport'))) {
      detectedJsreport = 'jsreport'
    } else if (fs.existsSync(path.join(cwd, 'node_modules/jsreport-core'))) {
      detectedJsreport = 'jsreport-core'
    }
  }

  if (!detectedJsreport) {
    return null
  }

  try {
    // always require top-level package from cwd
    detectedModule = require(require.resolve(path.join(cwd, 'node_modules', detectedJsreport)))

    detectedModule = {
      name: detectedJsreport,
      module: detectedModule
    }
  } catch (err) {
    detectedModule = null
  }

  return detectedModule
}
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var Promise = require('bluebird');
var Inotify = require('inotify').Inotify;

var serviceLocator = require('../service-locator');
var logger = serviceLocator.get('logger');
var JobHandlerRegistry = require('./handler/registry');

/**
 * @param {String} jobDirectory, an Absolute one!
 * @constructor
 */
function JobManager(jobDirectory) {
  if (!fs.statSync(jobDirectory).isDirectory()) {
    throw new Error('`jobDirectory` must be a directory');
  }
  this._jobDirectory = jobDirectory;
  this._inotify = new Inotify();
  this._watch = null;
  this._installFileListeners();
}

JobManager.prototype.reset = function() {
  this._removeFileListeners();
  this._installFileListeners();
};

JobManager.prototype._handleJobFile = function(filepath) {
  this._readJobFile(filepath)
    .then(function(job) {
      var handler = JobHandlerRegistry.getHandler(job['plugin'], job['event']);
      handler.handle(job['data']);
    }.bind(this))
    .catch(function(error) {
      logger.error(error);
    });
};

JobManager.prototype._readJobFile = function(filepath) {
  return new Promise(function(resolve, reject) {
    fs.readFile(filepath, function(error, content) {
      if (error) {
        reject(new Error('Invalid file "' + filepath + "'. " + error.message));
      }
      try {
        var job = JSON.parse(content);
      } catch (e) {
        reject(new Error('Invalid file content "' + filepath + "'. " + e.message));
      }
      if (!job['plugin'] || !job['event'] || !job['data']) {
        reject(new Error('"plugin", "event", "data" are required job file fields'));
      }
      resolve(job);
    });
  });
};

JobManager.prototype._installFileListeners = function() {
  this._watch = this._inotify.addWatch({
    path: this._jobDirectory,
    watch_for: Inotify.IN_CLOSE_WRITE,
    callback: function(event) {
      this._handleJobFile(path.join(this._jobDirectory, event.name));
    }.bind(this)
  });
};

JobManager.prototype._removeFileListeners = function() {
  this._inotify.removeWatch(this._watch);
};

module.exports = JobManager;
<commit_msg>Parse existing files on start<commit_after>var fs = require('fs');
var path = require('path');
var Promise = require('bluebird');
var Inotify = require('inotify').Inotify;

var serviceLocator = require('../service-locator');
var logger = serviceLocator.get('logger');
var JobHandlerRegistry = require('./handler/registry');

/**
 * @param {String} jobDirectory, an Absolute one!
 * @constructor
 */
function JobManager(jobDirectory) {
  if (!fs.statSync(jobDirectory).isDirectory()) {
    throw new Error('`jobDirectory` must be a directory');
  }
  this._jobDirectory = jobDirectory;
  this._inotify = new Inotify();
  this._watch = null;
  this._handleExistingJobFiles();
  this._installFileListeners();
}

JobManager.prototype.reset = function() {
  this._removeFileListeners();
  this._installFileListeners();
};

JobManager.prototype._handleJobFile = function(filepath) {
  this._readJobFile(filepath)
    .then(function(job) {
      var handler = JobHandlerRegistry.getHandler(job['plugin'], job['event']);
      handler.handle(job['data']);
    }.bind(this))
    .catch(function(error) {
      logger.error(error);
    });
};

JobManager.prototype._handleExistingJobFiles = function() {
  var self = this;
  fs.readdir(this._jobDirectory, function(error, files) {
    if (error) {
      throw error;
    }
    files.forEach(function(filename) {
      self._handleJobFile(path.join(self._jobDirectory, filename));
    });
  });
};

JobManager.prototype._readJobFile = function(filepath) {
  return new Promise(function(resolve, reject) {
    fs.readFile(filepath, function(error, content) {
      if (error) {
        reject(new Error('Invalid file "' + filepath + "'. " + error.message));
      }
      try {
        var job = JSON.parse(content);
      } catch (e) {
        reject(new Error('Invalid file content "' + filepath + "'. " + e.message));
      }
      if (!job || !job['plugin'] || !job['event'] || !job['data']) {
        reject(new Error('"plugin", "event", "data" are required job file fields'));
      }
      resolve(job);
    });
  });
};

JobManager.prototype._installFileListeners = function() {
  this._watch = this._inotify.addWatch({
    path: this._jobDirectory,
    watch_for: Inotify.IN_CLOSE_WRITE,
    callback: function(event) {
      this._handleJobFile(path.join(this._jobDirectory, event.name));
    }.bind(this)
  });
};

JobManager.prototype._removeFileListeners = function() {
  this._inotify.removeWatch(this._watch);
};

module.exports = JobManager;
<|endoftext|>