<commit_before>"use strict";

/**
 *   avi.js is a javascript avi encoder
 *   @license Copyright (C) 2012 Sebastian Mayr
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

(function() {

	/**
	 * @param {Uint8Array} buf
	 * @param {number} idx
	 * @param {Array.<number>} bytes
	 */
	function writeBytes(buf, idx, bytes) {
		for (var i=0; i < bytes.length; ++i) {
			buf[idx + i] = bytes[i];
		}
	}

	/**
	 * @param {Uint8Array} buf
	 * @param {number} idx
	 * @param {number} num
	 */
	function writeShort(buf, idx, num) {
		buf[idx] = num & 255;
		buf[idx + 1] = (num >> 8) & 255;
	}

	/**
	 * @param {Uint8Array} buf
	 * @param {number} idx
	 * @param {number} num
	 */
	function writeInt(buf, idx, num) {
		buf[idx] = num & 255;
		buf[idx + 1] = (num >> 8) & 255;
		buf[idx + 2] = (num >> 16) & 255;
		buf[idx + 3] = (num >> 24) & 255;
	}

	/**
	 * @param {number} idx
	 * @param {number} num
	 */
	function writeLong(buf, idx, num) {
		buf[idx] = num & 255;
		buf[idx + 1] = (num >> 8) & 255;
		buf[idx + 2] = (num >> 16) & 255;
		buf[idx + 3] = (num >> 24) & 255;
		buf[idx + 4] = 0;
		buf[idx + 5] = 0;
		buf[idx + 6] = 0;
		buf[idx + 7] = 0;
	};

	/**
	 * @param {number} idx
	 * @param {string} str
	 */
	function writeString(buf, idx, str) {
		for (var i=0; i < str.length; ++i) {
			buf[idx + i] = str.charCodeAt(i) & 255;
		}
	};

	/**
	 * @constructor
	 */
	function AVIJS() {
		this.settings = {
			width: 0,
			height: 0
		};

		this.streams = [];
	};

	AVIJS.prototype.getHeaderLength = function() {
		return 12 /* RIFF */ + 12 /* hdrl */ + 8 /* avih */ + 56 /* struct */ + 12 /* movi */;
	};

	AVIJS.prototype.getLength = function() {
		var len = this.getHeaderLength();
		for (var i=0; i < this.streams.length; ++i) {
			len += this.streams[i].getHeaderLength() + this.streams[i].getDataLength();
		}
		return len;
	};

	AVIJS.prototype.getBuffer = function() {
		var dataOffset = {};
		var offset = 0;
		var frames = 0;
		var streamHeaderLength = 0;
		for (var i=0; i < this.streams.length; ++i) {
			frames += this.streams[i].frames.length;
			streamHeaderLength += this.streams[i].getHeaderLength();
			dataOffset[i] = offset;
			offset += this.streams[i].getDataLength();
		}
		var moviOffset = this.getHeaderLength() + streamHeaderLength;

		var buffer = new Uint8Array(moviOffset + offset);
		writeString(buffer, 0, 'RIFF');
		writeString(buffer, 8, 'AVI ');

		writeString(buffer, 12, 'LIST');
		writeInt(buffer, 16, 68 + streamHeaderLength);
		writeString(buffer, 20, 'hdrl'); // hdrl list
		writeString(buffer, 24, 'avih'); // avih chunk
		writeInt(buffer, 28, 56); // avih size

		writeInt(buffer, 32, 66665);
		writeInt(buffer, 36, 0); // MaxBytesPerSec
		writeInt(buffer, 40, 2); // Padding (in bytes)
		writeInt(buffer, 44, 0); // Flags
		writeInt(buffer, 48, frames); // Total Frames
		writeInt(buffer, 52, 0); // Initial Frames
		writeInt(buffer, 56, this.streams.length); // Total Streams
		writeInt(buffer, 60, 0); // Suggested Buffer size
		writeInt(buffer, 64, this.settings.width); // pixel width
		writeInt(buffer, 68, this.settings.height); // pixel height
		writeInt(buffer, 72, 0); // Reserved int[4]
		writeInt(buffer, 76, 0);
		writeInt(buffer, 80, 0);
		writeInt(buffer, 84, 0);

		var len = 88;
		offset = 0;
		for (var i=0; i < this.streams.length; ++i) {
			len += this.streams[i].writeHeaderBuffer(buffer.subarray(88 + offset), i, moviOffset + dataOffset[i]);
		}

		writeString(buffer, len, 'LIST');
		writeString(buffer, len + 8, 'movi');

		var moviLen = 4;
		for (var i=0; i < this.streams.length; ++i) {
			moviLen += this.streams[i].writeDataBuffer(buffer.subarray(len + 8 + moviLen), i);
		}
		writeInt(buffer, len + 4, moviLen);

		writeInt(buffer, 4, len + moviLen);
		var blob = new BlobBuilder();
		blob.append(buffer.buffer);
		return blob.getBlob('video/avi');
	};

	/**
	 * @constructor
 	 * @param {number} fps
	 */
	AVIJS.Stream = function(fps, width, height) {
		this.fps = fps;
		this.width = width;
		this.height = height;
		this.frames = [];
	};

	AVIJS.Stream.prototype.addRGBAFrame = function(imgData) {
		var frame = new Uint8Array(imgData.length);
		for (var i=0; i < frame.length; i += 4) {
			frame[i] = imgData[i + 2];
			frame[i + 1] = imgData[i + 1];
			frame[i + 2] = imgData[i];
		}
		this.frames.push(frame);
	};

	AVIJS.Stream.prototype.getHeaderLength = function() {
		return 12 /* strl */ + 8 /* strh */ + 56 /* struct */ + 8 /* strf */ + 40 /* struct */ + 8 /* indx */ + 24 /* struct */ + this.frames.length * 4 * 2;
	};

	AVIJS.Stream.prototype.getDataLength = function() {
		var len = 0;
		for (var i=0; i < this.frames.length; ++i) {
			len += 8 + this.frames[i].length + (this.frames[i].length % 2 == 0 ? 0 : 1); // Pad if chunk not in word boundary
		}
		return len;
	};

	AVIJS.Stream.prototype.writeHeaderBuffer = function(buf, idx, dataOffset) {
		writeString(buf, 0, 'LIST');
		writeInt(buf, 4, 148 + this.frames.length * 4 * 2);
		writeString(buf, 8, 'strl');
		writeString(buf, 12, 'strh');
		writeInt(buf, 16, 56);
		writeString(buf, 20, 'vids'); // fourCC
		writeString(buf, 24, 'DIB '); // Uncompressed
		writeInt(buf, 28, 0); // Flags
		writeShort(buf, 32, 1); // Priority
		writeShort(buf, 34, 0); // Language
		writeInt(buf, 36, 0); // Initial frames
		writeInt(buf, 40, 1); // Scale
		writeInt(buf, 44, this.fps); // Rate
		writeInt(buf, 48, 0); // Startdelay
		writeInt(buf, 52, this.frames.length); // Length
		writeInt(buf, 56, this.width * this.height * 3); // suggested buffer size
		writeInt(buf, 60, -1); // quality
		writeInt(buf, 64, 0); // sampleSize
		writeShort(buf, 68, 0); // Rect left
		writeShort(buf, 70, 0); // Rect top
		writeShort(buf, 72, this.width); // Rect width
		writeShort(buf, 74, this.height); // Rect height

		writeString(buf, 76, 'strf');
		writeInt(buf, 80, 40);
		writeInt(buf, 84, 40); // struct size
		writeInt(buf, 88, this.width); // width
		writeInt(buf, 92, -this.height); // height
		writeShort(buf, 96, 1); // planes
		writeShort(buf, 98, 32); // bits per pixel
		writeInt(buf, 100, 0); // compression
		writeInt(buf, 104, 0); // image size
		writeInt(buf, 108, 0); // x pixels per meter
		writeInt(buf, 112, 0); // y pixels per meter
		writeInt(buf, 116, 0); // colortable used
		writeInt(buf, 120, 0); // colortable important

		writeString(buf, 124, 'indx');
		writeInt(buf, 128, 24 + this.frames.length * 4 * 2); // size
		writeShort(buf, 132, 2); // LongsPerEntry
		writeBytes(buf, 134, [0, 0x01]); // indexSubType + indexType
		writeInt(buf, 136, this.frames.length); // numIndexEntries
		writeString(buf, 140, (idx < 10 ? '0' + idx : idx) + 'db'); // chunkID
		writeLong(buf, 144, dataOffset); // data offset
		writeInt(buf, 152, 0); // reserved

		var offset = 0;
		for (var i=0; i < this.frames.length; ++i) { // index entries
			writeInt(buf, 156 + i * 8, offset); // offset
			writeInt(buf, 160 + i * 8, this.frames[i].length + 8); // size
			offset += this.frames[i].length + 8;
		}

		return 156 + this.frames.length * 4 * 2;
	};

	AVIJS.Stream.prototype.writeDataBuffer = function(buf, idx) {
		var len = 0;
		for (var i=0; i < this.frames.length; ++i) {
			writeString(buf, len, (idx < 10 ? '0' + idx : idx) + 'db');
			writeInt(buf, len + 4, this.frames[i].length);
			writeBytes(buf, len + 8, this.frames[i]);
			len += this.frames[i].length + 8;
		}
		return len;
	};

	var scope = new Function('return this')();
	scope['AVIJS'] = AVIJS;
})();<commit_msg>Added a webworker API.<commit_after>"use strict";

