text:
package p4Kirk;
//Author 		 : Justin Kirk
//Student Number : J00445608
//Date Submitted : April 21, 2015
//File           : GUI.java
//Instructor     : Mrs. McKinney
//Class          : CSC 121 (9:30 AM - 10:45 AM)
//Identification : Program 4
/* Purpose       : The purpose of this assignment is to give a problem-solving experience with
 *                 more GUI components and event-handlers, generic sorting, recursion, and binary files.
 *                 A text file can be opened and the subclasses of abstract super class Website are created
 *                 and placed in the  arrayOfWebsites. A binary file can be saved using the arrayOfWebsites.
 *                 A binary file containing an arrayOfWebsites can be opened and the arrayOfWebsites is set to this.
 *                 The main tab shows every website in the array in a table with columns of the websites'
 *                 attributes. A selected website shows each attribute above the table along with its logo which
 *                 when clicked will navigate the default browser to the website. The search tab needs to be
 *                 sorted first using a generic sort. A JList holds every websites' name which can be
 *                 filtered using a recursive binary search. When a row is clicked in the JList, the main tab is
 *                 displayed with that website's attributes displayed.
 */

//Import
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.*;
import javax.swing.border.TitledBorder;

//GUI inherits JFrame
public class GUI extends JFrame{

	//serialVersionUID
	private static final long serialVersionUID = 1L;
	//windowLayout
	FlowLayout windowLayout = new FlowLayout();

//Class JTextFields

	private static JTextField B_nameLBL = new JTextField(25);
	private static JTextField B_URLLBL = new JTextField(25);
	private static JTextField B_contentLBL = new JTextField(25);
	private static JTextField B_AccessLBL = new JTextField(25);
	private static JTextField B_purposeLBL = new JTextField(25);
	private static JTextField B_classificationLBL = new JTextField(25);
	private static JTextField searchBox =  new JTextField(15);

//Class JButtons

    private static JButton sortButton;
    private static JButton quitButton;
    private static JButton saveButton;
    private static JButton websiteImage;
    private static JButton searchButton;
    private static JButton clearButton;

//Class JTable

    private static JTable table;
    private static DefaultTableModel model;

//Class arrayOfWebsiteNames

	private static ArrayList<String> websiteNamesArray = new ArrayList<String>();

//Class JTabbedPane

    private static JTabbedPane tabbedPane;

//Class JList

    private static JList<Object> websiteNamesJList;

// Constructor for GUI
    public GUI (String name) {
    	//Inherits name from JFrame
        super(name);
    }

//Add components to Container pane
    public void addComponentsToPane(final Container pane) {

//----------------------JPanels----------------------------------

    	//sortSearch JPanel
    	final JPanel sortSearch = new JPanel();
    	sortSearch.setLayout(windowLayout);
    	sortSearch.setBorder(new TitledBorder ("Sort and Search Websites"));

        //website Image JPanel
    	final JPanel websiteImagePanel = new JPanel();
    	websiteImagePanel.setLayout(windowLayout);

        //NORTH JPanel
        final JPanel north = new JPanel();
        north.setLayout(new FlowLayout());

        //CENTER JPanel
        final JPanel center = new JPanel();
        center.setLayout(new BorderLayout());

        //actions JPanel
        final JPanel actions = new JPanel();
        actions.setLayout(windowLayout);
        actions.setBorder(new TitledBorder ("Actions"));

        //Text JPanel
        final JPanel Text = new JPanel();
        //13 rows with 2 columns
        Text.setLayout(new GridLayout(6,2));
        Text.setBorder(new TitledBorder ("Website Information"));

//----------------------JButtons--------------------------------------------------

        sortButton = new JButton("Sort", new ImageIcon("Images/sort.png"));
        quitButton = new JButton("Quit");
        saveButton = new JButton("Save");
        saveButton.setEnabled(false);
        searchButton = new JButton("Search");
        searchButton.setVisible(false);
        clearButton = new JButton("Clear");
        clearButton.setVisible(false);
        websiteImage = new JButton(new ImageIcon("Images/icon8080.png"));

//----------------------JLabels----------------------------------

        JLabel A_classificationLBL = new JLabel("Classification: ");
        JLabel A_nameLBL = new JLabel("Website Name: ");
        JLabel A_URLLBL = new JLabel("Web Address:");
        JLabel A_contentLBL = new JLabel("Content:");
        JLabel A_purposeLBL = new JLabel("Purpose/Agency:");
    	JLabel A_AccessLBL = new JLabel("Membership:");
    	searchBox.setVisible(false);
    	searchBox.setToolTipText("Search for a website by its name");

//----------------------Menu Bar----------------------
    	//Create JMenus
    	JMenu fileMenu, windowMenu;

        //Create the menu bar.
        JMenuBar menuBar = new JMenuBar();

//----------------------File-----------------------------

        fileMenu = new JMenu("File");
        menuBar.add(fileMenu);

        //New file
        JMenuItem newMenuItem = new JMenuItem("New file");
        newMenuItem.setIcon(new ImageIcon("Images/new.jpg"));
        newMenuItem.addMouseListener(new MouseAdapter() {
    		public void mousePressed(MouseEvent e) {
    			try {
    				//Initialize Array after user selects a file
					Program4Driver.initializeArray();
					saveButton.setEnabled(false);
					searchBox.setVisible(false);
					searchBox.setText("");
					sortButton.setVisible(true);
			        searchButton.setVisible(false);
			        clearButton.setVisible(false);
				} catch (IOException e1) {}
    			//Add rows based on arrayOfWebsites
    			addRowsToTable();
    			//Populate JList based on arrayOfWebsites
    			populateJList();
    			//Enabled save button
    			saveButton.setEnabled(true);
    		}
        });
        fileMenu.add(newMenuItem);

        //Open file
        JMenuItem openMenuItem = new JMenuItem("Open file");
        openMenuItem.setIcon(new ImageIcon("Images/open.png"));
        openMenuItem.addMouseListener(new MouseAdapter() {
    		public void mousePressed(MouseEvent e) {
    			Program4Driver.openBinaryFile();
    			saveButton.setEnabled(false);
				searchBox.setVisible(false);
				searchBox.setText("");
				sortButton.setVisible(true);
		        searchButton.setVisible(false);
		        clearButton.setVisible(false);

				//Add rows based on arrayOfWebsites
				addRowsToTable();
				//Populate JList based on arrayOfWebsites
				populateJList();
				//Enabled save button
				saveButton.setEnabled(true);
    		}
        });

        fileMenu.add(openMenuItem);

//----------------------Window-----------------------------

        windowMenu = new JMenu("Window");
        menuBar.add(windowMenu);

        //Quit
        JMenuItem quitMenuItem = new JMenuItem("Quit");
        quitMenuItem.addMouseListener(new MouseAdapter() {
    		public void mousePressed(MouseEvent e) {
    			JOptionPane.showMessageDialog(null, "The program has exited",
            			"Websites (Justin Kirk)",
            			JOptionPane.INFORMATION_MESSAGE);
            	//Exit
                System.exit(0);
    		}
        });
        windowMenu.add(quitMenuItem);
        //Add menuBar to GUI
        setJMenuBar(menuBar);

//------------------JTable-----------------------------------

        //Column Names for JTable
        String[] columnNames = {
        	"Classification",
            "Web Address",
            "Name",
            "Content",
            "Purpose/Agency",
            "Membership"};

        //Empty data for JTable
    	Object[][] data = {
    	{"", "", "", "", "", ""}
    	};
        //Base model on columnNames and data
		model = new DefaultTableModel(data, columnNames);
		//Set table to a new JTable based on the model
		table = new JTable(model);
		//Table is 500 long and 180 wide
		table.setPreferredScrollableViewportSize(new Dimension(500, 180));
		//Fill the scrollPane
		table.setFillsViewportHeight(true);
		//Select one row at a time
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		//When resizing a column, resize others
		table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		//New list selection model
		ListSelectionModel rowSM = table.getSelectionModel();
		rowSM.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				//Ignore extra messages.
				if (e.getValueIsAdjusting()) return;

				ListSelectionModel lsm = (ListSelectionModel)e.getSource();
				//If a selection is made call updateLabels
				if (!lsm.isSelectionEmpty()) {
					updateMain();
				}
			} //end valueChanged
		});
		//Put the JTable on a ScrollPane
		JScrollPane tablescrollPane = new JScrollPane(table);

//-----------------------------JList-------------------------

		//ArrayList of the website names as Strings
		websiteNamesArray = new ArrayList<String>();

		//Create the list and put it in a scroll pane
		websiteNamesJList = new JList<Object>(websiteNamesArray.toArray());

		//Single select items
		websiteNamesJList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		websiteNamesJList.setSelectedIndex(0);

		//Center text of items in JList
		DefaultListCellRenderer renderer =  (DefaultListCellRenderer)websiteNamesJList.getCellRenderer();
		renderer.setHorizontalAlignment(JLabel.CENTER);

		//New list selection model
		ListSelectionModel listItemSM = websiteNamesJList.getSelectionModel();
		listItemSM.addListSelectionListener(new ListSelectionListener() {
		public void valueChanged(ListSelectionEvent e) {
			//Ignore extra messages.
			if (e.getValueIsAdjusting()) return;

			ListSelectionModel lsm = (ListSelectionModel)e.getSource();
			if (!lsm.isSelectionEmpty()) {
				//Select the corresponding row in the JTable
				selectRowBasedOnJList();
				//Update the main components on the maid tab
				updateMain();
			}
		}
		});
		//Put the JList in a scrollPane
		JScrollPane listScrollPane = new JScrollPane(websiteNamesJList);

//--------------Add components to JPanels-----------------------

		//Add sortSearch controls
		sortSearch.add(searchBox);
		sortSearch.add(sortButton);
		sortSearch.add(searchButton);
		sortSearch.add(clearButton);

        //Add action buttons
        actions.add(saveButton);
        actions.add(quitButton);

        //Add text labels
        // Text.add(scrollPane);
        Text.add(A_classificationLBL);
    	Text.add(B_classificationLBL);
        Text.add(A_nameLBL);
    	Text.add(B_nameLBL);
    	Text.add(A_URLLBL);
    	Text.add(B_URLLBL);
    	Text.add(A_contentLBL);
    	Text.add(B_contentLBL);
    	Text.add(A_purposeLBL);
    	Text.add(B_purposeLBL);
    	Text.add(A_AccessLBL);
    	Text.add(B_AccessLBL);

        center.add(tablescrollPane);

        //Add Image to imagewebsite
        websiteImagePanel.add(websiteImage);

        //Add center panels
        north.add(websiteImagePanel);
        north.add(Text);

//---------------------Tabs---------------------------------

        tabbedPane = new JTabbedPane();

//-----------------Main Tab---------------------------------

        ImageIcon mainTabIcon = new ImageIcon("Images/main.png");
        JPanel mainTabPanel = new JPanel(new BorderLayout());
        mainTabPanel.add(north, BorderLayout.NORTH);
        mainTabPanel.add(center, BorderLayout.CENTER);

        tabbedPane.addTab("Main", mainTabIcon, mainTabPanel,
                "Main information about all websites");

//-----------------Search Tab---------------------------------

        ImageIcon searchTabIcon = new ImageIcon("Images/search.jpg");
        JPanel searchTabPanel = new JPanel(new BorderLayout());
        searchTabPanel.add(sortSearch, BorderLayout.NORTH);
        searchTabPanel.add(listScrollPane, BorderLayout.CENTER);

        tabbedPane.addTab("Search", searchTabIcon, searchTabPanel,
                "Search for a website");

        //Add the tabbed pane to this panel.
        pane.add(tabbedPane, BorderLayout.NORTH);
        pane.add(actions, BorderLayout.SOUTH);

