<commit_before>const CSV = require('csv-string'); // open source csv parser and stringifier
const dwv = require('dwv'); // open source DICOM parser, viewer, and writer
const fs = require('fs'); // built-in node.js file system library
const fsPath = require('fs-path'); // open source high level fs function
const glob = require('glob'); // open source glob capability for node
const mv = require('mv'); // open source mv capability for node
const open = require('open'); // open source web browser URL opener
const path = require('path'); // built-in node.js path library
const process = require('process'); // built-in node.js process library

function automaDICOM() {
	this.in = null;
	this.rules = __dirname + path.sep + 'usr' + path.sep + 'rules.csv';
	this.out = null;
	this.append = __dirname + path.sep + 'usr' + path.sep + 'append.csv';
	this.server = false;
	this.verbose = true;
	this.list = false;
	this.tags = [];
	this.values = [];
	this.newPaths = [];

	this.error = (err) => {
		console.log('ERROR: ' + err);
		process.exit(1);
	}

	this.getSubLevelTag = (tagReq, elements) => {
		switch (tagReq) {
			case 'CodeMeaning':
				return elements.getFromName('ViewCodeSequence')['x00080104'].value[0];
			case 'FrameLaterality':
				return elements.getFromName('SharedFunctionalGroupsSequence')['x00209071'].value[0]['x00209072'].value[0];
			default:
		}
	}

	this.fulfillTagReqs = (str, elements, values) => {
		let match, tagReq, tag;
		let useOgVal = false;
		let editIdx = -1;
		let regex = /\$[\w|\-|_]*/i;
		// loops while a match is found
		while (match = regex.exec(str)) {
			useOgVal = (match[0][1] == '$');
			tagReq = match[0].slice(((useOgVal) ? 2 : 1), match[0].length);
			// if values is not defined or if the requested tag is not found in this.tags
			if (useOgVal || (editIdx = this.tags.indexOf(tagReq)) <= -1) {
				// get the tag from the zero level DICOM by name
				tag = elements.getFromName(tagReq);
				if (tag == null) {
					tag = this.getSubLevelTag(tagReq, elements);
				}
				// if it's still null it wasn't found
				if (tag == null) {
					this.error(tagReq + ' tag not found!!');
				}
			} else {
				// get the tag from the values array
				tag = values[editIdx];
			}
			// replace the request with the tag itself, the quotes are necessary
			str = str.replace('$' + tagReq, `\'${tag}\'`);
		}
		// note that eval is used to evaluate user javascript dynamically!
		// direct access to String methods gives users advanced control
		// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
		try {
			str = eval(str);
		} catch (err) {}
		return str;
	}

	this.errorCheck = (tag, value) => {
		switch (tag) {
			case 'AcquisitionDate':
			case 'ContentDate':
			case 'InstanceCreationDate':
			case 'PatientBirthDate':
			case 'StudyDate':
				if (typeof value !== 'string') {
					this.error(`${tag} ${value}
	Dates must be entered as a String in the format 'YYYYMMDD'`);
				}
				let isYear = (parseInt(value.slice(0, 4)) >= 1900);
				let isMonth = (parseInt(value.slice(4, 6)) <= 12);
				let isDay = (parseInt(value.slice(6, 8)) <= 31);
				if ((!isYear || !isMonth || !isDay)) {
					this.error(`${tag} ${value}
	Dates must be entered as a String in the format 'YYYYMMDD'`);
				}
				break;
			case 'AcquisitionTime':
			case 'ContentTime':
			case 'InstanceCreationTime':
			case 'PatientBirthTime':
			case 'StudyTime':
				// check
				break;
			default:
		}
	}

	this.edit = (file, files) => {
		let i = 0;
		// loads the parser and writer from the open source library DWV
		let parser = new dwv.dicom.DicomParser();
		let writer = new dwv.dicom.DicomWriter();
		if (this.verbose) {
			console.log('loading ' + file);
		}
		// parse the array buffer of the file
		parser.parse(new Uint8Array(fs.readFileSync(file)).buffer);
		// get the tags
		let elements = parser.getDicomElements();
		if (this.list) {
			console.log(elements.dump());
		}
		// the default rule must be included, it simply copies all other tag's value(s)
		// hard coding this inside this program pervents users from screwing it up
		// also for user convience the action of their rules is always 'replace'
		let rules = {
			default: {
				action: 'copy',
				value: null
			}
		};
		// a seperate copy of the values array must be used for each image
		let values = this.values.slice();
		// rule objects conforms to the format the DICOM writer expects
		this.tags.forEach((tag, i) => {
			values[i] = this.fulfillTagReqs(values[i], elements, values);
			this.errorCheck(tag, values[i]);
			rules[tag] = {
				action: 'replace',
				value: values[i]
			};
		});
		if (this.verbose) {
			values.forEach((value, i) => {
				console.log(`${this.tags[i]} = ${value}`);
			});
		}
		// the rules are applied immediately after they are set
		writer.rules = rules;
		// buffer gets the modified DICOM file
		let buffer = writer.getBuffer(parser.getRawDicomElements());
		// let's decide where to write the file!
		let dir, imgName;
		let newPath = '';
		if (this.out != null) {
			dir = this.out;
			for (i = 0; i < this.append.length - 1; i++) {
				dir += path.sep + this.fulfillTagReqs(this.append[i][0], elements, values);
			}
			imgName = this.fulfillTagReqs(this.append[this.append.length - 1][0], elements, values);
			// at the end of this loop it is assured that a unique file name has been created
			for (i = 0; newPath == '' || this.newPaths.includes(newPath) || fs.existsSync(newPath); i++) {
				newPath = dir + path.sep + `${imgName}_${i.toString()}.dcm`;
				if (newPath == file) {
					break;
				}
			}
		} else {
			// get the directory of the file
			dir = path.parse(file).name;
			// prepend anon_ to the file name
			imgName = 'anon_' + path.parse(file).name + '.dcm';
			newPath = dir + imgName;
		}
		this.newPaths.push(newPath);
		if (this.verbose) {
			console.log('wrote ' + newPath);
		}

		// writeFile can be used asynchronously here, this is advantageous
		// fsPath makes any new directories if necessary
		fsPath.writeFile(newPath, Buffer(new Uint8Array(buffer)), (err) => {
			if (err) throw err;
			if (this.server) {
				// if running in server mode (continuous operation) delete the original file
				fs.unlink(file);
			}
		});
	};

	this.setup = (err, files) => {
		if (err || typeof files == 'undefined' || files.length == 0) {
			console.log('ERROR: invalid path, no files found');
			this.error(err);
		}
		// read the rules file synchronously
		this.rules = fs.readFileSync(this.rules, 'utf8');
		// parse the csv file into arrays we can use
		this.rules = CSV.parse(this.rules, ';');
		this.rules.forEach((rule) => {
			this.tags.push(rule[0]);
			this.values.push(rule[1]);
		});
		if (this.out != null) {
			this.append = fs.readFileSync(this.append, 'utf8');
			this.append = CSV.parse(this.append);
		}

		for (let i = 0, file = ''; i < files.length; i++) {
			file = files[i];
			if (!fs.statSync(file).isDirectory()) {
				if (path.parse(file).ext == '') {
					fs.renameSync(file, file += '.dcm');
				}
				if (path.parse(file).ext == '.dcm') {
					this.edit(file, files);
				}
			}
		}
	}

	this.run = () => {
		if (this.in != null) {
			console.log('');
			console.log('input: ' + this.in);
			// if the input path is a directory send it straight to the setup function
			// else glob for leaves of the fs
			if (!fs.statSync(this.in).isDirectory()) {
				this.setup(null, [this.in]);
			} else {
				glob(this.in + path.sep + '**' + path.sep + '*', this.setup);
			}
		} else {
			this.error('required input path not specified');
		}
	}
}

module.exports = new automaDICOM();
<commit_msg>v0.1.0<commit_after>const CSV = require('csv-string'); // open source csv parser and stringifier
const dwv = require('dwv'); // open source DICOM parser, viewer, and writer
const fs = require('fs'); // built-in node.js file system library
const fsPath = require('fs-path'); // open source high level fs function
const glob = require('glob'); // open source glob capability for node
const mv = require('mv'); // open source mv capability for node
const open = require('open'); // open source web browser URL opener
const path = require('path'); // built-in node.js path library
const process = require('process'); // built-in node.js process library