/**
 *   avi.js is a javascript avi encoder
 *   @license Copyright (C) 2012 Sebastian Mayr
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

(function() {

	/**
	 * @param {Uint8Array} buf
	 * @param {number} idx
	 * @param {Array.<number>} bytes
	 */
	function writeBytes(buf, idx, bytes) {
		for (var i=0; i < bytes.length; ++i) {
			buf[idx + i] = bytes[i];
		}
	}

	/**
	 * @param {Uint8Array} buf
	 * @param {number} idx
	 * @param {number} num
	 */
	function writeShort(buf, idx, num) {
		buf[idx] = num & 255;
		buf[idx + 1] = (num >> 8) & 255;
	}

	/**
	 * @param {Uint8Array} buf
	 * @param {number} idx
	 * @param {number} num
	 */
	function writeInt(buf, idx, num) {
		buf[idx] = num & 255;
		buf[idx + 1] = (num >> 8) & 255;
		buf[idx + 2] = (num >> 16) & 255;
		buf[idx + 3] = (num >> 24) & 255;
	}

	/**
	 * @param {number} idx
	 * @param {number} num
	 */
	function writeLong(buf, idx, num) {
		buf[idx] = num & 255;
		buf[idx + 1] = (num >> 8) & 255;
		buf[idx + 2] = (num >> 16) & 255;
		buf[idx + 3] = (num >> 24) & 255;
		buf[idx + 4] = 0;
		buf[idx + 5] = 0;
		buf[idx + 6] = 0;
		buf[idx + 7] = 0;
	};

	/**
	 * @param {number} idx
	 * @param {string} str
	 */
	function writeString(buf, idx, str) {
		for (var i=0; i < str.length; ++i) {
			buf[idx + i] = str.charCodeAt(i) & 255;
		}
	};

	/**
	 * @constructor
	 */
	function AVIJS() {
		this.settings = {
			width: 0,
			height: 0
		};

		this.streams = [];
	};

	AVIJS.prototype.getHeaderLength = function() {
		return 12 /* RIFF */ + 12 /* hdrl */ + 8 /* avih */ + 56 /* struct */ + 12 /* movi */;
	};

	AVIJS.prototype.getLength = function() {
		var len = this.getHeaderLength();
		for (var i=0; i < this.streams.length; ++i) {
			len += this.streams[i].getHeaderLength() + this.streams[i].getDataLength();
		}
		return len;
	};

	AVIJS.prototype.getBuffer = function() {
		var dataOffset = {};
		var offset = 0;
		var frames = 0;
		var streamHeaderLength = 0;
		for (var i=0; i < this.streams.length; ++i) {
			frames += this.streams[i].frames.length;
			streamHeaderLength += this.streams[i].getHeaderLength();
			dataOffset[i] = offset;
			offset += this.streams[i].getDataLength();
		}
		var moviOffset = this.getHeaderLength() + streamHeaderLength;

		var buffer = new Uint8Array(moviOffset + offset);
		writeString(buffer, 0, 'RIFF');
		writeString(buffer, 8, 'AVI ');

		writeString(buffer, 12, 'LIST');
		writeInt(buffer, 16, 68 + streamHeaderLength);
		writeString(buffer, 20, 'hdrl'); // hdrl list
		writeString(buffer, 24, 'avih'); // avih chunk
		writeInt(buffer, 28, 56); // avih size

		writeInt(buffer, 32, 66665);
		writeInt(buffer, 36, 0); // MaxBytesPerSec
		writeInt(buffer, 40, 2); // Padding (in bytes)
		writeInt(buffer, 44, 0); // Flags
		writeInt(buffer, 48, frames); // Total Frames
		writeInt(buffer, 52, 0); // Initial Frames
		writeInt(buffer, 56, this.streams.length); // Total Streams
		writeInt(buffer, 60, 0); // Suggested Buffer size
		writeInt(buffer, 64, this.settings.width); // pixel width
		writeInt(buffer, 68, this.settings.height); // pixel height
		writeInt(buffer, 72, 0); // Reserved int[4]
		writeInt(buffer, 76, 0);
		writeInt(buffer, 80, 0);
		writeInt(buffer, 84, 0);

		var len = 88;
		offset = 0;
		for (var i=0; i < this.streams.length; ++i) {
			len += this.streams[i].writeHeaderBuffer(buffer.subarray(88 + offset), i, moviOffset + dataOffset[i]);
		}

		writeString(buffer, len, 'LIST');
		writeString(buffer, len + 8, 'movi');

		var moviLen = 4;
		for (var i=0; i < this.streams.length; ++i) {
			moviLen += this.streams[i].writeDataBuffer(buffer.subarray(len + 8 + moviLen), i);
		}
		writeInt(buffer, len + 4, moviLen);

		writeInt(buffer, 4, len + moviLen);

		var blob;
		try {
			blob = new Blob([buffer.buffer], { 'type' : 'video/avi' });
		} catch (e) {
			var builder = new (typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof WebKitBlobBuilder !== 'undefined' ? WebKitBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : MSBlobBuilder)();
			builder.append(buffer.buffer);
			blob = builder.getBlob('video/avi')
		}

		return blob;
	};

	/**
	 * @constructor
 	 * @param {number} fps
	 */
	AVIJS.Stream = function(fps, width, height) {
		this.fps = fps;
		this.width = width;
		this.height = height;
		this.frames = [];
	};

	AVIJS.Stream.prototype.addRGBAFrame = function(imgData) {
		var frame = new Uint8Array(imgData.length);
		for (var i=0; i < frame.length; i += 4) {
			frame[i] = imgData[i + 2];
			frame[i + 1] = imgData[i + 1];
			frame[i + 2] = imgData[i];
		}
		this.frames.push(frame);
	};

	AVIJS.Stream.prototype.getHeaderLength = function() {
		return 12 /* strl */ + 8 /* strh */ + 56 /* struct */ + 8 /* strf */ + 40 /* struct */ + 8 /* indx */ + 24 /* struct */ + this.frames.length * 4 * 2;
	};

	AVIJS.Stream.prototype.getDataLength = function() {
		var len = 0;
		for (var i=0; i < this.frames.length; ++i) {
			len += 8 + this.frames[i].length + (this.frames[i].length % 2 == 0 ? 0 : 1); // Pad if chunk not in word boundary
		}
		return len;
	};

	AVIJS.Stream.prototype.writeHeaderBuffer = function(buf, idx, dataOffset) {
		writeString(buf, 0, 'LIST');
		writeInt(buf, 4, 148 + this.frames.length * 4 * 2);
		writeString(buf, 8, 'strl');
		writeString(buf, 12, 'strh');
		writeInt(buf, 16, 56);
		writeString(buf, 20, 'vids'); // fourCC
		writeString(buf, 24, 'DIB '); // Uncompressed
		writeInt(buf, 28, 0); // Flags
		writeShort(buf, 32, 1); // Priority
		writeShort(buf, 34, 0); // Language
		writeInt(buf, 36, 0); // Initial frames
		writeInt(buf, 40, 1); // Scale
		writeInt(buf, 44, this.fps); // Rate
		writeInt(buf, 48, 0); // Startdelay
		writeInt(buf, 52, this.frames.length); // Length
		writeInt(buf, 56, this.width * this.height * 3); // suggested buffer size
		writeInt(buf, 60, -1); // quality
		writeInt(buf, 64, 0); // sampleSize
		writeShort(buf, 68, 0); // Rect left
		writeShort(buf, 70, 0); // Rect top
		writeShort(buf, 72, this.width); // Rect width
		writeShort(buf, 74, this.height); // Rect height

		writeString(buf, 76, 'strf');
		writeInt(buf, 80, 40);
		writeInt(buf, 84, 40); // struct size
		writeInt(buf, 88, this.width); // width
		writeInt(buf, 92, -this.height); // height
		writeShort(buf, 96, 1); // planes
		writeShort(buf, 98, 32); // bits per pixel
		writeInt(buf, 100, 0); // compression
		writeInt(buf, 104, 0); // image size
		writeInt(buf, 108, 0); // x pixels per meter
		writeInt(buf, 112, 0); // y pixels per meter
		writeInt(buf, 116, 0); // colortable used
		writeInt(buf, 120, 0); // colortable important

		writeString(buf, 124, 'indx');
		writeInt(buf, 128, 24 + this.frames.length * 4 * 2); // size
		writeShort(buf, 132, 2); // LongsPerEntry
		writeBytes(buf, 134, [0, 0x01]); // indexSubType + indexType
		writeInt(buf, 136, this.frames.length); // numIndexEntries
		writeString(buf, 140, (idx < 10 ? '0' + idx : idx) + 'db'); // chunkID
		writeLong(buf, 144, dataOffset); // data offset
		writeInt(buf, 152, 0); // reserved

		var offset = 0;
		for (var i=0; i < this.frames.length; ++i) { // index entries
			writeInt(buf, 156 + i * 8, offset); // offset
			writeInt(buf, 160 + i * 8, this.frames[i].length + 8); // size
			offset += this.frames[i].length + 8;
		}

		return 156 + this.frames.length * 4 * 2;
	};

	AVIJS.Stream.prototype.writeDataBuffer = function(buf, idx) {
		var len = 0;
		for (var i=0; i < this.frames.length; ++i) {
			writeString(buf, len, (idx < 10 ? '0' + idx : idx) + 'db');
			writeInt(buf, len + 4, this.frames[i].length);
			writeBytes(buf, len + 8, this.frames[i]);
			len += this.frames[i].length + 8;
		}
		return len;
	};

	var scope = new Function('return this')();

	if (typeof WorkerLocation !== 'undefined' && scope.location instanceof WorkerLocation) {
		var avi = new AVIJS();

		scope.onmessage = function(evt) {
			switch (evt.data.action) {
				case 'settings':
					avi.settings = evt.data.data;
					break;
				case 'stream':
					avi.streams.push(new AVIJS.Stream(evt.data.fps, evt.data.width, evt.data.height));
					break;
				case 'frameRGBA':
					avi.streams[evt.data.stream].addRGBAFrame(evt.data.frame.data);
					break;
				case 'buffer':
					scope.postMessage(avi.getBuffer());
					break;
			}
		};
	} else {
		scope['AVIJS'] = AVIJS;
	}
})();<|endoftext|>


<commit_before>function sendMessage(message) {
  console.log(message);
}

function makeRating(obj) {
  let rating = 0;

  const get = () => rating;
  const set = (stars) => rating = stars;

  return {
    get,
    set
  };
}

function makeFeedback() {
  const feedback = [];

  const get = () => feedback;
  const add = (message) => feedback.push(message);

  return {
    get,
    add
  };
}

// Implementations

function makeFeedbackMessage() {
  var feedback = makeFeedback();

  function share(message) {
    feedback.add(message);
  }

  function send() {
    sendMessage(feedback.get());
  }

  return {
    share,
    send
  };
}

function makeRatingMessage() {
  var ratings = makeRating();

  function rate(stars) {
    ratings.set(stars);
  }

  function send() {
    sendMessage(ratings.get());
  }

  return {
    rate,
    send
  };
}
<commit_msg>refactor: interface segregation example code<commit_after>// "interfaces"
function postMessage(message) {
  console.log(message);
}

function makeRating() {
  let stars = 0;

  const get = () => stars;
  const set = (numberOfStars) => stars = numberOfStars;

  return {
    get,
    set
  };
}

function makeFeedback() {
  const messages = [];

  const get = () => messages;
  const add = (message) => messages.push(message);

  return {
    get,
    add
  };
}

// "clients"

function messageForFeedback() {
  var feedback = makeFeedback();

  const share = (message) => feedback.add(message);

  return {
    share,
    get: feedback.get
  };
}

function messageForRating() {
  var ratings = makeRating();

  const rate = (stars) => ratings.set(stars);
  const send = () => postMessage(ratings.get());

  return {
    rate,
    send
  };
}

// usage
const feedback = messageForFeedback();
feedback.share('Good job!');
const results = feedback.get();

const ratings = messageForRating();
ratings.rate(5);
ratings.send();
<|endoftext|>


<commit_before>/*
Copyright (c) 2016 Red Hat, Inc.

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 React, { Component } from 'react'
import ReactDOM from 'react-dom'
import hljs from 'highlight.js'

export default class Doc extends Component {
  render () {
    return

  }
  componentDidMount () {
    const html = this.props.concept.html
    const element = ReactDOM.findDOMNode(this)
    $(element).html(html)
    $('pre.highlightjs', element).each((index, value) => hljs.highlightBlock(value))
  }
}
<commit_msg>Don't return value from function called by "each"<commit_after>/*
Copyright (c) 2016 Red Hat, Inc.

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 React, { Component } from 'react'
import ReactDOM from 'react-dom'
import hljs from 'highlight.js'

export default class Doc extends Component {
  render () {
    return

  }
  componentDidMount () {
    const html = this.props.concept.html
    const element = ReactDOM.findDOMNode(this)
    $(element).html(html)
    $('pre.highlightjs', element).each((index, value) => {
      hljs.highlightBlock(value)
    })
  }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import './App.css';
import $ from 'jquery';
import InputCustom from './components/InputCustom';
import ButtonCustom from './components/ButtonCustom';
import AddressInfo from './components/AddressInfo';
import Error from './components/Error';

class App extends Component {
  constructor() {
    super();
    this.state = {
      cep: '',
      endereco:[],
      location:[],
      lat:[],
      lng:[],
      showingMap: false,
      showingError: false
    };
    this.enviaForm = this.enviaForm.bind(this);
    this.callback = this.callback.bind(this);
    this.closeMap = this.closeMap.bind(this);

  }

  handleChange(inputName,event){
    let handlingInput = {};
    handlingInput[inputName] = event.target.value;
    this.setState(handlingInput);
  }

  enviaForm(event) {
    event.preventDefault();
    $.getJSON({
      url: 'https://viacep.com.br/ws/' + this.state.cep + '/json/?callback=callback ',
      dataType:'jsonp',
      data: JSON.stringify({
        cep:this.state.cep,
        logradouro:this.state.logradouro,
        bairro: this.state.bairro,
        localidade:this.state.localidade,
        uf: this.state.uf
      }),

      success: function(data){
        this.callback(data);
      }.bind(this),
      error:(response) =>{
        if(response.status !== 200) {
          this.setState({showingError: true});

        }
      }
    });
  }

  callback(result){

    $.ajax({
      url: 'https://maps.googleapis.com/maps/api/geocode/json?address='+result.logradouro+'-'+result.bairro+'-'+result.localidade,
      success: function(data){
        this.setState({
          endereco: result,
          lat: data.results[0].geometry.location.lat,
          lng: data.results[0].geometry.location.lng,
          showingMap:true,
          showingError: false

        });
      }.bind(this),
      error:(error)=> {
        if(error.status !== 200) {
          this.setState({showingError: true});

        }

      }
    });
  }

  closeMap() {
    this.setState({
      showingMap: false,
      showingError: false

    });
  }

  cleanup() {
    this.setState({cep: ''});

  }

  render() {

    return (

Consulta de endereço

Consultar

              <form className="form-inline" onSubmit={this.enviaForm}>
                <InputCustom label="CEP"
                             id="cep"
                             type="text"
                             name="cep"
                             placeholder="00000-000"
                             value={this.state.cep}
                             required
                             onChange={this.handleChange.bind(this,'cep')}
                />
                <ButtonCustom value="Buscar"></ButtonCustom>
              </form>

            {
              this.state.showingError && <Error/>
            }

            {
              this.state.showingMap &&
                <AddressInfo endereco={this.state.endereco}
                             lat={this.state.lat}
                             lng={this.state.lng}
                             handleClose={() => { this.closeMap(); this.cleanup()} }

              />
            }

    );
  }

}
export default App;
<commit_msg>remove whitespaces<commit_after>import React, { Component } from 'react';
import './App.css';
import $ from 'jquery';
import InputCustom from './components/InputCustom';
import ButtonCustom from './components/ButtonCustom';
import AddressInfo from './components/AddressInfo';
import Error from './components/Error';

class App extends Component {
  constructor() {
    super();
    this.state = {
      cep: '',
      endereco:[],
      location:[],
      lat:[],
      lng:[],
      showingMap: false,
      showingError: false
    };
    this.enviaForm = this.enviaForm.bind(this);
    this.callback = this.callback.bind(this);
    this.closeMap = this.closeMap.bind(this);

  }

  handleChange(inputName,event){
    let handlingInput = {};
    handlingInput[inputName] = event.target.value;
    this.setState(handlingInput);
  }

  enviaForm(event) {
    event.preventDefault();
    $.getJSON({
      url: 'https://viacep.com.br/ws/' + this.state.cep + '/json/?callback=callback ',
      dataType:'jsonp',
      data: JSON.stringify({
        cep:this.state.cep,
        logradouro:this.state.logradouro,
        bairro: this.state.bairro,
        localidade:this.state.localidade,
        uf: this.state.uf
      }),

      success: function(data){
        this.callback(data);
      }.bind(this),
      error:(response) =>{
        if(response.status !== 200) {
          this.setState({showingError: true});

        }
      }
    });
  }

  callback(result){

    $.ajax({
      url: 'https://maps.googleapis.com/maps/api/geocode/json?address='+result.logradouro+'-'+result.bairro+'-'+result.localidade,
      success: function(data){
        this.setState({
          endereco: result,
          lat: data.results[0].geometry.location.lat,
          lng: data.results[0].geometry.location.lng,
          showingMap:true,
          showingError: false

        });
      }.bind(this),
      error:(error)=> {
        if(error.status !== 200) {
          this.setState({showingError: true});

        }

      }
    });
  }

  closeMap() {
    this.setState({
      showingMap: false,
      showingError: false

    });
  }

  cleanup() {
    this.setState({cep: ''});

  }

  render() {

    return (

Consulta de endereço

Consultar

              <form className="form-inline" onSubmit={this.enviaForm}>
                <InputCustom label="CEP"
                             id="cep"
                             type="text"
                             name="cep"
                             placeholder="00000-000"
                             value={this.state.cep}
                             required
                             onChange={this.handleChange.bind(this,'cep')}
                />
                <ButtonCustom value="Buscar"></ButtonCustom>
              </form>

            {
              this.state.showingError && <Error/>
            }

            {
              this.state.showingMap &&
                <AddressInfo endereco={this.state.endereco}
                             lat={this.state.lat}
                             lng={this.state.lng}
                             handleClose={() => { this.closeMap(); this.cleanup()} }

              />
            }

    );
  }

}
export default App;
<|endoftext|>


<commit_before><commit_msg>Remove app props we never see provided<commit_after><|endoftext|>


<commit_before>'use strict'

/**
 * Dependencies
 * @ignore
 */
