<commit_before>#!/usr/bin/env -S deno run --allow-net --allow-write --allow-read --allow-run

import { compress } from "https://deno.land/x/zip@v1.2.3/mod.ts";

const startUrl = "https://api.scryfall.com/cards/search" +
  "?format=json" +
  "&include_extras=true" +
  "&include_multilingual=false" +
  "&include_variations=true" +
  "&order=set" +
  "&page=1" +
  "&q=e%3Admu" +
  "&unique=prints";

const manaTypeRegex = /[A-Z]/gi;

const groupCardsByRarity = (cards) => cards
  .filter((it) => !it.isBasicLand && !it.isToken)
  .reduce((acc, value) => {
    if (!acc[value.rarity]) {
      acc[value.rarity] = [];
    }
    acc[value.rarity].push(value);
    return acc;
  }, {});

const groupCardsByMana = (cards) => cards
  .reduce((acc, value) => {
    if (!acc[value.manaType]) {
      acc[value.manaType] = [];
    }
    acc[value.manaType].push(value);
    return acc;
  }, {});

function getCards(url) {
  console.log("Visit next page");
  return fetch(url)
    .then((response) => response.json())
    .then(async (response) => {
      const out = response.data.map((it) => {
        const manaType = it.mana_cost.match(manaTypeRegex)
        const priceUSDstr = it.prices["usd"]
        return {
          id: it.collector_number,
          name: it.name,
          rarity: it.rarity,
          scryfall_uri: it.scryfall_uri,
          image_url: it.image_uris.small,
          isBasicLand: it.type_line.includes("Basic Land"),
          isToken: it.type_line.includes("Token"),
          manaType: manaType ? manaType.filter(uniq).sort().join("") : "-",
          price: priceUSDstr ? parseFloat(priceUSDstr) : -1
        };
      });
      if (response.has_more) {
        out.push.apply(out, await getCards(response.next_page));
      }
      return out;
    })
    .catch((error) => console.log(error));
}

async function main() {
  const remoteCards = getCards(startUrl);
  const cardsByRarity = groupCardsByRarity(await remoteCards);
  const numBoosters = 6;
  const numDecks = 3;
  for (let indexDeck = 0; indexDeck < numDecks; indexDeck++) {
    await generateDeck(numBoosters, remoteCards, cardsByRarity, indexDeck);
  }
  console.log(startUrl)
}
main();

async function generateDeck(numBoosters, remoteCards, cardsByRarity, indexDeck) {
  const allCards = [];
  const genFiles = []

  // generating booster files
  await generateBoosterFiles();

  // using the generated booster info to create filtered sets based on mana type
  const cardsByMana = groupCardsByMana(allCards.flat());
  await writeManaGroupedPages(cardsByMana);
  await writePricePage(allCards, genFiles);
  await writeIndexFile(cardsByMana, numBoosters, genFiles);
  await writeAllCardsPage(allCards, genFiles);

  await compress(genFiles, `sealed-deck-${indexDeck}.zip`, { overwrite: true });

  genFiles.forEach(element => {
    Deno.remove(element)
  });

  async function writeAllCardsPage(allCards, genFiles) {
    const filename = "mtg-all-cards.html";
    const output = createAllCardsContent(allCards.flat());
    genFiles.push(filename);
    await Deno.writeTextFile(filename, output);

    function createAllCardsContent(cards) {
      return `

      ${cards.map((it) => `

      Remove

`
      ).join("\n")}

    `;
    }
  }

  async function generateBoosterFiles() {
    for (let index = 0; index < numBoosters; index++) {
      const cards = await buildBooster(await remoteCards, cardsByRarity);
      allCards.push(cards);
      console.log(cards.map((it) => it.name));
      const output = createBoosterFileContent(cards);
      const filename = `mtg-booster-${index}.html`;
      genFiles.push(filename);
      await Deno.writeTextFile(filename, output);
    }

    const getRandomFromArray = (arr) => arr[Math.floor(Math.random() * arr.length)];

    function getRandomByRarity(cardsByRarity, rarity) {
      return cardsByRarity[rarity][
        Math.floor(Math.random() * cardsByRarity[rarity].length)
      ];
    }

    const findBasicLands = (cards) => cards
      .filter((it) => it.isBasicLand);

    function buildBooster(allCards, cardsByRarity) {
      return [
        Array(10).fill(0).map(() => getRandomByRarity(cardsByRarity, "common")),
        Array(3).fill(0).map(() => getRandomByRarity(cardsByRarity, "uncommon")),
        [
          Math.floor(Math.random() * 8) === 0
            ? getRandomByRarity(cardsByRarity, "mythic")
            : getRandomByRarity(cardsByRarity, "rare"),
        ],
        [getRandomFromArray(findBasicLands(allCards))],
      ].flatMap((it) => it);
    }
  }

  async function writeManaGroupedPages(cardsByMana) {
    for (const key in cardsByMana) {
      if (Object.hasOwnProperty.call(cardsByMana, key)) {
        const element = cardsByMana[key];
        const output = createBoosterFileContent(element);
        const filename = `mtg-booster-filtered-${key}.html`;
        genFiles.push(filename);
        await Deno.writeTextFile(filename, output);
      }
    }
  }
}

async function writePricePage(allCards, genFiles) {
  const cardsByPrice = allCards.flat().sort((a, b) => {
    if (a["price"] > b["price"]) {
      return -1;
    } else if (a["price"] < b["price"]) {
      return 1;
    } else {
      return 0;
    }
  });
  const output = `

  ${cardsByPrice.map((it) => `<a href="${it.scryfall_uri}"><div>${it.name}: ${it.price}</div></a>`).join("\n")}

  `;
  const filename = `mtg-price.html`;
  genFiles.push(filename);
  await Deno.writeTextFile(filename, output);
}

const uniq = (value, index, self) => self.indexOf(value) === index;