function automaDICOM() {
	this.in = null;
	this.rules = __dirname + path.sep + 'usr' + path.sep + 'rules.csv';
	this.out = null;
	this.append = __dirname + path.sep + 'usr' + path.sep + 'append.csv';
	this.server = false;
	this.verbose = true;
	this.list = false;
	this.tags = [];
	this.values = [];
	this.newPaths = [];

	this.error = (err) => {
		console.log('ERROR: ' + err);
		process.exit(1);
	}

	this.getSubLevelTag = (tagReq, elements) => {
		switch (tagReq) {
			case 'CodeMeaning':
				return elements.getFromName('ViewCodeSequence')['x00080104'].value[0];
			case 'FrameLaterality':
				return elements.getFromName('SharedFunctionalGroupsSequence')['x00209071'].value[0]['x00209072'].value[0];
			default:
		}
	}

	this.fulfillTagReqs = (str, elements, values) => {
		let match, tagReq, tag;
		let useOgVal = false;
		let editIdx = -1;
		let regex = /\$[\w|\-|_]*/i;
		// loops while a match is found
		while (match = regex.exec(str)) {
			useOgVal = (match[0][1] == '$');
			tagReq = match[0].slice(((useOgVal) ? 2 : 1), match[0].length);
			// if values is not defined or if the requested tag is not found in this.tags
			if (useOgVal || (editIdx = this.tags.indexOf(tagReq)) <= -1) {
				// get the tag from the zero level DICOM by name
				tag = elements.getFromName(tagReq);
				if (tag == null) {
					tag = this.getSubLevelTag(tagReq, elements);
				}
				// if it's still null it wasn't found
				if (tag == null) {
					this.error(tagReq + ' tag not found!!');
				}
			} else {
				// get the tag from the values array
				tag = values[editIdx];
			}
			// replace the request with the tag itself, the quotes are necessary
			str = str.replace('$' + tagReq, `\'${tag}\'`);
		}
		// note that eval is used to evaluate user javascript dynamically!
		// direct access to String methods gives users advanced control
		// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
		try {
			str = eval(str);
		} catch (err) {}
		return str;
	}

	this.errorCheck = (tag, value) => {
		switch (tag) {
			case 'AcquisitionDate':
			case 'ContentDate':
			case 'InstanceCreationDate':
			case 'PatientBirthDate':
			case 'StudyDate':
				if (typeof value !== 'string') {
					this.error(`${tag} ${value}
	Dates must be entered as a String in the format 'YYYYMMDD'`);
				}
				let isYear = (parseInt(value.slice(0, 4)) >= 1900);
				let isMonth = (parseInt(value.slice(4, 6)) <= 12);
				let isDay = (parseInt(value.slice(6, 8)) <= 31);
				if ((!isYear || !isMonth || !isDay)) {
					this.error(`${tag} ${value}
	Dates must be entered as a String in the format 'YYYYMMDD'`);
				}
				break;
			case 'AcquisitionTime':
			case 'ContentTime':
			case 'InstanceCreationTime':
			case 'PatientBirthTime':
			case 'StudyTime':
				// check
				break;
			default:
		}
	}

	this.edit = (file, files) => {
		let i = 0;
		// loads the parser and writer from the open source library DWV
		let parser = new dwv.dicom.DicomParser();
		let writer = new dwv.dicom.DicomWriter();
		if (this.verbose) {
			console.log('loading ' + file);
		}
		// parse the array buffer of the file
		parser.parse(new Uint8Array(fs.readFileSync(file)).buffer);
		// get the tags
		let elements = parser.getDicomElements();
		if (this.list) {
			console.log(elements.dump());
		}
		// the default rule must be included, it simply copies all other tag's value(s)
		// hard coding this inside this program pervents users from screwing it up
		// also for user convience the action of their rules is always 'replace'
		let rules = {
			default: {
				action: 'copy',
				value: null
			}
		};
		// a seperate copy of the values array must be used for each image
		let values = this.values.slice();
		// rule objects conforms to the format the DICOM writer expects
		this.tags.forEach((tag, i) => {
			values[i] = this.fulfillTagReqs(values[i], elements, values);
			this.errorCheck(tag, values[i]);
			rules[tag] = {
				action: 'replace',
				value: values[i]
			};
		});
		if (this.verbose) {
			values.forEach((value, i) => {
				console.log(`${this.tags[i]} = ${value}`);
			});
		}
		// the rules are applied immediately after they are set
		writer.rules = rules;
		// buffer gets the modified DICOM file
		let buffer = writer.getBuffer(parser.getRawDicomElements());
		// let's decide where to write the file!
		let dir, imgName;
		let newPath = '';
		if (this.out != null) {
			dir = this.out;
			for (i = 0; i < this.append.length - 1; i++) {
				dir += path.sep + this.fulfillTagReqs(this.append[i][0], elements, values);
			}
			imgName = this.fulfillTagReqs(this.append[this.append.length - 1][0], elements, values);
			// at the end of this loop it is assured that a unique file name has been created
			for (i = 0; newPath == '' || this.newPaths.includes(newPath) || fs.existsSync(newPath); i++) {
				newPath = dir + path.sep + `${imgName}_${i.toString()}.dcm`;
				if (newPath == file) {
					break;
				}
			}
		} else {
			// get the directory of the file
			dir = path.parse(file).dir;
			// prepend anon_ to the file name
			imgName = 'anon_' + path.parse(file).name + '.dcm';
			newPath = dir + imgName;
		}
		this.newPaths.push(newPath);
		if (this.verbose) {
			console.log('wrote ' + newPath);
		}

		// writeFile can be used asynchronously here, this is advantageous
		// fsPath makes any new directories if necessary
		fsPath.writeFile(newPath, Buffer(new Uint8Array(buffer)), (err) => {
			if (err) throw err;
			if (this.server) {
				// if running in server mode (continuous operation) delete the original file
				fs.unlink(file);
			}
		});
	};

	this.setup = (err, files) => {
		if (err || typeof files == 'undefined' || files.length == 0) {
			console.log('ERROR: invalid path, no files found');
			this.error(err);
		}
		// read the rules file synchronously
		this.rules = fs.readFileSync(this.rules, 'utf8');
		// parse the csv file into arrays we can use
		this.rules = CSV.parse(this.rules, ';');
		this.rules.forEach((rule) => {
			this.tags.push(rule[0]);
			this.values.push(rule[1]);
		});
		if (this.out != null) {
			this.append = fs.readFileSync(this.append, 'utf8');
			this.append = CSV.parse(this.append);
		}

		for (let i = 0, file = ''; i < files.length; i++) {
			file = files[i];
			if (!fs.statSync(file).isDirectory()) {
				if (path.parse(file).ext == '') {
					fs.renameSync(file, file += '.dcm');
				}
				if (path.parse(file).ext == '.dcm') {
					this.edit(file, files);
				}
			}
		}
	}

	this.run = () => {
		if (this.in != null) {
			console.log('');
			console.log('input: ' + this.in);
			// if the input path is a directory send it straight to the setup function
			// else glob for leaves of the fs
			if (!fs.statSync(this.in).isDirectory()) {
				this.setup(null, [this.in]);
			} else {
				glob(this.in + path.sep + '**' + path.sep + '*', this.setup);
			}
		} else {
			this.error('required input path not specified');
		}
	}
}

module.exports = new automaDICOM();
<|endoftext|>


<commit_before>/* ------------------------------------------------------------------------- *
 * Copyright 2002-2022, OpenNebula Project, OpenNebula Systems               *
 *                                                                           *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may   *
 * not use this file except in compliance with the License. You may obtain   *
 * a copy of the License at                                                  *
 *                                                                           *
 * http://www.apache.org/licenses/LICENSE-2.0                                *
 *                                                                           *
 * Unless required by applicable law or agreed to in writing, software       *
 * distributed under the License is distributed on an "AS IS" BASIS,         *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  *
 * See the License for the specific language governing permissions and       *
 * limitations under the License.                                            *
 * ------------------------------------------------------------------------- */
import { memo, useMemo } from 'react'
import PropTypes from 'prop-types'

import makeStyles from '@mui/styles/makeStyles'
import { useForm, Controller } from 'react-hook-form'

import { Actions, Inputs } from 'client/components/Tabs/Common/Attribute'
import { generateKey } from 'client/utils'

const useStyles = makeStyles({
  wrapper: {
    display: 'flex',
    alignItems: 'center',
    '& > *:first-child': {
      flexGrow: 1,
    },
  },
})

const AttributeCreateForm = memo(({ handleAdd }) => {
  const classes = useStyles()
  const key = useMemo(() => generateKey(), [])
  const nameInputKey = useMemo(() => `name-${key}`, [key])
  const valueInputKey = useMemo(() => `value-${key}`, [key])

  const { handleSubmit, reset, control } = useForm({
    defaultValues: { [nameInputKey]: '', [valueInputKey]: '' },
  })

  const handleCreateAttribute = async (data) => {
    const { [nameInputKey]: name, [valueInputKey]: value } = data

    await handleAdd?.(String(name).toUpperCase(), String(value).toUpperCase())

    reset()
  }

  return (
    <>
      {/* NAME ATTRIBUTE */}
      <Controller
        control={control}
        name={nameInputKey}
        render={({ field, formState }) => (
          <Inputs.Text {...field} disabled={formState.isSubmitting} />
        )}
      />

      {/* VALUE ATTRIBUTE */}
      <div className={classes.wrapper}>
        <Controller
          control={control}
          name={valueInputKey}
          render={({ field, formState }) => (
            <Inputs.Text {...field} disabled={formState.isSubmitting} />
          )}
        />
        <Actions.Add
          name={'action-add'}
          handleClick={handleSubmit(handleCreateAttribute)}
        />
      </div>
    </>
  )
})

AttributeCreateForm.propTypes = {
  handleAdd: PropTypes.func,
}

AttributeCreateForm.displayName = 'AttributeCreateForm'

export default AttributeCreateForm
<commit_msg>F #5422: Add blur & enter key event to attributes (#2041)<commit_after>/* ------------------------------------------------------------------------- *
 * Copyright 2002-2022, OpenNebula Project, OpenNebula Systems               *
 *                                                                           *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may   *
 * not use this file except in compliance with the License. You may obtain   *
 * a copy of the License at                                                  *
 *                                                                           *
 * http://www.apache.org/licenses/LICENSE-2.0                                *
 *                                                                           *
 * Unless required by applicable law or agreed to in writing, software       *
 * distributed under the License is distributed on an "AS IS" BASIS,         *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  *
 * See the License for the specific language governing permissions and       *
 * limitations under the License.                                            *
 * ------------------------------------------------------------------------- */
import { memo, useMemo, useCallback } from 'react'
import PropTypes from 'prop-types'

import { AddSquare as AddIcon } from 'iconoir-react'
import { Box, TextField } from '@mui/material'
import { useForm } from 'react-hook-form'

import { SubmitButton } from 'client/components/FormControl'
import { generateKey } from 'client/utils'

const AttributeCreateForm = memo(({ handleAdd }) => {
  const key = useMemo(() => generateKey(), [])
  const nameInputKey = useMemo(() => `name-${key}`, [key])
  const valueInputKey = useMemo(() => `value-${key}`, [key])

  const { handleSubmit, register, reset, formState } = useForm({
    defaultValues: { [nameInputKey]: '', [valueInputKey]: '' },
    reValidateMode: 'onSubmit',
  })

  const handleCreateAttribute = useCallback(
    async (data) => {
      try {
        const { [nameInputKey]: name, [valueInputKey]: value } = data

        if (!name || !value || formState.isSubmitting) return

        const upperName = `${name}`.toUpperCase()
        const upperValue = `${value}`.toUpperCase()

        await handleAdd?.(upperName, upperValue)
        reset()
      } catch {}
    },
    [handleAdd]
  )

  const handleKeyDown = (evt) => {
    if (evt.key === 'Enter') {
      handleSubmit(handleCreateAttribute)(evt)
    }
  }

  const handleBlur = (evt) => handleSubmit(handleCreateAttribute)(evt)

  return (
    <>
      {/* NAME ATTRIBUTE */}
      <TextField
        onKeyDown={handleKeyDown}
        disabled={formState.isSubmitting}
        inputProps={{ 'data-cy': `text-${nameInputKey}` }}
        {...register(nameInputKey, { onBlur: handleBlur })}
      />

      {/* VALUE ATTRIBUTE */}
      <Box display="inline-flex" alignItems="center">
        <TextField
          sx={{ flexGrow: 1 }}
          onKeyDown={handleKeyDown}
          disabled={formState.isSubmitting}
          inputProps={{ 'data-cy': `text-${valueInputKey}` }}
          {...register(valueInputKey, { onBlur: handleBlur })}
        />
        <SubmitButton
          data-cy={'action-add'}
          icon={<AddIcon />}
          isSubmitting={formState.isSubmitting}
          onClick={handleSubmit(handleCreateAttribute)}
        />
      </Box>
    </>
  )
})

AttributeCreateForm.propTypes = {
  handleAdd: PropTypes.func,
}

AttributeCreateForm.displayName = 'AttributeCreateForm'

export default AttributeCreateForm
<|endoftext|>


<commit_before>'use strict';

jest.unmock('./../Footer');

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import Footer from './../Footer';