//--------------Add ActionListeners--------------------------------

      //Quit button
        quitButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
            	JOptionPane.showMessageDialog(null, "The program has exited",
            			"Websites (Justin Kirk)",
            			JOptionPane.INFORMATION_MESSAGE);
            	//Exit
                System.exit(0);
            } // End actionPerformed
        }); // End addActionListener

        //Save button
        saveButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
            	//Save arrayOfWebsites to a binary file
            	Program4Driver.saveToBinaryFile();
            } // End actionPerformed
        }); // End addActionListener

      //search button
        searchButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
            	searchWebsiteNames();
            } // End actionPerformed
        }); // End addActionListener

        //search button
        searchBox.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
            	searchWebsiteNames();
            } // End actionPerformed
        }); // End addActionListener

      //websiteIcon button
        websiteImage.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
            	//Open website based on its URL/WebAddress
            	openWebsite();
            } // End actionPerformed
        }); // End addActionListener

      //sort button
        sortButton.addActionListener(new ActionListener(){
            @SuppressWarnings("unchecked")
			public void actionPerformed(ActionEvent e){
            	sortButton.setVisible(false);
            	searchButton.setVisible(true);
            	clearButton.setVisible(true);
            	searchBox.setVisible(true);
            	//Sort arrayOfWebsites
            	Program4Driver.sort(Program4Driver.arrayOfWebsites);
            	//Add rows to table based the now sorted arrayOfWebsites
            	addRowsToTable();
            	//Get all website names that are now sorted
            	populateJList();
            } // End actionPerformed
        }); // End addActionListener

      //clear button
        clearButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
            	//Just get all website names and clear searcBox
            	searchBox.setText("");
            	//Get all website names
            	populateJList();
            } // End actionPerformed
        }); // End addActionListener

    } // addComponentsToPane

//----------------------Main GUI Methods----------------------------------------------

   // Setup a new GUI frame
	static void createAndShowGUI() {
        //Create and set up a new GUI
        GUI frame = new GUI("Websites (Justin Kirk)");
        //Edit on close
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Setup list of images for frame's icons
        final ArrayList<Image> icons = new ArrayList<Image>();
        icons.add(new ImageIcon("Images/icon1616.png").getImage());
        icons.add(new ImageIcon("Images/icon3232.png").getImage());
        icons.add(new ImageIcon("Images/icon128128.png").getImage());

        //Add Icons to frame
        frame.setIconImages(icons);
        //Set location by platform
        frame.setLocationByPlatform(true);
        //Set up the content pane.
        frame.addComponentsToPane(frame.getContentPane());
        //Display the window.
        frame.pack();

        //Show the GUI
        frame.setVisible(true);

    } // createAndShowGUI

	//Set Textfields based on the table and update the website logo
	private static void updateMain()
	{
		String item = "";
		try {
			item = (String) table.getModel().getValueAt(table.getSelectedRow(), 0);
			B_classificationLBL.setText(item);
			item = (String) table.getModel().getValueAt(table.getSelectedRow(), 1);
			B_URLLBL.setText(item);
			item = (String) table.getModel().getValueAt(table.getSelectedRow(), 2);
			B_nameLBL.setText(item);

			item = (String) table.getModel().getValueAt(table.getSelectedRow(), 3);
			B_contentLBL.setText(item);
			item = (String) table.getModel().getValueAt(table.getSelectedRow(), 4);
			B_purposeLBL.setText(item);
			item = (String) table.getModel().getValueAt(table.getSelectedRow(), 5);
			B_AccessLBL.setText(item);

			B_classificationLBL.setCaretPosition(0);
	    	B_nameLBL.setCaretPosition(0);
	    	B_URLLBL.setCaretPosition(0);
	    	B_contentLBL.setCaretPosition(0);
	    	B_purposeLBL.setCaretPosition(0);
	    	B_AccessLBL.setCaretPosition(0);

	    	String imageLocation = Program4Driver.arrayOfWebsites.get(table.getSelectedRow()).getWebsiteLogo();
	    	websiteImage.setIcon(new ImageIcon(imageLocation));
		}
		catch (Exception ex)
		{
			Program4Driver.error("Selection Error");
		}

	} // updateLabels

	//Add a new row to the table based on the arrayOfWebsites
	private static void addRowsToTable()
	{
		MediaStreamingWebsite streamingWS;
		EducationalWebsite educationalWS;
		GovernmentWebsite governmentWS;

		//Removes all rows
		model.setNumRows(0);

		for (int i = 0; i < Program4Driver.arrayOfWebsites.size(); i ++)
		{
			//Use the get methods of MediaStreamingWebsite to create an array of data
			if(Program4Driver.arrayOfWebsites.get(i) instanceof MediaStreamingWebsite)
			{
				streamingWS = (MediaStreamingWebsite) Program4Driver.arrayOfWebsites.get(i);
				Object[] data = {getClassification(streamingWS.getWebAddress().getTopLevelDomain()),
								 streamingWS.getWebAddress().toString(),
								 streamingWS.getWebsiteName(),
								 streamingWS.getMediaContent(),
								 "Stream Content",
								 streamingWS.getSubscription()};
				model.addRow(data);
			} // end if

			//Use the get methods of EducationalWebsite to create an array of data
			else if(Program4Driver.arrayOfWebsites.get(i) instanceof EducationalWebsite)
			{
				educationalWS = (EducationalWebsite) Program4Driver.arrayOfWebsites.get(i);
				Object[] data = {getClassification(educationalWS.getWebAddress().getTopLevelDomain()),
								 educationalWS.getWebAddress().toString(),
								 educationalWS.getWebsiteName(),
								 educationalWS.getEducationalContent(),
								 educationalWS.getPurpose(),
								 "N/A"};
				model.addRow(data);
			} // end else if

			//Use the get methods of GovernmentWebsite to create an array of data
			else if(Program4Driver.arrayOfWebsites.get(i) instanceof GovernmentWebsite)
			{
				governmentWS = (GovernmentWebsite) Program4Driver.arrayOfWebsites.get(i);
				Object[] data = {getClassification(governmentWS.getWebAddress().getTopLevelDomain()),
								governmentWS.getWebAddress().toString(),
								governmentWS.getWebsiteName(),
								governmentWS.getInformationService(),
								governmentWS.getAgency(),
								"N/A"};
				model.addRow(data);
			} // end else if
		} // end for
	} // addRowsToTable

	//Return the descriptive word for the given topLevelDomain
	private static String getClassification(String topLevelDomain)
	{
		if(topLevelDomain.equals("edu"))
		{
			return "Educational";
		}
		else if(topLevelDomain.equals("gov"))
		{
			return "Government";
		}
		else
		{
			return "Media Streaming";
		}
	}

	//When the website logo is clicked, open the website
	//corresponding to the selected row of the JTables' URL
	private static void openWebsite()
	{
		try {
			//Get the URL using B_URLLBL's text
		     String url ="http://" + B_URLLBL.getText();

		     //Get the Desktop's browser
		     Desktop dt = Desktop.getDesktop();
		     // Create a new URL
		     URI uri = new URI(url);
		     //Open the URL in the user's browser
		     dt.browse(uri.resolve(uri));
		}
		catch (Exception ex)
		{
			Program4Driver.error("Website Not Opened");
		}

	} // openWebsite

	 //Select the row in the JTable that matches the selected
	//row in the JList based on the website name
	 private void selectRowBasedOnJList() {

		    String name = (String) websiteNamesJList.getSelectedValue();
			for (int i = 0; i < table.getRowCount(); i ++)
			{
				//The third column of the JList is the website name
				if (((String) table.getModel().getValueAt(i, 2)).equals(name))
				{
					table.clearSelection();
					//Select that one row that matches
					table.setRowSelectionInterval(i, i);
					//Set the tabbedPane to Main
					tabbedPane.setSelectedIndex(0);
					break;
				} // end if
			} // end for
		} // selectRowBasedOnSearch

	 //Clear and add rows to arrayOfWebsiteNames based on the arrayOfWebsites
	 //Use this arrayOfWebsiteNames to populate the JList
	 private static void populateJList()
	 {
		 websiteNamesArray.clear();
		 for (int i = 0; i < Program4Driver.arrayOfWebsites.size(); i ++)
		 {
			 //Create an array of website names
			 websiteNamesArray.add(Program4Driver.arrayOfWebsites.get(i).getWebsiteName());
		 } // end for

		 websiteNamesJList.setListData(websiteNamesArray.toArray());

	 } // populateJList

	 //Remove rows of JList that are not equal to the search key
	 //based on the index of the match
	 private static void filterJList(int nameIndex)
	 {
		String match =  websiteNamesArray.get(nameIndex);
		boolean isNotMatch = false;
		do {
			isNotMatch = false;
			 for (int i = 0; i < websiteNamesArray.size(); i ++)
			 {
				if(match != websiteNamesArray.get(i))
				{
					//Not a match so remove
					websiteNamesArray.remove(i);
					isNotMatch = true;
				}
			 } // end for
		}
		while(isNotMatch);

		websiteNamesJList.setListData(websiteNamesArray.toArray());

	 } // filterJList

	 //Determine whether to search or not
	 private static void searchWebsiteNames()
	 {
		 if(searchBox.getText().equals(""))
     	{
     		//Does the same thing the clearButton
     		//Don't search but get all names
     		populateJList();
     	} // end if
     	else
     	{
     		//Get all names
   			populateJList();
   			//Search for a website in websiteNamesArray using searchBox's text
     		int searchReturn = Program4Driver.recursiveBinarySearch(websiteNamesArray, searchBox.getText());
     		//A number that is -1 or less means the search failed
     		if(searchReturn > -1)
     		{
     			//Filter the JList based on the search
     			filterJList(searchReturn);
     		} // end if
     		//Search failed
     		else
     		{
     			//Complain
     			Program4Driver.error("Website Not Found");
     		} // end else
     	} // end else
	 } // searchWebsiteNames

} // End GUI


text:
package org.mrgeo.data.image;

import org.junit.Ignore;

@SuppressWarnings("static-method")
@Ignore
public class MrsImageWriterHDFSTest
{
//  private static String outputDir;
//  private Raster raster;
//
//  @BeforeClass
//  public static void init() throws IOException
//  {
//    outputDir = TestUtils.composeOutputDir(MrsImageWriterHDFSTest.class);
//  }
//
//  @Test
//  @Category(UnitTest.class)
//  public void appendRaster()
//  {
//    final MrsImageWriter writer = MrsImageWriter.getHdfsSequenceInstance(outputDir);
//    writer.append(new TileIdWritable(0), raster);
//    writer.close();
//  }
//
//  @Test(expected = NullPointerException.class)
//  @Category(UnitTest.class)
//  public void close()
//  {
//    final MrsImageWriter writer = MrsImageWriter.getHdfsSequenceInstance(outputDir);
//    writer.close();
//    // try to write to the closed raster, should be a NullPointerException
//    writer.append(new TileIdWritable(0), raster);
//  }
//
//  @Test
//  @Category(UnitTest.class)
//  public void getHdfsInstance()
//  {
//    final MrsImageWriter writer = MrsImageWriter.getHdfsSequenceInstance(outputDir);
//
//    Assert
//      .assertEquals("Bad writer class", "HdfsSequenceWriter", writer.getClass().getSimpleName());
//    writer.close();
//  }
//
//  @Test
//  @Category(UnitTest.class)
//  public void getImageName()
//  {
//    final MrsImageWriter writer = MrsImageWriter.getHdfsSequenceInstance(outputDir);
//    Assert.assertEquals("Bad image name", outputDir, writer.getImageName());
//    writer.close();
//  }
//
//  @Before
//  public void setUp()
//  {
//    final BufferedImage image = new BufferedImage(512, 512, ColorSpace.TYPE_RGB);
//    raster = image.getData();
//  }
//
//  @After
//  public void tearDown() throws Exception
//  {
//  }

}

redpajama_set_name: RedPajamaGithub


text:
module Markdownplus
  class HandlerRegistry
    @@registry = {}

    def self.handler_instance(name)
      handler_class(name).new if handler_class(name)
    end

    def self.handler_class(name)
      @@registry[name]
    end

    def self.register(name, handler)
      @@registry[name] = handler
    end

    def self.available_handlers
      @@registry.keys
    end
  end
end


text:
importScripts('./public/serviceworker-cache-polyfill.js');

// Here comes the install event!
// This only happens once, when the browser sees this
// version of the ServiceWorker for the first time.
self.addEventListener('install', function(event) {

  if (self.skipWaiting)
    self.skipWaiting()

  // We pass a promise to event.waitUntil to signal how
  // long install takes, and if it failed
  event.waitUntil(
    // We open a cache…
    caches.open('simple-sw-v1').then(function(cache) {

      cache.addAll([
        './public/ambience.ogg',
        './public/beep.ogg',
        './public/key1.ogg',
        './public/key2.ogg',
        './public/key3.ogg',
        './public/key4.ogg',
        './public/space.ogg',
        './public/DejaVuSansMono.ttf'
      ]);

      // And add resources to it
      return cache.addAll([
        './',
        './manifest.json',
        './public/styles.css',
        './public/all.js'
      ]);
    })
  );
});