async function writeIndexFile(cardsByMana, numBoosters, genFiles) {
  const filename = "index.html";
  const output = createIndexFileContent(cardsByMana, numBoosters);
  genFiles.push(filename);
  await Deno.writeTextFile(filename, output);

  function createIndexFileContent(cardsByMana, numBoosters) {
    const lines = []
    for (let index = 0; index < numBoosters; index++) {
      lines.push(`<a href="./mtg-booster-${index}.html"><div>Booster #${index}</div></a>`)
    }
    lines.push('
')
    const keys = []
    for (const key in cardsByMana) {
      keys.push(key)
    }
    keys.sort().forEach(key => {
      if (Object.hasOwnProperty.call(cardsByMana, key)) {
        const element = cardsByMana[key];
        lines.push(`<a href="./mtg-booster-filtered-${key}.html"><div>${key}: <strong>${element.length}</strong> cards</div></a>`)
      }
    })
    lines.push('
')
    lines.push(`<a href="./mtg-price.html"><div>Cards by price</a>`)
    lines.push(`<a href="./mtg-all-cards.html"><div>All cards</a>`)
    return `

  ${lines.flat().join("\n")}

`
  }
}

function createBoosterFileContent(cards) {
  return `

  ${cards.map((it) => `<a href="${it.scryfall_uri}"><img src="${it.image_url}"/></a>`
  ).join("\n")}

`;
}

<commit_msg>fixing all card page generation<commit_after>#!/usr/bin/env -S deno run --allow-net --allow-write --allow-read --allow-run

import { compress } from "https://deno.land/x/zip@v1.2.3/mod.ts";

const startUrl = "https://api.scryfall.com/cards/search" +
  "?format=json" +
  "&include_extras=true" +
  "&include_multilingual=false" +
  "&include_variations=true" +
  "&order=set" +
  "&page=1" +
  "&q=e%3Admu" +
  "&unique=prints";

const manaTypeRegex = /[A-Z]/gi;

const groupCardsByRarity = (cards) => cards
  .filter((it) => !it.isBasicLand && !it.isToken)
  .reduce((acc, value) => {
    if (!acc[value.rarity]) {
      acc[value.rarity] = [];
    }
    acc[value.rarity].push(value);
    return acc;
  }, {});

const groupCardsByMana = (cards) => cards
  .reduce((acc, value) => {
    if (!acc[value.manaType]) {
      acc[value.manaType] = [];
    }
    acc[value.manaType].push(value);
    return acc;
  }, {});

function getCards(url) {
  console.log("Visit next page");
  return fetch(url)
    .then((response) => response.json())
    .then(async (response) => {
      const out = response.data.map((it) => {
        const manaType = it.mana_cost.match(manaTypeRegex)
        const priceUSDstr = it.prices["usd"]
        return {
          id: it.collector_number,
          name: it.name,
          rarity: it.rarity,
          scryfall_uri: it.scryfall_uri,
          image_url: it.image_uris.small,
          isBasicLand: it.type_line.includes("Basic Land"),
          isToken: it.type_line.includes("Token"),
          manaType: manaType ? manaType.filter(uniq).sort().join("") : "-",
          price: priceUSDstr ? parseFloat(priceUSDstr) : -1
        };
      });
      if (response.has_more) {
        out.push.apply(out, await getCards(response.next_page));
      }
      return out;
    })
    .catch((error) => console.log(error));
}

async function main() {
  const remoteCards = getCards(startUrl);
  const cardsByRarity = groupCardsByRarity(await remoteCards);
  const numBoosters = 6;
  const numDecks = 3;
  for (let indexDeck = 0; indexDeck < numDecks; indexDeck++) {
    await generateDeck(numBoosters, remoteCards, cardsByRarity, indexDeck);
  }
  console.log(startUrl)
}
main();

async function generateDeck(numBoosters, remoteCards, cardsByRarity, indexDeck) {
  const allCards = [];
  const genFiles = []

  // generating booster files
  await generateBoosterFiles();

  // using the generated booster info to create filtered sets based on mana type
  const cardsByMana = groupCardsByMana(allCards.flat());
  await writeManaGroupedPages(cardsByMana);
  await writePricePage(allCards, genFiles);
  await writeIndexFile(cardsByMana, numBoosters, genFiles);
  await writeAllCardsPage(allCards, genFiles);

  await compress(genFiles, `sealed-deck-${indexDeck}.zip`, { overwrite: true });

  genFiles.forEach(element => {
    Deno.remove(element)
  });

  async function writeAllCardsPage(allCards, genFiles) {
    const filename = "mtg-all-cards.html";
    const output = createAllCardsContent(allCards.flat());
    genFiles.push(filename);
    await Deno.writeTextFile(filename, output);

    function createAllCardsContent(cards) {
      return `

      ${cards.map((it, index) => {
        return `

      Remove

`;
      }).join("\n")}

    `;
    }
  }

  async function generateBoosterFiles() {
    for (let index = 0; index < numBoosters; index++) {
      const cards = await buildBooster(await remoteCards, cardsByRarity);
      allCards.push(cards);
      console.log(cards.map((it) => it.name));
      const output = createBoosterFileContent(cards);
      const filename = `mtg-booster-${index}.html`;
      genFiles.push(filename);
      await Deno.writeTextFile(filename, output);
    }

    function buildBooster(allCards, cardsByRarity) {
      const getRandomFromArray = (arr) => arr[Math.floor(Math.random() * arr.length)];

      function getRandomByRarity(cardsByRarity, rarity) {
        return cardsByRarity[rarity][
          Math.floor(Math.random() * cardsByRarity[rarity].length)
        ];
      }

      const findBasicLands = (cards) => cards
        .filter((it) => it.isBasicLand);

      return [
        Array(10).fill(0).map(() => getRandomByRarity(cardsByRarity, "common")),
        Array(3).fill(0).map(() => getRandomByRarity(cardsByRarity, "uncommon")),
        [
          Math.floor(Math.random() * 8) === 0
            ? getRandomByRarity(cardsByRarity, "mythic")
            : getRandomByRarity(cardsByRarity, "rare"),
        ],
        [getRandomFromArray(findBasicLands(allCards))],
      ].flatMap((it) => it);
    }
  }

  async function writeManaGroupedPages(cardsByMana) {
    for (const key in cardsByMana) {
      if (Object.hasOwnProperty.call(cardsByMana, key)) {
        const element = cardsByMana[key];
        const output = createBoosterFileContent(element);
        const filename = `mtg-booster-filtered-${key}.html`;
        genFiles.push(filename);
        await Deno.writeTextFile(filename, output);
      }
    }
  }
}

async function writePricePage(allCards, genFiles) {
  const cardsByPrice = allCards.flat().sort((a, b) => {
    if (a["price"] > b["price"]) {
      return -1;
    } else if (a["price"] < b["price"]) {
      return 1;
    } else {
      return 0;
    }
  });
  const output = `

  ${cardsByPrice.map((it) => `<a href="${it.scryfall_uri}"><div>${it.name}: ${it.price}</div></a>`).join("\n")}

  `;
  const filename = `mtg-price.html`;
  genFiles.push(filename);
  await Deno.writeTextFile(filename, output);
}

const uniq = (value, index, self) => self.indexOf(value) === index;

async function writeIndexFile(cardsByMana, numBoosters, genFiles) {
  const filename = "index.html";
  const output = createIndexFileContent(cardsByMana, numBoosters);
  genFiles.push(filename);
  await Deno.writeTextFile(filename, output);

  function createIndexFileContent(cardsByMana, numBoosters) {
    const lines = []
    for (let index = 0; index < numBoosters; index++) {
      lines.push(`<a href="./mtg-booster-${index}.html"><div>Booster #${index}</div></a>`)
    }
    lines.push('
')
    const keys = []
    for (const key in cardsByMana) {
      keys.push(key)
    }
    keys.sort().forEach(key => {
      if (Object.hasOwnProperty.call(cardsByMana, key)) {
        const element = cardsByMana[key];
        lines.push(`<a href="./mtg-booster-filtered-${key}.html"><div>${key}: <strong>${element.length}</strong> cards</div></a>`)
      }
    })
    lines.push('
')
    lines.push(`<a href="./mtg-price.html"><div>Cards by price</a>`)
    lines.push(`<a href="./mtg-all-cards.html"><div>All cards</a>`)
    return `

  ${lines.flat().join("\n")}

`
  }
}

function createBoosterFileContent(cards) {
  return `

  ${cards.map((it) => `<a href="${it.scryfall_uri}"><img src="${it.image_url}"/></a>`
  ).join("\n")}

`;
}

<|endoftext|>


<commit_before>$(function(){
    $('#map_layer_toggle').on('click', function(e){
        e.preventDefault();
        var $t = $(this), text = $t.text();
        if (text == translation_strings.map_map) {
            $t.text(translation_strings.map_satellite);
            fixmystreet.map.setBaseLayer(fixmystreet.map.layers[1]);
        } else {
            $t.text(translation_strings.map_map);
            fixmystreet.map.setBaseLayer(fixmystreet.map.layers[0]);
        }
    });

/*    window.setTimeout(function(){
        if (typeof fixmystreet_google_default === 'undefined') {
            $('#map_layer_toggle').click();
        }
    }, 5000);*/

});

function set_map_config(perm) {
    var permalink_id;
    if ($('#map_permalink').length) {
        permalink_id = 'map_permalink';
    }

    fixmystreet.controls = [
        new OpenLayers.Control.ArgParser(),
        new OpenLayers.Control.Navigation(),
        new OpenLayers.Control.PermalinkFMS(permalink_id),
        new OpenLayers.Control.PanZoomFMS({id: 'fms_pan_zoom' })
    ];

    fixmystreet.map_type = OpenLayers.Layer.Google;
    fixmystreet.map_options = {
        zoomDuration: 10
    };

    fixmystreet.layer_options = [
        { type: google.maps.MapTypeId.HYBRID },
        {},
    ];
}

<commit_msg>Fix maps issue<commit_after>$(function(){
    $('#map_layer_toggle').on('click', function(e){
        e.preventDefault();
        var $t = $(this), text = $t.text();
        if (text == translation_strings.map_map) {
            $t.text(translation_strings.map_satellite);
            fixmystreet.map.setBaseLayer(fixmystreet.map.layers[1]);
        } else {
            $t.text(translation_strings.map_map);
            fixmystreet.map.setBaseLayer(fixmystreet.map.layers[0]);
        }
    });

    window.setTimeout(function(){
        if (typeof fixmystreet_google_default === 'undefined') {
            $('#map_layer_toggle').click();
        }
    }, 2000);

});

function set_map_config(perm) {
    var permalink_id;
    if ($('#map_permalink').length) {
        permalink_id = 'map_permalink';
    }

    fixmystreet.controls = [
        new OpenLayers.Control.ArgParser(),
        new OpenLayers.Control.Navigation(),
        new OpenLayers.Control.PermalinkFMS(permalink_id),
        new OpenLayers.Control.PanZoomFMS({id: 'fms_pan_zoom' })
    ];

    fixmystreet.map_type = OpenLayers.Layer.Google;
    fixmystreet.map_options = {
        zoomDuration: 10
    };

    fixmystreet.layer_options = [
        { type: google.maps.MapTypeId.HYBRID },
        {},
    ];
}

<|endoftext|>


<commit_before>import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import queensReducer from 'reducers';
import App from 'components/App';
import { loadState, saveState } from 'utils/localStorage';
import rootSaga from 'sagas';
import 'global-styles';

const localState = loadState();

const sagaMiddleware = createSagaMiddleware();

const store = createStore(queensReducer, localState, applyMiddleware(sagaMiddleware));

sagaMiddleware.run(rootSaga);

store.subscribe(() => {
  saveState(store.getState());
});

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('app'),
);

module.hot.accept();
<commit_msg>fix hot module error in prodction<commit_after>import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import queensReducer from 'reducers';
import App from 'components/App';
import { loadState, saveState } from 'utils/localStorage';
import rootSaga from 'sagas';
import 'global-styles';

const localState = loadState();

const sagaMiddleware = createSagaMiddleware();

const store = createStore(queensReducer, localState, applyMiddleware(sagaMiddleware));

sagaMiddleware.run(rootSaga);

store.subscribe(() => {
  saveState(store.getState());
});

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('app'),
);

if (process.env.NODE_ENV !== 'production') {
  module.hot.accept();
}
<|endoftext|>


<commit_before>function initMap () {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {lat: 45.5231, lng: -122.6765},
    //the starting center point before the user inputs a specific address
    //minZoom: 10,//minimum zoom level that will be displayed. It will be a number without the quotes.
    //maxZoom: 20,//maximum zoom level that will be displayed. It will be a number without the quotes.
    mapTypeId: 'roadmap',
    fullscreenControl: true
  });
  //pulls the geocoder and declares a new goecoding instance
  var geocoder = new google.maps.Geocoder();

  document.getElementById('submit').addEventListener('click', function() {
    geocodeAddress(geocoder, map);
  });
};