describe('Footer', () => {

  it('verify the text content and link are correctly', () => {

    const footer = TestUtils.renderIntoDocument(
    	<Footer />
    );

    const footerNode = ReactDOM.findDOMNode(footer);

    expect(footerNode.textContent).toEqual('Made with  by @afonsopacifer');
  });

});<commit_msg>Make more tests at Footer component<commit_after>'use strict';

jest.unmock('./../Footer');

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import Footer from './../Footer';

describe('Footer', () => {

  it('verify the text content are correctly', () => {

    const footer = TestUtils.renderIntoDocument(
      <Footer />
    );

    const footerNode = ReactDOM.findDOMNode(footer);

    expect(footerNode.textContent).toEqual('Made with  by @afonsopacifer');
  });

  it('link of github author should be https://github.com/afonsopacifer', () => {

    const footer = TestUtils.renderIntoDocument(
      <Footer />
    );

    const linkElement = TestUtils.scryRenderedDOMComponentsWithTag(footer, 'a');

    expect(linkElement.length).toEqual(1);
    expect(linkElement[0].getAttribute('href')).toEqual('https://github.com/afonsopacifer');
  });

});<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser')
var fs = require('fs');
var cp = require('child_process');
var irc = require('irc');
var app = express();

app.use(bodyParser.urlencoded({ extended: false }));

var ircclient = new irc.Client('irc.freenode.net', 'XiphAWCY', {
    channels: ['#daala'],
});
ircclient.addListener('error', function(message) {
    console.log('error: ', message);
});

var job;
var job_queue = [];
var job_in_progress = false;

var key = fs.readFileSync('secret_key', {encoding: 'utf8'}).trim();

function check_key(req,res,next) {
  if (key != req.body.key) {
    console.log(req.body.key.trim());
    console.log(key);
    res.status(403).send('Key verification failed.\n');
    return;
  }
  next();
};

function process_queue() {
  if (job_in_progress) { return; };
  if (job_queue.length > 0) {
    job_in_progress = true;
    job = job_queue.pop();
    console.log('Starting job '+job.run_id);
    cp.execFile('./run_video_test.sh',[job.commit,job.run_id,job.task],function(error,stdout,stderr) {
      if (error == null) {
        console.log('video test succeeded');
        ircclient.say('#daala','AWCY: Finished '+job.run_id);
      } else {
        console.log(stdout);
        console.log(stderr);
        ircclient.say('#daala','AWCY: Exploded '+job.run_id);
      }
      job_in_progress = false;
      job = null;
      process_queue();
    });
  }
};

app.use(express.static(__dirname + '/www'));
app.use('/runs',express.static(__dirname + '/runs'));
app.use('/sets.json',express.static(__dirname + '/rd_tool/sets.json'));

app.get('/run_list.json',function(req,res) {
  fs.readdir('runs',function(err,files) {
    res.send(files);
  });
});

app.get('/job_queue.json',function(req,res) {
  res.send(JSON.stringify(job_queue));
});

app.get('/job',function(req,res) {
  res.send(JSON.stringify(job));
});

app.use('/submit',check_key);

app.post('/submit/job',function(req,res) {
  var job = {};
  job.codec = 'daala';
  job.commit = req.body.commit;
  job.run_id = req.body.run_id;
  job.task = 'video-1-short';
  job.task_type = 'video';
  if (fs.existsSync('runs/'+job.run_id)) {
    res.status(400).send('ID is not unique! Choose another.\n');
    return;
  }
  job_queue.push(job);
  process_queue();
  res.send('ok');
  ircclient.say('#daala','AWCY: Starting '+job.run_id);
});

app.listen(3000);
<commit_msg>Add BD rate get<commit_after>var express = require('express');
var bodyParser = require('body-parser')
var fs = require('fs');
var cp = require('child_process');
var irc = require('irc');
var app = express();

app.use(bodyParser.urlencoded({ extended: false }));

var ircclient = new irc.Client('irc.freenode.net', 'XiphAWCY', {
    channels: ['#daala'],
});
ircclient.addListener('error', function(message) {
    console.log('error: ', message);
});

var job;
var job_queue = [];
var job_in_progress = false;

var key = fs.readFileSync('secret_key', {encoding: 'utf8'}).trim();

function check_key(req,res,next) {
  if (key != req.body.key) {
    console.log(req.body.key.trim());
    console.log(key);
    res.status(403).send('Key verification failed.\n');
    return;
  }
  next();
};

function process_queue() {
  if (job_in_progress) { return; };
  if (job_queue.length > 0) {
    job_in_progress = true;
    job = job_queue.pop();
    console.log('Starting job '+job.run_id);
    cp.execFile('./run_video_test.sh',[job.commit,job.run_id,job.task],function(error,stdout,stderr) {
      if (error == null) {
        console.log('video test succeeded');
        ircclient.say('#daala','AWCY: Finished '+job.run_id);
      } else {
        console.log(stdout);
        console.log(stderr);
        ircclient.say('#daala','AWCY: Exploded '+job.run_id);
      }
      job_in_progress = false;
      job = null;
      process_queue();
    });
  }
};

app.use(express.static(__dirname + '/www'));
app.use('/runs',express.static(__dirname + '/runs'));
app.use('/sets.json',express.static(__dirname + '/rd_tool/sets.json'));

app.get('/run_list.json',function(req,res) {
  fs.readdir('runs',function(err,files) {
    res.send(files);
  });
});

app.get('/job_queue.json',function(req,res) {
  res.send(JSON.stringify(job_queue));
});

app.get('/job',function(req,res) {
  res.send(JSON.stringify(job));
});

app.get('/bd_rate',function(req,res) {
  var a = req.query['a'];
  var b = req.query['b'];
  var file = req.query['file'];
  var a_file = 'runs/'+a+'/video-1-short/'+file;
  var b_file = 'runs/'+b+'/video-1-short/'+file;
  cp.execFile('daalatool/tools/bd_rate.sh',[a_file,b_file],
              {env: {'BUILD_ROOT': 'daalatool/'}},
              function(error,stdout,stderr) {
    res.send(stderr+stdout);
  });
});

app.use('/submit',check_key);

app.post('/submit/job',function(req,res) {
  var job = {};
  job.codec = 'daala';
  job.commit = req.body.commit;
  job.run_id = req.body.run_id;
  job.task = 'video-1-short';
  job.task_type = 'video';
  if (fs.existsSync('runs/'+job.run_id)) {
    res.status(400).send('ID is not unique! Choose another.\n');
    return;
  }
  job_queue.push(job);
  process_queue();
  res.send('ok');
  ircclient.say('#daala','AWCY: Starting '+job.run_id);
});

app.listen(3000);
<|endoftext|>


<commit_before>/**
 * The Pad Manager is a Factory for pad Objects
 */

/*
 * 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var ERR = require("async-stacktrace");
var customError = require("../utils/customError");
var Pad = require("../db/Pad").Pad;
var db = require("./DB").db;

/**
 * An Object containing all known Pads. Provides "get" and "set" functions,
 * which should be used instead of indexing with brackets. These prepend a
 * colon to the key, to avoid conflicting with built-in Object methods or with
 * these functions themselves.
 *
 * If this is needed in other places, it would be wise to make this a prototype
 * that's defined somewhere more sensible.
 */
var globalPads = {
    get: function (name) { return this[':'+name]; },
    set: function (name, value)
    {
      this[':'+name] = value;
      padList.addPad(name);
    },
    remove: function (name) { delete this[':'+name]; }
};

var padList = {
  list: [],
  sorted : false,
  init: function()
  {
    db.findKeys("pad:*", "*:*:*", function(err, dbData)
    {
      if(ERR(err)) return;
      if(dbData != null){
        dbData.forEach(function(val){
          padList.addPad(val.replace(/pad:/,""),false);
        });
      }
    });
  },
  /**
   * Returns all pads in alphabetical order as array.
   */
  getPads: function(){
    if(!this.sorted){
      this.list=this.list.sort();
      this.sorted=true;
    }
    return this.list;
  },
  addPad: function(name)
  {
    if(this.list.indexOf(name) == -1){
      this.list.push(name);
      this.sorted=false;
    }
  },
  removePad: function(name)
  {
    var index=this.list.indexOf(name);
    if(index>-1){
      this.list.splice(index,1);
      this.sorted=false;
    }
  }
};
//initialises the allknowing data structure
padList.init();

/**
 * An array of padId transformations. These represent changes in pad name policy over
 * time, and allow us to "play back" these changes so legacy padIds can be found.
 */
var padIdTransforms = [
  [/\s+/g, '_'],
  [/:+/g, '_']
];

/**
 * Returns a Pad Object with the callback
 * @param id A String with the id of the pad
 * @param {Function} callback
 */
exports.getPad = function(id, text, callback)
{
  //check if this is a valid padId
  if(!exports.isValidPadId(id))
  {
    callback(new customError(id + " is not a valid padId","apierror"));
    return;
  }

  //make text an optional parameter
  if(typeof text == "function")
  {
    callback = text;
    text = null;
  }

  //check if this is a valid text
  if(text != null)
  {
    //check if text is a string
    if(typeof text != "string")
    {
      callback(new customError("text is not a string","apierror"));
      return;
    }

    //check if text is less than 100k chars
    if(text.length > 100000)
    {
      callback(new customError("text must be less than 100k chars","apierror"));
      return;
    }
  }

  var pad = globalPads.get(id);

  //return pad if its already loaded
  if(pad != null)
  {
    callback(null, pad);
  }
  //try to load pad
  else
  {
    pad = new Pad(id);

    //initalize the pad
    pad.init(text, function(err)
    {
      if(ERR(err, callback)) return;

      globalPads.set(id, pad);
      callback(null, pad);
    });
  }
}

exports.listAllPads = function(callback)
{
  if(callback != null){
    callback(null,{padIDs: padList.getPads()});
  }else{
    return {padIDs: padList.getPads()};
  }
}

//checks if a pad exists
exports.doesPadExists = function(padId, callback)
{
  db.get("pad:"+padId, function(err, value)
  {
    if(ERR(err, callback)) return;
    if(value != null && value.atext){
      callback(null, true);
    }
    else
    {
      callback(null, false);
    }
  });
}

//returns a sanitized padId, respecting legacy pad id formats
exports.sanitizePadId = function(padId, callback) {
  var transform_index = arguments[2] || 0;
  //we're out of possible transformations, so just return it
  if(transform_index >= padIdTransforms.length)
  {
    callback(padId);
  }
  //check if padId exists
  else
  {
    exports.doesPadExists(padId, function(junk, exists)
    {
      if(exists)
      {
        callback(padId);
      }
      else
      {
        //get the next transformation *that's different*
        var transformedPadId = padId;
        while(transformedPadId == padId && transform_index < padIdTransforms.length)
        {
          transformedPadId = padId.replace(padIdTransforms[transform_index][0], padIdTransforms[transform_index][1]);
          transform_index += 1;
        }
        //check the next transform
        exports.sanitizePadId(transformedPadId, callback, transform_index);
      }
    });
  }
}