// The fetch event happens for the page request with the
// ServiceWorker's scope, and any request made within that
// page
self.addEventListener('fetch', function(event) {

  var response = fetch(event.request).then(function (response) {
    // We return the original response for
    // anything other then a local file
    var isLocalFile = new RegExp( event.request.referrer + "(|.+\\..+)$" )
    if ( !isLocalFile.test( response.url ))
      return response
    // Then replace the cached response
    // with the newly recieved
    caches.open('simple-sw-v1').then(function(cache) {
      cache.put( event.request.url, response )
    })
    // And keep the response copy for
    // case when the cache is empty
    return response.clone()
  }).catch(function(){
    // Do smth when offline
  })

  // Calling event.respondWith means we're in charge
  // of providing the response. We pass in a promise
  // that resolves with a response object
  event.respondWith(
    // First we look for something in the caches that
    // matches the request
    caches.match(event.request).then(function(cached) {
      // Then return the cached response or
      // if empty, the fresh response
      return cached || response
    })
  );
});


text:
/*	$NetBSD: atareg.h,v 1.43 2013/10/30 15:37:49 drochner Exp $	*/

/*
 * Copyright (c) 1998, 2001 Manuel Bouyer.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*-
 * Copyright (c) 1991 The Regents of the University of California.
 * All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * William Jolitz.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)wdreg.h	7.1 (Berkeley) 5/9/91
 */

#ifndef _DEV_ATA_ATAREG_H_
#define	_DEV_ATA_ATAREG_H_

/*
 * ATA Task File register definitions.
 */

/* Status bits. */
#define	WDCS_BSY		0x80    /* busy */
#define	WDCS_DRDY		0x40    /* drive ready */
#define	WDCS_DWF		0x20    /* drive write fault */
#define	WDCS_DSC		0x10    /* drive seek complete */
#define	WDCS_DRQ		0x08    /* data request */
#define	WDCS_CORR		0x04    /* corrected data */
#define	WDCS_IDX		0x02    /* index */
#define	WDCS_ERR		0x01    /* error */
#define	WDCS_BITS \
    "\020\010bsy\007drdy\006dwf\005dsc\004drq\003corr\002idx\001err"

/* Error bits. */
#define	WDCE_BBK		0x80	/* bad block detected */
#define	WDCE_CRC		0x80	/* CRC error (Ultra-DMA only) */
#define	WDCE_UNC		0x40	/* uncorrectable data error */
#define	WDCE_MC			0x20	/* media changed */
#define	WDCE_IDNF		0x10	/* id not found */
#define	WDCE_MCR		0x08	/* media change requested */
#define	WDCE_ABRT		0x04	/* aborted command */
#define	WDCE_TK0NF		0x02	/* track 0 not found */
#define	WDCE_AMNF		0x01	/* address mark not found */

/* Commands for Disk Controller. */
#define	WDCC_NOP		0x00	/* Always fail with "aborted command" */
#define ATA_DATA_SET_MANAGEMENT	0x06
#define	WDCC_RECAL		0x10	/* disk restore code -- resets cntlr */

#define	WDCC_READ		0x20	/* disk read code */
#define	WDCC_WRITE		0x30	/* disk write code */
#define	 WDCC__LONG		 0x02	/* modifier -- access ecc bytes */
#define	 WDCC__NORETRY		 0x01	/* modifier -- no retrys */

#define	WDCC_FORMAT		0x50	/* disk format code */
#define	WDCC_DIAGNOSE		0x90	/* controller diagnostic */
#define	WDCC_IDP		0x91	/* initialize drive parameters */

#define	WDCC_SMART		0xb0	/* Self Mon, Analysis, Reporting Tech */

#define	WDCC_READMULTI		0xc4	/* read multiple */
#define	WDCC_WRITEMULTI		0xc5	/* write multiple */
#define	WDCC_SETMULTI		0xc6	/* set multiple mode */

#define	WDCC_READDMA		0xc8	/* read with DMA */
#define	WDCC_WRITEDMA		0xca	/* write with DMA */

#define	WDCC_ACKMC		0xdb	/* acknowledge media change */
#define	WDCC_LOCK		0xde	/* lock drawer */
#define	WDCC_UNLOCK		0xdf	/* unlock drawer */

#define	WDCC_FLUSHCACHE		0xe7	/* Flush cache */
#define	WDCC_FLUSHCACHE_EXT	0xea	/* Flush cache ext */
#define	WDCC_IDENTIFY		0xec	/* read parameters from controller */
#define	SET_FEATURES		0xef	/* set features */

#define	WDCC_IDLE		0xe3	/* set idle timer & enter idle mode */
#define	WDCC_IDLE_IMMED		0xe1	/* enter idle mode */
#define	WDCC_SLEEP		0xe6	/* enter sleep mode */
#define	WDCC_STANDBY		0xe2	/* set standby timer & enter standby */
#define	WDCC_STANDBY_IMMED	0xe0	/* enter standby mode */
#define	WDCC_CHECK_PWR		0xe5	/* check power mode */

/* Security feature set */
#define	WDCC_SECURITY_SET_PASSWORD	0xf1
#define	WDCC_SECURITY_UNLOCK		0xf2
#define	WDCC_SECURITY_ERASE_PREPARE	0xf3
#define	WDCC_SECURITY_ERASE_UNIT	0xf4
#define	WDCC_SECURITY_FREEZE		0xf5
#define	WDCC_SECURITY_DISABLE_PASSWORD	0xf6

/* Big Drive support */
#define	WDCC_READ_EXT		0x24	/* read 48-bit addressing */
#define	WDCC_WRITE_EXT		0x34	/* write 48-bit addressing */

#define	WDCC_READMULTI_EXT	0x29	/* read multiple 48-bit addressing */
#define	WDCC_WRITEMULTI_EXT	0x39	/* write multiple 48-bit addressing */

#define	WDCC_READDMA_EXT	0x25	/* read 48-bit addressing with DMA */
#define	WDCC_WRITEDMA_EXT	0x35	/* write 48-bit addressing with DMA */

#if defined(_KERNEL) || defined(_STANDALONE)
#include <dev/ata/ataconf.h>

/* Convert a 32-bit command to a 48-bit command. */
static __inline int
atacmd_to48(int cmd32)
{
	switch (cmd32) {
	case WDCC_READ:
		return WDCC_READ_EXT;
	case WDCC_WRITE:
		return WDCC_WRITE_EXT;
	case WDCC_READMULTI:
		return WDCC_READMULTI_EXT;
	case WDCC_WRITEMULTI:
		return WDCC_WRITEMULTI_EXT;
#if NATA_DMA
	case WDCC_READDMA:
		return WDCC_READDMA_EXT;
	case WDCC_WRITEDMA:
		return WDCC_WRITEDMA_EXT;
#endif
	default:
		panic("atacmd_to48: illegal 32-bit command: %d", cmd32);
		/* NOTREACHED */
	}
}
#endif /* _KERNEL || _STANDALONE */

/* Native SATA command queueing */
#define	WDCC_READ_FPDMA_QUEUED	0x60	/* SATA native queued read (48bit) */
#define	WDCC_WRITE_FPDMA_QUEUED	0x61	/* SATA native queued write (48bit) */

#ifdef _KERNEL
/* Convert a 32-bit command to a Native SATA Queued command. */
static __inline int
atacmd_tostatq(int cmd32)
{
	switch (cmd32) {
	case WDCC_READDMA:
		return WDCC_READ_FPDMA_QUEUED;
	case WDCC_WRITEDMA:
		return WDCC_WRITE_FPDMA_QUEUED;
	default:
		panic("atacmd_tosataq: illegal 32-bit command: %d", cmd32);
		/* NOTREACHED */
	}
}
#endif /* _KERNEL */

/* Subcommands for SET_FEATURES (features register) */
#define	WDSF_8BIT_PIO_EN	0x01
#define	WDSF_WRITE_CACHE_EN	0x02
#define	WDSF_SET_MODE		0x03
#define	WDSF_REASSIGN_EN	0x04
#define	WDSF_APM_EN		0x05
#define	WDSF_PUIS_EN		0x06
#define	WDSF_PUIS_SPIN_UP	0x07
#define	WDSF_SATA_EN		0x10
#define	WDSF_RETRY_DS		0x33
#define	WDSF_AAM_EN		0x42
#define	WDSF_SET_CACHE_SGMT	0x54
#define	WDSF_READAHEAD_DS	0x55
#define	WDSF_POD_DS		0x66
#define	WDSF_ECC_DS		0x77
#define	WDSF_WRITE_CACHE_DS	0x82
#define	WDSF_REASSIGN_DS	0x84
#define	WDSF_APM_DS		0x85
#define	WDSF_PUIS_DS		0x86
#define	WDSF_ECC_EN		0x88
#define	WDSF_SATA_DS		0x90
#define	WDSF_RETRY_EN		0x99
#define	WDSF_SET_CURRENT	0x9a
#define	WDSF_READAHEAD_EN	0xaa
#define	WDSF_PREFETCH_SET	0xab
#define	WDSF_AAM_DS		0xc2
#define	WDSF_POD_EN		0xcc

/* Subcommands for WDSF_SATA (count register) */
#define	WDSF_SATA_NONZERO_OFFSETS	0x01
#define	WDSF_SATA_DMA_SETUP_AUTO	0x02
#define	WDSF_SATA_DRIVE_PWR_MGMT	0x03
#define	WDSF_SATA_IN_ORDER_DATA		0x04
#define	WDSF_SATA_ASYNC_NOTIFY		0x05
#define	WDSF_SATA_SW_STTNGS_PRS		0x06

/* Subcommands for SMART (features register) */
#define	WDSM_RD_DATA		0xd0
#define	WDSM_RD_THRESHOLDS	0xd1
#define	WDSM_ATTR_AUTOSAVE_EN	0xd2
#define	WDSM_SAVE_ATTR		0xd3
#define	WDSM_EXEC_OFFL_IMM	0xd4
#define	WDSM_RD_LOG		0xd5
#define	WDSM_ENABLE_OPS		0xd8
#define	WDSM_DISABLE_OPS	0xd9
#define	WDSM_STATUS		0xda

#define WDSMART_CYL		0xc24f

/* parameters uploaded to device/heads register */
#define	WDSD_IBM		0xa0	/* forced to 512 byte sector, ecc */
#define	WDSD_CHS		0x00	/* cylinder/head/sector addressing */
#define	WDSD_LBA		0x40	/* logical block addressing */

/* Commands for ATAPI devices */
#define	ATAPI_CHECK_POWER_MODE	0xe5
#define	ATAPI_EXEC_DRIVE_DIAGS	0x90
#define	ATAPI_IDLE_IMMEDIATE	0xe1
#define	ATAPI_NOP		0x00
#define	ATAPI_PKT_CMD		0xa0
#define	ATAPI_IDENTIFY_DEVICE	0xa1
#define	ATAPI_SOFT_RESET	0x08
#define	ATAPI_SLEEP		0xe6
#define	ATAPI_STANDBY_IMMEDIATE	0xe0

/* Bytes used by ATAPI_PACKET_COMMAND (feature register) */
#define	ATAPI_PKT_CMD_FTRE_DMA	0x01
#define	ATAPI_PKT_CMD_FTRE_OVL	0x02

/* ireason */
#define	WDCI_CMD		0x01	/* command(1) or data(0) */
#define	WDCI_IN			0x02	/* transfer to(1) or from(0) the host */
#define	WDCI_RELEASE		0x04	/* bus released until completion */

#define	PHASE_CMDOUT		(WDCS_DRQ | WDCI_CMD)
#define	PHASE_DATAIN		(WDCS_DRQ | WDCI_IN)
#define	PHASE_DATAOUT		(WDCS_DRQ)
#define	PHASE_COMPLETED		(WDCI_IN | WDCI_CMD)
#define	PHASE_ABORTED		(0)

/*
 * Drive parameter structure for ATA/ATAPI.
 * Bit fields: WDC_* : common to ATA/ATAPI
 *             ATA_* : ATA only
 *             ATAPI_* : ATAPI only.
 */