const crypto = require('crypto')
const base64url = require('base64url')
const { JWA } = require('@trust/jwa')

/**
 * Module Dependencies
 * @ignore
 */
const { DataError } = require('./errors')

/**
 * JWK
 * @ignore
 */
class JWK {

  /**
   * constructor
   *
   * @class JWK
   *
   * @description
   * JSON Web Key ([IETF RFC7517](https://tools.ietf.org/html/rfc7517))
   *
   * @param  {Object} data
   * @param  {Object} [options={}] - Additional JWK metadata.
   */
  constructor (data, options = {}) {
    if (!data) {
      throw new DataError('Invalid JWK')
    }

    // Handle string input
    if (typeof data === 'string') {
      try {
        data = JSON.parse(data)
      } catch (error) {
        throw new DataError('Invalid JWK JSON String')
      }
    }

    // Handle options input
    let metadata = Object.keys(options)
      .filter(key => {
        let dataValue = data[key]
        let optionsValue = options[key]

        if (dataValue && optionsValue && dataValue !== optionsValue) {
          throw new DataError(`Conflicting '${key}' option`)
        }

        return !dataValue && optionsValue
      })
      .reduce((state, key) => {
        state[key] = options[key]
        return state
      }, {})

    // Assign input
    Object.assign(this, data, metadata)

    // Enforce required properties
    if (!this.alg) {
      throw new DataError('Valid \'alg\' required for JWK')
    }

    if (!this.kid) {
      this.kid = this.thumbprint()
    }
  }

  /**
   * importKey
   *
   * @description
   * Import a JWK from JSON String or a JS Object.
   *
   * @param  {(String|Object)} data
   * @param  {Object} [options] - Additional JWK metadata.
   * @return {Promise.<JWK>} A promise that resolves the JWK instance.
   */
  static importKey (data, options) {
    return Promise.resolve()
      // Create instance
      .then(() => new JWK(data, options))

      // Import CryptoKey and assign to JWK
      .then(jwk => JWA.importKey(jwk).then(({ cryptoKey }) => {
        Object.defineProperty(jwk, 'cryptoKey', {
          value: cryptoKey,
          enumerable: false,
          configurable: false
        })

        return jwk
      }))
  }

  /**
   * fromCryptoKey
   *
   * @description
   * Import a JWK from a [WebCrypto CryptoKey](https://github.com/anvilresearch/webcrypto).
   *
   * @param  {CryptoKey} key - [WebCrypto CryptoKey]{@link https://github.com/anvilresearch/webcrypto}.
   * @param  {Object} [options] - Additional JWK metadata.
   * @return {Promise.<JWK>} A promise that resolves the JWK instance.
   */
  static fromCryptoKey (key, options) {
    // Export JWK
    return JWA.exportKey('jwk', key)

      // Create JWK instance and assign CryptoKey
      .then(data => {
        let jwk = new JWK(data, options)

        Object.defineProperty(jwk, 'cryptoKey', {
          value: key,
          enumerable: false,
          configurable: false
        })

        return jwk
      })
  }

  /**
   * sign
   *
   * @description
   * Sign arbitrary data using the JWK.
   *
   * @example
Signing the string "test"

   * privateJwk.sign('test')
   *   .then(console.log)
   * //
   * // (line breaks for display only)
   * //
   * // => "MEUCIQCHwnGM8IsOJgfQsoPgs3hMd8
   * //     ahfWHM9ZNvj1K6i2yhKQIgWGOuXX43
   * //     lSTo-U8Pa8sURR53lv6Osjw-dtoLse
   * //     lftqQ"
   *
   * @param  {(String|Buffer)} data - The data to sign.
   * @return {Promise.<String>} A promise that resolves the base64url encoded signature string.
   */
  sign (data) {
    let { alg, cryptoKey } = this
    return JWA.sign(alg, cryptoKey, data)
  }

  /**
   * verify
   *
   * @description
   * Verify a signature using the JWK.
   *
   * @example
Verify a signature of the string "test"

   * // base64url encoded signature string
   * let signature = `MEUCIQCHwnGM8IsOJgfQsoPgs3hMd8ahfWHM9ZN
   * vj1K6i2yhKQIgWGOuXX43lSTo-U8Pa8sURR53lv6Osjw-dtoLselftqQ`
   *
   * publicJwk.verify('test', signature)
   *   .then(console.log)
   * // => true
   *
   * @param  {(String|Buffer)} data - The data to verify.
   * @param  {String} signature - A base64url signature string.
   * @return {Promise.<Boolean>} A promise that resolves the boolean result of the signature verification.
   */
  verify (data, signature) {
    let { alg, cryptoKey } = this
    return JWA.verify(alg, cryptoKey, signature, data)
  }

  /**
   * encrypt
   *
   * @description
   * Encrypt arbitrary data using the JWK.
   *
   * @example
Encrypt the string "data"

   * secretJwk.encrypt('data')
   *   .then(console.log)
   * // => { iv: 'u0l3ttqUFDQ8mcRboHv5Vw',
   * //      ciphertext: 'yq3K4w',
   * //      tag: 'fHlZ__uuUnHn0ac-Lnrr-A' }
   *
   * @param  {(String|Object)} data - The data to encrypt.
   * @param  {(String|Buffer)} [aad] - Additional non-encrypted integrity protected data (AES-GCM).
   * @return {Promise.<Object>} A promise that resolves an object containing the base64url encoded `iv`, `ciphertext` and `tag` (AES-GCM).
   */
  encrypt (data, aad) {
    let { alg, cryptoKey } = this
    return JWA.encrypt(alg, cryptoKey, data, aad)
  }

  /**
   * decrypt
   *
   * @description
   * Decrypt data using the JWK.
   *
   * @example
Decrypt encrypted string "test"

   * // base64url encoded data
   * let ciphertext = 'yq3K4w'
   * let iv = 'u0l3ttqUFDQ8mcRboHv5Vw'
   * let tag = 'fHlZ__uuUnHn0ac-Lnrr-A'
   *
   * secretJwk.decrypt(ciphertext, iv, tag)
   *   .then(console.log)
   * // => "data"
   *
   * @param  {(String|Buffer)} ciphertext - The encrypted data to decrypt.
   * @param  {(String|Buffer)} iv - The initialization vector.
   * @param  {(String|Buffer)} [tag] - The authorization tag (AES-GCM).
   * @param  {(String|Buffer)} [aad] - Additional non-encrypted integrity protected data (AES-GCM).
   * @return {Promise.<String>} A promise that resolves the plaintext data.
   */
  decrypt (ciphertext, iv, tag, aad) {
    let { alg, cryptoKey } = this
    return JWA.decrypt(alg, cryptoKey, ciphertext, iv, tag, aad)
  }

  /**
   * thumbprint
   *
   * @description
   * Calculate the SHA-256 JWK Thumbprint according to [RFC7638]{@link https://tools.ietf.org/html/rfc7638}.
   * This method is used to create a unique `kid` if none is specified.
   *
   * @example
SHA-256 Thumbprint

   * jwk.thumbprint()
   * //
   * // (line breaks for display only)
   * //
   * // => "45BLsBiWcghaEf_NF70Gf5oQcYLHaA
   * //     tks0C48tT5SJ4"
   *
   * @return {String} JWK Thumbprint String
   */
  thumbprint () {
    let { kty } = this
    let data

    // RSA JWK Thumbprint Fields
    if (kty === 'RSA') {
      let { e, n } = this
      data = { e, kty, n }

    // ECDSA JWK Thumbprint Fields
    } else if (kty === 'EC') {
      let { crv, x, y } = this
      data = { crv, kty, x, y }

    // Symmetric JWK Thumbprint Fields
    } else if (kty === 'oct') {
      let { k } = this
      data = { k, kty }

    // Invalid kty
    } else {
      throw new DataError('Invalid \'kty\'')
    }

    let hash = crypto.createHash('sha256')
    let json = JSON.stringify(data)

    hash.update(json)
    return base64url(hash.digest())
  }
}

/**
 * Exports
 * @ignore
 */
module.exports = JWK
<commit_msg>feat(JWK): generate JWS protected headers from JWK. Closes #4<commit_after>'use strict'

/**
 * Dependencies
 * @ignore
 */
const crypto = require('crypto')
const base64url = require('base64url')
const { JWA } = require('@trust/jwa')

/**
 * Module Dependencies
 * @ignore
 */
const { DataError } = require('./errors')

/**
 * JWK
 * @ignore
 */
class JWK {

  /**
   * constructor
   *
   * @class JWK
   *
   * @description
   * JSON Web Key ([IETF RFC7517](https://tools.ietf.org/html/rfc7517))
   *
   * @param  {Object} data
   * @param  {Object} [options={}] - Additional JWK metadata.
   */
  constructor (data, options = {}) {
    if (!data) {
      throw new DataError('Invalid JWK')
    }

    // Handle string input
    if (typeof data === 'string') {
      try {
        data = JSON.parse(data)
      } catch (error) {
        throw new DataError('Invalid JWK JSON String')
      }
    }

    // Handle options input
    let metadata = Object.keys(options)
      .filter(key => {
        let dataValue = data[key]
        let optionsValue = options[key]

        if (dataValue && optionsValue && dataValue !== optionsValue) {
          throw new DataError(`Conflicting '${key}' option`)
        }

        return !dataValue && optionsValue
      })
      .reduce((state, key) => {
        state[key] = options[key]
        return state
      }, {})

    // Assign input
    Object.assign(this, data, metadata)

    // Enforce required properties
    if (!this.alg) {
      throw new DataError('Valid \'alg\' required for JWK')
    }

    if (!this.kid) {
      this.kid = this.thumbprint()
    }
  }