exports.isValidPadId = function(padId)
{
  return /^(g.[a-zA-Z0-9]{16}\$)?[^$]{1,50}$/.test(padId);
}

/**
 * Removes the pad from database and unloads it.
 */
exports.removePad = function(padId){
  db.remove("pad:"+padId);
  exports.unloadPad(padId);
  padList.removePad(padId);
}

//removes a pad from the array
exports.unloadPad = function(padId)
{
  if(globalPads.get(padId))
    globalPads.remove(padId);
}
<commit_msg>Reverted change<commit_after>/**
 * The Pad Manager is a Factory for pad Objects
 */

/*
 * 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var ERR = require("async-stacktrace");
var customError = require("../utils/customError");
var Pad = require("../db/Pad").Pad;
var db = require("./DB").db;

/**
 * An Object containing all known Pads. Provides "get" and "set" functions,
 * which should be used instead of indexing with brackets. These prepend a
 * colon to the key, to avoid conflicting with built-in Object methods or with
 * these functions themselves.
 *
 * If this is needed in other places, it would be wise to make this a prototype
 * that's defined somewhere more sensible.
 */
var globalPads = {
    get: function (name) { return this[':'+name]; },
    set: function (name, value)
    {
      this[':'+name] = value;
      padList.addPad(name);
    },
    remove: function (name) { delete this[':'+name]; }
};

var padList = {
  list: [],
  sorted : false,
  init: function()
  {
    db.findKeys("pad:*", "*:*:*", function(err, dbData)
    {
      if(ERR(err)) return;
      if(dbData != null){
        dbData.forEach(function(val){
          padList.addPad(val.replace(/pad:/,""),false);
        });
      }
    });
    return this;
  },
  /**
   * Returns all pads in alphabetical order as array.
   */
  getPads: function(){
    if(!this.sorted){
      this.list=this.list.sort();
      this.sorted=true;
    }
    return this.list;
  },
  addPad: function(name)
  {
    if(this.list.indexOf(name) == -1){
      this.list.push(name);
      this.sorted=false;
    }
  },
  removePad: function(name)
  {
    var index=this.list.indexOf(name);
    if(index>-1){
      this.list.splice(index,1);
      this.sorted=false;
    }
  }
};
//initialises the allknowing data structure
padList.init();

/**
 * An array of padId transformations. These represent changes in pad name policy over
 * time, and allow us to "play back" these changes so legacy padIds can be found.
 */
var padIdTransforms = [
  [/\s+/g, '_'],
  [/:+/g, '_']
];

/**
 * Returns a Pad Object with the callback
 * @param id A String with the id of the pad
 * @param {Function} callback
 */
exports.getPad = function(id, text, callback)
{
  //check if this is a valid padId
  if(!exports.isValidPadId(id))
  {
    callback(new customError(id + " is not a valid padId","apierror"));
    return;
  }

  //make text an optional parameter
  if(typeof text == "function")
  {
    callback = text;
    text = null;
  }

  //check if this is a valid text
  if(text != null)
  {
    //check if text is a string
    if(typeof text != "string")
    {
      callback(new customError("text is not a string","apierror"));
      return;
    }

    //check if text is less than 100k chars
    if(text.length > 100000)
    {
      callback(new customError("text must be less than 100k chars","apierror"));
      return;
    }
  }

  var pad = globalPads.get(id);

  //return pad if its already loaded
  if(pad != null)
  {
    callback(null, pad);
  }
  //try to load pad
  else
  {
    pad = new Pad(id);

    //initalize the pad
    pad.init(text, function(err)
    {
      if(ERR(err, callback)) return;

      globalPads.set(id, pad);
      callback(null, pad);
    });
  }
}

exports.listAllPads = function(callback)
{
  if(callback != null){
    callback(null,{padIDs: padList.getPads()});
  }else{
    return {padIDs: padList.getPads()};
  }
}

//checks if a pad exists
exports.doesPadExists = function(padId, callback)
{
  db.get("pad:"+padId, function(err, value)
  {
    if(ERR(err, callback)) return;
    if(value != null && value.atext){
      callback(null, true);
    }
    else
    {
      callback(null, false);
    }
  });
}

//returns a sanitized padId, respecting legacy pad id formats
exports.sanitizePadId = function(padId, callback) {
  var transform_index = arguments[2] || 0;
  //we're out of possible transformations, so just return it
  if(transform_index >= padIdTransforms.length)
  {
    callback(padId);
  }
  //check if padId exists
  else
  {
    exports.doesPadExists(padId, function(junk, exists)
    {
      if(exists)
      {
        callback(padId);
      }
      else
      {
        //get the next transformation *that's different*
        var transformedPadId = padId;
        while(transformedPadId == padId && transform_index < padIdTransforms.length)
        {
          transformedPadId = padId.replace(padIdTransforms[transform_index][0], padIdTransforms[transform_index][1]);
          transform_index += 1;
        }
        //check the next transform
        exports.sanitizePadId(transformedPadId, callback, transform_index);
      }
    });
  }
}

exports.isValidPadId = function(padId)
{
  return /^(g.[a-zA-Z0-9]{16}\$)?[^$]{1,50}$/.test(padId);
}

/**
 * Removes the pad from database and unloads it.
 */
exports.removePad = function(padId){
  db.remove("pad:"+padId);
  exports.unloadPad(padId);
  padList.removePad(padId);
}

//removes a pad from the array
exports.unloadPad = function(padId)
{
  if(globalPads.get(padId))
    globalPads.remove(padId);
}
<|endoftext|>


<commit_before>import React, { useRef, useEffect, useCallback, useReducer, useMemo } from 'react'
import { FormattedMessage, useIntl } from 'react-intl'
import Modal from 'react-modal'
import cx from 'classnames'

import isNumber from 'lodash/fp/isNumber'
import initial from 'lodash/fp/initial'
import dropRightWhile from 'lodash/fp/dropRightWhile'

import HelpPin from '../../components/HelpPin'
import Spinner from '../../components/Spinner'
import PrefixSetter from '../../components/PrefixSetter'
import CardsList from '../../components/CardsList'
import KnownPageCard from '../../components/KnownPages/KnownPageCard'
import { urlToLru, lruVariations, longestMatching, lruToUrl, lruObjectToString } from '../../utils/lru'

import './InModal.styl'

const compareWithoutWww = (lru) => {
  const lrus = lruVariations(lru)
  return (url) =>
    lruVariations(url.lru).some(urlVariation =>
      lrus.some(lruVariation =>
        urlVariation.startsWith(lruVariation)
      )
    )
}

const PagesList = ({
  selectedPage,
  setSelectedPage,
  pages,
  isPaginating,
  totalPages
}) => (
  <CardsList
    displayLoader={ isPaginating }
    count={ pages.length }
    total={ totalPages }>
    { pages.map((link, index) => {
      return (
        <KnownPageCard
          isActive={ index === selectedPage }
          onClick={ () => setSelectedPage(index) }
          key={ index }
          { ...link }
          innerWidth={ 560 }
          displayHomePageButton={ false }
        />
      )
    }) }
  </CardsList>
)

const Prefixes = (props) => {
  return (
    <React.Fragment>

        <PrefixSetter
          parts={ props.prefixes }
          setPrefix={ props.onSetPrefixes }
        />

            <button
              disabled={ props.disable }
              onClick={ props.onValidate }
              className='btn btn-success'
            ><FormattedMessage id="in-modale.confirm" /></button>

    </React.Fragment>
  )
}

const parsePrefixes = (lru, url, newEntity, tldTree) => {
  const urlLru = lruObjectToString(urlToLru(url, tldTree))
  const l = lru.split('|').length
  return dropRightWhile((stem) => stem === 'p:', initial(urlLru.split('|'))).map((stem, index) => {
    const editable = newEntity ? index >= l : index >= l - 1
    return {
      name: stem,
      editable,
      selected: index < l - 1 || newEntity,
    }
  })
}

const orderList = (pages, prefix, tabLru) => {
  if (pages) {
    return [tabLru, prefix].reduce((accumulator, value) => {
      if (!accumulator.some(({ lru }) => lru === value)) {
        return [
          {
            url: lruToUrl(value),
            crawled: null,
            lru: value,
            linked: null,
          },
          ...accumulator
        ]
      } else {
        return accumulator
      }
    },
    pages.filter(compareWithoutWww(prefix)).sort((linkA, linkB) =>
      linkA.url.length - linkB.url.length || linkA.url.localeCompare(linkB.lru)
    ))
  } else {
    return []
  }
}

const modalReducer = (state, action) => {
  switch (action.type) {
  case 'ERROR':
    return { ...state, error: true, loading: false }
  case 'SET_PREFIX':
    return {
      ...state,
      prefix: action.payload,
      step: 1,
      selectedPage: null,
    }
  case 'SET_NAME':
    return {
      ...state,
      name: action.payload,
    }
  case 'VALIDATE_NAME':
    return {
      ...state,
      step: 4,
    }
  case 'SET_PAGE':
    return {
      ...state,
      selectedPage: action.payload,
      step: state.step > 2 ? 2 : state.step,
    }
  case 'SET_STEP':
    return {
      ...state,
      step: action.payload
    }
  case 'SET_TAGS':
    return {
      ...state,
      tags: action.payload
    }
  case 'SET_NOTES':
    return {
      ...state,
      notes: action.payload
    }
  case 'LOADING':
    return {
      ...state,
      loading: true
    }
  }
  return state
}

const customStyles = {
  content: {
    padding: 0,
    top: 60,
  }
}