struct ataparams {
    /* drive info */
    uint16_t	atap_config;		/* 0: general configuration */
#define WDC_CFG_CFA_MAGIC	0x848a
#define WDC_CFG_ATAPI    	0x8000
#define	ATA_CFG_REMOVABLE	0x0080
#define	ATA_CFG_FIXED		0x0040
#define ATAPI_CFG_TYPE_MASK	0x1f00
#define ATAPI_CFG_TYPE(x) (((x) & ATAPI_CFG_TYPE_MASK) >> 8)
#define	ATAPI_CFG_REMOV		0x0080
#define ATAPI_CFG_DRQ_MASK	0x0060
#define ATAPI_CFG_STD_DRQ	0x0000
#define ATAPI_CFG_IRQ_DRQ	0x0020
#define ATAPI_CFG_ACCEL_DRQ	0x0040
#define ATAPI_CFG_CMD_MASK	0x0003
#define ATAPI_CFG_CMD_12	0x0000
#define ATAPI_CFG_CMD_16	0x0001
/* words 1-9 are ATA only */
    uint16_t	atap_cylinders;		/* 1: # of non-removable cylinders */
    uint16_t	__reserved1;
    uint16_t	atap_heads;		/* 3: # of heads */
    uint16_t	__retired1[2];		/* 4-5: # of unform. bytes/track */
    uint16_t	atap_sectors;		/* 6: # of sectors */
    uint16_t	__retired2[3];

    uint8_t	atap_serial[20];	/* 10-19: serial number */
    uint16_t	__retired3[2];
    uint16_t	__obsolete1;
    uint8_t	atap_revision[8];	/* 23-26: firmware revision */
    uint8_t	atap_model[40];		/* 27-46: model number */
    uint16_t	atap_multi;		/* 47: maximum sectors per irq (ATA) */
    uint16_t	__reserved2;
    uint16_t	atap_capabilities1;	/* 49: capability flags */
#define WDC_CAP_IORDY	0x0800
#define WDC_CAP_IORDY_DSBL 0x0400
#define	WDC_CAP_LBA	0x0200
#define	WDC_CAP_DMA	0x0100
#define ATA_CAP_STBY	0x2000
#define ATAPI_CAP_INTERL_DMA	0x8000
#define ATAPI_CAP_CMD_QUEUE	0x4000
#define	ATAPI_CAP_OVERLP	0X2000
#define ATAPI_CAP_ATA_RST	0x1000
    uint16_t	atap_capabilities2;	/* 50: capability flags (ATA) */
#if BYTE_ORDER == LITTLE_ENDIAN
    uint8_t	__junk2;
    uint8_t	atap_oldpiotiming;	/* 51: old PIO timing mode */
    uint8_t	__junk3;
    uint8_t	atap_olddmatiming;	/* 52: old DMA timing mode (ATA) */
#else
    uint8_t	atap_oldpiotiming;	/* 51: old PIO timing mode */
    uint8_t	__junk2;
    uint8_t	atap_olddmatiming;	/* 52: old DMA timing mode (ATA) */
    uint8_t	__junk3;
#endif
    uint16_t	atap_extensions;	/* 53: extensions supported */
#define WDC_EXT_UDMA_MODES	0x0004
#define WDC_EXT_MODES		0x0002
#define WDC_EXT_GEOM		0x0001
/* words 54-62 are ATA only */
    uint16_t	atap_curcylinders;	/* 54: current logical cylinders */
    uint16_t	atap_curheads;		/* 55: current logical heads */
    uint16_t	atap_cursectors;	/* 56: current logical sectors/tracks */
    uint16_t	atap_curcapacity[2];	/* 57-58: current capacity */
    uint16_t	atap_curmulti;		/* 59: current multi-sector setting */
#define WDC_MULTI_VALID 0x0100
#define WDC_MULTI_MASK  0x00ff
    uint16_t	atap_capacity[2];  	/* 60-61: total capacity (LBA only) */
    uint16_t	__retired4;
#if BYTE_ORDER == LITTLE_ENDIAN
    uint8_t	atap_dmamode_supp; 	/* 63: multiword DMA mode supported */
    uint8_t	atap_dmamode_act; 	/*     multiword DMA mode active */
    uint8_t	atap_piomode_supp;	/* 64: PIO mode supported */
    uint8_t	__junk4;
#else
    uint8_t	atap_dmamode_act; 	/*     multiword DMA mode active */
    uint8_t	atap_dmamode_supp; 	/* 63: multiword DMA mode supported */
    uint8_t	__junk4;
    uint8_t	atap_piomode_supp;	/* 64: PIO mode supported */
#endif
    uint16_t	atap_dmatiming_mimi;	/* 65: minimum DMA cycle time */
    uint16_t	atap_dmatiming_recom;	/* 66: recommended DMA cycle time */
    uint16_t	atap_piotiming;		/* 67: mini PIO cycle time without FC */
    uint16_t	atap_piotiming_iordy;	/* 68: mini PIO cycle time with IORDY FC */
    uint16_t	__reserved3[2];
/* words 71-72 are ATAPI only */
    uint16_t	atap_pkt_br;		/* 71: time (ns) to bus release */
    uint16_t	atap_pkt_bsyclr;	/* 72: tme to clear BSY after service */
    uint16_t	__reserved4[2];
    uint16_t	atap_queuedepth;	/* 75: */
#define WDC_QUEUE_DEPTH_MASK 0x1F
    uint16_t	atap_sata_caps;		/* 76: */
#define SATA_SIGNAL_GEN1	0x02
#define SATA_SIGNAL_GEN2	0x04
#define SATA_SIGNAL_GEN3	0x08
#define SATA_NATIVE_CMDQ	0x0100
#define SATA_HOST_PWR_MGMT	0x0200
#define SATA_PHY_EVNT_CNT	0x0400
    uint16_t	atap_sata_reserved;	/* 77: */
    uint16_t	atap_sata_features_supp; /* 78: */
#define SATA_NONZERO_OFFSETS	0x02
#define SATA_DMA_SETUP_AUTO	0x04
#define SATA_DRIVE_PWR_MGMT	0x08
#define SATA_IN_ORDER_DATA	0x10
#define SATA_SW_STTNGS_PRS	0x40
    uint16_t	atap_sata_features_en;	/* 79: */
    uint16_t	atap_ata_major;  	/* 80: Major version number */
#define	WDC_VER_ATA1	0x0002
#define	WDC_VER_ATA2	0x0004
#define	WDC_VER_ATA3	0x0008
#define	WDC_VER_ATA4	0x0010
#define	WDC_VER_ATA5	0x0020
#define	WDC_VER_ATA6	0x0040
#define	WDC_VER_ATA7	0x0080
#define	WDC_VER_ATA8	0x0100
    uint16_t	atap_ata_minor;		/* 81: Minor version number */
    uint16_t	atap_cmd_set1;		/* 82: command set supported */
#define	WDC_CMD1_NOP	0x4000		/*	NOP */
#define	WDC_CMD1_RB	0x2000		/*	READ BUFFER */
#define	WDC_CMD1_WB	0x1000		/*	WRITE BUFFER */
/*			0x0800			Obsolete */
#define	WDC_CMD1_HPA	0x0400		/*	Host Protected Area */
#define	WDC_CMD1_DVRST	0x0200		/*	DEVICE RESET */
#define	WDC_CMD1_SRV	0x0100		/*	SERVICE */
#define	WDC_CMD1_RLSE	0x0080		/*	release interrupt */
#define	WDC_CMD1_AHEAD	0x0040		/*	look-ahead */
#define	WDC_CMD1_CACHE	0x0020		/*	write cache */
#define	WDC_CMD1_PKT	0x0010		/*	PACKET */
#define	WDC_CMD1_PM	0x0008		/*	Power Management */
#define	WDC_CMD1_REMOV	0x0004		/*	Removable Media */
#define	WDC_CMD1_SEC	0x0002		/*	Security Mode */
#define	WDC_CMD1_SMART	0x0001		/*	SMART */
    uint16_t	atap_cmd_set2;		/* 83: command set supported */
#define	ATA_CMD2_FCE	0x2000		/*	FLUSH CACHE EXT */
#define	WDC_CMD2_FC	0x1000		/*	FLUSH CACHE */
#define	WDC_CMD2_DCO	0x0800		/*	Device Configuration Overlay */
#define	ATA_CMD2_LBA48	0x0400		/*	48-bit Address */
#define	WDC_CMD2_AAM	0x0200		/*	Automatic Acoustic Management */
#define	WDC_CMD2_SM	0x0100		/*	SET MAX security extension */
#define	WDC_CMD2_SFREQ	0x0040		/*	SET FEATURE is required
						to spin-up after power-up */
#define	WDC_CMD2_PUIS	0x0020		/*	Power-Up In Standby */
#define	WDC_CMD2_RMSN	0x0010		/*	Removable Media Status Notify */
#define	ATA_CMD2_APM	0x0008		/*	Advanced Power Management */
#define	ATA_CMD2_CFA	0x0004		/*	CFA */
#define	ATA_CMD2_RWQ	0x0002		/*	READ/WRITE DMA QUEUED */
#define	WDC_CMD2_DM	0x0001		/*	DOWNLOAD MICROCODE */
    uint16_t	atap_cmd_ext;		/* 84: command/features supp. ext. */
#define	ATA_CMDE_TLCONT	0x1000		/*	Time-limited R/W Continuous */
#define	ATA_CMDE_TL	0x0800		/*	Time-limited R/W */
#define	ATA_CMDE_URGW	0x0400		/*	URG for WRITE STREAM DMA/PIO */
#define	ATA_CMDE_URGR	0x0200		/*	URG for READ STREAM DMA/PIO */
#define	ATA_CMDE_WWN	0x0100		/*	World Wide name */
#define	ATA_CMDE_WQFE	0x0080		/*	WRITE DMA QUEUED FUA EXT */
#define	ATA_CMDE_WFE	0x0040		/*	WRITE DMA/MULTIPLE FUA EXT */
#define	ATA_CMDE_GPL	0x0020		/*	General Purpose Logging */
#define	ATA_CMDE_STREAM	0x0010		/*	Streaming */
#define	ATA_CMDE_MCPTC	0x0008		/*	Media Card Pass Through Cmd */
#define	ATA_CMDE_MS	0x0004		/*	Media serial number */
#define	ATA_CMDE_SST	0x0002		/*	SMART self-test */
#define	ATA_CMDE_SEL	0x0001		/*	SMART error logging */
    uint16_t	atap_cmd1_en;		/* 85: cmd/features enabled */
/* bits are the same as atap_cmd_set1 */
    uint16_t	atap_cmd2_en;		/* 86: cmd/features enabled */
/* bits are the same as atap_cmd_set2 */
    uint16_t	atap_cmd_def;		/* 87: cmd/features default */
#if BYTE_ORDER == LITTLE_ENDIAN
    uint8_t	atap_udmamode_supp; 	/* 88: Ultra-DMA mode supported */
    uint8_t	atap_udmamode_act; 	/*     Ultra-DMA mode active */
#else
    uint8_t	atap_udmamode_act; 	/*     Ultra-DMA mode active */
    uint8_t	atap_udmamode_supp; 	/* 88: Ultra-DMA mode supported */
#endif
/* 89-92 are ATA-only */
    uint16_t	atap_seu_time;		/* 89: Sec. Erase Unit compl. time */
    uint16_t	atap_eseu_time;		/* 90: Enhanced SEU compl. time */
    uint16_t	atap_apm_val;		/* 91: current APM value */
    uint16_t	__reserved5[8];		/* 92-99: reserved */
    uint16_t	atap_max_lba[4];	/* 100-103: Max. user LBA addr */
    uint16_t	__reserved6;		/* 104: reserved */
    uint16_t	max_dsm_blocks;		/* 105: DSM (ATA-8/ACS-2) */
    uint16_t	atap_secsz;		/* 106: physical/logical sector size */
#define ATA_SECSZ_VALID_MASK 0xc000
#define ATA_SECSZ_VALID      0x4000
#define ATA_SECSZ_LPS        0x2000	/* long physical sectors */
#define ATA_SECSZ_LLS        0x1000	/* long logical sectors */
#define ATA_SECSZ_LPS_SZMSK  0x000f	/* 2**N logical per physical */
    uint16_t	atap_iso7779_isd;	/* 107: ISO 7779 inter-seek delay */
    uint16_t 	atap_wwn[4];		/* 108-111: World Wide Name */
    uint16_t	__reserved7[5];		/* 112-116 */
    uint16_t	atap_lls_secsz[2];	/* 117-118: long logical sector size */
    uint16_t	__reserved8[8];		/* 119-126 */
    uint16_t	atap_rmsn_supp;		/* 127: remov. media status notif. */
#define WDC_RMSN_SUPP_MASK 0x0003
#define WDC_RMSN_SUPP 0x0001
    uint16_t	atap_sec_st;		/* 128: security status */
#define WDC_SEC_LEV_MAX	0x0100
#define WDC_SEC_ESE_SUPP 0x0020
#define WDC_SEC_EXP	0x0010
#define WDC_SEC_FROZEN	0x0008
#define WDC_SEC_LOCKED	0x0004
#define WDC_SEC_EN	0x0002
#define WDC_SEC_SUPP	0x0001
    uint16_t	__reserved9[31];	/* 129-159: vendor specific */
    uint16_t	atap_cfa_power;		/* 160: CFA powermode */
#define ATA_CFA_MAX_MASK  0x0fff
#define ATA_CFA_MODE1_DIS 0x1000	/* CFA Mode 1 Disabled */
#define ATA_CFA_MODE1_REQ 0x2000	/* CFA Mode 1 Required */
#define ATA_CFA_WORD160   0x8000	/* Word 160 supported */
    uint16_t	__reserved10[8];	/* 161-168: reserved for CFA */
    uint16_t	support_dsm;		/* 169: DSM (ATA-8/ACS-2) */
#define ATA_SUPPORT_DSM_TRIM	0x0001
    uint16_t	__reserved10a[6];	/* 170-175: reserved for CFA */
    uint8_t	atap_media_serial[60];	/* 176-205: media serial number */
    uint16_t	__reserved11[3];	/* 206-208: */
    uint16_t	atap_logical_align;	/* 209: logical/physical alignment */
#define ATA_LA_VALID_MASK 0xc000
#define ATA_LA_VALID      0x4000
#define ATA_LA_MASK       0x3fff	/* offset of sector LBA 0 in PBA 0 */
    uint16_t	__reserved12[45];	/* 210-254: */
    uint16_t	atap_integrity;		/* 255: Integrity word */
#define WDC_INTEGRITY_MAGIC_MASK 0x00ff
#define WDC_INTEGRITY_MAGIC      0x00a5
};