  /**
   * importKey
   *
   * @description
   * Import a JWK from JSON String or a JS Object.
   *
   * @param  {(String|Object)} data
   * @param  {Object} [options] - Additional JWK metadata.
   * @return {Promise.<JWK>} A promise that resolves the JWK instance.
   */
  static importKey (data, options) {
    return Promise.resolve()
      // Create instance
      .then(() => new JWK(data, options))

      // Import CryptoKey and assign to JWK
      .then(jwk => JWA.importKey(jwk).then(({ cryptoKey }) => {
        Object.defineProperty(jwk, 'cryptoKey', {
          value: cryptoKey,
          enumerable: false,
          configurable: false
        })

        return jwk
      }))
  }

  /**
   * fromCryptoKey
   *
   * @description
   * Import a JWK from a [WebCrypto CryptoKey](https://github.com/anvilresearch/webcrypto).
   *
   * @param  {CryptoKey} key - [WebCrypto CryptoKey]{@link https://github.com/anvilresearch/webcrypto}.
   * @param  {Object} [options] - Additional JWK metadata.
   * @return {Promise.<JWK>} A promise that resolves the JWK instance.
   */
  static fromCryptoKey (key, options) {
    // Export JWK
    return JWA.exportKey('jwk', key)

      // Create JWK instance and assign CryptoKey
      .then(data => {
        let jwk = new JWK(data, options)

        Object.defineProperty(jwk, 'cryptoKey', {
          value: key,
          enumerable: false,
          configurable: false
        })

        return jwk
      })
  }

  /**
   * sign
   *
   * @description
   * Sign arbitrary data using the JWK.
   *
   * @example
Signing the string "test"

   * privateJwk.sign('test')
   *   .then(console.log)
   * //
   * // (line breaks for display only)
   * //
   * // => "MEUCIQCHwnGM8IsOJgfQsoPgs3hMd8
   * //     ahfWHM9ZNvj1K6i2yhKQIgWGOuXX43
   * //     lSTo-U8Pa8sURR53lv6Osjw-dtoLse
   * //     lftqQ"
   *
   * @param  {(String|Buffer)} data - The data to sign.
   * @return {Promise.<String>} A promise that resolves the base64url encoded signature string.
   */
  sign (data) {
    let { alg, cryptoKey } = this
    return JWA.sign(alg, cryptoKey, data)
  }

  /**
   * verify
   *
   * @description
   * Verify a signature using the JWK.
   *
   * @example
Verify a signature of the string "test"

   * // base64url encoded signature string
   * let signature = `MEUCIQCHwnGM8IsOJgfQsoPgs3hMd8ahfWHM9ZN
   * vj1K6i2yhKQIgWGOuXX43lSTo-U8Pa8sURR53lv6Osjw-dtoLselftqQ`
   *
   * publicJwk.verify('test', signature)
   *   .then(console.log)
   * // => true
   *
   * @param  {(String|Buffer)} data - The data to verify.
   * @param  {String} signature - A base64url signature string.
   * @return {Promise.<Boolean>} A promise that resolves the boolean result of the signature verification.
   */
  verify (data, signature) {
    let { alg, cryptoKey } = this
    return JWA.verify(alg, cryptoKey, signature, data)
  }

  /**
   * encrypt
   *
   * @description
   * Encrypt arbitrary data using the JWK.
   *
   * @example
Encrypt the string "data"

   * secretJwk.encrypt('data')
   *   .then(console.log)
   * // => { iv: 'u0l3ttqUFDQ8mcRboHv5Vw',
   * //      ciphertext: 'yq3K4w',
   * //      tag: 'fHlZ__uuUnHn0ac-Lnrr-A' }
   *
   * @param  {(String|Object)} data - The data to encrypt.
   * @param  {(String|Buffer)} [aad] - Additional non-encrypted integrity protected data (AES-GCM).
   * @return {Promise.<Object>} A promise that resolves an object containing the base64url encoded `iv`, `ciphertext` and `tag` (AES-GCM).
   */
  encrypt (data, aad) {
    let { alg, cryptoKey } = this
    return JWA.encrypt(alg, cryptoKey, data, aad)
  }

  /**
   * decrypt
   *
   * @description
   * Decrypt data using the JWK.
   *
   * @example
Decrypt encrypted string "test"

   * // base64url encoded data
   * let ciphertext = 'yq3K4w'
   * let iv = 'u0l3ttqUFDQ8mcRboHv5Vw'
   * let tag = 'fHlZ__uuUnHn0ac-Lnrr-A'
   *
   * secretJwk.decrypt(ciphertext, iv, tag)
   *   .then(console.log)
   * // => "data"
   *
   * @param  {(String|Buffer)} ciphertext - The encrypted data to decrypt.
   * @param  {(String|Buffer)} iv - The initialization vector.
   * @param  {(String|Buffer)} [tag] - The authorization tag (AES-GCM).
   * @param  {(String|Buffer)} [aad] - Additional non-encrypted integrity protected data (AES-GCM).
   * @return {Promise.<String>} A promise that resolves the plaintext data.
   */
  decrypt (ciphertext, iv, tag, aad) {
    let { alg, cryptoKey } = this
    return JWA.decrypt(alg, cryptoKey, ciphertext, iv, tag, aad)
  }

  /**
   * thumbprint
   *
   * @description
   * Calculate the SHA-256 JWK Thumbprint according to [RFC7638]{@link https://tools.ietf.org/html/rfc7638}.
   * This method is used to create a unique `kid` if none is specified.
   *
   * @example
SHA-256 Thumbprint

   * jwk.thumbprint()
   * //
   * // (line breaks for display only)
   * //
   * // => "45BLsBiWcghaEf_NF70Gf5oQcYLHaA
   * //     tks0C48tT5SJ4"
   *
   * @return {String} JWK Thumbprint String
   */
  thumbprint () {
    let { kty } = this
    let data

    // RSA JWK Thumbprint Fields
    if (kty === 'RSA') {
      let { e, n } = this
      data = { e, kty, n }

    // ECDSA JWK Thumbprint Fields
    } else if (kty === 'EC') {
      let { crv, x, y } = this
      data = { crv, kty, x, y }

    // Symmetric JWK Thumbprint Fields
    } else if (kty === 'oct') {
      let { k } = this
      data = { k, kty }

    // Invalid kty
    } else {
      throw new DataError('Invalid \'kty\'')
    }

    let hash = crypto.createHash('sha256')
    let json = JSON.stringify(data)

    hash.update(json)
    return base64url(hash.digest())
  }

  /**
   * generateProtected
   *
   * @description
   * Use key metadata to generate a JWS protected header object.
   *
   * @example
Basic JWS Header with JWC

   * jwk.generateProtected({ jwc: 'base64url encoded compact jwc' })
   * // => { alg: 'RS256',
   * //      kid: 'abcd123$',
   * //      jwc: 'base64url encoded compact jwc' }
   *
   * @example
Basic JWS Header with JKU

   * jwk.generateProtected({ jku: 'https://example.com/jwks' })
   * // => { alg: 'RS256',
   * //      kid: 'abcd123$',
   * //      jku: 'https://example.com/jwks' }
   *
   * @param  {Object} props - Additional properties to include in header.
   * @return {Object} JWS Header
   */
  generateProtected (props) {
    let { alg, kid, key_ops, use } = this
    let header = Object.assign({}, { alg, kid }, props)

    // Check key_ops or use
    if (!(Array.isArray(key_ops) && key_ops.includes('sign')) && !(use && use === 'sig')) {
      throw new DataError('Invalid key usage option')
    }

    // Check for mandatory properties
    if (!header.alg) {
      throw new DataError('\'alg\' is required')
    }

    if (!header.kid) {
      throw new DataError('\'kid\' is required')
    }

    if (!header.jku && !header.jwc) {
      throw new DataError('Either \'jku\' or \'jwc\' is required')
    }

    return header
  }
}

/**
 * Exports
 * @ignore
 */
module.exports = JWK
<|endoftext|>


<commit_before>/**
 Methods used for scraping encyclopedia data
 */

/**
 Gets an object list of all entries for a category
 @param username {string} The username to query
 @param category {CATEGORY_TYPE} The category to query
 @param callback Called when finished with first param entries {array}

    ENTRY_MODEL
    {
        'title':            string
        'url':              string
        'rating':           string
        'comment':          string
        'category':         CATEGORY_TYPE

        REQ. ADDTL PARSING:
        'userRatings':      ???
        'genres':           array [string]
        'op':               string
        'ed':               string
        'vintage':          string
        'epLength':         int
        'thumbnail':        Base64 image

        USER ADDED:
        'dateStarted':      date
        'dateFinished':     date
        'currentEp':        length

    }
 */
function getEntriesForCategory(username, category, callback)
{
    var retrievedEntries = [];

    username = encodeURIComponent(username);

    crossSiteGet('http://www.animenewsnetwork.com/MyAnime/?user=' + username + '&categ=' + category, 'html', function (data)
    {
        valueByKey(data, 'table', function (tableElement)
        {
            valueByKey(tableElement, 'tr', function (dataEntries)
            {
                for (var i = 0; i < dataEntries.length; i++)
                {
                    var category = 0;
                    var dataId = dataEntries[i].id;
                    if (dataId)
                    {
                        var splitId = dataId.split('-')[0];
                        category = splitId.match(/\d+$/)[0];
                    }
                    else
                    {
                        continue;
                    }

                    var currentEntry = dataEntries[i].td;
                    var entryContainer = currentEntry[0] ? currentEntry[0].strong : currentEntry.strong;
                    if (!entryContainer || entryContainer.length == 0)
                    {
                        continue;
                    }

                    var title = entryContainer && entryContainer.a ?
                                entryContainer.a.font.content : '';
                    var url = entryContainer && entryContainer.a ?
                              entryContainer.a.href : '';
                    var rating = currentEntry[1] && currentEntry[1].p ?
                                 currentEntry[1].p : '--';
                    var comment = currentEntry[2] ?
                                  currentEntry[2].small : '--';

                    // Convert rating to a number so we can do calculations and stuff
                    rating = RATINGS_TYPE[rating];

                    // Get other id
                    var annId = url.match(/id=(\d+)/)[1];

                    // Format data
                    var newEntry =
                    {
                        'id':           i,
                        'annId':        annId,
                        'title':        title.trim(),
                        'url':          url,
                        'rating':       rating,
                        'comment':      comment,
                        'category':     category
                    };

                    if (newEntry.title.length > 0 && newEntry.url.length > 0)
                    {
                        retrievedEntries.push(newEntry);
                    }
                }
            });
        });

        callback(retrievedEntries);
    });
}

/**
 */
function getAdditionalData(entry)
{
    var entryId = entry.annId;
    crossSiteGet('http://cdn.animenewsnetwork.com/encyclopedia/api.xml?title=' + entryId, 'xml', function (data)
    {
        var infoData = data.query.results.ann.anime.info;

        var info = {};
        for (var i = 0; i < infoData.length; i++)
        {
            if (infoData[i].type && infoData[i].type.length > 0)
            {
                var type = infoData[i].type;

                // Initialize array if not defined
                if (!info[type])
                {
                    info[type] = [];
                }

                var contentData;

                if (infoData[i].content)
                {
                    contentData = infoData[i].content;
                }
                else if (infoData[i].img)
                {
                    var imageData = infoData[i]['img'];
                    if (typeof imageData == 'array')
                    {
                        contentData = imageData[0];
                    }
                    else
                    {
                        contentData = imageData;
                    }
                }

                info[type].push(contentData);
            }
        }

        entry['titleData'] = info;

        entry['eps'] = (info['Number of episodes']) ? info['Number of episodes'][0] : 1;

        if (info['Picture'])
        {
            if (info['Picture'][0].length > 1)
            {
                entry['thumbnail'] = info['Picture'][0][0]['src'];
            }
            else
            {
                entry['thumbnail'] = info['Picture'][0]['src'];
            }
        }

        $('#tableContainer').jtable('reload', function ()
        {
            applyLazyload();
        });
    });
}<commit_msg>Save after getting data<commit_after>/**
 Methods used for scraping encyclopedia data
 */