const EntityModal = ({
  isOpen,
  onRequestClose,
  onSuccess,
  webentity,
  createNewEntity,
  tabUrl,
  tlds,
}) => {
  const { formatMessage } = useIntl()
  const longestLru = useMemo(
    () => longestMatching(webentity.prefixes, tabUrl, tlds).lru,
    [webentity.prefixes, tabUrl, tlds]
  )
  const prefixes = useMemo(
    () => parsePrefixes(lruObjectToString(longestLru), tabUrl, createNewEntity, tlds),
    [longestLru, tabUrl, createNewEntity, tlds]
  )
  const initialPrefix = useMemo(
    () => prefixes
      .filter(({ selected }) => selected)
      .reduce((prev, part) => `${prev}${part.name}|`, '')
  )

  const [state, dispatch] = useReducer(
    modalReducer,
    {
      step: 1,
      selectedPage: null,
      name: createNewEntity ? '' : webentity.name,
      prefix: initialPrefix,
      loading: false,
      error: false,
      tags: true,
      notes: true
    }
  )

  const prefixHasChanged = initialPrefix !== state.prefix
  const hasTags = !!(webentity.tags.USER && Object.keys(webentity.tags.USER).length)
  const showCopyStep = (prefixHasChanged || createNewEntity) && hasTags
  const totalStepsNumber = showCopyStep ? 4 : 3

  const pagesList = useMemo(
    () => orderList(webentity.paginatePages, state.prefix, lruObjectToString(urlToLru(tabUrl, tlds))),
    [webentity.paginatePages, state.prefix, tlds, tabUrl]
  )

  const onSubmit = useCallback(() => {
    dispatch({
      type: 'LOADING',
    })
    onSuccess(webentity, {
      prefix: state.prefix,
      homepage: pagesList[state.selectedPage].url,
      name: state.name,
      crawl: true,
      copy: {
        tags: showCopyStep && state.tags,
        notes: showCopyStep && state.notes
      },
    })
  }, [state])

  const onSetPrefixes = useCallback((prefix) => {
    if (prefix === state.prefix) {
      return
    }
    dispatch({ type: 'SET_PREFIX', payload: prefix })
  }, [state.prefix])

  const ndLock = state.step !== 2 || !isNumber(state.selectedPage)
  const nameRef = React.useRef(null)
  const onNameConfirm = useCallback(() => {
    if (nameRef.current.value.length) {
      dispatch({ type: 'VALIDATE_NAME', payload: nameRef.current.value })
    }
  }, [])
  const onInputChange = useCallback((e) => {
    dispatch({ type: 'SET_NAME', payload: e.target.value })
    if (state.step !== 3) {
      dispatch({ type: 'SET_STEP', payload: 3 })
    }
  }, [state.step])
  const setPage = useCallback((index) => dispatch({ type: 'SET_PAGE', payload: index }))
  const validatestags = useCallback(() => dispatch({ type: 'SET_STEP', payload: 5 }))

  const modalBody = useRef()
  useEffect(() => {
    if (modalBody.current) {
      const element = modalBody.current.querySelector(`.step-container:nth-child(${state.step + 1})`)
      if (element) {
        element.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'nearest' })
      }
    }
  }, [state.step])

  return (
    <Modal
      isOpen={ isOpen }
      onRequestClose={ onRequestClose }
      style={ customStyles }
      contentLabel="New entity modal"
    >

        {state.loading && (

            <Spinner />

        )}

{ createNewEntity ? <FormattedMessage id="browse-create" /> : <FormattedMessage id="in-modale.title-in" /> }

            {createNewEntity ? <FormattedMessage id="in-modale.explanation-text-first-add" /> : <FormattedMessage id="in-modale.explanation-text-first-in" />}

            <FormattedMessage id="in-modale.explanation-text-base" />

              1/{totalStepsNumber} <FormattedMessage id="in-modale.title-step-1" /><HelpPin place="top">{formatMessage({ id: 'in-modale.tooltip-step-1' })}</HelpPin>

            <Prefixes
              prefixes={ prefixes }
              onSetPrefixes={ onSetPrefixes }
              disable={ state.step > 1 }
              onValidate={ () => dispatch({ type: 'SET_STEP', payload: 2 }) }
            />

          <div className={ cx('step-container', { 'is-disabled': state.step < 2 }) }>

              2/{totalStepsNumber} <FormattedMessage id="in-modale.title-step-2" /> <HelpPin place="top">{formatMessage({ id: 'in-modale.tooltip-step-2' })}</HelpPin>
              <button disabled={ ndLock }  onClick={ () => dispatch({ type: 'SET_STEP', payload: 3 }) } className="btn btn-success"><FormattedMessage id="in-modale.confirm" /></button>

            {
              webentity.paginatePages ?
                <PagesList
                  pages={ pagesList }
                  isPaginating={ webentity.token }
                  totalPages={ webentity.pages_total }
                  selectedPage={ state.selectedPage }
                  setSelectedPage={ setPage }
                /> : <Spinner />
            }

              <button disabled={ ndLock } onClick={ () => dispatch({ type: 'SET_STEP', payload: 3 }) } className="btn btn-success"><FormattedMessage id="in-modale.confirm" /></button>

          <div className={ cx('step-container', { 'is-disabled': state.step < 3 }) }>

              3/{ totalStepsNumber } { createNewEntity ? <FormattedMessage id="in-modale.title-step-3-add" /> : <FormattedMessage id="in-modale.title-step-3-in" /> }<HelpPin place="top">{formatMessage({ id: 'in-modale.tooltip-step-3' })}</HelpPin>

              <input
                className="input"
                ref={ nameRef }
                defaultValue={ state.name }
                onChange={ onInputChange }
              />

<button disabled={ state.step !== 3 || !state.name }  onClick={ onNameConfirm } className="btn btn-success"><FormattedMessage id="in-modale.confirm" /></button>

          {
            totalStepsNumber === 4 &&
            <div className={ cx('step-container', { 'is-disabled': state.step < 4 }) }>

                4/{totalStepsNumber} <FormattedMessage id="in-modale.title-step-4" /><HelpPin  place="top">{formatMessage({ id: 'in-modale.tooltip-step-4' })}</HelpPin>

              <form className="settings-container">

                    <input defaultChecked onChange={ (event) => dispatch({ type: 'SET_TAGS', payload: event.target.checked }) } id="copy-tags" type="checkbox" /><FormattedMessage id="in-modale.copy-tags" />

                    <input defaultChecked onChange={ (event) => dispatch({ type: 'SET_NOTES', payload: event.target.checked }) } id="copy-notes" type="checkbox" /><FormattedMessage id="in-modale.copy-notes" />

                    <button disabled={ state.step !== 4 } onClick={ validatestags } className="btn btn-success"><FormattedMessage id="in-modale.confirm" /></button>

              </form>

          }

              <button
                onClick={ onRequestClose }
                className="btn btn-danger"
              ><FormattedMessage id="cancel" /></button>

              <button
                onClick={ onSubmit }
                disabled={ state.step !== totalStepsNumber + 1 }
                className="btn btn-success"
              >
                {createNewEntity ? <FormattedMessage id="in-modale.confirm-modale-add" /> : <FormattedMessage id="in-modale.confirm-modale-in" />}
              </button>

    </Modal>
  )
}

export default EntityModal
<commit_msg>fix loader count #104<commit_after>import React, { useRef, useEffect, useCallback, useReducer, useMemo } from 'react'
import { FormattedMessage, useIntl } from 'react-intl'
import Modal from 'react-modal'
import cx from 'classnames'

import isNumber from 'lodash/fp/isNumber'
import initial from 'lodash/fp/initial'
import dropRightWhile from 'lodash/fp/dropRightWhile'

import HelpPin from '../../components/HelpPin'
import Spinner from '../../components/Spinner'
import PrefixSetter from '../../components/PrefixSetter'
import CardsList from '../../components/CardsList'
import KnownPageCard from '../../components/KnownPages/KnownPageCard'
import { urlToLru, lruVariations, longestMatching, lruToUrl, lruObjectToString } from '../../utils/lru'

import './InModal.styl'

const compareWithoutWww = (lru) => {
  const lrus = lruVariations(lru)
  return (url) =>
    lruVariations(url.lru).some(urlVariation =>
      lrus.some(lruVariation =>
        urlVariation.startsWith(lruVariation)
      )
    )
}

const PagesList = ({
  selectedPage,
  setSelectedPage,
  pages,
  isPaginating,
  paginatePages,
  totalPages
}) => (
  <CardsList
    displayLoader={ isPaginating }
    count={ paginatePages }
    total={ totalPages }>
    { pages.map((link, index) => {
      return (
        <KnownPageCard
          isActive={ index === selectedPage }
          onClick={ () => setSelectedPage(index) }
          key={ index }
          { ...link }
          innerWidth={ 560 }
          displayHomePageButton={ false }
        />
      )
    }) }
  </CardsList>
)

const Prefixes = (props) => {
  return (
    <React.Fragment>

        <PrefixSetter
          parts={ props.prefixes }
          setPrefix={ props.onSetPrefixes }
        />

            <button
              disabled={ props.disable }
              onClick={ props.onValidate }
              className='btn btn-success'
            ><FormattedMessage id="in-modale.confirm" /></button>

    </React.Fragment>
  )
}

const parsePrefixes = (lru, url, newEntity, tldTree) => {
  const urlLru = lruObjectToString(urlToLru(url, tldTree))
  const l = lru.split('|').length
  return dropRightWhile((stem) => stem === 'p:', initial(urlLru.split('|'))).map((stem, index) => {
    const editable = newEntity ? index >= l : index >= l - 1
    return {
      name: stem,
      editable,
      selected: index < l - 1 || newEntity,
    }
  })
}

const orderList = (pages, prefix, tabLru) => {
  if (pages) {
    return [tabLru, prefix].reduce((accumulator, value) => {
      if (!accumulator.some(({ lru }) => lru === value)) {
        return [
          {
            url: lruToUrl(value),
            crawled: null,
            lru: value,
            linked: null,
          },
          ...accumulator
        ]
      } else {
        return accumulator
      }
    },
    pages.filter(compareWithoutWww(prefix)).sort((linkA, linkB) =>
      linkA.url.length - linkB.url.length || linkA.url.localeCompare(linkB.lru)
    ))
  } else {
    return []
  }
}

const modalReducer = (state, action) => {
  switch (action.type) {
  case 'ERROR':
    return { ...state, error: true, loading: false }
  case 'SET_PREFIX':
    return {
      ...state,
      prefix: action.payload,
      step: 1,
      selectedPage: null,
    }
  case 'SET_NAME':
    return {
      ...state,
      name: action.payload,
    }
  case 'VALIDATE_NAME':
    return {
      ...state,
      step: 4,
    }
  case 'SET_PAGE':
    return {
      ...state,
      selectedPage: action.payload,
      step: state.step > 2 ? 2 : state.step,
    }
  case 'SET_STEP':
    return {
      ...state,
      step: action.payload
    }
  case 'SET_TAGS':
    return {
      ...state,
      tags: action.payload
    }
  case 'SET_NOTES':
    return {
      ...state,
      notes: action.payload
    }
  case 'LOADING':
    return {
      ...state,
      loading: true
    }
  }
  return state
}

const customStyles = {
  content: {
    padding: 0,
    top: 60,
  }
}