/*
 * If WDSM_ATTR_ADVISORY, device exceeded intended design life period.
 * If not WDSM_ATTR_ADVISORY, imminent data loss predicted.
 */
#define WDSM_ATTR_ADVISORY	1

/*
 * If WDSM_ATTR_COLLECTIVE, attribute only updated in off-line testing.
 * If not WDSM_ATTR_COLLECTIVE, attribute updated also in on-line testing.
 */
#define WDSM_ATTR_COLLECTIVE	2

/*
 * ATA SMART attributes
 */

struct ata_smart_attr {
	uint8_t		id;		/* attribute id number */
	uint16_t	flags;
	uint8_t		value;		/* attribute value */
	uint8_t		worst;
	uint8_t		raw[6];
	uint8_t		reserved;
} __packed;

struct ata_smart_attributes {
	uint16_t	data_structure_revision;
	struct ata_smart_attr attributes[30];
	uint8_t		offline_data_collection_status;
	uint8_t		self_test_exec_status;
	uint16_t	total_time_to_complete_off_line;
	uint8_t		vendor_specific_366;
	uint8_t		offline_data_collection_capability;
	uint16_t	smart_capability;
	uint8_t		errorlog_capability;
	uint8_t		vendor_specific_371;
	uint8_t		short_test_completion_time;
	uint8_t		extend_test_completion_time;
	uint8_t		reserved_374_385[12];
	uint8_t		vendor_specific_386_509[125];
	int8_t		checksum;
} __packed;

struct ata_smart_thresh {
	uint8_t		id;
	uint8_t		value;
	uint8_t		reserved[10];
} __packed;

struct ata_smart_thresholds {
	uint16_t	data_structure_revision;
	struct ata_smart_thresh	thresholds[30];
	uint8_t		reserved[18];
	uint8_t		vendor_specific[131];
	int8_t		checksum;
} __packed;

struct ata_smart_selftest {
	uint8_t		number;
	uint8_t		status;
	uint16_t	time_stamp;
	uint8_t		failure_check_point;
	uint32_t	lba_first_error;
	uint8_t		vendor_specific[15];
} __packed;

struct ata_smart_selftestlog {
	uint16_t	data_structure_revision;
	struct ata_smart_selftest log_entries[21];
	uint8_t		vendorspecific[2];
	uint8_t		mostrecenttest;
	uint8_t		reserved[2];
	uint8_t		checksum;
} __packed;

#endif /* _DEV_ATA_ATAREG_H_ */


text:
export interface UpdateSearchMenuMessage {
  method: 'Nunze_updateSearchMenu';
  name: string;
}

export interface UpdateSearchMenuResponse {
  method: 'Nunze_updateSearchMenu';
  succeed: boolean;
}

export function isUpdateSearchMenuResponse(
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  response: any
): response is UpdateSearchMenuResponse {
  return response.method === 'Nunze_updateSearchMenu';
}


text:
using System.Linq;
using System.Web.Http;
using System.Web.OData;
using System.Web.OData.Routing;
using Microsoft.Web.Http;
using TestRestfulAPI.Infrastructure.Authorization.Attributes;
using TestRestfulAPI.Infrastructure.Controllers;
using TestRestfulAPI.RestApi.odata.v1.Contents.Services;
using TestRestfulAPI.RestApi.odata.v1.Offers.Entities;
using TestRestfulAPI.RestApi.odata.v1.Offers.Services;
using TestRestfulAPI.RestApi.odata.v1.Contents.Entities;
using System;

namespace TestRestfulAPI.RestApi.odata.v1.Contents.Controllers
{
    [ApiVersion("1.0")]
    [ODataRoutePrefix("Contents")]
    [UserHasRole("UserControl")]
    public class ContentController : ResourceODataController, ICrudController<Content>
    {
        private readonly ContentService _contentService = GlobalServices.ContentService;

        // POST: {resource}/Contents()
        [UserHasResourceAccess, UserHasPermission("Write")]
        [EnableQuery, HttpPost, ODataRoute("()")]
        public IHttpActionResult Create([FromBody] Content content)
        {
            this.ParseResource();
            return ODataCreated(this._contentService.Create(this.Resource, content), content.Id);
        }

        // DELETE: {resource}/Contents({id})
        [UserHasResourceAccess, UserHasPermission("Remove")]
        [EnableQuery, HttpDelete, ODataRoute("({id})")]
        public void Delete(int id)
        {
            this.ParseResource();
            this._contentService.Delete(this.Resource, id);
            this.ODataDeleted(); // Set response headers
        }

        // GET: {resource}/Contents()
        [EnableQuery, HttpGet, ODataRoute()]
        public IQueryable<Content> Get()
        {
            this.ParseResource();
            return this._contentService.All(this.Resource);
        }

        // GET: {resource}/Contents({id})
        [UserHasResourceAccess, UserHasPermission("Read")]
        [EnableQuery, HttpGet, ODataRoute("({id})")]
        public Content Get(int id)
        {
            this.ParseResource();
            return this._contentService.Get(this.Resource, id);
        }

        // PATCH: {resource}/Contents({id})
        [UserHasResourceAccess, UserHasPermission("Modify")]
        [EnableQuery, HttpPatch, ODataRoute("({id})")]
        public Content PartialUpdate(int id, [FromBody] Delta<Content> content)
        {
            this.ParseResource();
            return this._contentService.PartialUpdate(this.Resource, id, content);
        }

        // PUT: {resource}/Contents({id})
        [UserHasResourceAccess, UserHasPermission("Modify")]
        [EnableQuery, HttpPut, ODataRoute("({id})")]
        public Content Update(int id, Content content)
        {
            this.ParseResource();
            return this._contentService.Update(this.Resource, content);
        }

        // Put: {resource}/Contents({contentId})
        [UserHasResourceAccess, UserHasPermission("Write")]
        [EnableQuery, HttpPut, ODataRoute("({contentId})/TextItems({textitemId})")]
        public Content AddTextItem(int contentId, int textitemId)
        {
            this.ParseResource();
            return this._contentService.AddTextItem(this.Resource, contentId, textitemId);

        }

        // Put: {resource}/Contents({contentId})
        [UserHasResourceAccess, UserHasPermission("Write")]
        [EnableQuery, HttpPut, ODataRoute("({contentId})/Articles({articleId})")]
        public Content AddArticle(int contentId, int articleId)
        {
            this.ParseResource();
            return this._contentService.AddArticle(this.Resource, contentId, articleId);

        }
    }
}


text:
package hu.itsh.gyakorlat.szotar.ui.windows;

import java.awt.LayoutManager;
import java.beans.PropertyVetoException;

import javax.swing.JInternalFrame;
import javax.swing.JPanel;

import hu.itsh.gyakorlat.szotar.ui.MainContentPane;

public abstract class InternalWindow extends JInternalFrame {

	protected JPanel contentPane;
	public static MainContentPane mainContentPane;

	public InternalWindow(String title) {
		super(title, true, true, true, true);
		contentPane = (JPanel) this.getContentPane();
		setContentPane(contentPane);
	}

	public InternalWindow(String title, LayoutManager layout) {
		super(title, true, true, true, true);
		contentPane = (JPanel) this.getContentPane();
		contentPane.setLayout(layout);
		setContentPane(contentPane);
	}

	public InternalWindow(String title, JPanel contentPane) {
		super(title, true, true, true, true);
		this.contentPane = contentPane;
		setContentPane(contentPane);
	}
}


text:
import Ember from 'ember';

// TODO: remove this component...
// defaults taken from
// https://github.com/RSSchermer/ember-spinner-button/blob/master/addon/components/spinner-button.js
// ember-spinner-button does not work later versions of ember
export default Ember.Component.extend({
  tagName: 'button',
  classNames: ['spinner-button'],
  classNameBindings: ['spinning'],
  attributeBindings: ['disabled', 'title'],
  disabled: false,
  title: null,
  isSpinning: false,
  action: null,
  onclick: null,

  click() {
    if (!this.get('isSpinning')) {
      if (this.get('action')) {
        this.sendAction();
      }

      if (typeof this.get('onclick') === 'function') {
        this.get('onclick')();
      }
    }
  }
});


text:
using System;
using Agiil.Domain.Sprints;
using Agiil.ObjectMaps.Resolvers;
using Agiil.Web.Models.Sprints;
using AutoMapper;

namespace Agiil.ObjectMaps.Sprints
{
  public class EditSprintSpecificationToEditSprintRequestProfile : Profile
  {
    public EditSprintSpecificationToEditSprintRequestProfile()
    {
      CreateMap<EditSprintSpecification,EditSprintRequest>()
        .ForMember(x => x.SprintIdentity, opts => opts.ResolveUsing<CreateIdentityResolver<Sprint>, long>(x => x.Id));
    }
  }
}


text:
#pragma once

#include <functional>
#include <iostream>
#include <sstream>

inline void error_with_message(char const* file,
                               uint64_t line,
                               char const* msg,
                               std::function<void(std::ostream&)> extra_msg) {
  std::stringstream ss;
  ss << "In file " << file << ":" << line;
  ss << ":" << std::endl;
  ss << "Check failed: `" << msg << "`" << std::endl;
  std::stringstream ss2;
  extra_msg(ss2);
  auto s = ss2.str();
  if (s.size() > 0) {
    ss << s << std::endl;
  }
  ss << std::endl;
  std::cerr << ss.str() << std::endl;
  std::abort();
}

/// Macro for checking a boolean value
/// and printing a custom error message
#define CHECK_INTERNAL(x, msg, ...)                                            \
  if (!(x)) {                                                                  \
    error_with_message(__FILE__, __LINE__, msg,                                \
                       [&](auto& o) { o << "" __VA_ARGS__; });                 \
  }

// Ensure we have a sane define environment
#if defined(DEBUG) && defined(NDEBUG)
#error Both NDEBUG and DEBUG are set
#endif
#if !defined(DEBUG) && !defined(NDEBUG)
#error Neither NDEBUG nor DEBUG are set
#endif

// Conditionally define DCHECK_INTERNAL
#ifdef DEBUG
#define DCHECK_INTERNAL(x, msg, ...) CHECK_INTERNAL(x, msg, ##__VA_ARGS__)
#else // DEBUG
#define DCHECK_INTERNAL(x, msg, ...)
#endif // DEBUG