/**
 Gets an object list of all entries for a category
 @param username {string} The username to query
 @param category {CATEGORY_TYPE} The category to query
 @param callback Called when finished with first param entries {array}

    ENTRY_MODEL
    {
        'title':            string
        'url':              string
        'rating':           string
        'comment':          string
        'category':         CATEGORY_TYPE

        REQ. ADDTL PARSING:
        'userRatings':      ???
        'genres':           array [string]
        'op':               string
        'ed':               string
        'vintage':          string
        'epLength':         int
        'thumbnail':        Base64 image

        USER ADDED:
        'dateStarted':      date
        'dateFinished':     date
        'currentEp':        length

    }
 */
function getEntriesForCategory(username, category, callback)
{
    var retrievedEntries = [];

    username = encodeURIComponent(username);

    crossSiteGet('http://www.animenewsnetwork.com/MyAnime/?user=' + username + '&categ=' + category, 'html', function (data)
    {
        valueByKey(data, 'table', function (tableElement)
        {
            valueByKey(tableElement, 'tr', function (dataEntries)
            {
                for (var i = 0; i < dataEntries.length; i++)
                {
                    var category = 0;
                    var dataId = dataEntries[i].id;
                    if (dataId)
                    {
                        var splitId = dataId.split('-')[0];
                        category = splitId.match(/\d+$/)[0];
                    }
                    else
                    {
                        continue;
                    }

                    var currentEntry = dataEntries[i].td;
                    var entryContainer = currentEntry[0] ? currentEntry[0].strong : currentEntry.strong;
                    if (!entryContainer || entryContainer.length == 0)
                    {
                        continue;
                    }

                    var title = entryContainer && entryContainer.a ?
                                entryContainer.a.font.content : '';
                    var url = entryContainer && entryContainer.a ?
                              entryContainer.a.href : '';
                    var rating = currentEntry[1] && currentEntry[1].p ?
                                 currentEntry[1].p : '--';
                    var comment = currentEntry[2] ?
                                  currentEntry[2].small : '--';

                    // Convert rating to a number so we can do calculations and stuff
                    rating = RATINGS_TYPE[rating];

                    // Get other id
                    var annId = url.match(/id=(\d+)/)[1];

                    // Format data
                    var newEntry =
                    {
                        'id':           i,
                        'annId':        annId,
                        'title':        title.trim(),
                        'url':          url,
                        'rating':       rating,
                        'comment':      comment,
                        'category':     category
                    };

                    if (newEntry.title.length > 0 && newEntry.url.length > 0)
                    {
                        retrievedEntries.push(newEntry);
                    }
                }
            });
        });

        callback(retrievedEntries);
    });
}

/**
 */
function getAdditionalData(entry)
{
    var entryId = entry.annId;
    crossSiteGet('http://cdn.animenewsnetwork.com/encyclopedia/api.xml?title=' + entryId, 'xml', function (data)
    {
        var infoData = data.query.results.ann.anime.info;

        var info = {};
        for (var i = 0; i < infoData.length; i++)
        {
            if (infoData[i].type && infoData[i].type.length > 0)
            {
                var type = infoData[i].type;

                // Initialize array if not defined
                if (!info[type])
                {
                    info[type] = [];
                }

                var contentData;

                if (infoData[i].content)
                {
                    contentData = infoData[i].content;
                }
                else if (infoData[i].img)
                {
                    var imageData = infoData[i]['img'];
                    if (typeof imageData == 'array')
                    {
                        contentData = imageData[0];
                    }
                    else
                    {
                        contentData = imageData;
                    }
                }

                info[type].push(contentData);
            }
        }

        entry['titleData'] = info;

        entry['eps'] = (info['Number of episodes']) ? info['Number of episodes'][0] : 1;

        if (info['Picture'])
        {
            if (info['Picture'][0].length > 1)
            {
                entry['thumbnail'] = info['Picture'][0][0]['src'];
            }
            else
            {
                entry['thumbnail'] = info['Picture'][0]['src'];
            }
        }

        saveData();

        $('#tableContainer').jtable('reload', function ()
        {
            applyLazyload();
        });
    });
}<|endoftext|>


<commit_before>import React from 'react'
import {Link} from 'react-router'

// 引入Antd的导航组件
import {Menu, Icon} from 'antd'
const SubMenu = Menu.SubMenu

import './App.less'

/*import './App.css'*/

export default React.createClass({
    render() {
        return (

                <Menu theme="dark"
                      style={{width: 185}}
                      defaultOpenKeys={['sub1', 'sub2']}
                      mode="inline"
                >
                    <SubMenu key="sub1" title={<Icon type="heart"/>云报销}>
                        <Menu.Item key="1"><Link to="/freebillm">报销单管理</Link></Menu.Item>
                        <Menu.Item key="2"><Link to="/costform">费用支出分析</Link></Menu.Item>
                        <Menu.Item key="3"><Link to="/costpay">费用构成分析</Link></Menu.Item>
                        <Menu.Item key="4"><Link to="/freebillp">报销进度分析</Link></Menu.Item>
                        <Menu.Item key="5"><Link to="/costdefine">费用类型</Link></Menu.Item>
                    </SubMenu>
                    <SubMenu key="sub2" title={<Icon type="appstore"/>测试}>
                        <Menu.Item key="6"><Link to="/about">antd</Link></Menu.Item>
                        <Menu.Item key="7"><Link to="/repos">antd2</Link></Menu.Item>
                        <Menu.Item key="8"><Link to="/chart">chart</Link></Menu.Item>
                        <Menu.Item key="9"><Link to="/testapi">TestApi</Link></Menu.Item>
                    </SubMenu>
                </Menu>

                    {this.props.children}

        )
    }
})

<commit_msg>报销单列表框架已完成33<commit_after>import React from 'react'
import {Link} from 'react-router'

// 引入Antd的导航组件
import {Menu, Icon} from 'antd'
const SubMenu = Menu.SubMenu

import './App.less'

/*import './App.css'*/

export default React.createClass({
    render() {
        return (

                <Menu theme="dark"
                      style={{width: 185}}
                      defaultOpenKeys={['sub1', 'sub2']}
                      mode="inline"
                >
                    <SubMenu key="sub1" title={<Icon type="heart"/>云报销}>
                        <Menu.Item key="1"><Link to="/freebillm">报销单管理</Link></Menu.Item>
                        <Menu.Item key="2"><Link to="/costform">费用支出分析</Link></Menu.Item>
                        <Menu.Item key="3"><Link to="/costpay">费用构成分析</Link></Menu.Item>
                        <Menu.Item key="4"><Link to="/freebillp">报销进度分析</Link></Menu.Item>
                        <Menu.Item key="5"><Link to="/costdefine">费用类型</Link></Menu.Item>
                    </SubMenu>
                    <SubMenu key="sub2" title={<Icon type="appstore"/>测试}>
                        <Menu.Item key="6"><Link to="/about">antd</Link></Menu.Item>
                        <Menu.Item key="7"><Link to="/repos">antd2</Link></Menu.Item>
                        <Menu.Item key="8"><Link to="/chart">chart</Link></Menu.Item>
                        <Menu.Item key="9"><Link to="/testapi">TestApi</Link></Menu.Item>
                    </SubMenu>
                </Menu>

                    {this.props.children}

        )
    }
})

<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var EventEmitter = require('events');
var cluster = require('cluster');

/**
 * Write pid to file description
 * @param  {FileDescriptor} fd
 */
function writePid(fd, callback) {
  var buf = new Buffer(process.pid + '\n');
  fs.write(fd, buf, 0, buf.length, null, function(err){
    if (err) {
      throw err;
    }
    fs.close(fd, callback);
  });
}

/**
 * Check to see if a specific process id is actually running
 * @param    {Number}    pid
 * @return   {Boolean}
 */
function processExists(pid) {
  try {
    return process.kill(pid, 0);
  } catch (err) {
    return err.code === 'EPERM';
  }
}

/**
 * Create Pid
 * @param  {String} path Path to save
 * @param  {Object} options (optional) Settings
 * @example
 * 	var Pid = require('./Pid');
 * 	var pid = new Pid('/var/log/app.pid');
 */
function Pid(filename, options) {
  /**
   * Default options
   * @type {Object}
   */
  this.options = {
    /**
     * File path to pid
     */
    path: path.resolve(filename),
    /**
     * Automatically remove it when the process exists
     * @type {Boolean}
     */
    removeOnExit: true,
    /**
     * Overwrite an existing pid?
     * @type {Boolean}
     */
    overwrite: true
  };
  Object.assign(this.options, options);

  this.id = process.pid;

  // Emitter
  this._events = new EventEmitter();
  this.on = this._events.on.bind(this._events);
  this.once = this._events.once.bind(this._events);
  this.off = this._events.removeListener.bind(this._events);
  this.emit = this._events.emit.bind(this._events);

  // Bindings
  this.create = this.create.bind(this);
  this.remote = this.remove.bind(this);

  // Write pid file
  this.create(function(err){
    if (err) {
      this.emit('error', err);
    } else if (this.options.removeOnExit) {
      process.on('exit', this.remove.bind(this));
    }
    this.emit('created', this);
  }.bind(this));
}

/**
 * Sync remove pid
 * @return {Boolean}
 */
Pid.prototype.remove = function remove() {
  try {
    fs.unlinkSync(this.options.path);
    this.emit('removed', this);
    return true;
  } catch(err) {
    if (err.code === 'ENOENT') {
      // Ignore any errors for missing files
      return true;
    }
    console.error(err);
    return false;
  }
};

/**
 * Create pid file
 */
Pid.prototype.create = function create(callback) {
  let pid = NaN;
  try {
    // Attempt to read the pid. Must be sync otherwise the rest of the app starts too quick
    pid = parseInt(fs.readFileSync(this.options.path, 'utf8'), 10);
  } catch(e) {
    // If it doesn't exist that's cool. We'll make it later.
    if (e.code !== 'ENOENT') {
      callback(e);
      return;
    }
  }

  if (pid === process.pid) {
    // The pid file already exists and matches the current pid
    callback();
    return;
  }

  // Check to see if we can see the process running
  const existingProcessRunning = !isNaN(pid) && processExists(pid);

  if (this.options.overwrite && existingProcessRunning) {
    this.emit('existing', pid, this.id);
    // If we do find a pid and we see a process is running, try to close it
    process.kill(pid, 'SIGTERM');
  } else if (!this.options.overwrite && existingProcessRunning) {
    // If we're not in overwrite mode and we see an existing PID throw
    callback(new Error('application already running - ' + pid.toString()));
    return;
  }

  // Open up file descriptor. By default fail if it exists
  fs.open(this.options.path, this.options.overwrite ? 'w' : 'wx', function(err, fd) {
    if (err) {
      callback(err);
    } else {
      writePid(fd, callback);
    }
  });
};

module.exports = Pid;
<commit_msg>removed unused var<commit_after>var fs = require('fs');
var path = require('path');
var EventEmitter = require('events');

/**
 * Write pid to file description
 * @param  {FileDescriptor} fd
 */
function writePid(fd, callback) {
  var buf = new Buffer(process.pid + '\n');
  fs.write(fd, buf, 0, buf.length, null, function(err){
    if (err) {
      throw err;
    }
    fs.close(fd, callback);
  });
}

/**
 * Check to see if a specific process id is actually running
 * @param    {Number}    pid
 * @return   {Boolean}
 */
function processExists(pid) {
  try {
    return process.kill(pid, 0);
  } catch (err) {
    return err.code === 'EPERM';
  }
}

/**
 * Create Pid
 * @param  {String} path Path to save
 * @param  {Object} options (optional) Settings
 * @example
 * 	var Pid = require('./Pid');
 * 	var pid = new Pid('/var/log/app.pid');
 */
function Pid(filename, options) {
  /**
   * Default options
   * @type {Object}
   */
  this.options = {
    /**
     * File path to pid
     */
    path: path.resolve(filename),
    /**
     * Automatically remove it when the process exists
     * @type {Boolean}
     */
    removeOnExit: true,
    /**
     * Overwrite an existing pid?
     * @type {Boolean}
     */
    overwrite: true
  };
  Object.assign(this.options, options);

  this.id = process.pid;

  // Emitter
  this._events = new EventEmitter();
  this.on = this._events.on.bind(this._events);
  this.once = this._events.once.bind(this._events);
  this.off = this._events.removeListener.bind(this._events);
  this.emit = this._events.emit.bind(this._events);

  // Bindings
  this.create = this.create.bind(this);
  this.remote = this.remove.bind(this);

  // Write pid file
  this.create(function(err){
    if (err) {
      this.emit('error', err);
    } else if (this.options.removeOnExit) {
      process.on('exit', this.remove.bind(this));
    }
    this.emit('created', this);
  }.bind(this));
}