const EntityModal = ({
  isOpen,
  onRequestClose,
  onSuccess,
  webentity,
  createNewEntity,
  tabUrl,
  tlds,
}) => {
  const { formatMessage } = useIntl()
  const longestLru = useMemo(
    () => longestMatching(webentity.prefixes, tabUrl, tlds).lru,
    [webentity.prefixes, tabUrl, tlds]
  )
  const prefixes = useMemo(
    () => parsePrefixes(lruObjectToString(longestLru), tabUrl, createNewEntity, tlds),
    [longestLru, tabUrl, createNewEntity, tlds]
  )
  const initialPrefix = useMemo(
    () => prefixes
      .filter(({ selected }) => selected)
      .reduce((prev, part) => `${prev}${part.name}|`, '')
  )

  const [state, dispatch] = useReducer(
    modalReducer,
    {
      step: 1,
      selectedPage: null,
      name: createNewEntity ? '' : webentity.name,
      prefix: initialPrefix,
      loading: false,
      error: false,
      tags: true,
      notes: true
    }
  )

  const prefixHasChanged = initialPrefix !== state.prefix
  const hasTags = !!(webentity.tags.USER && Object.keys(webentity.tags.USER).length)
  const showCopyStep = (prefixHasChanged || createNewEntity) && hasTags
  const totalStepsNumber = showCopyStep ? 4 : 3

  const pagesList = useMemo(
    () => orderList(webentity.paginatePages, state.prefix, lruObjectToString(urlToLru(tabUrl, tlds))),
    [webentity.paginatePages, state.prefix, tlds, tabUrl]
  )

  const onSubmit = useCallback(() => {
    dispatch({
      type: 'LOADING',
    })
    onSuccess(webentity, {
      prefix: state.prefix,
      homepage: pagesList[state.selectedPage].url,
      name: state.name,
      crawl: true,
      copy: {
        tags: showCopyStep && state.tags,
        notes: showCopyStep && state.notes
      },
    })
  }, [state])

  const onSetPrefixes = useCallback((prefix) => {
    if (prefix === state.prefix) {
      return
    }
    dispatch({ type: 'SET_PREFIX', payload: prefix })
  }, [state.prefix])

  const ndLock = state.step !== 2 || !isNumber(state.selectedPage)
  const nameRef = React.useRef(null)
  const onNameConfirm = useCallback(() => {
    if (nameRef.current.value.length) {
      dispatch({ type: 'VALIDATE_NAME', payload: nameRef.current.value })
    }
  }, [])
  const onInputChange = useCallback((e) => {
    dispatch({ type: 'SET_NAME', payload: e.target.value })
    if (state.step !== 3) {
      dispatch({ type: 'SET_STEP', payload: 3 })
    }
  }, [state.step])
  const setPage = useCallback((index) => dispatch({ type: 'SET_PAGE', payload: index }))
  const validatestags = useCallback(() => dispatch({ type: 'SET_STEP', payload: 5 }))

  const modalBody = useRef()
  useEffect(() => {
    if (modalBody.current) {
      const element = modalBody.current.querySelector(`.step-container:nth-child(${state.step + 1})`)
      if (element) {
        element.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'nearest' })
      }
    }
  }, [state.step])

  return (
    <Modal
      isOpen={ isOpen }
      onRequestClose={ onRequestClose }
      style={ customStyles }
      contentLabel="New entity modal"
    >

        {state.loading && (

            <Spinner />

        )}

{ createNewEntity ? <FormattedMessage id="browse-create" /> : <FormattedMessage id="in-modale.title-in" /> }

            {createNewEntity ? <FormattedMessage id="in-modale.explanation-text-first-add" /> : <FormattedMessage id="in-modale.explanation-text-first-in" />}

            <FormattedMessage id="in-modale.explanation-text-base" />

              1/{totalStepsNumber} <FormattedMessage id="in-modale.title-step-1" /><HelpPin place="top">{formatMessage({ id: 'in-modale.tooltip-step-1' })}</HelpPin>

            <Prefixes
              prefixes={ prefixes }
              onSetPrefixes={ onSetPrefixes }
              disable={ state.step > 1 }
              onValidate={ () => dispatch({ type: 'SET_STEP', payload: 2 }) }
            />

          <div className={ cx('step-container', { 'is-disabled': state.step < 2 }) }>

              2/{totalStepsNumber} <FormattedMessage id="in-modale.title-step-2" /> <HelpPin place="top">{formatMessage({ id: 'in-modale.tooltip-step-2' })}</HelpPin>
              <button disabled={ ndLock }  onClick={ () => dispatch({ type: 'SET_STEP', payload: 3 }) } className="btn btn-success"><FormattedMessage id="in-modale.confirm" /></button>

            {
              webentity.paginatePages ?
                <PagesList
                  pages={ pagesList }
                  isPaginating={ webentity.token }
                  paginatePages={ webentity.paginatePages.length }
                  totalPages={ webentity.pages_total }
                  selectedPage={ state.selectedPage }
                  setSelectedPage={ setPage }
                /> : <Spinner />
            }

              <button disabled={ ndLock } onClick={ () => dispatch({ type: 'SET_STEP', payload: 3 }) } className="btn btn-success"><FormattedMessage id="in-modale.confirm" /></button>

          <div className={ cx('step-container', { 'is-disabled': state.step < 3 }) }>

              3/{ totalStepsNumber } { createNewEntity ? <FormattedMessage id="in-modale.title-step-3-add" /> : <FormattedMessage id="in-modale.title-step-3-in" /> }<HelpPin place="top">{formatMessage({ id: 'in-modale.tooltip-step-3' })}</HelpPin>

              <input
                className="input"
                ref={ nameRef }
                defaultValue={ state.name }
                onChange={ onInputChange }
              />

<button disabled={ state.step !== 3 || !state.name }  onClick={ onNameConfirm } className="btn btn-success"><FormattedMessage id="in-modale.confirm" /></button>

          {
            totalStepsNumber === 4 &&
            <div className={ cx('step-container', { 'is-disabled': state.step < 4 }) }>

                4/{totalStepsNumber} <FormattedMessage id="in-modale.title-step-4" /><HelpPin  place="top">{formatMessage({ id: 'in-modale.tooltip-step-4' })}</HelpPin>

              <form className="settings-container">

                    <input defaultChecked onChange={ (event) => dispatch({ type: 'SET_TAGS', payload: event.target.checked }) } id="copy-tags" type="checkbox" /><FormattedMessage id="in-modale.copy-tags" />

                    <input defaultChecked onChange={ (event) => dispatch({ type: 'SET_NOTES', payload: event.target.checked }) } id="copy-notes" type="checkbox" /><FormattedMessage id="in-modale.copy-notes" />

                    <button disabled={ state.step !== 4 } onClick={ validatestags } className="btn btn-success"><FormattedMessage id="in-modale.confirm" /></button>

              </form>

          }

              <button
                onClick={ onRequestClose }
                className="btn btn-danger"
              ><FormattedMessage id="cancel" /></button>

              <button
                onClick={ onSubmit }
                disabled={ state.step !== totalStepsNumber + 1 }
                className="btn btn-success"
              >
                {createNewEntity ? <FormattedMessage id="in-modale.confirm-modale-add" /> : <FormattedMessage id="in-modale.confirm-modale-in" />}
              </button>

    </Modal>
  )
}

export default EntityModal
<|endoftext|>


<commit_before>"use strict";

var _ = require("lodash");
var parse = require("parse");
var unparse = require("unparse");

module.exports = _.flow(parse, solve, unparse);

function solve(problem) {
  return "solved";
}
<commit_msg>simple algo<commit_after>"use strict";

var _ = require("lodash");
var parse = require("parse");
var unparse = require("unparse");

module.exports = _.flow(parse, solve, unparse);

function solve(problem) {
  return _.times(problem.nsteps, function(istep) {
    return _.times(problem.nloons, function() {
      if (istep === 0) return 1;
      if (istep % 2 === 0) return -1;
      else return 1;
    });
  });
}
<|endoftext|>


<commit_before>import Util from "../../helpers/Util";

import HealthCheckProtocols from "../../constants/HealthCheckProtocols";
import HealthCheckPortTypes from "../../constants/HealthCheckPortTypes";

import healthChecksRowScheme from "../schemes/healthChecksRowScheme";

function hasOnlyEmptyValues(obj) {
  return obj == null || Util.isObject(obj) &&
    Object.values(obj)
    .every((element) => {
      return element == null ||
        element === false ||
        (Util.isArray(element) && element.length === 0) ||
        Util.isStringAndEmpty(element);
    });
}

const AppFormModelPostProcess = {
  acceptedResourceRoles: (app) => {
    var acceptedResourceRoles = app.acceptedResourceRoles;

    if (acceptedResourceRoles != null &&
        Util.isArray(acceptedResourceRoles) &&
        acceptedResourceRoles.length === 0) {
      app.acceptedResourceRoles = ["*"];
    }
  },
  container: (app) => {
    var container = app.container;

    if (container == null) {
      return;
    }

    let isEmpty = (Util.isArray(container.volumes) &&
        container.volumes.length === 0 ||
        container.volumes == null) &&
      hasOnlyEmptyValues(container.docker);

    if (isEmpty) {
      app.container = null;
    } else {
      // sending null unsets any pre-existing command in the API
      if (Util.isStringAndEmpty(app.cmd)) {
        app.cmd = null;
      }
    }
  },
  healthChecks: (app) => {
    var healthChecks = app.healthChecks;

    if (healthChecks == null || healthChecks.length !== 1) {
      return;
    }

    let hc = healthChecks[0];

    let isEmpty = hc.protocol === HealthCheckProtocols.HTTP &&
      hc.path == null || Util.isStringAndEmpty(healthChecks.path) &&
      ["portIndex",
      "port",
      "gracePeriodSeconds",
      "intervalSeconds",
      "timeoutSeconds",
      "maxConsecutiveFailures",
      "ignoreHttp1xx"]
        .every((key) => hc[key] === healthChecksRowScheme[key]);

    if (hc.portType === HealthCheckPortTypes.PORT_INDEX) {
      delete hc.port;
    } else if (hc.portType === HealthCheckPortTypes.PORT_NUMBER) {
      delete hc.portIndex;
    }
    delete hc.portType;

    if (isEmpty) {
      app.healthChecks = [];
    }
  }
};

export default Object.freeze(AppFormModelPostProcess);
<commit_msg>Empty fetch array can't exist beside uris array<commit_after>import Util from "../../helpers/Util";

import HealthCheckProtocols from "../../constants/HealthCheckProtocols";
import HealthCheckPortTypes from "../../constants/HealthCheckPortTypes";

import healthChecksRowScheme from "../schemes/healthChecksRowScheme";

function hasOnlyEmptyValues(obj) {
  return obj == null || Util.isObject(obj) &&
    Object.values(obj)
    .every((element) => {
      return element == null ||
        element === false ||
        (Util.isArray(element) && element.length === 0) ||
        Util.isStringAndEmpty(element);
    });
}