function geocodeAddress(geocoder, resultsMap) {
  var address = $('#street_address').val() + $('#zip').val();
  console.log(address);
  //grabbing the specified address the user has given
  geocoder.geocode({'address': address},
  function(results, status) {
  //turning the address into lat/long for google to render onto the map. Making sure the status is okay
    if (status === 'OK') {
      resultsMap.setCenter(results[0].geometry.location);
      //set the center for the speicified address
      var marker = new google.maps.Marker({
        map: resultsMap,
        position: results[0].geometry.location
      });
      //make a new marker for the speicified address
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

var script = document.createElement('script');
script.src = //whatever the path is to grab the bike stands json data
  document.getElementsByTagName('head')[0].appendChild(script); //requests JSONP directly from the biketown servers by appending a script tag to the head of the document
window.markBikeStands = function(results) {
    //results are the bike stands
    //looping through the results array (bikestand objects) and placing a marker for each one
  for (var i = 0; i < results.features.length; i++) {
    var coords = results.features[i].geometry.coordinates;
    var latLng = new google.maps.LatLng(coords[1], coords[0]);
    var marker = new google.maps.Marker({
      position: latLng, //sets position of the marker
      map: map //we are adding to the map that has already been made
    });
  };
};
<commit_msg>didn't make any changes, was trying to test making the bike stand markers<commit_after>function initMap () {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {lat: 45.5231, lng: -122.6765},
    //the starting center point before the user inputs a specific address
    //minZoom: 10,//minimum zoom level that will be displayed. It will be a number without the quotes.
    //maxZoom: 20,//maximum zoom level that will be displayed. It will be a number without the quotes.
    mapTypeId: 'roadmap',
    fullscreenControl: true
  });
  //pulls the geocoder and declares a new goecoding instance
  var geocoder = new google.maps.Geocoder();

  document.getElementById('submit').addEventListener('click', function() {
    geocodeAddress(geocoder, map);
  });
};

function geocodeAddress(geocoder, resultsMap) {
  var address = $('#street_address').val() + $('#zip').val();
  console.log(address);
  //grabbing the specified address the user has given
  geocoder.geocode({'address': address},
  function(results, status) {
  //turning the address into lat/long for google to render onto the map. Making sure the status is okay
    if (status === 'OK') {
      resultsMap.setCenter(results[0].geometry.location);
      //set the center for the speicified address
      var marker = new google.maps.Marker({
        map: resultsMap,
        position: results[0].geometry.location
      });
      //make a new marker for the speicified address
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

/*var script = document.createElement('script');
script.src = //whatever the path is to grab the bike stands json data
  document.getElementsByTagName('head')[0].appendChild(script); //requests JSONP directly from the biketown servers by appending a script tag to the head of the document
window.markBikeStands = function(results) {
    //results are the bike stands
    //looping through the results array (bikestand objects) and placing a marker for each one
  for (var i = 0; i < results.features.length; i++) {
    var coords = results.features[i].geometry.coordinates;
    var latLng = new google.maps.LatLng(coords[1], coords[0]);
    var marker = new google.maps.Marker({
      position: latLng, //sets position of the marker
      map: map //we are adding to the map that has already been made
    });
  };
};*/
<|endoftext|>


<commit_before>function gui(data_source){
    var width = 1280,
    height = 1280;
    var radius = 8;
    var color = d3.scale.category20();

    var svg = d3.select("#topology").append("svg:svg")
	.attr("width", width)
	.attr("height", height);

    var force = d3.layout.force()
	.charge(-500)
	.linkDistance(100)
	.size([width, height]);

    var path = svg.selectAll("path");
    var circle = svg.selectAll("circle");
    var text = svg.selectAll("g");
    var node_drag = d3.behavior.drag()
        .on("dragstart", dragstart)
        .on("drag", dragmove)
        .on("dragend", dragend);

    d3.json(data_source, init);

/* For debugging
    $("#more").click( function() {
        $.ajax({
	    url: 'http://gui.onlab.us:8080/topology_more',
	    success: function(json) {
		update(json);
	    },
	    dataType: "json"
        });
    });
    $("#less").click( function() {
        $.ajax({
	    url: 'http://gui.onlab.us:8080/topology_less',
	    success: function(json) {
		update(json);
	    },
	    dataType: "json"
        });
    });
*/

    function compare_link (a, b){
        if (a.source > b.source) {return 1;}
        else if (a.source < b.source) {return -1;}
        else {
            if (a.target > b.target) {return 1 ;}
            if (a.target < b.target) {return -1;}
            else {return 0;}
        }
    }

    function init(json){
        nodes = force.nodes();
        links = force.links();

	json.nodes.forEach(function(item) {
            nodes.push(item);
	});
	json.links.forEach(function(item) {
            links.push(item);
	});

        links.sort(compare_link);
        for (var i=1; i<links.length; i++) {
          if (links[i].source == links[i-1].source &&
            links[i].target == links[i-1].target) {
            links[i].linknum = links[i-1].linknum + 1;
          }
          else {
	      links[i].linknum = 1;
	  };
        };
	init_draw(nodes, links);
    }

    /* Return nodes that is not in the current list of nodes */
    Array.prototype.node_diff = function(arr) {
	return this.filter(function(i) {
	    for (var j = 0; j < arr.length ; j++) {
		if (arr[j].name === i.name)
		    return false;
	    }
	    return true;
	});
    };

    /* Return removed links */
    function gone_links (json, links, gone) {
	for (var i = 0; i < links.length ; i ++){
	    var found = 0;
	    for (var j = 0; j < json.links.length ; j ++){
		if (links[i].source.name == json.nodes[json.links[j].source].name &&
		    links[i].target.name == json.nodes[json.links[j].target].name ){
		    found = 1;
		    break;
		}
	    }
	    if ( found == 0 ){
		gone.push(links[i]);
	    }
	}
	return gone;
    }

    /* Return added links */
    function added_links (json, links, added) {
	for (var j = 0; j < json.links.length ; j ++){
	    var found = 0;
	    for (var i = 0; i < links.length ; i ++){
		if (links[i].source.name == json.nodes[json.links[j].source].name &&
		    links[i].target.name == json.nodes[json.links[j].target].name ){
		    found = 1;
		    break;
		}
	    }
	    if ( found == 0 ){
		added.push(json.links[j]);
	    }
	}
	return added;
    }

    function dragstart(d, i) {
        force.stop() // stops the force auto positioning before you start dragging
    }

    function dragmove(d, i) {
        d.px += d3.event.dx;
        d.py += d3.event.dy;
        d.x += d3.event.dx;
        d.y += d3.event.dy;
        tick(); // this is the key to make it work together with updating both px,py,x,y on d !
    }

    function dragend(d, i) {
        d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        tick();
        force.resume();
    }

    /* check if toplogy has changed and update node[] and link[] accordingly */
    function cdiff(json) {
        var changed = false;

	var n_adds = json.nodes.node_diff(nodes);
        var n_rems = nodes.node_diff(json.nodes);
        for (var i = 0; i < n_adds.length; i++) {
	    nodes.push(n_adds[i]);
	    changed = true;
        }
        for (var i = 0; i < n_rems.length; i++) {
	    for (var j = 0; j < nodes.length; j++) {
		if ( nodes[j].name == n_rems[i].name ){
		    nodes.splice(j,1);
		    changed = true;
		    break;
		}
	    }
        }
        var l_adds = [];
        var l_rems = [];
	l_adds = added_links(json, links, l_adds);
        l_rems = gone_links(json, links, l_rems);
        for (var i = 0; i < l_rems.length ; i++) {
	    for (var j = 0; j < links.length; j++) {
                if (links[j].source.name == l_rems[i].source.name &&
		    links[j].target.name == l_rems[i].target.name) {
		    links.splice(j,1);
		    changed = true;
		    break;
                }
	    }
        }
	// Sorce/target of an element of l_adds[] are corresponding to the index of json.node[]
	// which is different from the index of node[] (new nodes are always added to the last)
	// So update soure/target node indexes of l_add[] need to be fixed to point to the proper
	// node in node[];
        for (var i = 0; i < l_adds.length; i++) {
	    for (var j = 0; j < nodes.length; j++) {
		if ( json.nodes[l_adds[i].source].name == nodes[j].name ){
		    l_adds[i].source = j;
		    break;
		}
	    }
	    for (var j = 0; j < nodes.length; j++) {
		if ( json.nodes[l_adds[i].target].name == nodes[j].name ){
		    l_adds[i].target = j;
		    break;
		}
	    }
	    links.push(l_adds[i]);
	    changed = true;
        }

	// Update "group" attribute of nodes
	for (var i = 0; i < nodes.length; i++) {
            for (var j = 0; j < json.nodes.length; j++) {
		if ( nodes[i].name == json.nodes[j].name ){
		    if (nodes[i].group != json.nodes[j].group){
			nodes[i].group = json.nodes[j].group;
			changed = true;
		    }
		}
	    }
	}
	for (var i = 0; i < links.length; i++) {
            for (var j = 0; j < json.links.length; j++) {
		if (links[i].target.name == json.nodes[json.links[j].target].name &&
		    links[i].source.name == json.nodes[json.links[j].source].name ){
		    if (links[i].type != json.links[j].type){
			links[i].type = json.links[j].type;
			changed = true;
		    }
		}
	    }
	}
	return changed
    }

    function draw(force, path, circle, text){
	force.stop();
        path.enter().append("svg:path")
	    .attr("class", function(d) { return "link"; })
	    .attr("marker-end", function(d) {
		if(d.type == 1){
		    return "url(#TriangleRed)";
		} else {
		    return "url(#Triangle)";
		}
	    });

        circle.enter().append("svg:circle")
	    .attr("r", function(d) {
		if (d.group == 1000){
		    return radius/2;
		}else{
		    return radius;
		}
	    })
	    .call(node_drag);
//            .call(force.drag);

	text.enter().append("svg:text")
	    .attr("x", radius)
	    .attr("y", ".31em")
	    .text(function(d) {
		l=d.name.split(":").length
		return d.name.split(":")[l-3] + ":" + d.name.split(":")[l-2] + ":" + d.name.split(":")[l-1]
	    });

        circle.append("title")
	    .text(function(d) { return d.name; });

	circle.attr("fill", function(d) {
	    if (d.group == 1){return "red";}
	    else if (d.group == 2){return "blue";}
	    else if (d.group == 3){return "green";}
	    else if (d.group == 4){return "orange";}
	    else if (d.group == 1000){return "black";}
	    else{ return "gray"; }
	});

	path.attr("stroke", function(d) {
	    if(d.type == 1){
		return "red"
	    } else {
		return "black"
	    }
	}).attr("stroke-width", function(d) {
	    if(d.type == 1){
		return "2px";
	    } else {
		return "1.5px";
	    }
	}).attr("marker-end", function(d) {
	    if(d.type == 1){
		return "url(#TriangleRed)";
	    } else {
		return "url(#Triangle)";
	    }
	});

	path.exit().remove();
        circle.exit().remove();
        text.exit().remove();

	force.on("tick", tick);
        force.start();

    }

    function update(json) {
	var changed = cdiff(json);

	console.log("changed? " + changed);
        path = svg.selectAll("path").data(links)
        circle = svg.selectAll("circle").data(nodes);
	text = svg.selectAll("text").data(nodes);

	console.log(path)
	if (changed){

	    draw(force, path, circle, text);
	}
    }

    function init_draw(nodes, links){
        path = svg.append("svg:g").selectAll("path").data(links);
        circle = svg.append("svg:g").selectAll("circle").data(nodes);
	text = svg.append("svg:g").selectAll("text").data(nodes);

	draw(force, path, circle, text);

	setInterval(function() {
            $.ajax({
		url: data_source,
		success: function(json) {
		    update(json)
		},
		dataType: "json"
            });
	}, 3000);
    }
    function tick() {
	path.attr("d", function(d) {
	    var dx = d.target.x - d.source.x,
	    dy = d.target.y - d.source.y,
	    dr = 1/d.linknum;  //linknum is defined above
	    dr = 0;  // 0 for direct line
	    return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
	});
	path.attr("stroke", function(d) {
	    if(d.type == 1){
		return "red"
	    } else {
		return "black"
	    }
	}).attr("stroke-width", function(d) {
	    if(d.type == 1){
		return "3px";
	    } else {
		return "1.5px";
	    }
	}).attr("marker-end", function(d) {
	    if(d.type == 1){
		return "url(#TriangleRed)";
	    } else {
		return "url(#Triangle)";
	    }
	});

//	circle.attr("cx", function(d) { return d.x; }).attr("cy", function(d) { return d.y; });
	circle.attr("transform", function(d) {
	    x = Math.max(radius, Math.min(width - radius, d.x));
	    y = Math.max(radius, Math.min(height - radius, d.y));
//	    return "translate(" + d.x + "," + d.y + ")";
	    return "translate(" + x + "," + y + ")";
	})

	circle.attr("fill", function(d) {
	    ;	    if (d.group == 1){return "red";}
	    else if (d.group == 2){return "blue";}
	    else if (d.group == 3){return "green";}
	    else if (d.group == 4){return "orange";}
	    else if (d.group == 1000){return "black";}
	    else{ return "gray"; }
	});
//	text.attr("x", function(d) { return d.x; }).attr("y", function(d) { return d.y; });
	text.attr("transform", function(d) {
	    return "translate(" + d.x + "," + d.y + ")";
	});
    }
}

<commit_msg>change to show last 2 bytes of dpid in GUI<commit_after>function gui(data_source){
    var width = 1280,
    height = 1280;
    var radius = 8;
    var color = d3.scale.category20();

    var svg = d3.select("#topology").append("svg:svg")
	.attr("width", width)
	.attr("height", height);

    var force = d3.layout.force()
	.charge(-500)
	.linkDistance(100)
	.size([width, height]);

    var path = svg.selectAll("path");
    var circle = svg.selectAll("circle");
    var text = svg.selectAll("g");
    var node_drag = d3.behavior.drag()
        .on("dragstart", dragstart)
        .on("drag", dragmove)
        .on("dragend", dragend);

    d3.json(data_source, init);

/* For debugging
    $("#more").click( function() {
        $.ajax({
	    url: 'http://gui.onlab.us:8080/topology_more',
	    success: function(json) {
		update(json);
	    },
	    dataType: "json"
        });
    });
    $("#less").click( function() {
        $.ajax({
	    url: 'http://gui.onlab.us:8080/topology_less',
	    success: function(json) {
		update(json);
	    },
	    dataType: "json"
        });
    });
*/

    function compare_link (a, b){
        if (a.source > b.source) {return 1;}
        else if (a.source < b.source) {return -1;}
        else {
            if (a.target > b.target) {return 1 ;}
            if (a.target < b.target) {return -1;}
            else {return 0;}
        }
    }

    function init(json){
        nodes = force.nodes();
        links = force.links();

	json.nodes.forEach(function(item) {
            nodes.push(item);
	});
	json.links.forEach(function(item) {
            links.push(item);
	});

        links.sort(compare_link);
        for (var i=1; i<links.length; i++) {
          if (links[i].source == links[i-1].source &&
            links[i].target == links[i-1].target) {
            links[i].linknum = links[i-1].linknum + 1;
          }
          else {
	      links[i].linknum = 1;
	  };
        };
	init_draw(nodes, links);
    }

    /* Return nodes that is not in the current list of nodes */
    Array.prototype.node_diff = function(arr) {
	return this.filter(function(i) {
	    for (var j = 0; j < arr.length ; j++) {
		if (arr[j].name === i.name)
		    return false;
	    }
	    return true;
	});
    };

    /* Return removed links */
    function gone_links (json, links, gone) {
	for (var i = 0; i < links.length ; i ++){
	    var found = 0;
	    for (var j = 0; j < json.links.length ; j ++){
		if (links[i].source.name == json.nodes[json.links[j].source].name &&
		    links[i].target.name == json.nodes[json.links[j].target].name ){
		    found = 1;
		    break;
		}
	    }
	    if ( found == 0 ){
		gone.push(links[i]);
	    }
	}
	return gone;
    }

    /* Return added links */
    function added_links (json, links, added) {
	for (var j = 0; j < json.links.length ; j ++){
	    var found = 0;
	    for (var i = 0; i < links.length ; i ++){
		if (links[i].source.name == json.nodes[json.links[j].source].name &&
		    links[i].target.name == json.nodes[json.links[j].target].name ){
		    found = 1;
		    break;
		}
	    }
	    if ( found == 0 ){
		added.push(json.links[j]);
	    }
	}
	return added;
    }

    function dragstart(d, i) {
        force.stop() // stops the force auto positioning before you start dragging
    }

    function dragmove(d, i) {
        d.px += d3.event.dx;
        d.py += d3.event.dy;
        d.x += d3.event.dx;
        d.y += d3.event.dy;
        tick(); // this is the key to make it work together with updating both px,py,x,y on d !
    }

    function dragend(d, i) {
        d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        tick();
        force.resume();
    }

    /* check if toplogy has changed and update node[] and link[] accordingly */
    function cdiff(json) {
        var changed = false;

	var n_adds = json.nodes.node_diff(nodes);
        var n_rems = nodes.node_diff(json.nodes);
        for (var i = 0; i < n_adds.length; i++) {
	    nodes.push(n_adds[i]);
	    changed = true;
        }
        for (var i = 0; i < n_rems.length; i++) {
	    for (var j = 0; j < nodes.length; j++) {
		if ( nodes[j].name == n_rems[i].name ){
		    nodes.splice(j,1);
		    changed = true;
		    break;
		}
	    }
        }
        var l_adds = [];
        var l_rems = [];
	l_adds = added_links(json, links, l_adds);
        l_rems = gone_links(json, links, l_rems);
        for (var i = 0; i < l_rems.length ; i++) {
	    for (var j = 0; j < links.length; j++) {
                if (links[j].source.name == l_rems[i].source.name &&
		    links[j].target.name == l_rems[i].target.name) {
		    links.splice(j,1);
		    changed = true;
		    break;
                }
	    }
        }
	// Sorce/target of an element of l_adds[] are corresponding to the index of json.node[]
	// which is different from the index of node[] (new nodes are always added to the last)
	// So update soure/target node indexes of l_add[] need to be fixed to point to the proper
	// node in node[];
        for (var i = 0; i < l_adds.length; i++) {
	    for (var j = 0; j < nodes.length; j++) {
		if ( json.nodes[l_adds[i].source].name == nodes[j].name ){
		    l_adds[i].source = j;
		    break;
		}
	    }
	    for (var j = 0; j < nodes.length; j++) {
		if ( json.nodes[l_adds[i].target].name == nodes[j].name ){
		    l_adds[i].target = j;
		    break;
		}
	    }
	    links.push(l_adds[i]);
	    changed = true;
        }

	// Update "group" attribute of nodes
	for (var i = 0; i < nodes.length; i++) {
            for (var j = 0; j < json.nodes.length; j++) {
		if ( nodes[i].name == json.nodes[j].name ){
		    if (nodes[i].group != json.nodes[j].group){
			nodes[i].group = json.nodes[j].group;
			changed = true;
		    }
		}
	    }
	}
	for (var i = 0; i < links.length; i++) {
            for (var j = 0; j < json.links.length; j++) {
		if (links[i].target.name == json.nodes[json.links[j].target].name &&
		    links[i].source.name == json.nodes[json.links[j].source].name ){
		    if (links[i].type != json.links[j].type){
			links[i].type = json.links[j].type;
			changed = true;
		    }
		}
	    }
	}
	return changed
    }

    function draw(force, path, circle, text){
	force.stop();
        path.enter().append("svg:path")
	    .attr("class", function(d) { return "link"; })
	    .attr("marker-end", function(d) {
		if(d.type == 1){
		    return "url(#TriangleRed)";
		} else {
		    return "url(#Triangle)";
		}
	    });

        circle.enter().append("svg:circle")
	    .attr("r", function(d) {
		if (d.group == 1000){
		    return radius/2;
		}else{
		    return radius;
		}
	    })
	    .call(node_drag);
//            .call(force.drag);

	text.enter().append("svg:text")
	    .attr("x", radius)
	    .attr("y", ".31em")
	    .text(function(d) {
		l=d.name.split(":").length
		return d.name.split(":")[l-2] + ":" + d.name.split(":")[l-1]
	    });

        circle.append("title")
	    .text(function(d) { return d.name; });

	circle.attr("fill", function(d) {
	    if (d.group == 1){return "red";}
	    else if (d.group == 2){return "blue";}
	    else if (d.group == 3){return "green";}
	    else if (d.group == 4){return "orange";}
	    else if (d.group == 1000){return "black";}
	    else{ return "gray"; }
	});

	path.attr("stroke", function(d) {
	    if(d.type == 1){
		return "red"
	    } else {
		return "black"
	    }
	}).attr("stroke-width", function(d) {
	    if(d.type == 1){
		return "2px";
	    } else {
		return "1.5px";
	    }
	}).attr("marker-end", function(d) {
	    if(d.type == 1){
		return "url(#TriangleRed)";
	    } else {
		return "url(#Triangle)";
	    }
	});

	path.exit().remove();
        circle.exit().remove();
        text.exit().remove();

	force.on("tick", tick);
        force.start();

    }

    function update(json) {
	var changed = cdiff(json);

	console.log("changed? " + changed);
        path = svg.selectAll("path").data(links)
        circle = svg.selectAll("circle").data(nodes);
	text = svg.selectAll("text").data(nodes);

	console.log(path)
	if (changed){

	    draw(force, path, circle, text);
	}
    }

    function init_draw(nodes, links){
        path = svg.append("svg:g").selectAll("path").data(links);
        circle = svg.append("svg:g").selectAll("circle").data(nodes);
	text = svg.append("svg:g").selectAll("text").data(nodes);

	draw(force, path, circle, text);

	setInterval(function() {
            $.ajax({
		url: data_source,
		success: function(json) {
		    update(json)
		},
		dataType: "json"
            });
	}, 3000);
    }
    function tick() {
	path.attr("d", function(d) {
	    var dx = d.target.x - d.source.x,
	    dy = d.target.y - d.source.y,
	    dr = 1/d.linknum;  //linknum is defined above
	    dr = 0;  // 0 for direct line
	    return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
	});
	path.attr("stroke", function(d) {
	    if(d.type == 1){
		return "red"
	    } else {
		return "black"
	    }
	}).attr("stroke-width", function(d) {
	    if(d.type == 1){
		return "3px";
	    } else {
		return "1.5px";
	    }
	}).attr("marker-end", function(d) {
	    if(d.type == 1){
		return "url(#TriangleRed)";
	    } else {
		return "url(#Triangle)";
	    }
	});

//	circle.attr("cx", function(d) { return d.x; }).attr("cy", function(d) { return d.y; });
	circle.attr("transform", function(d) {
	    x = Math.max(radius, Math.min(width - radius, d.x));
	    y = Math.max(radius, Math.min(height - radius, d.y));
//	    return "translate(" + d.x + "," + d.y + ")";
	    return "translate(" + x + "," + y + ")";
	})

	circle.attr("fill", function(d) {
	    ;	    if (d.group == 1){return "red";}
	    else if (d.group == 2){return "blue";}
	    else if (d.group == 3){return "green";}
	    else if (d.group == 4){return "orange";}
	    else if (d.group == 1000){return "black";}
	    else{ return "gray"; }
	});
//	text.attr("x", function(d) { return d.x; }).attr("y", function(d) { return d.y; });
	text.attr("transform", function(d) {
	    return "translate(" + d.x + "," + d.y + ")";
	});
    }
}

<|endoftext|>


<commit_before>/* globals process */

import path from 'path'
import chokidar from 'chokidar'

import globBase from './lib/glob-base'
import mirror from './lib/mirror'
import trimQuotes from './lib/trim-quotes'
import { watcherCopy, watcherDestroy, watcherError } from './lib/watcher'

const defaults = {
  watch: false,
  delete: true,
  deleteInitial: false,
  depth: Infinity,
}

const syncGlob = (sources, target, options, notify) => {
  if (!Array.isArray(sources)) {
    // eslint-disable-next-line no-param-reassign
    sources = [sources]
  }
  // eslint-disable-next-line no-param-reassign
  sources = sources.map(trimQuotes)
  // eslint-disable-next-line no-param-reassign
  options = {
    ...defaults,
    base: globBase(sources),
    ...options,
  }

  if (typeof options.depth !== 'number' || isNaN(options.depth)) {
    notify('error', 'Expected valid number for option "depth"')
    return false
  }

  if (options.transform) {
    let transformPath = options.transform

    try {
      require.resolve(transformPath)
    } catch (e) {
      transformPath = path.join(process.cwd(), transformPath)
    }

    // eslint-disable-next-line
    options.transform = require(transformPath)
  }

  // Initial mirror
  const mirrored = mirror(sources, target, options, notify, 0)
  let watcher

  if (!mirrored) {
    notify('error', 'Initial mirror failed')
    return false
  }

  if (options.watch) {
    // Watcher to keep in sync from that
    watcher = chokidar.watch(sources, {
      persistent: true,
      depth: options.depth,
      ignoreInitial: true,
    })
      .on('ready', notify.bind(undefined, 'watch', sources))
      .on('add', watcherCopy(target, options, notify))
      .on('addDir', watcherCopy(target, options, notify))
      .on('change', watcherCopy(target, options, notify))
      .on('unlink', watcherDestroy(target, options, notify))
      .on('unlinkDir', watcherDestroy(target, options, notify))
      .on('error', watcherError(options, notify))

    process.on('SIGINT', stopWatching)
    process.on('SIGQUIT', stopWatching)
    process.on('SIGTERM', stopWatching)
  }

  return stopWatching

  function stopWatching() {
    if (watcher) {
      watcher.close()
      watcher = null
    }
  }
}

export default syncGlob
<commit_msg>log chokidar events too<commit_after>/* globals process */

import path from 'path'
import chokidar from 'chokidar'

import globBase from './lib/glob-base'
import mirror from './lib/mirror'
import trimQuotes from './lib/trim-quotes'
import { watcherCopy, watcherDestroy, watcherError } from './lib/watcher'

const defaults = {
  watch: false,
  delete: true,
  deleteInitial: false,
  depth: Infinity,
}

const syncGlob = (sources, target, options, notify) => {
  if (!Array.isArray(sources)) {
    // eslint-disable-next-line no-param-reassign
    sources = [sources]
  }
  // eslint-disable-next-line no-param-reassign
  sources = sources.map(trimQuotes)
  // eslint-disable-next-line no-param-reassign
  options = {
    ...defaults,
    base: globBase(sources),
    ...options,
  }

  if (typeof options.depth !== 'number' || isNaN(options.depth)) {
    notify('error', 'Expected valid number for option "depth"')
    return false
  }

  if (options.transform) {
    let transformPath = options.transform

    try {
      require.resolve(transformPath)
    } catch (e) {
      transformPath = path.join(process.cwd(), transformPath)
    }

    // eslint-disable-next-line
    options.transform = require(transformPath)
  }

  // Initial mirror
  const mirrored = mirror(sources, target, options, notify, 0)
  let watcher

  if (!mirrored) {
    notify('error', 'Initial mirror failed')
    return false
  }

  if (options.watch) {
    // Watcher to keep in sync from that
    watcher = chokidar.watch(sources, {
      persistent: true,
      depth: options.depth,
      ignoreInitial: true,
    })
      .on('ready', notify.bind(undefined, 'watch', sources))
      .on('add', watcherCopy(target, options, notify))
      .on('addDir', watcherCopy(target, options, notify))
      .on('change', watcherCopy(target, options, notify))
      .on('unlink', watcherDestroy(target, options, notify))
      .on('unlinkDir', watcherDestroy(target, options, notify))
      .on('error', watcherError(options, notify))
      .on('all', (...args) => {
        console.log(`***CHOKIDAR: ${args.join(', ')}***`)
      })

    process.on('SIGINT', stopWatching)
    process.on('SIGQUIT', stopWatching)
    process.on('SIGTERM', stopWatching)
  }

  return stopWatching

  function stopWatching() {
    if (watcher) {
      watcher.close()
      watcher = null
    }
  }
}

export default syncGlob
<|endoftext|>


<commit_before>var RhythmSample = {
  bpm:0,
  startTimer:0
};

RhythmSample.setBPM = function(b,startTime) {
  this.bpm = b;
  this.startTimer = startTime;
};

RhythmSample.play = function() {
  function playSound(buffer, time) {
    var source = context.createBufferSource();
    source.buffer = buffer;
    source.connect(context.destination);
    if (!source.start)
      source.start = source.noteOn;
    source.start(time);
  }

  var kick = BUFFERS.kick;
  var snare = BUFFERS.snare;
  var hihat = BUFFERS.hihat;
  var hey = BUFFERS.hey;

  // We'll start playing the rhythm 100 milliseconds from "now"
//  var startTime = context.currentTime + 0.100;
  var tempo = this.bpm; // BPM (beats per minute)
  var eighthNoteTime = (60 / tempo) / 2;
  var startTime = this.startTimer + ((60 / tempo));

  // Play 2 bars of the following:
  for (var bar = 0; bar < 1; bar++) {
    var time = startTime + bar * 8 * eighthNoteTime;
    // Play the bass (kick) drum on beats 1, 5
    playSound(hey, time);
    playSound(hey, time + 1 * eighthNoteTime);

  }
};
<commit_msg>speed<commit_after>var RhythmSample = {
  bpm:0,
  startTimer:0
};

RhythmSample.setBPM = function(b,startTime) {
  this.bpm = b;
  this.startTimer = startTime;
};

RhythmSample.play = function() {
  function playSound(buffer, time) {
    var source = context.createBufferSource();
    source.buffer = buffer;
    source.connect(context.destination);
    if (!source.start)
      source.start = source.noteOn;
    source.start(time);
  }

  var kick = BUFFERS.kick;
  var snare = BUFFERS.snare;
  var hihat = BUFFERS.hihat;
  var hey = BUFFERS.hey;

  // We'll start playing the rhythm 100 milliseconds from "now"
//  var startTime = context.currentTime + 0.100;
  var tempo = this.bpm; // BPM (beats per minute)
  var eighthNoteTime = (60 / tempo) / 2;
  var startTime = this.startTimer + ((60 / tempo));

  // Play 2 bars of the following:
  for (var bar = 0; bar < 1; bar++) {
    var time = startTime + bar * 8 * eighthNoteTime;
    // Play the bass (kick) drum on beats 1, 5
    playSound(hey, time);
    playSound(hey, time + 2 * eighthNoteTime);

  }
};
<|endoftext|>


<commit_before>'use strict';

var url          = require('url');
var path         = require('path');
var http         = require('http');
var fs           = require('fs');
var unzip        = require('unzip');
var postgresdb   = require('pg');
var ip           = require("ip");
var program      = require('commander');
var drivers      = new Object();
var connections  = new Object();
var express      = require('express')
var app          = express()
var timeout      = 0;
var init_drivers = false;
var port;
var hostaddress;
var typeOfSystem;
var centralHostAddress;
var centralHostPort;
var request      = require("request");
var toeval;
var open         = require('open');
var dbhelper     = require('../public/dbhelper');
var Gun          = require('gun');
var gun          = Gun({ file: 'data.json',
                          s3: {
                            key: '', // AWS Access Key
                            secret: '', // AWS Secret Token
                            bucket: '' // The bucket you want to save into
                          }
                        });
var parseSqlFn = require('node-sqlparser').parse;
var witheve = require("witheve");

path.join(__dirname, '../public/blockly/blockly_compressed.js')
path.join(__dirname, '../public/blockly/blocks_compressed.js')
path.join(__dirname, '../public/yazz_blockly_blocks.js')
path.join(__dirname, '../public/yazz_blockly_generator.js')
path.join(__dirname, '../public/yazz_blockly_output_code.js')
path.join(__dirname, '../public/blockly/msg/js/en.js')
path.join(__dirname, '../public/jquery-1.9.1.min.js')
path.join(__dirname, '../public/jquery.zoomooz.js')
path.join(__dirname, '../public/blockly_helper.js')
path.join(__dirname, '../public/blockly.png')
path.join(__dirname, '../public/polyfill.min.js')
path.join(__dirname, '../src/oracle.js')
path.join(__dirname, '../src/postgres.js')
path.join(__dirname, '../public/blockly_setup.js')
path.join(__dirname, '../public/tether.min.js')
path.join(__dirname, '../public/bootstrap.min.js')
path.join(__dirname, '../public/bootstrap.min.css')
path.join(__dirname, '../public/es6-shim.js')
path.join(__dirname, '../public/vue_app.css')
path.join(__dirname, '../public/dist/build.js')
//path.join(__dirname, '../oracle_driver.zip')
path.join(__dirname, '../public/sql.js')
path.join(__dirname, '../public/gosharedata_logo.PNG')
path.join(__dirname, '../public/favicon.ico')

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

program
  .version('0.0.1')
  .option('-t, --type [type]', 'Add the specified type of app [type]', 'client')
  .option('-p, --port [port]', 'Which port should I listen on? [port]', parseInt)
  .option('-h, --host [host]', 'Server address of the central host [host]', 'gosharedata.com')
  .option('-s, --hostport [hostport]', 'Server port of the central host [hostport]', parseInt)
  .parse(process.argv);

  port = program.port;
  if (!isNumber(port)) {port = 80;};
  typeOfSystem = program.type;
  centralHostAddress = program.host;
  centralHostPort = program.hostport;
  if (!isNumber(centralHostPort)) {centralHostPort = 80;};

  if (!(typeOfSystem == 'client' || typeOfSystem == 'server')) {
      console.log('-------* Invalid system type: ' + typeOfSystem);
      process.exit();
  };
  console.log('-------* System type: ' + typeOfSystem);
  console.log('-------* Port: ' + port);
  console.log('-------* Central host: ' + centralHostAddress);
  console.log('-------* Central host port: ' + centralHostPort);

console.dir ( ip.address() );

console.log('addr: '+ ip.address());
hostaddress = ip.address();

//------------------------------------------------------------
// wait three seconds for stuff to initialize
//------------------------------------------------------------
setTimeout(startServices, timeout);
console.log('Creating timeout: ' + timeout);

//------------------------------------------------------------
// wait three seconds for stuff to initialize
//------------------------------------------------------------
function startServices() {
  //
  // start the server
  //
  gun.wsp(app);

  dbhelper.setGunDB(gun)
  dbhelper.setGunDBClass(Gun)
  dbhelper.setSqlParseFn(parseSqlFn)
  //dbhelper.sql('select * from servertable where a.s = 1', null)
  //dbhelper.sql("SELECT age, name FROM Customers");
  dbhelper.realtimeSql("SELECT * FROM Customers where Age > 8");
//zzz
  dbhelper.realtimeSql("select * from db_connections where deleted != 'T'"
    ,function(results) {
        //console.log("select * from db_connections where deleted != 'T'")
        for (var i = 0 ; i < results.length ; i ++) {
            var conn = results[i]

            //console.log("    " + JSON.stringify(conn, null, 2))
            if (!connectionrows[conn.name]) {
              //data_connections_list.push(a);
              connectionrows[conn.name] = conn;
              //console.log(a);
              connections[conn.name] = conn;
            }
        }

    })

  //------------------------------------------------------------------------------
  // Show the default page
  //------------------------------------------------------------------------------
    app.get('/', function (req, res) {
      if (!init_drivers) {
        init_drivers = true;
        eval(toeval);
        if (drivers['oracle']['loadOnCondition']()) {
            drivers['oracle']['loadDriver']();
        };
        eval(pgeval);

      };

      if (typeOfSystem == 'client') {
          res.end(fs.readFileSync(path.join(__dirname, '../public/index.html')));
      }
      if (typeOfSystem == 'server') {
          res.end(fs.readFileSync(path.join(__dirname, '../public/index_server.html')));
      }
  })

app.use(express.static(path.join(__dirname, '../public/')))

//------------------------------------------------------------------------------
// Get the result of a SQL query
//------------------------------------------------------------------------------
  app.get('/getresult', function (req, res) {
    var queryData = url.parse(req.url, true).query;
    //console.log('request received source: ' + queryData.source);
    //console.log('request received SQL: ' + queryData.sql);
    if (connections[queryData.source]) {
        //console.log('query driver: ' + connections[queryData.source].driver);
        drivers[connections[queryData.source].driver]['get'](connections[queryData.source],queryData.sql,function(ordata) {
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end(JSON.stringify(ordata));
        });
    } else {
        console.log('query driver not found: ' + connections[queryData.source]);
    };
})

var requestClientInternalHostAddress = '';
var requestClientInternalPort        = -1;
var requestClientPublicIp            = '';
var requestClientPublicHostName      = '';

//------------------------------------------------------------------------------
// This is called by the central server to get the details of the last
// client that connected tp the central server
//------------------------------------------------------------------------------
app.get('/get_connect', function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(
            JSON.stringify(
                {
                    requestClientInternalHostAddress: requestClientInternalHostAddress
                    ,
                    requestClientInternalPort:        requestClientInternalPort
                    ,
                    requestClientPublicIp:            requestClientPublicIp
                    ,
                    requestClientPublicHostName:      requestClientPublicHostName
                    ,
                    version:      30
                }
          ));
})

//app.enable('trust proxy')

//------------------------------------------------------------------------------
// run on the central server only
//
// This is where the client sends its details to the central server
//------------------------------------------------------------------------------
app.get('/client_connect', function (req, res) {
    var queryData = url.parse(req.url, true).query;

    requestClientInternalHostAddress = req.query.requestClientInternalHostAddress;
    requestClientInternalPort        = req.query.requestClientInternalPort;
    requestClientPublicIp            = req.ip;
    //requestClientPublicHostName      = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    requestClientPublicHostName      = "req keys::" + Object.keys(req) + ", VIA::" + req.headers.via + ", raw::" + JSON.stringify(req.rawHeaders);

    console.log('Client attempting to connect from:');
    console.log('client internal host address:    ' + requestClientInternalHostAddress)
    console.log('client internal port:            ' + requestClientInternalPort)
    console.log('client public IP address:        ' + requestClientPublicIp)
    console.log('client public IP host name:      ' + requestClientPublicHostName)

    //TODO
    // add the host to a list here
})

//------------------------------------------------------------------------------
// start the web server
//------------------------------------------------------------------------------
app.listen(port, hostaddress, function () {
    console.log('GunDB listening on port ' + port + '!' + ' with /gun')
    console.log(typeOfSystem + ' started on port ' + port );
})

  //--------------------------------------------------------
  // open the app in a web browser
  //--------------------------------------------------------
  //open('http://' + hostaddress  + ":" + port);
  console.log('http://' + hostaddress  + ":" + port);

  //process.env['PATH'] = path.join(__dirname, '/instantclient') + ';' + process.env['PATH'];
  //var oracledb = require('oracledb');
  //console.log('Start oracle');

  //eval("oracledb= require('oracledb');");

  console.log('addr: '+ hostaddress + ":" + port);

  //console.log(toeval);
  //setTimeout(function(){eval(toeval)},1000);

  //  console.log('Done.');

  console.log("*********** CHECKING CONNECTIONS *****************8");
  var connectionrows        = new Object();
  /*gun.get("connections").map(function(a,b){
    delete a["_"];
    if (!connectionrows[a.id]) {
      //data_connections_list.push(a);
      connectionrows[a.id] = a;
      //console.log(a);
      connections[a.id] = a;
    }

},true);*/

    if (typeOfSystem == 'client') {
        var urlToConnectTo = "http://" + centralHostAddress + ":" + centralHostPort + '/client_connect';
        console.log('-------* urlToConnectTo: ' + urlToConnectTo);
        console.log('trying to connect to central server...');
        request({
              uri: urlToConnectTo,
              method: "GET",
              timeout: 10000,
              followRedirect: true,
              maxRedirects: 10,
              qs: {
                  requestClientInternalHostAddress: hostaddress
                  ,
                  requestClientInternalPort:        port
              }
            },
            function(error, response, body) {
                console.log(body);
            });
    }

    console.log("******************************ADDING DRIVERS*********************************")

    var pgeval = '(' + fs.readFileSync(path.join(__dirname, './postgres.js')).toString() + ')';
    drivers['postgres'] = eval( pgeval )
    addOrUpdateDriver('postgres', pgeval, drivers['postgres'])

    toeval =  '(' + fs.readFileSync(path.join(__dirname, './oracle.js')).toString() + ')';
    drivers['oracle']   = eval( toeval )
    addOrUpdateDriver('oracle',   toeval, drivers['oracle'])
    if (drivers['oracle'].loadOnCondition()) {
        drivers['oracle'].loadDriver()
    }

    var tdeval = '(' + fs.readFileSync(path.join(__dirname, './testdriver.js')).toString() + ')';
    drivers['TestDriver'] = eval(tdeval)
    addOrUpdateDriver('TestDriver', tdeval, drivers['TestDriver'])

    ////dbhelper.sql("insert into drivers (name,code,driver_type) values (?,?,?)",            ['a', 'b', 'c'])
    //dbhelper.sql("update drivers set type = '...2' where name = 'TestDriver'")
    //dbhelper.sql("select * from drivers where name = 'TestDriver' ")
    //dbhelper.sql("select * from drivers ")

    //console.log("************************************************ ")
    //console.log("******************************Doing Eve stuff ")
    //console.log("************************************************ ")
    let eve = new witheve.Program("program name");

    let inputs = [];
    //console.log(JSON.stringify(Object.keys(eve) , null, 2))
    var vv = 0
    /*setInterval(function() {
        console.log("--Tick ")
        let newinputs = [];
        witheve.appendAsEAVs(newinputs, {tag: "student", name: "Zubair " + vv});
        eve.inputEAVs(newinputs);
        vv ++
    }, 1000)

    eve.watch("Export information about students", function(arg) {
        console.log("--Eve Export information ")
      // search for records tagged student
      let student = arg.find("student");
      let eav = arg.lookup(student);
      return [
          // Add these attributes and values to the student, creating a diff to which we can react
          student.add(eav.attribute, eav.value)
      ];

    }).asDiffs(function(diff)  {
          console.log("--Eve in adDiffs ")
          for(let [e, a, v] of diff.adds) {
            console.log("--Eve add " + JSON.stringify(e , null, 2) + ", " + JSON.stringify(a , null, 2) + JSON.stringify(v , null, 2))
          }
          for(let [e, a, v] of diff.removes) {
              console.log("--Eve remove " + JSON.stringify(e , null, 2) + ", " + JSON.stringify(a , null, 2) + JSON.stringify(v , null, 2))
          }
        });;
        witheve.appendAsEAVs(inputs, {tag: "student", name: "Archibald"});
        witheve.appendAsEAVs(inputs, {tag: "student", name: "Zubair"});
        eve.inputEAVs(inputs);*/

    //console.log("************************************************ ")
    //console.log("******************************finished Eve stuff ")
    //console.log("************************************************ ")

function addOrUpdateDriver(name, code, theObject) {
    console.log("******************************addOrUpdateDriver ")
    console.log("       name = " + name)
    //console.log("       code = " + JSON.stringify(code , null, 2))
    var driverType = theObject.type;
    //console.log("******************************driver type= " + driverType)
    //console.log("******************************driver= " + JSON.stringify(theObject , null, 2))
    dbhelper.sql("select * from drivers where name = '" +  name +  "' ",
        function(records) {
            console.log("******************************records = " + records.length  )
            if(records.length > 0) {
                for (var record of records) {
                    dbhelper.sql("update drivers set code = ?  where name = '" + name + "'",  [code])
                    if (typeof driverType === 'string' || driverType instanceof String) {
                        console.log("******************************UPDATE DRIVER "+name)
                        //console.log("******************************record type = " + JSON.stringify(record.type , null, 2))
                        //console.log("******************************desired type = " + JSON.stringify(driverType , null, 2))
                        //console.log("******************************set driver type = " + JSON.stringify(driverType , null, 2))
                        //console.log("******************************for name = " + JSON.stringify(name , null, 2))
                        var sqlToRun = "update drivers set type = '" + driverType + "' where  name = '" + name + "'";

                        //console.log("******************************SQL  = " + JSON.stringify(sqlToRun , null, 2))
                        dbhelper.sql(sqlToRun, function(ack) {
                            //console.log("******************************SQL Done  = " + JSON.stringify(sqlToRun , null, 2))
                        })
                        //dbhelper.sql("update drivers set type = '...' where name = 'TestDriver'")
                    }
                }
            } else {
                console.log("******************************INSERT DRIVER "+name)
                dbhelper.sql("insert into drivers (name,code,type) values (?,?,?)",            [name, code, driverType])

            }
        })
}

//console.log("postgres.get = " + JSON.stringify(eval(pgeval) , null, 2))
//console.log("postgres.get = " + eval(pgeval).get)
}
<commit_msg>Force Oracle driver to load<commit_after>'use strict';

var url          = require('url');
var path         = require('path');
var http         = require('http');
var fs           = require('fs');
var unzip        = require('unzip');
var postgresdb   = require('pg');
var ip           = require("ip");
var program      = require('commander');
var drivers      = new Object();
var connections  = new Object();
var express      = require('express')
var app          = express()
var timeout      = 0;
var init_drivers = false;
var port;
var hostaddress;
var typeOfSystem;
var centralHostAddress;
var centralHostPort;
var request      = require("request");
var toeval;
var open         = require('open');
var dbhelper     = require('../public/dbhelper');
var Gun          = require('gun');
var gun          = Gun({ file: 'data.json',
                          s3: {
                            key: '', // AWS Access Key
                            secret: '', // AWS Secret Token
                            bucket: '' // The bucket you want to save into
                          }
                        });
var parseSqlFn = require('node-sqlparser').parse;
var witheve = require("witheve");

path.join(__dirname, '../public/blockly/blockly_compressed.js')
path.join(__dirname, '../public/blockly/blocks_compressed.js')
path.join(__dirname, '../public/yazz_blockly_blocks.js')
path.join(__dirname, '../public/yazz_blockly_generator.js')
path.join(__dirname, '../public/yazz_blockly_output_code.js')
path.join(__dirname, '../public/blockly/msg/js/en.js')
path.join(__dirname, '../public/jquery-1.9.1.min.js')
path.join(__dirname, '../public/jquery.zoomooz.js')
path.join(__dirname, '../public/blockly_helper.js')
path.join(__dirname, '../public/blockly.png')
path.join(__dirname, '../public/polyfill.min.js')
path.join(__dirname, '../src/oracle.js')
path.join(__dirname, '../src/postgres.js')
path.join(__dirname, '../public/blockly_setup.js')
path.join(__dirname, '../public/tether.min.js')
path.join(__dirname, '../public/bootstrap.min.js')
path.join(__dirname, '../public/bootstrap.min.css')
path.join(__dirname, '../public/es6-shim.js')
path.join(__dirname, '../public/vue_app.css')
path.join(__dirname, '../public/dist/build.js')
//path.join(__dirname, '../oracle_driver.zip')
path.join(__dirname, '../public/sql.js')
path.join(__dirname, '../public/gosharedata_logo.PNG')
path.join(__dirname, '../public/favicon.ico')

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

program
  .version('0.0.1')
  .option('-t, --type [type]', 'Add the specified type of app [type]', 'client')
  .option('-p, --port [port]', 'Which port should I listen on? [port]', parseInt)
  .option('-h, --host [host]', 'Server address of the central host [host]', 'gosharedata.com')
  .option('-s, --hostport [hostport]', 'Server port of the central host [hostport]', parseInt)
  .parse(process.argv);

  port = program.port;
  if (!isNumber(port)) {port = 80;};
  typeOfSystem = program.type;
  centralHostAddress = program.host;
  centralHostPort = program.hostport;
  if (!isNumber(centralHostPort)) {centralHostPort = 80;};

  if (!(typeOfSystem == 'client' || typeOfSystem == 'server')) {
      console.log('-------* Invalid system type: ' + typeOfSystem);
      process.exit();
  };
  console.log('-------* System type: ' + typeOfSystem);
  console.log('-------* Port: ' + port);
  console.log('-------* Central host: ' + centralHostAddress);
  console.log('-------* Central host port: ' + centralHostPort);

console.dir ( ip.address() );

console.log('addr: '+ ip.address());
hostaddress = ip.address();

//------------------------------------------------------------
// wait three seconds for stuff to initialize
//------------------------------------------------------------
setTimeout(startServices, timeout);
console.log('Creating timeout: ' + timeout);

//------------------------------------------------------------
// wait three seconds for stuff to initialize
//------------------------------------------------------------
function startServices() {
  //
  // start the server
  //
  gun.wsp(app);

  dbhelper.setGunDB(gun)
  dbhelper.setGunDBClass(Gun)
  dbhelper.setSqlParseFn(parseSqlFn)
  //dbhelper.sql('select * from servertable where a.s = 1', null)
  //dbhelper.sql("SELECT age, name FROM Customers");
  dbhelper.realtimeSql("SELECT * FROM Customers where Age > 8");
//zzz
  dbhelper.realtimeSql("select * from db_connections where deleted != 'T'"
    ,function(results) {
        //console.log("select * from db_connections where deleted != 'T'")
        for (var i = 0 ; i < results.length ; i ++) {
            var conn = results[i]

            //console.log("    " + JSON.stringify(conn, null, 2))
            if (!connectionrows[conn.name]) {
              //data_connections_list.push(a);
              connectionrows[conn.name] = conn;
              //console.log(a);
              connections[conn.name] = conn;
            }
        }

    })

  //------------------------------------------------------------------------------
  // Show the default page
  //------------------------------------------------------------------------------
    app.get('/', function (req, res) {
      if (!init_drivers) {
        init_drivers = true;
        eval(toeval);
        if (drivers['oracle']['loadOnCondition']()) {
            drivers['oracle']['loadDriver']();
        };
        eval(pgeval);

      };

      if (typeOfSystem == 'client') {
          res.end(fs.readFileSync(path.join(__dirname, '../public/index.html')));
      }
      if (typeOfSystem == 'server') {
          res.end(fs.readFileSync(path.join(__dirname, '../public/index_server.html')));
      }
  })

app.use(express.static(path.join(__dirname, '../public/')))

//------------------------------------------------------------------------------
// Get the result of a SQL query
//------------------------------------------------------------------------------
  app.get('/getresult', function (req, res) {
    var queryData = url.parse(req.url, true).query;
    //console.log('request received source: ' + queryData.source);
    //console.log('request received SQL: ' + queryData.sql);
    if (connections[queryData.source]) {
        //console.log('query driver: ' + connections[queryData.source].driver);
        drivers[connections[queryData.source].driver]['get'](connections[queryData.source],queryData.sql,function(ordata) {
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end(JSON.stringify(ordata));
        });
    } else {
        console.log('query driver not found: ' + connections[queryData.source]);
    };
})

var requestClientInternalHostAddress = '';
var requestClientInternalPort        = -1;
var requestClientPublicIp            = '';
var requestClientPublicHostName      = '';

//------------------------------------------------------------------------------
// This is called by the central server to get the details of the last
// client that connected tp the central server
//------------------------------------------------------------------------------
app.get('/get_connect', function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(
            JSON.stringify(
                {
                    requestClientInternalHostAddress: requestClientInternalHostAddress
                    ,
                    requestClientInternalPort:        requestClientInternalPort
                    ,
                    requestClientPublicIp:            requestClientPublicIp
                    ,
                    requestClientPublicHostName:      requestClientPublicHostName
                    ,
                    version:      30
                }
          ));
})

//app.enable('trust proxy')

//------------------------------------------------------------------------------
// run on the central server only
//
// This is where the client sends its details to the central server
//------------------------------------------------------------------------------
app.get('/client_connect', function (req, res) {
    var queryData = url.parse(req.url, true).query;

    requestClientInternalHostAddress = req.query.requestClientInternalHostAddress;
    requestClientInternalPort        = req.query.requestClientInternalPort;
    requestClientPublicIp            = req.ip;
    //requestClientPublicHostName      = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    requestClientPublicHostName      = "req keys::" + Object.keys(req) + ", VIA::" + req.headers.via + ", raw::" + JSON.stringify(req.rawHeaders);

    console.log('Client attempting to connect from:');
    console.log('client internal host address:    ' + requestClientInternalHostAddress)
    console.log('client internal port:            ' + requestClientInternalPort)
    console.log('client public IP address:        ' + requestClientPublicIp)
    console.log('client public IP host name:      ' + requestClientPublicHostName)

    //TODO
    // add the host to a list here
})

//------------------------------------------------------------------------------
// start the web server
//------------------------------------------------------------------------------
app.listen(port, hostaddress, function () {
    console.log('GunDB listening on port ' + port + '!' + ' with /gun')
    console.log(typeOfSystem + ' started on port ' + port );
})

  //--------------------------------------------------------
  // open the app in a web browser
  //--------------------------------------------------------
  //open('http://' + hostaddress  + ":" + port);
  console.log('http://' + hostaddress  + ":" + port);

  //process.env['PATH'] = path.join(__dirname, '/instantclient') + ';' + process.env['PATH'];
  //var oracledb = require('oracledb');
  //console.log('Start oracle');

  //eval("oracledb= require('oracledb');");

  console.log('addr: '+ hostaddress + ":" + port);

  //console.log(toeval);
  //setTimeout(function(){eval(toeval)},1000);

  //  console.log('Done.');

  console.log("*********** CHECKING CONNECTIONS *****************8");
  var connectionrows        = new Object();
  /*gun.get("connections").map(function(a,b){
    delete a["_"];
    if (!connectionrows[a.id]) {
      //data_connections_list.push(a);
      connectionrows[a.id] = a;
      //console.log(a);
      connections[a.id] = a;
    }

},true);*/

    if (typeOfSystem == 'client') {
        var urlToConnectTo = "http://" + centralHostAddress + ":" + centralHostPort + '/client_connect';
        console.log('-------* urlToConnectTo: ' + urlToConnectTo);
        console.log('trying to connect to central server...');
        request({
              uri: urlToConnectTo,
              method: "GET",
              timeout: 10000,
              followRedirect: true,
              maxRedirects: 10,
              qs: {
                  requestClientInternalHostAddress: hostaddress
                  ,
                  requestClientInternalPort:        port
              }
            },
            function(error, response, body) {
                console.log(body);
            });
    }

    console.log("******************************ADDING DRIVERS*********************************")

    var pgeval = '(' + fs.readFileSync(path.join(__dirname, './postgres.js')).toString() + ')';
    drivers['postgres'] = eval( pgeval )
    addOrUpdateDriver('postgres', pgeval, drivers['postgres'])

    toeval =  '(' + fs.readFileSync(path.join(__dirname, './oracle.js')).toString() + ')';
    drivers['oracle']   = eval( toeval )
    addOrUpdateDriver('oracle',   toeval, drivers['oracle'])
	process.env['PATH'] = process.cwd() + '\\oracle_driver\\instantclient32' + ';' + process.env['PATH'];
    if (drivers['oracle'].loadOnCondition()) {
        drivers['oracle'].loadDriver()
    }

    var tdeval = '(' + fs.readFileSync(path.join(__dirname, './testdriver.js')).toString() + ')';
    drivers['TestDriver'] = eval(tdeval)
    addOrUpdateDriver('TestDriver', tdeval, drivers['TestDriver'])

    ////dbhelper.sql("insert into drivers (name,code,driver_type) values (?,?,?)",            ['a', 'b', 'c'])
    //dbhelper.sql("update drivers set type = '...2' where name = 'TestDriver'")
    //dbhelper.sql("select * from drivers where name = 'TestDriver' ")
    //dbhelper.sql("select * from drivers ")

    //console.log("************************************************ ")
    //console.log("******************************Doing Eve stuff ")
    //console.log("************************************************ ")
    let eve = new witheve.Program("program name");

    let inputs = [];
    //console.log(JSON.stringify(Object.keys(eve) , null, 2))
    var vv = 0
    /*setInterval(function() {
        console.log("--Tick ")
        let newinputs = [];
        witheve.appendAsEAVs(newinputs, {tag: "student", name: "Zubair " + vv});
        eve.inputEAVs(newinputs);
        vv ++
    }, 1000)

    eve.watch("Export information about students", function(arg) {
        console.log("--Eve Export information ")
      // search for records tagged student
      let student = arg.find("student");
      let eav = arg.lookup(student);
      return [
          // Add these attributes and values to the student, creating a diff to which we can react
          student.add(eav.attribute, eav.value)
      ];

    }).asDiffs(function(diff)  {
          console.log("--Eve in adDiffs ")
          for(let [e, a, v] of diff.adds) {
            console.log("--Eve add " + JSON.stringify(e , null, 2) + ", " + JSON.stringify(a , null, 2) + JSON.stringify(v , null, 2))
          }
          for(let [e, a, v] of diff.removes) {
              console.log("--Eve remove " + JSON.stringify(e , null, 2) + ", " + JSON.stringify(a , null, 2) + JSON.stringify(v , null, 2))
          }
        });;
        witheve.appendAsEAVs(inputs, {tag: "student", name: "Archibald"});
        witheve.appendAsEAVs(inputs, {tag: "student", name: "Zubair"});
        eve.inputEAVs(inputs);*/

    //console.log("************************************************ ")
    //console.log("******************************finished Eve stuff ")
    //console.log("************************************************ ")

function addOrUpdateDriver(name, code, theObject) {
    console.log("******************************addOrUpdateDriver ")
    console.log("       name = " + name)
    //console.log("       code = " + JSON.stringify(code , null, 2))
    var driverType = theObject.type;
    //console.log("******************************driver type= " + driverType)
    //console.log("******************************driver= " + JSON.stringify(theObject , null, 2))
    dbhelper.sql("select * from drivers where name = '" +  name +  "' ",
        function(records) {
            console.log("******************************records = " + records.length  )
            if(records.length > 0) {
                for (var record of records) {
                    dbhelper.sql("update drivers set code = ?  where name = '" + name + "'",  [code])
                    if (typeof driverType === 'string' || driverType instanceof String) {
                        console.log("******************************UPDATE DRIVER "+name)
                        //console.log("******************************record type = " + JSON.stringify(record.type , null, 2))
                        //console.log("******************************desired type = " + JSON.stringify(driverType , null, 2))
                        //console.log("******************************set driver type = " + JSON.stringify(driverType , null, 2))
                        //console.log("******************************for name = " + JSON.stringify(name , null, 2))
                        var sqlToRun = "update drivers set type = '" + driverType + "' where  name = '" + name + "'";

                        //console.log("******************************SQL  = " + JSON.stringify(sqlToRun , null, 2))
                        dbhelper.sql(sqlToRun, function(ack) {
                            //console.log("******************************SQL Done  = " + JSON.stringify(sqlToRun , null, 2))
                        })
                        //dbhelper.sql("update drivers set type = '...' where name = 'TestDriver'")
                    }
                }
            } else {
                console.log("******************************INSERT DRIVER "+name)
                dbhelper.sql("insert into drivers (name,code,type) values (?,?,?)",            [name, code, driverType])

            }
        })
}

//console.log("postgres.get = " + JSON.stringify(eval(pgeval) , null, 2))
//console.log("postgres.get = " + eval(pgeval).get)
}
<|endoftext|>