/**
 * Sync remove pid
 * @return {Boolean}
 */
Pid.prototype.remove = function remove() {
  try {
    fs.unlinkSync(this.options.path);
    this.emit('removed', this);
    return true;
  } catch(err) {
    if (err.code === 'ENOENT') {
      // Ignore any errors for missing files
      return true;
    }
    console.error(err);
    return false;
  }
};

/**
 * Create pid file
 */
Pid.prototype.create = function create(callback) {
  let pid = NaN;
  try {
    // Attempt to read the pid. Must be sync otherwise the rest of the app starts too quick
    pid = parseInt(fs.readFileSync(this.options.path, 'utf8'), 10);
  } catch(e) {
    // If it doesn't exist that's cool. We'll make it later.
    if (e.code !== 'ENOENT') {
      callback(e);
      return;
    }
  }

  if (pid === process.pid) {
    // The pid file already exists and matches the current pid
    callback();
    return;
  }

  // Check to see if we can see the process running
  const existingProcessRunning = !isNaN(pid) && processExists(pid);

  if (this.options.overwrite && existingProcessRunning) {
    this.emit('existing', pid, this.id);
    // If we do find a pid and we see a process is running, try to close it
    process.kill(pid, 'SIGTERM');
  } else if (!this.options.overwrite && existingProcessRunning) {
    // If we're not in overwrite mode and we see an existing PID throw
    callback(new Error('application already running - ' + pid.toString()));
    return;
  }

  // Open up file descriptor. By default fail if it exists
  fs.open(this.options.path, this.options.overwrite ? 'w' : 'wx', function(err, fd) {
    if (err) {
      callback(err);
    } else {
      writePid(fd, callback);
    }
  });
};

module.exports = Pid;
<|endoftext|>