const AppFormModelPostProcess = {
  acceptedResourceRoles: (app) => {
    var acceptedResourceRoles = app.acceptedResourceRoles;

    if (acceptedResourceRoles != null &&
        Util.isArray(acceptedResourceRoles) &&
        acceptedResourceRoles.length === 0) {
      app.acceptedResourceRoles = ["*"];
    }
  },
  container: (app) => {
    var container = app.container;

    if (container == null) {
      return;
    }

    let isEmpty = (Util.isArray(container.volumes) &&
        container.volumes.length === 0 ||
        container.volumes == null) &&
      hasOnlyEmptyValues(container.docker);

    if (isEmpty) {
      app.container = null;
    } else {
      // sending null unsets any pre-existing command in the API
      if (Util.isStringAndEmpty(app.cmd)) {
        app.cmd = null;
      }
    }
  },
  fetch: (app) => {
    // This is a quickfix for mesosphere/marathon#3054
    // Please remove this after there is a better solution
    if (Util.isArray(app.fetch) && Util.isArray(app.uris)) {
      if (app.fetch.length === 0) {
        delete app.fetch;
      } else if (app.uris.length === 0) {
        delete app.uris;
      }
    }
  },
  healthChecks: (app) => {
    var healthChecks = app.healthChecks;

    if (healthChecks == null || healthChecks.length !== 1) {
      return;
    }

    let hc = healthChecks[0];

    let isEmpty = hc.protocol === HealthCheckProtocols.HTTP &&
      hc.path == null || Util.isStringAndEmpty(healthChecks.path) &&
      ["portIndex",
      "port",
      "gracePeriodSeconds",
      "intervalSeconds",
      "timeoutSeconds",
      "maxConsecutiveFailures",
      "ignoreHttp1xx"]
        .every((key) => hc[key] === healthChecksRowScheme[key]);

    if (hc.portType === HealthCheckPortTypes.PORT_INDEX) {
      delete hc.port;
    } else if (hc.portType === HealthCheckPortTypes.PORT_NUMBER) {
      delete hc.portIndex;
    }
    delete hc.portType;

    if (isEmpty) {
      app.healthChecks = [];
    }
  }
};

export default Object.freeze(AppFormModelPostProcess);
<|endoftext|>


<commit_before>const BinaryPjax       = require('../../../../base/binary_pjax');
const Client           = require('../../../../base/client');
const BinarySocket     = require('../../../../base/socket');
const localize         = require('../../../../../_common/localize').localize;
const State            = require('../../../../../_common/storage').State;
const getPropertyValue = require('../../../../../_common/utility').getPropertyValue;

const professionalClient = (() => {
    let is_in_page = false;

    const onLoad = () => {
        BinarySocket.wait('get_account_status').then((response) => {
            if (/professional_requested|professional/.test(getPropertyValue(response, ['get_account_status', 'status']))) {
                BinaryPjax.loadPreviousUrl();
                return;
            }
            init(Client.isAccountOfType('financial'), true);
        });
    };

    const init = (is_financial, is_page) => {
        is_in_page = !!is_page;
        BinarySocket.wait('landing_company').then(() => { populateProfessionalClient(is_financial); });
    };

    const populateProfessionalClient = (is_financial) => {
        const has_maltainvest = State.getResponse('landing_company.financial_company.shortcode') === 'maltainvest';
        if (!has_maltainvest || !is_financial) { // then it's not upgrading to financial
            if (is_in_page) {
                BinaryPjax.loadPreviousUrl();
            }
            return;
        }
        const $container        = $('#fs_professional');
        const $chk_professional = $container.find('#chk_professional');
        const $info             = $container.find('#professional_info');
        const $popup_contents   = $container.find('#popup');
        const $error            = $('#form_message');
        const popup_selector    = '#professional_popup';

        $container.find('#professional_info_toggle').off('click').on('click', function() {
            $(this).toggleClass('open');
            $info.slideToggle();
            $(`#${Client.get('residence') === 'gb' ? '' : 'non_'}uk`).toggleClass('invisible');
        });

        $chk_professional.on('change', () => {
            if ($chk_professional.is(':checked') && !$(popup_selector).length) {
                $('body').append($('<div/>', { id: 'professional_popup', class: 'lightbox' }).append($popup_contents.clone().setVisibility(1)));

                const $popup = $(popup_selector);
                $popup.find('#btn_accept, #btn_decline').off('click').on('click dblclick', function() {
                    if ($(this).attr('data-value') === 'decline') {
                        $chk_professional.prop('checked', false);
                    }
                    $popup.remove();
                });
            }
        });

        if (has_maltainvest) {
            $container.find('#show_financial').setVisibility(1);
        }

        $container.setVisibility(1);

        if (is_in_page) {
            $('#loading').remove();
            $('#frm_professional')
                .off('submit')
                .on('submit', (e) => {
                    e.preventDefault();
                    if ($chk_professional.is(':checked')) {
                        BinarySocket.wait('get_settings').then((res) => {
                            BinarySocket.send(populateReq(res.get_settings)).then((response) => {
                                if (response.error) {
                                    $error.text(response.error.message).removeClass('invisible');
                                } else {
                                    BinarySocket.send({get_account_status: 1}).then(() => {
                                        BinaryPjax.loadPreviousUrl();
                                    });
                                }
                            });
                        });
                    } else {
                        $error.text(localize('This field is required.')).removeClass('invisible');
                    }
                })
                .setVisibility(1);
        }
    };

    const populateReq = (get_settings) => {
        const req = {
            set_settings               : 1,
            request_professional_status: 1,
        };

        if (get_settings.tax_identification_number) {
            req.tax_identification_number = get_settings.tax_identification_number;
        }
        if (get_settings.tax_residence) {
            req.tax_residence = get_settings.tax_residence;
        }

        return req;
    };

    return {
        onLoad,
        init,
    };
})();

module.exports = professionalClient;
<commit_msg>Close dialog on ESC<commit_after>const BinaryPjax       = require('../../../../base/binary_pjax');
const Client           = require('../../../../base/client');
const BinarySocket     = require('../../../../base/socket');
const localize         = require('../../../../../_common/localize').localize;
const State            = require('../../../../../_common/storage').State;
const getPropertyValue = require('../../../../../_common/utility').getPropertyValue;

const professionalClient = (() => {
    let is_in_page = false;

    const onLoad = () => {
        BinarySocket.wait('get_account_status').then((response) => {
            if (/professional_requested|professional/.test(getPropertyValue(response, ['get_account_status', 'status']))) {
                BinaryPjax.loadPreviousUrl();
                return;
            }
            init(Client.isAccountOfType('financial'), true);
        });
    };

    const init = (is_financial, is_page) => {
        is_in_page = !!is_page;
        BinarySocket.wait('landing_company').then(() => { populateProfessionalClient(is_financial); });
    };

    const populateProfessionalClient = (is_financial) => {
        const has_maltainvest = State.getResponse('landing_company.financial_company.shortcode') === 'maltainvest';
        if (!has_maltainvest || !is_financial) { // then it's not upgrading to financial
            if (is_in_page) {
                BinaryPjax.loadPreviousUrl();
            }
            return;
        }
        const $container        = $('#fs_professional');
        const $chk_professional = $container.find('#chk_professional');
        const $info             = $container.find('#professional_info');
        const $popup_contents   = $container.find('#popup');
        const $error            = $('#form_message');
        const popup_selector    = '#professional_popup';

        $container.find('#professional_info_toggle').off('click').on('click', function() {
            $(this).toggleClass('open');
            $info.slideToggle();
            $(`#${Client.get('residence') === 'gb' ? '' : 'non_'}uk`).toggleClass('invisible');
        });

        $chk_professional.on('change', () => {
            if ($chk_professional.is(':checked') && !$(popup_selector).length) {
                $('body').append($('<div/>', { id: 'professional_popup', class: 'lightbox' }).append($popup_contents.clone().setVisibility(1)));

                const $popup = $(popup_selector);
                $popup.find('#btn_accept, #btn_decline').off('click').on('click dblclick', function() {
                    if ($(this).attr('data-value') === 'decline') {
                        $chk_professional.prop('checked', false);
                    }
                    $popup.remove();
                });
            }
        });

        if (has_maltainvest) {
            $container.find('#show_financial').setVisibility(1);
        }

        $container.setVisibility(1);

        if (is_in_page) {
            $('#loading').remove();
            $('#frm_professional')
                .off('submit')
                .on('submit', (e) => {
                    e.preventDefault();
                    if ($chk_professional.is(':checked')) {
                        BinarySocket.wait('get_settings').then((res) => {
                            BinarySocket.send(populateReq(res.get_settings)).then((response) => {
                                if (response.error) {
                                    $error.text(response.error.message).removeClass('invisible');
                                } else {
                                    BinarySocket.send({get_account_status: 1}).then(() => {
                                        BinaryPjax.loadPreviousUrl();
                                    });
                                }
                            });
                        });
                    } else {
                        $error.text(localize('This field is required.')).removeClass('invisible');
                    }
                })
                .setVisibility(1);
        }

        $(document).on('keydown', (e) => {
            const $popup = $(popup_selector);
            if (e.which === 27 && $popup.length) {
                $popup.remove();
                $chk_professional.prop('checked', false);
            }
        });
    };

    const populateReq = (get_settings) => {
        const req = {
            set_settings               : 1,
            request_professional_status: 1,
        };

        if (get_settings.tax_identification_number) {
            req.tax_identification_number = get_settings.tax_identification_number;
        }
        if (get_settings.tax_residence) {
            req.tax_residence = get_settings.tax_residence;
        }

        return req;
    };

    return {
        onLoad,
        init,
    };
})();

module.exports = professionalClient;
<|endoftext|>


<commit_before>import {expect} from 'chai'
import {describe, it} from 'mocha'
import {changeValue, validate, CHANGE_VALUE, VALIDATION_RESOLVED} from 'ember-frost-bunsen/actions'
import _ from 'lodash'

describe('changeValue action', function () {
  it(`returns a dispatcher action with type "${CHANGE_VALUE}"`, function () {
    const action = changeValue('some.path', 'value')

    expect(action).to.eql({
      type: CHANGE_VALUE,
      bunsenId: 'some.path',
      value: 'value'
    })
  })
})