// Internal macro for checking a binary operator.
#define DCHECK_OP(op, lhs, rhs)                                                \
  DCHECK_INTERNAL(((lhs) op(rhs)), #lhs " " #op " " #rhs,                      \
                  << "Which is:      " << (lhs) << " " << #op << " " << (rhs))

/// Macro for checking a boolean value. Takes an optional `ostream` message
/// paramter.
///
/// Example:
/// ```
/// DCHECK(predicate(x));
/// DCHECK(y.predicate(), << "invariant in y does not hold");
/// ```
#define DCHECK(x) DCHECK_INTERNAL(x, #x, )
/// Check for equality (==)
#define DCHECK_EQ(x, y) DCHECK_OP(==, x, y)
/// Check for inequality (!=)
#define DCHECK_NE(x, y) DCHECK_OP(!=, x, y)
/// Check for less-than or equal (<=)
#define DCHECK_LE(x, y) DCHECK_OP(<=, x, y)
/// Check for less-than (<)
#define DCHECK_LT(x, y) DCHECK_OP(<, x, y)
/// Check for greater-than or equal (>=)
#define DCHECK_GE(x, y) DCHECK_OP(>=, x, y)
/// Check for greater-than (>)
#define DCHECK_GT(x, y) DCHECK_OP(>, x, y)

/// Macro for checking a boolean value. Takes an optional `ostream` message
/// paramter.
///
/// Example:
/// ```
/// CHECK(predicate(x));
/// CHECK(y.predicate(), << "invariant in y does not hold");
/// ```
#define CHECK(x) CHECK_INTERNAL(x, #x, )

/******************************************************************************/


text:
Ember multiapp hosting for https://github.com/ember-cli/ember-cli-deploy

Fork of https://github.com/philipheinser/ember-lightning, which only supports 1 app per server instance.

[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/dough-com/ember-storm)

# Docker support

ember-storm is also available as a docker container. To build the container run:

```shell
docker build --tag ember-storm .
```

Then, to serve an ember-cli application run the container:

```shell
docker run --name ember-storm --env REDIS_HOST=your-redis-server.example.com ember-storm:latest
```

The image responds to these environment variables:

### `REDIS_HOST`

The hostname of the Redis server where ember-cli applications are deployed.
This default to `redis` and so it is also possible to use Docker container
links to connect the ember-storm container to a running Redis container.

### `REDIS_PORT`

The port that Redis is listening on. Defaults to 6379. This only needs to be
set if Redis is listening on a non-default port.

### `REDIS_SECRET`

The shared secret to use for authenticating to Redis. It is blank by default,
which disables authentication.


text:
#pragma once
#ifndef HDR_H
#define HDR_H

#include "Modules/Graphics/Common/Graphics_Technique.h"
#include "Assets/Shader.h"
#include "Assets/Auto_Model.h"
#include "Utilities/GL/DynamicBuffer.h"
#include "Utilities/GL/IndirectDraw.h"

/** A post-processing technique for tone-mapping and gamma correcting the final lighting product. */
class HDR final : public Graphics_Technique {
public:
	// Public (De)Constructors
	/** Destroy this effect. */
	~HDR();
	/** Construct a HDR effect.
	@param	engine			reference to the engine to use. */
	explicit HDR(Engine& engine);

	// Public Interface Implementations.
	void clearCache(const float& deltaTime) noexcept final;
	void renderTechnique(const float& deltaTime, Viewport& viewport, const std::vector<std::pair<int, int>>& perspectives) final;

private:
	// Private but deleted
	/** Disallow default constructor. */
	inline HDR() noexcept = delete;
	/** Disallow move constructor. */
	inline HDR(HDR&&) noexcept = delete;
	/** Disallow copy constructor. */
	inline HDR(const HDR&) noexcept = delete;
	/** Disallow move assignment. */
	inline HDR& operator =(HDR&&) noexcept = delete;
	/** Disallow copy assignment. */
	inline HDR& operator =(const HDR&) noexcept = delete;

	// Private Attributes
	Engine& m_engine;
	float m_gamma = 1.0f;
	Shared_Shader m_shaderHDR;
	Shared_Auto_Model m_shapeQuad;
	struct DrawData {
		DynamicBuffer<> camBufferIndex;
		IndirectDraw<> indirectQuad = IndirectDraw((GLuint)6, 1, 0, GL_DYNAMIC_STORAGE_BIT);
	};
	std::vector<DrawData> m_drawData;
	int	m_drawIndex = 0;
	std::shared_ptr<bool> m_aliveIndicator = std::make_shared<bool>(true);
};

#endif // HDR_H


text:
using System.Collections.Generic;
using System.Linq;
using VirtualScene.BusinessComponents.Core.Controllers;
using VirtualScene.BusinessComponents.Core.Entities;
using VirtualScene.Entities.SceneEntities;
using VirtualScene.EntityPresentationComponents.WPF.Properties;
using VirtualScene.PresentationComponents.WPF.ViewModels;

namespace VirtualScene.EntityPresentationComponents.WPF.ViewModels
{
    /// <summary>
    /// The view-model for the content view of a selected <see cref="ISceneEntity" />
    /// </summary>
    public class SceneEntityContentViewModel<TSceneEntity> : ViewModelBase, ICollectionItemsOperationSubscriber
        where TSceneEntity : class, ISceneEntity
    {
        private TSceneEntity _sceneEntity;

        /// <summary>
        /// Creates a new view-model of content-view of the scene-entity
        /// </summary>
        /// <param name="sceneContent">The content of the scene</param>
        public SceneEntityContentViewModel(ISceneContent sceneContent)
        {
            sceneContent.SubscribeOnSelectedItems<TSceneEntity>(this);
            Title = Resources.Title_Scene_Entity;
            TitleColumnWidth = 80;
        }

        /// <summary>
        /// The title of the view
        /// </summary>
        public string Title { get; private set; }
        /// <summary>
        /// The width of the column with property titles.
        /// </summary>
        public int TitleColumnWidth { get; set; }

        /// <summary>
        /// Notification about the operation with the collection.
        /// </summary>
        /// <param name="items">The changed collection.</param>
        /// <typeparam name="T">The type of items in the collection.</typeparam>
        public void Notify<T>(ICollection<T> items)
        {
            var sceneEntities = items as ICollection<ISceneEntity>;
            if (sceneEntities != null && sceneEntities.Count == 1)
                SceneEntity = sceneEntities.First() as TSceneEntity;
        }

        /// <summary>
        /// The <see cref="ISceneEntity" /> shown on the view.
        /// </summary>
        public TSceneEntity SceneEntity
        {
            get { return _sceneEntity; }
            set
            {
                if (Equals(value, _sceneEntity) || value == null)
                    return;
                _sceneEntity = value;
                OnPropertyChanged();
            }
        }
    }
}


text:
package temp;

import com.amazonaws.regions.Regions;
import com.amazonaws.services.sns.AmazonSNSClient;
import com.amazonaws.services.sns.AmazonSNSClientBuilder;
import com.amazonaws.services.sns.model.MessageAttributeValue;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.PublishResult;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Robert Li
 */
public class MyTest {

    public static void main(String[] args) {
        AmazonSNSClient snsClient = (AmazonSNSClient) AmazonSNSClientBuilder.standard()
                .withRegion(Regions.US_WEST_2)
                .build();

        String message = "My SMS message2";
        String phoneNumber = "+16043000134";

        Map<String, MessageAttributeValue> smsAttributes = new HashMap<>();
//        smsAttributes.put("AWS.SNS.SMS.SenderID", new MessageAttributeValue()
//                .withStringValue("mySenderID") //The sender ID shown on the device.
//                .withDataType("String"));
//        smsAttributes.put("AWS.SNS.SMS.MaxPrice", new MessageAttributeValue()
//                .withStringValue("0.50") //Sets the max price to 0.50 USD.
//                .withDataType("Number"));
//        smsAttributes.put("AWS.SNS.SMS.SMSType", new MessageAttributeValue()
//                .withStringValue("Promotional") //Sets the type to promotional.
//                .withDataType("String"));

        //<set SMS attributes>
        sendSMSMessage(snsClient, message, phoneNumber, smsAttributes);
    }

    public static void sendSMSMessage(AmazonSNSClient snsClient, String message, String phoneNumber, Map<String, MessageAttributeValue> smsAttributes) {
        PublishResult result = snsClient.publish(new PublishRequest()
                .withMessage(message)
                .withPhoneNumber(phoneNumber)
                .withMessageAttributes(smsAttributes));
        System.out.println(result); // Prints the message ID.

    }
}


text:
using namespace Beans;

class FPSController : public Component, protected Utilities::AutoLister<FPSController>
{
public:
  FPSController(GameObject* owner);

  REFLECT_CLASS;

  static void UpdateFPSControllers(double dt);
  void Update(double dt);

  double speed;

  bool InvertY = false;

private:
  Transform* transform_;
  Camera* camera_;

  float yaw_;
  float pitch_;

  const float c_max_pitch_ = 89;
};


text:
/**
 * This program and the accompanying materials
 * are made available under the terms of the License
 * which accompanies this distribution in the file LICENSE.txt
 */
package com.archimatetool.editor.diagram.tools;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import junit.framework.JUnit4TestAdapter;

import org.eclipse.swt.graphics.RGB;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.archimatetool.editor.diagram.tools.FormatPainterInfo.PaintFormat;
import com.archimatetool.model.IArchimateFactory;
import com.archimatetool.model.IDiagramModelArchimateObject;
import com.archimatetool.testingtools.ArchimateTestModel;

public class FormatPainterInfoTests {

    private FormatPainterInfo info;

    public static junit.framework.Test suite() {
        return new JUnit4TestAdapter(FormatPainterInfoTests.class);
    }

    @Before
    public void runBeforeEachTest() {
        info = new FormatPainterInfo();
    }

    @After
    public void runAfterEachTest() {
        info.dispose();
    }

    // ---------------------------------------------------------------------------------------------
    // Tests
    // ---------------------------------------------------------------------------------------------

    @Test
    public void testGetPaintFormat() {
        // Should be null initially
        PaintFormat pf = info.getPaintFormat();
        assertNull(pf);
    }

    @Test
    public void testUpdatePaintFormat() {
        // Set FormatPainterInfo to Source component
        IDiagramModelArchimateObject sourceComponent =
                ArchimateTestModel.createDiagramModelArchimateObject(IArchimateFactory.eINSTANCE.createBusinessActor());
        info.updatePaintFormat(sourceComponent);
        PaintFormat pf = info.getPaintFormat();
        assertNotNull(pf);
        assertEquals(sourceComponent, pf.getSourceComponent());

        // Check cursor
        assertEquals(new RGB(255, 255, 181), pf.getCursorColor());
    }

    @Test
    public void testIsFat() {
        assertFalse(info.isFat());

        IDiagramModelArchimateObject sourceComponent =
                ArchimateTestModel.createDiagramModelArchimateObject(IArchimateFactory.eINSTANCE.createBusinessActor());
        info.updatePaintFormat(sourceComponent);
        assertTrue(info.isFat());
    }

    @Test
    public void testReset() {
        PaintFormat pf = info.getPaintFormat();
        assertNull(pf);

        IDiagramModelArchimateObject sourceComponent =
                ArchimateTestModel.createDiagramModelArchimateObject(IArchimateFactory.eINSTANCE.createBusinessActor());
        info.updatePaintFormat(sourceComponent);
        pf = info.getPaintFormat();
        assertNotNull(pf);

        info.reset();
        pf = info.getPaintFormat();
        assertNull(pf);
    }
}


text: implicit class Foo // error


text:
/**
 * Network (TCP)
 * =============
 *
 * An abstraction over node's net module.
 */
"use strict";
let dependencies = {
  Channel: require('./channel-tcp'),
  Constants: require('./constants').Default.Network,
  extend: require('./extend'),
  net: require('net'),
  Struct: require('./struct')
};

function inject(deps) {
  let Channel = deps.Channel;
  let Constants = deps.Constants;
  let extend = deps.extend;
  let net = deps.net;
  let Struct = deps.Struct;

  function Network(opts, netstream, awaits) {
    if (!(this instanceof Network))
      return new Network(opts, netstream, awaits);
    this.initialize();
    this.fromObject({
      opts: opts,
      netstream: netstream,
      awaits: awaits
    });
  }

  Network.prototype.fromObject = Struct.prototype.fromObject;

  Network.prototype.initialize = function() {
    this.opts = {};
    this.awaits = [];
  };

  Network.prototype.createNetstream = function() {
    this.netstream = net.createServer(this.onConnection.bind(this));
    this.netstream.maxConnections = Constants.maxconnections;
    return this;
  };

  Network.prototype.open = function() {
    if (!this.netstream)
      this.createNetstream();
    let opts = extend({}, Constants, this.opts);
    return new Promise(function(resolve, reject) {
      this.netstream.listen(opts, resolve);
      this.netstream.on('error', function(error) {
        reject(error);
      });
    }.bind(this));
  };

  Network.prototype.address = function() {
    return this.netstream.address();
  };

  Network.prototype.onConnection = function(bufstream) {
    let channel = Channel({}, bufstream);
    channel.monitor();
    this.awaits.forEach(function(await) {
      await.resolve(channel);
    });
    return this;
  };

  Network.prototype.awaitChannels = function*() {
    while (this.netstream) {
      yield new Promise(function(resolve, reject) {
        this.awaits.push({
          resolve: resolve,
          reject: reject
        });
      }.bind(this));
    }
  };

  Network.prototype.connect = function(opts) {
    return new Promise(function(resolve, reject) {
      let bufstream = net.connect(opts);
      bufstream.on('connect', function() {
        let channel = Channel(opts, bufstream);
        channel.monitor();
        resolve(channel);
      });
      bufstream.on('error', reject);
    }.bind(this));
  };

  /**
   * Close the network. Note that this promise will not resolve until all
   * connections on this network are also closed.
   */
  Network.prototype.close = function() {
    return new Promise(function(resolve, reject) {
      this.netstream.close(function(error) {
        if (error)
          reject(error);
        else
          resolve();
      });
      delete this.netstream;
    }.bind(this));
  };

  return Network;
};

inject = require('./injector')(inject, dependencies);
let Network = inject();
module.exports = Network;


text:
The `amgSentryPlugin` is a symfony 1.4 plugin for Sentry interface.

This plugin is based on Raven client library [raven-php](https://github.com/getsentry/raven-php).

## Requirements

* PHP ≥ 5.2
* symfony ≥ 1.4
* Sentry instance

## Installation

In the `plugins` folder of your symfony project.

### The Composer way

Add the require to your composer.json. It's oddly named but like this Composer's symfony1 installer camelcases it correctly. Composer will install it into your project's plugins directory automatically, and add the requirements.

```json
{
    "config": {
        "vendor-dir": "lib/vendor"
    },
    "require": {
        "amg-dev/amg-sentry-plugin": "dev-master"
    }
}
```

Of course, don't forget to add Composer's autoloader to your ProjectConfiguration:

```php
// config/ProjectConfiguration.class.php

require __DIR__ .'/../lib/vendor/autoload.php';

require_once dirname(__FILE__) .'/../lib/vendor/symfony/lib/autoload/sfCoreAutoload.class.php';
sfCoreAutoload::register();

class ProjectConfiguration extends sfProjectConfiguration
{
    public function setup()
    {
        $this->enablePlugins(array(
            'amgSentryPlugin',
            ...
        ));

        // mandatory because of the Composer vendor directory naming scheme
        sfConfig::set('sf_raven_path', sfConfig::get('sf_lib_dir') .'/vendor/raven/raven');
    }
}
```

### Via git clone

```
$ git clone git@github.com:amg-dev/symfony-amg-sentry-plugin.git plugins/amgSentryPlugin
$ cd plugins/amgSentryPlugin
$ git submodule update --init
```

### Via git submodule

```
$ git submodule add github.com:amg-dev/symfony-amg-sentry-plugin.git plugins/amgSentryPlugin
$ git submodule update --init --recursive
```

### Via zip archive

[Download](https://github.com/amg-dev/symfony-amg-sentry-plugin/archive/master.zip) and extract zip archive.

## Configuration

In your symfony project folder.

### Activate the plugin in `config/ProjectConfiguration.class.php`

```php
class ProjectConfiguration extends sfProjectConfiguration
{
	public function setup()
	{
		$this->enablePlugins(array(
			'sfDoctrinePlugin',
			'amgSentryPlugin',
			'...'
		));
	}
}
```

### Configure the plugin in `config/app.yml` (project and/or application level)

```yaml
prod:
  amg_sentry:
    enabled: true
    dsn: 'http://public:secret@sentry.example.com:9000/[PROJECT_ID]'
    logger: 'custom-logger-name'
    reportPHPErrors: true
    reportPHPWarnings: false
    report404: false
```

 * `dsn` - If it is possible for sites with high traffic use UDP protocol.
 * `reportPHPErrors` - If true, it sends a notification when there is a exception.
 * `reportPHPWarnings` - If true, it sends a notification when there is a warning.
 * `report404` - If true, it sends a notification when a user lands on a page 404. It should be used only for the duration of the study, the risk is that web crawlers will produce a lot of notifications.

### (Optional) Enable the helper in `config/settings.yml` (application level)

```yaml
.settings:
  standard_helpers: [default, Sentry, ...]
```

### (Optional) Configure the symfony logger in `config/factories.yml` (project and/or application level)

```yaml
prod:
  logger:
    param:
      loggers:
        amg_sentry_logger:
          class: amgSentryLogger
          param:
            level: warning
```

Additional docs about logging:

* [The factories.yml Configuration File (official doc)](http://symfony.com/legacy/doc/reference/1_4/en/05-Factories)
* [Enable logging in the production environment](http://symfony-blog.driebit.nl/2010/11/enable-logging-in-the-production-environment/)

### Clear the cache

```
$ symfony cc
```

## Usage

### amgSentry

```php
// send a message with no description and information level (by default)
amgSentry::sendMessage('Message title');

// send a debug message
amgSentry::sendMessage('Debug message title', 'Debug message description', amgSentry::DEBUG);

// send a warning message
amgSentry::sendMessage('Warning message title', 'Warning message description', amgSentry::WARNING);

// send an error message
amgSentry::sendMessage('Error message title', 'Error message description', amgSentry::ERROR);

// send an exception
amgSentry::sendException(new Exception('Exception message'), 'Exception description');

// set logger
amgSentry::setLogger('new-logger');

// reset logger
amgSentry::resetLogger();
```

### SentryHelper

```php
// send a message with no description and information level (by default)
sentry_send_message('Message title');

// send a debug message
sentry_send_message('Debug message title', 'Debug message description', amgSentry::DEBUG);

// send a warning message
sentry_send_message('Warning message title', 'Warning message description', amgSentry::WARNING);

// send an error message
sentry_send_message('Error message title', 'Error message description', amgSentry::ERROR);

// send an exception
sentry_send_exception(new Exception('Exception message'), 'Exception description');

// set logger
sentry_set_logger('new-logger');

// reset logger
sentry_reset_logger();
```

### sfLogger

```php
// log a debug message
sfContext::getInstance()->getLogger()->debug('Debug message');

// log an error message
sfContext::getInstance()->getLogger()->err('Error message');
```

## Contributors

* Nicolas Dubois <nicolas.c.dubois@gmail.com>
* Jean Roussel <contact@jean-roussel.fr>
* Arkadiusz Tułodziecki <atulodzi@gmail.com>

### vendor/raven-php

The Raven PHP client was originally written by Michael van Tellingen
and is maintained by the Sentry Team.

http://github.com/getsentry/raven-php/contributors


text:
'use strict';

var _minimist = require('minimist');

var _minimist2 = _interopRequireDefault(_minimist);

var _Avifors = require('./Avifors');

var _Avifors2 = _interopRequireDefault(_Avifors);

var _YamlModelBuilder = require('./model/YamlModelBuilder');

var _YamlModelBuilder2 = _interopRequireDefault(_YamlModelBuilder);

var _Configuration = require('./Configuration');

var _Configuration2 = _interopRequireDefault(_Configuration);

var _help = require('./help');

var _YamlHelper = require('./tools/YamlHelper');

var _YamlHelper2 = _interopRequireDefault(_YamlHelper);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var avifors = new _Avifors2.default();
var corePlugins = ['./model/plugin', './template/plugin', './commands/plugin'];
corePlugins.forEach(function (plugin) {
  return require(plugin).default(avifors);
});

var argv = (0, _minimist2.default)(process.argv.slice(2));
var userCommand = argv._[0];
if (userCommand === undefined || userCommand === 'help') {
  console.log(_help.helpMessage);
} else {
  var yamlHelper = new _YamlHelper2.default();
  var config = new _Configuration2.default(argv.config, yamlHelper);

  avifors.loadPlugins(config.plugins);

  var modelBuilder = new _YamlModelBuilder2.default(avifors, yamlHelper);
  var model = modelBuilder.build(config.modelFiles);
  avifors.setModel(model);

  avifors.getCommand(userCommand)({
    avifors: avifors,
    model: model,
    argv: argv
  });
}


text:
import * as React from 'react'
import SEO from '../components/seo'
import '../images/lines.css'

function lines(backgroundSize: number, fill: string, rotation: number, rotationCenter: number): string[] {
  return [
    `
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 400 400" height="${backgroundSize}" width="${backgroundSize}"><g transform="rotate(${rotation}, ${rotationCenter}, ${rotationCenter})">      <path d="M12 5 H395 V388 Z" fill="${fill}"/>
      <path d="M5 12 V395 H388 Z" fill="${fill}"/>
    </g></svg>
    `,
    `
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 400 400" height="${backgroundSize}" width="${backgroundSize}"><g transform="rotate(${rotation}, ${rotationCenter}, ${rotationCenter})">      <path d="M5 188 V5 H388 Z" fill="${fill}"/>
      <path d="M8.5 200 L395 12 V388 Z" fill="${fill}"/>
      <path d="M5 212 V395 H388 Z" fill="${fill}"/>
    </g></svg>
    `,
    `
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 400 400" height="${backgroundSize}" width="${backgroundSize}"><g transform="rotate(${rotation}, ${rotationCenter}, ${rotationCenter})">      <path d="M5 188 V5 H388 Z" fill="${fill}"/>
      <path d="M12 195 H395 V12 Z" fill="${fill}"/>
      <path d="M12 205 H395 V388 Z" fill="${fill}"/>
      <path d="M5 212 V395 H388 Z" fill="${fill}"/>
    </g></svg>
    `,
    `
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 400 400" height="${backgroundSize}" width="${backgroundSize}"><g transform="rotate(${rotation}, ${rotationCenter}, ${rotationCenter})">      <path d="M12 5 H395 V188 Z" fill="${fill}"/>
      <path d="M5 12 V195 H388 Z" fill="${fill}"/>
      <path d="M12 205 H395 V388 Z" fill="${fill}"/>
      <path d="M5 212 V395 H388 Z" fill="${fill}"/>
    </g></svg>
    `,
    `
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 400 400" height="${backgroundSize}" width="${backgroundSize}"><g transform="rotate(${rotation}, ${rotationCenter}, ${rotationCenter})">      <path d="M5 5 V395 h90 V5 Z" fill="${fill}"/>
      <path d="M105 5 V395 h90 V5 Z" fill="${fill}"/>
      <path d="M205 5 V395 h90 V5 Z" fill="${fill}"/>
      <path d="M305 5 V395 h90 V5 Z" fill="${fill}"/>
    </g></svg>
    `,
    `
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 400 400" height="${backgroundSize}" width="${backgroundSize}"><g transform="rotate(${rotation}, ${rotationCenter}, ${rotationCenter})">      <path d="M5 5 V395 h123.3 V5 Z" fill="${fill}"/>
      <path d="M138.3 5 V395 h123.3 V5 Z" fill="${fill}"/>
      <path d="M271.6 5 V395 h123.3 V5 Z" fill="${fill}"/>
    </g></svg>
    `,
    `
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 400 400" height="${backgroundSize}" width="${backgroundSize}"><g transform="rotate(${rotation}, ${rotationCenter}, ${rotationCenter})">      <path d="M5 5 V395 h190 V5 Z" fill="${fill}"/>
      <path d="M205 5 V395 h190 V5 Z" fill="${fill}"/>
    </g></svg>
    `,
  ];
}

interface Props {
  rotationCenter: number
  rotationGranularity: number
}

interface State {
  width: number;
  height: number;
}

class Lines extends React.Component<Props, State> {
  colors: string[] = ['#55cc94', '#9455cc', '#55c8cc', '#cc558c', '#cc9455']
  color: string = this.colors[Math.floor(Math.random()*this.colors.length)]

  constructor(props: Props) {
    super(props)
    this.state = {
      width: 100,
      height: 100
    }
  }

  componentDidMount() {
    window.addEventListener("resize", this.updateDimensions.bind(this))
    this.setState({
      width: this.getWidth(),
      height: this.getHeight()
    })
  }

  getHeight() {
    return window.innerHeight || document.body.clientHeight
  }

  getWidth() {
    return window.innerWidth || document.body.clientWidth
  }

  /**
   * Calculate & Update state of new dimensions
   */
  updateDimensions() {
    // TODO: this only needs to update state when width or height changes more then the shape size
    this.setState({ width: this.getWidth(), height: this.getHeight() })
  }

  render() {
    const lineArray: JSX.Element[] = []

    for (var i = 0; i < this.state.height; i = i + 70) {
      let row = ""
      for (var j = 0; j < this.state.width; j = j + 70) {
        var rotation = Math.floor(Math.random()*this.props.rotationGranularity) * (360/this.props.rotationGranularity)
        var shapes = lines(70, '#1c1b26', rotation, this.props.rotationCenter)
        row += (shapes[Math.floor(Math.random()*shapes.length)])
      }
      lineArray.push(

      )
    }
    return (

       {lineArray}

    );
  }
}

const LinesPage = () =>  (

    <SEO title="lines"/>
    <Lines
      rotationCenter={200}
      rotationGranularity={4}
    />
    <Lines
      rotationCenter={35}
      rotationGranularity={4}
    />
    <Lines
      rotationCenter={35}
      rotationGranularity={360}
    />

)

export default LinesPage


text:
#ifndef __MAIN_H__
#define __MAIN_H__

#include <windows.h>

/*  To use this exported function of dll, include this header
 *  in your project.
 */

#ifdef BUILD_DLL
    #define DLL_EXPORT __declspec(dllexport)
#else
    #define DLL_EXPORT __declspec(dllimport)
#endif

#ifdef __cplusplus
extern "C"
{
#endif

void DLL_EXPORT SomeFunction(const LPCSTR sometext);

#ifdef __cplusplus
}
#endif

#endif // __MAIN_H__


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Boletellus cerasinus R. Heim & Perr.-Bertr.

### Remarks
null


text:
package com.ibasco.agql.protocols.supercell.coc.webapi.interfaces.leagues;

import com.ibasco.agql.protocols.supercell.coc.webapi.CocApiConstants;
import com.ibasco.agql.protocols.supercell.coc.webapi.CocWebApiRequest;
import org.jetbrains.annotations.ApiStatus;

/**
 *
GetLeagueSeasonRankings class.

 *
 * @author Rafael Luis Ibasco
 */
@Deprecated
@ApiStatus.ScheduledForRemoval
public class GetLeagueSeasonRankings extends CocWebApiRequest {

    /**
     *
Constructor for GetLeagueSeasonRankings.

     *
     * @param apiVersion
     *         a int
     * @param leagueId
     *         a int
     * @param seasonId
     *         a {@link java.lang.String} object
     * @param limit
     *         a int
     * @param before
     *         a int
     * @param after
     *         a int
     */
    public GetLeagueSeasonRankings(int apiVersion, int leagueId, String seasonId, int limit, int before, int after) {
        super(apiVersion, CocApiConstants.UF_COC_LEAGUE_SEASON_RANKINGS, limit, before, after);
        property(CocApiConstants.UF_PROP_LEAGUE_ID, leagueId);
        property(CocApiConstants.UF_PROP_SEASON_ID, seasonId);
    }
}


text:
{-# LANGUAGE TupleSections #-}
module Reactive.Bacon.EventStream.Timed where

import Reactive.Bacon.Core
import Reactive.Bacon.EventStream.IO
import Reactive.Bacon.EventStream.Monadic
import System.Time
import Control.Concurrent(threadDelay, forkIO)
import Control.Monad(void, unless)
import Data.IORef

laterE :: TimeDiff -> a -> IO (EventStream a)
laterE diff x = timedE [(diff, x)] >>= return . fst

periodicallyE :: TimeDiff -> a -> IO (EventStream a, Disposable)
periodicallyE diff x = timedE (repeat (diff, x))

sequentiallyE :: TimeDiff -> [a] -> IO (EventStream a)
sequentiallyE delay xs = timedE (map (delay,) xs) >>= return . fst

timedE :: [(TimeDiff, a)] -> IO (EventStream a, Disposable)
timedE events = fromStoppableProcess $ \sink stopper -> void $ forkIO $ serve sink events stopper
  where serve sink [] _ = sink End
        serve sink ((diff, event) : events) getStopState = do
          stop <- getStopState
          unless stop $ do
            threadDelay (toMicros diff)
            sink $ Next event
            serve sink events getStopState

delayE :: EventSource s => TimeDiff -> s a -> IO (EventStream a)
delayE diff = flatMapE (laterE diff)

throttleE :: EventSource s => TimeDiff -> s a -> IO (EventStream a)
throttleE diff = switchE (laterE diff)

toMicros :: TimeDiff -> Int
toMicros diff = fromInteger((toPicos diff) `div` 1000000)
 where
    toPicos :: TimeDiff -> Integer
    toPicos (TimeDiff 0 0 0 h m s p) = p + (fromHours h) + (fromMinutes m) + (fromSeconds s)
      where fromSeconds s = 1000000000000 * (toInteger s)
            fromMinutes m = 60 * (fromSeconds m)
            fromHours   h = 60 * (fromMinutes h)

-- | Milliseconds to TimeDiff
milliseconds :: Integral a => a -> TimeDiff
milliseconds ms = noTimeDiff { tdPicosec = (toInteger ms) * 1000000000}

-- | Seconds to TimeDiff
seconds :: Integral a => a -> TimeDiff
seconds = milliseconds . (*1000)


text:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var tropowebapi = require('tropo-webapi');
var request = require('request');
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })
var fs = require('fs');
var fsAccess = require('fs-access');
var xlsx = require('node-xlsx');

app.use(bodyParser.json())

//Tropo Call App Token to trigger Tropo Voice Web-API Script
//EDIT THIS LINE HERE
var tropoToken = 'insert_token_here'

//placedCalls tracks Tropo session ID's with DID's dialed
var placedCalls = {}

//Spark Public Integrations Hook Room URL - get from Web Spark Client Integrations Tab
var sparkHook = null

//timer object used to clear timeout
var timerknock = null

//Express Engine to accept XLSX file
app.post('/dataformupload', upload.single('file'), function (req, res, next) {

  	//console.log(req.body) - Contains form parameters - may be useful for getting Spark Hook URL
  	console.log(req.body)
  	if (req.body.sparkHookURL != null) {
  		sparkHook = req.body.sparkHookURL
  		console.log(sparkHook)
  		fs.writeFileSync('uploads/sparkHookURL.txt',sparkHook)
  	}
	var tmp_path = req.file.path;
	var target_path = 'uploads/numbersToValidate.xlsx';
	var src = fs.createReadStream(tmp_path);
  	var dest = fs.createWriteStream(target_path);
  	src.pipe(dest);
  	src.on('end', function() {
  		if (timerknock != null ) {
  			clearTimeout(timerknock)
  		}
  		fs.unlink(tmp_path)
  		res.sendStatus(200)
  		parseXLSX(target_path)
  		//call execution of file
  	});
  	src.on('error', function(err) { res.status(500).send('Something broke!'); });

  	// req.body will hold the text fields, if there were any

})

//Parse XCEL file to get callers array - calculate the "setTimeout" to run at midnight, designated time, etc.
//Or could just have a static file and "chron" the start of the .js file and have it process on start every time
var parseXLSX = function(path) {

	//Set logic to parse XLSX file and then for each entry, call validateNumbers(callers)
	var parseFile = function() {
		obj = xlsx.parse(path)
		data = obj[0].data
		data.shift()
		console.log(data.length)
		if (data.length >= 1) {
			validateNumbers(data)
		}
		else {
			console.log('Empty XLSX file - waiting for new upload in web UI')
		}

	}

	//Check if path was passed - if not, check if file already exists.  If path exists, parse with that path
	if (path == null) {
		testpath = 'uploads/numbersToValidate.xlsx'
		fsAccess(testpath, function(err) {
		    if (!err) {
		        path = 'uploads/numbersToValidate.xlsx'
		        parseFile();
		    } else {
		        console.log('No XLSX file to parse - will wait for one to be uploaded in WebUI')

		    }
		});

	}
	else {
		parseFile();
	}

}

//Tropo Application
var validateNumbers = function (callers) {

	var startOutbound = function() {

		//Let Spark Room know we're starting testing
		date = new Date
		var options = {
	  		uri: sparkHook,
	  		method: 'POST',
	  		json: {
	  			"text" : 'Starting testing to provided numbers on '+date+'.  Any errors found will be posted here shortly.'
	  		}
	  	}
		request(options, function (error, response, body) {
	  		if (!error && response.statusCode == 204) {
	  			console.log('Successfully posted startup message to Spark room')
	  		}
	  		else {
	  			console.log('Error posting to Spark for initialization.')
	  		}
		})

		placedCalls = {} //Reset data for placedCalls session ID's
		//Start outbound calls
		callers.forEach(function(caller) {
			parameters = {to: caller[0]}
			placeCall(parameters) //May want to introduce a timeout with some variability for each outbound call to throttle number of calls coming in the trunks
			console.log('Placing call to',caller[0])
		});

		console.log('Parsed file & placed calls - sleeping for 3 minutes')
		timerknock = setTimeout(parseXLSX, 300000) //86400000 ms for 1 full day, 180000 is 3 min for testing.  This is where you would want to remove the setTimeout if you want to chron the service to run every day, or calculate a setTimeout based no when you want it to run next (i.e. every night at midnight).  Leaving it running allows access to the webui, but this could be run from someone's laptop etc.

	}

	//Check if flat file has SparkURI
	if (sparkHook == null) {
		testpath = 'uploads/sparkHookURL.txt'
		fsAccess(testpath, function(err) {
		    if (!err) {
		        fs.readFile(testpath, 'utf8', function(err, data) {
					if (err) throw err;
					sparkHook = data
					console.log('sparkHook found in flat file is',data)
					startOutbound();
				});
		    }
		    else {
		   		console.log('No Spark Hook URL in flat file - no place to post notifications to so waiting for Spark URL from uploader')
		    }
		});
	}
	else {
		startOutbound();
	}

}

var placeCall = function (parameters) {
	// var session = new TropoSession();
	var options = {
  		uri: 'https://api.tropo.com/1.0/sessions',
  		method: 'POST'
  	}
  	token = tropoToken
  	parameters.token = token
  	options.json = parameters
	request(options, function (error, response, body) {
  		if (!error && response.statusCode == 200) {
  			placedCalls[body.id] = {}
  			placedCalls[body.id].to = parameters.to
  			//console.log(placedCalls)
  		}
  		else {
  			console.log('Error calling outbound for caller',parameters.to)
  		}
	})

};

// Stereo Outbound Dialer
app.post('/', function (req, res) {
	parameters = req.body.session.parameters
	// console.log(parameters)
	var callingparty = '+15551231234'  //Change to the caller ID you want to use when placing calls
	var tropo = new tropowebapi.TropoWebAPI();
	tropo.call(parameters.to, null, null, callingparty, null, parameters.to, null, null, null, '4', null, null);
	tropo.wait(1000);
	tropo.say('This is a test of the emergency phone system.  Please disregard this call.')
	tropo.on("incomplete", null, "/incomplete", true)
    tropo.on("hangup", null, "/hangup", true)
    tropo.on("error", null, "/error", true)
    console.log(tropowebapi.TropoJSON(tropo))
	res.send(tropowebapi.TropoJSON(tropo));
});

app.post('/incomplete', function (req, res) {
	callId = req.body.result.sessionId
	//console.log(callId)
	console.log('Incomplete call data received from Tropo for',placedCalls[callId].to)
	date = new Date
	var options = {
  		uri: sparkHook,
  		method: 'POST',
  		json: {
  			"text" : 'The call to '+placedCalls[callId].to+' failed at ' +date+'.  Please check the analog port and confirm its operation.'
  		}
  	}
	request(options, function (error, response, body) {
  		if (!error && response.statusCode == 204) {
  			console.log('Successfully posted failed call to Spark room')
  		}
  		else {
  			console.log('Error posting to Spark for failed call to',placedCalls[callId].to)
  		}
	})

	res.sendStatus(200)

});

app.post('/hangup', function (req, res) {
	parameters = req.body
	console.log('Hangup call in Tropo')
	console.log(parameters)
	res.sendStatus(200)

});

app.post('/error', function (req, res) {
	parameters = req.body
	console.log('Error calling in Tropo')
	console.log(parameters)
	res.sendStatus(200)

});

//Start parsing flat-files on launch.  If not found, will wait for upload from web-interface.
parseXLSX();

//Serve Static Web Files

app.use('/validator', express.static(__dirname + "/circuitValidationStaticFiles"));
app.use('/bower_components', express.static(__dirname + '/bower_components'));

//Mount App to Port 8080
app.listen(8080);
console.log("validationApp server running on port 8080");