<commit_before>(function (exports) {
	'use strict';
	/*jshint node:true */

	var request, fs, hub, scrape, writer, Writer, ROOT_URL, getKnownEntities, types, logger,
		uuid, knownEntities, Sync, SPARQLURL, Query, query, NOW, diseaseFiles, getDiseaseFiles;

	ROOT_URL = process.env.ROOT_URL;
	SPARQLURL = process.env.SPARQLURL;
	request = require('request');
	hub = require('node-pubsub');
	fs = require('fs');
	NOW = (new Date()).toISOString(); //add .slice(0,10) to get date only.

	// Generate a UUID
	uuid = function uuid(a){
		//Function from https://gist.github.com/982883 (@jed)
		return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,uuid);
	};

	// Semaphore from https://gist.github.com/1296828
	Sync = function Sync(syncCount, callback, preventInstantCallbackExecution) {
		this.syncCount = syncCount;
		this.callback = callback;
		if(preventInstantCallbackExecution === false && this.syncCount === 0) {
			this.executeCallback();
		}
		Sync.prototype.decrement = function() {
			--this.syncCount;
			if(this.syncCount === 0) {
				this.executeCallback();
			}
		};
		Sync.prototype.increment = function() {
			++this.syncCount;
		};
		Sync.prototype.executeCallback = function() {
			if (typeof this.callback === "function") this.callback();
		};
	};

	// Writer Singleton
	Writer = (function (){
		var instantiated, init;

		init = function () {

			var writer = {}, fileName;

			fileName = "/tcgascrape"+Date.now()+".nt";

			writer.stream = fs.createWriteStream(process.cwd()+fileName);

			writer.listen = function (msg) {
				var triples = msg.triples;
				//triples = triples.split(" . ").join(" .\n");
				writer.stream.write(triples);
			};

			writer.close = function () {
				writer.stream.end();
			};

			return writer;

		};

		return {
			getInstance : function () {
				if (!instantiated) instantiated = init();
				return instantiated;
			}
		};
	})();

	// Query Singleton
	Query = (function (){
		var instantiated, init;

		init = function () {

			var query = {}, url, triples;

			url = process.env.SPARQLURL;
			triples = [];

			query.url = function (_) {
				if (!_) return url;
				else url = _;
				return query;
			};

			query.listen = function (msg) {
				triples.push(msg.triples);
				if (triples.length > 100) query.write();
			};

			query.write = function (){
				var insertQuery;
				insertQuery = 'INSERT DATA {\n'+triples.join("")+'\n}';
				triples = [];
				query.execute(insertQuery, function (error, response, body) {
					if (error || response.statusCode >= 300) {
						console.log("Unable to load triples:", insertQuery, error);
						console.log(response.statusCode, response.body);
						return;
					}
				});
			};

			query.flush = function () {
				query.write();
			};

			query.execute = function (query, callback) {
				request({
					url : url,//+encodeURIComponent(query),
					method : "POST",
					body : query
				}, callback);
			};

			return query;
		};

		return {
			getInstance : function () {
				if (!instantiated) instantiated = init();
				return instantiated;
			}
		};

	})();

	types = {
		9 : "DiseaseStudy",
		diseaseStudy : "DiseaseStudy",
		10 : "CenterType",
		11 : "CenterDomain",
		12 : "Platform",
		13 : "DataType",
		14 : "Archive",
		archive : "Archive",
		15 : "File",
		file : "File"
	};

	knownEntities = {};

	diseaseFiles = {};

	getKnownEntities = function (callback) {
		var query;

		query = [
			'prefix rdfs:<http://www.w3.org/2000/01/rdf-schema#>',
			'prefix tcga:<http://purl.org/tcga/core#>',
			'select distinct ?url ?id where {',
			'	?id tcga:url ?url .',
			'	?id a ?type .',
			'	filter (!(?type = tcga:File))',
			'}'
		].join(' ');

		request({
				method : "POST",
				url : SPARQLURL+encodeURIComponent(query),
				headers : { "Accept" : "application/sparql-results+json" }
			}, function ( error, response, body ) {

				if (response.statusCode === 204) {
					console.log('Found no known entities.');
					return callback();
				}

				if (error || response.statusCode !== 200) {
					console.log("Unable to query SPARQL endpoint");
					return;
				}

				var bindings;

				bindings = JSON.parse(body).results.bindings;

				bindings.forEach(function (binding) {
					knownEntities[binding.url.value] = binding;
				});

				console.log('Found', bindings.length, 'entities.');

				return callback();
		});
	};

	getDiseaseFiles = function (disease, callback) {
		var query;

		diseaseFiles = {};

		query = [
			'prefix rdfs:<http://www.w3.org/2000/01/rdf-schema#>',
			'prefix tcga:<http://purl.org/tcga/core#>',
			'select distinct ?url ?id where {',
			'	?id tcga:url ?url .',
			'	?id tcga:diseaseStudy ?d .',
			'	?d rdfs:label "'+disease+'" .',
			'}'
		].join(' ');

		request({
				method : "POST",
				url : SPARQLURL+encodeURIComponent(query),
				headers : { "Accept" : "application/sparql-results+json" }
			}, function ( error, response, body ) {

				if (response.statusCode === 204) {
					console.log("Found no entities for", disease, ".");
					return callback();
				}

				if (error || response.statusCode !== 200) {
					console.log("Unable to query SPARQL endpoint for",disease,"files.");
					return;
				}

				var bindings;

				bindings = JSON.parse(body).results.bindings;

				bindings.forEach(function (binding) {
					diseaseFiles[binding.url.value] = binding;
				});

				console.log('Found', bindings.length, 'entities for', disease,'.');

				return callback();
		});

	};

	scrape = function (options) {
		var opts, target, parent, callback, start, callCallback;

		opts = options || {};
		target = opts.target || ROOT_URL;
		parent = opts.parent || {};

		callCallback = function () {
			if (callback && typeof callback === 'function') callback();
		};
		callback = opts.callback;

		request(target, function (error, response, body) {

			if (error || response.statusCode !== 200) {
				console.log("Failed to get", target);
				return callCallback();
			}

			else {

				var pre, rows, children = [], tcga, literal;

				tcga = function (name) { return "<http://purl.org/tcga/core#"+name+">"; };
				literal = function (value) { return '"'+value+'"'; };
				pre = body.match(/<pre>([\s\S]*)<\/pre>/);
				if (!pre) {
					console.log("Could not parse (pre)", target);
					return callCallback();
				} else pre = pre[1];
				rows = pre.match(/<a[^>]+>[^<]+<\/a>\s+\d{2}-\w{3}-\d{4}/g);

				if (rows) rows.forEach(function (row) {

					var name, id, url, type, tripleString, lastModified, subject, scrapeChildren = true, level;

					name = row.match(/>([\s\S]*)</);
					if (!name) console.log("Could not parse (name)", row); else name = name[1];
					id = uuid();
					url = target + row.match(/href="(.*)"/)[1];
					level = target.split('/').length;
					type = types[level];
					lastModified = (new Date(row.match(/\d{2}-\w{3}-\d{4}/)[0])).toISOString().slice(0,10);
					tripleString = "";

					if ((process.env.TESTING && level === 10) || level >= 15) {
						scrapeChildren = false;
						if (target.match(/ucec|thca|stad/)) scrapeChildren = true;
					}

					if (name === 'lost+found/') return;

					name = name.trim();

					// Things with extensions are files (e.g. reallylong_name.tiff)
					// TODO Use MIME types to determine files.
					if (name.match(/^.*\.[^\/]+$/)) {
						type = types.file;
						scrapeChildren = false;
					}

					// Remove the trailing "/"
					if (name.charAt(name.length-1) === "/") name = name.slice(0,-1);

					// If a file ends in .tar.gz or .tar.gz.md5, type it as an archive
					if (type === types.file && name.match(/\.tar\.gz($|\.md5$)/)) {
						type = types.archive;
					}

					// If a file is of the form
					// <domain>_<disease study>.<platform>.<archive type>.<serial index>.<revision>.<series>
					// type it as an archive
					if (name.match(/.*?_(.*?\.){5}\d$/)) {
						type = types.archive;
					}

					// Either insert or update, based on whether this item exists in the known entities.
					if (!knownEntities[url] && !diseaseFiles[url]) {
						var entity = {
							id : { value : id },
							newEntity : true
						};
						if (type !== types.file) knownEntities[url] = entity;
						else diseaseFiles[url] = entity;
						subject = id.length === 36 ? tcga(id) : "<" + id + ">";
						tripleString = [
							subject, tcga("lastSeen"), literal(NOW), ".\n",
							subject, tcga("firstSeen"), literal(NOW), ".\n",
							subject, "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>",  tcga(type), ".\n",
							subject, "<http://www.w3.org/2000/01/rdf-schema#label>", literal(name), ".\n",
							subject, tcga("url"), literal(url), ".\n"
						];

						if (type === types.file || types === types.archive) {
							tripleString.push(subject, tcga("lastModified"), literal(lastModified), ".\n");
						}

						if (type === types.file) {
							var ancestor;
							Object.keys(parent).forEach(function (ancestor) {
								// Make the first letter lowercase
								var property = ancestor.charAt(0).toLowerCase() + ancestor.slice(1);
								tripleString.push(subject, tcga(property), parent[ancestor], ".\n");
							});
						}
					}
					else {
						if (knownEntities[url]) id = knownEntities[url].id.value;
						else id = diseaseFiles[url].id.value;
						subject = id.length === 36 ? tcga(id) : "<" + id + ">";
						tripleString = [
							subject, tcga("lastSeen"), literal(NOW), ".\n"
						];

						// Additional URLS may need to be added for new entities, such as center types.
						if (knownEntities[url] && knownEntities[url].newEntity) {
							tripleString.push(subject, tcga("url"), literal(url), ".\n");
						}
					}

					hub.publish('/triples', [{
						triples : tripleString.join(" "),
						type : type,
						name : name
					}]);

					if (scrapeChildren){
						var child;
						parent[type] = subject;
						child = {target:url, parent:JSON.parse(JSON.stringify(parent))};
						if (type == types.diseaseStudy) {
							child.type = type;
							child.name = name;
						}
						children.push(child);
					}

				});

				if (children.length > 0) {
					var counter = new Sync(children.length, callback);
					var nextChild = function nextChild(children){
						var child = children.pop();
						if (child){
							child.callback = function(){
								counter.decrement();
								nextChild(children);
							};
							if (child.type === types.diseaseStudy) {
								getDiseaseFiles(child.name, function () {
									scrape(child);
								});
							} else {
								scrape(child);
							}
						}
					};
					nextChild(children);
				}
				else callCallback();

			}

		});
	};

	//writer = Writer.getInstance();

	query = Query.getInstance().url(process.env.SPARQLURL);

	hub.subscribe('/triples', query.listen);

	//hub.subscribe('/triples', writer.listen);

	console.log('Getting known entities from hub.');

	getKnownEntities(function (err) {
		if (err) console.log(err);
		console.log('Beginning scrape of', ROOT_URL);
		scrape({
			target : ROOT_URL,
			callback : function () {
				Query.getInstance().flush();
				// writer.close();
				console.log("Scrape finished");
			}
		});
	});

})( exports );
<commit_msg>Updated regex to match new date format in TCGA.<commit_after>(function (exports) {
	'use strict';
	/*jshint node:true */

	var request, fs, hub, scrape, writer, Writer, ROOT_URL, getKnownEntities, types, logger,
		uuid, knownEntities, Sync, SPARQLURL, Query, query, NOW, diseaseFiles, getDiseaseFiles;

	ROOT_URL = process.env.ROOT_URL;
	SPARQLURL = process.env.SPARQLURL;
	request = require('request');
	hub = require('node-pubsub');
	fs = require('fs');
	NOW = (new Date()).toISOString(); //add .slice(0,10) to get date only.

	// Generate a UUID
	uuid = function uuid(a){
		//Function from https://gist.github.com/982883 (@jed)
		return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,uuid);
	};

	// Semaphore from https://gist.github.com/1296828
	Sync = function Sync(syncCount, callback, preventInstantCallbackExecution) {
		this.syncCount = syncCount;
		this.callback = callback;
		if(preventInstantCallbackExecution === false && this.syncCount === 0) {
			this.executeCallback();
		}
		Sync.prototype.decrement = function() {
			--this.syncCount;
			if(this.syncCount === 0) {
				this.executeCallback();
			}
		};
		Sync.prototype.increment = function() {
			++this.syncCount;
		};
		Sync.prototype.executeCallback = function() {
			if (typeof this.callback === "function") this.callback();
		};
	};

	// Writer Singleton
	Writer = (function (){
		var instantiated, init;

		init = function () {

			var writer = {}, fileName;

			fileName = "/tcgascrape"+Date.now()+".nt";

			writer.stream = fs.createWriteStream(process.cwd()+fileName);

			writer.listen = function (msg) {
				var triples = msg.triples;
				//triples = triples.split(" . ").join(" .\n");
				writer.stream.write(triples);
			};

			writer.close = function () {
				writer.stream.end();
			};

			return writer;

		};

		return {
			getInstance : function () {
				if (!instantiated) instantiated = init();
				return instantiated;
			}
		};
	})();

	// Query Singleton
	Query = (function (){
		var instantiated, init;

		init = function () {

			var query = {}, url, triples;

			url = process.env.SPARQLURL;
			triples = [];

			query.url = function (_) {
				if (!_) return url;
				else url = _;
				return query;
			};

			query.listen = function (msg) {
				triples.push(msg.triples);
				if (triples.length > 100) query.write();
			};

			query.write = function (){
				var insertQuery;
				insertQuery = 'INSERT DATA {\n'+triples.join("")+'\n}';
				triples = [];
				query.execute(insertQuery, function (error, response, body) {
					if (error || response.statusCode >= 300) {
						console.log("Unable to load triples:", insertQuery, error);
						console.log(response.statusCode, response.body);
						return;
					}
				});
			};

			query.flush = function () {
				query.write();
			};

			query.execute = function (query, callback) {
				request({
					url : url,//+encodeURIComponent(query),
					method : "POST",
					body : query
				}, callback);
			};

			return query;
		};

		return {
			getInstance : function () {
				if (!instantiated) instantiated = init();
				return instantiated;
			}
		};

	})();

	types = {
		9 : "DiseaseStudy",
		diseaseStudy : "DiseaseStudy",
		10 : "CenterType",
		11 : "CenterDomain",
		12 : "Platform",
		13 : "DataType",
		14 : "Archive",
		archive : "Archive",
		15 : "File",
		file : "File"
	};

	knownEntities = {};

	diseaseFiles = {};

	getKnownEntities = function (callback) {
		var query;

		query = [
			'prefix rdfs:<http://www.w3.org/2000/01/rdf-schema#>',
			'prefix tcga:<http://purl.org/tcga/core#>',
			'select distinct ?url ?id where {',
			'	?id tcga:url ?url .',
			'	?id a ?type .',
			'	filter (!(?type = tcga:File))',
			'}'
		].join(' ');

		request({
				method : "POST",
				url : SPARQLURL+encodeURIComponent(query),
				headers : { "Accept" : "application/sparql-results+json" }
			}, function ( error, response, body ) {

				if (response.statusCode === 204) {
					console.log('Found no known entities.');
					return callback();
				}

				if (error || response.statusCode !== 200) {
					console.log("Unable to query SPARQL endpoint");
					return;
				}

				var bindings;

				bindings = JSON.parse(body).results.bindings;

				bindings.forEach(function (binding) {
					knownEntities[binding.url.value] = binding;
				});

				console.log('Found', bindings.length, 'entities.');

				return callback();
		});
	};

	getDiseaseFiles = function (disease, callback) {
		var query;

		diseaseFiles = {};

		query = [
			'prefix rdfs:<http://www.w3.org/2000/01/rdf-schema#>',
			'prefix tcga:<http://purl.org/tcga/core#>',
			'select distinct ?url ?id where {',
			'	?id tcga:url ?url .',
			'	?id tcga:diseaseStudy ?d .',
			'	?d rdfs:label "'+disease+'" .',
			'}'
		].join(' ');

		request({
				method : "POST",
				url : SPARQLURL+encodeURIComponent(query),
				headers : { "Accept" : "application/sparql-results+json" }
			}, function ( error, response, body ) {

				if (response.statusCode === 204) {
					console.log("Found no entities for", disease, ".");
					return callback();
				}

				if (error || response.statusCode !== 200) {
					console.log("Unable to query SPARQL endpoint for",disease,"files.");
					return;
				}

				var bindings;

				bindings = JSON.parse(body).results.bindings;

				bindings.forEach(function (binding) {
					diseaseFiles[binding.url.value] = binding;
				});

				console.log('Found', bindings.length, 'entities for', disease,'.');

				return callback();
		});

	};

	scrape = function (options) {
		var opts, target, parent, callback, start, callCallback;

		opts = options || {};
		target = opts.target || ROOT_URL;
		parent = opts.parent || {};

		callCallback = function () {
			if (callback && typeof callback === 'function') callback();
		};
		callback = opts.callback;

		request(target, function (error, response, body) {

			if (error || response.statusCode !== 200) {
				console.log("Failed to get", target);
				return callCallback();
			}

			else {

				var pre, rows, children = [], tcga, literal;

				tcga = function (name) { return "<http://purl.org/tcga/core#"+name+">"; };
				literal = function (value) { return '"'+value+'"'; };
				pre = body.match(/<pre>([\s\S]*)<\/pre>/);
				if (!pre) {
					console.log("Could not parse (pre)", target);
					return callCallback();
				} else pre = pre[1];
				rows = pre.match(/<a[^>]+>[^<]+<\/a>\s+[\d-]{10}/g);

				if (rows) rows.forEach(function (row) {

					var name, id, url, type, tripleString, lastModified, subject, scrapeChildren = true, level;

					name = row.match(/>([\s\S]*)</);
					if (!name) console.log("Could not parse (name)", row); else name = name[1];
					id = uuid();
					url = target + row.match(/href="(.*)"/)[1];
					level = target.split('/').length;
					type = types[level];
					lastModified = (new Date(row.match(/[\d-]{10}/)[0])).toISOString().slice(0,10);
					tripleString = "";

					if ((process.env.TESTING && level === 10) || level >= 15) {
						scrapeChildren = false;
						if (target.match(/ucec|thca|stad/)) scrapeChildren = true;
					}

					if (name === 'lost+found/') return;

					name = name.trim();

					// Things with extensions are files (e.g. reallylong_name.tiff)
					// TODO Use MIME types to determine files.
					if (name.match(/^.*\.[^\/]+$/)) {
						type = types.file;
						scrapeChildren = false;
					}

					// Remove the trailing "/"
					if (name.charAt(name.length-1) === "/") name = name.slice(0,-1);

					// If a file ends in .tar.gz or .tar.gz.md5, type it as an archive
					if (type === types.file && name.match(/\.tar\.gz($|\.md5$)/)) {
						type = types.archive;
					}

					// If a file is of the form
					// <domain>_<disease study>.<platform>.<archive type>.<serial index>.<revision>.<series>
					// type it as an archive
					if (name.match(/.*?_(.*?\.){5}\d$/)) {
						type = types.archive;
					}

					// Either insert or update, based on whether this item exists in the known entities.
					if (!knownEntities[url] && !diseaseFiles[url]) {
						var entity = {
							id : { value : id },
							newEntity : true
						};
						if (type !== types.file) knownEntities[url] = entity;
						else diseaseFiles[url] = entity;
						subject = id.length === 36 ? tcga(id) : "<" + id + ">";
						tripleString = [
							subject, tcga("lastSeen"), literal(NOW), ".\n",
							subject, tcga("firstSeen"), literal(NOW), ".\n",
							subject, "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>",  tcga(type), ".\n",
							subject, "<http://www.w3.org/2000/01/rdf-schema#label>", literal(name), ".\n",
							subject, tcga("url"), literal(url), ".\n"
						];

						if (type === types.file || types === types.archive) {
							tripleString.push(subject, tcga("lastModified"), literal(lastModified), ".\n");
						}

						if (type === types.file) {
							var ancestor;
							Object.keys(parent).forEach(function (ancestor) {
								// Make the first letter lowercase
								var property = ancestor.charAt(0).toLowerCase() + ancestor.slice(1);
								tripleString.push(subject, tcga(property), parent[ancestor], ".\n");
							});
						}
					}
					else {
						if (knownEntities[url]) id = knownEntities[url].id.value;
						else id = diseaseFiles[url].id.value;
						subject = id.length === 36 ? tcga(id) : "<" + id + ">";
						tripleString = [
							subject, tcga("lastSeen"), literal(NOW), ".\n"
						];

						// Additional URLS may need to be added for new entities, such as center types.
						if (knownEntities[url] && knownEntities[url].newEntity) {
							tripleString.push(subject, tcga("url"), literal(url), ".\n");
						}
					}

					hub.publish('/triples', [{
						triples : tripleString.join(" "),
						type : type,
						name : name
					}]);

					if (scrapeChildren){
						var child;
						parent[type] = subject;
						child = {target:url, parent:JSON.parse(JSON.stringify(parent))};
						if (type == types.diseaseStudy) {
							child.type = type;
							child.name = name;
						}
						children.push(child);
					}

				});

				if (children.length > 0) {
					var counter = new Sync(children.length, callback);
					var nextChild = function nextChild(children){
						var child = children.pop();
						if (child){
							child.callback = function(){
								counter.decrement();
								nextChild(children);
							};
							if (child.type === types.diseaseStudy) {
								getDiseaseFiles(child.name, function () {
									scrape(child);
								});
							} else {
								scrape(child);
							}
						}
					};
					nextChild(children);
				}
				else callCallback();

			}

		});
	};

	//writer = Writer.getInstance();

	query = Query.getInstance().url(process.env.SPARQLURL);

	hub.subscribe('/triples', query.listen);

	//hub.subscribe('/triples', writer.listen);

	console.log('Getting known entities from hub.');

	getKnownEntities(function (err) {
		if (err) console.log(err);
		console.log('Beginning scrape of', ROOT_URL);
		scrape({
			target : ROOT_URL,
			callback : function () {
				Query.getInstance().flush();
				// writer.close();
				console.log("Scrape finished");
			}
		});
	});

})( exports );
<|endoftext|>


<commit_before>import React, { Component } from "react"
import Weekview from "./Weekview"
import Scheduleview from "./Scheduleview"
import Titlebar from "./Titlebar"

class App extends Component {
  state = {
    courses: null,
    termBounds: null,
    currentDateRange: null,
    calendarType: "weekview",
    theme: "oakland",
    url: null
  }