describe('validate action', function () {
  const SCHEMA_WITH_DEFAULTS = {
    type: 'object',
    properties: {
      firstName: {
        type: 'string',
        default: 'Bruce'
      },
      lastName: {
        type: 'string',
        default: 'Wayne'
      },
      alias: {
        type: 'string',
        title: 'Nickname',
        default: 'Batman'
      },
      onlyChild: {
        type: 'boolean',
        default: true
      },
      age: {
        type: 'number',
        title: 'Age'
      }
    },
    required: ['lastName']
  }
  const SCHEMA_WITH_OBJECT_DEFAULTS = {
    type: 'object',
    properties: {
      firstName: {
        type: 'string',
        default: 'Bruce'
      },
      lastName: {
        type: 'string',
        default: 'Wayne'
      },
      alias: {
        type: 'string',
        title: 'Nickname',
        default: 'Batman'
      },
      onlyChild: {
        type: 'boolean',
        default: true
      },
      age: {
        type: 'number',
        title: 'Age'
      }
    },
    required: ['lastName'],
    default: {
      firstName: 'Clark',
      lastName: 'Kent',
      alias: 'Superman'
    }
  }
  const SCHEMA_WITH_DEEP_DEFAULTS = {
    type: 'object',
    properties: {
      someotherProp: {
        type: 'object',
        properties: {
          name: {
            type: 'object',
            properties: {
              firstName: {
                type: 'string',
                default: 'Bruce'
              },
              lastName: {
                type: 'string',
                default: 'Wayne'
              }
            }
          }
        }
      },
      alias: {
        type: 'string',
        title: 'Nickname',
        default: 'Batman'
      }
    },
    required: ['alias']
  }

  const SCHEMA_WITH_REFS = {
    type: 'object',
    properties: {
      hero: {
        type: 'object',
        '$ref': '#/definitions/superhero'
      }
    },
    required: ['hero'],
    definitions: {
      superhero: {
        type: 'object',
        properties: {
          firstName: {
            type: 'string',
            default: 'Bruce'
          },
          lastName: {
            type: 'string',
            default: 'Wayne'
          },
          alias: {
            type: 'string',
            title: 'Nickname',
            default: 'Batman'
          }
        }
      }
    }
  }

  const SCHEMA_WITH_NO_DEFAULTS = {
    type: 'object',
    properties: {
      someotherProp: {
        type: 'object',
        properties: {
          name: {
            type: 'object',
            properties: {
              firstName: {
                type: 'string'
              },
              lastName: {
                type: 'string'
              }
            }
          }
        }
      },
      alias: {
        type: 'string',
        title: 'Nickname'
      }
    }
  }

  const SCHEMA_WITH_ARRAY_DEFAULTS = {
    type: 'object',
    properties: {
      superheroes: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            firstName: {
              type: 'string',
              default: 'Bruce'
            },
            lastName: {
              type: 'string',
              default: 'Wayne'
            },
            alias: {
              type: 'string',
              title: 'Nickname',
              default: 'Batman'
            }
          }
        }
      }
    }
  }

  function getDefaultValue (path, initialValue, schema) {
    const thunk = validate(path, initialValue, schema, [])
    const defaultValue = {}

    thunk(function (action) {
      _.assign(defaultValue, action.value)
    }, function () { return {} })

    return defaultValue
  }
  it('fills in defaults', function () {
    const defaultValue = getDefaultValue(null, {}, SCHEMA_WITH_DEFAULTS)
    expect(defaultValue).to.eql({
      firstName: 'Bruce',
      lastName: 'Wayne',
      alias: 'Batman',
      onlyChild: true
    })
  })

  it('fills in defaults for specific values', function () {
    const defaultValue = getDefaultValue('someotherProp.name', {}, SCHEMA_WITH_DEEP_DEFAULTS)

    expect(defaultValue).to.eql({
      firstName: 'Bruce',
      lastName: 'Wayne'
    })
  })

  it('handles defaults in deep objects', function () {
    const defaultValue = getDefaultValue(null, {}, SCHEMA_WITH_DEEP_DEFAULTS)
    expect(defaultValue).to.eql({
      someotherProp: {
        name: {
          firstName: 'Bruce',
          lastName: 'Wayne'
        }
      },
      alias: 'Batman'
    })
  })

  it('handles defaults for objects', function () {
    const defaultValue = getDefaultValue(null, {}, SCHEMA_WITH_OBJECT_DEFAULTS)
    expect(defaultValue).to.eql({
      firstName: 'Clark',
      lastName: 'Kent',
      alias: 'Superman',
      onlyChild: true
    })
  })

  it('handles defaults in refs', function () {
    const defaultValue = getDefaultValue(null, {}, SCHEMA_WITH_REFS)
    expect(defaultValue).to.eql({
      hero: {
        firstName: 'Bruce',
        lastName: 'Wayne',
        alias: 'Batman'
      }
    })
  })

  it('handles a schema with no defaults', function () {
    const defaultValue = getDefaultValue(null, {}, SCHEMA_WITH_NO_DEFAULTS)
    expect(defaultValue).to.eql({})
  })

  function getState () {
    return {
      get value () {
        return {}
      }
    }
  }

  it('resolves if no validators are given', function () {
    let thunk = validate(null, {}, SCHEMA_WITH_DEFAULTS, [])
    thunk(function (action) {
      if (action.type === VALIDATION_RESOLVED) {
        expect(action.errors).to.eql([])
      }
    }, getState)
  })

  it('handles defaults for new array elements', function () {
    const defaultValue = getDefaultValue('superheroes.0', {}, SCHEMA_WITH_ARRAY_DEFAULTS)

    expect(defaultValue).to.eql({
      firstName: 'Bruce',
      lastName: 'Wayne',
      alias: 'Batman'
    })
  })
})
<commit_msg>Fix test<commit_after>import {expect} from 'chai'
import {describe, it} from 'mocha'
import {changeValue, validate, CHANGE_VALUE, VALIDATION_RESOLVED} from 'ember-frost-bunsen/actions'
import _ from 'lodash'

describe('changeValue action', function () {
  it(`returns a dispatcher action with type "${CHANGE_VALUE}"`, function () {
    const action = changeValue('some.path', 'value')

    expect(action).to.eql({
      type: CHANGE_VALUE,
      bunsenId: 'some.path',
      value: 'value'
    })
  })
})

describe('validate action', function () {
  const SCHEMA_WITH_DEFAULTS = {
    type: 'object',
    properties: {
      firstName: {
        type: 'string',
        default: 'Bruce'
      },
      lastName: {
        type: 'string',
        default: 'Wayne'
      },
      alias: {
        type: 'string',
        title: 'Nickname',
        default: 'Batman'
      },
      onlyChild: {
        type: 'boolean',
        default: true
      },
      age: {
        type: 'number',
        title: 'Age'
      }
    },
    required: ['lastName']
  }
  const SCHEMA_WITH_OBJECT_DEFAULTS = {
    type: 'object',
    properties: {
      firstName: {
        type: 'string',
        default: 'Bruce'
      },
      lastName: {
        type: 'string',
        default: 'Wayne'
      },
      alias: {
        type: 'string',
        title: 'Nickname',
        default: 'Batman'
      },
      onlyChild: {
        type: 'boolean',
        default: true
      },
      age: {
        type: 'number',
        title: 'Age'
      }
    },
    required: ['lastName'],
    default: {
      firstName: 'Clark',
      lastName: 'Kent',
      alias: 'Superman'
    }
  }
  const SCHEMA_WITH_DEEP_DEFAULTS = {
    type: 'object',
    properties: {
      someotherProp: {
        type: 'object',
        properties: {
          name: {
            type: 'object',
            properties: {
              firstName: {
                type: 'string',
                default: 'Bruce'
              },
              lastName: {
                type: 'string',
                default: 'Wayne'
              }
            }
          }
        }
      },
      alias: {
        type: 'string',
        title: 'Nickname',
        default: 'Batman'
      }
    },
    required: ['alias']
  }

  const SCHEMA_WITH_REFS = {
    type: 'object',
    properties: {
      hero: {
        type: 'object',
        '$ref': '#/definitions/superhero'
      }
    },
    required: ['hero'],
    definitions: {
      superhero: {
        type: 'object',
        properties: {
          firstName: {
            type: 'string',
            default: 'Bruce'
          },
          lastName: {
            type: 'string',
            default: 'Wayne'
          },
          alias: {
            type: 'string',
            title: 'Nickname',
            default: 'Batman'
          }
        }
      }
    }
  }

  const SCHEMA_WITH_NO_DEFAULTS = {
    type: 'object',
    properties: {
      someotherProp: {
        type: 'object',
        properties: {
          name: {
            type: 'object',
            properties: {
              firstName: {
                type: 'string'
              },
              lastName: {
                type: 'string'
              }
            }
          }
        }
      },
      alias: {
        type: 'string',
        title: 'Nickname'
      }
    }
  }

  const SCHEMA_WITH_ARRAY_DEFAULTS = {
    type: 'object',
    properties: {
      superheroes: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            firstName: {
              type: 'string',
              default: 'Bruce'
            },
            lastName: {
              type: 'string',
              default: 'Wayne'
            },
            alias: {
              type: 'string',
              title: 'Nickname',
              default: 'Batman'
            }
          }
        }
      }
    }
  }

  function getDefaultValue (path, initialValue, schema) {
    const thunk = validate(path, initialValue, schema, [])
    const defaultValue = {}

    thunk(function (action) {
      _.assign(defaultValue, action.value)
    }, function () { return {} })

    return defaultValue
  }
  it('fills in defaults', function () {
    const defaultValue = getDefaultValue(null, {}, SCHEMA_WITH_DEFAULTS)
    expect(defaultValue).to.eql({
      firstName: 'Bruce',
      lastName: 'Wayne',
      alias: 'Batman',
      onlyChild: true
    })
  })

  it('fills in defaults for specific values', function () {
    const defaultValue = getDefaultValue('someotherProp.name', {}, SCHEMA_WITH_DEEP_DEFAULTS)

    expect(defaultValue).to.eql({
      firstName: 'Bruce',
      lastName: 'Wayne'
    })
  })

  it('handles defaults in deep objects', function () {
    const defaultValue = getDefaultValue(null, {}, SCHEMA_WITH_DEEP_DEFAULTS)
    expect(defaultValue).to.eql({
      someotherProp: {
        name: {
          firstName: 'Bruce',
          lastName: 'Wayne'
        }
      },
      alias: 'Batman'
    })
  })

  it('handles defaults for objects', function () {
    const defaultValue = getDefaultValue(null, {}, SCHEMA_WITH_OBJECT_DEFAULTS)
    expect(defaultValue).to.eql({
      firstName: 'Clark',
      lastName: 'Kent',
      alias: 'Superman',
      onlyChild: true
    })
  })

  it('handles defaults in refs', function () {
    const defaultValue = getDefaultValue(null, {}, SCHEMA_WITH_REFS)
    expect(defaultValue).to.eql({
      hero: {
        firstName: 'Bruce',
        lastName: 'Wayne',
        alias: 'Batman'
      }
    })
  })

  it('handles a schema with no defaults', function () {
    const defaultValue = getDefaultValue(null, {}, SCHEMA_WITH_NO_DEFAULTS)
    expect(defaultValue).to.eql({})
  })

  function getState () {
    return {
      get value () {
        return {}
      }
    }
  }

  it('resolves if no validators are given', function () {
    const schema = _.cloneDeep(SCHEMA_WITH_DEFAULTS)
    delete schema.required
    let thunk = validate(null, {}, schema, [])
    thunk(function (action) {
      if (action.type === VALIDATION_RESOLVED) {
        expect(action.errors).to.eql({})
      }
    }, getState)
  })

  it('handles defaults for new array elements', function () {
    const defaultValue = getDefaultValue('superheroes.0', {}, SCHEMA_WITH_ARRAY_DEFAULTS)

    expect(defaultValue).to.eql({
      firstName: 'Bruce',
      lastName: 'Wayne',
      alias: 'Batman'
    })
  })
})
<|endoftext|>