  componentDidMount() {
    fetch("http://localhost:8082/api/terms")
      .then(response => {
        return response.json()
      })
      .then(data => {
        this.setState({ termBounds: [data.terms[0].start, data.terms[0].end] })
      })

    fetch("http://localhost:8082/api/courses")
      .then(response => {
        return response.json()
      })
      .then(data => {
        this.setState({ courses: data.courses })
      })

    let d = new Date()
    let obj = {
      year: d.getFullYear(),
      month: d.getMonth(),
      day: d.getDate()
    }
    this.setState({ currentDateRange: obj })
  }

  changeCalendarView = view => {
    this.setState({ calendarType: view })
  }

  render() {
    if (this.state.courses === null || this.state.courses === undefined) {
      return
boom

    }
    return (

        <Titlebar
          currentDateRange={this.state.currentDateRange}
          termBounds={this.state.termBounds}
          courses={this.state.courses}
          calendarType={this.state.calendarType}
          changeCalendarView={this.changeCalendarView}
        />
        <Weekview />

    )
  }
}

export default App
<commit_msg>Added method to change parent date state<commit_after>import React, { Component } from "react"
import Weekview from "./Weekview"
import Scheduleview from "./Scheduleview"
import Titlebar from "./Titlebar"
import { getWeekOfMonth } from "./utils/DateHelper"

class App extends Component {
  state = {
    courses: null,
    termBounds: null,
    currentDateRange: null,
    calendarType: "weekview",
    theme: "oakland",
    url: null
  }

  componentDidMount() {
    fetch("http://localhost:8082/api/terms")
      .then(response => {
        return response.json()
      })
      .then(data => {
        this.setState({ termBounds: [data.terms[0].start, data.terms[0].end] })
      })

    fetch("http://localhost:8082/api/courses")
      .then(response => {
        return response.json()
      })
      .then(data => {
        this.setState({ courses: data.courses })
      })

    let d = new Date()
    let obj = {
      year: d.getFullYear(),
      month: d.getMonth(),
      week: getWeekOfMonth(d.getFullYear(), d.getMonth(), d.getDate()),
      day: d.getDate()
    }
    this.setState({ currentDateRange: obj })
  }

  changeCalendarView = view => {
    this.setState({ calendarType: view })
  }

  changeDateRange = (obj) => {
    this.setState({
      currentDateRange: {
        year: obj.year,
        month: obj.month,
        week: obj.week,
        day: obj.day
      }
    })
  }

  render() {
    if (this.state.courses === null || this.state.courses === undefined) {
      return
boom

    }
    return (

        <Titlebar
          currentDateRange={this.state.currentDateRange}
          termBounds={this.state.termBounds}
          courses={this.state.courses}
          calendarType={this.state.calendarType}
          changeCalendarView={this.changeCalendarView}
          changeDateRange={this.changeDateRange}
        />
        <Weekview />

    )
  }
}

export default App
<|endoftext|>


<commit_before>var request = require('request')
var cheerio = require('cheerio')
var config = require('./config')
var secrets = require('./secrets')

request(config.scrapeUrl, function(error, response, html) {
  if(error) {
    console.error(error)
    return
  }

  var $ = cheerio.load(html)

  $('#ObjectsContainer input[type=hidden]').each(function() {
    var id = $(this).attr('id')
    if(id == 'mgmMarkerIDs'){
      return
    }

    var data = $(this).attr('value').split('~')
    var object = {
      id: data[0],
      prijs: data[16] + ' ' + data[17] + (data[15] ? ' ' + data[15] : ''),
      buurt: data[5],
      status: data[23] == '1' ? 'te koop' : data[13],
      url: data[18]
    }

    console.log(object)
  });
})

// 00 : ID            'ReaOP1135624512',
// 01 : ?             '1',
// 02 : Lat,Lng       '52.3569568,4.79270919999999',
// 03 : Postcode      '1069DW',
// 04 : Stad          'Amsterdam',
// 05 : Wijk          'Amsterdam, Sloten/Slotervaart/Osdorp',
// 06 : Straat        'Tussen Meer',
// 07 : Huisnummer    '226',
// 08 : Toevoeging    '',
// 09 : ?             'WH',
// 10 : ?             '1',
// 11 : Type woning   'Portiekflat',
// 12 : Vol addres    'Tussen Meer 226 1069 DW Amsterdam, Sloten/Slotervaart/Osdorp ',
// 13 : Prijs HTML    'Koopsom
€ 160.000 ',
// 14 : Prijs raw     '160000',
// 15 : Prijs type    'k.k.',
// 16 : Prijs beschr. 'koopsom',
// 17 : Prijs nice    '160.000',
// 18 : URL           'http://www.mva.nl/huizen/Tussen-Meer-226-1069DW-Amsterdam-ReaOP1135624512.html',
// 19 : Thumbnail     'http://media.mva.nl/MVASysteem/WONEN/ReaOP1135624512/1.jpg',
// 20 : ?             '0',
// 21 : ?             '1',
// 22 : Datum         '14/04/2015',
// 23 : Status        '1' // 1: te koop, 2: verkocht, 6: onder bod
<commit_msg>Docs update.<commit_after>var request = require('request')
var cheerio = require('cheerio')
var config = require('./config')
var secrets = require('./secrets')

request(config.scrapeUrl, function(error, response, html) {
  if(error) {
    console.error(error)
    return
  }

  var $ = cheerio.load(html)

  $('#ObjectsContainer input[type=hidden]').each(function() {
    var id = $(this).attr('id')
    if(id == 'mgmMarkerIDs'){
      return
    }

    var data = $(this).attr('value').split('~')
    var object = {
      id: data[0],
      prijs: data[16] + ' ' + data[17] + (data[15] ? ' ' + data[15] : ''),
      buurt: data[5],
      status: data[23] == '1' ? 'te koop' : data[13],
      url: data[18]
    }

    console.log(object)
  });
})

// 00 : ID               'ReaOP1135624512',
// 01 : ?                '1',
// 02 : Lat,Lng          '52.3569568,4.79270919999999',
// 03 : Postcode         '1069DW',
// 04 : Stad             'Amsterdam',
// 05 : Wijk             'Amsterdam, Sloten/Slotervaart/Osdorp',
// 06 : Straat           'Tussen Meer',
// 07 : Huisnummer       '226',
// 08 : Toevoeging       '',
// 09 : ?                'WH',
// 10 : ?                '1',
// 11 : Type woning      'Portiekflat',
// 12 : Vol addres       'Tussen Meer 226 1069 DW Amsterdam, Sloten/Slotervaart/Osdorp ',
// 13 : Prijs of status  'Koopsom
€ 160.000 ',
// 14 : Prijs raw        '160000',
// 15 : Prijs type       'k.k.',
// 16 : Prijs beschr.    'koopsom',
// 17 : Prijs nice       '160.000',
// 18 : URL              'http://www.mva.nl/huizen/Tussen-Meer-226-1069DW-Amsterdam-ReaOP1135624512.html',
// 19 : Thumbnail        'http://media.mva.nl/MVASysteem/WONEN/ReaOP1135624512/1.jpg',
// 20 : ?                '0',
// 21 : ?                '1',
// 22 : Datum            '14/04/2015',
// 23 : Status           '1' // 1: te koop, 2: verkocht, 6: onder bod
<|endoftext|>


<commit_before><commit_msg>display instructions in embed level mode<commit_after><|endoftext|>


<commit_before>import React from 'react'
import Helmet from 'react-helmet'
import Modal from 'react-modal'
import { Route, Switch, Redirect } from 'react-router'
import Body from './Body.js'
import Home from './Home'
import Products from './Products'
import Photos from './Photos'
import Covid from './Covid'
import Information from './Information'

// Title
const baseTitle = 'K&K  Blueberries - U-Pick Blueberries in Hermiston, Oregon!'
const defaultTitle = 'Welcome to ' + baseTitle
const titleTemplate = '%s ' + baseTitle

// Meta tags
const metaDescription =
  'K & K Blueberries offers u-pick blueberries in Hermiston, Oregon, located in the pacific northwest'
const metaKeywords =
  'blueberries, pick bluberries, u-pick, family blueberry farm, Hermiston bluberries, fun u-pick farms, berry farm pacific northwest, July blueberries, bluberry farm, Umatilla county farm, Minnehaha farm'

// Status message shown at the top of all pages
// const statusMessage = (
//

//     We are opening for the 2021 fresh blueberry picking season{' '}
//     on Thursday, June 17th! Looking forward to seeing our returning
//     customers and meeting our new ones! Call or visit our{' '}
//
//       Facebook page
//     {' '}
//     for up to date information.
//

// )

const statusMessage = (

    K {'&'} K Blueberries has closed for the 2021 season. 💜💜💜 I want to thank all the people who came out during this short, hot blueberry season. You supported my small business, got outside with your family and friends, and went home with some delicious blueberries. It was a great season made better for seeing all of you! 💜💜💜. Remember to start looking around Father's Day on our Facebook page - it's when I get a good idea of when I will be able to open. See you next year! Kathy

)

// const warningMessage = (
//

//     We'll be open for the 2020 season and following social distancing
//     guidelines. Please read our{' '}
//     <Link to={{ pathname: '/covid19' }}>COVID-19 Policy</Link> before arriving.
//

// )

// const warningMessage = (
//

//     Due to extreme heat we are extending our morning hours 6:30 to 2 Monday through Sunday but will NOT be having an evening pick. Sunday is still 7 am to 2. Sorry for the inconvenience.
//

// )

const warningMessage = undefined;

Modal.setAppElement('#app')

export default () => (

    <Helmet titleTemplate={titleTemplate} defaultTitle={defaultTitle}>
      <meta name="description" content={metaDescription} />
      <meta name="keywords" content={metaKeywords} />
    </Helmet>

      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/covid19" component={Covid} />
        <Route exact path="/photos" component={Photos} />
        <Route exact path="/products" component={Products} />
        <Route exact path="/info" component={Information} />
        <Redirect to="/" />
      </Switch>

)
<commit_msg>Coming soon message<commit_after>import React from 'react'
import Helmet from 'react-helmet'
import Modal from 'react-modal'
import { Route, Switch, Redirect } from 'react-router'
import Body from './Body.js'
import Home from './Home'
import Products from './Products'
import Photos from './Photos'
import Covid from './Covid'
import Information from './Information'

// Title
const baseTitle = 'K&K  Blueberries - U-Pick Blueberries in Hermiston, Oregon!'
const defaultTitle = 'Welcome to ' + baseTitle
const titleTemplate = '%s ' + baseTitle

// Meta tags
const metaDescription =
  'K & K Blueberries offers u-pick blueberries in Hermiston, Oregon, located in the pacific northwest'
const metaKeywords =
  'blueberries, pick bluberries, u-pick, family blueberry farm, Hermiston bluberries, fun u-pick farms, berry farm pacific northwest, July blueberries, bluberry farm, Umatilla county farm, Minnehaha farm'

// Status message shown at the top of all pages
const statusMessage = (

    Due to the cooler than normal spring, blueberry season is going to be a little later than normal - closer to the end of June than the middle. Please keep checking for updates here on our webpage and on our{' '}

      Facebook page
    . See you soon, Kathy

)

// const statusMessage = (
//

//     K {'&'} K Blueberries has closed for the 2021 season. 💜💜💜 I want to thank all the people who came out during this short, hot blueberry season. You supported my small business, got outside with your family and friends, and went home with some delicious blueberries. It was a great season made better for seeing all of you! 💜💜💜. Remember to start looking around Father's Day on our Facebook page - it's when I get a good idea of when I will be able to open. See you next year! Kathy
//

// )

// const warningMessage = (
//

//     We'll be open for the 2020 season and following social distancing
//     guidelines. Please read our{' '}
//     <Link to={{ pathname: '/covid19' }}>COVID-19 Policy</Link> before arriving.
//

// )

// const warningMessage = (
//

//     Due to extreme heat we are extending our morning hours 6:30 to 2 Monday through Sunday but will NOT be having an evening pick. Sunday is still 7 am to 2. Sorry for the inconvenience.
//

// )

const warningMessage = undefined;

Modal.setAppElement('#app')

export default () => (

    <Helmet titleTemplate={titleTemplate} defaultTitle={defaultTitle}>
      <meta name="description" content={metaDescription} />
      <meta name="keywords" content={metaKeywords} />
    </Helmet>

      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/covid19" component={Covid} />
        <Route exact path="/photos" component={Photos} />
        <Route exact path="/products" component={Products} />
        <Route exact path="/info" component={Information} />
        <Redirect to="/" />
      </Switch>

)
<|endoftext|>